Skip to content

Commit

Permalink
Add code and tests for checking DOM Node types (#4)
Browse files Browse the repository at this point in the history
This code was initially written for the `xpath` project and then was ported here to allow faster iteration and wider use.
  • Loading branch information
cjbarth authored Sep 15, 2023
1 parent facd7ad commit edf12a7
Show file tree
Hide file tree
Showing 20 changed files with 21,782 additions and 5 deletions.
27 changes: 27 additions & 0 deletions .eslintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
{
"env": {
"node": true,
"mocha": true,
"es6": false
},
"root": true,
"parser": "@typescript-eslint/parser",
"plugins": ["@typescript-eslint", "deprecation"],
"parserOptions": {
"ecmaVersion": 6,
"project": "./tsconfig.eslint.json",
"ext": ".ts"
},
"extends": [
"eslint:recommended",
"plugin:@typescript-eslint/eslint-recommended",
"plugin:@typescript-eslint/recommended",
"prettier"
],
"rules": {
"no-console": "error",
"deprecation/deprecation": "warn",
"@typescript-eslint/no-non-null-assertion": "error",
"@typescript-eslint/no-unused-vars": "error"
}
}
71 changes: 71 additions & 0 deletions .github/workflows/codeql-analysis.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
# For most projects, this workflow file will not need changing; you simply need
# to commit it to your repository.
#
# You may wish to alter this file to override the set of languages analyzed,
# or to provide custom queries or build logic.
#
# ******** NOTE ********
# We have attempted to detect the languages in your repository. Please check
# the `language` matrix defined below to confirm you have the correct set of
# supported CodeQL languages.
#
name: "CodeQL"

on:
push:
branches: [main]
pull_request:
# The branches below must be a subset of the branches above
branches: [main]
schedule:
- cron: "21 12 * * 1"

jobs:
analyze:
name: Analyze
runs-on: ubuntu-latest
permissions:
actions: read
contents: read
security-events: write

strategy:
fail-fast: false
matrix:
language: ["javascript"]
# CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python' ]
# Learn more:
# https://docs.github.com/en/free-pro-team@latest/github/finding-security-vulnerabilities-and-errors-in-your-code/configuring-code-scanning#changing-the-languages-that-are-analyzed

steps:
- name: Checkout repository
uses: actions/checkout@v3

# Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL
uses: github/codeql-action/init@v2
with:
languages: ${{ matrix.language }}
# If you wish to specify custom queries, you can do so here or in a config file.
# By default, queries listed here will override any specified in a config file.
# Prefix the list here with "+" to use these queries and those in the config file.
# queries: ./path/to/local/query, your-org/your-repo/queries@main

# Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
# If this step fails, then you should remove it and run the build manually (see below)
- name: Autobuild
uses: github/codeql-action/autobuild@v2

# ℹ️ Command-line programs to run using the OS shell.
# 📚 https://git.io/JvXDl

# ✏️ If the Autobuild fails above, remove it and uncomment the following three lines
# and modify them (or add more) to build your code if your project
# uses a compiled language

#- run: |
# make bootstrap
# make release

- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v2
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
node_modules
coverage/
.nyc_output/
dist/
54 changes: 54 additions & 0 deletions .grenrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
module.exports = {
dataSource: "prs",
prefix: "",
onlyMilestones: false,
ignoreTagsWith: [],
ignoreLabels: [],
tags: "all",
groupBy: {
"Major Changes": ["semver-major", "breaking-change"],
"Minor Changes": ["semver-minor", "enhancement", "new-feature"],
Dependencies: ["dependencies"],
"Bug Fixes": ["semver-patch", "bug", "security"],
Documentation: ["documentation"],
"Technical Tasks": ["chore"],
Other: ["..."],
},
changelogFilename: "CHANGELOG.md",
username: "xmldom",
repo: "is-dom-node",
template: {
issue: function (placeholders) {
const parts = [
"-",
placeholders.labels,
placeholders.name,
`[${placeholders.text}](${placeholders.url})`,
];
return parts
.filter((_) => _)
.join(" ")
.replace(" ", " ");
},
release: function (placeholders) {
placeholders.body = placeholders.body.replace(
"*No changelog for this release.*",
"\n_No changelog for this release._",
);
return `## ${placeholders.release} (${placeholders.date})\n${placeholders.body}`;
},
group: function (placeholders) {
const iconMap = {
Enhancements: "🚀",
"Minor Changes": "🚀",
"Bug Fixes": "🐛",
Documentation: "📚",
"Technical Tasks": "⚙️",
"Major Changes": "💣",
Dependencies: "🔗",
};
const icon = iconMap[placeholders.heading] || "🙈";
return "\n### " + icon + " " + placeholders.heading + "\n";
},
},
};
10 changes: 10 additions & 0 deletions .mocharc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"diff": true,
"extension": "spec.ts",
"package": "./package.json",
"recursive": true,
"reporter": "spec",
"require": ["choma", "ts-node/register"],
"spec": "test/**/*.spec.ts",
"watch-files": "test/**/*.spec.ts"
}
7 changes: 7 additions & 0 deletions .nycrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"extends": "@istanbuljs/nyc-config-typescript",
"all": true,
"check-coverage": false,
"reporter": ["lcov", "text"],
"include": ["src"]
}
3 changes: 3 additions & 0 deletions .prettierrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"printWidth": 100
}
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# Changelog

