flow like the river

This commit is contained in:
root 2025-11-07 00:06:12 +01:00
commit 013fe673f3
42435 changed files with 5764238 additions and 0 deletions

2
BACK_BACK/node_modules/htmlnano/.eslintignore generated vendored Executable file
View file

@ -0,0 +1,2 @@
lib/modules/example.es6
test.js

258
BACK_BACK/node_modules/htmlnano/CHANGELOG.md generated vendored Executable file
View file

@ -0,0 +1,258 @@
# Change Log
All notable changes to this project will be documented in this file.
This project adheres to [Semantic Versioning](http://semver.org/).
## [0.2.9] - 2021-04-11
### Added
- `minifyConditionalComment` support `<html>` [#125].
- Minify JS within `<script type="module">` [#135].
### Fixed
- `collapseWhitespaces` around comment [#120].
- handle `CDATA` inside script correctly [#122].
- Minify SVG correctly [#129].
### Changed
- Upgrade to terser@5 (JS minification).
## [0.2.8] - 2020-11-15
### Added
- [`removeOptionalTags`](https://github.com/posthtml/htmlnano#removeoptionaltags) [#110].
- [`sortAttributes`](https://github.com/posthtml/htmlnano#removeoptionaltags) [#113].
- `source[src]` and `srcset` support to `minifyUrls` [#117].
- [`minifyConditionalComments`](https://github.com/posthtml/htmlnano#minifyconditionalcomments) [#119].
### Changed
- Sort by frequency `sortAttributesWithLists` [#111].
- Strip more spaces in `collapseWhitespace` [#112].
- Remove `loading="eager"` from `<img>` and `<iframe>` [#114].
- Remove redundant `type` from `<script>` [#114].
- Strip whitespaces between textnode and element [#116].
## [0.2.7] - 2020-10-17
### Added
- More aggressive whitespace removal option [#90].
- Cloudflare SSE support to `removeComments` [#94].
- Improve compression ratio by sorting attribute values [#95].
- New `minifyUrls` module [#98].
- New `removeAttributeQuotes` module [#104].
- Remove `type=text/css` for `link[rel=stylesheet]` [#102].
- Collapse `crossorigin` attributes [#107].
- Exclude excerpt comment for common CMS [#108].
### Fixed
- Keep JS inside SVG wrapped in `//<![CDATA[ //]]` [#88].
## [0.2.6] - 2020-07-15
### Added
- Let PostHTML options to be passed.
### Fixed
- `<script>` tags merging without content.
## [0.2.5] - 2019-11-09
### Added
- Option to remove unused CSS using PurgeCSS [#84].
### Fixed
- Keep the order of inline and external JS [#80].
## [0.2.4] - 2019-07-11
### Fixed
- Remove crossorigin from boolean attribute [#78], [#79].
- Disable SVGO plugin convertShapeToPath in safe preset [#76].
## [0.2.3] - 2019-02-14
### Fixed
- Keep `<g>` in SVG by default [#71].
## [0.2.2] - 2019-01-03
### Added
- `removeUnusedCss` module [#36].
### Fixed
- Bug when `tag === false` [#66].
- Add `crossorigin` to boolean attributes [#67].
## [0.2.1] - 2018-12-01
### Fixed
- Disable JS minifying on AMP pages [#65].
## [0.2.0] - 2018-09-14
### Breaking changes
- The API of `minifyCss` module has been changed since `cssnano` has been updated to version 4, which has a different API. Check the following resources for more info:
* [htmlnano docs](https://github.com/posthtml/htmlnano#minifycss)
* [cssnano docs](https://cssnano.co/guides/presets)
* Diff of commit [979f2c](https://github.com/posthtml/htmlnano/commit/979f2c821892c9e979e8b85f74ed0394330fceaf) with the changes of related docs.
### Added
- Add presets [#64].
- Add `collapseAttributeWhitespace` module for collapsing spaces in list-like attributes [#25].
- Add `deduplicateAttributeValues` module for de-duplicating values in list-like attributes [#39].
- Better support for AMP pages [#59].
- Collapse whitespaces between top-level tags [#24].
### Changed
- Improve whitespace normalization using `normalize-html-whitespace` [#21].
### Fixed
- Don't collapse `visible="false"` attributes in A-Frame pages [#62].
## [0.1.10] - 2018-08-03
### Fixed
- Merging `<script>` tags without leading `;` [#55].
## [0.1.9] - 2018-04-29
### Fixed
- Default minification options safety [#50].
## [0.1.8] - 2018-04-17
### Fixed
- ES6+ minification [#48].
## [0.1.7] - 2018-03-13
### Fixed
- Update dependencies which also fixes the SVG minification bug [#47].
## [0.1.6] - 2017-06-27
### Fixed
- "Not a function" error [#42].
## [0.1.5] - 2016-04-24
### Added
- Minify SVG [#28].
- Merge `<script>` [#19].
### Changed
- Remove redundant `type="submit"` from `<button>` [#31].
### Fixed
- Windows build [#30].
## [0.1.4] - 2016-02-16
### Added
- Minify JSON.
- Merge multiple `<style>` into one.
- Collapse boolean attributes.
- Remove redundant attributes.
- HTML minifiers benchmark [#22].
### Changed
- Expand list of JSON-like mime types [#20].
## [0.1.3] - 2016-02-09
### Fixed
- Don't alter HTML comments inside not relevant modules [#17].
## [0.1.2] - 2016-02-07
### Fixed
- Don't remove conditional comments in safe mode [#13].
- Downgrade: `String.startsWith -> String.search`.
## [0.1.1] - 2016-01-31
### Added
- Minify CSS inside `<style>` tags and `style` attributes.
- Minify JS inside `<script>` tags and `on*` attributes.
### Changed
- Remove attributes that contains only white spaces.
[0.2.9]: https://github.com/posthtml/htmlnano/compare/0.2.8...0.2.9
[0.2.8]: https://github.com/posthtml/htmlnano/compare/0.2.7...0.2.8
[0.2.7]: https://github.com/posthtml/htmlnano/compare/0.2.6...0.2.7
[0.2.6]: https://github.com/posthtml/htmlnano/compare/0.2.5...0.2.6
[0.2.5]: https://github.com/posthtml/htmlnano/compare/0.2.4...0.2.5
[0.2.4]: https://github.com/posthtml/htmlnano/compare/0.2.3...0.2.4
[0.2.3]: https://github.com/posthtml/htmlnano/compare/0.2.2...0.2.3
[0.2.2]: https://github.com/posthtml/htmlnano/compare/0.2.1...0.2.2
[0.2.1]: https://github.com/posthtml/htmlnano/compare/0.2.0...0.2.1
[0.2.0]: https://github.com/posthtml/htmlnano/compare/0.1.10...0.2.0
[0.1.10]: https://github.com/posthtml/htmlnano/compare/0.1.9...0.1.10
[0.1.9]: https://github.com/posthtml/htmlnano/compare/0.1.8...0.1.9
[0.1.8]: https://github.com/posthtml/htmlnano/compare/0.1.7...0.1.8
[0.1.7]: https://github.com/posthtml/htmlnano/compare/0.1.6...0.1.7
[0.1.6]: https://github.com/posthtml/htmlnano/compare/0.1.5...0.1.6
[0.1.5]: https://github.com/posthtml/htmlnano/compare/0.1.4...0.1.5
[0.1.4]: https://github.com/posthtml/htmlnano/compare/0.1.3...0.1.4
[0.1.3]: https://github.com/posthtml/htmlnano/compare/0.1.2...0.1.3
[0.1.2]: https://github.com/posthtml/htmlnano/compare/0.1.1...0.1.2
[0.1.1]: https://github.com/posthtml/htmlnano/compare/0.1.0...0.1.1
[#135]: https://github.com/posthtml/htmlnano/issues/135
[#129]: https://github.com/posthtml/htmlnano/issues/129
[#125]: https://github.com/posthtml/htmlnano/issues/125
[#122]: https://github.com/posthtml/htmlnano/issues/122
[#120]: https://github.com/posthtml/htmlnano/issues/120
[#119]: https://github.com/posthtml/htmlnano/issues/119
[#117]: https://github.com/posthtml/htmlnano/issues/117
[#116]: https://github.com/posthtml/htmlnano/issues/116
[#114]: https://github.com/posthtml/htmlnano/issues/114
[#113]: https://github.com/posthtml/htmlnano/issues/113
[#112]: https://github.com/posthtml/htmlnano/issues/112
[#111]: https://github.com/posthtml/htmlnano/issues/111
[#110]: https://github.com/posthtml/htmlnano/issues/110
[#107]: https://github.com/posthtml/htmlnano/issues/107
[#108]: https://github.com/posthtml/htmlnano/issues/108
[#102]: https://github.com/posthtml/htmlnano/issues/102
[#104]: https://github.com/posthtml/htmlnano/issues/104
[#98]: https://github.com/posthtml/htmlnano/issues/98
[#95]: https://github.com/posthtml/htmlnano/issues/95
[#94]: https://github.com/posthtml/htmlnano/issues/94
[#90]: https://github.com/posthtml/htmlnano/issues/90
[#88]: https://github.com/posthtml/htmlnano/issues/88
[#84]: https://github.com/posthtml/htmlnano/issues/84
[#80]: https://github.com/posthtml/htmlnano/issues/80
[#79]: https://github.com/posthtml/htmlnano/issues/79
[#78]: https://github.com/posthtml/htmlnano/issues/78
[#76]: https://github.com/posthtml/htmlnano/issues/76
[#71]: https://github.com/posthtml/htmlnano/issues/71
[#67]: https://github.com/posthtml/htmlnano/issues/67
[#66]: https://github.com/posthtml/htmlnano/issues/66
[#65]: https://github.com/posthtml/htmlnano/issues/65
[#64]: https://github.com/posthtml/htmlnano/issues/64
[#62]: https://github.com/posthtml/htmlnano/issues/62
[#59]: https://github.com/posthtml/htmlnano/issues/59
[#55]: https://github.com/posthtml/htmlnano/issues/55
[#50]: https://github.com/posthtml/htmlnano/issues/50
[#48]: https://github.com/posthtml/htmlnano/issues/48
[#47]: https://github.com/posthtml/htmlnano/issues/47
[#42]: https://github.com/posthtml/htmlnano/issues/42
[#39]: https://github.com/posthtml/htmlnano/issues/39
[#36]: https://github.com/posthtml/htmlnano/issues/36
[#31]: https://github.com/posthtml/htmlnano/issues/31
[#30]: https://github.com/posthtml/htmlnano/issues/30
[#28]: https://github.com/posthtml/htmlnano/issues/28
[#25]: https://github.com/posthtml/htmlnano/issues/25
[#24]: https://github.com/posthtml/htmlnano/issues/24
[#22]: https://github.com/posthtml/htmlnano/issues/22
[#21]: https://github.com/posthtml/htmlnano/issues/21
[#20]: https://github.com/posthtml/htmlnano/issues/20
[#19]: https://github.com/posthtml/htmlnano/issues/19
[#17]: https://github.com/posthtml/htmlnano/issues/17
[#13]: https://github.com/posthtml/htmlnano/issues/13

21
BACK_BACK/node_modules/htmlnano/LICENSE.txt generated vendored Executable file
View file

@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2016 Kirill Maltsev <maltsevkirill@gmail.com>
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.

898
BACK_BACK/node_modules/htmlnano/README.md generated vendored Executable file
View file

@ -0,0 +1,898 @@
# htmlnano
[![npm version](https://badge.fury.io/js/htmlnano.svg)](http://badge.fury.io/js/htmlnano)
[![Build Status](https://travis-ci.org/posthtml/htmlnano.svg?branch=master)](https://travis-ci.org/posthtml/htmlnano)
Modular HTML minifier, built on top of the [PostHTML](https://github.com/posthtml/posthtml). Inspired by [cssnano](http://cssnano.co/).
> The author of htmlnano is available for hire as a full stack web developer: https://kirillmaltsev.net/services
## [Benchmark](https://github.com/maltsev/html-minifiers-benchmark/blob/master/README.md)
[html-minifier@4.0.0]: https://www.npmjs.com/package/html-minifier
[htmlnano@0.2.8]: https://www.npmjs.com/package/htmlnano
| Website | Source (KB) | [html-minifier@4.0.0] | [htmlnano@0.2.8] |
|---------|------------:|----------------:|-----------:|
| [stackoverflow.blog](https://stackoverflow.blog/) | 78 | 72 | 66 |
| [github.com](https://github.com/) | 215 | 187 | 177 |
| [en.wikipedia.org](https://en.wikipedia.org/wiki/Main_Page) | 78 | 73 | 72 |
| [npmjs.com](https://www.npmjs.com/features) | 29 | 25 | 25 |
| **Avg. minify rate** | 0% | **10%** | **13%** |
## Usage
### Gulp
```bash
npm install --save-dev gulp-htmlnano
```
```js
const gulp = require('gulp');
const htmlnano = require('gulp-htmlnano');
const options = {
removeComments: false
};
gulp.task('default', function() {
return gulp
.src('./index.html')
.pipe(htmlnano(options))
.pipe(gulp.dest('./build'));
});
```
### Javascript
```js
const htmlnano = require('htmlnano');
const options = {
removeEmptyAttributes: false, // Disable the module "removeEmptyAttributes"
collapseWhitespace: 'conservative' // Pass options to the module "collapseWhitespace"
};
// posthtml, posthtml-render, and posthtml-parse options
const postHtmlOptions = {
sync: true, // https://github.com/posthtml/posthtml#usage
lowerCaseTags: true, // https://github.com/posthtml/posthtml-parser#options
quoteAllAttributes: false, // https://github.com/posthtml/posthtml-render#options
};
htmlnano
// "preset" arg might be skipped (see "Presets" section below for more info)
// "postHtmlOptions" arg might be skipped
.process(html, options, preset, postHtmlOptions)
.then(function (result) {
// result.html is minified
})
.catch(function (err) {
console.error(err);
});
```
### PostHTML
Just add `htmlnano` as a final plugin:
```js
const posthtml = require('posthtml');
const options = {
removeComments: false, // Disable the module "removeComments"
collapseWhitespace: 'conservative' // Pass options to the module "collapseWhitespace"
};
const posthtmlPlugins = [
/* other PostHTML plugins */
require('htmlnano')(options)
];
const postHtmlOptions = {
// See PostHTML docs
};
posthtml(posthtmlPlugins)
.process(html, posthtmlOptions)
.then(function (result) {
// result.html is minified
})
.catch(function (err) {
console.error(err);
});
```
## Presets
A preset is just an object with modules config.
Currently the following presets are available:
- [safe](https://github.com/posthtml/htmlnano/blob/master/lib/presets/safe.es6) — a default preset for minifying a regular HTML in a safe way (without breaking anything)
- [ampSafe](https://github.com/posthtml/htmlnano/blob/master/lib/presets/ampSafe.es6) - same as `safe` preset but for [AMP pages](https://www.ampproject.org/)
- [max](https://github.com/posthtml/htmlnano/blob/master/lib/presets/max.es6) - maximal minification (might break some pages)
You can use them the following way:
```js
const htmlnano = require('htmlnano');
const ampSafePreset = require('htmlnano').presets.ampSafe;
const options = {
// Your options
};
htmlnano
.process(html, options, ampSafePreset)
.then(function (result) {
// result.html is minified
})
.catch(function (err) {
console.error(err);
});
```
If you skip `preset` argument [`safe`](https://github.com/posthtml/htmlnano/blob/master/lib/presets/safe.es6) preset would be used by default.
If you'd like to define your very own config without any presets pass an empty object as a preset:
```js
const htmlnano = require('htmlnano');
const options = {
// Your options
};
htmlnano
.process(html, options, {})
.then(function (result) {
// result.html is minified
})
.catch(function (err) {
console.error(err);
});
```
You might create also your own presets:
```js
const htmlnano = require('htmlnano');
// Preset for minifying email templates
const emailPreset = {
mergeStyles: true,
minifyCss: {
safe: true
},
};
const options = {
// Some specific options
};
htmlnano
.process(html, options, emailPreset)
.then(function (result) {
// result.html is minified
})
.catch(function (err) {
console.error(err);
});
```
Feel free [to submit a PR](https://github.com/posthtml/htmlnano/issues/new) with your preset if it might be useful for other developers as well.
## Modules
By default the modules should only perform safe transforms, see the module documentation below for details.
You can disable modules by passing `false` as option, and enable them by passing `true`.
### collapseAttributeWhitespace
Collapse redundant white spaces in list-like attributes (`class`, `rel`, `ping`).
##### Example
Source:
```html
<div class=" content page "></div>
```
Minified:
```html
<div class="content page"></div>
```
### collapseWhitespace
Collapses redundant white spaces (including new lines). It doesnt affect white spaces in the elements `<style>`, `<textarea>`, `<script>` and `<pre>`.
##### Options
- `conservative` — collapses all redundant white spaces to 1 space (default)
- `aggressive` — collapses all whitespaces that are redundant and safe to remove
- `all` — collapses all redundant white spaces
##### Side effects
*all*
`<i>hello</i> <i>world</i>` or `<i>hello</i><br><i>world</i>` after minification will be rendered as `helloworld`.
To prevent that use either the default `conservative` option, or the `aggressive` option.
##### Example
Source:
```html
<div>
hello world!
<a href="#">answer</a>
<style>div { color: red; } </style>
<main></main>
</div>
```
Minified (with `all`):
```html
<div>hello world!<a href="#">answer</a><style>div { color: red; } </style><main></main></div>
```
Minified (with `aggressive`):
```html
<div> hello world! <a href="#">answer</a> <style>div { color: red; } </style><main></main></div>
```
Minified (with `conservative`):
```html
<div> hello world! <a href="#">answer</a> <style>div { color: red; } </style> <main></main> </div>
```
### deduplicateAttributeValues
Remove duplicate values from list-like attributes (`class`, `rel`, `ping`).
##### Example
Source:
```html
<div class="sidebar left sidebar"></div>
```
Minified:
```html
<div class="sidebar left"></div>
```
### removeComments
##### Options
- `safe` removes all HTML comments except the conditional comments and [`<!--noindex--><!--/noindex-->`](https://yandex.com/support/webmaster/controlling-robot/html.xml) (default)
- `all` — removes all HTML comments
##### Example
Source:
```html
<div><!-- test --></div>
```
Minified:
```html
<div></div>
```
### removeEmptyAttributes
Removes empty [safe-to-remove](https://github.com/posthtml/htmlnano/blob/master/lib/modules/removeEmptyAttributes.es6) attributes.
##### Side effects
This module could break your styles or JS if you use selectors with attributes:
```CSS
img[style=""] {
margin: 10px;
}
```
##### Example
Source:
```html
<img src="foo.jpg" alt="" style="">
```
Minified:
```html
<img src="foo.jpg" alt="">
```
### removeAttributeQuotes
Remove quotes around attributes when possible, see [HTML Standard - 12.1.2.3 Attributes - Unquoted attribute value syntax](https://html.spec.whatwg.org/multipage/syntax.html#attributes-2).
##### Example
Source:
```html
<div class="foo" title="hello world"></div>
```
Minified:
```html
<div class=foo title="hello world"></div>
```
##### Notice
The feature is implemented by [posthtml-render's `quoteAllAttributes`](https://github.com/posthtml/posthtml-render#options), which is one of the PostHTML's option. So `removeAttributeQuotes` could be overriden by other PostHTML's plugins and PostHTML's configuration.
For example:
```js
posthtml([
htmlnano({
removeAttributeQuotes: true
})
]).process(html, {
quoteAllAttributes: true
})
```
`removeAttributeQuotes` will not work because PostHTML's `quoteAllAttributes` takes the priority.
### removeUnusedCss
Removes unused CSS inside `<style>` tags with either [uncss](https://github.com/uncss/uncss)
or [PurgeCSS](https://github.com/FullHuman/purgecss).
#### With uncss
##### Options
See [the documentation of uncss](https://github.com/uncss/uncss) for all supported options.
uncss options can be passed directly to the `removeUnusedCss` module:
```js
htmlnano.process(html, {
removeUnusedCss: {
ignore: ['.do-not-remove']
}
});
```
The following uncss options are ignored if passed to the module:
- `stylesheets`
- `ignoreSheets`
- `raw`
#### With PurgeCSS
Use PurgeCSS instead of uncss by adding `tool: 'purgeCSS'` to the options.
##### Options
See [the documentation of PurgeCSS](https://www.purgecss.com) for all supported options.
PurgeCSS options can be passed directly to the `removeUnusedCss` module:
```js
htmlnano.process(html, {
removeUnusedCss: {
tool: 'purgeCSS',
whitelist: ['.do-not-remove']
}
});
```
The following PurgeCSS options are ignored if passed to the module:
- `content`
- `css`
- `extractors`
##### Example
Source:
```html
<div class="b">
<style>
.a {
margin: 10px 10px 10px 10px;
}
.b {
color: #ff0000;
}
</style>
</div>
```
Optimized:
```html
<div class="b">
<style>
.b {
color: #ff0000;
}
</style>
</div>
```
### minifyCss
Minifies CSS with [cssnano](http://cssnano.co/) inside `<style>` tags and `style` attributes.
##### Options
See [the documentation of cssnano](http://cssnano.co/optimisations/) for all supported optimizations.
By default CSS is minified with preset `default`, which shouldn't have any side-effects.
To use another preset or disabled some optimizations pass options to `minifyCss` module:
```js
htmlnano.process(html, {
minifyCss: {
preset: ['default', {
discardComments: {
removeAll: true,
},
}]
}
});
```
##### Example
Source:
```html
<div>
<style>
h1 {
margin: 10px 10px 10px 10px;
color: #ff0000;
}
</style>
</div>
```
Minified:
```html
<div>
<style>h1{margin:10px;color:red}</style>
</div>
```
### minifyJs
Minifies JS using [Terser](https://github.com/fabiosantoscode/terser) inside `<script>` tags.
##### Options
See [the documentation of Terser](https://github.com/fabiosantoscode/terser#api-reference) for all supported options.
Terser options can be passed directly to the `minifyJs` module:
```js
htmlnano.process(html, {
minifyJs: {
output: { quote_style: 1 },
},
});
```
##### Example
Source:
```html
<div>
<script>
/* comment */
const foo = function () {
};
</script>
</div>
```
Minified:
```html
<div>
<script>const foo=function(){};</script>
</div>
```
### minifyJson
Minifies JSON inside `<script type="application/json"></script>`.
##### Example
Source:
```html
<script type="application/json">
{
"user": "me"
}
</script>
```
Minified:
```html
<script type="application/json">{"user":"me"}</script>
```
### minifySvg
Minifies SVG inside `<svg>` tags using [SVGO](https://github.com/svg/svgo/).
##### Options
See [the documentation of SVGO](https://github.com/svg/svgo/blob/master/README.md) for all supported options.
SVGO options can be passed directly to the `minifySvg` module:
```js
htmlnano.process(html, {
minifySvg: {
plugins: [
{ collapseGroups: false },
],
},
});
```
##### Example
Source:
```html
<svg version="1.1" baseProfile="full" width="300" height="200" xmlns="http://www.w3.org/2000/svg">
<rect width="100%" height="100%" fill="red" />
<circle cx="150" cy="100" r="80" fill="green" />
<text x="150" y="125" font-size="60" text-anchor="middle" fill="white">SVG</text>
</svg>`
```
Minified:
```html
<svg baseProfile="full" width="300" height="200" xmlns="http://www.w3.org/2000/svg"><rect width="100%" height="100%" fill="red"/><circle cx="150" cy="100" r="80" fill="green"/><text x="150" y="125" font-size="60" text-anchor="middle" fill="#fff">SVG</text></svg>
```
### minifyConditionalComments
Minify content inside conditional comments.
##### Example
Source:
```html
<!--[if lte IE 7]>
<style type="text/css">
.title {
color: red;
}
</style>
<![endif]-->
```
Minified:
```html
<!--[if lte IE 7]><style>.title{color:red}</style><![endif]-->
```
### removeRedundantAttributes
Removes redundant attributes from tags if they contain default values:
- `method="get"` from `<form>`
- `type="text"` from `<input>`
- `type="submit"` from `<button>`
- `language="javascript"` and `type="text/javascript"` from `<script>`
- `charset` from `<script>` if it's an external script
- `media="all"` from `<style>` and `<link>`
- `type="text/css"` from `<link rel="stylesheet">`
##### Options
This module is disabled by default, change option to true to enable this module.
##### Side effects
This module could break your styles or JS if you use selectors with attributes:
```CSS
form[method="get"] {
color: red;
}
```
##### Example
Source:
```html
<form method="get">
<input type="text">
</form>
```
Minified:
```html
<form>
<input>
</form>
```
### collapseBooleanAttributes
Collapses boolean attributes (like `disabled`) to the minimized form.
##### Options
If your document uses [AMP](https://www.ampproject.org/), set the `amphtml` flag
to collapse additonal, AMP-specific boolean attributes:
```Json
"collapseBooleanAttributes": {
"amphtml": true
}
```
##### Side effects
This module could break your styles or JS if you use selectors with attributes:
```CSS
button[disabled="disabled"] {
color: red;
}
```
##### Example
Source:
```html
<button disabled="disabled">click</button>
<script defer=""></script>
```
Minified:
```html
<button disabled>click</button>
<script defer></script>
```
### mergeStyles
Merges multiple `<style>` with the same `media` and `type` into one tag.
`<style scoped>...</style>` are skipped.
##### Example
Source:
```html
<style>h1 { color: red }</style>
<style media="print">div { color: blue }</style>
<style type="text/css" media="print">a {}</style>
<style>div { font-size: 20px }</style>
```
Minified:
```html
<style>h1 { color: red } div { font-size: 20px }</style>
<style media="print">div { color: blue } a {}</style>
```
### mergeScripts
Merge multiple `<script>` with the same attributes (`id, class, type, async, defer`) into one (last) tag.
##### Side effects
It could break your code if the tags with different attributes share the same variable scope.
See the example below.
##### Example
Source:
```html
<script>const foo = 'A:1';</script>
<script class="test">foo = 'B:1';</script>
<script type="text/javascript">foo = 'A:2';</script>
<script defer>foo = 'C:1';</script>
<script>foo = 'A:3';</script>
<script defer="defer">foo = 'C:2';</script>
<script class="test" type="text/javascript">foo = 'B:2';</script>
```
Minified:
```html
<script>const foo = 'A:1'; foo = 'A:2'; foo = 'A:3';</script>
<script defer="defer">foo = 'C:1'; foo = 'C:2';</script>
<script class="test" type="text/javascript">foo = 'B:1'; foo = 'B:2';</script>
```
### custom
It's also possible to pass custom modules in the minifier.
As a function:
```js
const options = {
custom: function (tree, options) {
// Some minification
return tree;
}
};
```
Or as a list of functions:
```js
const options = {
custom: [
function (tree, options) {
// Some minification
return tree;
},
function (tree, options) {
// Some other minification
return tree;
}
]
};
```
`options` is an object with all options that were passed to the plugin.
### sortAttributesWithLists
Sort values in list-like attributes (`class`, `rel`, `ping`).
The module won't impact the plain-text size of the output. However it will improve the compression ratio of gzip/brotli used in HTTP compression.
##### Options
- `alphabetical`: Default option. Sort attribute values in alphabetical order.
- `frequency`: Sort attribute values by frequency.
##### Example
**alphabetical**
Source:
```html
<div class="foo baz bar">click</div>
```
Processed:
```html
<div class="bar baz foo">click</div>
```
**frequency**
Source:
```html
<div class="foo baz bar"></div><div class="bar foo"></div>
```
Processed:
```html
<div class="foo bar baz"></div><div class="foo bar"></div>
```
### sortAttributes
Sort attributes inside elements.
The module won't impact the plain-text size of the output. However it will improve the compression ratio of gzip/brotli used in HTTP compression.
##### Options
- `alphabetical`: Default option. Sort attributes in alphabetical order.
- `frequency`: Sort attributes by frequency.
##### Example
**alphabetical**
Source:
```html
<input type="text" class="form-control" name="testInput" autofocus="" autocomplete="off" id="testId">
```
Processed:
```html
<input autocomplete="off" autofocus="" class="form-control" id="testId" name="testInput" type="text">
```
**frequency**
Source:
```html
<input type="text" class="form-control" name="testInput" id="testId">
<a id="testId" href="#" class="testClass"></a>
<img width="20" src="../images/image.png" height="40" alt="image" class="cls" id="id2">
```
Processed:
```html
<input class="form-control" id="testId" type="text" name="testInput">
<a class="testClass" id="testId" href="#"></a>
<img class="cls" id="id2" width="20" src="../images/image.png" height="40" alt="image">
```
### minifyUrls
Convert absolute URL to relative URL using [relateurl](https://www.npmjs.com/package/relateurl).
##### Options
The base URL to resolve against. Support `String` & `URL`.
```js
htmlnano.process(html, {
minifyUrls: 'https://example.com' // Valid configuration
});
```
```js
htmlnano.process(html, {
minifyUrls: new URL('https://example.com') // Valid configuration
});
```
```js
htmlnano.process(html, {
minifyUrls: false // The module will be disabled
});
```
```js
htmlnano.process(html, {
minifyUrls: true // Invalid configuration, the module will be disabled
});
```
##### Example
**Basic Usage**
Configuration:
```js
htmlnano.process(html, {
minifyUrls: 'https://example.com'
});
```
Source:
```html
<a href="https://example.com/foo/bar/baz">bar</a>
```
Minified:
```html
<a href="foo/bar/baz">bar</a>
```
**With sub-directory**
Configuration:
```js
htmlnano.process(html, {
minifyUrls: 'https://example.com/foo/baz/'
});
```
Source:
```html
<a href="https://example.com/foo/bar">bar</a>
```
Minified:
```html
<a href="../bar">bar</a>
```
## removeOptionalTags
Remove certain tags that can be omitted, see [HTML Standard - 13.1.2.4 Optional tags](https://html.spec.whatwg.org/multipage/syntax.html#optional-tags).
##### Example
Source:
```html
<html><head><title>Title</title></head><body><p>Hi</p></body></html>
```
Minified:
```html
<title>Title</title><p>Hi</p>
```
##### Notice
Due to [the limitation of PostHTML](https://github.com/posthtml/htmlnano/issues/99), htmlnano can't remove only the start tag or the end tag of an element. Currently, htmlnano only supports removing the following optional tags, as htmlnano can remove their start tag and end tag at the same time:
- `html`
- `head`
- `body`
- `colgroup`
- `tbody`
## Contribute
Since the minifier is modular, it's very easy to add new modules:
1. Create a ES6-file inside `lib/modules/` with a function that does some minification. For example you can check [`lib/modules/example.es6`](https://github.com/posthtml/htmlnano/blob/master/lib/modules/example.es6).
2. Add the module's name into one of those [presets](https://github.com/posthtml/htmlnano/tree/master/lib/presets). You can choose either `ampSafe`, `max`, or `safe`.
3. Create a JS-file inside `test/modules/` with some unit-tests.
4. Describe your module in the section "[Modules](https://github.com/posthtml/htmlnano/blob/master/README.md#modules)".
5. Send me a pull request.
Other types of contribution (bug fixes, documentation improves, etc) are also welcome!
Would like to contribute, but don't have any ideas what to do? Check out [our issues](https://github.com/posthtml/htmlnano/labels/help%20wanted).

1
BACK_BACK/node_modules/htmlnano/index.js generated vendored Executable file
View file

@ -0,0 +1 @@
module.exports = require('./lib/htmlnano').default;

41
BACK_BACK/node_modules/htmlnano/lib/helpers.js generated vendored Executable file
View file

@ -0,0 +1,41 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.isAmpBoilerplate = isAmpBoilerplate;
exports.isComment = isComment;
exports.isConditionalComment = isConditionalComment;
exports.isStyleNode = isStyleNode;
exports.extractCssFromStyleNode = extractCssFromStyleNode;
const ampBoilerplateAttributes = ['amp-boilerplate', 'amp4ads-boilerplate', 'amp4email-boilerplate'];
function isAmpBoilerplate(node) {
if (!node.attrs) {
return false;
}
for (const attr of ampBoilerplateAttributes) {
if (attr in node.attrs) {
return true;
}
}
return false;
}
function isComment(content) {
return (content || '').trim().startsWith('<!--');
}
function isConditionalComment(content) {
return (content || '').trim().startsWith('<!--[if');
}
function isStyleNode(node) {
return node.tag === 'style' && !isAmpBoilerplate(node) && 'content' in node && node.content.length > 0;
}
function extractCssFromStyleNode(node) {
return Array.isArray(node.content) ? node.content.join(' ') : node.content;
}

54
BACK_BACK/node_modules/htmlnano/lib/htmlnano.js generated vendored Executable file
View file

@ -0,0 +1,54 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _posthtml = _interopRequireDefault(require("posthtml"));
var _safe = _interopRequireDefault(require("./presets/safe"));
var _ampSafe = _interopRequireDefault(require("./presets/ampSafe"));
var _max = _interopRequireDefault(require("./presets/max"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function htmlnano(options = {}, preset = _safe.default) {
return function minifier(tree) {
options = { ...preset,
...options
};
let promise = Promise.resolve(tree);
for (const [moduleName, moduleOptions] of Object.entries(options)) {
if (!moduleOptions) {
// The module is disabled
continue;
}
if (_safe.default[moduleName] === undefined) {
throw new Error('Module "' + moduleName + '" is not defined');
}
let module = require('./modules/' + moduleName);
promise = promise.then(tree => module.default(tree, options, moduleOptions));
}
return promise;
};
}
htmlnano.process = function (html, options, preset, postHtmlOptions) {
return (0, _posthtml.default)([htmlnano(options, preset)]).process(html, postHtmlOptions);
};
htmlnano.presets = {
safe: _safe.default,
ampSafe: _ampSafe.default,
max: _max.default
};
var _default = htmlnano;
exports.default = _default;

View file

@ -0,0 +1,32 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = collapseAttributeWhitespace;
exports.attributesWithLists = void 0;
const attributesWithLists = new Set(['class', 'rel', 'ping']);
/** Collapse whitespaces inside list-like attributes (e.g. class, rel) */
exports.attributesWithLists = attributesWithLists;
function collapseAttributeWhitespace(tree) {
tree.walk(node => {
if (!node.attrs) {
return node;
}
Object.entries(node.attrs).forEach(([attrName, attrValue]) => {
const attrNameLower = attrName.toLowerCase();
if (!attributesWithLists.has(attrNameLower)) {
return;
}
const newAttrValue = attrValue.replace(/\s+/g, ' ').trim();
node.attrs[attrName] = newAttrValue;
});
return node;
});
return tree;
}

View file

@ -0,0 +1,44 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = collapseBooleanAttributes;
// Source: https://github.com/kangax/html-minifier/issues/63
const htmlBooleanAttributes = new Set(['allowfullscreen', 'allowpaymentrequest', 'allowtransparency', 'async', 'autofocus', 'autoplay', 'checked', 'compact', 'controls', 'declare', 'default', 'defaultchecked', 'defaultmuted', 'defaultselected', 'defer', 'disabled', 'enabled', 'formnovalidate', 'hidden', 'indeterminate', 'inert', 'ismap', 'itemscope', 'loop', 'multiple', 'muted', 'nohref', 'noresize', 'noshade', 'novalidate', 'nowrap', 'open', 'pauseonexit', 'readonly', 'required', 'reversed', 'scoped', 'seamless', 'selected', 'sortable', 'truespeed', 'typemustmatch', 'visible']);
const amphtmlBooleanAttributes = new Set(['⚡', 'amp', '⚡4ads', 'amp4ads', '⚡4email', 'amp4email', 'amp-custom', 'amp-boilerplate', 'amp4ads-boilerplate', 'amp4email-boilerplate', 'allow-blocked-ranges', 'amp-access-hide', 'amp-access-template', 'amp-keyframes', 'animate', 'arrows', 'data-block-on-consent', 'data-enable-refresh', 'data-multi-size', 'date-template', 'disable-double-tap', 'disable-session-states', 'disableremoteplayback', 'dots', 'expand-single-section', 'expanded', 'fallback', 'first', 'fullscreen', 'inline', 'lightbox', 'noaudio', 'noautoplay', 'noloading', 'once', 'open-after-clear', 'open-after-select', 'open-button', 'placeholder', 'preload', 'reset-on-refresh', 'reset-on-resize', 'resizable', 'rotate-to-fullscreen', 'second', 'standalone', 'stereo', 'submit-error', 'submit-success', 'submitting', 'subscriptions-actions', 'subscriptions-dialog']);
function collapseBooleanAttributes(tree, options, moduleOptions) {
tree.walk(node => {
if (!node.attrs) {
return node;
}
if (!node.tag) {
return node;
}
for (const attrName of Object.keys(node.attrs)) {
if (attrName === 'visible' && node.tag.startsWith('a-')) {
continue;
}
if (htmlBooleanAttributes.has(attrName)) {
node.attrs[attrName] = true;
}
if (moduleOptions.amphtml && amphtmlBooleanAttributes.has(attrName) && node.attrs[attrName] === '') {
node.attrs[attrName] = true;
} // collapse crossorigin attributes
// Specification: https://html.spec.whatwg.org/multipage/urls-and-fetching.html#cors-settings-attributes
if (attrName.toLowerCase() === 'crossorigin' && (node.attrs[attrName] === 'anonymous' || node.attrs[attrName] === '')) {
node.attrs[attrName] = true;
}
}
return node;
});
return tree;
}

View file

@ -0,0 +1,76 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = collapseWhitespace;
var _helpers = require("../helpers");
const noWhitespaceCollapseElements = new Set(['script', 'style', 'pre', 'textarea']);
const noTrimWhitespacesArroundElements = new Set([// non-empty tags that will maintain whitespace around them
'a', 'abbr', 'acronym', 'b', 'bdi', 'bdo', 'big', 'button', 'cite', 'code', 'del', 'dfn', 'em', 'font', 'i', 'ins', 'kbd', 'label', 'mark', 'math', 'nobr', 'object', 'q', 'rp', 'rt', 'rtc', 'ruby', 's', 'samp', 'select', 'small', 'span', 'strike', 'strong', 'sub', 'sup', 'svg', 'textarea', 'time', 'tt', 'u', 'var', // self-closing tags that will maintain whitespace around them
'comment', 'img', 'input', 'wbr']);
const noTrimWhitespacesInsideElements = new Set([// non-empty tags that will maintain whitespace within them
'a', 'abbr', 'acronym', 'b', 'big', 'del', 'em', 'font', 'i', 'ins', 'kbd', 'mark', 'nobr', 'rp', 's', 'samp', 'small', 'span', 'strike', 'strong', 'sub', 'sup', 'time', 'tt', 'u', 'var']);
const whitespacePattern = /\s+/g;
const NONE = '';
const SINGLE_SPACE = ' ';
const validOptions = ['all', 'aggressive', 'conservative'];
/** Collapses redundant whitespaces */
function collapseWhitespace(tree, options, collapseType, tag) {
collapseType = validOptions.includes(collapseType) ? collapseType : 'conservative';
tree.forEach((node, index) => {
if (typeof node === 'string') {
const prevNode = tree[index - 1];
const nextNode = tree[index + 1];
const prevNodeTag = prevNode && prevNode.tag;
const nextNodeTag = nextNode && nextNode.tag;
const isTopLevel = !tag || tag === 'html' || tag === 'head';
const shouldTrim = collapseType === 'all' || isTopLevel ||
/*
* When collapseType is set to 'aggressive', and the tag is not inside 'noTrimWhitespacesInsideElements'.
* the first & last space inside the tag will be trimmed
*/
collapseType === 'aggressive' && !noTrimWhitespacesInsideElements.has(tag);
node = collapseRedundantWhitespaces(node, collapseType, shouldTrim, tag, prevNodeTag, nextNodeTag);
}
const isAllowCollapseWhitespace = !noWhitespaceCollapseElements.has(node.tag);
if (node.content && node.content.length && isAllowCollapseWhitespace) {
node.content = collapseWhitespace(node.content, options, collapseType, node.tag);
}
tree[index] = node;
});
return tree;
}
function collapseRedundantWhitespaces(text, collapseType, shouldTrim = false, currentTag, prevNodeTag, nextNodeTag) {
if (!text || text.length === 0) {
return NONE;
}
if (!(0, _helpers.isComment)(text)) {
text = text.replace(whitespacePattern, SINGLE_SPACE);
}
if (shouldTrim) {
if (collapseType === 'aggressive') {
if (!noTrimWhitespacesArroundElements.has(prevNodeTag)) {
text = text.trimStart();
}
if (!noTrimWhitespacesArroundElements.has(nextNodeTag)) {
text = text.trimEnd();
}
} else {
// collapseType is 'all', trim spaces
text = text.trim();
}
}
return text;
}

22
BACK_BACK/node_modules/htmlnano/lib/modules/custom.js generated vendored Executable file
View file

@ -0,0 +1,22 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = custom;
/** Meta-module that runs custom modules */
function custom(tree, options, customModules) {
if (!customModules) {
return tree;
}
if (!Array.isArray(customModules)) {
customModules = [customModules];
}
customModules.forEach(customModule => {
tree = customModule(tree, options);
});
return tree;
}

View file

@ -0,0 +1,46 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = collapseAttributeWhitespace;
var _collapseAttributeWhitespace = require("./collapseAttributeWhitespace");
/** Deduplicate values inside list-like attributes (e.g. class, rel) */
function collapseAttributeWhitespace(tree) {
tree.walk(node => {
if (!node.attrs) {
return node;
}
Object.keys(node.attrs).forEach(attrName => {
const attrNameLower = attrName.toLowerCase();
if (!_collapseAttributeWhitespace.attributesWithLists.has(attrNameLower)) {
return;
}
const attrValues = node.attrs[attrName].split(/\s/);
const uniqeAttrValues = new Set();
const deduplicatedAttrValues = [];
attrValues.forEach(attrValue => {
if (!attrValue) {
// Keep whitespaces
deduplicatedAttrValues.push('');
return;
}
if (uniqeAttrValues.has(attrValue)) {
return;
}
deduplicatedAttrValues.push(attrValue);
uniqeAttrValues.add(attrValue);
});
node.attrs[attrName] = deduplicatedAttrValues.join(' ');
});
return node;
});
return tree;
}

63
BACK_BACK/node_modules/htmlnano/lib/modules/mergeScripts.js generated vendored Executable file
View file

@ -0,0 +1,63 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = mergeScripts;
/* Merge multiple <script> into one */
function mergeScripts(tree) {
let scriptNodesIndex = {};
let scriptSrcIndex = 1;
tree.match({
tag: 'script'
}, node => {
const nodeAttrs = node.attrs || {};
if (nodeAttrs.src) {
scriptSrcIndex++;
return node;
}
const scriptType = nodeAttrs.type || 'text/javascript';
if (scriptType !== 'text/javascript' && scriptType !== 'application/javascript') {
return node;
}
const scriptKey = JSON.stringify({
id: nodeAttrs.id,
class: nodeAttrs.class,
type: scriptType,
defer: nodeAttrs.defer !== undefined,
async: nodeAttrs.async !== undefined,
index: scriptSrcIndex
});
if (!scriptNodesIndex[scriptKey]) {
scriptNodesIndex[scriptKey] = [];
}
scriptNodesIndex[scriptKey].push(node);
return node;
});
for (const scriptNodes of Object.values(scriptNodesIndex)) {
let lastScriptNode = scriptNodes.pop();
scriptNodes.reverse().forEach(scriptNode => {
let scriptContent = (scriptNode.content || []).join(' ');
scriptContent = scriptContent.trim();
if (scriptContent.slice(-1) !== ';') {
scriptContent += ';';
}
lastScriptNode.content = lastScriptNode.content || [];
lastScriptNode.content.unshift(scriptContent);
scriptNode.tag = false;
scriptNode.content = [];
});
}
return tree;
}

42
BACK_BACK/node_modules/htmlnano/lib/modules/mergeStyles.js generated vendored Executable file
View file

@ -0,0 +1,42 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = mergeStyles;
var _helpers = require("../helpers");
/* Merge multiple <style> into one */
function mergeStyles(tree) {
const styleNodes = {};
tree.match({
tag: 'style'
}, node => {
const nodeAttrs = node.attrs || {}; // Skip <style scoped></style>
// https://developer.mozilla.org/en/docs/Web/HTML/Element/style
if (nodeAttrs.scoped !== undefined) {
return node;
}
if ((0, _helpers.isAmpBoilerplate)(node)) {
return node;
}
const styleType = nodeAttrs.type || 'text/css';
const styleMedia = nodeAttrs.media || 'all';
const styleKey = styleType + '_' + styleMedia;
if (styleNodes[styleKey]) {
const styleContent = (node.content || []).join(' ');
styleNodes[styleKey].content.push(' ' + styleContent);
return '';
}
node.content = node.content || [];
styleNodes[styleKey] = node;
return node;
});
return tree;
}

View file

@ -0,0 +1,58 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = minifyConditionalComments;
var _htmlnano = _interopRequireDefault(require("../htmlnano"));
var _helpers = require("../helpers");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// Spec: https://docs.microsoft.com/en-us/previous-versions/windows/internet-explorer/ie-developer/compatibility/ms537512(v=vs.85)
const CONDITIONAL_COMMENT_REGEXP = /(<!--\[if\s+?[^<>[\]]+?]>)([\s\S]+?)(<!\[endif\]-->)/gm;
/** Minify content inside conditional comments */
async function minifyConditionalComments(tree, htmlnanoOptions) {
// forEach, tree.walk, tree.match just don't support Promise.
for (let i = 0, len = tree.length; i < len; i++) {
const node = tree[i];
if (typeof node === 'string' && (0, _helpers.isConditionalComment)(node)) {
tree[i] = await minifycontentInsideConditionalComments(node, htmlnanoOptions);
}
if (node.content && node.content.length) {
tree[i].content = await minifyConditionalComments(node.content, htmlnanoOptions);
}
}
return tree;
}
async function minifycontentInsideConditionalComments(text, htmlnanoOptions) {
let match;
const matches = []; // FIXME!
// String#matchAll is supported since Node.js 12
while ((match = CONDITIONAL_COMMENT_REGEXP.exec(text)) !== null) {
matches.push([match[1], match[2], match[3]]);
}
if (!matches.length) {
return Promise.resolve(text);
}
return Promise.all(matches.map(async match => {
const result = await _htmlnano.default.process(match[1], htmlnanoOptions, {}, {});
let minified = result.html;
if (match[1].includes('<html') && minified.includes('</html>')) {
minified = minified.replace('</html>', '');
}
return match[0] + minified + match[2];
}));
}

78
BACK_BACK/node_modules/htmlnano/lib/modules/minifyCss.js generated vendored Executable file
View file

@ -0,0 +1,78 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = minifyCss;
var _helpers = require("../helpers");
var _cssnano = _interopRequireDefault(require("cssnano"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const postcssOptions = {
// Prevent the following warning from being shown:
// > Without `from` option PostCSS could generate wrong source map and will not find Browserslist config.
// > Set it to CSS file path or to `undefined` to prevent this warning.
from: undefined
};
/** Minify CSS with cssnano */
function minifyCss(tree, options, cssnanoOptions) {
let promises = [];
tree.walk(node => {
if ((0, _helpers.isStyleNode)(node)) {
promises.push(processStyleNode(node, cssnanoOptions));
} else if (node.attrs && node.attrs.style) {
promises.push(processStyleAttr(node, cssnanoOptions));
}
return node;
});
return Promise.all(promises).then(() => tree);
}
function processStyleNode(styleNode, cssnanoOptions) {
let css = (0, _helpers.extractCssFromStyleNode)(styleNode); // Improve performance by avoiding calling stripCdata again and again
let isCdataWrapped = false;
if (css.includes('CDATA')) {
const strippedCss = stripCdata(css);
isCdataWrapped = css !== strippedCss;
css = strippedCss;
}
return _cssnano.default.process(css, postcssOptions, cssnanoOptions).then(result => {
if (isCdataWrapped) {
return styleNode.content = ['<![CDATA[' + result + ']]>'];
}
return styleNode.content = [result.css];
});
}
function processStyleAttr(node, cssnanoOptions) {
// CSS "color: red;" is invalid. Therefore it should be wrapped inside some selector:
// a{color: red;}
const wrapperStart = 'a{';
const wrapperEnd = '}';
const wrappedStyle = wrapperStart + (node.attrs.style || '') + wrapperEnd;
return _cssnano.default.process(wrappedStyle, postcssOptions, cssnanoOptions).then(result => {
const minifiedCss = result.css; // Remove wrapperStart at the start and wrapperEnd at the end of minifiedCss
node.attrs.style = minifiedCss.substring(wrapperStart.length, minifiedCss.length - wrapperEnd.length);
});
}
function stripCdata(css) {
const leftStrippedCss = css.replace('<![CDATA[', '');
if (leftStrippedCss === css) {
return css;
}
const strippedCss = leftStrippedCss.replace(']]>', '');
return leftStrippedCss === strippedCss ? css : strippedCss;
}

109
BACK_BACK/node_modules/htmlnano/lib/modules/minifyJs.js generated vendored Executable file
View file

@ -0,0 +1,109 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = minifyJs;
var _terser = _interopRequireDefault(require("terser"));
var _removeRedundantAttributes = require("./removeRedundantAttributes");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/** Minify JS with Terser */
function minifyJs(tree, options, terserOptions) {
let promises = [];
tree.walk(node => {
if (node.tag && node.tag === 'script') {
const nodeAttrs = node.attrs || {};
const mimeType = nodeAttrs.type || 'text/javascript';
if (_removeRedundantAttributes.redundantScriptTypes.has(mimeType) || mimeType === 'module') {
promises.push(processScriptNode(node, terserOptions));
}
}
if (node.attrs) {
promises = promises.concat(processNodeWithOnAttrs(node, terserOptions));
}
return node;
});
return Promise.all(promises).then(() => tree);
}
function stripCdata(js) {
const leftStrippedJs = js.replace(/\/\/\s*<!\[CDATA\[/, '').replace(/\/\*\s*<!\[CDATA\[\s*\*\//, '');
if (leftStrippedJs === js) {
return js;
}
const strippedJs = leftStrippedJs.replace(/\/\/\s*\]\]>/, '').replace(/\/\*\s*\]\]>\s*\*\//, '');
return leftStrippedJs === strippedJs ? js : strippedJs;
}
function processScriptNode(scriptNode, terserOptions) {
let js = (scriptNode.content || []).join('').trim();
if (!js) {
return scriptNode;
} // Improve performance by avoiding calling stripCdata again and again
let isCdataWrapped = false;
if (js.includes('CDATA')) {
const strippedJs = stripCdata(js);
isCdataWrapped = js !== strippedJs;
js = strippedJs;
}
return _terser.default.minify(js, terserOptions).then(result => {
if (result.error) {
throw new Error(result.error);
}
if (result.code === undefined) {
return;
}
let content = result.code;
if (isCdataWrapped) {
content = '/*<![CDATA[*/' + content + '/*]]>*/';
}
scriptNode.content = [content];
});
}
function processNodeWithOnAttrs(node, terserOptions) {
const jsWrapperStart = 'function _(){';
const jsWrapperEnd = '}';
const promises = [];
for (const attrName of Object.keys(node.attrs || {})) {
if (!attrName.startsWith('on')) {
continue;
} // For example onclick="return false" is valid,
// but "return false;" is invalid (error: 'return' outside of function)
// Therefore the attribute's code should be wrapped inside function:
// "function _(){return false;}"
let wrappedJs = jsWrapperStart + node.attrs[attrName] + jsWrapperEnd;
let promise = _terser.default.minify(wrappedJs, terserOptions).then(({
code
}) => {
let minifiedJs = code.substring(jsWrapperStart.length, code.length - jsWrapperEnd.length);
node.attrs[attrName] = minifiedJs;
});
promises.push(promise);
}
return promises;
}

33
BACK_BACK/node_modules/htmlnano/lib/modules/minifyJson.js generated vendored Executable file
View file

@ -0,0 +1,33 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = minifyJson;
/* Minify JSON inside <script> tags */
function minifyJson(tree) {
// Match all <script> tags which have JSON mime type
tree.match({
tag: 'script',
attrs: {
type: /(\/|\+)json/
}
}, node => {
let content = (node.content || []).join('');
if (!content) {
return node;
}
try {
content = JSON.stringify(JSON.parse(content));
} catch (error) {
return node;
}
node.content = [content];
return node;
});
return tree;
}

32
BACK_BACK/node_modules/htmlnano/lib/modules/minifySvg.js generated vendored Executable file
View file

@ -0,0 +1,32 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = minifySvg;
var _svgo = _interopRequireDefault(require("svgo"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/** Minify SVG with SVGO */
function minifySvg(tree, options, svgoOptions = {}) {
let promises = [];
const svgo = new _svgo.default(svgoOptions);
tree.match({
tag: 'svg'
}, node => {
let svgStr = tree.render(node, {
closingSingleTag: 'slash',
quoteAllAttributes: true
});
let promise = svgo.optimize(svgStr).then(result => {
node.tag = false;
node.attrs = {};
node.content = result.data;
});
promises.push(promise);
return node;
});
return Promise.all(promises).then(() => tree);
}

116
BACK_BACK/node_modules/htmlnano/lib/modules/minifyUrls.js generated vendored Executable file
View file

@ -0,0 +1,116 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = minifyUrls;
var _relateurl = _interopRequireDefault(require("relateurl"));
var _srcset = _interopRequireDefault(require("srcset"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// Adopts from https://github.com/kangax/html-minifier/blob/51ce10f4daedb1de483ffbcccecc41be1c873da2/src/htmlminifier.js#L209-L221
const tagsHaveUriValuesForAttributes = new Set(['a', 'area', 'link', 'base', 'img', 'object', 'q', 'blockquote', 'ins', 'form', 'input', 'head', 'script']);
const tagsHasHrefAttributes = new Set(['a', 'area', 'link', 'base']);
const attributesOfImgTagHasUriValues = new Set(['src', 'longdesc', 'usemap']);
const attributesOfObjectTagHasUriValues = new Set(['classid', 'codebase', 'data', 'usemap']);
const isUriTypeAttribute = (tag, attr) => {
return tagsHasHrefAttributes.has(tag) && attr === 'href' || tag === 'img' && attributesOfImgTagHasUriValues.has(attr) || tag === 'object' && attributesOfObjectTagHasUriValues.has(attr) || tag === 'q' && attr === 'cite' || tag === 'blockquote' && attr === 'cite' || (tag === 'ins' || tag === 'del') && attr === 'cite' || tag === 'form' && attr === 'action' || tag === 'input' && (attr === 'src' || attr === 'usemap') || tag === 'head' && attr === 'profile' || tag === 'script' && (attr === 'src' || attr === 'for') ||
/**
* https://html.spec.whatwg.org/#attr-source-src
*
* Although most of browsers recommend not to use "src" in <source>,
* but technically it does comply with HTML Standard.
*/
tag === 'source' && attr === 'src';
};
const isSrcsetAttribute = (tag, attr) => {
return tag === 'source' && attr === 'srcset' || tag === 'img' && attr === 'srcset' || tag === 'link' && attr === 'imagesrcset';
};
const processModuleOptions = options => {
// FIXME!
// relateurl@1.0.0-alpha only supports URL while stable version (0.2.7) only supports string
// should convert input into URL instance after relateurl@1 is stable
if (typeof options === 'string') return options;
if (options instanceof URL) return options.toString();
return false;
};
const isLinkRelCanonical = ({
tag,
attrs
}) => {
// Return false early for non-"link" tag
if (tag !== 'link') return false;
for (const [attrName, attrValue] of Object.entries(attrs)) {
if (attrName.toLowerCase() === 'rel' && attrValue === 'canonical') return true;
}
return false;
};
let relateUrlInstance;
let STORED_URL_BASE;
/** Convert absolute url into relative url */
function minifyUrls(tree, options, moduleOptions) {
const urlBase = processModuleOptions(moduleOptions); // Invalid configuration, return tree directly
if (!urlBase) return tree;
/** Bring up a reusable RelateUrl instances (only once)
*
* STORED_URL_BASE is used to invalidate RelateUrl instances,
* avoiding require.cache acrossing multiple htmlnano instance with different configuration,
* e.g. unit tests cases.
*/
if (!relateUrlInstance || STORED_URL_BASE !== urlBase) {
relateUrlInstance = new _relateurl.default(urlBase);
STORED_URL_BASE = urlBase;
}
tree.walk(node => {
if (!node.attrs) return node;
if (!node.tag) return node;
if (!tagsHaveUriValuesForAttributes.has(node.tag)) return node; // Prevent link[rel=canonical] being processed
// Can't be excluded by isUriTypeAttribute()
if (isLinkRelCanonical(node)) return node;
for (const [attrName, attrValue] of Object.entries(node.attrs)) {
const attrNameLower = attrName.toLowerCase();
if (isUriTypeAttribute(node.tag, attrNameLower)) {
// FIXME!
// relateurl@1.0.0-alpha only supports URL while stable version (0.2.7) only supports string
// the WHATWG URL API is very strict while attrValue might not be a valid URL
// new URL should be used, and relateUrl#relate should be wrapped in try...catch after relateurl@1 is stable
node.attrs[attrName] = relateUrlInstance.relate(attrValue);
continue;
}
if (isSrcsetAttribute(node.tag, attrNameLower)) {
try {
const parsedSrcset = _srcset.default.parse(attrValue);
node.attrs[attrName] = _srcset.default.stringify(parsedSrcset.map(srcset => {
srcset.url = relateUrlInstance.relate(srcset.url);
return srcset;
}));
} catch (e) {// srcset will throw an Error for invalid srcset.
}
continue;
}
}
return node;
});
return tree;
}

View file

@ -0,0 +1,19 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = removeAttributeQuotes;
// Specification: https://html.spec.whatwg.org/multipage/syntax.html#attributes-2
// See also: https://github.com/posthtml/posthtml-render/pull/30
// See also: https://github.com/posthtml/htmlnano/issues/6#issuecomment-707105334
/** Disable quoteAllAttributes while not overriding the configuration */
function removeAttributeQuotes(tree) {
if (tree.options && typeof tree.options.quoteAllAttributes === 'undefined') {
tree.options.quoteAllAttributes = false;
}
return tree;
}

View file

@ -0,0 +1,72 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = removeComments;
var _helpers = require("../helpers");
const MATCH_EXCERPT_REGEXP = /<!-- ?more ?-->/i;
/** Removes HTML comments */
function removeComments(tree, options, removeType) {
if (removeType !== 'all' && removeType !== 'safe') {
removeType = 'safe';
}
tree.walk(node => {
if (node.contents && node.contents.length) {
node.contents = node.contents.filter(content => !isCommentToRemove(content, removeType));
} else if (isCommentToRemove(node, removeType)) {
node = '';
}
return node;
});
return tree;
}
function isCommentToRemove(text, removeType) {
if (typeof text !== 'string') {
return false;
}
if (!(0, _helpers.isComment)(text)) {
// Not HTML comment
return false;
}
if (removeType === 'safe') {
const isNoindex = text === '<!--noindex-->' || text === '<!--/noindex-->'; // Don't remove noindex comments.
// See: https://yandex.com/support/webmaster/controlling-robot/html.xml
if (isNoindex) {
return false;
}
const isServerSideExclude = text === '<!--sse-->' || text === '<!--/sse-->'; // Don't remove sse comments.
// See: https://support.cloudflare.com/hc/en-us/articles/200170036-What-does-Server-Side-Excludes-SSE-do-
if (isServerSideExclude) {
return false;
} // https://en.wikipedia.org/wiki/Conditional_comment
if ((0, _helpers.isConditionalComment)(text)) {
return false;
} // Hexo: https://hexo.io/docs/tag-plugins#Post-Excerpt
// Hugo: https://gohugo.io/content-management/summaries/#manual-summary-splitting
// WordPress: https://wordpress.com/support/wordpress-editor/blocks/more-block/2/
// Jekyll: https://jekyllrb.com/docs/posts/#post-excerpts
const isCMSExcerptComment = MATCH_EXCERPT_REGEXP.test(text);
if (isCMSExcerptComment) {
return false;
}
}
return true;
}

View file

@ -0,0 +1,31 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = removeEmptyAttributes;
// Source: https://www.w3.org/TR/html4/sgml/dtd.html#events (Generic Attributes)
const safeToRemoveAttrs = new Set(['id', 'class', 'style', 'title', 'lang', 'dir', 'onclick', 'ondblclick', 'onmousedown', 'onmouseup', 'onmouseover', 'onmousemove', 'onmouseout', 'onkeypress', 'onkeydown', 'onkeyup']);
/** Removes empty attributes */
function removeEmptyAttributes(tree) {
tree.walk(node => {
if (!node.attrs) {
return node;
}
Object.entries(node.attrs).forEach(([attrName, attrValue]) => {
const attrNameLower = attrName.toLowerCase();
if (!safeToRemoveAttrs.has(attrNameLower)) {
return;
}
if (attrValue === '' || (attrValue || '').match(/^\s+$/)) {
delete node.attrs[attrName];
}
});
return node;
});
return tree;
}

View file

@ -0,0 +1,220 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = removeOptionalTags;
var _helpers = require("../helpers");
const startWithWhitespacePattern = /^\s+/;
const bodyStartTagCantBeOmittedWithFirstChildTags = new Set(['meta', 'link', 'script', 'style']);
const tbodyStartTagCantBeOmittedWithPrecededTags = new Set(['tbody', 'thead', 'tfoot']);
const tbodyEndTagCantBeOmittedWithFollowedTags = new Set(['tbody', 'tfoot']);
function isEmptyTextNode(node) {
if (typeof node === 'string' && node.trim() === '') {
return true;
}
return false;
}
function isEmptyNode(node) {
if (!node.content) {
return true;
}
if (node.content.length) {
return !node.content.filter(n => typeof n === 'string' && isEmptyTextNode(n) ? false : true).length;
}
return true;
}
function getFirstChildTag(node, nonEmpty = true) {
if (node.content && node.content.length) {
if (nonEmpty) {
for (const childNode of node.content) {
if (childNode.tag) return childNode;
if (typeof childNode === 'string' && !isEmptyTextNode(childNode)) return childNode;
}
} else {
return node.content[0] || null;
}
}
return null;
}
function getPrevNode(tree, currentNodeIndex, nonEmpty = false) {
if (nonEmpty) {
for (let i = currentNodeIndex - 1; i >= 0; i--) {
const node = tree[i];
if (node.tag) return node;
if (typeof node === 'string' && !isEmptyTextNode(node)) return node;
}
} else {
return tree[currentNodeIndex - 1] || null;
}
return null;
}
function getNextNode(tree, currentNodeIndex, nonEmpty = false) {
if (nonEmpty) {
for (let i = currentNodeIndex + 1; i < tree.length; i++) {
const node = tree[i];
if (node.tag) return node;
if (typeof node === 'string' && !isEmptyTextNode(node)) return node;
}
} else {
return tree[currentNodeIndex + 1] || null;
}
return null;
} // Specification https://html.spec.whatwg.org/multipage/syntax.html#optional-tags
/** Remove optional tag in the DOM */
function removeOptionalTags(tree) {
tree.forEach((node, index) => {
if (!node.tag) return node;
if (node.attrs && Object.keys(node.attrs).length) return node; // const prevNode = getPrevNode(tree, index);
const prevNonEmptyNode = getPrevNode(tree, index, true);
const nextNode = getNextNode(tree, index);
const nextNonEmptyNode = getNextNode(tree, index, true);
const firstChildNode = getFirstChildTag(node, false);
const firstNonEmptyChildNode = getFirstChildTag(node);
/**
* An "html" element's start tag may be omitted if the first thing inside the "html" element is not a comment.
* An "html" element's end tag may be omitted if the "html" element is not IMMEDIATELY followed by a comment.
*/
if (node.tag === 'html') {
let isHtmlStartTagCanBeOmitted = true;
let isHtmlEndTagCanBeOmitted = true;
if (typeof firstNonEmptyChildNode === 'string' && (0, _helpers.isComment)(firstNonEmptyChildNode)) {
isHtmlStartTagCanBeOmitted = false;
}
if (typeof nextNonEmptyNode === 'string' && (0, _helpers.isComment)(nextNonEmptyNode)) {
isHtmlEndTagCanBeOmitted = false;
}
if (isHtmlStartTagCanBeOmitted && isHtmlEndTagCanBeOmitted) {
node.tag = false;
}
}
/**
* A "head" element's start tag may be omitted if the element is empty, or if the first thing inside the "head" element is an element.
* A "head" element's end tag may be omitted if the "head" element is not IMMEDIATELY followed by ASCII whitespace or a comment.
*/
if (node.tag === 'head') {
let isHeadStartTagCanBeOmitted = false;
let isHeadEndTagCanBeOmitted = true;
if (isEmptyNode(node) || firstNonEmptyChildNode && firstNonEmptyChildNode.tag) {
isHeadStartTagCanBeOmitted = true;
}
if (nextNode && typeof nextNode === 'string' && startWithWhitespacePattern.test(nextNode) || nextNonEmptyNode && typeof nextNonEmptyNode === 'string' && (0, _helpers.isComment)(nextNode)) {
isHeadEndTagCanBeOmitted = false;
}
if (isHeadStartTagCanBeOmitted && isHeadEndTagCanBeOmitted) {
node.tag = false;
}
}
/**
* A "body" element's start tag may be omitted if the element is empty, or if the first thing inside the "body" element is not ASCII whitespace or a comment, except if the first thing inside the "body" element is a "meta", "link", "script", "style", or "template" element.
* A "body" element's end tag may be omitted if the "body" element is not IMMEDIATELY followed by a comment.
*/
if (node.tag === 'body') {
let isBodyStartTagCanBeOmitted = true;
let isBodyEndTagCanBeOmitted = true;
if (typeof firstChildNode === 'string' && startWithWhitespacePattern.test(firstChildNode) || typeof firstNonEmptyChildNode === 'string' && (0, _helpers.isComment)(firstNonEmptyChildNode)) {
isBodyStartTagCanBeOmitted = false;
}
if (firstNonEmptyChildNode && firstNonEmptyChildNode.tag && bodyStartTagCantBeOmittedWithFirstChildTags.has(firstNonEmptyChildNode.tag)) {
isBodyStartTagCanBeOmitted = false;
}
if (nextNode && typeof nextNode === 'string' && (0, _helpers.isComment)(nextNode)) {
isBodyEndTagCanBeOmitted = false;
}
if (isBodyStartTagCanBeOmitted && isBodyEndTagCanBeOmitted) {
node.tag = false;
}
}
/**
* A "colgroup" element's start tag may be omitted if the first thing inside the "colgroup" element is a "col" element, and if the element is not IMMEDIATELY preceded by another "colgroup" element. It can't be omitted if the element is empty.
* A "colgroup" element's end tag may be omitted if the "colgroup" element is not IMMEDIATELY followed by ASCII whitespace or a comment.
*/
if (node.tag === 'colgroup') {
let isColgroupStartTagCanBeOmitted = false;
let isColgroupEndTagCanBeOmitted = true;
if (firstNonEmptyChildNode && firstNonEmptyChildNode.tag && firstNonEmptyChildNode.tag === 'col') {
isColgroupStartTagCanBeOmitted = true;
}
if (prevNonEmptyNode && prevNonEmptyNode.tag && prevNonEmptyNode.tag === 'colgroup') {
isColgroupStartTagCanBeOmitted = false;
}
if (nextNode && typeof nextNode === 'string' && startWithWhitespacePattern.test(nextNode) || nextNonEmptyNode && typeof nextNonEmptyNode === 'string' && (0, _helpers.isComment)(nextNonEmptyNode)) {
isColgroupEndTagCanBeOmitted = false;
}
if (isColgroupStartTagCanBeOmitted && isColgroupEndTagCanBeOmitted) {
node.tag = false;
}
}
/**
* A "tbody" element's start tag may be omitted if the first thing inside the "tbody" element is a "tr" element, and if the element is not immediately preceded by another "tbody", "thead" or "tfoot" element. It can't be omitted if the element is empty.
* A "tbody" element's end tag may be omitted if the "tbody" element is not IMMEDIATELY followed by a "tbody" or "tfoot" element.
*/
if (node.tag === 'tbody') {
let isTbodyStartTagCanBeOmitted = false;
let isTbodyEndTagCanBeOmitted = true;
if (firstNonEmptyChildNode && firstNonEmptyChildNode.tag && firstNonEmptyChildNode.tag === 'tr') {
isTbodyStartTagCanBeOmitted = true;
}
if (prevNonEmptyNode && prevNonEmptyNode.tag && tbodyStartTagCantBeOmittedWithPrecededTags.has(prevNonEmptyNode.tag)) {
isTbodyStartTagCanBeOmitted = false;
}
if (nextNonEmptyNode && nextNonEmptyNode.tag && tbodyEndTagCantBeOmittedWithFollowedTags.has(nextNonEmptyNode.tag)) {
isTbodyEndTagCanBeOmitted = false;
}
if (isTbodyStartTagCanBeOmitted && isTbodyEndTagCanBeOmitted) {
node.tag = false;
}
}
if (node.content && node.content.length) {
removeOptionalTags(node.content);
}
return node;
});
return tree;
}

View file

@ -0,0 +1,110 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = removeRedundantAttributes;
exports.redundantScriptTypes = void 0;
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types#JavaScript_types
const redundantScriptTypes = new Set(['application/javascript', 'application/ecmascript', 'application/x-ecmascript', 'application/x-javascript', 'text/javascript', 'text/ecmascript', 'text/javascript1.0', 'text/javascript1.1', 'text/javascript1.2', 'text/javascript1.3', 'text/javascript1.4', 'text/javascript1.5', 'text/jscript', 'text/livescript', 'text/x-ecmascript', 'text/x-javascript']);
exports.redundantScriptTypes = redundantScriptTypes;
const redundantAttributes = {
'form': {
'method': 'get'
},
'input': {
'type': 'text'
},
'button': {
'type': 'submit'
},
'script': {
'language': 'javascript',
'type': node => {
for (const [attrName, attrValue] of Object.entries(node.attrs)) {
if (attrName.toLowerCase() !== 'type') {
continue;
}
return redundantScriptTypes.has(attrValue);
}
return false;
},
// Remove attribute if the function returns false
'charset': node => {
// The charset attribute only really makes sense on “external” SCRIPT elements:
// http://perfectionkills.com/optimizing-html/#8_script_charset
return node.attrs && !node.attrs.src;
}
},
'style': {
'media': 'all',
'type': 'text/css'
},
'link': {
'media': 'all',
'type': node => {
// https://html.spec.whatwg.org/multipage/links.html#link-type-stylesheet
let isRelStyleSheet = false;
let isTypeTextCSS = false;
if (node.attrs) {
for (const [attrName, attrValue] of Object.entries(node.attrs)) {
if (attrName.toLowerCase() === 'rel' && attrValue === 'stylesheet') {
isRelStyleSheet = true;
}
if (attrName.toLowerCase() === 'type' && attrValue === 'text/css') {
isTypeTextCSS = true;
}
}
} // Only "text/css" is redudant for link[rel=stylesheet]. Otherwise "type" shouldn't be removed
return isRelStyleSheet && isTypeTextCSS;
}
},
// See: https://html.spec.whatwg.org/#lazy-loading-attributes
'img': {
'loading': 'eager'
},
'iframe': {
'loading': 'eager'
}
};
const tagsHaveRedundantAttributes = new Set(Object.keys(redundantAttributes));
/** Removes redundant attributes */
function removeRedundantAttributes(tree) {
tree.walk(node => {
if (!node.tag) {
return node;
}
if (!tagsHaveRedundantAttributes.has(node.tag)) {
return node;
}
const tagRedundantAttributes = redundantAttributes[node.tag];
node.attrs = node.attrs || {};
for (const redundantAttributeName of Object.keys(tagRedundantAttributes)) {
let tagRedundantAttributeValue = tagRedundantAttributes[redundantAttributeName];
let isRemove = false;
if (typeof tagRedundantAttributeValue === 'function') {
isRemove = tagRedundantAttributeValue(node);
} else if (node.attrs[redundantAttributeName] === tagRedundantAttributeValue) {
isRemove = true;
}
if (isRemove) {
delete node.attrs[redundantAttributeName];
}
}
return node;
});
return tree;
}

View file

@ -0,0 +1,125 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = removeUnusedCss;
var _helpers = require("../helpers");
var _uncss = _interopRequireDefault(require("uncss"));
var _purgecss = _interopRequireDefault(require("purgecss"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// These options must be set and shouldn't be overriden to ensure uncss doesn't look at linked stylesheets.
const uncssOptions = {
ignoreSheets: [/\s*/],
stylesheets: []
};
function processStyleNodeUnCSS(html, styleNode, uncssOptions) {
const css = (0, _helpers.extractCssFromStyleNode)(styleNode);
return runUncss(html, css, uncssOptions).then(css => {
// uncss may have left some style tags empty
if (css.trim().length === 0) {
styleNode.tag = false;
styleNode.content = [];
return;
}
styleNode.content = [css];
});
}
function runUncss(html, css, userOptions) {
if (typeof userOptions !== 'object') {
userOptions = {};
}
const options = { ...userOptions,
...uncssOptions
};
return new Promise((resolve, reject) => {
options.raw = css;
(0, _uncss.default)(html, options, (error, output) => {
if (error) {
reject(error);
return;
}
resolve(output);
});
});
}
const purgeFromHtml = function (tree) {
// content is not used as we can directly used the parsed HTML,
// making the process faster
const selectors = [];
tree.walk(node => {
const classes = node.attrs && node.attrs.class && node.attrs.class.split(' ') || [];
const ids = node.attrs && node.attrs.id && node.attrs.id.split(' ') || [];
selectors.push(...classes, ...ids);
node.tag && selectors.push(node.tag);
return node;
});
return () => selectors;
};
function processStyleNodePurgeCSS(tree, styleNode, purgecssOptions) {
const css = (0, _helpers.extractCssFromStyleNode)(styleNode);
return runPurgecss(tree, css, purgecssOptions).then(css => {
if (css.trim().length === 0) {
styleNode.tag = false;
styleNode.content = [];
return;
}
styleNode.content = [css];
});
}
function runPurgecss(tree, css, userOptions) {
if (typeof userOptions !== 'object') {
userOptions = {};
}
const options = { ...userOptions,
content: [{
raw: tree,
extension: 'html'
}],
css: [{
raw: css,
extension: 'css'
}],
extractors: [{
extractor: purgeFromHtml(tree),
extensions: ['html']
}]
};
return new _purgecss.default().purge(options).then(result => {
return result[0].css;
});
}
/** Remove unused CSS */
function removeUnusedCss(tree, options, userOptions) {
const promises = [];
const html = userOptions.tool !== 'purgeCSS' && tree.render(tree);
tree.walk(node => {
if ((0, _helpers.isStyleNode)(node)) {
if (userOptions.tool === 'purgeCSS') {
promises.push(processStyleNodePurgeCSS(tree, node, userOptions));
} else {
promises.push(processStyleNodeUnCSS(html, node, userOptions));
}
}
return node;
});
return Promise.all(promises).then(() => tree);
}

115
BACK_BACK/node_modules/htmlnano/lib/modules/sortAttributes.js generated vendored Executable file
View file

@ -0,0 +1,115 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = sortAttributes;
var _timsort = require("timsort");
const validOptions = new Set(['frequency', 'alphabetical']);
const processModuleOptions = options => {
if (options === true) return 'alphabetical';
return validOptions.has(options) ? options : false;
};
class AttributeTokenChain {
constructor() {
this.freqData = new Map(); // <attr, frequency>[]
}
addFromNodeAttrs(nodeAttrs) {
Object.keys(nodeAttrs).forEach(attrName => {
const attrNameLower = attrName.toLowerCase();
if (this.freqData.has(attrNameLower)) {
this.freqData.set(attrNameLower, this.freqData.get(attrNameLower) + 1);
} else {
this.freqData.set(attrNameLower, 1);
}
});
}
createSortOrder() {
let _sortOrder = [...this.freqData.entries()];
(0, _timsort.sort)(_sortOrder, (a, b) => b[1] - a[1]);
this.sortOrder = _sortOrder.map(i => i[0]);
}
sortFromNodeAttrs(nodeAttrs) {
const newAttrs = {}; // Convert node.attrs attrName into lower case.
const loweredNodeAttrs = {};
Object.entries(nodeAttrs).forEach(([attrName, attrValue]) => {
loweredNodeAttrs[attrName.toLowerCase()] = attrValue;
});
if (!this.sortOrder) {
this.createSortOrder();
}
this.sortOrder.forEach(attrNameLower => {
// The attrName inside "sortOrder" has been lowered
if (loweredNodeAttrs[attrNameLower]) {
newAttrs[attrNameLower] = loweredNodeAttrs[attrNameLower];
}
});
return newAttrs;
}
}
/** Sort attibutes */
function sortAttributes(tree, options, moduleOptions) {
const sortType = processModuleOptions(moduleOptions);
if (sortType === 'alphabetical') {
return sortAttributesInAlphabeticalOrder(tree);
}
if (sortType === 'frequency') {
return sortAttributesByFrequency(tree);
} // Invalid configuration
return tree;
}
function sortAttributesInAlphabeticalOrder(tree) {
tree.walk(node => {
if (!node.attrs) {
return node;
}
const newAttrs = {};
Object.keys(node.attrs).sort((a, b) => typeof a.localeCompare === 'function' ? a.localeCompare(b) : a - b).forEach(attr => newAttrs[attr] = node.attrs[attr]);
node.attrs = newAttrs;
return node;
});
return tree;
}
function sortAttributesByFrequency(tree) {
const tokenchain = new AttributeTokenChain(); // Traverse through tree to get frequency
tree.walk(node => {
if (!node.attrs) {
return node;
}
tokenchain.addFromNodeAttrs(node.attrs);
return node;
}); // Traverse through tree again, this time sort the attributes
tree.walk(node => {
if (!node.attrs) {
return node;
}
node.attrs = tokenchain.sortFromNodeAttrs(node.attrs);
return node;
});
return tree;
}

View file

@ -0,0 +1,138 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = collapseAttributeWhitespace;
var _timsort = require("timsort");
var _collapseAttributeWhitespace = require("./collapseAttributeWhitespace");
// class, rel, ping
const validOptions = new Set(['frequency', 'alphabetical']);
const processModuleOptions = options => {
if (options === true) return 'alphabetical';
return validOptions.has(options) ? options : false;
};
class AttributeTokenChain {
constructor() {
this.freqData = new Map(); // <attrValue, frequency>[]
}
addFromNodeAttrsArray(attrValuesArray) {
attrValuesArray.forEach(attrValue => {
if (this.freqData.has(attrValue)) {
this.freqData.set(attrValue, this.freqData.get(attrValue) + 1);
} else {
this.freqData.set(attrValue, 1);
}
});
}
createSortOrder() {
let _sortOrder = [...this.freqData.entries()];
(0, _timsort.sort)(_sortOrder, (a, b) => b[1] - a[1]);
this.sortOrder = _sortOrder.map(i => i[0]);
}
sortFromNodeAttrsArray(attrValuesArray) {
const resultArray = [];
if (!this.sortOrder) {
this.createSortOrder();
}
this.sortOrder.forEach(k => {
if (attrValuesArray.includes(k)) {
resultArray.push(k);
}
});
return resultArray;
}
}
/** Sort values inside list-like attributes (e.g. class, rel) */
function collapseAttributeWhitespace(tree, options, moduleOptions) {
const sortType = processModuleOptions(moduleOptions);
if (sortType === 'alphabetical') {
return sortAttributesWithListsInAlphabeticalOrder(tree);
}
if (sortType === 'frequency') {
return sortAttributesWithListsByFrequency(tree);
} // Invalid configuration
return tree;
}
function sortAttributesWithListsInAlphabeticalOrder(tree) {
tree.walk(node => {
if (!node.attrs) {
return node;
}
Object.keys(node.attrs).forEach(attrName => {
const attrNameLower = attrName.toLowerCase();
if (!_collapseAttributeWhitespace.attributesWithLists.has(attrNameLower)) {
return;
}
const attrValues = node.attrs[attrName].split(/\s/);
node.attrs[attrName] = attrValues.sort((a, b) => {
return typeof a.localeCompare === 'function' ? a.localeCompare(b) : a - b;
}).join(' ');
});
return node;
});
return tree;
}
function sortAttributesWithListsByFrequency(tree) {
const tokenChainObj = {}; // <attrNameLower: AttributeTokenChain>[]
// Traverse through tree to get frequency
tree.walk(node => {
if (!node.attrs) {
return node;
}
Object.entries(node.attrs).forEach(([attrName, attrValues]) => {
const attrNameLower = attrName.toLowerCase();
if (!_collapseAttributeWhitespace.attributesWithLists.has(attrNameLower)) {
return;
}
tokenChainObj[attrNameLower] = tokenChainObj[attrNameLower] || new AttributeTokenChain();
tokenChainObj[attrNameLower].addFromNodeAttrsArray(attrValues.split(/\s/));
});
return node;
}); // Traverse through tree again, this time sort the attribute values
tree.walk(node => {
if (!node.attrs) {
return node;
}
Object.entries(node.attrs).forEach(([attrName, attrValues]) => {
const attrNameLower = attrName.toLowerCase();
if (!_collapseAttributeWhitespace.attributesWithLists.has(attrNameLower)) {
return;
}
if (tokenChainObj[attrNameLower]) {
node.attrs[attrName] = tokenChainObj[attrNameLower].sortFromNodeAttrsArray(attrValues.split(/\s/)).join(' ');
}
});
return node;
});
}

26
BACK_BACK/node_modules/htmlnano/lib/presets/ampSafe.js generated vendored Executable file
View file

@ -0,0 +1,26 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _safe = _interopRequireDefault(require("./safe"));
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
/**
* A safe preset for AMP pages (https://www.ampproject.org)
*/
var _default = { ..._safe.default,
collapseBooleanAttributes: {
amphtml: true
},
minifyJs: false
};
exports.default = _default;

33
BACK_BACK/node_modules/htmlnano/lib/presets/max.js generated vendored Executable file
View file

@ -0,0 +1,33 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _safe = _interopRequireDefault(require("./safe"));
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
/**
* Maximal minification (might break some pages)
*/
var _default = { ..._safe.default,
collapseWhitespace: 'all',
removeComments: 'all',
removeAttributeQuotes: true,
removeRedundantAttributes: true,
removeUnusedCss: {},
minifyCss: {
preset: 'default'
},
minifySvg: {},
minifyConditionalComments: true,
removeOptionalTags: true
};
exports.default = _default;

44
BACK_BACK/node_modules/htmlnano/lib/presets/safe.js generated vendored Executable file
View file

@ -0,0 +1,44 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
/**
* Minify HTML in a safe way without breaking anything.
*/
var _default = {
sortAttributes: false,
collapseAttributeWhitespace: true,
collapseBooleanAttributes: {
amphtml: false
},
collapseWhitespace: 'conservative',
custom: [],
deduplicateAttributeValues: true,
mergeScripts: true,
mergeStyles: true,
removeUnusedCss: false,
minifyCss: {
preset: 'default'
},
minifyJs: {},
minifyJson: {},
minifySvg: {
plugins: [{
collapseGroups: false
}, {
convertShapeToPath: false
}]
},
minifyConditionalComments: false,
removeEmptyAttributes: true,
removeRedundantAttributes: false,
removeComments: 'safe',
removeAttributeQuotes: false,
sortAttributesWithLists: 'alphabetical',
minifyUrls: false,
removeOptionalTags: false
};
exports.default = _default;

1
BACK_BACK/node_modules/htmlnano/node_modules/.bin/acorn generated vendored Symbolic link
View file

@ -0,0 +1 @@
../acorn/bin/acorn

View file

@ -0,0 +1 @@
../terser/bin/terser

View file

@ -0,0 +1,910 @@
## 8.12.1 (2024-07-03)
### Bug fixes
Fix a regression that caused Acorn to no longer run on Node versions <8.10.
## 8.12.0 (2024-06-14)
### New features
Support ES2025 duplicate capture group names in regular expressions.
### Bug fixes
Include `VariableDeclarator` in the `AnyNode` type so that walker objects can refer to it without getting a type error.
Properly raise a parse error for invalid `for`/`of` statements using `async` as binding name.
Properly recognize \"use strict\" when preceded by a string with an escaped newline.
Mark the `Parser` constructor as protected, not private, so plugins can extend it without type errors.
Fix a bug where some invalid `delete` expressions were let through when the operand was parenthesized and `preserveParens` was enabled.
Properly normalize line endings in raw strings of invalid template tokens.
Properly track line numbers for escaped newlines in strings.
Fix a bug that broke line number accounting after a template literal with invalid escape sequences.
## 8.11.3 (2023-12-29)
### Bug fixes
Add `Function` and `Class` to the `AggregateType` type, so that they can be used in walkers without raising a type error.
Make sure `onToken` get an `import` keyword token when parsing `import.meta`.
Fix a bug where `.loc.start` could be undefined for `new.target` `meta` nodes.
## 8.11.2 (2023-10-27)
### Bug fixes
Fix a bug that caused regular expressions after colon tokens to not be properly tokenized in some circumstances.
## 8.11.1 (2023-10-26)
### Bug fixes
Fix a regression where `onToken` would receive 'name' tokens for 'new' keyword tokens.
## 8.11.0 (2023-10-26)
### Bug fixes
Fix an issue where tokenizing (without parsing) an object literal with a property named `class` or `function` could, in some circumstance, put the tokenizer into an invalid state.
Fix an issue where a slash after a call to a propery named the same as some keywords would be tokenized as a regular expression.
### New features
Upgrade to Unicode 15.1.
Use a set of new, much more precise, TypeScript types.
## 8.10.0 (2023-07-05)
### New features
Add a `checkPrivateFields` option that disables strict checking of private property use.
## 8.9.0 (2023-06-16)
### Bug fixes
Forbid dynamic import after `new`, even when part of a member expression.
### New features
Add Unicode properties for ES2023.
Add support for the `v` flag to regular expressions.
## 8.8.2 (2023-01-23)
### Bug fixes
Fix a bug that caused `allowHashBang` to be set to false when not provided, even with `ecmaVersion >= 14`.
Fix an exception when passing no option object to `parse` or `new Parser`.
Fix incorrect parse error on `if (0) let\n[astral identifier char]`.
## 8.8.1 (2022-10-24)
### Bug fixes
Make type for `Comment` compatible with estree types.
## 8.8.0 (2022-07-21)
### Bug fixes
Allow parentheses around spread args in destructuring object assignment.
Fix an issue where the tree contained `directive` properties in when parsing with a language version that doesn't support them.
### New features
Support hashbang comments by default in ECMAScript 2023 and later.
## 8.7.1 (2021-04-26)
### Bug fixes
Stop handling `"use strict"` directives in ECMAScript versions before 5.
Fix an issue where duplicate quoted export names in `export *` syntax were incorrectly checked.
Add missing type for `tokTypes`.
## 8.7.0 (2021-12-27)
### New features
Support quoted export names.
Upgrade to Unicode 14.
Add support for Unicode 13 properties in regular expressions.
### Bug fixes
Use a loop to find line breaks, because the existing regexp search would overrun the end of the searched range and waste a lot of time in minified code.
## 8.6.0 (2021-11-18)
### Bug fixes
Fix a bug where an object literal with multiple `__proto__` properties would incorrectly be accepted if a later property value held an assigment.
### New features
Support class private fields with the `in` operator.
## 8.5.0 (2021-09-06)
### Bug fixes
Improve context-dependent tokenization in a number of corner cases.
Fix location tracking after a 0x2028 or 0x2029 character in a string literal (which before did not increase the line number).
Fix an issue where arrow function bodies in for loop context would inappropriately consume `in` operators.
Fix wrong end locations stored on SequenceExpression nodes.
Implement restriction that `for`/`of` loop LHS can't start with `let`.
### New features
Add support for ES2022 class static blocks.
Allow multiple input files to be passed to the CLI tool.
## 8.4.1 (2021-06-24)
### Bug fixes
Fix a bug where `allowAwaitOutsideFunction` would allow `await` in class field initializers, and setting `ecmaVersion` to 13 or higher would allow top-level await in non-module sources.
## 8.4.0 (2021-06-11)
### New features
A new option, `allowSuperOutsideMethod`, can be used to suppress the error when `super` is used in the wrong context.
## 8.3.0 (2021-05-31)
### New features
Default `allowAwaitOutsideFunction` to true for ECMAScript 2022 an higher.
Add support for the `d` ([indices](https://github.com/tc39/proposal-regexp-match-indices)) regexp flag.
## 8.2.4 (2021-05-04)
### Bug fixes
Fix spec conformity in corner case 'for await (async of ...)'.
## 8.2.3 (2021-05-04)
### Bug fixes
Fix an issue where the library couldn't parse 'for (async of ...)'.
Fix a bug in UTF-16 decoding that would read characters incorrectly in some circumstances.
## 8.2.2 (2021-04-29)
### Bug fixes
Fix a bug where a class field initialized to an async arrow function wouldn't allow await inside it. Same issue existed for generator arrow functions with yield.
## 8.2.1 (2021-04-24)
### Bug fixes
Fix a regression introduced in 8.2.0 where static or async class methods with keyword names fail to parse.
## 8.2.0 (2021-04-24)
### New features
Add support for ES2022 class fields and private methods.
## 8.1.1 (2021-04-12)
### Various
Stop shipping source maps in the NPM package.
## 8.1.0 (2021-03-09)
### Bug fixes
Fix a spurious error in nested destructuring arrays.
### New features
Expose `allowAwaitOutsideFunction` in CLI interface.
Make `allowImportExportAnywhere` also apply to `import.meta`.
## 8.0.5 (2021-01-25)
### Bug fixes
Adjust package.json to work with Node 12.16.0 and 13.0-13.6.
## 8.0.4 (2020-10-05)
### Bug fixes
Make `await x ** y` an error, following the spec.
Fix potentially exponential regular expression.
## 8.0.3 (2020-10-02)
### Bug fixes
Fix a wasteful loop during `Parser` creation when setting `ecmaVersion` to `"latest"`.
## 8.0.2 (2020-09-30)
### Bug fixes
Make the TypeScript types reflect the current allowed values for `ecmaVersion`.
Fix another regexp/division tokenizer issue.
## 8.0.1 (2020-08-12)
### Bug fixes
Provide the correct value in the `version` export.
## 8.0.0 (2020-08-12)
### Bug fixes
Disallow expressions like `(a = b) = c`.
Make non-octal escape sequences a syntax error in strict mode.
### New features
The package can now be loaded directly as an ECMAScript module in node 13+.
Update to the set of Unicode properties from ES2021.
### Breaking changes
The `ecmaVersion` option is now required. For the moment, omitting it will still work with a warning, but that will change in a future release.
Some changes to method signatures that may be used by plugins.
## 7.4.0 (2020-08-03)
### New features
Add support for logical assignment operators.
Add support for numeric separators.
## 7.3.1 (2020-06-11)
### Bug fixes
Make the string in the `version` export match the actual library version.
## 7.3.0 (2020-06-11)
### Bug fixes
Fix a bug that caused parsing of object patterns with a property named `set` that had a default value to fail.
### New features
Add support for optional chaining (`?.`).
## 7.2.0 (2020-05-09)
### Bug fixes
Fix precedence issue in parsing of async arrow functions.
### New features
Add support for nullish coalescing.
Add support for `import.meta`.
Support `export * as ...` syntax.
Upgrade to Unicode 13.
## 6.4.1 (2020-03-09)
### Bug fixes
More carefully check for valid UTF16 surrogate pairs in regexp validator.
## 7.1.1 (2020-03-01)
### Bug fixes
Treat `\8` and `\9` as invalid escapes in template strings.
Allow unicode escapes in property names that are keywords.
Don't error on an exponential operator expression as argument to `await`.
More carefully check for valid UTF16 surrogate pairs in regexp validator.
## 7.1.0 (2019-09-24)
### Bug fixes
Disallow trailing object literal commas when ecmaVersion is less than 5.
### New features
Add a static `acorn` property to the `Parser` class that contains the entire module interface, to allow plugins to access the instance of the library that they are acting on.
## 7.0.0 (2019-08-13)
### Breaking changes
Changes the node format for dynamic imports to use the `ImportExpression` node type, as defined in [ESTree](https://github.com/estree/estree/blob/master/es2020.md#importexpression).
Makes 10 (ES2019) the default value for the `ecmaVersion` option.
## 6.3.0 (2019-08-12)
### New features
`sourceType: "module"` can now be used even when `ecmaVersion` is less than 6, to parse module-style code that otherwise conforms to an older standard.
## 6.2.1 (2019-07-21)
### Bug fixes
Fix bug causing Acorn to treat some characters as identifier characters that shouldn't be treated as such.
Fix issue where setting the `allowReserved` option to `"never"` allowed reserved words in some circumstances.
## 6.2.0 (2019-07-04)
### Bug fixes
Improve valid assignment checking in `for`/`in` and `for`/`of` loops.
Disallow binding `let` in patterns.
### New features
Support bigint syntax with `ecmaVersion` >= 11.
Support dynamic `import` syntax with `ecmaVersion` >= 11.
Upgrade to Unicode version 12.
## 6.1.1 (2019-02-27)
### Bug fixes
Fix bug that caused parsing default exports of with names to fail.
## 6.1.0 (2019-02-08)
### Bug fixes
Fix scope checking when redefining a `var` as a lexical binding.
### New features
Split up `parseSubscripts` to use an internal `parseSubscript` method to make it easier to extend with plugins.
## 6.0.7 (2019-02-04)
### Bug fixes
Check that exported bindings are defined.
Don't treat `\u180e` as a whitespace character.
Check for duplicate parameter names in methods.
Don't allow shorthand properties when they are generators or async methods.
Forbid binding `await` in async arrow function's parameter list.
## 6.0.6 (2019-01-30)
### Bug fixes
The content of class declarations and expressions is now always parsed in strict mode.
Don't allow `let` or `const` to bind the variable name `let`.
Treat class declarations as lexical.
Don't allow a generator function declaration as the sole body of an `if` or `else`.
Ignore `"use strict"` when after an empty statement.
Allow string line continuations with special line terminator characters.
Treat `for` bodies as part of the `for` scope when checking for conflicting bindings.
Fix bug with parsing `yield` in a `for` loop initializer.
Implement special cases around scope checking for functions.
## 6.0.5 (2019-01-02)
### Bug fixes
Fix TypeScript type for `Parser.extend` and add `allowAwaitOutsideFunction` to options type.
Don't treat `let` as a keyword when the next token is `{` on the next line.
Fix bug that broke checking for parentheses around an object pattern in a destructuring assignment when `preserveParens` was on.
## 6.0.4 (2018-11-05)
### Bug fixes
Further improvements to tokenizing regular expressions in corner cases.
## 6.0.3 (2018-11-04)
### Bug fixes
Fix bug in tokenizing an expression-less return followed by a function followed by a regular expression.
Remove stray symlink in the package tarball.
## 6.0.2 (2018-09-26)
### Bug fixes
Fix bug where default expressions could fail to parse inside an object destructuring assignment expression.
## 6.0.1 (2018-09-14)
### Bug fixes
Fix wrong value in `version` export.
## 6.0.0 (2018-09-14)
### Bug fixes
Better handle variable-redefinition checks for catch bindings and functions directly under if statements.
Forbid `new.target` in top-level arrow functions.
Fix issue with parsing a regexp after `yield` in some contexts.
### New features
The package now comes with TypeScript definitions.
### Breaking changes
The default value of the `ecmaVersion` option is now 9 (2018).
Plugins work differently, and will have to be rewritten to work with this version.
The loose parser and walker have been moved into separate packages (`acorn-loose` and `acorn-walk`).
## 5.7.3 (2018-09-10)
### Bug fixes
Fix failure to tokenize regexps after expressions like `x.of`.
Better error message for unterminated template literals.
## 5.7.2 (2018-08-24)
### Bug fixes
Properly handle `allowAwaitOutsideFunction` in for statements.
Treat function declarations at the top level of modules like let bindings.
Don't allow async function declarations as the only statement under a label.
## 5.7.0 (2018-06-15)
### New features
Upgraded to Unicode 11.
## 5.6.0 (2018-05-31)
### New features
Allow U+2028 and U+2029 in string when ECMAVersion >= 10.
Allow binding-less catch statements when ECMAVersion >= 10.
Add `allowAwaitOutsideFunction` option for parsing top-level `await`.
## 5.5.3 (2018-03-08)
### Bug fixes
A _second_ republish of the code in 5.5.1, this time with yarn, to hopefully get valid timestamps.
## 5.5.2 (2018-03-08)
### Bug fixes
A republish of the code in 5.5.1 in an attempt to solve an issue with the file timestamps in the npm package being 0.
## 5.5.1 (2018-03-06)
### Bug fixes
Fix misleading error message for octal escapes in template strings.
## 5.5.0 (2018-02-27)
### New features
The identifier character categorization is now based on Unicode version 10.
Acorn will now validate the content of regular expressions, including new ES9 features.
## 5.4.0 (2018-02-01)
### Bug fixes
Disallow duplicate or escaped flags on regular expressions.
Disallow octal escapes in strings in strict mode.
### New features
Add support for async iteration.
Add support for object spread and rest.
## 5.3.0 (2017-12-28)
### Bug fixes
Fix parsing of floating point literals with leading zeroes in loose mode.
Allow duplicate property names in object patterns.
Don't allow static class methods named `prototype`.
Disallow async functions directly under `if` or `else`.
Parse right-hand-side of `for`/`of` as an assignment expression.
Stricter parsing of `for`/`in`.
Don't allow unicode escapes in contextual keywords.
### New features
Parsing class members was factored into smaller methods to allow plugins to hook into it.
## 5.2.1 (2017-10-30)
### Bug fixes
Fix a token context corruption bug.
## 5.2.0 (2017-10-30)
### Bug fixes
Fix token context tracking for `class` and `function` in property-name position.
Make sure `%*` isn't parsed as a valid operator.
Allow shorthand properties `get` and `set` to be followed by default values.
Disallow `super` when not in callee or object position.
### New features
Support [`directive` property](https://github.com/estree/estree/compare/b3de58c9997504d6fba04b72f76e6dd1619ee4eb...1da8e603237144f44710360f8feb7a9977e905e0) on directive expression statements.
## 5.1.2 (2017-09-04)
### Bug fixes
Disable parsing of legacy HTML-style comments in modules.
Fix parsing of async methods whose names are keywords.
## 5.1.1 (2017-07-06)
### Bug fixes
Fix problem with disambiguating regexp and division after a class.
## 5.1.0 (2017-07-05)
### Bug fixes
Fix tokenizing of regexps in an object-desctructuring `for`/`of` loop and after `yield`.
Parse zero-prefixed numbers with non-octal digits as decimal.
Allow object/array patterns in rest parameters.
Don't error when `yield` is used as a property name.
Allow `async` as a shorthand object property.
### New features
Implement the [template literal revision proposal](https://github.com/tc39/proposal-template-literal-revision) for ES9.
## 5.0.3 (2017-04-01)
### Bug fixes
Fix spurious duplicate variable definition errors for named functions.
## 5.0.2 (2017-03-30)
### Bug fixes
A binary operator after a parenthesized arrow expression is no longer incorrectly treated as an error.
## 5.0.0 (2017-03-28)
### Bug fixes
Raise an error for duplicated lexical bindings.
Fix spurious error when an assignement expression occurred after a spread expression.
Accept regular expressions after `of` (in `for`/`of`), `yield` (in a generator), and braced arrow functions.
Allow labels in front or `var` declarations, even in strict mode.
### Breaking changes
Parse declarations following `export default` as declaration nodes, not expressions. This means that class and function declarations nodes can now have `null` as their `id`.
## 4.0.11 (2017-02-07)
### Bug fixes
Allow all forms of member expressions to be parenthesized as lvalue.
## 4.0.10 (2017-02-07)
### Bug fixes
Don't expect semicolons after default-exported functions or classes, even when they are expressions.
Check for use of `'use strict'` directives in non-simple parameter functions, even when already in strict mode.
## 4.0.9 (2017-02-06)
### Bug fixes
Fix incorrect error raised for parenthesized simple assignment targets, so that `(x) = 1` parses again.
## 4.0.8 (2017-02-03)
### Bug fixes
Solve spurious parenthesized pattern errors by temporarily erring on the side of accepting programs that our delayed errors don't handle correctly yet.
## 4.0.7 (2017-02-02)
### Bug fixes
Accept invalidly rejected code like `(x).y = 2` again.
Don't raise an error when a function _inside_ strict code has a non-simple parameter list.
## 4.0.6 (2017-02-02)
### Bug fixes
Fix exponential behavior (manifesting itself as a complete hang for even relatively small source files) introduced by the new 'use strict' check.
## 4.0.5 (2017-02-02)
### Bug fixes
Disallow parenthesized pattern expressions.
Allow keywords as export names.
Don't allow the `async` keyword to be parenthesized.
Properly raise an error when a keyword contains a character escape.
Allow `"use strict"` to appear after other string literal expressions.
Disallow labeled declarations.
## 4.0.4 (2016-12-19)
### Bug fixes
Fix crash when `export` was followed by a keyword that can't be
exported.
## 4.0.3 (2016-08-16)
### Bug fixes
Allow regular function declarations inside single-statement `if` branches in loose mode. Forbid them entirely in strict mode.
Properly parse properties named `async` in ES2017 mode.
Fix bug where reserved words were broken in ES2017 mode.
## 4.0.2 (2016-08-11)
### Bug fixes
Don't ignore period or 'e' characters after octal numbers.
Fix broken parsing for call expressions in default parameter values of arrow functions.
## 4.0.1 (2016-08-08)
### Bug fixes
Fix false positives in duplicated export name errors.
## 4.0.0 (2016-08-07)
### Breaking changes
The default `ecmaVersion` option value is now 7.
A number of internal method signatures changed, so plugins might need to be updated.
### Bug fixes
The parser now raises errors on duplicated export names.
`arguments` and `eval` can now be used in shorthand properties.
Duplicate parameter names in non-simple argument lists now always produce an error.
### New features
The `ecmaVersion` option now also accepts year-style version numbers
(2015, etc).
Support for `async`/`await` syntax when `ecmaVersion` is >= 8.
Support for trailing commas in call expressions when `ecmaVersion` is >= 8.
## 3.3.0 (2016-07-25)
### Bug fixes
Fix bug in tokenizing of regexp operator after a function declaration.
Fix parser crash when parsing an array pattern with a hole.
### New features
Implement check against complex argument lists in functions that enable strict mode in ES7.
## 3.2.0 (2016-06-07)
### Bug fixes
Improve handling of lack of unicode regexp support in host
environment.
Properly reject shorthand properties whose name is a keyword.
### New features
Visitors created with `visit.make` now have their base as _prototype_, rather than copying properties into a fresh object.
## 3.1.0 (2016-04-18)
### Bug fixes
Properly tokenize the division operator directly after a function expression.
Allow trailing comma in destructuring arrays.
## 3.0.4 (2016-02-25)
### Fixes
Allow update expressions as left-hand-side of the ES7 exponential operator.
## 3.0.2 (2016-02-10)
### Fixes
Fix bug that accidentally made `undefined` a reserved word when parsing ES7.
## 3.0.0 (2016-02-10)
### Breaking changes
The default value of the `ecmaVersion` option is now 6 (used to be 5).
Support for comprehension syntax (which was dropped from the draft spec) has been removed.
### Fixes
`let` and `yield` are now “contextual keywords”, meaning you can mostly use them as identifiers in ES5 non-strict code.
A parenthesized class or function expression after `export default` is now parsed correctly.
### New features
When `ecmaVersion` is set to 7, Acorn will parse the exponentiation operator (`**`).
The identifier character ranges are now based on Unicode 8.0.0.
Plugins can now override the `raiseRecoverable` method to override the way non-critical errors are handled.
## 2.7.0 (2016-01-04)
### Fixes
Stop allowing rest parameters in setters.
Disallow `y` rexexp flag in ES5.
Disallow `\00` and `\000` escapes in strict mode.
Raise an error when an import name is a reserved word.
## 2.6.2 (2015-11-10)
### Fixes
Don't crash when no options object is passed.
## 2.6.0 (2015-11-09)
### Fixes
Add `await` as a reserved word in module sources.
Disallow `yield` in a parameter default value for a generator.
Forbid using a comma after a rest pattern in an array destructuring.
### New features
Support parsing stdin in command-line tool.
## 2.5.0 (2015-10-27)
### Fixes
Fix tokenizer support in the command-line tool.
Stop allowing `new.target` outside of functions.
Remove legacy `guard` and `guardedHandler` properties from try nodes.
Stop allowing multiple `__proto__` properties on an object literal in strict mode.
Don't allow rest parameters to be non-identifier patterns.
Check for duplicate paramter names in arrow functions.

21
BACK_BACK/node_modules/htmlnano/node_modules/acorn/LICENSE generated vendored Executable file
View file

@ -0,0 +1,21 @@
MIT License
Copyright (C) 2012-2022 by various contributors (see AUTHORS)
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.

282
BACK_BACK/node_modules/htmlnano/node_modules/acorn/README.md generated vendored Executable file
View file

@ -0,0 +1,282 @@
# Acorn
A tiny, fast JavaScript parser written in JavaScript.
## Community
Acorn is open source software released under an
[MIT license](https://github.com/acornjs/acorn/blob/master/acorn/LICENSE).
You are welcome to
[report bugs](https://github.com/acornjs/acorn/issues) or create pull
requests on [github](https://github.com/acornjs/acorn).
## Installation
The easiest way to install acorn is from [`npm`](https://www.npmjs.com/):
```sh
npm install acorn
```
Alternately, you can download the source and build acorn yourself:
```sh
git clone https://github.com/acornjs/acorn.git
cd acorn
npm install
```
## Interface
**parse**`(input, options)` is the main interface to the library. The
`input` parameter is a string, `options` must be an object setting
some of the options listed below. The return value will be an abstract
syntax tree object as specified by the [ESTree
spec](https://github.com/estree/estree).
```javascript
let acorn = require("acorn");
console.log(acorn.parse("1 + 1", {ecmaVersion: 2020}));
```
When encountering a syntax error, the parser will raise a
`SyntaxError` object with a meaningful message. The error object will
have a `pos` property that indicates the string offset at which the
error occurred, and a `loc` object that contains a `{line, column}`
object referring to that same position.
Options are provided by in a second argument, which should be an
object containing any of these fields (only `ecmaVersion` is
required):
- **ecmaVersion**: Indicates the ECMAScript version to parse. Can be a
number, either in year (`2022`) or plain version number (`6`) form,
or `"latest"` (the latest the library supports). This influences
support for strict mode, the set of reserved words, and support for
new syntax features.
**NOTE**: Only 'stage 4' (finalized) ECMAScript features are being
implemented by Acorn. Other proposed new features must be
implemented through plugins.
- **sourceType**: Indicate the mode the code should be parsed in. Can be
either `"script"` or `"module"`. This influences global strict mode
and parsing of `import` and `export` declarations.
**NOTE**: If set to `"module"`, then static `import` / `export` syntax
will be valid, even if `ecmaVersion` is less than 6.
- **onInsertedSemicolon**: If given a callback, that callback will be
called whenever a missing semicolon is inserted by the parser. The
callback will be given the character offset of the point where the
semicolon is inserted as argument, and if `locations` is on, also a
`{line, column}` object representing this position.
- **onTrailingComma**: Like `onInsertedSemicolon`, but for trailing
commas.
- **allowReserved**: If `false`, using a reserved word will generate
an error. Defaults to `true` for `ecmaVersion` 3, `false` for higher
versions. When given the value `"never"`, reserved words and
keywords can also not be used as property names (as in Internet
Explorer's old parser).
- **allowReturnOutsideFunction**: By default, a return statement at
the top level raises an error. Set this to `true` to accept such
code.
- **allowImportExportEverywhere**: By default, `import` and `export`
declarations can only appear at a program's top level. Setting this
option to `true` allows them anywhere where a statement is allowed,
and also allows `import.meta` expressions to appear in scripts
(when `sourceType` is not `"module"`).
- **allowAwaitOutsideFunction**: If `false`, `await` expressions can
only appear inside `async` functions. Defaults to `true` in modules
for `ecmaVersion` 2022 and later, `false` for lower versions.
Setting this option to `true` allows to have top-level `await`
expressions. They are still not allowed in non-`async` functions,
though.
- **allowSuperOutsideMethod**: By default, `super` outside a method
raises an error. Set this to `true` to accept such code.
- **allowHashBang**: When this is enabled, if the code starts with the
characters `#!` (as in a shellscript), the first line will be
treated as a comment. Defaults to true when `ecmaVersion` >= 2023.
- **checkPrivateFields**: By default, the parser will verify that
private properties are only used in places where they are valid and
have been declared. Set this to false to turn such checks off.
- **locations**: When `true`, each node has a `loc` object attached
with `start` and `end` subobjects, each of which contains the
one-based line and zero-based column numbers in `{line, column}`
form. Default is `false`.
- **onToken**: If a function is passed for this option, each found
token will be passed in same format as tokens returned from
`tokenizer().getToken()`.
If array is passed, each found token is pushed to it.
Note that you are not allowed to call the parser from the
callback—that will corrupt its internal state.
- **onComment**: If a function is passed for this option, whenever a
comment is encountered the function will be called with the
following parameters:
- `block`: `true` if the comment is a block comment, false if it
is a line comment.
- `text`: The content of the comment.
- `start`: Character offset of the start of the comment.
- `end`: Character offset of the end of the comment.
When the `locations` options is on, the `{line, column}` locations
of the comments start and end are passed as two additional
parameters.
If array is passed for this option, each found comment is pushed
to it as object in Esprima format:
```javascript
{
"type": "Line" | "Block",
"value": "comment text",
"start": Number,
"end": Number,
// If `locations` option is on:
"loc": {
"start": {line: Number, column: Number}
"end": {line: Number, column: Number}
},
// If `ranges` option is on:
"range": [Number, Number]
}
```
Note that you are not allowed to call the parser from the
callback—that will corrupt its internal state.
- **ranges**: Nodes have their start and end characters offsets
recorded in `start` and `end` properties (directly on the node,
rather than the `loc` object, which holds line/column data. To also
add a
[semi-standardized](https://bugzilla.mozilla.org/show_bug.cgi?id=745678)
`range` property holding a `[start, end]` array with the same
numbers, set the `ranges` option to `true`.
- **program**: It is possible to parse multiple files into a single
AST by passing the tree produced by parsing the first file as the
`program` option in subsequent parses. This will add the toplevel
forms of the parsed file to the "Program" (top) node of an existing
parse tree.
- **sourceFile**: When the `locations` option is `true`, you can pass
this option to add a `source` attribute in every nodes `loc`
object. Note that the contents of this option are not examined or
processed in any way; you are free to use whatever format you
choose.
- **directSourceFile**: Like `sourceFile`, but a `sourceFile` property
will be added (regardless of the `location` option) directly to the
nodes, rather than the `loc` object.
- **preserveParens**: If this option is `true`, parenthesized expressions
are represented by (non-standard) `ParenthesizedExpression` nodes
that have a single `expression` property containing the expression
inside parentheses.
**parseExpressionAt**`(input, offset, options)` will parse a single
expression in a string, and return its AST. It will not complain if
there is more of the string left after the expression.
**tokenizer**`(input, options)` returns an object with a `getToken`
method that can be called repeatedly to get the next token, a `{start,
end, type, value}` object (with added `loc` property when the
`locations` option is enabled and `range` property when the `ranges`
option is enabled). When the token's type is `tokTypes.eof`, you
should stop calling the method, since it will keep returning that same
token forever.
Note that tokenizing JavaScript without parsing it is, in modern
versions of the language, not really possible due to the way syntax is
overloaded in ways that can only be disambiguated by the parse
context. This package applies a bunch of heuristics to try and do a
reasonable job, but you are advised to use `parse` with the `onToken`
option instead of this.
In ES6 environment, returned result can be used as any other
protocol-compliant iterable:
```javascript
for (let token of acorn.tokenizer(str)) {
// iterate over the tokens
}
// transform code to array of tokens:
var tokens = [...acorn.tokenizer(str)];
```
**tokTypes** holds an object mapping names to the token type objects
that end up in the `type` properties of tokens.
**getLineInfo**`(input, offset)` can be used to get a `{line,
column}` object for a given program string and offset.
### The `Parser` class
Instances of the **`Parser`** class contain all the state and logic
that drives a parse. It has static methods `parse`,
`parseExpressionAt`, and `tokenizer` that match the top-level
functions by the same name.
When extending the parser with plugins, you need to call these methods
on the extended version of the class. To extend a parser with plugins,
you can use its static `extend` method.
```javascript
var acorn = require("acorn");
var jsx = require("acorn-jsx");
var JSXParser = acorn.Parser.extend(jsx());
JSXParser.parse("foo(<bar/>)", {ecmaVersion: 2020});
```
The `extend` method takes any number of plugin values, and returns a
new `Parser` class that includes the extra parser logic provided by
the plugins.
## Command line interface
The `bin/acorn` utility can be used to parse a file from the command
line. It accepts as arguments its input file and the following
options:
- `--ecma3|--ecma5|--ecma6|--ecma7|--ecma8|--ecma9|--ecma10`: Sets the ECMAScript version
to parse. Default is version 9.
- `--module`: Sets the parsing mode to `"module"`. Is set to `"script"` otherwise.
- `--locations`: Attaches a "loc" object to each node with "start" and
"end" subobjects, each of which contains the one-based line and
zero-based column numbers in `{line, column}` form.
- `--allow-hash-bang`: If the code starts with the characters #! (as
in a shellscript), the first line will be treated as a comment.
- `--allow-await-outside-function`: Allows top-level `await` expressions.
See the `allowAwaitOutsideFunction` option for more information.
- `--compact`: No whitespace is used in the AST output.
- `--silent`: Do not output the AST, just return the exit status.
- `--help`: Print the usage information and quit.
The utility spits out the syntax tree as JSON data.
## Existing plugins
- [`acorn-jsx`](https://github.com/RReverser/acorn-jsx): Parse [Facebook JSX syntax extensions](https://github.com/facebook/jsx)

View file

@ -0,0 +1,4 @@
#!/usr/bin/env node
"use strict"
require("../dist/bin.js")

View file

@ -0,0 +1,856 @@
export interface Node {
start: number
end: number
type: string
range?: [number, number]
loc?: SourceLocation | null
}
export interface SourceLocation {
source?: string | null
start: Position
end: Position
}
export interface Position {
/** 1-based */
line: number
/** 0-based */
column: number
}
export interface Identifier extends Node {
type: "Identifier"
name: string
}
export interface Literal extends Node {
type: "Literal"
value?: string | boolean | null | number | RegExp | bigint
raw?: string
regex?: {
pattern: string
flags: string
}
bigint?: string
}
export interface Program extends Node {
type: "Program"
body: Array<Statement | ModuleDeclaration>
sourceType: "script" | "module"
}
export interface Function extends Node {
id?: Identifier | null
params: Array<Pattern>
body: BlockStatement | Expression
generator: boolean
expression: boolean
async: boolean
}
export interface ExpressionStatement extends Node {
type: "ExpressionStatement"
expression: Expression | Literal
directive?: string
}
export interface BlockStatement extends Node {
type: "BlockStatement"
body: Array<Statement>
}
export interface EmptyStatement extends Node {
type: "EmptyStatement"
}
export interface DebuggerStatement extends Node {
type: "DebuggerStatement"
}
export interface WithStatement extends Node {
type: "WithStatement"
object: Expression
body: Statement
}
export interface ReturnStatement extends Node {
type: "ReturnStatement"
argument?: Expression | null
}
export interface LabeledStatement extends Node {
type: "LabeledStatement"
label: Identifier
body: Statement
}
export interface BreakStatement extends Node {
type: "BreakStatement"
label?: Identifier | null
}
export interface ContinueStatement extends Node {
type: "ContinueStatement"
label?: Identifier | null
}
export interface IfStatement extends Node {
type: "IfStatement"
test: Expression
consequent: Statement
alternate?: Statement | null
}
export interface SwitchStatement extends Node {
type: "SwitchStatement"
discriminant: Expression
cases: Array<SwitchCase>
}
export interface SwitchCase extends Node {
type: "SwitchCase"
test?: Expression | null
consequent: Array<Statement>
}
export interface ThrowStatement extends Node {
type: "ThrowStatement"
argument: Expression
}
export interface TryStatement extends Node {
type: "TryStatement"
block: BlockStatement
handler?: CatchClause | null
finalizer?: BlockStatement | null
}
export interface CatchClause extends Node {
type: "CatchClause"
param?: Pattern | null
body: BlockStatement
}
export interface WhileStatement extends Node {
type: "WhileStatement"
test: Expression
body: Statement
}
export interface DoWhileStatement extends Node {
type: "DoWhileStatement"
body: Statement
test: Expression
}
export interface ForStatement extends Node {
type: "ForStatement"
init?: VariableDeclaration | Expression | null
test?: Expression | null
update?: Expression | null
body: Statement
}
export interface ForInStatement extends Node {
type: "ForInStatement"
left: VariableDeclaration | Pattern
right: Expression
body: Statement
}
export interface FunctionDeclaration extends Function {
type: "FunctionDeclaration"
id: Identifier
body: BlockStatement
}
export interface VariableDeclaration extends Node {
type: "VariableDeclaration"
declarations: Array<VariableDeclarator>
kind: "var" | "let" | "const"
}
export interface VariableDeclarator extends Node {
type: "VariableDeclarator"
id: Pattern
init?: Expression | null
}
export interface ThisExpression extends Node {
type: "ThisExpression"
}
export interface ArrayExpression extends Node {
type: "ArrayExpression"
elements: Array<Expression | SpreadElement | null>
}
export interface ObjectExpression extends Node {
type: "ObjectExpression"
properties: Array<Property | SpreadElement>
}
export interface Property extends Node {
type: "Property"
key: Expression
value: Expression
kind: "init" | "get" | "set"
method: boolean
shorthand: boolean
computed: boolean
}
export interface FunctionExpression extends Function {
type: "FunctionExpression"
body: BlockStatement
}
export interface UnaryExpression extends Node {
type: "UnaryExpression"
operator: UnaryOperator
prefix: boolean
argument: Expression
}
export type UnaryOperator = "-" | "+" | "!" | "~" | "typeof" | "void" | "delete"
export interface UpdateExpression extends Node {
type: "UpdateExpression"
operator: UpdateOperator
argument: Expression
prefix: boolean
}
export type UpdateOperator = "++" | "--"
export interface BinaryExpression extends Node {
type: "BinaryExpression"
operator: BinaryOperator
left: Expression | PrivateIdentifier
right: Expression
}
export type BinaryOperator = "==" | "!=" | "===" | "!==" | "<" | "<=" | ">" | ">=" | "<<" | ">>" | ">>>" | "+" | "-" | "*" | "/" | "%" | "|" | "^" | "&" | "in" | "instanceof" | "**"
export interface AssignmentExpression extends Node {
type: "AssignmentExpression"
operator: AssignmentOperator
left: Pattern
right: Expression
}
export type AssignmentOperator = "=" | "+=" | "-=" | "*=" | "/=" | "%=" | "<<=" | ">>=" | ">>>=" | "|=" | "^=" | "&=" | "**=" | "||=" | "&&=" | "??="
export interface LogicalExpression extends Node {
type: "LogicalExpression"
operator: LogicalOperator
left: Expression
right: Expression
}
export type LogicalOperator = "||" | "&&" | "??"
export interface MemberExpression extends Node {
type: "MemberExpression"
object: Expression | Super
property: Expression | PrivateIdentifier
computed: boolean
optional: boolean
}
export interface ConditionalExpression extends Node {
type: "ConditionalExpression"
test: Expression
alternate: Expression
consequent: Expression
}
export interface CallExpression extends Node {
type: "CallExpression"
callee: Expression | Super
arguments: Array<Expression | SpreadElement>
optional: boolean
}
export interface NewExpression extends Node {
type: "NewExpression"
callee: Expression
arguments: Array<Expression | SpreadElement>
}
export interface SequenceExpression extends Node {
type: "SequenceExpression"
expressions: Array<Expression>
}
export interface ForOfStatement extends Node {
type: "ForOfStatement"
left: VariableDeclaration | Pattern
right: Expression
body: Statement
await: boolean
}
export interface Super extends Node {
type: "Super"
}
export interface SpreadElement extends Node {
type: "SpreadElement"
argument: Expression
}
export interface ArrowFunctionExpression extends Function {
type: "ArrowFunctionExpression"
}
export interface YieldExpression extends Node {
type: "YieldExpression"
argument?: Expression | null
delegate: boolean
}
export interface TemplateLiteral extends Node {
type: "TemplateLiteral"
quasis: Array<TemplateElement>
expressions: Array<Expression>
}
export interface TaggedTemplateExpression extends Node {
type: "TaggedTemplateExpression"
tag: Expression
quasi: TemplateLiteral
}
export interface TemplateElement extends Node {
type: "TemplateElement"
tail: boolean
value: {
cooked?: string | null
raw: string
}
}
export interface AssignmentProperty extends Node {
type: "Property"
key: Expression
value: Pattern
kind: "init"
method: false
shorthand: boolean
computed: boolean
}
export interface ObjectPattern extends Node {
type: "ObjectPattern"
properties: Array<AssignmentProperty | RestElement>
}
export interface ArrayPattern extends Node {
type: "ArrayPattern"
elements: Array<Pattern | null>
}
export interface RestElement extends Node {
type: "RestElement"
argument: Pattern
}
export interface AssignmentPattern extends Node {
type: "AssignmentPattern"
left: Pattern
right: Expression
}
export interface Class extends Node {
id?: Identifier | null
superClass?: Expression | null
body: ClassBody
}
export interface ClassBody extends Node {
type: "ClassBody"
body: Array<MethodDefinition | PropertyDefinition | StaticBlock>
}
export interface MethodDefinition extends Node {
type: "MethodDefinition"
key: Expression | PrivateIdentifier
value: FunctionExpression
kind: "constructor" | "method" | "get" | "set"
computed: boolean
static: boolean
}
export interface ClassDeclaration extends Class {
type: "ClassDeclaration"
id: Identifier
}
export interface ClassExpression extends Class {
type: "ClassExpression"
}
export interface MetaProperty extends Node {
type: "MetaProperty"
meta: Identifier
property: Identifier
}
export interface ImportDeclaration extends Node {
type: "ImportDeclaration"
specifiers: Array<ImportSpecifier | ImportDefaultSpecifier | ImportNamespaceSpecifier>
source: Literal
}
export interface ImportSpecifier extends Node {
type: "ImportSpecifier"
imported: Identifier | Literal
local: Identifier
}
export interface ImportDefaultSpecifier extends Node {
type: "ImportDefaultSpecifier"
local: Identifier
}
export interface ImportNamespaceSpecifier extends Node {
type: "ImportNamespaceSpecifier"
local: Identifier
}
export interface ExportNamedDeclaration extends Node {
type: "ExportNamedDeclaration"
declaration?: Declaration | null
specifiers: Array<ExportSpecifier>
source?: Literal | null
}
export interface ExportSpecifier extends Node {
type: "ExportSpecifier"
exported: Identifier | Literal
local: Identifier | Literal
}
export interface AnonymousFunctionDeclaration extends Function {
type: "FunctionDeclaration"
id: null
body: BlockStatement
}
export interface AnonymousClassDeclaration extends Class {
type: "ClassDeclaration"
id: null
}
export interface ExportDefaultDeclaration extends Node {
type: "ExportDefaultDeclaration"
declaration: AnonymousFunctionDeclaration | FunctionDeclaration | AnonymousClassDeclaration | ClassDeclaration | Expression
}
export interface ExportAllDeclaration extends Node {
type: "ExportAllDeclaration"
source: Literal
exported?: Identifier | Literal | null
}
export interface AwaitExpression extends Node {
type: "AwaitExpression"
argument: Expression
}
export interface ChainExpression extends Node {
type: "ChainExpression"
expression: MemberExpression | CallExpression
}
export interface ImportExpression extends Node {
type: "ImportExpression"
source: Expression
}
export interface ParenthesizedExpression extends Node {
type: "ParenthesizedExpression"
expression: Expression
}
export interface PropertyDefinition extends Node {
type: "PropertyDefinition"
key: Expression | PrivateIdentifier
value?: Expression | null
computed: boolean
static: boolean
}
export interface PrivateIdentifier extends Node {
type: "PrivateIdentifier"
name: string
}
export interface StaticBlock extends Node {
type: "StaticBlock"
body: Array<Statement>
}
export type Statement =
| ExpressionStatement
| BlockStatement
| EmptyStatement
| DebuggerStatement
| WithStatement
| ReturnStatement
| LabeledStatement
| BreakStatement
| ContinueStatement
| IfStatement
| SwitchStatement
| ThrowStatement
| TryStatement
| WhileStatement
| DoWhileStatement
| ForStatement
| ForInStatement
| ForOfStatement
| Declaration
export type Declaration =
| FunctionDeclaration
| VariableDeclaration
| ClassDeclaration
export type Expression =
| Identifier
| Literal
| ThisExpression
| ArrayExpression
| ObjectExpression
| FunctionExpression
| UnaryExpression
| UpdateExpression
| BinaryExpression
| AssignmentExpression
| LogicalExpression
| MemberExpression
| ConditionalExpression
| CallExpression
| NewExpression
| SequenceExpression
| ArrowFunctionExpression
| YieldExpression
| TemplateLiteral
| TaggedTemplateExpression
| ClassExpression
| MetaProperty
| AwaitExpression
| ChainExpression
| ImportExpression
| ParenthesizedExpression
export type Pattern =
| Identifier
| MemberExpression
| ObjectPattern
| ArrayPattern
| RestElement
| AssignmentPattern
export type ModuleDeclaration =
| ImportDeclaration
| ExportNamedDeclaration
| ExportDefaultDeclaration
| ExportAllDeclaration
export type AnyNode = Statement | Expression | Declaration | ModuleDeclaration | Literal | Program | SwitchCase | CatchClause | Property | Super | SpreadElement | TemplateElement | AssignmentProperty | ObjectPattern | ArrayPattern | RestElement | AssignmentPattern | ClassBody | MethodDefinition | MetaProperty | ImportSpecifier | ImportDefaultSpecifier | ImportNamespaceSpecifier | ExportSpecifier | AnonymousFunctionDeclaration | AnonymousClassDeclaration | PropertyDefinition | PrivateIdentifier | StaticBlock | VariableDeclarator
export function parse(input: string, options: Options): Program
export function parseExpressionAt(input: string, pos: number, options: Options): Expression
export function tokenizer(input: string, options: Options): {
getToken(): Token
[Symbol.iterator](): Iterator<Token>
}
export type ecmaVersion = 3 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 2015 | 2016 | 2017 | 2018 | 2019 | 2020 | 2021 | 2022 | 2023 | 2024 | 2025 | "latest"
export interface Options {
/**
* `ecmaVersion` indicates the ECMAScript version to parse. Can be a
* number, either in year (`2022`) or plain version number (`6`) form,
* or `"latest"` (the latest the library supports). This influences
* support for strict mode, the set of reserved words, and support for
* new syntax features.
*/
ecmaVersion: ecmaVersion
/**
* `sourceType` indicates the mode the code should be parsed in.
* Can be either `"script"` or `"module"`. This influences global
* strict mode and parsing of `import` and `export` declarations.
*/
sourceType?: "script" | "module"
/**
* a callback that will be called when a semicolon is automatically inserted.
* @param lastTokEnd the position of the comma as an offset
* @param lastTokEndLoc location if {@link locations} is enabled
*/
onInsertedSemicolon?: (lastTokEnd: number, lastTokEndLoc?: Position) => void
/**
* similar to `onInsertedSemicolon`, but for trailing commas
* @param lastTokEnd the position of the comma as an offset
* @param lastTokEndLoc location if `locations` is enabled
*/
onTrailingComma?: (lastTokEnd: number, lastTokEndLoc?: Position) => void
/**
* By default, reserved words are only enforced if ecmaVersion >= 5.
* Set `allowReserved` to a boolean value to explicitly turn this on
* an off. When this option has the value "never", reserved words
* and keywords can also not be used as property names.
*/
allowReserved?: boolean | "never"
/**
* When enabled, a return at the top level is not considered an error.
*/
allowReturnOutsideFunction?: boolean
/**
* When enabled, import/export statements are not constrained to
* appearing at the top of the program, and an import.meta expression
* in a script isn't considered an error.
*/
allowImportExportEverywhere?: boolean
/**
* By default, `await` identifiers are allowed to appear at the top-level scope only if {@link ecmaVersion} >= 2022.
* When enabled, await identifiers are allowed to appear at the top-level scope,
* but they are still not allowed in non-async functions.
*/
allowAwaitOutsideFunction?: boolean
/**
* When enabled, super identifiers are not constrained to
* appearing in methods and do not raise an error when they appear elsewhere.
*/
allowSuperOutsideMethod?: boolean
/**
* When enabled, hashbang directive in the beginning of file is
* allowed and treated as a line comment. Enabled by default when
* {@link ecmaVersion} >= 2023.
*/
allowHashBang?: boolean
/**
* By default, the parser will verify that private properties are
* only used in places where they are valid and have been declared.
* Set this to false to turn such checks off.
*/
checkPrivateFields?: boolean
/**
* When `locations` is on, `loc` properties holding objects with
* `start` and `end` properties as {@link Position} objects will be attached to the
* nodes.
*/
locations?: boolean
/**
* a callback that will cause Acorn to call that export function with object in the same
* format as tokens returned from `tokenizer().getToken()`. Note
* that you are not allowed to call the parser from the
* callbackthat will corrupt its internal state.
*/
onToken?: ((token: Token) => void) | Token[]
/**
* This takes a export function or an array.
*
* When a export function is passed, Acorn will call that export function with `(block, text, start,
* end)` parameters whenever a comment is skipped. `block` is a
* boolean indicating whether this is a block (`/* *\/`) comment,
* `text` is the content of the comment, and `start` and `end` are
* character offsets that denote the start and end of the comment.
* When the {@link locations} option is on, two more parameters are
* passed, the full locations of {@link Position} export type of the start and
* end of the comments.
*
* When a array is passed, each found comment of {@link Comment} export type is pushed to the array.
*
* Note that you are not allowed to call the
* parser from the callbackthat will corrupt its internal state.
*/
onComment?: ((
isBlock: boolean, text: string, start: number, end: number, startLoc?: Position,
endLoc?: Position
) => void) | Comment[]
/**
* Nodes have their start and end characters offsets recorded in
* `start` and `end` properties (directly on the node, rather than
* the `loc` object, which holds line/column data. To also add a
* [semi-standardized][range] `range` property holding a `[start,
* end]` array with the same numbers, set the `ranges` option to
* `true`.
*/
ranges?: boolean
/**
* It is possible to parse multiple files into a single AST by
* passing the tree produced by parsing the first file as
* `program` option in subsequent parses. This will add the
* toplevel forms of the parsed file to the `Program` (top) node
* of an existing parse tree.
*/
program?: Node
/**
* When {@link locations} is on, you can pass this to record the source
* file in every node's `loc` object.
*/
sourceFile?: string
/**
* This value, if given, is stored in every node, whether {@link locations} is on or off.
*/
directSourceFile?: string
/**
* When enabled, parenthesized expressions are represented by
* (non-standard) ParenthesizedExpression nodes
*/
preserveParens?: boolean
}
export class Parser {
options: Options
input: string
protected constructor(options: Options, input: string, startPos?: number)
parse(): Program
static parse(input: string, options: Options): Program
static parseExpressionAt(input: string, pos: number, options: Options): Expression
static tokenizer(input: string, options: Options): {
getToken(): Token
[Symbol.iterator](): Iterator<Token>
}
static extend(...plugins: ((BaseParser: typeof Parser) => typeof Parser)[]): typeof Parser
}
export const defaultOptions: Options
export function getLineInfo(input: string, offset: number): Position
export class TokenType {
label: string
keyword: string | undefined
}
export const tokTypes: {
num: TokenType
regexp: TokenType
string: TokenType
name: TokenType
privateId: TokenType
eof: TokenType
bracketL: TokenType
bracketR: TokenType
braceL: TokenType
braceR: TokenType
parenL: TokenType
parenR: TokenType
comma: TokenType
semi: TokenType
colon: TokenType
dot: TokenType
question: TokenType
questionDot: TokenType
arrow: TokenType
template: TokenType
invalidTemplate: TokenType
ellipsis: TokenType
backQuote: TokenType
dollarBraceL: TokenType
eq: TokenType
assign: TokenType
incDec: TokenType
prefix: TokenType
logicalOR: TokenType
logicalAND: TokenType
bitwiseOR: TokenType
bitwiseXOR: TokenType
bitwiseAND: TokenType
equality: TokenType
relational: TokenType
bitShift: TokenType
plusMin: TokenType
modulo: TokenType
star: TokenType
slash: TokenType
starstar: TokenType
coalesce: TokenType
_break: TokenType
_case: TokenType
_catch: TokenType
_continue: TokenType
_debugger: TokenType
_default: TokenType
_do: TokenType
_else: TokenType
_finally: TokenType
_for: TokenType
_function: TokenType
_if: TokenType
_return: TokenType
_switch: TokenType
_throw: TokenType
_try: TokenType
_var: TokenType
_const: TokenType
_while: TokenType
_with: TokenType
_new: TokenType
_this: TokenType
_super: TokenType
_class: TokenType
_extends: TokenType
_export: TokenType
_import: TokenType
_null: TokenType
_true: TokenType
_false: TokenType
_in: TokenType
_instanceof: TokenType
_typeof: TokenType
_void: TokenType
_delete: TokenType
}
export interface Comment {
type: "Line" | "Block"
value: string
start: number
end: number
loc?: SourceLocation
range?: [number, number]
}
export class Token {
type: TokenType
start: number
end: number
loc?: SourceLocation
range?: [number, number]
}
export const version: string

View file

@ -0,0 +1,856 @@
export interface Node {
start: number
end: number
type: string
range?: [number, number]
loc?: SourceLocation | null
}
export interface SourceLocation {
source?: string | null
start: Position
end: Position
}
export interface Position {
/** 1-based */
line: number
/** 0-based */
column: number
}
export interface Identifier extends Node {
type: "Identifier"
name: string
}
export interface Literal extends Node {
type: "Literal"
value?: string | boolean | null | number | RegExp | bigint
raw?: string
regex?: {
pattern: string
flags: string
}
bigint?: string
}
export interface Program extends Node {
type: "Program"
body: Array<Statement | ModuleDeclaration>
sourceType: "script" | "module"
}
export interface Function extends Node {
id?: Identifier | null
params: Array<Pattern>
body: BlockStatement | Expression
generator: boolean
expression: boolean
async: boolean
}
export interface ExpressionStatement extends Node {
type: "ExpressionStatement"
expression: Expression | Literal
directive?: string
}
export interface BlockStatement extends Node {
type: "BlockStatement"
body: Array<Statement>
}
export interface EmptyStatement extends Node {
type: "EmptyStatement"
}
export interface DebuggerStatement extends Node {
type: "DebuggerStatement"
}
export interface WithStatement extends Node {
type: "WithStatement"
object: Expression
body: Statement
}
export interface ReturnStatement extends Node {
type: "ReturnStatement"
argument?: Expression | null
}
export interface LabeledStatement extends Node {
type: "LabeledStatement"
label: Identifier
body: Statement
}
export interface BreakStatement extends Node {
type: "BreakStatement"
label?: Identifier | null
}
export interface ContinueStatement extends Node {
type: "ContinueStatement"
label?: Identifier | null
}
export interface IfStatement extends Node {
type: "IfStatement"
test: Expression
consequent: Statement
alternate?: Statement | null
}
export interface SwitchStatement extends Node {
type: "SwitchStatement"
discriminant: Expression
cases: Array<SwitchCase>
}
export interface SwitchCase extends Node {
type: "SwitchCase"
test?: Expression | null
consequent: Array<Statement>
}
export interface ThrowStatement extends Node {
type: "ThrowStatement"
argument: Expression
}
export interface TryStatement extends Node {
type: "TryStatement"
block: BlockStatement
handler?: CatchClause | null
finalizer?: BlockStatement | null
}
export interface CatchClause extends Node {
type: "CatchClause"
param?: Pattern | null
body: BlockStatement
}
export interface WhileStatement extends Node {
type: "WhileStatement"
test: Expression
body: Statement
}
export interface DoWhileStatement extends Node {
type: "DoWhileStatement"
body: Statement
test: Expression
}
export interface ForStatement extends Node {
type: "ForStatement"
init?: VariableDeclaration | Expression | null
test?: Expression | null
update?: Expression | null
body: Statement
}
export interface ForInStatement extends Node {
type: "ForInStatement"
left: VariableDeclaration | Pattern
right: Expression
body: Statement
}
export interface FunctionDeclaration extends Function {
type: "FunctionDeclaration"
id: Identifier
body: BlockStatement
}
export interface VariableDeclaration extends Node {
type: "VariableDeclaration"
declarations: Array<VariableDeclarator>
kind: "var" | "let" | "const"
}
export interface VariableDeclarator extends Node {
type: "VariableDeclarator"
id: Pattern
init?: Expression | null
}
export interface ThisExpression extends Node {
type: "ThisExpression"
}
export interface ArrayExpression extends Node {
type: "ArrayExpression"
elements: Array<Expression | SpreadElement | null>
}
export interface ObjectExpression extends Node {
type: "ObjectExpression"
properties: Array<Property | SpreadElement>
}
export interface Property extends Node {
type: "Property"
key: Expression
value: Expression
kind: "init" | "get" | "set"
method: boolean
shorthand: boolean
computed: boolean
}
export interface FunctionExpression extends Function {
type: "FunctionExpression"
body: BlockStatement
}
export interface UnaryExpression extends Node {
type: "UnaryExpression"
operator: UnaryOperator
prefix: boolean
argument: Expression
}
export type UnaryOperator = "-" | "+" | "!" | "~" | "typeof" | "void" | "delete"
export interface UpdateExpression extends Node {
type: "UpdateExpression"
operator: UpdateOperator
argument: Expression
prefix: boolean
}
export type UpdateOperator = "++" | "--"
export interface BinaryExpression extends Node {
type: "BinaryExpression"
operator: BinaryOperator
left: Expression | PrivateIdentifier
right: Expression
}
export type BinaryOperator = "==" | "!=" | "===" | "!==" | "<" | "<=" | ">" | ">=" | "<<" | ">>" | ">>>" | "+" | "-" | "*" | "/" | "%" | "|" | "^" | "&" | "in" | "instanceof" | "**"
export interface AssignmentExpression extends Node {
type: "AssignmentExpression"
operator: AssignmentOperator
left: Pattern
right: Expression
}
export type AssignmentOperator = "=" | "+=" | "-=" | "*=" | "/=" | "%=" | "<<=" | ">>=" | ">>>=" | "|=" | "^=" | "&=" | "**=" | "||=" | "&&=" | "??="
export interface LogicalExpression extends Node {
type: "LogicalExpression"
operator: LogicalOperator
left: Expression
right: Expression
}
export type LogicalOperator = "||" | "&&" | "??"
export interface MemberExpression extends Node {
type: "MemberExpression"
object: Expression | Super
property: Expression | PrivateIdentifier
computed: boolean
optional: boolean
}
export interface ConditionalExpression extends Node {
type: "ConditionalExpression"
test: Expression
alternate: Expression
consequent: Expression
}
export interface CallExpression extends Node {
type: "CallExpression"
callee: Expression | Super
arguments: Array<Expression | SpreadElement>
optional: boolean
}
export interface NewExpression extends Node {
type: "NewExpression"
callee: Expression
arguments: Array<Expression | SpreadElement>
}
export interface SequenceExpression extends Node {
type: "SequenceExpression"
expressions: Array<Expression>
}
export interface ForOfStatement extends Node {
type: "ForOfStatement"
left: VariableDeclaration | Pattern
right: Expression
body: Statement
await: boolean
}
export interface Super extends Node {
type: "Super"
}
export interface SpreadElement extends Node {
type: "SpreadElement"
argument: Expression
}
export interface ArrowFunctionExpression extends Function {
type: "ArrowFunctionExpression"
}
export interface YieldExpression extends Node {
type: "YieldExpression"
argument?: Expression | null
delegate: boolean
}
export interface TemplateLiteral extends Node {
type: "TemplateLiteral"
quasis: Array<TemplateElement>
expressions: Array<Expression>
}
export interface TaggedTemplateExpression extends Node {
type: "TaggedTemplateExpression"
tag: Expression
quasi: TemplateLiteral
}
export interface TemplateElement extends Node {
type: "TemplateElement"
tail: boolean
value: {
cooked?: string | null
raw: string
}
}
export interface AssignmentProperty extends Node {
type: "Property"
key: Expression
value: Pattern
kind: "init"
method: false
shorthand: boolean
computed: boolean
}
export interface ObjectPattern extends Node {
type: "ObjectPattern"
properties: Array<AssignmentProperty | RestElement>
}
export interface ArrayPattern extends Node {
type: "ArrayPattern"
elements: Array<Pattern | null>
}
export interface RestElement extends Node {
type: "RestElement"
argument: Pattern
}
export interface AssignmentPattern extends Node {
type: "AssignmentPattern"
left: Pattern
right: Expression
}
export interface Class extends Node {
id?: Identifier | null
superClass?: Expression | null
body: ClassBody
}
export interface ClassBody extends Node {
type: "ClassBody"
body: Array<MethodDefinition | PropertyDefinition | StaticBlock>
}
export interface MethodDefinition extends Node {
type: "MethodDefinition"
key: Expression | PrivateIdentifier
value: FunctionExpression
kind: "constructor" | "method" | "get" | "set"
computed: boolean
static: boolean
}
export interface ClassDeclaration extends Class {
type: "ClassDeclaration"
id: Identifier
}
export interface ClassExpression extends Class {
type: "ClassExpression"
}
export interface MetaProperty extends Node {
type: "MetaProperty"
meta: Identifier
property: Identifier
}
export interface ImportDeclaration extends Node {
type: "ImportDeclaration"
specifiers: Array<ImportSpecifier | ImportDefaultSpecifier | ImportNamespaceSpecifier>
source: Literal
}
export interface ImportSpecifier extends Node {
type: "ImportSpecifier"
imported: Identifier | Literal
local: Identifier
}
export interface ImportDefaultSpecifier extends Node {
type: "ImportDefaultSpecifier"
local: Identifier
}
export interface ImportNamespaceSpecifier extends Node {
type: "ImportNamespaceSpecifier"
local: Identifier
}
export interface ExportNamedDeclaration extends Node {
type: "ExportNamedDeclaration"
declaration?: Declaration | null
specifiers: Array<ExportSpecifier>
source?: Literal | null
}
export interface ExportSpecifier extends Node {
type: "ExportSpecifier"
exported: Identifier | Literal
local: Identifier | Literal
}
export interface AnonymousFunctionDeclaration extends Function {
type: "FunctionDeclaration"
id: null
body: BlockStatement
}
export interface AnonymousClassDeclaration extends Class {
type: "ClassDeclaration"
id: null
}
export interface ExportDefaultDeclaration extends Node {
type: "ExportDefaultDeclaration"
declaration: AnonymousFunctionDeclaration | FunctionDeclaration | AnonymousClassDeclaration | ClassDeclaration | Expression
}
export interface ExportAllDeclaration extends Node {
type: "ExportAllDeclaration"
source: Literal
exported?: Identifier | Literal | null
}
export interface AwaitExpression extends Node {
type: "AwaitExpression"
argument: Expression
}
export interface ChainExpression extends Node {
type: "ChainExpression"
expression: MemberExpression | CallExpression
}
export interface ImportExpression extends Node {
type: "ImportExpression"
source: Expression
}
export interface ParenthesizedExpression extends Node {
type: "ParenthesizedExpression"
expression: Expression
}
export interface PropertyDefinition extends Node {
type: "PropertyDefinition"
key: Expression | PrivateIdentifier
value?: Expression | null
computed: boolean
static: boolean
}
export interface PrivateIdentifier extends Node {
type: "PrivateIdentifier"
name: string
}
export interface StaticBlock extends Node {
type: "StaticBlock"
body: Array<Statement>
}
export type Statement =
| ExpressionStatement
| BlockStatement
| EmptyStatement
| DebuggerStatement
| WithStatement
| ReturnStatement
| LabeledStatement
| BreakStatement
| ContinueStatement
| IfStatement
| SwitchStatement
| ThrowStatement
| TryStatement
| WhileStatement
| DoWhileStatement
| ForStatement
| ForInStatement
| ForOfStatement
| Declaration
export type Declaration =
| FunctionDeclaration
| VariableDeclaration
| ClassDeclaration
export type Expression =
| Identifier
| Literal
| ThisExpression
| ArrayExpression
| ObjectExpression
| FunctionExpression
| UnaryExpression
| UpdateExpression
| BinaryExpression
| AssignmentExpression
| LogicalExpression
| MemberExpression
| ConditionalExpression
| CallExpression
| NewExpression
| SequenceExpression
| ArrowFunctionExpression
| YieldExpression
| TemplateLiteral
| TaggedTemplateExpression
| ClassExpression
| MetaProperty
| AwaitExpression
| ChainExpression
| ImportExpression
| ParenthesizedExpression
export type Pattern =
| Identifier
| MemberExpression
| ObjectPattern
| ArrayPattern
| RestElement
| AssignmentPattern
export type ModuleDeclaration =
| ImportDeclaration
| ExportNamedDeclaration
| ExportDefaultDeclaration
| ExportAllDeclaration
export type AnyNode = Statement | Expression | Declaration | ModuleDeclaration | Literal | Program | SwitchCase | CatchClause | Property | Super | SpreadElement | TemplateElement | AssignmentProperty | ObjectPattern | ArrayPattern | RestElement | AssignmentPattern | ClassBody | MethodDefinition | MetaProperty | ImportSpecifier | ImportDefaultSpecifier | ImportNamespaceSpecifier | ExportSpecifier | AnonymousFunctionDeclaration | AnonymousClassDeclaration | PropertyDefinition | PrivateIdentifier | StaticBlock | VariableDeclarator
export function parse(input: string, options: Options): Program
export function parseExpressionAt(input: string, pos: number, options: Options): Expression
export function tokenizer(input: string, options: Options): {
getToken(): Token
[Symbol.iterator](): Iterator<Token>
}
export type ecmaVersion = 3 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 2015 | 2016 | 2017 | 2018 | 2019 | 2020 | 2021 | 2022 | 2023 | 2024 | 2025 | "latest"
export interface Options {
/**
* `ecmaVersion` indicates the ECMAScript version to parse. Can be a
* number, either in year (`2022`) or plain version number (`6`) form,
* or `"latest"` (the latest the library supports). This influences
* support for strict mode, the set of reserved words, and support for
* new syntax features.
*/
ecmaVersion: ecmaVersion
/**
* `sourceType` indicates the mode the code should be parsed in.
* Can be either `"script"` or `"module"`. This influences global
* strict mode and parsing of `import` and `export` declarations.
*/
sourceType?: "script" | "module"
/**
* a callback that will be called when a semicolon is automatically inserted.
* @param lastTokEnd the position of the comma as an offset
* @param lastTokEndLoc location if {@link locations} is enabled
*/
onInsertedSemicolon?: (lastTokEnd: number, lastTokEndLoc?: Position) => void
/**
* similar to `onInsertedSemicolon`, but for trailing commas
* @param lastTokEnd the position of the comma as an offset
* @param lastTokEndLoc location if `locations` is enabled
*/
onTrailingComma?: (lastTokEnd: number, lastTokEndLoc?: Position) => void
/**
* By default, reserved words are only enforced if ecmaVersion >= 5.
* Set `allowReserved` to a boolean value to explicitly turn this on
* an off. When this option has the value "never", reserved words
* and keywords can also not be used as property names.
*/
allowReserved?: boolean | "never"
/**
* When enabled, a return at the top level is not considered an error.
*/
allowReturnOutsideFunction?: boolean
/**
* When enabled, import/export statements are not constrained to
* appearing at the top of the program, and an import.meta expression
* in a script isn't considered an error.
*/
allowImportExportEverywhere?: boolean
/**
* By default, `await` identifiers are allowed to appear at the top-level scope only if {@link ecmaVersion} >= 2022.
* When enabled, await identifiers are allowed to appear at the top-level scope,
* but they are still not allowed in non-async functions.
*/
allowAwaitOutsideFunction?: boolean
/**
* When enabled, super identifiers are not constrained to
* appearing in methods and do not raise an error when they appear elsewhere.
*/
allowSuperOutsideMethod?: boolean
/**
* When enabled, hashbang directive in the beginning of file is
* allowed and treated as a line comment. Enabled by default when
* {@link ecmaVersion} >= 2023.
*/
allowHashBang?: boolean
/**
* By default, the parser will verify that private properties are
* only used in places where they are valid and have been declared.
* Set this to false to turn such checks off.
*/
checkPrivateFields?: boolean
/**
* When `locations` is on, `loc` properties holding objects with
* `start` and `end` properties as {@link Position} objects will be attached to the
* nodes.
*/
locations?: boolean
/**
* a callback that will cause Acorn to call that export function with object in the same
* format as tokens returned from `tokenizer().getToken()`. Note
* that you are not allowed to call the parser from the
* callbackthat will corrupt its internal state.
*/
onToken?: ((token: Token) => void) | Token[]
/**
* This takes a export function or an array.
*
* When a export function is passed, Acorn will call that export function with `(block, text, start,
* end)` parameters whenever a comment is skipped. `block` is a
* boolean indicating whether this is a block (`/* *\/`) comment,
* `text` is the content of the comment, and `start` and `end` are
* character offsets that denote the start and end of the comment.
* When the {@link locations} option is on, two more parameters are
* passed, the full locations of {@link Position} export type of the start and
* end of the comments.
*
* When a array is passed, each found comment of {@link Comment} export type is pushed to the array.
*
* Note that you are not allowed to call the
* parser from the callbackthat will corrupt its internal state.
*/
onComment?: ((
isBlock: boolean, text: string, start: number, end: number, startLoc?: Position,
endLoc?: Position
) => void) | Comment[]
/**
* Nodes have their start and end characters offsets recorded in
* `start` and `end` properties (directly on the node, rather than
* the `loc` object, which holds line/column data. To also add a
* [semi-standardized][range] `range` property holding a `[start,
* end]` array with the same numbers, set the `ranges` option to
* `true`.
*/
ranges?: boolean
/**
* It is possible to parse multiple files into a single AST by
* passing the tree produced by parsing the first file as
* `program` option in subsequent parses. This will add the
* toplevel forms of the parsed file to the `Program` (top) node
* of an existing parse tree.
*/
program?: Node
/**
* When {@link locations} is on, you can pass this to record the source
* file in every node's `loc` object.
*/
sourceFile?: string
/**
* This value, if given, is stored in every node, whether {@link locations} is on or off.
*/
directSourceFile?: string
/**
* When enabled, parenthesized expressions are represented by
* (non-standard) ParenthesizedExpression nodes
*/
preserveParens?: boolean
}
export class Parser {
options: Options
input: string
protected constructor(options: Options, input: string, startPos?: number)
parse(): Program
static parse(input: string, options: Options): Program
static parseExpressionAt(input: string, pos: number, options: Options): Expression
static tokenizer(input: string, options: Options): {
getToken(): Token
[Symbol.iterator](): Iterator<Token>
}
static extend(...plugins: ((BaseParser: typeof Parser) => typeof Parser)[]): typeof Parser
}
export const defaultOptions: Options
export function getLineInfo(input: string, offset: number): Position
export class TokenType {
label: string
keyword: string | undefined
}
export const tokTypes: {
num: TokenType
regexp: TokenType
string: TokenType
name: TokenType
privateId: TokenType
eof: TokenType
bracketL: TokenType
bracketR: TokenType
braceL: TokenType
braceR: TokenType
parenL: TokenType
parenR: TokenType
comma: TokenType
semi: TokenType
colon: TokenType
dot: TokenType
question: TokenType
questionDot: TokenType
arrow: TokenType
template: TokenType
invalidTemplate: TokenType
ellipsis: TokenType
backQuote: TokenType
dollarBraceL: TokenType
eq: TokenType
assign: TokenType
incDec: TokenType
prefix: TokenType
logicalOR: TokenType
logicalAND: TokenType
bitwiseOR: TokenType
bitwiseXOR: TokenType
bitwiseAND: TokenType
equality: TokenType
relational: TokenType
bitShift: TokenType
plusMin: TokenType
modulo: TokenType
star: TokenType
slash: TokenType
starstar: TokenType
coalesce: TokenType
_break: TokenType
_case: TokenType
_catch: TokenType
_continue: TokenType
_debugger: TokenType
_default: TokenType
_do: TokenType
_else: TokenType
_finally: TokenType
_for: TokenType
_function: TokenType
_if: TokenType
_return: TokenType
_switch: TokenType
_throw: TokenType
_try: TokenType
_var: TokenType
_const: TokenType
_while: TokenType
_with: TokenType
_new: TokenType
_this: TokenType
_super: TokenType
_class: TokenType
_extends: TokenType
_export: TokenType
_import: TokenType
_null: TokenType
_true: TokenType
_false: TokenType
_in: TokenType
_instanceof: TokenType
_typeof: TokenType
_void: TokenType
_delete: TokenType
}
export interface Comment {
type: "Line" | "Block"
value: string
start: number
end: number
loc?: SourceLocation
range?: [number, number]
}
export class Token {
type: TokenType
start: number
end: number
loc?: SourceLocation
range?: [number, number]
}
export const version: string

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,90 @@
'use strict';
var path = require('path');
var fs = require('fs');
var acorn = require('./acorn.js');
function _interopNamespaceDefault(e) {
var n = Object.create(null);
if (e) {
Object.keys(e).forEach(function (k) {
if (k !== 'default') {
var d = Object.getOwnPropertyDescriptor(e, k);
Object.defineProperty(n, k, d.get ? d : {
enumerable: true,
get: function () { return e[k]; }
});
}
});
}
n.default = e;
return Object.freeze(n);
}
var acorn__namespace = /*#__PURE__*/_interopNamespaceDefault(acorn);
var inputFilePaths = [], forceFileName = false, fileMode = false, silent = false, compact = false, tokenize = false;
var options = {};
function help(status) {
var print = (status === 0) ? console.log : console.error;
print("usage: " + path.basename(process.argv[1]) + " [--ecma3|--ecma5|--ecma6|--ecma7|--ecma8|--ecma9|...|--ecma2015|--ecma2016|--ecma2017|--ecma2018|...]");
print(" [--tokenize] [--locations] [--allow-hash-bang] [--allow-await-outside-function] [--compact] [--silent] [--module] [--help] [--] [<infile>...]");
process.exit(status);
}
for (var i = 2; i < process.argv.length; ++i) {
var arg = process.argv[i];
if (arg[0] !== "-" || arg === "-") { inputFilePaths.push(arg); }
else if (arg === "--") {
inputFilePaths.push.apply(inputFilePaths, process.argv.slice(i + 1));
forceFileName = true;
break
} else if (arg === "--locations") { options.locations = true; }
else if (arg === "--allow-hash-bang") { options.allowHashBang = true; }
else if (arg === "--allow-await-outside-function") { options.allowAwaitOutsideFunction = true; }
else if (arg === "--silent") { silent = true; }
else if (arg === "--compact") { compact = true; }
else if (arg === "--help") { help(0); }
else if (arg === "--tokenize") { tokenize = true; }
else if (arg === "--module") { options.sourceType = "module"; }
else {
var match = arg.match(/^--ecma(\d+)$/);
if (match)
{ options.ecmaVersion = +match[1]; }
else
{ help(1); }
}
}
function run(codeList) {
var result = [], fileIdx = 0;
try {
codeList.forEach(function (code, idx) {
fileIdx = idx;
if (!tokenize) {
result = acorn__namespace.parse(code, options);
options.program = result;
} else {
var tokenizer = acorn__namespace.tokenizer(code, options), token;
do {
token = tokenizer.getToken();
result.push(token);
} while (token.type !== acorn__namespace.tokTypes.eof)
}
});
} catch (e) {
console.error(fileMode ? e.message.replace(/\(\d+:\d+\)$/, function (m) { return m.slice(0, 1) + inputFilePaths[fileIdx] + " " + m.slice(1); }) : e.message);
process.exit(1);
}
if (!silent) { console.log(JSON.stringify(result, null, compact ? null : 2)); }
}
if (fileMode = inputFilePaths.length && (forceFileName || !inputFilePaths.includes("-") || inputFilePaths.length !== 1)) {
run(inputFilePaths.map(function (path) { return fs.readFileSync(path, "utf8"); }));
} else {
var code = "";
process.stdin.resume();
process.stdin.on("data", function (chunk) { return code += chunk; });
process.stdin.on("end", function () { return run([code]); });
}

View file

@ -0,0 +1,50 @@
{
"name": "acorn",
"description": "ECMAScript parser",
"homepage": "https://github.com/acornjs/acorn",
"main": "dist/acorn.js",
"types": "dist/acorn.d.ts",
"module": "dist/acorn.mjs",
"exports": {
".": [
{
"import": "./dist/acorn.mjs",
"require": "./dist/acorn.js",
"default": "./dist/acorn.js"
},
"./dist/acorn.js"
],
"./package.json": "./package.json"
},
"version": "8.12.1",
"engines": {
"node": ">=0.4.0"
},
"maintainers": [
{
"name": "Marijn Haverbeke",
"email": "marijnh@gmail.com",
"web": "https://marijnhaverbeke.nl"
},
{
"name": "Ingvar Stepanyan",
"email": "me@rreverser.com",
"web": "https://rreverser.com/"
},
{
"name": "Adrian Heine",
"web": "http://adrianheine.de"
}
],
"repository": {
"type": "git",
"url": "git+https://github.com/acornjs/acorn.git"
},
"license": "MIT",
"scripts": {
"prepare": "cd ..; npm run build:main"
},
"bin": {
"acorn": "bin/acorn"
}
}

View file

@ -0,0 +1,11 @@
License
(The MIT License)
Copyright (c) 2014 The cheeriojs contributors
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.

View file

@ -0,0 +1,97 @@
# dom-serializer [![Build Status](https://travis-ci.com/cheeriojs/dom-serializer.svg?branch=master)](https://travis-ci.com/cheeriojs/dom-serializer)
Renders a [domhandler](https://github.com/fb55/domhandler) DOM node or an array of domhandler DOM nodes to a string.
```js
import render from "dom-serializer";
// OR
const render = require("dom-serializer").default;
```
# API
## `render`
**render**(`node`: Node \| Node[], `options?`: [_Options_](#Options)): _string_
Renders a DOM node or an array of DOM nodes to a string.
Can be thought of as the equivalent of the `outerHTML` of the passed node(s).
#### Parameters:
| Name | Type | Default value | Description |
| :-------- | :--------------------------------- | :------------ | :----------------------------- |
| `node` | Node \| Node[] | - | Node to be rendered. |
| `options` | [_DomSerializerOptions_](#Options) | {} | Changes serialization behavior |
**Returns:** _string_
## Options
### `decodeEntities`
`Optional` **decodeEntities**: _boolean_
Encode characters that are either reserved in HTML or XML, or are outside of the ASCII range.
**`default`** true
---
### `emptyAttrs`
`Optional` **emptyAttrs**: _boolean_
Print an empty attribute's value.
**`default`** xmlMode
**`example`** With <code>emptyAttrs: false</code>: <code>&lt;input checked&gt;</code>
**`example`** With <code>emptyAttrs: true</code>: <code>&lt;input checked=""&gt;</code>
---
### `selfClosingTags`
`Optional` **selfClosingTags**: _boolean_
Print self-closing tags for tags without contents.
**`default`** xmlMode
**`example`** With <code>selfClosingTags: false</code>: <code>&lt;foo&gt;&lt;/foo&gt;</code>
**`example`** With <code>selfClosingTags: true</code>: <code>&lt;foo /&gt;</code>
---
### `xmlMode`
`Optional` **xmlMode**: _boolean_ \| _"foreign"_
Treat the input as an XML document; enables the `emptyAttrs` and `selfClosingTags` options.
If the value is `"foreign"`, it will try to correct mixed-case attribute names.
**`default`** false
---
## Ecosystem
| Name | Description |
| ------------------------------------------------------------- | ------------------------------------------------------- |
| [htmlparser2](https://github.com/fb55/htmlparser2) | Fast & forgiving HTML/XML parser |
| [domhandler](https://github.com/fb55/domhandler) | Handler for htmlparser2 that turns documents into a DOM |
| [domutils](https://github.com/fb55/domutils) | Utilities for working with domhandler's DOM |
| [css-select](https://github.com/fb55/css-select) | CSS selector engine, compatible with domhandler's DOM |
| [cheerio](https://github.com/cheeriojs/cheerio) | The jQuery API for domhandler's DOM |
| [dom-serializer](https://github.com/cheeriojs/dom-serializer) | Serializer for domhandler's DOM |
---
LICENSE: MIT

View file

@ -0,0 +1,3 @@
export declare const elementNames: Map<string, string>;
export declare const attributeNames: Map<string, string>;
//# sourceMappingURL=foreignNames.d.ts.map

View file

@ -0,0 +1 @@
{"version":3,"file":"foreignNames.d.ts","sourceRoot":"","sources":["../../src/foreignNames.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,YAAY,qBAwCxB,CAAC;AACF,eAAO,MAAM,cAAc,qBA8D1B,CAAC"}

View file

@ -0,0 +1,100 @@
export const elementNames = new Map([
"altGlyph",
"altGlyphDef",
"altGlyphItem",
"animateColor",
"animateMotion",
"animateTransform",
"clipPath",
"feBlend",
"feColorMatrix",
"feComponentTransfer",
"feComposite",
"feConvolveMatrix",
"feDiffuseLighting",
"feDisplacementMap",
"feDistantLight",
"feDropShadow",
"feFlood",
"feFuncA",
"feFuncB",
"feFuncG",
"feFuncR",
"feGaussianBlur",
"feImage",
"feMerge",
"feMergeNode",
"feMorphology",
"feOffset",
"fePointLight",
"feSpecularLighting",
"feSpotLight",
"feTile",
"feTurbulence",
"foreignObject",
"glyphRef",
"linearGradient",
"radialGradient",
"textPath",
].map((val) => [val.toLowerCase(), val]));
export const attributeNames = new Map([
"definitionURL",
"attributeName",
"attributeType",
"baseFrequency",
"baseProfile",
"calcMode",
"clipPathUnits",
"diffuseConstant",
"edgeMode",
"filterUnits",
"glyphRef",
"gradientTransform",
"gradientUnits",
"kernelMatrix",
"kernelUnitLength",
"keyPoints",
"keySplines",
"keyTimes",
"lengthAdjust",
"limitingConeAngle",
"markerHeight",
"markerUnits",
"markerWidth",
"maskContentUnits",
"maskUnits",
"numOctaves",
"pathLength",
"patternContentUnits",
"patternTransform",
"patternUnits",
"pointsAtX",
"pointsAtY",
"pointsAtZ",
"preserveAlpha",
"preserveAspectRatio",
"primitiveUnits",
"refX",
"refY",
"repeatCount",
"repeatDur",
"requiredExtensions",
"requiredFeatures",
"specularConstant",
"specularExponent",
"spreadMethod",
"startOffset",
"stdDeviation",
"stitchTiles",
"surfaceScale",
"systemLanguage",
"tableValues",
"targetX",
"targetY",
"textLength",
"viewBox",
"viewTarget",
"xChannelSelector",
"yChannelSelector",
"zoomAndPan",
].map((val) => [val.toLowerCase(), val]));

View file

@ -0,0 +1,52 @@
import type { AnyNode } from "domhandler";
export interface DomSerializerOptions {
/**
* Print an empty attribute's value.
*
* @default xmlMode
* @example With <code>emptyAttrs: false</code>: <code>&lt;input checked&gt;</code>
* @example With <code>emptyAttrs: true</code>: <code>&lt;input checked=""&gt;</code>
*/
emptyAttrs?: boolean;
/**
* Print self-closing tags for tags without contents.
*
* @default xmlMode
* @example With <code>selfClosingTags: false</code>: <code>&lt;foo&gt;&lt;/foo&gt;</code>
* @example With <code>selfClosingTags: true</code>: <code>&lt;foo /&gt;</code>
*/
selfClosingTags?: boolean;
/**
* Treat the input as an XML document; enables the `emptyAttrs` and `selfClosingTags` options.
*
* If the value is `"foreign"`, it will try to correct mixed-case attribute names.
*
* @default false
*/
xmlMode?: boolean | "foreign";
/**
* Encode characters that are either reserved in HTML or XML.
*
* If `xmlMode` is `true` or the value not `'utf8'`, characters outside of the utf8 range will be encoded as well.
*
* @default `decodeEntities`
*/
encodeEntities?: boolean | "utf8";
/**
* Option inherited from parsing; will be used as the default value for `encodeEntities`.
*
* @default true
*/
decodeEntities?: boolean;
}
/**
* Renders a DOM node or an array of DOM nodes to a string.
*
* Can be thought of as the equivalent of the `outerHTML` of the passed node(s).
*
* @param node Node to be rendered.
* @param options Changes serialization behavior
*/
export declare function render(node: AnyNode | ArrayLike<AnyNode>, options?: DomSerializerOptions): string;
export default render;
//# sourceMappingURL=index.d.ts.map

View file

@ -0,0 +1 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EACV,OAAO,EAMR,MAAM,YAAY,CAAC;AAWpB,MAAM,WAAW,oBAAoB;IACnC;;;;;;OAMG;IACH,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB;;;;;;OAMG;IACH,eAAe,CAAC,EAAE,OAAO,CAAC;IAC1B;;;;;;OAMG;IACH,OAAO,CAAC,EAAE,OAAO,GAAG,SAAS,CAAC;IAC9B;;;;;;OAMG;IACH,cAAc,CAAC,EAAE,OAAO,GAAG,MAAM,CAAC;IAClC;;;;OAIG;IACH,cAAc,CAAC,EAAE,OAAO,CAAC;CAC1B;AA4ED;;;;;;;GAOG;AACH,wBAAgB,MAAM,CACpB,IAAI,EAAE,OAAO,GAAG,SAAS,CAAC,OAAO,CAAC,EAClC,OAAO,GAAE,oBAAyB,GACjC,MAAM,CAUR;AAED,eAAe,MAAM,CAAC"}

View file

@ -0,0 +1,190 @@
/*
* Module dependencies
*/
import * as ElementType from "domelementtype";
import { encodeXML, escapeAttribute, escapeText } from "entities";
/**
* Mixed-case SVG and MathML tags & attributes
* recognized by the HTML parser.
*
* @see https://html.spec.whatwg.org/multipage/parsing.html#parsing-main-inforeign
*/
import { elementNames, attributeNames } from "./foreignNames.js";
const unencodedElements = new Set([
"style",
"script",
"xmp",
"iframe",
"noembed",
"noframes",
"plaintext",
"noscript",
]);
function replaceQuotes(value) {
return value.replace(/"/g, "&quot;");
}
/**
* Format attributes
*/
function formatAttributes(attributes, opts) {
var _a;
if (!attributes)
return;
const encode = ((_a = opts.encodeEntities) !== null && _a !== void 0 ? _a : opts.decodeEntities) === false
? replaceQuotes
: opts.xmlMode || opts.encodeEntities !== "utf8"
? encodeXML
: escapeAttribute;
return Object.keys(attributes)
.map((key) => {
var _a, _b;
const value = (_a = attributes[key]) !== null && _a !== void 0 ? _a : "";
if (opts.xmlMode === "foreign") {
/* Fix up mixed-case attribute names */
key = (_b = attributeNames.get(key)) !== null && _b !== void 0 ? _b : key;
}
if (!opts.emptyAttrs && !opts.xmlMode && value === "") {
return key;
}
return `${key}="${encode(value)}"`;
})
.join(" ");
}
/**
* Self-enclosing tags
*/
const singleTag = new Set([
"area",
"base",
"basefont",
"br",
"col",
"command",
"embed",
"frame",
"hr",
"img",
"input",
"isindex",
"keygen",
"link",
"meta",
"param",
"source",
"track",
"wbr",
]);
/**
* Renders a DOM node or an array of DOM nodes to a string.
*
* Can be thought of as the equivalent of the `outerHTML` of the passed node(s).
*
* @param node Node to be rendered.
* @param options Changes serialization behavior
*/
export function render(node, options = {}) {
const nodes = "length" in node ? node : [node];
let output = "";
for (let i = 0; i < nodes.length; i++) {
output += renderNode(nodes[i], options);
}
return output;
}
export default render;
function renderNode(node, options) {
switch (node.type) {
case ElementType.Root:
return render(node.children, options);
// @ts-expect-error We don't use `Doctype` yet
case ElementType.Doctype:
case ElementType.Directive:
return renderDirective(node);
case ElementType.Comment:
return renderComment(node);
case ElementType.CDATA:
return renderCdata(node);
case ElementType.Script:
case ElementType.Style:
case ElementType.Tag:
return renderTag(node, options);
case ElementType.Text:
return renderText(node, options);
}
}
const foreignModeIntegrationPoints = new Set([
"mi",
"mo",
"mn",
"ms",
"mtext",
"annotation-xml",
"foreignObject",
"desc",
"title",
]);
const foreignElements = new Set(["svg", "math"]);
function renderTag(elem, opts) {
var _a;
// Handle SVG / MathML in HTML
if (opts.xmlMode === "foreign") {
/* Fix up mixed-case element names */
elem.name = (_a = elementNames.get(elem.name)) !== null && _a !== void 0 ? _a : elem.name;
/* Exit foreign mode at integration points */
if (elem.parent &&
foreignModeIntegrationPoints.has(elem.parent.name)) {
opts = { ...opts, xmlMode: false };
}
}
if (!opts.xmlMode && foreignElements.has(elem.name)) {
opts = { ...opts, xmlMode: "foreign" };
}
let tag = `<${elem.name}`;
const attribs = formatAttributes(elem.attribs, opts);
if (attribs) {
tag += ` ${attribs}`;
}
if (elem.children.length === 0 &&
(opts.xmlMode
? // In XML mode or foreign mode, and user hasn't explicitly turned off self-closing tags
opts.selfClosingTags !== false
: // User explicitly asked for self-closing tags, even in HTML mode
opts.selfClosingTags && singleTag.has(elem.name))) {
if (!opts.xmlMode)
tag += " ";
tag += "/>";
}
else {
tag += ">";
if (elem.children.length > 0) {
tag += render(elem.children, opts);
}
if (opts.xmlMode || !singleTag.has(elem.name)) {
tag += `</${elem.name}>`;
}
}
return tag;
}
function renderDirective(elem) {
return `<${elem.data}>`;
}
function renderText(elem, opts) {
var _a;
let data = elem.data || "";
// If entities weren't decoded, no need to encode them back
if (((_a = opts.encodeEntities) !== null && _a !== void 0 ? _a : opts.decodeEntities) !== false &&
!(!opts.xmlMode &&
elem.parent &&
unencodedElements.has(elem.parent.name))) {
data =
opts.xmlMode || opts.encodeEntities !== "utf8"
? encodeXML(data)
: escapeText(data);
}
return data;
}
function renderCdata(elem) {
return `<![CDATA[${elem.children[0].data}]]>`;
}
function renderComment(elem) {
return `<!--${elem.data}-->`;
}

View file

@ -0,0 +1 @@
{"type":"module"}

View file

@ -0,0 +1,3 @@
export declare const elementNames: Map<string, string>;
export declare const attributeNames: Map<string, string>;
//# sourceMappingURL=foreignNames.d.ts.map

View file

@ -0,0 +1 @@
{"version":3,"file":"foreignNames.d.ts","sourceRoot":"","sources":["../src/foreignNames.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,YAAY,qBAsCvB,CAAC;AACH,eAAO,MAAM,cAAc,qBA4DzB,CAAC"}

View file

@ -0,0 +1,103 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.attributeNames = exports.elementNames = void 0;
exports.elementNames = new Map([
["altglyph", "altGlyph"],
["altglyphdef", "altGlyphDef"],
["altglyphitem", "altGlyphItem"],
["animatecolor", "animateColor"],
["animatemotion", "animateMotion"],
["animatetransform", "animateTransform"],
["clippath", "clipPath"],
["feblend", "feBlend"],
["fecolormatrix", "feColorMatrix"],
["fecomponenttransfer", "feComponentTransfer"],
["fecomposite", "feComposite"],
["feconvolvematrix", "feConvolveMatrix"],
["fediffuselighting", "feDiffuseLighting"],
["fedisplacementmap", "feDisplacementMap"],
["fedistantlight", "feDistantLight"],
["fedropshadow", "feDropShadow"],
["feflood", "feFlood"],
["fefunca", "feFuncA"],
["fefuncb", "feFuncB"],
["fefuncg", "feFuncG"],
["fefuncr", "feFuncR"],
["fegaussianblur", "feGaussianBlur"],
["feimage", "feImage"],
["femerge", "feMerge"],
["femergenode", "feMergeNode"],
["femorphology", "feMorphology"],
["feoffset", "feOffset"],
["fepointlight", "fePointLight"],
["fespecularlighting", "feSpecularLighting"],
["fespotlight", "feSpotLight"],
["fetile", "feTile"],
["feturbulence", "feTurbulence"],
["foreignobject", "foreignObject"],
["glyphref", "glyphRef"],
["lineargradient", "linearGradient"],
["radialgradient", "radialGradient"],
["textpath", "textPath"],
]);
exports.attributeNames = new Map([
["definitionurl", "definitionURL"],
["attributename", "attributeName"],
["attributetype", "attributeType"],
["basefrequency", "baseFrequency"],
["baseprofile", "baseProfile"],
["calcmode", "calcMode"],
["clippathunits", "clipPathUnits"],
["diffuseconstant", "diffuseConstant"],
["edgemode", "edgeMode"],
["filterunits", "filterUnits"],
["glyphref", "glyphRef"],
["gradienttransform", "gradientTransform"],
["gradientunits", "gradientUnits"],
["kernelmatrix", "kernelMatrix"],
["kernelunitlength", "kernelUnitLength"],
["keypoints", "keyPoints"],
["keysplines", "keySplines"],
["keytimes", "keyTimes"],
["lengthadjust", "lengthAdjust"],
["limitingconeangle", "limitingConeAngle"],
["markerheight", "markerHeight"],
["markerunits", "markerUnits"],
["markerwidth", "markerWidth"],
["maskcontentunits", "maskContentUnits"],
["maskunits", "maskUnits"],
["numoctaves", "numOctaves"],
["pathlength", "pathLength"],
["patterncontentunits", "patternContentUnits"],
["patterntransform", "patternTransform"],
["patternunits", "patternUnits"],
["pointsatx", "pointsAtX"],
["pointsaty", "pointsAtY"],
["pointsatz", "pointsAtZ"],
["preservealpha", "preserveAlpha"],
["preserveaspectratio", "preserveAspectRatio"],
["primitiveunits", "primitiveUnits"],
["refx", "refX"],
["refy", "refY"],
["repeatcount", "repeatCount"],
["repeatdur", "repeatDur"],
["requiredextensions", "requiredExtensions"],
["requiredfeatures", "requiredFeatures"],
["specularconstant", "specularConstant"],
["specularexponent", "specularExponent"],
["spreadmethod", "spreadMethod"],
["startoffset", "startOffset"],
["stddeviation", "stdDeviation"],
["stitchtiles", "stitchTiles"],
["surfacescale", "surfaceScale"],
["systemlanguage", "systemLanguage"],
["tablevalues", "tableValues"],
["targetx", "targetX"],
["targety", "targetY"],
["textlength", "textLength"],
["viewbox", "viewBox"],
["viewtarget", "viewTarget"],
["xchannelselector", "xChannelSelector"],
["ychannelselector", "yChannelSelector"],
["zoomandpan", "zoomAndPan"],
]);

View file

@ -0,0 +1,43 @@
import type { Node } from "domhandler";
export interface DomSerializerOptions {
/**
* Print an empty attribute's value.
*
* @default xmlMode
* @example With <code>emptyAttrs: false</code>: <code>&lt;input checked&gt;</code>
* @example With <code>emptyAttrs: true</code>: <code>&lt;input checked=""&gt;</code>
*/
emptyAttrs?: boolean;
/**
* Print self-closing tags for tags without contents.
*
* @default xmlMode
* @example With <code>selfClosingTags: false</code>: <code>&lt;foo&gt;&lt;/foo&gt;</code>
* @example With <code>selfClosingTags: true</code>: <code>&lt;foo /&gt;</code>
*/
selfClosingTags?: boolean;
/**
* Treat the input as an XML document; enables the `emptyAttrs` and `selfClosingTags` options.
*
* If the value is `"foreign"`, it will try to correct mixed-case attribute names.
*
* @default false
*/
xmlMode?: boolean | "foreign";
/**
* Encode characters that are either reserved in HTML or XML, or are outside of the ASCII range.
*
* @default true
*/
decodeEntities?: boolean;
}
/**
* Renders a DOM node or an array of DOM nodes to a string.
*
* Can be thought of as the equivalent of the `outerHTML` of the passed node(s).
*
* @param node Node to be rendered.
* @param options Changes serialization behavior
*/
export default function render(node: Node | ArrayLike<Node>, options?: DomSerializerOptions): string;
//# sourceMappingURL=index.d.ts.map

View file

@ -0,0 +1 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,IAAI,EAAuC,MAAM,YAAY,CAAC;AAW5E,MAAM,WAAW,oBAAoB;IACnC;;;;;;OAMG;IACH,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB;;;;;;OAMG;IACH,eAAe,CAAC,EAAE,OAAO,CAAC;IAC1B;;;;;;OAMG;IACH,OAAO,CAAC,EAAE,OAAO,GAAG,SAAS,CAAC;IAC9B;;;;OAIG;IACH,cAAc,CAAC,EAAE,OAAO,CAAC;CAC1B;AAqED;;;;;;;GAOG;AACH,MAAM,CAAC,OAAO,UAAU,MAAM,CAC5B,IAAI,EAAE,IAAI,GAAG,SAAS,CAAC,IAAI,CAAC,EAC5B,OAAO,GAAE,oBAAyB,GACjC,MAAM,CAUR"}

View file

@ -0,0 +1,211 @@
"use strict";
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
/*
* Module dependencies
*/
var ElementType = __importStar(require("domelementtype"));
var entities_1 = require("entities");
/**
* Mixed-case SVG and MathML tags & attributes
* recognized by the HTML parser.
*
* @see https://html.spec.whatwg.org/multipage/parsing.html#parsing-main-inforeign
*/
var foreignNames_1 = require("./foreignNames");
var unencodedElements = new Set([
"style",
"script",
"xmp",
"iframe",
"noembed",
"noframes",
"plaintext",
"noscript",
]);
/**
* Format attributes
*/
function formatAttributes(attributes, opts) {
if (!attributes)
return;
return Object.keys(attributes)
.map(function (key) {
var _a, _b;
var value = (_a = attributes[key]) !== null && _a !== void 0 ? _a : "";
if (opts.xmlMode === "foreign") {
/* Fix up mixed-case attribute names */
key = (_b = foreignNames_1.attributeNames.get(key)) !== null && _b !== void 0 ? _b : key;
}
if (!opts.emptyAttrs && !opts.xmlMode && value === "") {
return key;
}
return key + "=\"" + (opts.decodeEntities !== false
? entities_1.encodeXML(value)
: value.replace(/"/g, "&quot;")) + "\"";
})
.join(" ");
}
/**
* Self-enclosing tags
*/
var singleTag = new Set([
"area",
"base",
"basefont",
"br",
"col",
"command",
"embed",
"frame",
"hr",
"img",
"input",
"isindex",
"keygen",
"link",
"meta",
"param",
"source",
"track",
"wbr",
]);
/**
* Renders a DOM node or an array of DOM nodes to a string.
*
* Can be thought of as the equivalent of the `outerHTML` of the passed node(s).
*
* @param node Node to be rendered.
* @param options Changes serialization behavior
*/
function render(node, options) {
if (options === void 0) { options = {}; }
var nodes = "length" in node ? node : [node];
var output = "";
for (var i = 0; i < nodes.length; i++) {
output += renderNode(nodes[i], options);
}
return output;
}
exports.default = render;
function renderNode(node, options) {
switch (node.type) {
case ElementType.Root:
return render(node.children, options);
case ElementType.Directive:
case ElementType.Doctype:
return renderDirective(node);
case ElementType.Comment:
return renderComment(node);
case ElementType.CDATA:
return renderCdata(node);
case ElementType.Script:
case ElementType.Style:
case ElementType.Tag:
return renderTag(node, options);
case ElementType.Text:
return renderText(node, options);
}
}
var foreignModeIntegrationPoints = new Set([
"mi",
"mo",
"mn",
"ms",
"mtext",
"annotation-xml",
"foreignObject",
"desc",
"title",
]);
var foreignElements = new Set(["svg", "math"]);
function renderTag(elem, opts) {
var _a;
// Handle SVG / MathML in HTML
if (opts.xmlMode === "foreign") {
/* Fix up mixed-case element names */
elem.name = (_a = foreignNames_1.elementNames.get(elem.name)) !== null && _a !== void 0 ? _a : elem.name;
/* Exit foreign mode at integration points */
if (elem.parent &&
foreignModeIntegrationPoints.has(elem.parent.name)) {
opts = __assign(__assign({}, opts), { xmlMode: false });
}
}
if (!opts.xmlMode && foreignElements.has(elem.name)) {
opts = __assign(__assign({}, opts), { xmlMode: "foreign" });
}
var tag = "<" + elem.name;
var attribs = formatAttributes(elem.attribs, opts);
if (attribs) {
tag += " " + attribs;
}
if (elem.children.length === 0 &&
(opts.xmlMode
? // In XML mode or foreign mode, and user hasn't explicitly turned off self-closing tags
opts.selfClosingTags !== false
: // User explicitly asked for self-closing tags, even in HTML mode
opts.selfClosingTags && singleTag.has(elem.name))) {
if (!opts.xmlMode)
tag += " ";
tag += "/>";
}
else {
tag += ">";
if (elem.children.length > 0) {
tag += render(elem.children, opts);
}
if (opts.xmlMode || !singleTag.has(elem.name)) {
tag += "</" + elem.name + ">";
}
}
return tag;
}
function renderDirective(elem) {
return "<" + elem.data + ">";
}
function renderText(elem, opts) {
var data = elem.data || "";
// If entities weren't decoded, no need to encode them back
if (opts.decodeEntities !== false &&
!(!opts.xmlMode &&
elem.parent &&
unencodedElements.has(elem.parent.name))) {
data = entities_1.encodeXML(data);
}
return data;
}
function renderCdata(elem) {
return "<![CDATA[" + elem.children[0].data + "]]>";
}
function renderComment(elem) {
return "<!--" + elem.data + "-->";
}

View file

@ -0,0 +1,55 @@
{
"name": "dom-serializer",
"version": "1.4.1",
"description": "render domhandler DOM nodes to a string",
"author": "Felix Boehm <me@feedic.com>",
"sideEffects": false,
"keywords": [
"html",
"xml",
"render"
],
"repository": {
"type": "git",
"url": "git://github.com/cheeriojs/dom-renderer.git"
},
"main": "lib/index.js",
"types": "lib/index.d.ts",
"files": [
"lib/**/*"
],
"dependencies": {
"domelementtype": "^2.0.1",
"domhandler": "^4.2.0",
"entities": "^2.0.0"
},
"devDependencies": {
"@types/jest": "^26.0.23",
"@types/node": "^15.3.0",
"@typescript-eslint/eslint-plugin": "^4.23.0",
"@typescript-eslint/parser": "^4.23.0",
"cheerio": "^1.0.0-rc.9",
"coveralls": "^3.0.5",
"eslint": "^7.26.0",
"eslint-config-prettier": "^8.3.0",
"htmlparser2": "^6.1.0",
"jest": "^26.0.1",
"prettier": "^2.3.0",
"ts-jest": "^26.5.6",
"typescript": "^4.0.2"
},
"scripts": {
"test": "jest --coverage && npm run lint",
"coverage": "cat coverage/lcov.info | coveralls",
"lint": "eslint src",
"format": "prettier --write '**/*.{ts,md,json}'",
"build": "tsc",
"prepare": "npm run build"
},
"jest": {
"preset": "ts-jest",
"testEnvironment": "node"
},
"funding": "https://github.com/cheeriojs/dom-serializer?sponsor=1",
"license": "MIT"
}

View file

@ -0,0 +1,11 @@
Copyright (c) Felix Böhm
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
THIS IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

View file

@ -0,0 +1,48 @@
/** Types of elements found in htmlparser2's DOM */
export declare enum ElementType {
/** Type for the root element of a document */
Root = "root",
/** Type for Text */
Text = "text",
/** Type for <? ... ?> */
Directive = "directive",
/** Type for <!-- ... --> */
Comment = "comment",
/** Type for <script> tags */
Script = "script",
/** Type for <style> tags */
Style = "style",
/** Type for Any tag */
Tag = "tag",
/** Type for <![CDATA[ ... ]]> */
CDATA = "cdata",
/** Type for <!doctype ...> */
Doctype = "doctype"
}
/**
* Tests whether an element is a tag or not.
*
* @param elem Element to test
*/
export declare function isTag(elem: {
type: ElementType;
}): boolean;
/** Type for the root element of a document */
export declare const Root = ElementType.Root;
/** Type for Text */
export declare const Text = ElementType.Text;
/** Type for <? ... ?> */
export declare const Directive = ElementType.Directive;
/** Type for <!-- ... --> */
export declare const Comment = ElementType.Comment;
/** Type for <script> tags */
export declare const Script = ElementType.Script;
/** Type for <style> tags */
export declare const Style = ElementType.Style;
/** Type for Any tag */
export declare const Tag = ElementType.Tag;
/** Type for <![CDATA[ ... ]]> */
export declare const CDATA = ElementType.CDATA;
/** Type for <!doctype ...> */
export declare const Doctype = ElementType.Doctype;
//# sourceMappingURL=index.d.ts.map

View file

@ -0,0 +1 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,mDAAmD;AACnD,oBAAY,WAAW;IACnB,8CAA8C;IAC9C,IAAI,SAAS;IACb,oBAAoB;IACpB,IAAI,SAAS;IACb,yBAAyB;IACzB,SAAS,cAAc;IACvB,4BAA4B;IAC5B,OAAO,YAAY;IACnB,6BAA6B;IAC7B,MAAM,WAAW;IACjB,4BAA4B;IAC5B,KAAK,UAAU;IACf,uBAAuB;IACvB,GAAG,QAAQ;IACX,iCAAiC;IACjC,KAAK,UAAU;IACf,8BAA8B;IAC9B,OAAO,YAAY;CACtB;AAED;;;;GAIG;AACH,wBAAgB,KAAK,CAAC,IAAI,EAAE;IAAE,IAAI,EAAE,WAAW,CAAA;CAAE,GAAG,OAAO,CAM1D;AAGD,8CAA8C;AAC9C,eAAO,MAAM,IAAI,mBAAmB,CAAC;AACrC,oBAAoB;AACpB,eAAO,MAAM,IAAI,mBAAmB,CAAC;AACrC,yBAAyB;AACzB,eAAO,MAAM,SAAS,wBAAwB,CAAC;AAC/C,4BAA4B;AAC5B,eAAO,MAAM,OAAO,sBAAsB,CAAC;AAC3C,6BAA6B;AAC7B,eAAO,MAAM,MAAM,qBAAqB,CAAC;AACzC,4BAA4B;AAC5B,eAAO,MAAM,KAAK,oBAAoB,CAAC;AACvC,uBAAuB;AACvB,eAAO,MAAM,GAAG,kBAAkB,CAAC;AACnC,iCAAiC;AACjC,eAAO,MAAM,KAAK,oBAAoB,CAAC;AACvC,8BAA8B;AAC9B,eAAO,MAAM,OAAO,sBAAsB,CAAC"}

View file

@ -0,0 +1,51 @@
/** Types of elements found in htmlparser2's DOM */
export var ElementType;
(function (ElementType) {
/** Type for the root element of a document */
ElementType["Root"] = "root";
/** Type for Text */
ElementType["Text"] = "text";
/** Type for <? ... ?> */
ElementType["Directive"] = "directive";
/** Type for <!-- ... --> */
ElementType["Comment"] = "comment";
/** Type for <script> tags */
ElementType["Script"] = "script";
/** Type for <style> tags */
ElementType["Style"] = "style";
/** Type for Any tag */
ElementType["Tag"] = "tag";
/** Type for <![CDATA[ ... ]]> */
ElementType["CDATA"] = "cdata";
/** Type for <!doctype ...> */
ElementType["Doctype"] = "doctype";
})(ElementType || (ElementType = {}));
/**
* Tests whether an element is a tag or not.
*
* @param elem Element to test
*/
export function isTag(elem) {
return (elem.type === ElementType.Tag ||
elem.type === ElementType.Script ||
elem.type === ElementType.Style);
}
// Exports for backwards compatibility
/** Type for the root element of a document */
export const Root = ElementType.Root;
/** Type for Text */
export const Text = ElementType.Text;
/** Type for <? ... ?> */
export const Directive = ElementType.Directive;
/** Type for <!-- ... --> */
export const Comment = ElementType.Comment;
/** Type for <script> tags */
export const Script = ElementType.Script;
/** Type for <style> tags */
export const Style = ElementType.Style;
/** Type for Any tag */
export const Tag = ElementType.Tag;
/** Type for <![CDATA[ ... ]]> */
export const CDATA = ElementType.CDATA;
/** Type for <!doctype ...> */
export const Doctype = ElementType.Doctype;

View file

@ -0,0 +1 @@
{"type":"module"}

View file

@ -0,0 +1,48 @@
/** Types of elements found in htmlparser2's DOM */
export declare enum ElementType {
/** Type for the root element of a document */
Root = "root",
/** Type for Text */
Text = "text",
/** Type for <? ... ?> */
Directive = "directive",
/** Type for <!-- ... --> */
Comment = "comment",
/** Type for <script> tags */
Script = "script",
/** Type for <style> tags */
Style = "style",
/** Type for Any tag */
Tag = "tag",
/** Type for <![CDATA[ ... ]]> */
CDATA = "cdata",
/** Type for <!doctype ...> */
Doctype = "doctype"
}
/**
* Tests whether an element is a tag or not.
*
* @param elem Element to test
*/
export declare function isTag(elem: {
type: ElementType;
}): boolean;
/** Type for the root element of a document */
export declare const Root = ElementType.Root;
/** Type for Text */
export declare const Text = ElementType.Text;
/** Type for <? ... ?> */
export declare const Directive = ElementType.Directive;
/** Type for <!-- ... --> */
export declare const Comment = ElementType.Comment;
/** Type for <script> tags */
export declare const Script = ElementType.Script;
/** Type for <style> tags */
export declare const Style = ElementType.Style;
/** Type for Any tag */
export declare const Tag = ElementType.Tag;
/** Type for <![CDATA[ ... ]]> */
export declare const CDATA = ElementType.CDATA;
/** Type for <!doctype ...> */
export declare const Doctype = ElementType.Doctype;
//# sourceMappingURL=index.d.ts.map

View file

@ -0,0 +1 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,mDAAmD;AACnD,oBAAY,WAAW;IACnB,8CAA8C;IAC9C,IAAI,SAAS;IACb,oBAAoB;IACpB,IAAI,SAAS;IACb,yBAAyB;IACzB,SAAS,cAAc;IACvB,4BAA4B;IAC5B,OAAO,YAAY;IACnB,6BAA6B;IAC7B,MAAM,WAAW;IACjB,4BAA4B;IAC5B,KAAK,UAAU;IACf,uBAAuB;IACvB,GAAG,QAAQ;IACX,iCAAiC;IACjC,KAAK,UAAU;IACf,8BAA8B;IAC9B,OAAO,YAAY;CACtB;AAED;;;;GAIG;AACH,wBAAgB,KAAK,CAAC,IAAI,EAAE;IAAE,IAAI,EAAE,WAAW,CAAA;CAAE,GAAG,OAAO,CAM1D;AAGD,8CAA8C;AAC9C,eAAO,MAAM,IAAI,mBAAmB,CAAC;AACrC,oBAAoB;AACpB,eAAO,MAAM,IAAI,mBAAmB,CAAC;AACrC,yBAAyB;AACzB,eAAO,MAAM,SAAS,wBAAwB,CAAC;AAC/C,4BAA4B;AAC5B,eAAO,MAAM,OAAO,sBAAsB,CAAC;AAC3C,6BAA6B;AAC7B,eAAO,MAAM,MAAM,qBAAqB,CAAC;AACzC,4BAA4B;AAC5B,eAAO,MAAM,KAAK,oBAAoB,CAAC;AACvC,uBAAuB;AACvB,eAAO,MAAM,GAAG,kBAAkB,CAAC;AACnC,iCAAiC;AACjC,eAAO,MAAM,KAAK,oBAAoB,CAAC;AACvC,8BAA8B;AAC9B,eAAO,MAAM,OAAO,sBAAsB,CAAC"}

View file

@ -0,0 +1,55 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Doctype = exports.CDATA = exports.Tag = exports.Style = exports.Script = exports.Comment = exports.Directive = exports.Text = exports.Root = exports.isTag = exports.ElementType = void 0;
/** Types of elements found in htmlparser2's DOM */
var ElementType;
(function (ElementType) {
/** Type for the root element of a document */
ElementType["Root"] = "root";
/** Type for Text */
ElementType["Text"] = "text";
/** Type for <? ... ?> */
ElementType["Directive"] = "directive";
/** Type for <!-- ... --> */
ElementType["Comment"] = "comment";
/** Type for <script> tags */
ElementType["Script"] = "script";
/** Type for <style> tags */
ElementType["Style"] = "style";
/** Type for Any tag */
ElementType["Tag"] = "tag";
/** Type for <![CDATA[ ... ]]> */
ElementType["CDATA"] = "cdata";
/** Type for <!doctype ...> */
ElementType["Doctype"] = "doctype";
})(ElementType = exports.ElementType || (exports.ElementType = {}));
/**
* Tests whether an element is a tag or not.
*
* @param elem Element to test
*/
function isTag(elem) {
return (elem.type === ElementType.Tag ||
elem.type === ElementType.Script ||
elem.type === ElementType.Style);
}
exports.isTag = isTag;
// Exports for backwards compatibility
/** Type for the root element of a document */
exports.Root = ElementType.Root;
/** Type for Text */
exports.Text = ElementType.Text;
/** Type for <? ... ?> */
exports.Directive = ElementType.Directive;
/** Type for <!-- ... --> */
exports.Comment = ElementType.Comment;
/** Type for <script> tags */
exports.Script = ElementType.Script;
/** Type for <style> tags */
exports.Style = ElementType.Style;
/** Type for Any tag */
exports.Tag = ElementType.Tag;
/** Type for <![CDATA[ ... ]]> */
exports.CDATA = ElementType.CDATA;
/** Type for <!doctype ...> */
exports.Doctype = ElementType.Doctype;

View file

@ -0,0 +1,54 @@
{
"name": "domelementtype",
"version": "2.3.0",
"description": "all the types of nodes in htmlparser2's dom",
"author": "Felix Boehm <me@feedic.com>",
"license": "BSD-2-Clause",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/fb55"
}
],
"sideEffects": false,
"main": "lib/index.js",
"types": "lib/index.d.ts",
"module": "lib/esm/index.js",
"exports": {
"require": "./lib/index.js",
"import": "./lib/esm/index.js"
},
"files": [
"lib/**/*"
],
"repository": {
"type": "git",
"url": "git://github.com/fb55/domelementtype.git"
},
"keywords": [
"dom",
"element",
"types",
"htmlparser2"
],
"scripts": {
"test": "npm run lint && prettier --check **/*.{ts,json,md}",
"lint": "eslint src",
"format": "prettier --write **/*.{ts,json,md}",
"build": "npm run build:cjs && npm run build:esm",
"build:cjs": "tsc",
"build:esm": "tsc --module esnext --target es2019 --outDir lib/esm && echo '{\"type\":\"module\"}' > lib/esm/package.json",
"prepare": "npm run build"
},
"prettier": {
"tabWidth": 4
},
"devDependencies": {
"@typescript-eslint/eslint-plugin": "^5.18.0",
"@typescript-eslint/parser": "^5.18.0",
"eslint": "^8.12.0",
"eslint-config-prettier": "^8.5.0",
"prettier": "^2.6.2",
"typescript": "^4.6.3"
}
}

View file

@ -0,0 +1 @@
All the types of nodes in htmlparser2's DOM.

View file

@ -0,0 +1,11 @@
Copyright (c) Felix Böhm
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
THIS IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

View file

@ -0,0 +1,85 @@
import { Node, Element, DataNode, NodeWithChildren, Document } from "./node";
export * from "./node";
export interface DomHandlerOptions {
/**
* Add a `startIndex` property to nodes.
* When the parser is used in a non-streaming fashion, `startIndex` is an integer
* indicating the position of the start of the node in the document.
*
* @default false
*/
withStartIndices?: boolean;
/**
* Add an `endIndex` property to nodes.
* When the parser is used in a non-streaming fashion, `endIndex` is an integer
* indicating the position of the end of the node in the document.
*
* @default false
*/
withEndIndices?: boolean;
/**
* Replace all whitespace with single spaces.
*
* **Note:** Enabling this might break your markup.
*
* @default false
* @deprecated
*/
normalizeWhitespace?: boolean;
/**
* Treat the markup as XML.
*
* @default false
*/
xmlMode?: boolean;
}
interface ParserInterface {
startIndex: number | null;
endIndex: number | null;
}
declare type Callback = (error: Error | null, dom: Node[]) => void;
declare type ElementCallback = (element: Element) => void;
export declare class DomHandler {
/** The elements of the DOM */
dom: Node[];
/** The root element for the DOM */
root: Document;
/** Called once parsing has completed. */
private readonly callback;
/** Settings for the handler. */
private readonly options;
/** Callback whenever a tag is closed. */
private readonly elementCB;
/** Indicated whether parsing has been completed. */
private done;
/** Stack of open tags. */
protected tagStack: NodeWithChildren[];
/** A data node that is still being written to. */
protected lastNode: DataNode | null;
/** Reference to the parser instance. Used for location information. */
private parser;
/**
* @param callback Called once parsing has completed.
* @param options Settings for the handler.
* @param elementCB Callback whenever a tag is closed.
*/
constructor(callback?: Callback | null, options?: DomHandlerOptions | null, elementCB?: ElementCallback);
onparserinit(parser: ParserInterface): void;
onreset(): void;
onend(): void;
onerror(error: Error): void;
onclosetag(): void;
onopentag(name: string, attribs: {
[key: string]: string;
}): void;
ontext(data: string): void;
oncomment(data: string): void;
oncommentend(): void;
oncdatastart(): void;
oncdataend(): void;
onprocessinginstruction(name: string, data: string): void;
protected handleCallback(error: Error | null): void;
protected addNode(node: Node): void;
}
export default DomHandler;
//# sourceMappingURL=index.d.ts.map

View file

@ -0,0 +1 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EACH,IAAI,EACJ,OAAO,EACP,QAAQ,EAGR,gBAAgB,EAChB,QAAQ,EAEX,MAAM,QAAQ,CAAC;AAEhB,cAAc,QAAQ,CAAC;AAIvB,MAAM,WAAW,iBAAiB;IAC9B;;;;;;OAMG;IACH,gBAAgB,CAAC,EAAE,OAAO,CAAC;IAE3B;;;;;;OAMG;IACH,cAAc,CAAC,EAAE,OAAO,CAAC;IAEzB;;;;;;;OAOG;IACH,mBAAmB,CAAC,EAAE,OAAO,CAAC;IAE9B;;;;OAIG;IACH,OAAO,CAAC,EAAE,OAAO,CAAC;CACrB;AAUD,UAAU,eAAe;IACrB,UAAU,EAAE,MAAM,GAAG,IAAI,CAAC;IAC1B,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAC;CAC3B;AAED,aAAK,QAAQ,GAAG,CAAC,KAAK,EAAE,KAAK,GAAG,IAAI,EAAE,GAAG,EAAE,IAAI,EAAE,KAAK,IAAI,CAAC;AAC3D,aAAK,eAAe,GAAG,CAAC,OAAO,EAAE,OAAO,KAAK,IAAI,CAAC;AAElD,qBAAa,UAAU;IACnB,8BAA8B;IACvB,GAAG,EAAE,IAAI,EAAE,CAAM;IAExB,mCAAmC;IAC5B,IAAI,WAA0B;IAErC,yCAAyC;IACzC,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAkB;IAE3C,gCAAgC;IAChC,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAoB;IAE5C,yCAAyC;IACzC,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAyB;IAEnD,oDAAoD;IACpD,OAAO,CAAC,IAAI,CAAS;IAErB,0BAA0B;IAC1B,SAAS,CAAC,QAAQ,EAAE,gBAAgB,EAAE,CAAe;IAErD,kDAAkD;IAClD,SAAS,CAAC,QAAQ,EAAE,QAAQ,GAAG,IAAI,CAAQ;IAE3C,uEAAuE;IACvE,OAAO,CAAC,MAAM,CAAgC;IAE9C;;;;OAIG;gBAEC,QAAQ,CAAC,EAAE,QAAQ,GAAG,IAAI,EAC1B,OAAO,CAAC,EAAE,iBAAiB,GAAG,IAAI,EAClC,SAAS,CAAC,EAAE,eAAe;IAiBxB,YAAY,CAAC,MAAM,EAAE,eAAe,GAAG,IAAI;IAK3C,OAAO,IAAI,IAAI;IAUf,KAAK,IAAI,IAAI;IAOb,OAAO,CAAC,KAAK,EAAE,KAAK,GAAG,IAAI;IAI3B,UAAU,IAAI,IAAI;IAYlB,SAAS,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE;QAAE,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAAA;KAAE,GAAG,IAAI;IAOjE,MAAM,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI;IA2B1B,SAAS,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI;IAW7B,YAAY,IAAI,IAAI;IAIpB,YAAY,IAAI,IAAI;IAUpB,UAAU,IAAI,IAAI;IAIlB,uBAAuB,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,IAAI;IAKhE,SAAS,CAAC,cAAc,CAAC,KAAK,EAAE,KAAK,GAAG,IAAI,GAAG,IAAI;IAQnD,SAAS,CAAC,OAAO,CAAC,IAAI,EAAE,IAAI,GAAG,IAAI;CAwBtC;AAED,eAAe,UAAU,CAAC"}

View file

@ -0,0 +1,176 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.DomHandler = void 0;
var domelementtype_1 = require("domelementtype");
var node_1 = require("./node");
__exportStar(require("./node"), exports);
var reWhitespace = /\s+/g;
// Default options
var defaultOpts = {
normalizeWhitespace: false,
withStartIndices: false,
withEndIndices: false,
xmlMode: false,
};
var DomHandler = /** @class */ (function () {
/**
* @param callback Called once parsing has completed.
* @param options Settings for the handler.
* @param elementCB Callback whenever a tag is closed.
*/
function DomHandler(callback, options, elementCB) {
/** The elements of the DOM */
this.dom = [];
/** The root element for the DOM */
this.root = new node_1.Document(this.dom);
/** Indicated whether parsing has been completed. */
this.done = false;
/** Stack of open tags. */
this.tagStack = [this.root];
/** A data node that is still being written to. */
this.lastNode = null;
/** Reference to the parser instance. Used for location information. */
this.parser = null;
// Make it possible to skip arguments, for backwards-compatibility
if (typeof options === "function") {
elementCB = options;
options = defaultOpts;
}
if (typeof callback === "object") {
options = callback;
callback = undefined;
}
this.callback = callback !== null && callback !== void 0 ? callback : null;
this.options = options !== null && options !== void 0 ? options : defaultOpts;
this.elementCB = elementCB !== null && elementCB !== void 0 ? elementCB : null;
}
DomHandler.prototype.onparserinit = function (parser) {
this.parser = parser;
};
// Resets the handler back to starting state
DomHandler.prototype.onreset = function () {
this.dom = [];
this.root = new node_1.Document(this.dom);
this.done = false;
this.tagStack = [this.root];
this.lastNode = null;
this.parser = null;
};
// Signals the handler that parsing is done
DomHandler.prototype.onend = function () {
if (this.done)
return;
this.done = true;
this.parser = null;
this.handleCallback(null);
};
DomHandler.prototype.onerror = function (error) {
this.handleCallback(error);
};
DomHandler.prototype.onclosetag = function () {
this.lastNode = null;
var elem = this.tagStack.pop();
if (this.options.withEndIndices) {
elem.endIndex = this.parser.endIndex;
}
if (this.elementCB)
this.elementCB(elem);
};
DomHandler.prototype.onopentag = function (name, attribs) {
var type = this.options.xmlMode ? domelementtype_1.ElementType.Tag : undefined;
var element = new node_1.Element(name, attribs, undefined, type);
this.addNode(element);
this.tagStack.push(element);
};
DomHandler.prototype.ontext = function (data) {
var normalizeWhitespace = this.options.normalizeWhitespace;
var lastNode = this.lastNode;
if (lastNode && lastNode.type === domelementtype_1.ElementType.Text) {
if (normalizeWhitespace) {
lastNode.data = (lastNode.data + data).replace(reWhitespace, " ");
}
else {
lastNode.data += data;
}
if (this.options.withEndIndices) {
lastNode.endIndex = this.parser.endIndex;
}
}
else {
if (normalizeWhitespace) {
data = data.replace(reWhitespace, " ");
}
var node = new node_1.Text(data);
this.addNode(node);
this.lastNode = node;
}
};
DomHandler.prototype.oncomment = function (data) {
if (this.lastNode && this.lastNode.type === domelementtype_1.ElementType.Comment) {
this.lastNode.data += data;
return;
}
var node = new node_1.Comment(data);
this.addNode(node);
this.lastNode = node;
};
DomHandler.prototype.oncommentend = function () {
this.lastNode = null;
};
DomHandler.prototype.oncdatastart = function () {
var text = new node_1.Text("");
var node = new node_1.NodeWithChildren(domelementtype_1.ElementType.CDATA, [text]);
this.addNode(node);
text.parent = node;
this.lastNode = text;
};
DomHandler.prototype.oncdataend = function () {
this.lastNode = null;
};
DomHandler.prototype.onprocessinginstruction = function (name, data) {
var node = new node_1.ProcessingInstruction(name, data);
this.addNode(node);
};
DomHandler.prototype.handleCallback = function (error) {
if (typeof this.callback === "function") {
this.callback(error, this.dom);
}
else if (error) {
throw error;
}
};
DomHandler.prototype.addNode = function (node) {
var parent = this.tagStack[this.tagStack.length - 1];
var previousSibling = parent.children[parent.children.length - 1];
if (this.options.withStartIndices) {
node.startIndex = this.parser.startIndex;
}
if (this.options.withEndIndices) {
node.endIndex = this.parser.endIndex;
}
parent.children.push(node);
if (previousSibling) {
node.prev = previousSibling;
previousSibling.next = node;
}
node.parent = parent;
this.lastNode = null;
};
return DomHandler;
}());
exports.DomHandler = DomHandler;
exports.default = DomHandler;

View file

@ -0,0 +1,237 @@
import { ElementType } from "domelementtype";
interface SourceCodeLocation {
/** One-based line index of the first character. */
startLine: number;
/** One-based column index of the first character. */
startCol: number;
/** Zero-based first character index. */
startOffset: number;
/** One-based line index of the last character. */
endLine: number;
/** One-based column index of the last character. Points directly *after* the last character. */
endCol: number;
/** Zero-based last character index. Points directly *after* the last character. */
endOffset: number;
}
interface TagSourceCodeLocation extends SourceCodeLocation {
startTag?: SourceCodeLocation;
endTag?: SourceCodeLocation;
}
/**
* This object will be used as the prototype for Nodes when creating a
* DOM-Level-1-compliant structure.
*/
export declare class Node {
type: ElementType;
/** Parent of the node */
parent: NodeWithChildren | null;
/** Previous sibling */
prev: Node | null;
/** Next sibling */
next: Node | null;
/** The start index of the node. Requires `withStartIndices` on the handler to be `true. */
startIndex: number | null;
/** The end index of the node. Requires `withEndIndices` on the handler to be `true. */
endIndex: number | null;
/**
* `parse5` source code location info.
*
* Available if parsing with parse5 and location info is enabled.
*/
sourceCodeLocation?: SourceCodeLocation | null;
/**
*
* @param type The type of the node.
*/
constructor(type: ElementType);
/**
* [DOM spec](https://dom.spec.whatwg.org/#dom-node-nodetype)-compatible
* node {@link type}.
*/
get nodeType(): number;
/**
* Same as {@link parent}.
* [DOM spec](https://dom.spec.whatwg.org)-compatible alias.
*/
get parentNode(): NodeWithChildren | null;
set parentNode(parent: NodeWithChildren | null);
/**
* Same as {@link prev}.
* [DOM spec](https://dom.spec.whatwg.org)-compatible alias.
*/
get previousSibling(): Node | null;
set previousSibling(prev: Node | null);
/**
* Same as {@link next}.
* [DOM spec](https://dom.spec.whatwg.org)-compatible alias.
*/
get nextSibling(): Node | null;
set nextSibling(next: Node | null);
/**
* Clone this node, and optionally its children.
*
* @param recursive Clone child nodes as well.
* @returns A clone of the node.
*/
cloneNode<T extends Node>(this: T, recursive?: boolean): T;
}
/**
* A node that contains some data.
*/
export declare class DataNode extends Node {
data: string;
/**
* @param type The type of the node
* @param data The content of the data node
*/
constructor(type: ElementType.Comment | ElementType.Text | ElementType.Directive, data: string);
/**
* Same as {@link data}.
* [DOM spec](https://dom.spec.whatwg.org)-compatible alias.
*/
get nodeValue(): string;
set nodeValue(data: string);
}
/**
* Text within the document.
*/
export declare class Text extends DataNode {
constructor(data: string);
}
/**
* Comments within the document.
*/
export declare class Comment extends DataNode {
constructor(data: string);
}
/**
* Processing instructions, including doc types.
*/
export declare class ProcessingInstruction extends DataNode {
name: string;
constructor(name: string, data: string);
/** If this is a doctype, the document type name (parse5 only). */
"x-name"?: string;
/** If this is a doctype, the document type public identifier (parse5 only). */
"x-publicId"?: string;
/** If this is a doctype, the document type system identifier (parse5 only). */
"x-systemId"?: string;
}
/**
* A `Node` that can have children.
*/
export declare class NodeWithChildren extends Node {
children: Node[];
/**
* @param type Type of the node.
* @param children Children of the node. Only certain node types can have children.
*/
constructor(type: ElementType.Root | ElementType.CDATA | ElementType.Script | ElementType.Style | ElementType.Tag, children: Node[]);
/** First child of the node. */
get firstChild(): Node | null;
/** Last child of the node. */
get lastChild(): Node | null;
/**
* Same as {@link children}.
* [DOM spec](https://dom.spec.whatwg.org)-compatible alias.
*/
get childNodes(): Node[];
set childNodes(children: Node[]);
}
/**
* The root node of the document.
*/
export declare class Document extends NodeWithChildren {
constructor(children: Node[]);
/** [Document mode](https://dom.spec.whatwg.org/#concept-document-limited-quirks) (parse5 only). */
"x-mode"?: "no-quirks" | "quirks" | "limited-quirks";
}
/**
* The description of an individual attribute.
*/
interface Attribute {
name: string;
value: string;
namespace?: string;
prefix?: string;
}
/**
* An element within the DOM.
*/
export declare class Element extends NodeWithChildren {
name: string;
attribs: {
[name: string]: string;
};
/**
* @param name Name of the tag, eg. `div`, `span`.
* @param attribs Object mapping attribute names to attribute values.
* @param children Children of the node.
*/
constructor(name: string, attribs: {
[name: string]: string;
}, children?: Node[], type?: ElementType.Tag | ElementType.Script | ElementType.Style);
/**
* `parse5` source code location info, with start & end tags.
*
* Available if parsing with parse5 and location info is enabled.
*/
sourceCodeLocation?: TagSourceCodeLocation | null;
/**
* Same as {@link name}.
* [DOM spec](https://dom.spec.whatwg.org)-compatible alias.
*/
get tagName(): string;
set tagName(name: string);
get attributes(): Attribute[];
/** Element namespace (parse5 only). */
namespace?: string;
/** Element attribute namespaces (parse5 only). */
"x-attribsNamespace"?: Record<string, string>;
/** Element attribute namespace-related prefixes (parse5 only). */
"x-attribsPrefix"?: Record<string, string>;
}
/**
* @param node Node to check.
* @returns `true` if the node is a `Element`, `false` otherwise.
*/
export declare function isTag(node: Node): node is Element;
/**
* @param node Node to check.
* @returns `true` if the node has the type `CDATA`, `false` otherwise.
*/
export declare function isCDATA(node: Node): node is NodeWithChildren;
/**
* @param node Node to check.
* @returns `true` if the node has the type `Text`, `false` otherwise.
*/
export declare function isText(node: Node): node is Text;
/**
* @param node Node to check.
* @returns `true` if the node has the type `Comment`, `false` otherwise.
*/
export declare function isComment(node: Node): node is DataNode;
/**
* @param node Node to check.
* @returns `true` if the node has the type `ProcessingInstruction`, `false` otherwise.
*/
export declare function isDirective(node: Node): node is ProcessingInstruction;
/**
* @param node Node to check.
* @returns `true` if the node has the type `ProcessingInstruction`, `false` otherwise.
*/
export declare function isDocument(node: Node): node is Document;
/**
* @param node Node to check.
* @returns `true` if the node is a `NodeWithChildren` (has children), `false` otherwise.
*/
export declare function hasChildren(node: Node): node is NodeWithChildren;
/**
* Clone a node, and optionally its children.
*
* @param recursive Clone child nodes as well.
* @returns A clone of the node.
*/
export declare function cloneNode<T extends Node>(node: T, recursive?: boolean): T;
export {};
//# sourceMappingURL=node.d.ts.map

View file

@ -0,0 +1 @@
{"version":3,"file":"node.d.ts","sourceRoot":"","sources":["../src/node.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAqB,MAAM,gBAAgB,CAAC;AAahE,UAAU,kBAAkB;IACxB,mDAAmD;IACnD,SAAS,EAAE,MAAM,CAAC;IAClB,qDAAqD;IACrD,QAAQ,EAAE,MAAM,CAAC;IACjB,wCAAwC;IACxC,WAAW,EAAE,MAAM,CAAC;IACpB,kDAAkD;IAClD,OAAO,EAAE,MAAM,CAAC;IAChB,gGAAgG;IAChG,MAAM,EAAE,MAAM,CAAC;IACf,mFAAmF;IACnF,SAAS,EAAE,MAAM,CAAC;CACrB;AAED,UAAU,qBAAsB,SAAQ,kBAAkB;IACtD,QAAQ,CAAC,EAAE,kBAAkB,CAAC;IAC9B,MAAM,CAAC,EAAE,kBAAkB,CAAC;CAC/B;AAED;;;GAGG;AACH,qBAAa,IAAI;IA2BM,IAAI,EAAE,WAAW;IA1BpC,yBAAyB;IACzB,MAAM,EAAE,gBAAgB,GAAG,IAAI,CAAQ;IAEvC,uBAAuB;IACvB,IAAI,EAAE,IAAI,GAAG,IAAI,CAAQ;IAEzB,mBAAmB;IACnB,IAAI,EAAE,IAAI,GAAG,IAAI,CAAQ;IAEzB,2FAA2F;IAC3F,UAAU,EAAE,MAAM,GAAG,IAAI,CAAQ;IAEjC,uFAAuF;IACvF,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAQ;IAE/B;;;;OAIG;IACH,kBAAkB,CAAC,EAAE,kBAAkB,GAAG,IAAI,CAAC;IAE/C;;;OAGG;gBACgB,IAAI,EAAE,WAAW;IAIpC;;;OAGG;IACH,IAAI,QAAQ,IAAI,MAAM,CAErB;IAID;;;OAGG;IACH,IAAI,UAAU,IAAI,gBAAgB,GAAG,IAAI,CAExC;IAED,IAAI,UAAU,CAAC,MAAM,EAAE,gBAAgB,GAAG,IAAI,EAE7C;IAED;;;OAGG;IACH,IAAI,eAAe,IAAI,IAAI,GAAG,IAAI,CAEjC;IAED,IAAI,eAAe,CAAC,IAAI,EAAE,IAAI,GAAG,IAAI,EAEpC;IAED;;;OAGG;IACH,IAAI,WAAW,IAAI,IAAI,GAAG,IAAI,CAE7B;IAED,IAAI,WAAW,CAAC,IAAI,EAAE,IAAI,GAAG,IAAI,EAEhC;IAED;;;;;OAKG;IACH,SAAS,CAAC,CAAC,SAAS,IAAI,EAAE,IAAI,EAAE,CAAC,EAAE,SAAS,UAAQ,GAAG,CAAC;CAG3D;AAED;;GAEG;AACH,qBAAa,QAAS,SAAQ,IAAI;IAOnB,IAAI,EAAE,MAAM;IANvB;;;OAGG;gBAEC,IAAI,EAAE,WAAW,CAAC,OAAO,GAAG,WAAW,CAAC,IAAI,GAAG,WAAW,CAAC,SAAS,EAC7D,IAAI,EAAE,MAAM;IAKvB;;;OAGG;IACH,IAAI,SAAS,IAAI,MAAM,CAEtB;IAED,IAAI,SAAS,CAAC,IAAI,EAAE,MAAM,EAEzB;CACJ;AAED;;GAEG;AACH,qBAAa,IAAK,SAAQ,QAAQ;gBAClB,IAAI,EAAE,MAAM;CAG3B;AAED;;GAEG;AACH,qBAAa,OAAQ,SAAQ,QAAQ;gBACrB,IAAI,EAAE,MAAM;CAG3B;AAED;;GAEG;AACH,qBAAa,qBAAsB,SAAQ,QAAQ;IAC5B,IAAI,EAAE,MAAM;gBAAZ,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM;IAI7C,kEAAkE;IAClE,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,+EAA+E;IAC/E,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,+EAA+E;IAC/E,YAAY,CAAC,EAAE,MAAM,CAAC;CACzB;AAED;;GAEG;AACH,qBAAa,gBAAiB,SAAQ,IAAI;IAY3B,QAAQ,EAAE,IAAI,EAAE;IAX3B;;;OAGG;gBAEC,IAAI,EACE,WAAW,CAAC,IAAI,GAChB,WAAW,CAAC,KAAK,GACjB,WAAW,CAAC,MAAM,GAClB,WAAW,CAAC,KAAK,GACjB,WAAW,CAAC,GAAG,EACd,QAAQ,EAAE,IAAI,EAAE;IAM3B,+BAA+B;IAC/B,IAAI,UAAU,IAAI,IAAI,GAAG,IAAI,CAE5B;IAED,8BAA8B;IAC9B,IAAI,SAAS,IAAI,IAAI,GAAG,IAAI,CAI3B;IAED;;;OAGG;IACH,IAAI,UAAU,IAAI,IAAI,EAAE,CAEvB;IAED,IAAI,UAAU,CAAC,QAAQ,EAAE,IAAI,EAAE,EAE9B;CACJ;AAED;;GAEG;AACH,qBAAa,QAAS,SAAQ,gBAAgB;gBAC9B,QAAQ,EAAE,IAAI,EAAE;IAI5B,mGAAmG;IACnG,QAAQ,CAAC,EAAE,WAAW,GAAG,QAAQ,GAAG,gBAAgB,CAAC;CACxD;AAED;;GAEG;AACH,UAAU,SAAS;IACf,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,EAAE,MAAM,CAAC;IACd,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,MAAM,CAAC,EAAE,MAAM,CAAC;CACnB;AAED;;GAEG;AACH,qBAAa,OAAQ,SAAQ,gBAAgB;IAO9B,IAAI,EAAE,MAAM;IACZ,OAAO,EAAE;QAAE,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAAA;KAAE;IAP9C;;;;OAIG;gBAEQ,IAAI,EAAE,MAAM,EACZ,OAAO,EAAE;QAAE,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAAA;KAAE,EAC1C,QAAQ,GAAE,IAAI,EAAO,EACrB,IAAI,GACE,WAAW,CAAC,GAAG,GACf,WAAW,CAAC,MAAM,GAClB,WAAW,CAAC,KAIG;IAKzB;;;;OAIG;IACH,kBAAkB,CAAC,EAAE,qBAAqB,GAAG,IAAI,CAAC;IAIlD;;;OAGG;IACH,IAAI,OAAO,IAAI,MAAM,CAEpB;IAED,IAAI,OAAO,CAAC,IAAI,EAAE,MAAM,EAEvB;IAED,IAAI,UAAU,IAAI,SAAS,EAAE,CAO5B;IAED,uCAAuC;IACvC,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,kDAAkD;IAClD,oBAAoB,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAC9C,kEAAkE;IAClE,iBAAiB,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CAC9C;AAED;;;GAGG;AACH,wBAAgB,KAAK,CAAC,IAAI,EAAE,IAAI,GAAG,IAAI,IAAI,OAAO,CAEjD;AAED;;;GAGG;AACH,wBAAgB,OAAO,CAAC,IAAI,EAAE,IAAI,GAAG,IAAI,IAAI,gBAAgB,CAE5D;AAED;;;GAGG;AACH,wBAAgB,MAAM,CAAC,IAAI,EAAE,IAAI,GAAG,IAAI,IAAI,IAAI,CAE/C;AAED;;;GAGG;AACH,wBAAgB,SAAS,CAAC,IAAI,EAAE,IAAI,GAAG,IAAI,IAAI,QAAQ,CAEtD;AAED;;;GAGG;AACH,wBAAgB,WAAW,CAAC,IAAI,EAAE,IAAI,GAAG,IAAI,IAAI,qBAAqB,CAErE;AAED;;;GAGG;AACH,wBAAgB,UAAU,CAAC,IAAI,EAAE,IAAI,GAAG,IAAI,IAAI,QAAQ,CAEvD;AAED;;;GAGG;AACH,wBAAgB,WAAW,CAAC,IAAI,EAAE,IAAI,GAAG,IAAI,IAAI,gBAAgB,CAEhE;AAED;;;;;GAKG;AACH,wBAAgB,SAAS,CAAC,CAAC,SAAS,IAAI,EAAE,IAAI,EAAE,CAAC,EAAE,SAAS,UAAQ,GAAG,CAAC,CA4DvE"}

View file

@ -0,0 +1,444 @@
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.cloneNode = exports.hasChildren = exports.isDocument = exports.isDirective = exports.isComment = exports.isText = exports.isCDATA = exports.isTag = exports.Element = exports.Document = exports.NodeWithChildren = exports.ProcessingInstruction = exports.Comment = exports.Text = exports.DataNode = exports.Node = void 0;
var domelementtype_1 = require("domelementtype");
var nodeTypes = new Map([
[domelementtype_1.ElementType.Tag, 1],
[domelementtype_1.ElementType.Script, 1],
[domelementtype_1.ElementType.Style, 1],
[domelementtype_1.ElementType.Directive, 1],
[domelementtype_1.ElementType.Text, 3],
[domelementtype_1.ElementType.CDATA, 4],
[domelementtype_1.ElementType.Comment, 8],
[domelementtype_1.ElementType.Root, 9],
]);
/**
* This object will be used as the prototype for Nodes when creating a
* DOM-Level-1-compliant structure.
*/
var Node = /** @class */ (function () {
/**
*
* @param type The type of the node.
*/
function Node(type) {
this.type = type;
/** Parent of the node */
this.parent = null;
/** Previous sibling */
this.prev = null;
/** Next sibling */
this.next = null;
/** The start index of the node. Requires `withStartIndices` on the handler to be `true. */
this.startIndex = null;
/** The end index of the node. Requires `withEndIndices` on the handler to be `true. */
this.endIndex = null;
}
Object.defineProperty(Node.prototype, "nodeType", {
// Read-only aliases
/**
* [DOM spec](https://dom.spec.whatwg.org/#dom-node-nodetype)-compatible
* node {@link type}.
*/
get: function () {
var _a;
return (_a = nodeTypes.get(this.type)) !== null && _a !== void 0 ? _a : 1;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Node.prototype, "parentNode", {
// Read-write aliases for properties
/**
* Same as {@link parent}.
* [DOM spec](https://dom.spec.whatwg.org)-compatible alias.
*/
get: function () {
return this.parent;
},
set: function (parent) {
this.parent = parent;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Node.prototype, "previousSibling", {
/**
* Same as {@link prev}.
* [DOM spec](https://dom.spec.whatwg.org)-compatible alias.
*/
get: function () {
return this.prev;
},
set: function (prev) {
this.prev = prev;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Node.prototype, "nextSibling", {
/**
* Same as {@link next}.
* [DOM spec](https://dom.spec.whatwg.org)-compatible alias.
*/
get: function () {
return this.next;
},
set: function (next) {
this.next = next;
},
enumerable: false,
configurable: true
});
/**
* Clone this node, and optionally its children.
*
* @param recursive Clone child nodes as well.
* @returns A clone of the node.
*/
Node.prototype.cloneNode = function (recursive) {
if (recursive === void 0) { recursive = false; }
return cloneNode(this, recursive);
};
return Node;
}());
exports.Node = Node;
/**
* A node that contains some data.
*/
var DataNode = /** @class */ (function (_super) {
__extends(DataNode, _super);
/**
* @param type The type of the node
* @param data The content of the data node
*/
function DataNode(type, data) {
var _this = _super.call(this, type) || this;
_this.data = data;
return _this;
}
Object.defineProperty(DataNode.prototype, "nodeValue", {
/**
* Same as {@link data}.
* [DOM spec](https://dom.spec.whatwg.org)-compatible alias.
*/
get: function () {
return this.data;
},
set: function (data) {
this.data = data;
},
enumerable: false,
configurable: true
});
return DataNode;
}(Node));
exports.DataNode = DataNode;
/**
* Text within the document.
*/
var Text = /** @class */ (function (_super) {
__extends(Text, _super);
function Text(data) {
return _super.call(this, domelementtype_1.ElementType.Text, data) || this;
}
return Text;
}(DataNode));
exports.Text = Text;
/**
* Comments within the document.
*/
var Comment = /** @class */ (function (_super) {
__extends(Comment, _super);
function Comment(data) {
return _super.call(this, domelementtype_1.ElementType.Comment, data) || this;
}
return Comment;
}(DataNode));
exports.Comment = Comment;
/**
* Processing instructions, including doc types.
*/
var ProcessingInstruction = /** @class */ (function (_super) {
__extends(ProcessingInstruction, _super);
function ProcessingInstruction(name, data) {
var _this = _super.call(this, domelementtype_1.ElementType.Directive, data) || this;
_this.name = name;
return _this;
}
return ProcessingInstruction;
}(DataNode));
exports.ProcessingInstruction = ProcessingInstruction;
/**
* A `Node` that can have children.
*/
var NodeWithChildren = /** @class */ (function (_super) {
__extends(NodeWithChildren, _super);
/**
* @param type Type of the node.
* @param children Children of the node. Only certain node types can have children.
*/
function NodeWithChildren(type, children) {
var _this = _super.call(this, type) || this;
_this.children = children;
return _this;
}
Object.defineProperty(NodeWithChildren.prototype, "firstChild", {
// Aliases
/** First child of the node. */
get: function () {
var _a;
return (_a = this.children[0]) !== null && _a !== void 0 ? _a : null;
},
enumerable: false,
configurable: true
});
Object.defineProperty(NodeWithChildren.prototype, "lastChild", {
/** Last child of the node. */
get: function () {
return this.children.length > 0
? this.children[this.children.length - 1]
: null;
},
enumerable: false,
configurable: true
});
Object.defineProperty(NodeWithChildren.prototype, "childNodes", {
/**
* Same as {@link children}.
* [DOM spec](https://dom.spec.whatwg.org)-compatible alias.
*/
get: function () {
return this.children;
},
set: function (children) {
this.children = children;
},
enumerable: false,
configurable: true
});
return NodeWithChildren;
}(Node));
exports.NodeWithChildren = NodeWithChildren;
/**
* The root node of the document.
*/
var Document = /** @class */ (function (_super) {
__extends(Document, _super);
function Document(children) {
return _super.call(this, domelementtype_1.ElementType.Root, children) || this;
}
return Document;
}(NodeWithChildren));
exports.Document = Document;
/**
* An element within the DOM.
*/
var Element = /** @class */ (function (_super) {
__extends(Element, _super);
/**
* @param name Name of the tag, eg. `div`, `span`.
* @param attribs Object mapping attribute names to attribute values.
* @param children Children of the node.
*/
function Element(name, attribs, children, type) {
if (children === void 0) { children = []; }
if (type === void 0) { type = name === "script"
? domelementtype_1.ElementType.Script
: name === "style"
? domelementtype_1.ElementType.Style
: domelementtype_1.ElementType.Tag; }
var _this = _super.call(this, type, children) || this;
_this.name = name;
_this.attribs = attribs;
return _this;
}
Object.defineProperty(Element.prototype, "tagName", {
// DOM Level 1 aliases
/**
* Same as {@link name}.
* [DOM spec](https://dom.spec.whatwg.org)-compatible alias.
*/
get: function () {
return this.name;
},
set: function (name) {
this.name = name;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Element.prototype, "attributes", {
get: function () {
var _this = this;
return Object.keys(this.attribs).map(function (name) {
var _a, _b;
return ({
name: name,
value: _this.attribs[name],
namespace: (_a = _this["x-attribsNamespace"]) === null || _a === void 0 ? void 0 : _a[name],
prefix: (_b = _this["x-attribsPrefix"]) === null || _b === void 0 ? void 0 : _b[name],
});
});
},
enumerable: false,
configurable: true
});
return Element;
}(NodeWithChildren));
exports.Element = Element;
/**
* @param node Node to check.
* @returns `true` if the node is a `Element`, `false` otherwise.
*/
function isTag(node) {
return (0, domelementtype_1.isTag)(node);
}
exports.isTag = isTag;
/**
* @param node Node to check.
* @returns `true` if the node has the type `CDATA`, `false` otherwise.
*/
function isCDATA(node) {
return node.type === domelementtype_1.ElementType.CDATA;
}
exports.isCDATA = isCDATA;
/**
* @param node Node to check.
* @returns `true` if the node has the type `Text`, `false` otherwise.
*/
function isText(node) {
return node.type === domelementtype_1.ElementType.Text;
}
exports.isText = isText;
/**
* @param node Node to check.
* @returns `true` if the node has the type `Comment`, `false` otherwise.
*/
function isComment(node) {
return node.type === domelementtype_1.ElementType.Comment;
}
exports.isComment = isComment;
/**
* @param node Node to check.
* @returns `true` if the node has the type `ProcessingInstruction`, `false` otherwise.
*/
function isDirective(node) {
return node.type === domelementtype_1.ElementType.Directive;
}
exports.isDirective = isDirective;
/**
* @param node Node to check.
* @returns `true` if the node has the type `ProcessingInstruction`, `false` otherwise.
*/
function isDocument(node) {
return node.type === domelementtype_1.ElementType.Root;
}
exports.isDocument = isDocument;
/**
* @param node Node to check.
* @returns `true` if the node is a `NodeWithChildren` (has children), `false` otherwise.
*/
function hasChildren(node) {
return Object.prototype.hasOwnProperty.call(node, "children");
}
exports.hasChildren = hasChildren;
/**
* Clone a node, and optionally its children.
*
* @param recursive Clone child nodes as well.
* @returns A clone of the node.
*/
function cloneNode(node, recursive) {
if (recursive === void 0) { recursive = false; }
var result;
if (isText(node)) {
result = new Text(node.data);
}
else if (isComment(node)) {
result = new Comment(node.data);
}
else if (isTag(node)) {
var children = recursive ? cloneChildren(node.children) : [];
var clone_1 = new Element(node.name, __assign({}, node.attribs), children);
children.forEach(function (child) { return (child.parent = clone_1); });
if (node.namespace != null) {
clone_1.namespace = node.namespace;
}
if (node["x-attribsNamespace"]) {
clone_1["x-attribsNamespace"] = __assign({}, node["x-attribsNamespace"]);
}
if (node["x-attribsPrefix"]) {
clone_1["x-attribsPrefix"] = __assign({}, node["x-attribsPrefix"]);
}
result = clone_1;
}
else if (isCDATA(node)) {
var children = recursive ? cloneChildren(node.children) : [];
var clone_2 = new NodeWithChildren(domelementtype_1.ElementType.CDATA, children);
children.forEach(function (child) { return (child.parent = clone_2); });
result = clone_2;
}
else if (isDocument(node)) {
var children = recursive ? cloneChildren(node.children) : [];
var clone_3 = new Document(children);
children.forEach(function (child) { return (child.parent = clone_3); });
if (node["x-mode"]) {
clone_3["x-mode"] = node["x-mode"];
}
result = clone_3;
}
else if (isDirective(node)) {
var instruction = new ProcessingInstruction(node.name, node.data);
if (node["x-name"] != null) {
instruction["x-name"] = node["x-name"];
instruction["x-publicId"] = node["x-publicId"];
instruction["x-systemId"] = node["x-systemId"];
}
result = instruction;
}
else {
throw new Error("Not implemented yet: ".concat(node.type));
}
result.startIndex = node.startIndex;
result.endIndex = node.endIndex;
if (node.sourceCodeLocation != null) {
result.sourceCodeLocation = node.sourceCodeLocation;
}
return result;
}
exports.cloneNode = cloneNode;
function cloneChildren(childs) {
var children = childs.map(function (child) { return cloneNode(child, true); });
for (var i = 1; i < children.length; i++) {
children[i].prev = children[i - 1];
children[i - 1].next = children[i];
}
return children;
}

View file

@ -0,0 +1,58 @@
{
"name": "domhandler",
"version": "4.3.1",
"description": "Handler for htmlparser2 that turns pages into a dom",
"author": "Felix Boehm <me@feedic.com>",
"funding": {
"url": "https://github.com/fb55/domhandler?sponsor=1"
},
"license": "BSD-2-Clause",
"main": "lib/index.js",
"types": "lib/index.d.ts",
"sideEffects": false,
"files": [
"lib"
],
"scripts": {
"test": "npm run test:jest && npm run lint",
"test:jest": "jest",
"lint": "eslint src",
"format": "prettier --write '**/*.{ts,md,json}'",
"build": "tsc",
"prepare": "npm run build"
},
"repository": {
"type": "git",
"url": "git://github.com/fb55/domhandler.git"
},
"keywords": [
"dom",
"htmlparser2"
],
"engines": {
"node": ">= 4"
},
"dependencies": {
"domelementtype": "^2.2.0"
},
"devDependencies": {
"@types/jest": "^27.4.1",
"@types/node": "^17.0.21",
"@typescript-eslint/eslint-plugin": "^5.15.0",
"@typescript-eslint/parser": "^5.15.0",
"eslint": "^8.11.0",
"eslint-config-prettier": "^8.5.0",
"htmlparser2": "^7.2.0",
"jest": "^27.5.1",
"prettier": "^2.6.0",
"ts-jest": "^27.1.3",
"typescript": "^4.6.2"
},
"jest": {
"preset": "ts-jest",
"testEnvironment": "node"
},
"prettier": {
"tabWidth": 4
}
}

View file

@ -0,0 +1,163 @@
# domhandler [![Build Status](https://travis-ci.com/fb55/domhandler.svg?branch=master)](https://travis-ci.com/fb55/domhandler)
The DOM handler creates a tree containing all nodes of a page.
The tree can be manipulated using the [domutils](https://github.com/fb55/domutils)
or [cheerio](https://github.com/cheeriojs/cheerio) libraries and
rendered using [dom-serializer](https://github.com/cheeriojs/dom-serializer) .
## Usage
```javascript
const handler = new DomHandler([ <func> callback(err, dom), ] [ <obj> options ]);
// const parser = new Parser(handler[, options]);
```
Available options are described below.
## Example
```javascript
const { Parser } = require("htmlparser2");
const { DomHandler } = require("domhandler");
const rawHtml =
"Xyz <script language= javascript>var foo = '<<bar>>';</script><!--<!-- Waah! -- -->";
const handler = new DomHandler((error, dom) => {
if (error) {
// Handle error
} else {
// Parsing completed, do something
console.log(dom);
}
});
const parser = new Parser(handler);
parser.write(rawHtml);
parser.end();
```
Output:
```javascript
[
{
data: "Xyz ",
type: "text",
},
{
type: "script",
name: "script",
attribs: {
language: "javascript",
},
children: [
{
data: "var foo = '<bar>';<",
type: "text",
},
],
},
{
data: "<!-- Waah! -- ",
type: "comment",
},
];
```
## Option: `withStartIndices`
Add a `startIndex` property to nodes.
When the parser is used in a non-streaming fashion, `startIndex` is an integer
indicating the position of the start of the node in the document.
The default value is `false`.
## Option: `withEndIndices`
Add an `endIndex` property to nodes.
When the parser is used in a non-streaming fashion, `endIndex` is an integer
indicating the position of the end of the node in the document.
The default value is `false`.
## Option: `normalizeWhitespace` _(deprecated)_
Replace all whitespace with single spaces.
The default value is `false`.
**Note:** Enabling this might break your markup.
For the following examples, this HTML will be used:
```html
<font> <br />this is the text <font></font></font>
```
### Example: `normalizeWhitespace: true`
```javascript
[
{
type: "tag",
name: "font",
children: [
{
data: " ",
type: "text",
},
{
type: "tag",
name: "br",
},
{
data: "this is the text ",
type: "text",
},
{
type: "tag",
name: "font",
},
],
},
];
```
### Example: `normalizeWhitespace: false`
```javascript
[
{
type: "tag",
name: "font",
children: [
{
data: "\n\t",
type: "text",
},
{
type: "tag",
name: "br",
},
{
data: "this is the text\n",
type: "text",
},
{
type: "tag",
name: "font",
},
],
},
];
```
---
License: BSD-2-Clause
## Security contact information
To report a security vulnerability, please use the [Tidelift security contact](https://tidelift.com/security).
Tidelift will coordinate the fix and disclosure.
## `domhandler` for enterprise
Available as part of the Tidelift Subscription
The maintainers of `domhandler` and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-domhandler?utm_source=npm-domhandler&utm_medium=referral&utm_campaign=enterprise&utm_term=repo)

View file

@ -0,0 +1,11 @@
Copyright (c) Felix Böhm
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
THIS IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

View file

@ -0,0 +1,45 @@
import type { Node } from "domhandler";
export declare type FeedItemMediaMedium = "image" | "audio" | "video" | "document" | "executable";
export declare type FeedItemMediaExpression = "sample" | "full" | "nonstop";
export interface FeedItemMedia {
medium: FeedItemMediaMedium | undefined;
isDefault: boolean;
url?: string;
fileSize?: number;
type?: string;
expression?: FeedItemMediaExpression;
bitrate?: number;
framerate?: number;
samplingrate?: number;
channels?: number;
duration?: number;
height?: number;
width?: number;
lang?: string;
}
export interface FeedItem {
id?: string;
title?: string;
link?: string;
description?: string;
pubDate?: Date;
media: FeedItemMedia[];
}
export interface Feed {
type: string;
id?: string;
title?: string;
link?: string;
description?: string;
updated?: Date;
author?: string;
items: FeedItem[];
}
/**
* Get the feed object from the root of a DOM tree.
*
* @param doc - The DOM to to extract the feed from.
* @returns The feed.
*/
export declare function getFeed(doc: Node[]): Feed | null;
//# sourceMappingURL=feeds.d.ts.map

View file

@ -0,0 +1 @@
{"version":3,"file":"feeds.d.ts","sourceRoot":"","sources":["../src/feeds.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAW,MAAM,YAAY,CAAC;AAIhD,oBAAY,mBAAmB,GACzB,OAAO,GACP,OAAO,GACP,OAAO,GACP,UAAU,GACV,YAAY,CAAC;AAEnB,oBAAY,uBAAuB,GAAG,QAAQ,GAAG,MAAM,GAAG,SAAS,CAAC;AAEpE,MAAM,WAAW,aAAa;IAC1B,MAAM,EAAE,mBAAmB,GAAG,SAAS,CAAC;IACxC,SAAS,EAAE,OAAO,CAAC;IACnB,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,UAAU,CAAC,EAAE,uBAAuB,CAAC;IACrC,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,IAAI,CAAC,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,WAAW,QAAQ;IACrB,EAAE,CAAC,EAAE,MAAM,CAAC;IACZ,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,OAAO,CAAC,EAAE,IAAI,CAAC;IACf,KAAK,EAAE,aAAa,EAAE,CAAC;CAC1B;AAED,MAAM,WAAW,IAAI;IACjB,IAAI,EAAE,MAAM,CAAC;IACb,EAAE,CAAC,EAAE,MAAM,CAAC;IACZ,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,OAAO,CAAC,EAAE,IAAI,CAAC;IACf,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,KAAK,EAAE,QAAQ,EAAE,CAAC;CACrB;AAED;;;;;GAKG;AACH,wBAAgB,OAAO,CAAC,GAAG,EAAE,IAAI,EAAE,GAAG,IAAI,GAAG,IAAI,CAQhD"}

View file

@ -0,0 +1,190 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getFeed = void 0;
var stringify_1 = require("./stringify");
var legacy_1 = require("./legacy");
/**
* Get the feed object from the root of a DOM tree.
*
* @param doc - The DOM to to extract the feed from.
* @returns The feed.
*/
function getFeed(doc) {
var feedRoot = getOneElement(isValidFeed, doc);
return !feedRoot
? null
: feedRoot.name === "feed"
? getAtomFeed(feedRoot)
: getRssFeed(feedRoot);
}
exports.getFeed = getFeed;
/**
* Parse an Atom feed.
*
* @param feedRoot The root of the feed.
* @returns The parsed feed.
*/
function getAtomFeed(feedRoot) {
var _a;
var childs = feedRoot.children;
var feed = {
type: "atom",
items: (0, legacy_1.getElementsByTagName)("entry", childs).map(function (item) {
var _a;
var children = item.children;
var entry = { media: getMediaElements(children) };
addConditionally(entry, "id", "id", children);
addConditionally(entry, "title", "title", children);
var href = (_a = getOneElement("link", children)) === null || _a === void 0 ? void 0 : _a.attribs.href;
if (href) {
entry.link = href;
}
var description = fetch("summary", children) || fetch("content", children);
if (description) {
entry.description = description;
}
var pubDate = fetch("updated", children);
if (pubDate) {
entry.pubDate = new Date(pubDate);
}
return entry;
}),
};
addConditionally(feed, "id", "id", childs);
addConditionally(feed, "title", "title", childs);
var href = (_a = getOneElement("link", childs)) === null || _a === void 0 ? void 0 : _a.attribs.href;
if (href) {
feed.link = href;
}
addConditionally(feed, "description", "subtitle", childs);
var updated = fetch("updated", childs);
if (updated) {
feed.updated = new Date(updated);
}
addConditionally(feed, "author", "email", childs, true);
return feed;
}
/**
* Parse a RSS feed.
*
* @param feedRoot The root of the feed.
* @returns The parsed feed.
*/
function getRssFeed(feedRoot) {
var _a, _b;
var childs = (_b = (_a = getOneElement("channel", feedRoot.children)) === null || _a === void 0 ? void 0 : _a.children) !== null && _b !== void 0 ? _b : [];
var feed = {
type: feedRoot.name.substr(0, 3),
id: "",
items: (0, legacy_1.getElementsByTagName)("item", feedRoot.children).map(function (item) {
var children = item.children;
var entry = { media: getMediaElements(children) };
addConditionally(entry, "id", "guid", children);
addConditionally(entry, "title", "title", children);
addConditionally(entry, "link", "link", children);
addConditionally(entry, "description", "description", children);
var pubDate = fetch("pubDate", children);
if (pubDate)
entry.pubDate = new Date(pubDate);
return entry;
}),
};
addConditionally(feed, "title", "title", childs);
addConditionally(feed, "link", "link", childs);
addConditionally(feed, "description", "description", childs);
var updated = fetch("lastBuildDate", childs);
if (updated) {
feed.updated = new Date(updated);
}
addConditionally(feed, "author", "managingEditor", childs, true);
return feed;
}
var MEDIA_KEYS_STRING = ["url", "type", "lang"];
var MEDIA_KEYS_INT = [
"fileSize",
"bitrate",
"framerate",
"samplingrate",
"channels",
"duration",
"height",
"width",
];
/**
* Get all media elements of a feed item.
*
* @param where Nodes to search in.
* @returns Media elements.
*/
function getMediaElements(where) {
return (0, legacy_1.getElementsByTagName)("media:content", where).map(function (elem) {
var attribs = elem.attribs;
var media = {
medium: attribs.medium,
isDefault: !!attribs.isDefault,
};
for (var _i = 0, MEDIA_KEYS_STRING_1 = MEDIA_KEYS_STRING; _i < MEDIA_KEYS_STRING_1.length; _i++) {
var attrib = MEDIA_KEYS_STRING_1[_i];
if (attribs[attrib]) {
media[attrib] = attribs[attrib];
}
}
for (var _a = 0, MEDIA_KEYS_INT_1 = MEDIA_KEYS_INT; _a < MEDIA_KEYS_INT_1.length; _a++) {
var attrib = MEDIA_KEYS_INT_1[_a];
if (attribs[attrib]) {
media[attrib] = parseInt(attribs[attrib], 10);
}
}
if (attribs.expression) {
media.expression =
attribs.expression;
}
return media;
});
}
/**
* Get one element by tag name.
*
* @param tagName Tag name to look for
* @param node Node to search in
* @returns The element or null
*/
function getOneElement(tagName, node) {
return (0, legacy_1.getElementsByTagName)(tagName, node, true, 1)[0];
}
/**
* Get the text content of an element with a certain tag name.
*
* @param tagName Tag name to look for.
* @param where Node to search in.
* @param recurse Whether to recurse into child nodes.
* @returns The text content of the element.
*/
function fetch(tagName, where, recurse) {
if (recurse === void 0) { recurse = false; }
return (0, stringify_1.textContent)((0, legacy_1.getElementsByTagName)(tagName, where, recurse, 1)).trim();
}
/**
* Adds a property to an object if it has a value.
*
* @param obj Object to be extended
* @param prop Property name
* @param tagName Tag name that contains the conditionally added property
* @param where Element to search for the property
* @param recurse Whether to recurse into child nodes.
*/
function addConditionally(obj, prop, tagName, where, recurse) {
if (recurse === void 0) { recurse = false; }
var val = fetch(tagName, where, recurse);
if (val)
obj[prop] = val;
}
/**
* Checks if an element is a feed root node.
*
* @param value The name of the element to check.
* @returns Whether an element is a feed root node.
*/
function isValidFeed(value) {
return value === "rss" || value === "feed" || value === "rdf:RDF";
}

View file

@ -0,0 +1,51 @@
import { Node } from "domhandler";
/**
* Given an array of nodes, remove any member that is contained by another.
*
* @param nodes Nodes to filter.
* @returns Remaining nodes that aren't subtrees of each other.
*/
export declare function removeSubsets(nodes: Node[]): Node[];
export declare const enum DocumentPosition {
DISCONNECTED = 1,
PRECEDING = 2,
FOLLOWING = 4,
CONTAINS = 8,
CONTAINED_BY = 16
}
/**
* Compare the position of one node against another node in any other document.
* The return value is a bitmask with the following values:
*
* Document order:
* > There is an ordering, document order, defined on all the nodes in the
* > document corresponding to the order in which the first character of the
* > XML representation of each node occurs in the XML representation of the
* > document after expansion of general entities. Thus, the document element
* > node will be the first node. Element nodes occur before their children.
* > Thus, document order orders element nodes in order of the occurrence of
* > their start-tag in the XML (after expansion of entities). The attribute
* > nodes of an element occur after the element and before its children. The
* > relative order of attribute nodes is implementation-dependent./
*
* Source:
* http://www.w3.org/TR/DOM-Level-3-Core/glossary.html#dt-document-order
*
* @param nodeA The first node to use in the comparison
* @param nodeB The second node to use in the comparison
* @returns A bitmask describing the input nodes' relative position.
*
* See http://dom.spec.whatwg.org/#dom-node-comparedocumentposition for
* a description of these values.
*/
export declare function compareDocumentPosition(nodeA: Node, nodeB: Node): number;
/**
* Sort an array of nodes based on their relative position in the document and
* remove any duplicate nodes. If the array contains nodes that do not belong
* to the same document, sort order is unspecified.
*
* @param nodes Array of DOM nodes.
* @returns Collection of unique nodes, sorted in document order.
*/
export declare function uniqueSort<T extends Node>(nodes: T[]): T[];
//# sourceMappingURL=helpers.d.ts.map

View file

@ -0,0 +1 @@
{"version":3,"file":"helpers.d.ts","sourceRoot":"","sources":["../src/helpers.ts"],"names":[],"mappings":"AAAA,OAAO,EAAe,IAAI,EAAE,MAAM,YAAY,CAAC;AAE/C;;;;;GAKG;AACH,wBAAgB,aAAa,CAAC,KAAK,EAAE,IAAI,EAAE,GAAG,IAAI,EAAE,CA6BnD;AAGD,0BAAkB,gBAAgB;IAC9B,YAAY,IAAI;IAChB,SAAS,IAAI;IACb,SAAS,IAAI;IACb,QAAQ,IAAI;IACZ,YAAY,KAAK;CACpB;AAED;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,wBAAgB,uBAAuB,CAAC,KAAK,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,GAAG,MAAM,CA4CxE;AAED;;;;;;;GAOG;AACH,wBAAgB,UAAU,CAAC,CAAC,SAAS,IAAI,EAAE,KAAK,EAAE,CAAC,EAAE,GAAG,CAAC,EAAE,CAc1D"}

View file

@ -0,0 +1,125 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.uniqueSort = exports.compareDocumentPosition = exports.removeSubsets = void 0;
var domhandler_1 = require("domhandler");
/**
* Given an array of nodes, remove any member that is contained by another.
*
* @param nodes Nodes to filter.
* @returns Remaining nodes that aren't subtrees of each other.
*/
function removeSubsets(nodes) {
var idx = nodes.length;
/*
* Check if each node (or one of its ancestors) is already contained in the
* array.
*/
while (--idx >= 0) {
var node = nodes[idx];
/*
* Remove the node if it is not unique.
* We are going through the array from the end, so we only
* have to check nodes that preceed the node under consideration in the array.
*/
if (idx > 0 && nodes.lastIndexOf(node, idx - 1) >= 0) {
nodes.splice(idx, 1);
continue;
}
for (var ancestor = node.parent; ancestor; ancestor = ancestor.parent) {
if (nodes.includes(ancestor)) {
nodes.splice(idx, 1);
break;
}
}
}
return nodes;
}
exports.removeSubsets = removeSubsets;
/**
* Compare the position of one node against another node in any other document.
* The return value is a bitmask with the following values:
*
* Document order:
* > There is an ordering, document order, defined on all the nodes in the
* > document corresponding to the order in which the first character of the
* > XML representation of each node occurs in the XML representation of the
* > document after expansion of general entities. Thus, the document element
* > node will be the first node. Element nodes occur before their children.
* > Thus, document order orders element nodes in order of the occurrence of
* > their start-tag in the XML (after expansion of entities). The attribute
* > nodes of an element occur after the element and before its children. The
* > relative order of attribute nodes is implementation-dependent./
*
* Source:
* http://www.w3.org/TR/DOM-Level-3-Core/glossary.html#dt-document-order
*
* @param nodeA The first node to use in the comparison
* @param nodeB The second node to use in the comparison
* @returns A bitmask describing the input nodes' relative position.
*
* See http://dom.spec.whatwg.org/#dom-node-comparedocumentposition for
* a description of these values.
*/
function compareDocumentPosition(nodeA, nodeB) {
var aParents = [];
var bParents = [];
if (nodeA === nodeB) {
return 0;
}
var current = (0, domhandler_1.hasChildren)(nodeA) ? nodeA : nodeA.parent;
while (current) {
aParents.unshift(current);
current = current.parent;
}
current = (0, domhandler_1.hasChildren)(nodeB) ? nodeB : nodeB.parent;
while (current) {
bParents.unshift(current);
current = current.parent;
}
var maxIdx = Math.min(aParents.length, bParents.length);
var idx = 0;
while (idx < maxIdx && aParents[idx] === bParents[idx]) {
idx++;
}
if (idx === 0) {
return 1 /* DISCONNECTED */;
}
var sharedParent = aParents[idx - 1];
var siblings = sharedParent.children;
var aSibling = aParents[idx];
var bSibling = bParents[idx];
if (siblings.indexOf(aSibling) > siblings.indexOf(bSibling)) {
if (sharedParent === nodeB) {
return 4 /* FOLLOWING */ | 16 /* CONTAINED_BY */;
}
return 4 /* FOLLOWING */;
}
if (sharedParent === nodeA) {
return 2 /* PRECEDING */ | 8 /* CONTAINS */;
}
return 2 /* PRECEDING */;
}
exports.compareDocumentPosition = compareDocumentPosition;
/**
* Sort an array of nodes based on their relative position in the document and
* remove any duplicate nodes. If the array contains nodes that do not belong
* to the same document, sort order is unspecified.
*
* @param nodes Array of DOM nodes.
* @returns Collection of unique nodes, sorted in document order.
*/
function uniqueSort(nodes) {
nodes = nodes.filter(function (node, i, arr) { return !arr.includes(node, i + 1); });
nodes.sort(function (a, b) {
var relative = compareDocumentPosition(a, b);
if (relative & 2 /* PRECEDING */) {
return -1;
}
else if (relative & 4 /* FOLLOWING */) {
return 1;
}
return 0;
});
return nodes;
}
exports.uniqueSort = uniqueSort;

View file

@ -0,0 +1,10 @@
export * from "./stringify";
export * from "./traversal";
export * from "./manipulation";
export * from "./querying";
export * from "./legacy";
export * from "./helpers";
export * from "./feeds";
/** @deprecated Use these methods from `domhandler` directly. */
export { isTag, isCDATA, isText, isComment, isDocument, hasChildren, } from "domhandler";
//# sourceMappingURL=index.d.ts.map

View file

@ -0,0 +1 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,aAAa,CAAC;AAC5B,cAAc,aAAa,CAAC;AAC5B,cAAc,gBAAgB,CAAC;AAC/B,cAAc,YAAY,CAAC;AAC3B,cAAc,UAAU,CAAC;AACzB,cAAc,WAAW,CAAC;AAC1B,cAAc,SAAS,CAAC;AACxB,gEAAgE;AAChE,OAAO,EACH,KAAK,EACL,OAAO,EACP,MAAM,EACN,SAAS,EACT,UAAU,EACV,WAAW,GACd,MAAM,YAAY,CAAC"}

View file

@ -0,0 +1,28 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.hasChildren = exports.isDocument = exports.isComment = exports.isText = exports.isCDATA = exports.isTag = void 0;
__exportStar(require("./stringify"), exports);
__exportStar(require("./traversal"), exports);
__exportStar(require("./manipulation"), exports);
__exportStar(require("./querying"), exports);
__exportStar(require("./legacy"), exports);
__exportStar(require("./helpers"), exports);
__exportStar(require("./feeds"), exports);
/** @deprecated Use these methods from `domhandler` directly. */
var domhandler_1 = require("domhandler");
Object.defineProperty(exports, "isTag", { enumerable: true, get: function () { return domhandler_1.isTag; } });
Object.defineProperty(exports, "isCDATA", { enumerable: true, get: function () { return domhandler_1.isCDATA; } });
Object.defineProperty(exports, "isText", { enumerable: true, get: function () { return domhandler_1.isText; } });
Object.defineProperty(exports, "isComment", { enumerable: true, get: function () { return domhandler_1.isComment; } });
Object.defineProperty(exports, "isDocument", { enumerable: true, get: function () { return domhandler_1.isDocument; } });
Object.defineProperty(exports, "hasChildren", { enumerable: true, get: function () { return domhandler_1.hasChildren; } });

View file

@ -0,0 +1,47 @@
import { Node, Element } from "domhandler";
import { ElementType } from "domelementtype";
interface TestElementOpts {
tag_name?: string | ((name: string) => boolean);
tag_type?: string | ((name: string) => boolean);
tag_contains?: string | ((data?: string) => boolean);
[attributeName: string]: undefined | string | ((attributeValue: string) => boolean);
}
/**
* @param options An object describing nodes to look for.
* @param node The element to test.
* @returns Whether the element matches the description in `options`.
*/
export declare function testElement(options: TestElementOpts, node: Node): boolean;
/**
* @param options An object describing nodes to look for.
* @param nodes Nodes to search through.
* @param recurse Also consider child nodes.
* @param limit Maximum number of nodes to return.
* @returns All nodes that match `options`.
*/
export declare function getElements(options: TestElementOpts, nodes: Node | Node[], recurse: boolean, limit?: number): Node[];
/**
* @param id The unique ID attribute value to look for.
* @param nodes Nodes to search through.
* @param recurse Also consider child nodes.
* @returns The node with the supplied ID.
*/
export declare function getElementById(id: string | ((id: string) => boolean), nodes: Node | Node[], recurse?: boolean): Element | null;
/**
* @param tagName Tag name to search for.
* @param nodes Nodes to search through.
* @param recurse Also consider child nodes.
* @param limit Maximum number of nodes to return.
* @returns All nodes with the supplied `tagName`.
*/
export declare function getElementsByTagName(tagName: string | ((name: string) => boolean), nodes: Node | Node[], recurse?: boolean, limit?: number): Element[];
/**
* @param type Element type to look for.
* @param nodes Nodes to search through.
* @param recurse Also consider child nodes.
* @param limit Maximum number of nodes to return.
* @returns All nodes with the supplied `type`.
*/
export declare function getElementsByTagType(type: ElementType | ((type: ElementType) => boolean), nodes: Node | Node[], recurse?: boolean, limit?: number): Node[];
export {};
//# sourceMappingURL=legacy.d.ts.map

View file

@ -0,0 +1 @@
{"version":3,"file":"legacy.d.ts","sourceRoot":"","sources":["../src/legacy.ts"],"names":[],"mappings":"AAAA,OAAO,EAAiB,IAAI,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAC1D,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAK7C,UAAU,eAAe;IACrB,QAAQ,CAAC,EAAE,MAAM,GAAG,CAAC,CAAC,IAAI,EAAE,MAAM,KAAK,OAAO,CAAC,CAAC;IAChD,QAAQ,CAAC,EAAE,MAAM,GAAG,CAAC,CAAC,IAAI,EAAE,MAAM,KAAK,OAAO,CAAC,CAAC;IAChD,YAAY,CAAC,EAAE,MAAM,GAAG,CAAC,CAAC,IAAI,CAAC,EAAE,MAAM,KAAK,OAAO,CAAC,CAAC;IACrD,CAAC,aAAa,EAAE,MAAM,GAChB,SAAS,GACT,MAAM,GACN,CAAC,CAAC,cAAc,EAAE,MAAM,KAAK,OAAO,CAAC,CAAC;CAC/C;AAqED;;;;GAIG;AACH,wBAAgB,WAAW,CAAC,OAAO,EAAE,eAAe,EAAE,IAAI,EAAE,IAAI,GAAG,OAAO,CAGzE;AAED;;;;;;GAMG;AACH,wBAAgB,WAAW,CACvB,OAAO,EAAE,eAAe,EACxB,KAAK,EAAE,IAAI,GAAG,IAAI,EAAE,EACpB,OAAO,EAAE,OAAO,EAChB,KAAK,SAAW,GACjB,IAAI,EAAE,CAGR;AAED;;;;;GAKG;AACH,wBAAgB,cAAc,CAC1B,EAAE,EAAE,MAAM,GAAG,CAAC,CAAC,EAAE,EAAE,MAAM,KAAK,OAAO,CAAC,EACtC,KAAK,EAAE,IAAI,GAAG,IAAI,EAAE,EACpB,OAAO,UAAO,GACf,OAAO,GAAG,IAAI,CAGhB;AAED;;;;;;GAMG;AACH,wBAAgB,oBAAoB,CAChC,OAAO,EAAE,MAAM,GAAG,CAAC,CAAC,IAAI,EAAE,MAAM,KAAK,OAAO,CAAC,EAC7C,KAAK,EAAE,IAAI,GAAG,IAAI,EAAE,EACpB,OAAO,UAAO,EACd,KAAK,SAAW,GACjB,OAAO,EAAE,CAEX;AAED;;;;;;GAMG;AACH,wBAAgB,oBAAoB,CAChC,IAAI,EAAE,WAAW,GAAG,CAAC,CAAC,IAAI,EAAE,WAAW,KAAK,OAAO,CAAC,EACpD,KAAK,EAAE,IAAI,GAAG,IAAI,EAAE,EACpB,OAAO,UAAO,EACd,KAAK,SAAW,GACjB,IAAI,EAAE,CAER"}

View file

@ -0,0 +1,124 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getElementsByTagType = exports.getElementsByTagName = exports.getElementById = exports.getElements = exports.testElement = void 0;
var domhandler_1 = require("domhandler");
var querying_1 = require("./querying");
var Checks = {
tag_name: function (name) {
if (typeof name === "function") {
return function (elem) { return (0, domhandler_1.isTag)(elem) && name(elem.name); };
}
else if (name === "*") {
return domhandler_1.isTag;
}
return function (elem) { return (0, domhandler_1.isTag)(elem) && elem.name === name; };
},
tag_type: function (type) {
if (typeof type === "function") {
return function (elem) { return type(elem.type); };
}
return function (elem) { return elem.type === type; };
},
tag_contains: function (data) {
if (typeof data === "function") {
return function (elem) { return (0, domhandler_1.isText)(elem) && data(elem.data); };
}
return function (elem) { return (0, domhandler_1.isText)(elem) && elem.data === data; };
},
};
/**
* @param attrib Attribute to check.
* @param value Attribute value to look for.
* @returns A function to check whether the a node has an attribute with a particular value.
*/
function getAttribCheck(attrib, value) {
if (typeof value === "function") {
return function (elem) { return (0, domhandler_1.isTag)(elem) && value(elem.attribs[attrib]); };
}
return function (elem) { return (0, domhandler_1.isTag)(elem) && elem.attribs[attrib] === value; };
}
/**
* @param a First function to combine.
* @param b Second function to combine.
* @returns A function taking a node and returning `true` if either
* of the input functions returns `true` for the node.
*/
function combineFuncs(a, b) {
return function (elem) { return a(elem) || b(elem); };
}
/**
* @param options An object describing nodes to look for.
* @returns A function executing all checks in `options` and returning `true`
* if any of them match a node.
*/
function compileTest(options) {
var funcs = Object.keys(options).map(function (key) {
var value = options[key];
return Object.prototype.hasOwnProperty.call(Checks, key)
? Checks[key](value)
: getAttribCheck(key, value);
});
return funcs.length === 0 ? null : funcs.reduce(combineFuncs);
}
/**
* @param options An object describing nodes to look for.
* @param node The element to test.
* @returns Whether the element matches the description in `options`.
*/
function testElement(options, node) {
var test = compileTest(options);
return test ? test(node) : true;
}
exports.testElement = testElement;
/**
* @param options An object describing nodes to look for.
* @param nodes Nodes to search through.
* @param recurse Also consider child nodes.
* @param limit Maximum number of nodes to return.
* @returns All nodes that match `options`.
*/
function getElements(options, nodes, recurse, limit) {
if (limit === void 0) { limit = Infinity; }
var test = compileTest(options);
return test ? (0, querying_1.filter)(test, nodes, recurse, limit) : [];
}
exports.getElements = getElements;
/**
* @param id The unique ID attribute value to look for.
* @param nodes Nodes to search through.
* @param recurse Also consider child nodes.
* @returns The node with the supplied ID.
*/
function getElementById(id, nodes, recurse) {
if (recurse === void 0) { recurse = true; }
if (!Array.isArray(nodes))
nodes = [nodes];
return (0, querying_1.findOne)(getAttribCheck("id", id), nodes, recurse);
}
exports.getElementById = getElementById;
/**
* @param tagName Tag name to search for.
* @param nodes Nodes to search through.
* @param recurse Also consider child nodes.
* @param limit Maximum number of nodes to return.
* @returns All nodes with the supplied `tagName`.
*/
function getElementsByTagName(tagName, nodes, recurse, limit) {
if (recurse === void 0) { recurse = true; }
if (limit === void 0) { limit = Infinity; }
return (0, querying_1.filter)(Checks.tag_name(tagName), nodes, recurse, limit);
}
exports.getElementsByTagName = getElementsByTagName;
/**
* @param type Element type to look for.
* @param nodes Nodes to search through.
* @param recurse Also consider child nodes.
* @param limit Maximum number of nodes to return.
* @returns All nodes with the supplied `type`.
*/
function getElementsByTagType(type, nodes, recurse, limit) {
if (recurse === void 0) { recurse = true; }
if (limit === void 0) { limit = Infinity; }
return (0, querying_1.filter)(Checks.tag_type(type), nodes, recurse, limit);
}
exports.getElementsByTagType = getElementsByTagType;

View file

@ -0,0 +1,43 @@
import type { Node, Element } from "domhandler";
/**
* Remove an element from the dom
*
* @param elem The element to be removed
*/
export declare function removeElement(elem: Node): void;
/**
* Replace an element in the dom
*
* @param elem The element to be replaced
* @param replacement The element to be added
*/
export declare function replaceElement(elem: Node, replacement: Node): void;
/**
* Append a child to an element.
*
* @param elem The element to append to.
* @param child The element to be added as a child.
*/
export declare function appendChild(elem: Element, child: Node): void;
/**
* Append an element after another.
*
* @param elem The element to append after.
* @param next The element be added.
*/
export declare function append(elem: Node, next: Node): void;
/**
* Prepend a child to an element.
*
* @param elem The element to prepend before.
* @param child The element to be added as a child.
*/
export declare function prependChild(elem: Element, child: Node): void;
/**
* Prepend an element before another.
*
* @param elem The element to prepend before.
* @param prev The element be added.
*/
export declare function prepend(elem: Node, prev: Node): void;
//# sourceMappingURL=manipulation.d.ts.map

View file

@ -0,0 +1 @@
{"version":3,"file":"manipulation.d.ts","sourceRoot":"","sources":["../src/manipulation.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAEhD;;;;GAIG;AACH,wBAAgB,aAAa,CAAC,IAAI,EAAE,IAAI,GAAG,IAAI,CAQ9C;AAED;;;;;GAKG;AACH,wBAAgB,cAAc,CAAC,IAAI,EAAE,IAAI,EAAE,WAAW,EAAE,IAAI,GAAG,IAAI,CAgBlE;AAED;;;;;GAKG;AACH,wBAAgB,WAAW,CAAC,IAAI,EAAE,OAAO,EAAE,KAAK,EAAE,IAAI,GAAG,IAAI,CAa5D;AAED;;;;;GAKG;AACH,wBAAgB,MAAM,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,GAAG,IAAI,CAoBnD;AAED;;;;;GAKG;AACH,wBAAgB,YAAY,CAAC,IAAI,EAAE,OAAO,EAAE,KAAK,EAAE,IAAI,GAAG,IAAI,CAa7D;AAED;;;;;GAKG;AACH,wBAAgB,OAAO,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,GAAG,IAAI,CAiBpD"}

View file

@ -0,0 +1,129 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.prepend = exports.prependChild = exports.append = exports.appendChild = exports.replaceElement = exports.removeElement = void 0;
/**
* Remove an element from the dom
*
* @param elem The element to be removed
*/
function removeElement(elem) {
if (elem.prev)
elem.prev.next = elem.next;
if (elem.next)
elem.next.prev = elem.prev;
if (elem.parent) {
var childs = elem.parent.children;
childs.splice(childs.lastIndexOf(elem), 1);
}
}
exports.removeElement = removeElement;
/**
* Replace an element in the dom
*
* @param elem The element to be replaced
* @param replacement The element to be added
*/
function replaceElement(elem, replacement) {
var prev = (replacement.prev = elem.prev);
if (prev) {
prev.next = replacement;
}
var next = (replacement.next = elem.next);
if (next) {
next.prev = replacement;
}
var parent = (replacement.parent = elem.parent);
if (parent) {
var childs = parent.children;
childs[childs.lastIndexOf(elem)] = replacement;
}
}
exports.replaceElement = replaceElement;
/**
* Append a child to an element.
*
* @param elem The element to append to.
* @param child The element to be added as a child.
*/
function appendChild(elem, child) {
removeElement(child);
child.next = null;
child.parent = elem;
if (elem.children.push(child) > 1) {
var sibling = elem.children[elem.children.length - 2];
sibling.next = child;
child.prev = sibling;
}
else {
child.prev = null;
}
}
exports.appendChild = appendChild;
/**
* Append an element after another.
*
* @param elem The element to append after.
* @param next The element be added.
*/
function append(elem, next) {
removeElement(next);
var parent = elem.parent;
var currNext = elem.next;
next.next = currNext;
next.prev = elem;
elem.next = next;
next.parent = parent;
if (currNext) {
currNext.prev = next;
if (parent) {
var childs = parent.children;
childs.splice(childs.lastIndexOf(currNext), 0, next);
}
}
else if (parent) {
parent.children.push(next);
}
}
exports.append = append;
/**
* Prepend a child to an element.
*
* @param elem The element to prepend before.
* @param child The element to be added as a child.
*/
function prependChild(elem, child) {
removeElement(child);
child.parent = elem;
child.prev = null;
if (elem.children.unshift(child) !== 1) {
var sibling = elem.children[1];
sibling.prev = child;
child.next = sibling;
}
else {
child.next = null;
}
}
exports.prependChild = prependChild;
/**
* Prepend an element before another.
*
* @param elem The element to prepend before.
* @param prev The element be added.
*/
function prepend(elem, prev) {
removeElement(prev);
var parent = elem.parent;
if (parent) {
var childs = parent.children;
childs.splice(childs.indexOf(elem), 0, prev);
}
if (elem.prev) {
elem.prev.next = prev;
}
prev.parent = parent;
prev.prev = elem.prev;
prev.next = elem;
elem.prev = prev;
}
exports.prepend = prepend;

View file

@ -0,0 +1,55 @@
import { Node, Element } from "domhandler";
/**
* Search a node and its children for nodes passing a test function.
*
* @param test Function to test nodes on.
* @param node Node to search. Will be included in the result set if it matches.
* @param recurse Also consider child nodes.
* @param limit Maximum number of nodes to return.
* @returns All nodes passing `test`.
*/
export declare function filter(test: (elem: Node) => boolean, node: Node | Node[], recurse?: boolean, limit?: number): Node[];
/**
* Search an array of node and its children for nodes passing a test function.
*
* @param test Function to test nodes on.
* @param nodes Array of nodes to search.
* @param recurse Also consider child nodes.
* @param limit Maximum number of nodes to return.
* @returns All nodes passing `test`.
*/
export declare function find(test: (elem: Node) => boolean, nodes: Node[], recurse: boolean, limit: number): Node[];
/**
* Finds the first element inside of an array that matches a test function.
*
* @param test Function to test nodes on.
* @param nodes Array of nodes to search.
* @returns The first node in the array that passes `test`.
*/
export declare function findOneChild(test: (elem: Node) => boolean, nodes: Node[]): Node | undefined;
/**
* Finds one element in a tree that passes a test.
*
* @param test Function to test nodes on.
* @param nodes Array of nodes to search.
* @param recurse Also consider child nodes.
* @returns The first child node that passes `test`.
*/
export declare function findOne(test: (elem: Element) => boolean, nodes: Node[], recurse?: boolean): Element | null;
/**
* @param test Function to test nodes on.
* @param nodes Array of nodes to search.
* @returns Whether a tree of nodes contains at least one node passing a test.
*/
export declare function existsOne(test: (elem: Element) => boolean, nodes: Node[]): boolean;
/**
* Search and array of nodes and its children for nodes passing a test function.
*
* Same as `find`, only with less options, leading to reduced complexity.
*
* @param test Function to test nodes on.
* @param nodes Array of nodes to search.
* @returns All nodes passing `test`.
*/
export declare function findAll(test: (elem: Element) => boolean, nodes: Node[]): Element[];
//# sourceMappingURL=querying.d.ts.map

View file

@ -0,0 +1 @@
{"version":3,"file":"querying.d.ts","sourceRoot":"","sources":["../src/querying.ts"],"names":[],"mappings":"AAAA,OAAO,EAAsB,IAAI,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAE/D;;;;;;;;GAQG;AACH,wBAAgB,MAAM,CAClB,IAAI,EAAE,CAAC,IAAI,EAAE,IAAI,KAAK,OAAO,EAC7B,IAAI,EAAE,IAAI,GAAG,IAAI,EAAE,EACnB,OAAO,UAAO,EACd,KAAK,SAAW,GACjB,IAAI,EAAE,CAGR;AAED;;;;;;;;GAQG;AACH,wBAAgB,IAAI,CAChB,IAAI,EAAE,CAAC,IAAI,EAAE,IAAI,KAAK,OAAO,EAC7B,KAAK,EAAE,IAAI,EAAE,EACb,OAAO,EAAE,OAAO,EAChB,KAAK,EAAE,MAAM,GACd,IAAI,EAAE,CAkBR;AAED;;;;;;GAMG;AACH,wBAAgB,YAAY,CACxB,IAAI,EAAE,CAAC,IAAI,EAAE,IAAI,KAAK,OAAO,EAC7B,KAAK,EAAE,IAAI,EAAE,GACd,IAAI,GAAG,SAAS,CAElB;AAED;;;;;;;GAOG;AACH,wBAAgB,OAAO,CACnB,IAAI,EAAE,CAAC,IAAI,EAAE,OAAO,KAAK,OAAO,EAChC,KAAK,EAAE,IAAI,EAAE,EACb,OAAO,UAAO,GACf,OAAO,GAAG,IAAI,CAehB;AAED;;;;GAIG;AACH,wBAAgB,SAAS,CACrB,IAAI,EAAE,CAAC,IAAI,EAAE,OAAO,KAAK,OAAO,EAChC,KAAK,EAAE,IAAI,EAAE,GACd,OAAO,CAQT;AAED;;;;;;;;GAQG;AACH,wBAAgB,OAAO,CACnB,IAAI,EAAE,CAAC,IAAI,EAAE,OAAO,KAAK,OAAO,EAChC,KAAK,EAAE,IAAI,EAAE,GACd,OAAO,EAAE,CAYX"}

View file

@ -0,0 +1,126 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.findAll = exports.existsOne = exports.findOne = exports.findOneChild = exports.find = exports.filter = void 0;
var domhandler_1 = require("domhandler");
/**
* Search a node and its children for nodes passing a test function.
*
* @param test Function to test nodes on.
* @param node Node to search. Will be included in the result set if it matches.
* @param recurse Also consider child nodes.
* @param limit Maximum number of nodes to return.
* @returns All nodes passing `test`.
*/
function filter(test, node, recurse, limit) {
if (recurse === void 0) { recurse = true; }
if (limit === void 0) { limit = Infinity; }
if (!Array.isArray(node))
node = [node];
return find(test, node, recurse, limit);
}
exports.filter = filter;
/**
* Search an array of node and its children for nodes passing a test function.
*
* @param test Function to test nodes on.
* @param nodes Array of nodes to search.
* @param recurse Also consider child nodes.
* @param limit Maximum number of nodes to return.
* @returns All nodes passing `test`.
*/
function find(test, nodes, recurse, limit) {
var result = [];
for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
var elem = nodes_1[_i];
if (test(elem)) {
result.push(elem);
if (--limit <= 0)
break;
}
if (recurse && (0, domhandler_1.hasChildren)(elem) && elem.children.length > 0) {
var children = find(test, elem.children, recurse, limit);
result.push.apply(result, children);
limit -= children.length;
if (limit <= 0)
break;
}
}
return result;
}
exports.find = find;
/**
* Finds the first element inside of an array that matches a test function.
*
* @param test Function to test nodes on.
* @param nodes Array of nodes to search.
* @returns The first node in the array that passes `test`.
*/
function findOneChild(test, nodes) {
return nodes.find(test);
}
exports.findOneChild = findOneChild;
/**
* Finds one element in a tree that passes a test.
*
* @param test Function to test nodes on.
* @param nodes Array of nodes to search.
* @param recurse Also consider child nodes.
* @returns The first child node that passes `test`.
*/
function findOne(test, nodes, recurse) {
if (recurse === void 0) { recurse = true; }
var elem = null;
for (var i = 0; i < nodes.length && !elem; i++) {
var checked = nodes[i];
if (!(0, domhandler_1.isTag)(checked)) {
continue;
}
else if (test(checked)) {
elem = checked;
}
else if (recurse && checked.children.length > 0) {
elem = findOne(test, checked.children);
}
}
return elem;
}
exports.findOne = findOne;
/**
* @param test Function to test nodes on.
* @param nodes Array of nodes to search.
* @returns Whether a tree of nodes contains at least one node passing a test.
*/
function existsOne(test, nodes) {
return nodes.some(function (checked) {
return (0, domhandler_1.isTag)(checked) &&
(test(checked) ||
(checked.children.length > 0 &&
existsOne(test, checked.children)));
});
}
exports.existsOne = existsOne;
/**
* Search and array of nodes and its children for nodes passing a test function.
*
* Same as `find`, only with less options, leading to reduced complexity.
*
* @param test Function to test nodes on.
* @param nodes Array of nodes to search.
* @returns All nodes passing `test`.
*/
function findAll(test, nodes) {
var _a;
var result = [];
var stack = nodes.filter(domhandler_1.isTag);
var elem;
while ((elem = stack.shift())) {
var children = (_a = elem.children) === null || _a === void 0 ? void 0 : _a.filter(domhandler_1.isTag);
if (children && children.length > 0) {
stack.unshift.apply(stack, children);
}
if (test(elem))
result.push(elem);
}
return result;
}
exports.findAll = findAll;

View file

@ -0,0 +1,41 @@
import { Node } from "domhandler";
import { DomSerializerOptions } from "dom-serializer";
/**
* @param node Node to get the outer HTML of.
* @param options Options for serialization.
* @deprecated Use the `dom-serializer` module directly.
* @returns `node`'s outer HTML.
*/
export declare function getOuterHTML(node: Node | Node[], options?: DomSerializerOptions): string;
/**
* @param node Node to get the inner HTML of.
* @param options Options for serialization.
* @deprecated Use the `dom-serializer` module directly.
* @returns `node`'s inner HTML.
*/
export declare function getInnerHTML(node: Node, options?: DomSerializerOptions): string;
/**
* Get a node's inner text. Same as `textContent`, but inserts newlines for `<br>` tags.
*
* @deprecated Use `textContent` instead.
* @param node Node to get the inner text of.
* @returns `node`'s inner text.
*/
export declare function getText(node: Node | Node[]): string;
/**
* Get a node's text content.
*
* @param node Node to get the text content of.
* @returns `node`'s text content.
* @see {@link https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent}
*/
export declare function textContent(node: Node | Node[]): string;
/**
* Get a node's inner text.
*
* @param node Node to get the inner text of.
* @returns `node`'s inner text.
* @see {@link https://developer.mozilla.org/en-US/docs/Web/API/Node/innerText}
*/
export declare function innerText(node: Node | Node[]): string;
//# sourceMappingURL=stringify.d.ts.map

View file

@ -0,0 +1 @@
{"version":3,"file":"stringify.d.ts","sourceRoot":"","sources":["../src/stringify.ts"],"names":[],"mappings":"AAAA,OAAO,EAKH,IAAI,EAEP,MAAM,YAAY,CAAC;AACpB,OAAmB,EAAE,oBAAoB,EAAE,MAAM,gBAAgB,CAAC;AAGlE;;;;;GAKG;AACH,wBAAgB,YAAY,CACxB,IAAI,EAAE,IAAI,GAAG,IAAI,EAAE,EACnB,OAAO,CAAC,EAAE,oBAAoB,GAC/B,MAAM,CAER;AAED;;;;;GAKG;AACH,wBAAgB,YAAY,CACxB,IAAI,EAAE,IAAI,EACV,OAAO,CAAC,EAAE,oBAAoB,GAC/B,MAAM,CAIR;AAED;;;;;;GAMG;AACH,wBAAgB,OAAO,CAAC,IAAI,EAAE,IAAI,GAAG,IAAI,EAAE,GAAG,MAAM,CAMnD;AAED;;;;;;GAMG;AACH,wBAAgB,WAAW,CAAC,IAAI,EAAE,IAAI,GAAG,IAAI,EAAE,GAAG,MAAM,CAOvD;AAED;;;;;;GAMG;AACH,wBAAgB,SAAS,CAAC,IAAI,EAAE,IAAI,GAAG,IAAI,EAAE,GAAG,MAAM,CAOrD"}

View file

@ -0,0 +1,86 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.innerText = exports.textContent = exports.getText = exports.getInnerHTML = exports.getOuterHTML = void 0;
var domhandler_1 = require("domhandler");
var dom_serializer_1 = __importDefault(require("dom-serializer"));
var domelementtype_1 = require("domelementtype");
/**
* @param node Node to get the outer HTML of.
* @param options Options for serialization.
* @deprecated Use the `dom-serializer` module directly.
* @returns `node`'s outer HTML.
*/
function getOuterHTML(node, options) {
return (0, dom_serializer_1.default)(node, options);
}
exports.getOuterHTML = getOuterHTML;
/**
* @param node Node to get the inner HTML of.
* @param options Options for serialization.
* @deprecated Use the `dom-serializer` module directly.
* @returns `node`'s inner HTML.
*/
function getInnerHTML(node, options) {
return (0, domhandler_1.hasChildren)(node)
? node.children.map(function (node) { return getOuterHTML(node, options); }).join("")
: "";
}
exports.getInnerHTML = getInnerHTML;
/**
* Get a node's inner text. Same as `textContent`, but inserts newlines for `<br>` tags.
*
* @deprecated Use `textContent` instead.
* @param node Node to get the inner text of.
* @returns `node`'s inner text.
*/
function getText(node) {
if (Array.isArray(node))
return node.map(getText).join("");
if ((0, domhandler_1.isTag)(node))
return node.name === "br" ? "\n" : getText(node.children);
if ((0, domhandler_1.isCDATA)(node))
return getText(node.children);
if ((0, domhandler_1.isText)(node))
return node.data;
return "";
}
exports.getText = getText;
/**
* Get a node's text content.
*
* @param node Node to get the text content of.
* @returns `node`'s text content.
* @see {@link https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent}
*/
function textContent(node) {
if (Array.isArray(node))
return node.map(textContent).join("");
if ((0, domhandler_1.hasChildren)(node) && !(0, domhandler_1.isComment)(node)) {
return textContent(node.children);
}
if ((0, domhandler_1.isText)(node))
return node.data;
return "";
}
exports.textContent = textContent;
/**
* Get a node's inner text.
*
* @param node Node to get the inner text of.
* @returns `node`'s inner text.
* @see {@link https://developer.mozilla.org/en-US/docs/Web/API/Node/innerText}
*/
function innerText(node) {
if (Array.isArray(node))
return node.map(innerText).join("");
if ((0, domhandler_1.hasChildren)(node) && (node.type === domelementtype_1.ElementType.Tag || (0, domhandler_1.isCDATA)(node))) {
return innerText(node.children);
}
if ((0, domhandler_1.isText)(node))
return node.data;
return "";
}
exports.innerText = innerText;

Some files were not shown because too many files have changed in this diff Show more