## 1.0.0 (2023-09-13)

### ⚙️ Technical Tasks

- [**chore**] Configure Renovate [#2](https://github.com/xmldom/is-dom-node/pull/2)
33 changes: 33 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
# Contributing to is-dom-node

First off, thank you for considering contributing to is-dom-node! It's people like you that make is-dom-node such a great tool.

## Getting Started

- Fork the repository on GitHub.
- Clone your fork to your local machine.
- Create a new branch from `main` for your work.

## Code Guidelines

- Ensure your code follows the ESLint and TypeScript configuration provided.
- Write tests for any new features or bug fixes.
- Style is enforced using ESLint and Prettier. Run `npm run lint` to check your code.

## Pull Requests

- Make sure all tests pass before submitting a pull request.
- Describe what your pull request does and what issue(s) it addresses.

## Issues

- Feel free to open issues for bugs, feature requests, or other topics.
- Please be as descriptive as possible and include any relevant code snippets or error messages.

## License

By contributing, you agree that your contributions will be licensed under the project's MIT License.

## Questions?

If you have any questions or need further clarification, feel free to reach out or open an issue. We appreciate your contribution and are happy to help.
21 changes: 21 additions & 0 deletions LICENSE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# MIT License

Copyright (c) 2023 Chris Barth

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
91 changes: 91 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
# is-dom-node

![Build Status](https://img.shields.io/travis/xmldom/is-dom-node)
![Code Coverage](https://img.shields.io/codecov/c/github/xmldom/is-dom-node)
![NPM Version](https://img.shields.io/npm/v/@xmldom/is-dom-node)
![License](https://img.shields.io/npm/l/@xmldom/is-dom-node)

## Description

`@xmldom/is-dom-node` is a versatile TypeScript library designed to provide robust utility functions for working with DOM nodes. Whether you're developing for the browser or dealing with XML in NodeJS, this library offers a comprehensive set of functions for checking and asserting various types of DOM nodes. It's particularly useful when working with NodeJS libraries like [xpath](https://www.npmjs.com/package/xpath) and [@xmldom/xmldom](https://www.npmjs.com/package/@xmldom/xmldom), as it can validate the objects returned by these libraries.

## Installation

```shell
npm install @xmldom/is-dom-node
```

## Usage

Import the library and use it as follows:

```javascript
import * as isDomNode from "@xmldom/is-dom-node";

const element = document.createElement("div");
const result = isDomNode.isElementNode(element); // Output: true
```

### TypeScript Example

```typescript
import * as isDomNode from "@xmldom/is-dom-node";

function handleNode(node: Node) {
if (isDomNode.isElementNode(node)) {
// TypeScript now knows `node` is an Element
console.log(node.tagName);
} else if (isDomNode.isTextNode(node)) {
// TypeScript now knows `node` is a Text node
console.log(node.wholeText);
} else {
try {
// Assert that the node is a Comment node
isDomNode.assertIsCommentNode(node);
// TypeScript now knows `node` is a Comment node
console.log(node.nodeValue);
} catch (error) {
console.error("Node is not a Comment node:", error);
}
}
}
```

## API Overview

The API consists of two main types of functions:

### `is...` Functions

These functions return a boolean value indicating whether the given object meets certain criteria:

- `isNodeLike`: Checks if a given value resembles a DOM node.
- `isArrayOfNodes`: Checks if the given value is an array of DOM nodes.
- `isElementNode`, `isAttributeNode`, `isTextNode`, etc.: Check for specific types of DOM nodes.

### `assertIs...` Functions

These functions assert that a given object meets certain criteria and throw an error if it doesn't:

- `assertIsNodeLike`: Asserts that a given value is a DOM node.
- `assertIsArrayOfNodes`: Asserts that the given value is an array of DOM nodes.
- `assertIsElementNode`, `assertIsAttributeNode`, `assertIsTextNode`, etc.: Assert for specific types of DOM nodes.

### TypeScript Type Narrowing

Both the `is...` and `assertIs...` functions can be used for TypeScript type narrowing. After a successful check or assertion, TypeScript will recognize the specific type of the DOM node, allowing for more robust and error-free code.

## Features

- Lightweight
- Written in TypeScript
- Comprehensive tests
- Compatible with NodeJS XML libraries like `xpath` and `@xmldom/xmldom`

## Contributing

Please read [CONTRIBUTING.md](CONTRIBUTING.md) for details on our code of conduct, and the process for submitting pull requests.

## License

This project is licensed under the MIT License - see the [LICENSE.md](LICENSE.md) file for details.
Loading

0 comments on commit edf12a7

Please sign in to comment.