前端 uni-app 重写: 9页面 H5

This commit is contained in:
zhiqui
2026-11-15 15:09:37 +08:00
parent 513b53672e
commit ea7c2529e9
24104 changed files with 3667749 additions and 0 deletions
+20
View File
@@ -0,0 +1,20 @@
The MIT License (MIT)
Copyright 2015 Mark Dalgleish <mark.john.dalgleish@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.
+123
View File
@@ -0,0 +1,123 @@
[![Build Status][ci-img]][ci] [![codecov][codecov-img]][codecov] [![npm][npm-img]][npm]
# CSS Modules: Local by Default
Transformation examples:
Selectors (mode `local`, by default)::
<!-- prettier-ignore-start -->
```css
.foo { ... } /* => */ :local(.foo) { ... }
.foo .bar { ... } /* => */ :local(.foo) :local(.bar) { ... }
/* Shorthand global selector */
:global .foo .bar { ... } /* => */ .foo .bar { ... }
.foo :global .bar { ... } /* => */ :local(.foo) .bar { ... }
/* Targeted global selector */
:global(.foo) .bar { ... } /* => */ .foo :local(.bar) { ... }
.foo:global(.bar) { ... } /* => */ :local(.foo).bar { ... }
.foo :global(.bar) .baz { ... } /* => */ :local(.foo) .bar :local(.baz) { ... }
.foo:global(.bar) .baz { ... } /* => */ :local(.foo).bar :local(.baz) { ... }
```
<!-- prettier-ignore-end -->
Declarations (mode `local`, by default):
<!-- prettier-ignore-start -->
```css
.foo {
animation-name: fadeInOut, global(moveLeft300px), local(bounce);
}
.bar {
animation: rotate 1s, global(spin) 3s, local(fly) 6s;
}
/* => */
:local(.foo) {
animation-name: :local(fadeInOut), moveLeft300px, :local(bounce);
}
:local(.bar) {
animation: :local(rotate) 1s, spin 3s, :local(fly) 6s;
}
```
<!-- prettier-ignore-end -->
## Pure Mode
In pure mode, all selectors must contain at least one local class or id
selector
To ignore this rule for a specific selector, add the a `/* cssmodules-pure-ignore */` comment in front
of the selector:
```css
/* cssmodules-pure-ignore */
:global(#modal-backdrop) {
...;
}
```
or by adding a `/* cssmodules-pure-no-check */` comment at the top of a file to disable this check for the whole file:
```css
/* cssmodules-pure-no-check */
:global(#modal-backdrop) {
...;
}
:global(#my-id) {
...;
}
```
## Building
```bash
$ npm install
$ npm test
```
- Build: [![Build Status][ci-img]][ci]
- Lines: [![coveralls][coveralls-img]][coveralls]
- Statements: [![codecov][codecov-img]][codecov]
## Development
```bash
$ yarn test:watch
```
## License
MIT
## With thanks
- [Tobias Koppers](https://github.com/sokra)
- [Glen Maddern](https://github.com/geelen)
---
Mark Dalgleish, 2015.
[ci-img]: https://github.com/css-modules/postcss-modules-local-by-default/actions/workflows/nodejs.yml/badge.svg
[ci]: https://github.com/css-modules/postcss-modules-local-by-default/actions/workflows/nodejs.yml
[npm-img]: https://img.shields.io/npm/v/postcss-modules-local-by-default.svg?style=flat-square
[npm]: https://www.npmjs.com/package/postcss-modules-local-by-default
[coveralls-img]: https://img.shields.io/coveralls/css-modules/postcss-modules-local-by-default/master.svg?style=flat-square
[coveralls]: https://coveralls.io/r/css-modules/postcss-modules-local-by-default?branch=master
[codecov-img]: https://img.shields.io/codecov/c/github/css-modules/postcss-modules-local-by-default/master.svg?style=flat-square
[codecov]: https://codecov.io/github/css-modules/postcss-modules-local-by-default?branch=master
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,629 @@
# Changelog of `postcss-selector-parser`
## 7.2.1 - 2026-11-10
- revert: the class constructor writes `value` as given again, as it did through 7.1.8. 7.2.0 escaped it, so the names CSS Modules builds (postcss-modules-scope with css-loader) were escaped a second time and their selectors stopped matching ([#362](https://github.com/postcss/postcss-selector-parser/issues/362), reported by [@denniskigen](https://github.com/denniskigen))
- revert: assigning to an id's `value` writes it as given again, as it did through 7.1.8, for the same reason. Both changes are parked for the next major ([#357](https://github.com/postcss/postcss-selector-parser/issues/357))
- fix(types): spell `Selector` without a self-referencing type alias, which TypeScript 7.1 previews reject with TS5115, while its children still exclude `Selector` ([#348](https://github.com/postcss/postcss-selector-parser/issues/348), [#350](https://github.com/postcss/postcss-selector-parser/pull/350) by [@firefoxic](https://github.com/firefoxic))
- docs: state the 7.x contract for `className` and `id` values in `API.md`
## 7.2.0 - 2026-11-08
- feat: add the opt-in `maxInputLength` option, which rejects a selector longer than the limit before parsing it
- feat: support the case-sensitive attribute flag `s` per Selectors Level 4, on `Attribute#sensitive` and `Attribute#sensitiveFlag`. `[a=b s]` previously left `insensitive: false` and filed the flag in `raws.insensitiveFlag` ([#327](https://github.com/postcss/postcss-selector-parser/pull/327) by [@abhu85](https://github.com/abhu85))
- docs: add a threat model to `SECURITY.md`: resource consumption caused by unbounded untrusted input is now handled as a regular bug
- docs: document the raw-value helpers (`stringifyProperty`, `valueToString`, `setPropertyAndEscape`, `appendToPropertyAndEscape`, `setPropertyWithoutEscape`), the seventeen type guards, and the `clone()` overrides argument ([#231](https://github.com/postcss/postcss-selector-parser/issues/231))
- fix: forward the default options given to the parser factory, so `parser(fn, { maxInputLength })` and the other options take effect there as documented ([#345](https://github.com/postcss/postcss-selector-parser/pull/345) by [@Aurantium-47](https://github.com/Aurantium-47))
- fix: preserve the spaces declared on selector and root containers, through `rawSpaceBefore` and `rawSpaceAfter` ([#356](https://github.com/postcss/postcss-selector-parser/pull/356) by [@Aschenbath](https://github.com/Aschenbath))
- fix: preserve selector delimiters after an escaped backslash, so `.a\\.b` parses as two classes ([#354](https://github.com/postcss/postcss-selector-parser/pull/354) by [@wozhenbang2004](https://github.com/wozhenbang2004))
- fix: escape class values supplied to the constructor, matching what the `value` setter already did ([#349](https://github.com/postcss/postcss-selector-parser/pull/349) by [@SAY-5](https://github.com/SAY-5))
- fix: escape values assigned to an id through the `value` setter, and replace a stale `raws.value` on assignment ([#326](https://github.com/postcss/postcss-selector-parser/pull/326) by [@mahirhir](https://github.com/mahirhir))
- fix: keep `$` in an attribute name inside a preprocessor interpolation, so `[#{$attr}]` in SCSS and `[@{attr}]` in Less round-trip ([#336](https://github.com/postcss/postcss-selector-parser/pull/336) by [@theRizwan](https://github.com/theRizwan))
- fix: reject an attribute selector with no valid attribute name, instead of throwing a raw `TypeError` or emitting the literal text `undefined` ([#335](https://github.com/postcss/postcss-selector-parser/pull/335) by [@theRizwan](https://github.com/theRizwan))
- fix: keep the processor's entry points usable when destructured, as in `const { process } = parser()` ([#145](https://github.com/postcss/postcss-selector-parser/issues/145))
### Behaviour notes
- `className` and `id` values are escaped when passed to a constructor or assigned through `value`, so an already-escaped value is now escaped twice. `setPropertyWithoutEscape()` is the escape hatch. Reverted in 7.2.1.
- `[a=b s]` sets `sensitive: true` rather than filing the flag in `raws.insensitiveFlag`. Serialization is byte-identical for `i`, `I`, `s`, `S` and non-standard flags.
- `Selector` and `Root` emit their own `rawSpaceBefore` and `rawSpaceAfter`, which changes serialization for ASTs that set them.
- An attribute selector with no attribute name raises the parser's own error rather than throwing a raw `TypeError` or serializing the text `undefined`: `[ns|*]` and `[ * ]` are affected. A trailing `*`, `$`, `^`, `~` or `|` after a valid name is dropped, as `[href=]` already was.
## 7.1.8 - 2026-11-08
- fix: parse selectors in linear time on four more kinds of crafted input, closing a CPU exhaustion vulnerability ([GHSA-67xj-gfww-g738](https://github.com/advisories/GHSA-67xj-gfww-g738), reported by [@zachariah-mithani](https://github.com/zachariah-mithani))
- chore: replace the `cssesc` dependency with an internal copy, whose redundant space removal is linear
## 7.1.7 - 2026-10-19
- fix: `lossless: true` preserves trailing whitespace in a selector that ends empty, such as `:not(a, )`. Note that `:not( )` now yields a selector holding one empty string node rather than an empty selector ([#337](https://github.com/postcss/postcss-selector-parser/pull/337) by [@theRizwan](https://github.com/theRizwan))
- fix: consume the whitespace that terminates a hexadecimal escape, so `[x="\000061 b"]` unescapes to `ab` ([#340](https://github.com/postcss/postcss-selector-parser/pull/340) by [@jakezwang](https://github.com/jakezwang))
- fix: set the parent on every node passed to `insertBefore` and `insertAfter`, not only the first ([#343](https://github.com/postcss/postcss-selector-parser/pull/343) by [@feritcemkahraman](https://github.com/feritcemkahraman))
- fix: assigning `combinator.value` clears the stale raw spelling instead of being ignored ([#342](https://github.com/postcss/postcss-selector-parser/pull/342) by [@SAY-5](https://github.com/SAY-5))
- fix: keep whitespace around the namespace separator in attribute selectors, so `[ foo | bar ]` round-trips ([#339](https://github.com/postcss/postcss-selector-parser/pull/339) by [@dkryaklin](https://github.com/dkryaklin))
## 7.1.6 - 2026-09-03
- fix: parse flat selectors in linear time, closing a CPU exhaustion vulnerability ([CVE-2026-104844](https://github.com/advisories/GHSA-rj75-hqrm-r3gf) / GHSA-rj75-hqrm-r3gf, reported by Wayde Shi)
## 7.1.5 - 2026-08-07
- fix: don't treat a non-prefix token before `|` as a namespace ([#324](https://github.com/postcss/postcss-selector-parser/pull/324) by [@spokodev](https://github.com/spokodev))
- fix: preserve whitespace before a `*` namespace in attribute selectors ([#325](https://github.com/postcss/postcss-selector-parser/pull/325) by [@spokodev](https://github.com/spokodev))
- fix: TypeError on unclosed `[`, `(` and trailing `|` ([#330](https://github.com/postcss/postcss-selector-parser/pull/330) by [@theRizwan](https://github.com/theRizwan))
## 7.1.4 - 2026-06-11
- fix: tolerate non-node children when serializing selectors
## 7.1.3 - 2026-06-11
- Improve fix CVE-2026-9358 (NVD) / SNYK-JS-POSTCSSSELECTORPARSER-16873882 (clone/walk)
## 7.1.2 - 2026-06-09
- Fix [CVE-2026-9358](https://github.com/advisories/GHSA-w9m9-85wc-3x92) (NVD) / SNYK-JS-POSTCSSSELECTORPARSER-16873882 ([#316](https://github.com/postcss/postcss-selector-parser/pull/316) by [@MoOx](https://github.com/MoOx))
## 7.1.1
- perf: replace startsWith with strict equality (#308)
- fix(types): add walkUniversal declaration (#311)
## 7.1.0
- feat: insert(Before|After) support multiple new node
## 7.0.0
- Feat: make insertions during iteration safe (major)
## 6.1.2
- Fixed: erroneous trailing combinators in pseudos
## 6.1.1
- Fixed: improve typings of constructor helpers (#292)
## 6.1.0
- Feature: add `sourceIndex` to `Selector` nodes (#290)
## 6.0.16
- Fixed: add missing `index` argument to `each`/`walk` callback types (#289)
## 6.0.15
- Fixed: Node#prev and Node#next type for the first/last node
## 6.0.14
- Fixed: type definitions
## 6.0.13
- Fixed: throw on unexpected pipe symbols
## 6.0.12
- Fixed: `clone` arguments should be optional
## 6.0.11
- Fixed: parse attribute case insensitivity flag
## 6.0.10
- Fixed: `isPseudoElement()` supports `:first-letter` and `:first-line`
## 6.0.9
- Fixed: `Combinator.raws` property type
## 6.0.8
- Fixed: reduced size
## 6.0.7
- Fixed: parse animation percents
## 6.0.6
- Fixed: parse quoted attributes containing a newline correctly
## 6.0.5
- Perf: rework unesc for a 63+% performance boost
## 6.0.4
- Fixed: ts errors
## 6.0.3
- Fixed: replace node built-in "util" module with "util-deprecate"
- Fixed: handle uppercase pseudo elements
- Fixed: do not create invalid combinator before comment
## 6.0.2
- Fixed an issue with parsing and stringifying an empty attribute value
## 6.0.1
- Fixed an issue with unicode surrogate pair parsing
## 6.0.0
- Updated: `cssesc` to 3.0.0 (major)
- Fixed: Issues with escaped `id` and `class` selectors
## 5.0.0
- Allow escaped dot within class name.
- Update PostCSS to 7.0.7 (patch)
## 5.0.0-rc.4
- Fixed an issue where comments immediately after an insensitive (in attribute)
were not parsed correctly.
- Updated `cssesc` to 2.0.0 (major).
- Removed outdated integration tests.
- Added tests for custom selectors, tags with attributes, the universal
selector with pseudos, and tokens after combinators.
## 5.0.0-rc.1
To ease adoption of the v5.0 release, we have relaxed the node version
check performed by npm at installation time to allow for node 4, which
remains officially unsupported, but likely to continue working for the
time being.
## 5.0.0-rc.0
This release has **BREAKING CHANGES** that were required to fix regressions
in 4.0.0 and to make the Combinator Node API consistent for all combinator
types. Please read carefully.
### Summary of Changes
* The way a descendent combinator that isn't a single space character (E.g. `.a .b`) is stored in the AST has changed.
* Named Combinators (E.g. `.a /for/ .b`) are now properly parsed as a combinator.
* It is now possible to look up a node based on the source location of a character in that node and to query nodes if they contain some character.
* Several bug fixes that caused the parser to hang and run out of memory when a `/` was encountered have been fixed.
* The minimum supported version of Node is now `v6.0.0`.
#### Changes to the Descendent Combinator
In prior releases, the value of a descendant combinator with multiple spaces included all the spaces.
* `.a .b`: Extra spaces are now stored as space before.
- Old & Busted:
- `combinator.value === " "`
- New hotness:
- `combinator.value === " " && combinator.spaces.before === " "`
* `.a /*comment*/.b`: A comment at the end of the combinator causes extra space to become after space.
- Old & Busted:
- `combinator.value === " "`
- `combinator.raws.value === " /*comment/"`
- New hotness:
- `combinator.value === " "`
- `combinator.spaces.after === " "`
- `combinator.raws.spaces.after === " /*comment*/"`
* `.a<newline>.b`: whitespace that doesn't start or end with a single space character is stored as a raw value.
- Old & Busted:
- `combinator.value === "\n"`
- `combinator.raws.value === undefined`
- New hotness:
- `combinator.value === " "`
- `combinator.raws.value === "\n"`
#### Support for "Named Combinators"
Although, nonstandard and unlikely to ever become a standard, combinators like `/deep/` and `/for/` are now properly supported.
Because they've been taken off the standardization track, there is no spec-official name for combinators of the form `/<ident>/`. However, I talked to [Tab Atkins](https://twitter.com/tabatkins) and we agreed to call them "named combinators" so now they are called that.
Before this release such named combinators were parsed without intention and generated three nodes of type `"tag"` where the first and last nodes had a value of `"/"`.
* `.a /for/ .b` is parsed as a combinator.
- Old & Busted:
- `root.nodes[0].nodes[1].type === "tag"`
- `root.nodes[0].nodes[1].value === "/"`
- New hotness:
- `root.nodes[0].nodes[1].type === "combinator"`
- `root.nodes[0].nodes[1].value === "/for/"`
* `.a /F\6fR/ .b` escapes are handled and uppercase is normalized.
- Old & Busted:
- `root.nodes[0].nodes[2].type === "tag"`
- `root.nodes[0].nodes[2].value === "F\\6fR"`
- New hotness:
- `root.nodes[0].nodes[1].type === "combinator"`
- `root.nodes[0].nodes[1].value === "/for/"`
- `root.nodes[0].nodes[1].raws.value === "/F\\6fR/"`
#### Source position checks and lookups
A new API was added to look up a node based on the source location.
```js
const selectorParser = require("postcss-selector-parser");
// You can find the most specific node for any given character
let combinator = selectorParser.astSync(".a > .b").atPosition(1,4);
combinator.toString() === " > ";
// You can check if a node includes a specific character
// Whitespace surrounding the node that is owned by that node
// is included in the check.
[2,3,4,5,6].map(column => combinator.isAtPosition(1, column));
// => [false, true, true, true, false]
```
## 4.0.0
This release has **BREAKING CHANGES** that were required to fix bugs regarding values with escape sequences. Please read carefully.
* **Identifiers with escapes** - CSS escape sequences are now hidden from the public API by default.
The normal value of a node like a class name or ID, or an aspect of a node such as attribute
selector's value, is unescaped. Escapes representing Non-ascii characters are unescaped into
unicode characters. For example: `bu\tton, .\31 00, #i\2764\FE0Fu, [attr="value is \"quoted\""]`
will parse respectively to the values `button`, `100`, `i❤️u`, `value is "quoted"`.
The original escape sequences for these values can be found in the corresponding property name
in `node.raws`. Where possible, deprecation warnings were added, but the nature
of escape handling makes it impossible to detect what is escaped or not. Our expectation is
that most users are neither expecting nor handling escape sequences in their use of this library,
and so for them, this is a bug fix. Users who are taking care to handle escapes correctly can
now update their code to remove the escape handling and let us do it for them.
* **Mutating values with escapes** - When you make an update to a node property that has escape handling
The value is assumed to be unescaped, and any special characters are escaped automatically and
the corresponding `raws` value is immediately updated. This can result in changes to the original
escape format. Where the exact value of the escape sequence is important there are methods that
allow both values to be set in conjunction. There are a number of new convenience methods for
manipulating values that involve escapes, especially for attributes values where the quote mark
is involved. See https://github.com/postcss/postcss-selector-parser/pull/133 for an extensive
write-up on these changes.
**Upgrade/API Example**
In `3.x` there was no unescape handling and internal consistency of several properties was the caller's job to maintain. It was very easy for the developer
to create a CSS file that did not parse correctly when some types of values
were in use.
```js
const selectorParser = require("postcss-selector-parser");
let attr = selectorParser.attribute({attribute: "id", operator: "=", value: "a-value"});
attr.value; // => "a-value"
attr.toString(); // => [id=a-value]
// Add quotes to an attribute's value.
// All these values have to be set by the caller to be consistent:
// no internal consistency is maintained.
attr.raws.unquoted = attr.value
attr.value = "'" + attr.value + "'";
attr.value; // => "'a-value'"
attr.quoted = true;
attr.toString(); // => "[id='a-value']"
```
In `4.0` there is a convenient API for setting and mutating values
that may need escaping. Especially for attributes.
```js
const selectorParser = require("postcss-selector-parser");
// The constructor requires you specify the exact escape sequence
let className = selectorParser.className({value: "illegal class name", raws: {value: "illegal\\ class\\ name"}});
className.toString(); // => '.illegal\\ class\\ name'
// So it's better to set the value as a property
className = selectorParser.className();
// Most properties that deal with identifiers work like this
className.value = "escape for me";
className.value; // => 'escape for me'
className.toString(); // => '.escape\\ for\\ me'
// emoji and all non-ascii are escaped to ensure it works in every css file.
className.value = "😱🦄😍";
className.value; // => '😱🦄😍'
className.toString(); // => '.\\1F631\\1F984\\1F60D'
// you can control the escape sequence if you want, or do bad bad things
className.setPropertyAndEscape('value', 'xxxx', 'yyyy');
className.value; // => "xxxx"
className.toString(); // => ".yyyy"
// Pass a value directly through to the css output without escaping it.
className.setPropertyWithoutEscape('value', '$REPLACE_ME$');
className.value; // => "$REPLACE_ME$"
className.toString(); // => ".$REPLACE_ME$"
// The biggest changes are to the Attribute class
// passing quoteMark explicitly is required to avoid a deprecation warning.
let attr = selectorParser.attribute({attribute: "id", operator: "=", value: "a-value", quoteMark: null});
attr.toString(); // => "[id=a-value]"
// Get the value with quotes on it and any necessary escapes.
// This is the same as reading attr.value in 3.x.
attr.getQuotedValue(); // => "a-value";
attr.quoteMark; // => null
// Add quotes to an attribute's value.
attr.quoteMark = "'"; // This is all that's required.
attr.toString(); // => "[id='a-value']"
attr.quoted; // => true
// The value is still the same, only the quotes have changed.
attr.value; // => a-value
attr.getQuotedValue(); // => "'a-value'";
// deprecated assignment, no warning because there's no escapes
attr.value = "new-value";
// no quote mark is needed so it is removed
attr.getQuotedValue(); // => "new-value";
// deprecated assignment,
attr.value = "\"a 'single quoted' value\"";
// > (node:27859) DeprecationWarning: Assigning an attribute a value containing characters that might need to be escaped is deprecated. Call attribute.setValue() instead.
attr.getQuotedValue(); // => '"a \'single quoted\' value"';
// quote mark inferred from first and last characters.
attr.quoteMark; // => '"'
// setValue takes options to make manipulating the value simple.
attr.setValue('foo', {smart: true});
// foo doesn't require any escapes or quotes.
attr.toString(); // => '[id=foo]'
attr.quoteMark; // => null
// An explicit quote mark can be specified
attr.setValue('foo', {quoteMark: '"'});
attr.toString(); // => '[id="foo"]'
// preserves quote mark by default
attr.setValue('bar');
attr.toString(); // => '[id="bar"]'
attr.quoteMark = null;
attr.toString(); // => '[id=bar]'
// with no arguments, it preserves quote mark even when it's not a great idea
attr.setValue('a value \n that should be quoted');
attr.toString(); // => '[id=a\\ value\\ \\A\\ that\\ should\\ be\\ quoted]'
// smart preservation with a specified default
attr.setValue('a value \n that should be quoted', {smart: true, preferCurrentQuoteMark: true, quoteMark: "'"});
// => "[id='a value \\A that should be quoted']"
attr.quoteMark = '"';
// => '[id="a value \\A that should be quoted"]'
// this keeps double quotes because it wants to quote the value and the existing value has double quotes.
attr.setValue('this should be quoted', {smart: true, preferCurrentQuoteMark: true, quoteMark: "'"});
// => '[id="this should be quoted"]'
// picks single quotes because the value has double quotes
attr.setValue('a "double quoted" value', {smart: true, preferCurrentQuoteMark: true, quoteMark: "'"});
// => "[id='a "double quoted" value']"
// setPropertyAndEscape lets you do anything you want. Even things that are a bad idea and illegal.
attr.setPropertyAndEscape('value', 'xxxx', 'the password is 42');
attr.value; // => "xxxx"
attr.toString(); // => "[id=the password is 42]"
// Pass a value directly through to the css output without escaping it.
attr.setPropertyWithoutEscape('value', '$REPLACEMENT$');
attr.value; // => "$REPLACEMENT$"
attr.toString(); // => "[id=$REPLACEMENT$]"
```
## 3.1.2
* Fix: Removed dot-prop dependency since it's no longer written in es5.
## 3.1.1
* Fix: typescript definitions weren't in the published package.
## 3.1.0
* Fixed numerous bugs in attribute nodes relating to the handling of comments
and whitespace. There's significant changes to `attrNode.spaces` and `attrNode.raws` since the `3.0.0` release.
* Added `Attribute#offsetOf(part)` to get the offset location of
attribute parts like `"operator"` and `"value"`. This is most
often added to `Attribute#sourceIndex` for error reporting.
## 3.0.0
### Breaking changes
* Some tweaks to the tokenizer/attribute selector parsing mean that whitespace
locations might be slightly different to the 2.x code.
* Better attribute selector parsing with more validation; postcss-selector-parser
no longer uses regular expressions to parse attribute selectors.
* Added an async API (thanks to @jacobp100); the default `process` API is now
async, and the sync API is now accessed through `processSync` instead.
* `process()` and `processSync()` now return a string instead of the Processor
instance.
* Tweaks handling of Less interpolation (thanks to @jwilsson).
* Removes support for Node 0.12.
### Other changes
* `ast()` and `astSync()` methods have been added to the `Processor`. These
return the `Root` node of the selectors after processing them.
* `transform()` and `transformSync()` methods have been added to the
`Processor`. These return the value returned by the processor callback
after processing the selectors.
* Set the parent when inserting a node (thanks to @chriseppstein).
* Correctly adjust indices when using insertBefore/insertAfter (thanks to @tivac).
* Fixes handling of namespaces with qualified tag selectors.
* `process`, `ast` and `transform` (and their sync variants) now accept a
`postcss` rule node. When provided, better errors are generated and selector
processing is automatically set back to the rule selector (unless the `updateSelector` option is set to `false`.)
* Now more memory efficient when tokenizing selectors.
#### Upgrade hints
The pattern of:
`rule.selector = processor.process(rule.selector).result.toString();`
is now:
`processor.processSync(rule)`
## 2.2.3
* Resolves an issue where the parser would not reduce multiple spaces between an
ampersand and another simple selector in lossy mode (thanks to @adam-26).
## 2.2.2
* No longer hangs on an unescaped semicolon; instead the parser will throw
an exception for these cases.
## 2.2.1
* Allows a consumer to specify whitespace tokens when creating a new Node
(thanks to @Semigradsky).
## 2.2.0
* Added a new option to normalize whitespace when parsing the selector string
(thanks to @adam-26).
## 2.1.1
* Better unquoted value handling within attribute selectors
(thanks to @evilebottnawi).
## 2.1.0
* Added: Use string constants for all node types & expose them on the main
parser instance (thanks to @Aweary).
# 2.0.0
This release contains the following breaking changes:
* Renamed all `eachInside` iterators to `walk`. For example, `eachTag` is now
`walkTags`, and `eachInside` is now `walk`.
* Renamed `Node#removeSelf()` to `Node#remove()`.
* Renamed `Container#remove()` to `Container#removeChild()`.
* Renamed `Node#raw` to `Node#raws` (thanks to @davidtheclark).
* Now parses `&` as the *nesting* selector, rather than a *tag* selector.
* Fixes misinterpretation of Sass interpolation (e.g. `#{foo}`) as an
id selector (thanks to @davidtheclark).
and;
* Fixes parsing of attribute selectors with equals signs in them
(e.g. `[data-attr="foo=bar"]`) (thanks to @montmanu).
* Adds `quoted` and `raw.unquoted` properties to attribute nodes
(thanks to @davidtheclark).
## 1.3.3
* Fixes an infinite loop on `)` and `]` tokens when they had no opening pairs.
Now postcss-selector-parser will throw when it encounters these lone tokens.
# 1.3.2
* Now uses plain integers rather than `str.charCodeAt(0)` for compiled builds.
## 1.3.1
* Update flatten to v1.x (thanks to @shinnn).
## 1.3.0
* Adds a new node type, `String`, to fix a crash on selectors such as
`foo:bar("test")`.
## 1.2.1
* Fixes a crash when the parser encountered a trailing combinator.
## 1.2.0
* A more descriptive error is thrown when the parser expects to find a
pseudo-class/pseudo-element (thanks to @ashelley).
* Adds support for line/column locations for selector nodes, as well as a
`Node#sourceIndex` method (thanks to @davidtheclark).
## 1.1.4
* Fixes a crash when a selector started with a `>` combinator. The module will
now no longer throw if a selector has a leading/trailing combinator node.
## 1.1.3
* Fixes a crash on `@` tokens.
## 1.1.2
* Fixes an infinite loop caused by using parentheses in a non-pseudo element
context.
## 1.1.1
* Fixes a crash when a backslash ended a selector string.
## 1.1.0
* Adds support for replacing multiple nodes at once with `replaceWith`
(thanks to @jonathantneal).
* Parser no longer throws on sequential IDs and trailing commas, to support
parsing of selector hacks.
## 1.0.1
* Fixes using `insertAfter` and `insertBefore` during iteration.
## 1.0.0
* Adds `clone` and `replaceWith` methods to nodes.
* Adds `insertBefore` and `insertAfter` to containers.
* Stabilises API.
## 0.0.5
* Fixes crash on extra whitespace inside a pseudo selector's parentheses.
* Adds sort function to the container class.
* Enables the parser to pass its input through without transforming.
* Iteration-safe `each` and `eachInside`.
## 0.0.4
* Tidy up redundant duplication.
* Fixes a bug where the parser would loop infinitely on universal selectors
inside pseudo selectors.
* Adds `length` getter and `eachInside`, `map`, `reduce` to the container class.
* When a selector has been removed from the tree, the root node will no longer
cast it to a string.
* Adds node type iterators to the container class (e.g. `eachComment`).
* Adds filter function to the container class.
* Adds split function to the container class.
* Create new node types by doing `parser.id(opts)` etc.
* Adds support for pseudo classes anywhere in the selector.
## 0.0.3
* Adds `next` and `prev` to the node class.
* Adds `first` and `last` getters to the container class.
* Adds `every` and `some` iterators to the container class.
* Add `empty` alias for `removeAll`.
* Combinators are now types of node.
* Fixes the at method so that it is not an alias for `index`.
* Tidy up creation of new nodes in the parser.
* Refactors how namespaces are handled for consistency & less redundant code.
* Refactors AST to use `nodes` exclusively, and eliminates excessive nesting.
* Fixes nested pseudo parsing.
* Fixes whitespace parsing.
## 0.0.2
* Adds support for namespace selectors.
* Adds support for selectors joined by escaped spaces - such as `.\31\ 0`.
## 0.0.1
* Initial release.
@@ -0,0 +1,22 @@
Copyright (c) Ben Briggs <beneb.info@gmail.com> (http://beneb.info)
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.
@@ -0,0 +1,99 @@
# postcss-selector-parser
[![npm package version](https://img.shields.io/github/package-json/v/postcss/postcss-selector-parser) ![npm downloads](https://img.shields.io/npm/dm/postcss-selector-parser)](https://www.npmjs.com/package/postcss-selector-parser)
[![GitHub Workflow Status](https://img.shields.io/github/actions/workflow/status/postcss/postcss-selector-parser/test.yml)](https://github.com/postcss/postcss-selector-parser/actions)
[![License](https://img.shields.io/github/license/postcss/postcss-selector-parser)](https://github.com/postcss/postcss-selector-parser)
> Selector parser with built in methods for working with selector strings.
## Install
With [npm](https://npmjs.com/package/postcss-selector-parser) do:
```
npm install postcss-selector-parser
```
## Quick Start
```js
const parser = require('postcss-selector-parser');
const transform = selectors => {
selectors.walk(selector => {
// do something with the selector
console.log(String(selector))
});
};
const transformed = parser(transform).processSync('h1, h2, h3');
```
To normalize selector whitespace:
```js
const parser = require('postcss-selector-parser');
const normalized = parser().processSync('h1, h2, h3', {lossless: false});
// -> h1,h2,h3
```
Async support is provided through `parser.process` and will resolve a Promise
with the resulting selector string.
## API
Please see [API.md](API.md).
## Security
### Selector nesting depth (CVE-2026-9358)
The parser walks the selector AST recursively, both when parsing and when
serializing it back to a string (`.toString()`). In versions up to and
including `7.1.1`, a selector with extreme nesting — for example thousands of
nested `:not(...)` — could recurse deeply enough to overflow the call stack and
throw `RangeError: Maximum call stack size exceeded`, a potential
denial-of-service when processing untrusted CSS.
This is now bounded by a maximum nesting depth (default: `256`). Beyond that
depth, parsing and serialization throw a regular, catchable `Error` at a
predictable point instead of relying on the runtime hitting its stack limit.
The default is far above any realistic selector, so it does not affect normal
use.
**Practical impact is low.** The only attacker-controlled input is the selector
string itself, which is now capped by the default limit. The limit is
adjustable through the `maxNestingDepth` option, but that option is trusted
configuration provided by the integrating code — it is never derived from the
parsed CSS, so a malicious selector cannot change it:
```js
// Tighten the limit when parsing untrusted input:
parser().processSync(untrustedSelector, {maxNestingDepth: 128});
```
Raising `maxNestingDepth` to a very large value is an explicit, informed choice
and can reintroduce the stack-overflow risk in environments with a small call
stack (e.g. browser workers). The default is recommended unless you have a
specific need.
### Parsing untrusted selectors
This package parses CSS selectors written by developers. If yours come from
untrusted sources, bound their length with the `maxInputLength` option, which
is off by default:
```js
parser().processSync(untrustedSelector, {maxInputLength: 65536});
```
It applies to one selector list, the text of a single rule before its `{`,
never to a whole stylesheet. See the threat model in [SECURITY.md](SECURITY.md).
## Credits
* Huge thanks to Andrey Sitnik (@ai) for work on PostCSS which helped
accelerate this module's development.
## License
MIT
@@ -0,0 +1,44 @@
"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 __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 () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
var processor_1 = __importDefault(require("./processor"));
var selectors = __importStar(require("./selectors"));
var parser = function (processor, options) { return new processor_1.default(processor, options); };
Object.assign(parser, selectors);
delete parser.__esModule;
module.exports = parser;
//# sourceMappingURL=index.js.map
@@ -0,0 +1,184 @@
"use strict";
var __values = (this && this.__values) || function(o) {
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
if (m) return m.call(o);
if (o && typeof o.length === "number") return {
next: function () {
if (o && i >= o.length) o = void 0;
return { value: o && o[i++], done: !o };
}
};
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var parser_1 = __importDefault(require("./parser"));
// The entry points a caller may reasonably take off a processor, as in
// `const { process } = parser()`. They are bound per instance in the
// constructor: unbound, they lost their receiver and threw a TypeError on
// `this._run`.
var BOUND_METHODS = ["ast", "astSync", "transform", "transformSync", "process", "processSync"];
var Processor = /** @class */ (function () {
function Processor(func, options) {
var e_1, _a;
this.func = func || function noop() { };
this.funcRes = null;
this.options = options;
try {
for (var BOUND_METHODS_1 = __values(BOUND_METHODS), BOUND_METHODS_1_1 = BOUND_METHODS_1.next(); !BOUND_METHODS_1_1.done; BOUND_METHODS_1_1 = BOUND_METHODS_1.next()) {
var name = BOUND_METHODS_1_1.value;
this[name] = this[name].bind(this);
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (BOUND_METHODS_1_1 && !BOUND_METHODS_1_1.done && (_a = BOUND_METHODS_1.return)) _a.call(BOUND_METHODS_1);
}
finally { if (e_1) throw e_1.error; }
}
}
Processor.prototype._shouldUpdateSelector = function (rule, options) {
if (options === void 0) { options = {}; }
var merged = Object.assign({}, this.options, options);
if (merged.updateSelector === false) {
return false;
}
else {
return typeof rule !== "string";
}
};
Processor.prototype._isLossy = function (options) {
if (options === void 0) { options = {}; }
var merged = Object.assign({}, this.options, options);
if (merged.lossless === false) {
return true;
}
else {
return false;
}
};
Processor.prototype._root = function (rule, options) {
if (options === void 0) { options = {}; }
var parser = new parser_1.default(rule, this._parseOptions(options));
return parser.root;
};
Processor.prototype._parseOptions = function (options) {
var merged = Object.assign({}, this.options, options);
return {
lossy: this._isLossy(merged),
maxNestingDepth: merged.maxNestingDepth,
maxInputLength: merged.maxInputLength,
};
};
Processor.prototype._stringifyOptions = function (options) {
var merged = Object.assign({}, this.options, options);
return {
maxNestingDepth: merged.maxNestingDepth,
};
};
Processor.prototype._run = function (rule, options) {
var _this = this;
if (options === void 0) { options = {}; }
return new Promise(function (resolve, reject) {
try {
var root_1 = _this._root(rule, options);
Promise.resolve(_this.func(root_1))
.then(function (transform) {
var string = undefined;
if (_this._shouldUpdateSelector(rule, options)) {
string = root_1.toString(_this._stringifyOptions(options));
rule.selector = string;
}
return { transform: transform, root: root_1, string: string };
})
.then(resolve, reject);
}
catch (e) {
reject(e);
return;
}
});
};
Processor.prototype._runSync = function (rule, options) {
if (options === void 0) { options = {}; }
var root = this._root(rule, options);
var transform = this.func(root);
if (transform && typeof transform.then === "function") {
throw new Error("Selector processor returned a promise to a synchronous call.");
}
var string = undefined;
if (options.updateSelector && typeof rule !== "string") {
string = root.toString(this._stringifyOptions(options));
rule.selector = string;
}
return { transform: transform, root: root, string: string };
};
/**
* Process rule into a selector AST.
*
* @param rule {postcss.Rule | string} The css selector to be processed
* @param options The options for processing
* @returns {Promise<parser.Root>} The AST of the selector after processing it.
*/
Processor.prototype.ast = function (rule, options) {
return this._run(rule, options).then(function (result) { return result.root; });
};
/**
* Process rule into a selector AST synchronously.
*
* @param rule {postcss.Rule | string} The css selector to be processed
* @param options The options for processing
* @returns {parser.Root} The AST of the selector after processing it.
*/
Processor.prototype.astSync = function (rule, options) {
return this._runSync(rule, options).root;
};
/**
* Process a selector into a transformed value asynchronously
*
* @param rule {postcss.Rule | string} The css selector to be processed
* @param options The options for processing
* @returns {Promise<any>} The value returned by the processor.
*/
Processor.prototype.transform = function (rule, options) {
return this._run(rule, options).then(function (result) { return result.transform; });
};
/**
* Process a selector into a transformed value synchronously.
*
* @param rule {postcss.Rule | string} The css selector to be processed
* @param options The options for processing
* @returns {any} The value returned by the processor.
*/
Processor.prototype.transformSync = function (rule, options) {
return this._runSync(rule, options).transform;
};
/**
* Process a selector into a new selector string asynchronously.
*
* @param rule {postcss.Rule | string} The css selector to be processed
* @param options The options for processing
* @returns {string} the selector after processing.
*/
Processor.prototype.process = function (rule, options) {
var _this = this;
return this._run(rule, options).then(function (result) { return result.string || result.root.toString(_this._stringifyOptions(options)); });
};
/**
* Process a selector into a new selector string synchronously.
*
* @param rule {postcss.Rule | string} The css selector to be processed
* @param options The options for processing
* @returns {string} the selector after processing.
*/
Processor.prototype.processSync = function (rule, options) {
var result = this._runSync(rule, options);
return result.string || result.root.toString(this._stringifyOptions(options));
};
return Processor;
}());
exports.default = Processor;
//# sourceMappingURL=processor.js.map
@@ -0,0 +1,497 @@
"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 __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
var _a;
Object.defineProperty(exports, "__esModule", { value: true });
exports.unescapeValue = unescapeValue;
var cssesc_1 = __importDefault(require("../util/cssesc"));
var unesc_1 = __importDefault(require("../util/unesc"));
var namespace_1 = __importDefault(require("./namespace"));
var types_1 = require("./types");
var deprecate = require("util-deprecate");
var WRAPPED_IN_QUOTES = /^('|")([^]*)\1$/;
var warnOfDeprecatedValueAssignment = deprecate(function () { }, "Assigning an attribute a value containing characters that might need to be escaped is deprecated. " +
"Call attribute.setValue() instead.");
var warnOfDeprecatedQuotedAssignment = deprecate(function () { }, "Assigning attr.quoted is deprecated and has no effect. Assign to attr.quoteMark instead.");
var warnOfDeprecatedConstructor = deprecate(function () { }, "Constructing an Attribute selector with a value without specifying quoteMark is deprecated. Note: The value should be unescaped now.");
function unescapeValue(value) {
var deprecatedUsage = false;
var quoteMark = null;
var unescaped = value;
var m = unescaped.match(WRAPPED_IN_QUOTES);
if (m) {
quoteMark = m[1];
unescaped = m[2];
}
unescaped = (0, unesc_1.default)(unescaped);
if (unescaped !== value) {
deprecatedUsage = true;
}
return {
deprecatedUsage: deprecatedUsage,
unescaped: unescaped,
quoteMark: quoteMark,
};
}
function handleDeprecatedContructorOpts(opts) {
if (opts.quoteMark !== undefined) {
return opts;
}
if (opts.value === undefined) {
return opts;
}
warnOfDeprecatedConstructor();
var _a = unescapeValue(opts.value), quoteMark = _a.quoteMark, unescaped = _a.unescaped;
if (!opts.raws) {
opts.raws = {};
}
if (opts.raws.value === undefined) {
opts.raws.value = opts.value;
}
opts.value = unescaped;
opts.quoteMark = quoteMark;
return opts;
}
var Attribute = /** @class */ (function (_super) {
__extends(Attribute, _super);
function Attribute(opts) {
if (opts === void 0) { opts = {}; }
var _this = _super.call(this, handleDeprecatedContructorOpts(opts)) || this;
_this.type = types_1.ATTRIBUTE;
_this.raws = _this.raws || {};
Object.defineProperty(_this.raws, "unquoted", {
get: deprecate(function () { return _this.value; }, "attr.raws.unquoted is deprecated. Call attr.value instead."),
set: deprecate(function () { return _this.value; }, "Setting attr.raws.unquoted is deprecated and has no effect. attr.value is unescaped by default now."),
});
_this._constructed = true;
return _this;
}
/**
* Returns the Attribute's value quoted such that it would be legal to use
* in the value of a css file. The original value's quotation setting
* used for stringification is left unchanged. See `setValue(value, options)`
* if you want to control the quote settings of a new value for the attribute.
*
* You can also change the quotation used for the current value by setting quoteMark.
*
* Options:
* * quoteMark {'"' | "'" | null} - Use this value to quote the value. If this
* option is not set, the original value for quoteMark will be used. If
* indeterminate, a double quote is used. The legal values are:
* * `null` - the value will be unquoted and characters will be escaped as necessary.
* * `'` - the value will be quoted with a single quote and single quotes are escaped.
* * `"` - the value will be quoted with a double quote and double quotes are escaped.
* * preferCurrentQuoteMark {boolean} - if true, prefer the source quote mark
* over the quoteMark option value.
* * smart {boolean} - if true, will select a quote mark based on the value
* and the other options specified here. See the `smartQuoteMark()`
* method.
**/
Attribute.prototype.getQuotedValue = function (options) {
if (options === void 0) { options = {}; }
var quoteMark = this._determineQuoteMark(options);
var cssescopts = CSSESC_QUOTE_OPTIONS[quoteMark];
var escaped = (0, cssesc_1.default)(this._value, cssescopts);
return escaped;
};
Attribute.prototype._determineQuoteMark = function (options) {
return options.smart ? this.smartQuoteMark(options) : this.preferredQuoteMark(options);
};
/**
* Set the unescaped value with the specified quotation options. The value
* provided must not include any wrapping quote marks -- those quotes will
* be interpreted as part of the value and escaped accordingly.
*/
Attribute.prototype.setValue = function (value, options) {
if (options === void 0) { options = {}; }
this._value = value;
this._quoteMark = this._determineQuoteMark(options);
this._syncRawValue();
};
/**
* Intelligently select a quoteMark value based on the value's contents. If
* the value is a legal CSS ident, it will not be quoted. Otherwise a quote
* mark will be picked that minimizes the number of escapes.
*
* If there's no clear winner, the quote mark from these options is used,
* then the source quote mark (this is inverted if `preferCurrentQuoteMark` is
* true). If the quoteMark is unspecified, a double quote is used.
*
* @param options This takes the quoteMark and preferCurrentQuoteMark options
* from the quoteValue method.
*/
Attribute.prototype.smartQuoteMark = function (options) {
var v = this.value;
var numSingleQuotes = v.replace(/[^']/g, "").length;
var numDoubleQuotes = v.replace(/[^"]/g, "").length;
if (numSingleQuotes + numDoubleQuotes === 0) {
var escaped = (0, cssesc_1.default)(v, { isIdentifier: true });
if (escaped === v) {
return Attribute.NO_QUOTE;
}
else {
var pref = this.preferredQuoteMark(options);
if (pref === Attribute.NO_QUOTE) {
// pick a quote mark that isn't none and see if it's smaller
var quote = this.quoteMark || options.quoteMark || Attribute.DOUBLE_QUOTE;
var opts = CSSESC_QUOTE_OPTIONS[quote];
var quoteValue = (0, cssesc_1.default)(v, opts);
if (quoteValue.length < escaped.length) {
return quote;
}
}
return pref;
}
}
else if (numDoubleQuotes === numSingleQuotes) {
return this.preferredQuoteMark(options);
}
else if (numDoubleQuotes < numSingleQuotes) {
return Attribute.DOUBLE_QUOTE;
}
else {
return Attribute.SINGLE_QUOTE;
}
};
/**
* Selects the preferred quote mark based on the options and the current quote mark value.
* If you want the quote mark to depend on the attribute value, call `smartQuoteMark(opts)`
* instead.
*/
Attribute.prototype.preferredQuoteMark = function (options) {
var quoteMark = options.preferCurrentQuoteMark ? this.quoteMark : options.quoteMark;
if (quoteMark === undefined) {
quoteMark = options.preferCurrentQuoteMark ? options.quoteMark : this.quoteMark;
}
if (quoteMark === undefined) {
quoteMark = Attribute.DOUBLE_QUOTE;
}
return quoteMark;
};
Object.defineProperty(Attribute.prototype, "quoted", {
get: function () {
var qm = this.quoteMark;
return qm === "'" || qm === '"';
},
set: function (value) {
warnOfDeprecatedQuotedAssignment();
},
enumerable: false,
configurable: true
});
Object.defineProperty(Attribute.prototype, "quoteMark", {
/**
* returns a single (`'`) or double (`"`) quote character if the value is quoted.
* returns `null` if the value is not quoted.
* returns `undefined` if the quotation state is unknown (this can happen when
* the attribute is constructed without specifying a quote mark.)
*/
get: function () {
return this._quoteMark;
},
/**
* Set the quote mark to be used by this attribute's value.
* If the quote mark changes, the raw (escaped) value at `attr.raws.value` of the attribute
* value is updated accordingly.
*
* @param {"'" | '"' | null} quoteMark The quote mark or `null` if the value should be unquoted.
*/
set: function (quoteMark) {
if (!this._constructed) {
this._quoteMark = quoteMark;
return;
}
if (this._quoteMark !== quoteMark) {
this._quoteMark = quoteMark;
this._syncRawValue();
}
},
enumerable: false,
configurable: true
});
Attribute.prototype._syncRawValue = function () {
var rawValue = (0, cssesc_1.default)(this._value, CSSESC_QUOTE_OPTIONS[this.quoteMark]);
if (rawValue === this._value) {
if (this.raws) {
delete this.raws.value;
}
}
else {
this.raws.value = rawValue;
}
};
Object.defineProperty(Attribute.prototype, "qualifiedAttribute", {
get: function () {
return this.qualifiedName(this.raws.attribute || this.attribute);
},
enumerable: false,
configurable: true
});
Object.defineProperty(Attribute.prototype, "insensitiveFlag", {
get: function () {
return this.insensitive ? "i" : "";
},
enumerable: false,
configurable: true
});
Object.defineProperty(Attribute.prototype, "sensitiveFlag", {
get: function () {
return this.sensitive ? "s" : "";
},
enumerable: false,
configurable: true
});
Object.defineProperty(Attribute.prototype, "value", {
get: function () {
return this._value;
},
/**
* Before 3.0, the value had to be set to an escaped value including any wrapped
* quote marks. In 3.0, the semantics of `Attribute.value` changed so that the value
* is unescaped during parsing and any quote marks are removed.
*
* Because the ambiguity of this semantic change, if you set `attr.value = newValue`,
* a deprecation warning is raised when the new value contains any characters that would
* require escaping (including if it contains wrapped quotes).
*
* Instead, you should call `attr.setValue(newValue, opts)` and pass options that describe
* how the new value is quoted.
*/
set: function (v) {
if (this._constructed) {
var _a = unescapeValue(v), deprecatedUsage = _a.deprecatedUsage, unescaped = _a.unescaped, quoteMark = _a.quoteMark;
if (deprecatedUsage) {
warnOfDeprecatedValueAssignment();
}
if (unescaped === this._value && quoteMark === this._quoteMark) {
return;
}
this._value = unescaped;
this._quoteMark = quoteMark;
this._syncRawValue();
}
else {
this._value = v;
}
},
enumerable: false,
configurable: true
});
Object.defineProperty(Attribute.prototype, "insensitive", {
get: function () {
return this._insensitive;
},
/**
* Set the case insensitive flag.
* If the case insensitive flag changes, the raw (escaped) value at `attr.raws.insensitiveFlag`
* of the attribute is updated accordingly.
*
* The two case sensitivity flags are mutually exclusive, so setting this flag
* clears `attr.sensitive` and any `s`/`S` in `attr.raws.sensitiveFlag`.
*
* @param {true | false} insensitive true if the attribute should match case-insensitively.
*/
set: function (insensitive) {
if (insensitive) {
// `[attr=value i s]` is not a thing, so adopting the case-insensitive flag
// drops the explicit case-sensitive flag and its original notation.
this.sensitive = false;
}
else if (this.raws &&
(this.raws.insensitiveFlag === "I" || this.raws.insensitiveFlag === "i")) {
// "i" and "I" can be used in "this.raws.insensitiveFlag" to store the original notation.
// When setting `attr.insensitive = false` both should be erased to ensure correct serialization.
this.raws.insensitiveFlag = undefined;
}
this._insensitive = insensitive;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Attribute.prototype, "sensitive", {
get: function () {
return this._sensitive;
},
/**
* Set the explicit case sensitive flag (Selectors Level 4 `s`).
* If the case sensitive flag changes, the raw (escaped) value at `attr.raws.sensitiveFlag`
* of the attribute is updated accordingly.
*
* The two case sensitivity flags are mutually exclusive, so setting this flag
* clears `attr.insensitive` and any `i`/`I` in `attr.raws.insensitiveFlag`.
*
* @param {true | false} sensitive true if the attribute should match case-sensitively.
*/
set: function (sensitive) {
if (sensitive) {
// `[attr=value s i]` is not a thing, so adopting the case-sensitive flag
// drops the case-insensitive flag and its original notation. Only the
// standard "i"/"I" notations are erased, so a non-standard flag kept in
// "this.raws.insensitiveFlag" survives and can still be round-tripped.
this.insensitive = false;
}
else if (this.raws && (this.raws.sensitiveFlag === "S" || this.raws.sensitiveFlag === "s")) {
// "s" and "S" can be used in "this.raws.sensitiveFlag" to store the original notation.
// When setting `attr.sensitive = false` both should be erased to ensure correct serialization.
this.raws.sensitiveFlag = undefined;
}
this._sensitive = sensitive;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Attribute.prototype, "attribute", {
get: function () {
return this._attribute;
},
set: function (name) {
this._handleEscapes("attribute", name);
this._attribute = name;
},
enumerable: false,
configurable: true
});
Attribute.prototype._handleEscapes = function (prop, value) {
if (this._constructed) {
var escaped = (0, cssesc_1.default)(value, { isIdentifier: true });
if (escaped !== value) {
this.raws[prop] = escaped;
}
else {
delete this.raws[prop];
}
}
};
Attribute.prototype._spacesFor = function (name) {
var attrSpaces = { before: "", after: "" };
var spaces = this.spaces[name] || {};
var rawSpaces = (this.raws.spaces && this.raws.spaces[name]) || {};
return Object.assign(attrSpaces, spaces, rawSpaces);
};
Attribute.prototype._stringFor = function (name, spaceName, concat) {
if (spaceName === void 0) { spaceName = name; }
if (concat === void 0) { concat = defaultAttrConcat; }
var attrSpaces = this._spacesFor(spaceName);
return concat(this.stringifyProperty(name), attrSpaces);
};
/**
* returns the offset of the attribute part specified relative to the
* start of the node of the output string.
*
* * "ns" - alias for "namespace"
* * "namespace" - the namespace if it exists.
* * "attribute" - the attribute name
* * "attributeNS" - the start of the attribute or its namespace
* * "operator" - the match operator of the attribute
* * "value" - The value (string or identifier)
* * "insensitive" - the case insensitivity flag;
* * "sensitive" - the explicit case sensitivity flag;
* @param part One of the possible values inside an attribute.
* @returns -1 if the name is invalid or the value doesn't exist in this attribute.
*/
Attribute.prototype.offsetOf = function (name) {
var count = 1;
var attributeSpaces = this._spacesFor("attribute");
count += attributeSpaces.before.length;
if (name === "namespace" || name === "ns") {
return this.namespace ? count : -1;
}
if (name === "attributeNS") {
return count;
}
count += this.namespaceString.length;
if (this.namespace) {
count += 1;
}
if (name === "attribute") {
return count;
}
count += this.stringifyProperty("attribute").length;
count += attributeSpaces.after.length;
var operatorSpaces = this._spacesFor("operator");
count += operatorSpaces.before.length;
var operator = this.stringifyProperty("operator");
if (name === "operator") {
return operator ? count : -1;
}
count += operator.length;
count += operatorSpaces.after.length;
var valueSpaces = this._spacesFor("value");
count += valueSpaces.before.length;
var value = this.stringifyProperty("value");
if (name === "value") {
return value ? count : -1;
}
count += value.length;
count += valueSpaces.after.length;
// Both case sensitivity flags occupy the same slot after the value, so they
// share the "insensitive" spaces. Each name only resolves when its own flag
// is the one actually present.
var insensitiveSpaces = this._spacesFor("insensitive");
count += insensitiveSpaces.before.length;
if (name === "insensitive") {
return this.insensitive ? count : -1;
}
if (name === "sensitive") {
return this.sensitive ? count : -1;
}
return -1;
};
Attribute.prototype.toString = function () {
var _this = this;
var selector = [this.rawSpaceBefore, "["];
selector.push(this._stringFor("qualifiedAttribute", "attribute"));
if (this.operator && (this.value || this.value === "")) {
selector.push(this._stringFor("operator"));
selector.push(this._stringFor("value"));
// The case-sensitivity flag occupies a single slot after the value.
// Prefer the explicit case-sensitive flag ("s"/"S") when present,
// otherwise fall back to the case-insensitive flag ("i"/"I") or any
// non-standard flag preserved in `raws.insensitiveFlag`.
var flagProperty = this.sensitive ? "sensitiveFlag" : "insensitiveFlag";
selector.push(this._stringFor(flagProperty, "insensitive", function (attrValue, attrSpaces) {
if (attrValue.length > 0 &&
!_this.quoted &&
attrSpaces.before.length === 0 &&
!(_this.spaces.value && _this.spaces.value.after)) {
attrSpaces.before = " ";
}
return defaultAttrConcat(attrValue, attrSpaces);
}));
}
selector.push("]");
selector.push(this.rawSpaceAfter);
return selector.join("");
};
Attribute.NO_QUOTE = null;
Attribute.SINGLE_QUOTE = "'";
Attribute.DOUBLE_QUOTE = '"';
return Attribute;
}(namespace_1.default));
exports.default = Attribute;
var CSSESC_QUOTE_OPTIONS = (_a = {
"'": { quotes: "single", wrap: true },
'"': { quotes: "double", wrap: true }
},
_a[null] = { isIdentifier: true },
_a);
function defaultAttrConcat(attrValue, attrSpaces) {
return "".concat(attrSpaces.before).concat(attrValue).concat(attrSpaces.after);
}
//# sourceMappingURL=attribute.js.map
@@ -0,0 +1,59 @@
"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 __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var cssesc_1 = __importDefault(require("../util/cssesc"));
var util_1 = require("../util");
var node_1 = __importDefault(require("./node"));
var types_1 = require("./types");
var ClassName = /** @class */ (function (_super) {
__extends(ClassName, _super);
function ClassName(opts) {
var _this = _super.call(this, opts) || this;
_this.type = types_1.CLASS;
_this._constructed = true;
return _this;
}
Object.defineProperty(ClassName.prototype, "value", {
get: function () {
return this._value;
},
set: function (v) {
if (this._constructed) {
var escaped = (0, cssesc_1.default)(v, { isIdentifier: true });
if (escaped !== v) {
(0, util_1.ensureObject)(this, "raws");
this.raws.value = escaped;
}
else if (this.raws) {
delete this.raws.value;
}
}
this._value = v;
},
enumerable: false,
configurable: true
});
ClassName.prototype.valueToString = function () {
return "." + _super.prototype.valueToString.call(this);
};
return ClassName;
}(node_1.default));
exports.default = ClassName;
//# sourceMappingURL=className.js.map
@@ -0,0 +1,47 @@
"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 __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var node_1 = __importDefault(require("./node"));
var types_1 = require("./types");
var Combinator = /** @class */ (function (_super) {
__extends(Combinator, _super);
function Combinator(opts) {
var _this = _super.call(this, opts) || this;
_this.type = types_1.COMBINATOR;
_this._constructed = true;
return _this;
}
Object.defineProperty(Combinator.prototype, "value", {
get: function () {
return this._value;
},
set: function (value) {
if (this._constructed && this.raws) {
delete this.raws.value;
}
this._value = value;
},
enumerable: false,
configurable: true
});
return Combinator;
}(node_1.default));
exports.default = Combinator;
//# sourceMappingURL=combinator.js.map
@@ -0,0 +1,33 @@
"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 __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var node_1 = __importDefault(require("./node"));
var types_1 = require("./types");
var Comment = /** @class */ (function (_super) {
__extends(Comment, _super);
function Comment(opts) {
var _this = _super.call(this, opts) || this;
_this.type = types_1.COMMENT;
return _this;
}
return Comment;
}(node_1.default));
exports.default = Comment;
//# sourceMappingURL=comment.js.map
@@ -0,0 +1,43 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.universal = exports.tag = exports.string = exports.selector = exports.root = exports.pseudo = exports.nesting = exports.id = exports.comment = exports.combinator = exports.className = exports.attribute = void 0;
var attribute_1 = __importDefault(require("./attribute"));
var className_1 = __importDefault(require("./className"));
var combinator_1 = __importDefault(require("./combinator"));
var comment_1 = __importDefault(require("./comment"));
var id_1 = __importDefault(require("./id"));
var nesting_1 = __importDefault(require("./nesting"));
var pseudo_1 = __importDefault(require("./pseudo"));
var root_1 = __importDefault(require("./root"));
var selector_1 = __importDefault(require("./selector"));
var string_1 = __importDefault(require("./string"));
var tag_1 = __importDefault(require("./tag"));
var universal_1 = __importDefault(require("./universal"));
var attribute = function (opts) { return new attribute_1.default(opts); };
exports.attribute = attribute;
var className = function (opts) { return new className_1.default(opts); };
exports.className = className;
var combinator = function (opts) { return new combinator_1.default(opts); };
exports.combinator = combinator;
var comment = function (opts) { return new comment_1.default(opts); };
exports.comment = comment;
var id = function (opts) { return new id_1.default(opts); };
exports.id = id;
var nesting = function (opts) { return new nesting_1.default(opts); };
exports.nesting = nesting;
var pseudo = function (opts) { return new pseudo_1.default(opts); };
exports.pseudo = pseudo;
var root = function (opts) { return new root_1.default(opts); };
exports.root = root;
var selector = function (opts) { return new selector_1.default(opts); };
exports.selector = selector;
var string = function (opts) { return new string_1.default(opts); };
exports.string = string;
var tag = function (opts) { return new tag_1.default(opts); };
exports.tag = tag;
var universal = function (opts) { return new universal_1.default(opts); };
exports.universal = universal;
//# sourceMappingURL=constructors.js.map
@@ -0,0 +1,436 @@
"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 __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 __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 () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
var __values = (this && this.__values) || function(o) {
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
if (m) return m.call(o);
if (o && typeof o.length === "number") return {
next: function () {
if (o && i >= o.length) o = void 0;
return { value: o && o[i++], done: !o };
}
};
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
var __read = (this && this.__read) || function (o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
};
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
if (ar || !(i in from)) {
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
ar[i] = from[i];
}
}
return to.concat(ar || Array.prototype.slice.call(from));
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var util_1 = require("../util");
var node_1 = __importDefault(require("./node"));
var types = __importStar(require("./types"));
var Container = /** @class */ (function (_super) {
__extends(Container, _super);
function Container(opts) {
var _this = _super.call(this, opts) || this;
if (!_this.nodes) {
_this.nodes = [];
}
return _this;
}
Container.prototype.append = function (selector) {
selector.parent = this;
this.nodes.push(selector);
return this;
};
Container.prototype.prepend = function (selector) {
selector.parent = this;
this.nodes.unshift(selector);
for (var id in this.indexes) {
this.indexes[id]++;
}
return this;
};
Container.prototype.at = function (index) {
return this.nodes[index];
};
Container.prototype.index = function (child) {
if (typeof child === "number") {
return child;
}
return this.nodes.indexOf(child);
};
Object.defineProperty(Container.prototype, "first", {
get: function () {
return this.at(0);
},
enumerable: false,
configurable: true
});
Object.defineProperty(Container.prototype, "last", {
get: function () {
return this.at(this.length - 1);
},
enumerable: false,
configurable: true
});
Object.defineProperty(Container.prototype, "length", {
get: function () {
return this.nodes.length;
},
enumerable: false,
configurable: true
});
Container.prototype.removeChild = function (child) {
child = this.index(child);
this.at(child).parent = undefined;
this.nodes.splice(child, 1);
var index;
for (var id in this.indexes) {
index = this.indexes[id];
if (index >= child) {
this.indexes[id] = index - 1;
}
}
return this;
};
Container.prototype.removeAll = function () {
var e_1, _a;
try {
for (var _b = __values(this.nodes), _c = _b.next(); !_c.done; _c = _b.next()) {
var node = _c.value;
node.parent = undefined;
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
}
finally { if (e_1) throw e_1.error; }
}
this.nodes = [];
return this;
};
Container.prototype.empty = function () {
return this.removeAll();
};
Container.prototype.insertAfter = function (oldNode, newNode) {
var _a;
newNode.parent = this;
var oldIndex = this.index(oldNode);
var resetNode = [];
for (var i = 2; i < arguments.length; i++) {
arguments[i].parent = this;
resetNode.push(arguments[i]);
}
(_a = this.nodes).splice.apply(_a, __spreadArray([oldIndex + 1, 0, newNode], __read(resetNode), false));
newNode.parent = this;
var index;
for (var id in this.indexes) {
index = this.indexes[id];
if (oldIndex < index) {
this.indexes[id] = index + arguments.length - 1;
}
}
return this;
};
Container.prototype.insertBefore = function (oldNode, newNode) {
var _a;
newNode.parent = this;
var oldIndex = this.index(oldNode);
var resetNode = [];
for (var i = 2; i < arguments.length; i++) {
arguments[i].parent = this;
resetNode.push(arguments[i]);
}
(_a = this.nodes).splice.apply(_a, __spreadArray([oldIndex, 0, newNode], __read(resetNode), false));
newNode.parent = this;
var index;
for (var id in this.indexes) {
index = this.indexes[id];
if (index >= oldIndex) {
this.indexes[id] = index + arguments.length - 1;
}
}
return this;
};
Container.prototype._findChildAtPosition = function (line, col) {
var found = undefined;
this.each(function (node) {
if (node.atPosition) {
var foundChild = node.atPosition(line, col);
if (foundChild) {
found = foundChild;
return false;
}
}
else if (node.isAtPosition(line, col)) {
found = node;
return false;
}
});
return found;
};
/**
* Return the most specific node at the line and column number given.
* The source location is based on the original parsed location, locations aren't
* updated as selector nodes are mutated.
*
* Note that this location is relative to the location of the first character
* of the selector, and not the location of the selector in the overall document
* when used in conjunction with postcss.
*
* If not found, returns undefined.
* @param {number} line The line number of the node to find. (1-based index)
* @param {number} col The column number of the node to find. (1-based index)
*/
Container.prototype.atPosition = function (line, col) {
if (this.isAtPosition(line, col)) {
return this._findChildAtPosition(line, col) || this;
}
else {
return undefined;
}
};
Container.prototype._inferEndPosition = function () {
if (this.last && this.last.source && this.last.source.end) {
this.source = this.source || {};
this.source.end = this.source.end || {};
Object.assign(this.source.end, this.last.source.end);
}
};
Container.prototype.each = function (callback) {
if (!this.lastEach) {
this.lastEach = 0;
}
if (!this.indexes) {
this.indexes = {};
}
this.lastEach++;
var id = this.lastEach;
this.indexes[id] = 0;
if (!this.length) {
return undefined;
}
var index, result;
while (this.indexes[id] < this.length) {
index = this.indexes[id];
result = callback(this.at(index), index);
if (result === false) {
break;
}
this.indexes[id] += 1;
}
delete this.indexes[id];
if (result === false) {
return false;
}
};
Container.prototype.walk = function (callback, depth) {
if (depth === void 0) { depth = 0; }
// Bound recursion so a pathologically deep node tree raises a catchable
// error instead of overflowing the call stack (CVE-2026-9358 / CWE-674).
if (depth > util_1.MAX_NESTING_DEPTH) {
throw new Error("Cannot walk selector: nesting depth exceeds the maximum of ".concat(util_1.MAX_NESTING_DEPTH, "."));
}
return this.each(function (node, i) {
var result = callback(node, i);
if (result !== false && node.length) {
result = node.walk(callback, depth + 1);
}
if (result === false) {
return false;
}
});
};
Container.prototype.walkAttributes = function (callback) {
var _this = this;
return this.walk(function (selector) {
if (selector.type === types.ATTRIBUTE) {
return callback.call(_this, selector);
}
});
};
Container.prototype.walkClasses = function (callback) {
var _this = this;
return this.walk(function (selector) {
if (selector.type === types.CLASS) {
return callback.call(_this, selector);
}
});
};
Container.prototype.walkCombinators = function (callback) {
var _this = this;
return this.walk(function (selector) {
if (selector.type === types.COMBINATOR) {
return callback.call(_this, selector);
}
});
};
Container.prototype.walkComments = function (callback) {
var _this = this;
return this.walk(function (selector) {
if (selector.type === types.COMMENT) {
return callback.call(_this, selector);
}
});
};
Container.prototype.walkIds = function (callback) {
var _this = this;
return this.walk(function (selector) {
if (selector.type === types.ID) {
return callback.call(_this, selector);
}
});
};
Container.prototype.walkNesting = function (callback) {
var _this = this;
return this.walk(function (selector) {
if (selector.type === types.NESTING) {
return callback.call(_this, selector);
}
});
};
Container.prototype.walkPseudos = function (callback) {
var _this = this;
return this.walk(function (selector) {
if (selector.type === types.PSEUDO) {
return callback.call(_this, selector);
}
});
};
Container.prototype.walkTags = function (callback) {
var _this = this;
return this.walk(function (selector) {
if (selector.type === types.TAG) {
return callback.call(_this, selector);
}
});
};
Container.prototype.walkUniversals = function (callback) {
var _this = this;
return this.walk(function (selector) {
if (selector.type === types.UNIVERSAL) {
return callback.call(_this, selector);
}
});
};
Container.prototype.split = function (callback) {
var _this = this;
var current = [];
return this.reduce(function (memo, node, index) {
var split = callback.call(_this, node);
current.push(node);
if (split) {
memo.push(current);
current = [];
}
else if (index === _this.length - 1) {
memo.push(current);
}
return memo;
}, []);
};
Container.prototype.map = function (callback) {
return this.nodes.map(callback);
};
Container.prototype.reduce = function (callback, memo) {
return this.nodes.reduce(callback, memo);
};
Container.prototype.every = function (callback) {
return this.nodes.every(callback);
};
Container.prototype.some = function (callback) {
return this.nodes.some(callback);
};
Container.prototype.filter = function (callback) {
return this.nodes.filter(callback);
};
Container.prototype.sort = function (callback) {
return this.nodes.sort(callback);
};
Container.prototype.toString = function (options) {
if (options === void 0) { options = {}; }
return this._stringify(options, 0, (0, util_1.resolveMaxNestingDepth)(options.maxNestingDepth));
};
Container.prototype._stringify = function (options, depth, max) {
var _this = this;
var str = this.map(function (child) { return _this._stringifyChild(child, options, depth, max); }).join("");
return [this.rawSpaceBefore, str, this.rawSpaceAfter].join("");
};
// Serialize a child node. Historically `toString` used `this.map(String)`,
// which leniently coerced anything — including raw arrays inserted via
// `replaceWith(array)` / `insertBefore` / `insertAfter` (e.g. Tailwind's
// `:merge()` expansion). Fall back to `String(child)` for values that are not
// parser nodes so that behaviour is preserved.
Container.prototype._stringifyChild = function (child, options, depth, max) {
return typeof child._stringify === "function"
? child._stringify(options, depth, max)
: String(child);
};
return Container;
}(node_1.default));
exports.default = Container;
//# sourceMappingURL=container.js.map
@@ -0,0 +1,61 @@
"use strict";
var _a;
Object.defineProperty(exports, "__esModule", { value: true });
exports.isUniversal = exports.isTag = exports.isString = exports.isSelector = exports.isRoot = exports.isPseudo = exports.isNesting = exports.isIdentifier = exports.isComment = exports.isCombinator = exports.isClassName = exports.isAttribute = void 0;
exports.isNode = isNode;
exports.isPseudoElement = isPseudoElement;
exports.isPseudoClass = isPseudoClass;
exports.isContainer = isContainer;
exports.isNamespace = isNamespace;
var types_1 = require("./types");
var IS_TYPE = (_a = {},
_a[types_1.ATTRIBUTE] = true,
_a[types_1.CLASS] = true,
_a[types_1.COMBINATOR] = true,
_a[types_1.COMMENT] = true,
_a[types_1.ID] = true,
_a[types_1.NESTING] = true,
_a[types_1.PSEUDO] = true,
_a[types_1.ROOT] = true,
_a[types_1.SELECTOR] = true,
_a[types_1.STRING] = true,
_a[types_1.TAG] = true,
_a[types_1.UNIVERSAL] = true,
_a);
function isNode(node) {
return typeof node === "object" && IS_TYPE[node.type];
}
function isNodeType(type, node) {
return isNode(node) && node.type === type;
}
exports.isAttribute = isNodeType.bind(null, types_1.ATTRIBUTE);
exports.isClassName = isNodeType.bind(null, types_1.CLASS);
exports.isCombinator = isNodeType.bind(null, types_1.COMBINATOR);
exports.isComment = isNodeType.bind(null, types_1.COMMENT);
exports.isIdentifier = isNodeType.bind(null, types_1.ID);
exports.isNesting = isNodeType.bind(null, types_1.NESTING);
exports.isPseudo = isNodeType.bind(null, types_1.PSEUDO);
exports.isRoot = isNodeType.bind(null, types_1.ROOT);
exports.isSelector = isNodeType.bind(null, types_1.SELECTOR);
exports.isString = isNodeType.bind(null, types_1.STRING);
exports.isTag = isNodeType.bind(null, types_1.TAG);
exports.isUniversal = isNodeType.bind(null, types_1.UNIVERSAL);
function isPseudoElement(node) {
return ((0, exports.isPseudo)(node) &&
node.value &&
(node.value.startsWith("::") ||
node.value.toLowerCase() === ":before" ||
node.value.toLowerCase() === ":after" ||
node.value.toLowerCase() === ":first-letter" ||
node.value.toLowerCase() === ":first-line"));
}
function isPseudoClass(node) {
return (0, exports.isPseudo)(node) && !isPseudoElement(node);
}
function isContainer(node) {
return !!(isNode(node) && node.walk);
}
function isNamespace(node) {
return (0, exports.isAttribute)(node) || (0, exports.isTag)(node);
}
//# sourceMappingURL=guards.js.map
@@ -0,0 +1,36 @@
"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 __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var node_1 = __importDefault(require("./node"));
var types_1 = require("./types");
var ID = /** @class */ (function (_super) {
__extends(ID, _super);
function ID(opts) {
var _this = _super.call(this, opts) || this;
_this.type = types_1.ID;
return _this;
}
ID.prototype.valueToString = function () {
return "#" + _super.prototype.valueToString.call(this);
};
return ID;
}(node_1.default));
exports.default = ID;
//# sourceMappingURL=id.js.map
@@ -0,0 +1,20 @@
"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 });
__exportStar(require("./types"), exports);
__exportStar(require("./constructors"), exports);
__exportStar(require("./guards"), exports);
//# sourceMappingURL=index.js.map
@@ -0,0 +1,96 @@
"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 __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var cssesc_1 = __importDefault(require("../util/cssesc"));
var util_1 = require("../util");
var node_1 = __importDefault(require("./node"));
var Namespace = /** @class */ (function (_super) {
__extends(Namespace, _super);
function Namespace() {
return _super !== null && _super.apply(this, arguments) || this;
}
Object.defineProperty(Namespace.prototype, "namespace", {
get: function () {
return this._namespace;
},
set: function (namespace) {
if (namespace === true || namespace === "*" || namespace === "&") {
this._namespace = namespace;
if (this.raws) {
delete this.raws.namespace;
}
return;
}
var escaped = (0, cssesc_1.default)(namespace, { isIdentifier: true });
this._namespace = namespace;
if (escaped !== namespace) {
(0, util_1.ensureObject)(this, "raws");
this.raws.namespace = escaped;
}
else if (this.raws) {
delete this.raws.namespace;
}
},
enumerable: false,
configurable: true
});
Object.defineProperty(Namespace.prototype, "ns", {
get: function () {
return this._namespace;
},
set: function (namespace) {
this.namespace = namespace;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Namespace.prototype, "namespaceString", {
get: function () {
if (this.namespace) {
var ns = this.stringifyProperty("namespace");
if (ns === true) {
return "";
}
else {
return ns;
}
}
else {
return "";
}
},
enumerable: false,
configurable: true
});
Namespace.prototype.qualifiedName = function (value) {
if (this.namespace) {
return "".concat(this.namespaceString, "|").concat(value);
}
else {
return value;
}
};
Namespace.prototype.valueToString = function () {
return this.qualifiedName(_super.prototype.valueToString.call(this));
};
return Namespace;
}(node_1.default));
exports.default = Namespace;
//# sourceMappingURL=namespace.js.map
@@ -0,0 +1,34 @@
"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 __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var node_1 = __importDefault(require("./node"));
var types_1 = require("./types");
var Nesting = /** @class */ (function (_super) {
__extends(Nesting, _super);
function Nesting(opts) {
var _this = _super.call(this, opts) || this;
_this.type = types_1.NESTING;
_this.value = "&";
return _this;
}
return Nesting;
}(node_1.default));
exports.default = Nesting;
//# sourceMappingURL=nesting.js.map
@@ -0,0 +1,195 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var util_1 = require("../util");
var cloneNode = function (obj, parent, depth) {
if (depth === void 0) { depth = 0; }
// Bound recursion so a pathologically deep node tree raises a catchable
// error instead of overflowing the call stack (CVE-2026-9358 / CWE-674).
if (depth > util_1.MAX_NESTING_DEPTH) {
throw new Error("Cannot clone selector: nesting depth exceeds the maximum of ".concat(util_1.MAX_NESTING_DEPTH, "."));
}
if (typeof obj !== "object" || obj === null) {
return obj;
}
var cloned = new obj.constructor();
for (var i in obj) {
if (!obj.hasOwnProperty(i)) {
continue;
}
var value = obj[i];
var type = typeof value;
if (i === "parent" && type === "object") {
if (parent) {
cloned[i] = parent;
}
}
else if (value instanceof Array) {
cloned[i] = value.map(function (j) { return cloneNode(j, cloned, depth + 1); });
}
else {
cloned[i] = cloneNode(value, cloned, depth + 1);
}
}
return cloned;
};
var Node = /** @class */ (function () {
function Node(opts) {
if (opts === void 0) { opts = {}; }
Object.assign(this, opts);
this.spaces = this.spaces || {};
this.spaces.before = this.spaces.before || "";
this.spaces.after = this.spaces.after || "";
}
Node.prototype.remove = function () {
if (this.parent) {
this.parent.removeChild(this);
}
this.parent = undefined;
return this;
};
Node.prototype.replaceWith = function () {
if (this.parent) {
for (var index in arguments) {
this.parent.insertBefore(this, arguments[index]);
}
this.remove();
}
return this;
};
Node.prototype.next = function () {
return this.parent.at(this.parent.index(this) + 1);
};
Node.prototype.prev = function () {
return this.parent.at(this.parent.index(this) - 1);
};
Node.prototype.clone = function (overrides) {
if (overrides === void 0) { overrides = {}; }
var cloned = cloneNode(this);
for (var name in overrides) {
cloned[name] = overrides[name];
}
return cloned;
};
/**
* Some non-standard syntax doesn't follow normal escaping rules for css.
* This allows non standard syntax to be appended to an existing property
* by specifying the escaped value. By specifying the escaped value,
* illegal characters are allowed to be directly inserted into css output.
* @param {string} name the property to set
* @param {any} value the unescaped value of the property
* @param {string} valueEscaped optional. the escaped value of the property.
*/
Node.prototype.appendToPropertyAndEscape = function (name, value, valueEscaped) {
if (!this.raws) {
this.raws = {};
}
var originalValue = this[name];
var originalEscaped = this.raws[name];
this[name] = originalValue + value; // this may trigger a setter that updates raws, so it has to be set first.
if (originalEscaped || valueEscaped !== value) {
this.raws[name] = (originalEscaped || originalValue) + valueEscaped;
}
else {
delete this.raws[name]; // delete any escaped value that was created by the setter.
}
};
/**
* Some non-standard syntax doesn't follow normal escaping rules for css.
* This allows the escaped value to be specified directly, allowing illegal
* characters to be directly inserted into css output.
* @param {string} name the property to set
* @param {any} value the unescaped value of the property
* @param {string} valueEscaped the escaped value of the property.
*/
Node.prototype.setPropertyAndEscape = function (name, value, valueEscaped) {
if (!this.raws) {
this.raws = {};
}
this[name] = value; // this may trigger a setter that updates raws, so it has to be set first.
this.raws[name] = valueEscaped;
};
/**
* When you want a value to passed through to CSS directly. This method
* deletes the corresponding raw value causing the stringifier to fallback
* to the unescaped value.
* @param {string} name the property to set.
* @param {any} value The value that is both escaped and unescaped.
*/
Node.prototype.setPropertyWithoutEscape = function (name, value) {
this[name] = value; // this may trigger a setter that updates raws, so it has to be set first.
if (this.raws) {
delete this.raws[name];
}
};
/**
*
* @param {number} line The number (starting with 1)
* @param {number} column The column number (starting with 1)
*/
Node.prototype.isAtPosition = function (line, column) {
if (this.source && this.source.start && this.source.end) {
if (this.source.start.line > line) {
return false;
}
if (this.source.end.line < line) {
return false;
}
if (this.source.start.line === line && this.source.start.column > column) {
return false;
}
if (this.source.end.line === line && this.source.end.column < column) {
return false;
}
return true;
}
return undefined;
};
Node.prototype.stringifyProperty = function (name) {
return (this.raws && this.raws[name]) || this[name];
};
Object.defineProperty(Node.prototype, "rawSpaceBefore", {
get: function () {
var rawSpace = this.raws && this.raws.spaces && this.raws.spaces.before;
if (rawSpace === undefined) {
rawSpace = this.spaces && this.spaces.before;
}
return rawSpace || "";
},
set: function (raw) {
(0, util_1.ensureObject)(this, "raws", "spaces");
this.raws.spaces.before = raw;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Node.prototype, "rawSpaceAfter", {
get: function () {
var rawSpace = this.raws && this.raws.spaces && this.raws.spaces.after;
if (rawSpace === undefined) {
rawSpace = this.spaces.after;
}
return rawSpace || "";
},
set: function (raw) {
(0, util_1.ensureObject)(this, "raws", "spaces");
this.raws.spaces.after = raw;
},
enumerable: false,
configurable: true
});
Node.prototype.valueToString = function () {
return String(this.stringifyProperty("value"));
};
Node.prototype.toString = function () {
return [this.rawSpaceBefore, this.valueToString(), this.rawSpaceAfter].join("");
};
// Internal recursion entry point used by Container serialization. Leaf
// nodes don't recurse, so they ignore the depth/limit and stringify
// themselves. Containers override this to thread the nesting depth.
Node.prototype._stringify = function () {
return this.toString();
};
return Node;
}());
exports.default = Node;
//# sourceMappingURL=node.js.map
@@ -0,0 +1,45 @@
"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 __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var container_1 = __importDefault(require("./container"));
var types_1 = require("./types");
var Pseudo = /** @class */ (function (_super) {
__extends(Pseudo, _super);
function Pseudo(opts) {
var _this = _super.call(this, opts) || this;
_this.type = types_1.PSEUDO;
return _this;
}
Pseudo.prototype._stringify = function (options, depth, max) {
var _this = this;
if (depth >= max) {
throw new Error("Cannot serialize selector: nesting depth exceeds the maximum of ".concat(max, "."));
}
var params = this.length
? "(" +
this.map(function (child) { return _this._stringifyChild(child, options, depth + 1, max); }).join(",") +
")"
: "";
return [this.rawSpaceBefore, this.stringifyProperty("value"), params, this.rawSpaceAfter].join("");
};
return Pseudo;
}(container_1.default));
exports.default = Pseudo;
//# sourceMappingURL=pseudo.js.map
@@ -0,0 +1,59 @@
"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 __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var container_1 = __importDefault(require("./container"));
var types_1 = require("./types");
var Root = /** @class */ (function (_super) {
__extends(Root, _super);
function Root(opts) {
var _this = _super.call(this, opts) || this;
_this.type = types_1.ROOT;
return _this;
}
Root.prototype._stringify = function (options, depth, max) {
var _this = this;
var str = this.reduce(function (memo, selector) {
memo.push(_this._stringifyChild(selector, options, depth, max));
return memo;
}, []).join(",");
if (this.trailingComma) {
str += ",";
}
return [this.rawSpaceBefore, str, this.rawSpaceAfter].join("");
};
Root.prototype.error = function (message, options) {
if (this._error) {
return this._error(message, options);
}
else {
return new Error(message);
}
};
Object.defineProperty(Root.prototype, "errorGenerator", {
set: function (handler) {
this._error = handler;
},
enumerable: false,
configurable: true
});
return Root;
}(container_1.default));
exports.default = Root;
//# sourceMappingURL=root.js.map
@@ -0,0 +1,33 @@
"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 __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var container_1 = __importDefault(require("./container"));
var types_1 = require("./types");
var Selector = /** @class */ (function (_super) {
__extends(Selector, _super);
function Selector(opts) {
var _this = _super.call(this, opts) || this;
_this.type = types_1.SELECTOR;
return _this;
}
return Selector;
}(container_1.default));
exports.default = Selector;
//# sourceMappingURL=selector.js.map
@@ -0,0 +1,33 @@
"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 __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var node_1 = __importDefault(require("./node"));
var types_1 = require("./types");
var String = /** @class */ (function (_super) {
__extends(String, _super);
function String(opts) {
var _this = _super.call(this, opts) || this;
_this.type = types_1.STRING;
return _this;
}
return String;
}(node_1.default));
exports.default = String;
//# sourceMappingURL=string.js.map
@@ -0,0 +1,33 @@
"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 __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var namespace_1 = __importDefault(require("./namespace"));
var types_1 = require("./types");
var Tag = /** @class */ (function (_super) {
__extends(Tag, _super);
function Tag(opts) {
var _this = _super.call(this, opts) || this;
_this.type = types_1.TAG;
return _this;
}
return Tag;
}(namespace_1.default));
exports.default = Tag;
//# sourceMappingURL=tag.js.map
@@ -0,0 +1,16 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.UNIVERSAL = exports.ATTRIBUTE = exports.CLASS = exports.COMBINATOR = exports.COMMENT = exports.ID = exports.NESTING = exports.PSEUDO = exports.ROOT = exports.SELECTOR = exports.STRING = exports.TAG = void 0;
exports.TAG = "tag";
exports.STRING = "string";
exports.SELECTOR = "selector";
exports.ROOT = "root";
exports.PSEUDO = "pseudo";
exports.NESTING = "nesting";
exports.ID = "id";
exports.COMMENT = "comment";
exports.COMBINATOR = "combinator";
exports.CLASS = "class";
exports.ATTRIBUTE = "attribute";
exports.UNIVERSAL = "universal";
//# sourceMappingURL=types.js.map
@@ -0,0 +1,34 @@
"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 __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var namespace_1 = __importDefault(require("./namespace"));
var types_1 = require("./types");
var Universal = /** @class */ (function (_super) {
__extends(Universal, _super);
function Universal(opts) {
var _this = _super.call(this, opts) || this;
_this.type = types_1.UNIVERSAL;
_this.value = "*";
return _this;
}
return Universal;
}(namespace_1.default));
exports.default = Universal;
//# sourceMappingURL=universal.js.map
@@ -0,0 +1,7 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = sortAscending;
function sortAscending(list) {
return list.sort(function (a, b) { return a - b; });
}
//# sourceMappingURL=sortAscending.js.map
@@ -0,0 +1,37 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.combinator = exports.word = exports.comment = exports.str = exports.tab = exports.newline = exports.feed = exports.cr = exports.backslash = exports.bang = exports.slash = exports.doubleQuote = exports.singleQuote = exports.space = exports.greaterThan = exports.pipe = exports.equals = exports.plus = exports.caret = exports.tilde = exports.dollar = exports.closeSquare = exports.openSquare = exports.closeParenthesis = exports.openParenthesis = exports.semicolon = exports.colon = exports.comma = exports.at = exports.asterisk = exports.ampersand = void 0;
exports.ampersand = 38; // `&`.charCodeAt(0);
exports.asterisk = 42; // `*`.charCodeAt(0);
exports.at = 64; // `@`.charCodeAt(0);
exports.comma = 44; // `,`.charCodeAt(0);
exports.colon = 58; // `:`.charCodeAt(0);
exports.semicolon = 59; // `;`.charCodeAt(0);
exports.openParenthesis = 40; // `(`.charCodeAt(0);
exports.closeParenthesis = 41; // `)`.charCodeAt(0);
exports.openSquare = 91; // `[`.charCodeAt(0);
exports.closeSquare = 93; // `]`.charCodeAt(0);
exports.dollar = 36; // `$`.charCodeAt(0);
exports.tilde = 126; // `~`.charCodeAt(0);
exports.caret = 94; // `^`.charCodeAt(0);
exports.plus = 43; // `+`.charCodeAt(0);
exports.equals = 61; // `=`.charCodeAt(0);
exports.pipe = 124; // `|`.charCodeAt(0);
exports.greaterThan = 62; // `>`.charCodeAt(0);
exports.space = 32; // ` `.charCodeAt(0);
exports.singleQuote = 39; // `'`.charCodeAt(0);
exports.doubleQuote = 34; // `"`.charCodeAt(0);
exports.slash = 47; // `/`.charCodeAt(0);
exports.bang = 33; // `!`.charCodeAt(0);
exports.backslash = 92; // '\\'.charCodeAt(0);
exports.cr = 13; // '\r'.charCodeAt(0);
exports.feed = 12; // '\f'.charCodeAt(0);
exports.newline = 10; // '\n'.charCodeAt(0);
exports.tab = 9; // '\t'.charCodeAt(0);
// Expose aliases primarily for readability.
exports.str = exports.singleQuote;
// No good single character representation!
exports.comment = -1;
exports.word = -2;
exports.combinator = -3;
//# sourceMappingURL=tokenTypes.js.map
@@ -0,0 +1,301 @@
"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 __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 () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
var _a, _b;
Object.defineProperty(exports, "__esModule", { value: true });
exports.FIELDS = void 0;
exports.default = tokenize;
var t = __importStar(require("./tokenTypes"));
var unescapable = (_a = {},
_a[t.tab] = true,
_a[t.newline] = true,
_a[t.cr] = true,
_a[t.feed] = true,
_a);
var wordDelimiters = (_b = {},
_b[t.space] = true,
_b[t.tab] = true,
_b[t.newline] = true,
_b[t.cr] = true,
_b[t.feed] = true,
_b[t.ampersand] = true,
_b[t.asterisk] = true,
_b[t.bang] = true,
_b[t.comma] = true,
_b[t.colon] = true,
_b[t.semicolon] = true,
_b[t.openParenthesis] = true,
_b[t.closeParenthesis] = true,
_b[t.openSquare] = true,
_b[t.closeSquare] = true,
_b[t.singleQuote] = true,
_b[t.doubleQuote] = true,
_b[t.plus] = true,
_b[t.pipe] = true,
_b[t.tilde] = true,
_b[t.greaterThan] = true,
_b[t.equals] = true,
_b[t.dollar] = true,
_b[t.caret] = true,
_b[t.slash] = true,
_b);
var hex = {};
var hexChars = "0123456789abcdefABCDEF";
for (var i = 0; i < hexChars.length; i++) {
hex[hexChars.charCodeAt(i)] = true;
}
/**
* Returns the last index of the bar css word
* @param {string} css The string in which the word begins
* @param {number} start The index into the string where word's first letter occurs
*/
function consumeWord(css, start) {
var next = start;
var code;
do {
code = css.charCodeAt(next);
if (wordDelimiters[code]) {
return next - 1;
}
else if (code === t.backslash) {
next = consumeEscape(css, next) + 1;
}
else {
// All other characters are part of the word
next++;
}
} while (next < css.length);
return next - 1;
}
/**
* Returns the last index of the escape sequence
* @param {string} css The string in which the sequence begins
* @param {number} start The index into the string where escape character (`\`) occurs.
*/
function consumeEscape(css, start) {
var next = start;
var code = css.charCodeAt(next + 1);
if (unescapable[code]) {
// just consume the escape char
}
else if (hex[code]) {
var hexDigits = 0;
// consume up to 6 hex chars
do {
next++;
hexDigits++;
code = css.charCodeAt(next + 1);
} while (hex[code] && hexDigits < 6);
// if fewer than 6 hex chars, a trailing space ends the escape
if (hexDigits < 6 && code === t.space) {
next++;
}
}
else {
// the next char is part of the current word
next++;
}
return next;
}
exports.FIELDS = {
TYPE: 0,
START_LINE: 1,
START_COL: 2,
END_LINE: 3,
END_COL: 4,
START_POS: 5,
END_POS: 6,
};
function tokenize(input) {
var tokens = [];
var css = input.css.valueOf();
var length = css.length;
var offset = -1;
var line = 1;
var start = 0;
var end = 0;
var code, content, endColumn, endLine, escaped, escapePos, last, lines, next, nextLine, nextOffset, quote, tokenType;
function unclosed(what, fix) {
if (input.safe) {
// fyi: this is never set to true.
css += fix;
next = css.length - 1;
}
else {
throw input.error("Unclosed " + what, line, start - offset, start);
}
}
while (start < length) {
code = css.charCodeAt(start);
if (code === t.newline) {
offset = start;
line += 1;
}
switch (code) {
case t.space:
case t.tab:
case t.newline:
case t.cr:
case t.feed:
next = start;
do {
next += 1;
code = css.charCodeAt(next);
if (code === t.newline) {
offset = next;
line += 1;
}
} while (code === t.space ||
code === t.newline ||
code === t.tab ||
code === t.cr ||
code === t.feed);
tokenType = t.space;
endLine = line;
endColumn = next - offset - 1;
end = next;
break;
case t.plus:
case t.greaterThan:
case t.tilde:
case t.pipe:
next = start;
do {
next += 1;
code = css.charCodeAt(next);
} while (code === t.plus || code === t.greaterThan || code === t.tilde || code === t.pipe);
tokenType = t.combinator;
endLine = line;
endColumn = start - offset;
end = next;
break;
// Consume these characters as single tokens.
case t.asterisk:
case t.ampersand:
case t.bang:
case t.comma:
case t.equals:
case t.dollar:
case t.caret:
case t.openSquare:
case t.closeSquare:
case t.colon:
case t.semicolon:
case t.openParenthesis:
case t.closeParenthesis:
next = start;
tokenType = code;
endLine = line;
endColumn = start - offset;
end = next + 1;
break;
case t.singleQuote:
case t.doubleQuote:
quote = code === t.singleQuote ? "'" : '"';
next = start;
do {
escaped = false;
next = css.indexOf(quote, next + 1);
if (next === -1) {
unclosed("quote", quote);
}
escapePos = next;
while (css.charCodeAt(escapePos - 1) === t.backslash) {
escapePos -= 1;
escaped = !escaped;
}
} while (escaped);
tokenType = t.str;
endLine = line;
endColumn = start - offset;
end = next + 1;
break;
default:
if (code === t.slash && css.charCodeAt(start + 1) === t.asterisk) {
next = css.indexOf("*/", start + 2) + 1;
if (next === 0) {
unclosed("comment", "*/");
}
content = css.slice(start, next + 1);
lines = content.split("\n");
last = lines.length - 1;
if (last > 0) {
nextLine = line + last;
nextOffset = next - lines[last].length;
}
else {
nextLine = line;
nextOffset = offset;
}
tokenType = t.comment;
line = nextLine;
endLine = nextLine;
endColumn = next - nextOffset;
}
else if (code === t.slash) {
next = start;
tokenType = code;
endLine = line;
endColumn = start - offset;
end = next + 1;
}
else {
next = consumeWord(css, start);
tokenType = t.word;
endLine = line;
endColumn = next - offset;
}
end = next + 1;
break;
}
// Ensure that the token structure remains consistent
tokens.push([
tokenType, // [0] Token type
line, // [1] Starting line
start - offset, // [2] Starting column
endLine, // [3] Ending line
endColumn, // [4] Ending column
start, // [5] Start position / Source index
end, // [6] End position
]);
// Reset offset for the next token
if (nextOffset) {
offset = nextOffset;
nextOffset = null;
}
start = end;
}
return tokens;
}
//# sourceMappingURL=tokenize.js.map
@@ -0,0 +1,182 @@
"use strict";
/*!
* Adapted from cssesc v3.0.0 <https://mths.be/cssesc>
*
* Copyright Mathias Bynens <https://mathiasbynens.be/>
*
* 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.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = cssesc;
// The only behavioural difference from cssesc 3.0.0 is how redundant spaces
// after `\HEX` escapes are removed: upstream uses a regular expression that
// backtracks quadratically on long runs of backslashes, which a crafted
// selector could use to pin a CPU core. removeExcessiveSpaces() produces the
// same output in linear time. Upstream has not been released since 2019, and
// the pending fix there (mathiasbynens/cssesc#36) changes the output. An
// unreachable branch escaping \t, \n, \f, \r and \x0B was also dropped: those
// characters are below 0x20 and always take the hex escape path first.
var DEFAULTS = {
escapeEverything: false,
isIdentifier: false,
quotes: "single",
wrap: false,
};
var hasOwnProperty = Object.prototype.hasOwnProperty;
function merge(options, defaults) {
if (!options) {
return defaults;
}
var result = {};
for (var key in defaults) {
result[key] = hasOwnProperty.call(options, key) ? options[key] : defaults[key];
}
return result;
}
var regexAnySingleEscape = /[ -,./:-@[-^`{-~]/;
var regexSingleEscape = /[ -,./:-@[\]^`{-~]/;
var BACKSLASH = 0x5c;
var SPACE = 0x20;
function isUpperHex(code) {
return (code >= 0x30 && code <= 0x39) || (code >= 0x41 && code <= 0x46);
}
function isHexOrSpace(code) {
return isUpperHex(code) || (code >= 0x61 && code <= 0x66) || code === SPACE;
}
/**
* Remove spaces after `\HEX` escapes that are not followed by a hex digit or a
* space, since they are redundant. This is only possible if the escape is not
* preceded by an odd number of backslashes, which would make its own backslash
* an escaped one.
*
* Same result as cssesc 3.0.0's
* `output.replace(/(^|\\+)?(\\[A-F0-9]{1,6})\x20(?![a-fA-F0-9\x20])/g, ...)`:
* a match can only start at the beginning of a run of backslashes and only
* its last backslash can open the escape, so each run is measured once
* instead of being re-scanned from every position inside it.
*/
function removeExcessiveSpaces(output) {
var length = output.length;
var result = "";
var copied = 0;
var i = 0;
while (i < length) {
if (output.charCodeAt(i) !== BACKSLASH) {
i++;
continue;
}
var runEnd = i + 1;
while (runEnd < length && output.charCodeAt(runEnd) === BACKSLASH) {
runEnd++;
}
// Look at up to 7 hex digits: more than 6 can never be followed directly
// by the space.
var hexEnd = runEnd;
while (hexEnd < length && hexEnd - runEnd < 7 && isUpperHex(output.charCodeAt(hexEnd))) {
hexEnd++;
}
var hexLength = hexEnd - runEnd;
if (hexLength >= 1 &&
hexLength <= 6 &&
output.charCodeAt(hexEnd) === SPACE &&
!isHexOrSpace(output.charCodeAt(hexEnd + 1))) {
// Backslashes preceding the one that opens the escape.
if ((runEnd - i - 1) % 2 === 0) {
result += output.slice(copied, hexEnd);
copied = hexEnd + 1;
}
i = hexEnd + 1;
}
else {
i = runEnd;
}
}
return copied === 0 ? output : result + output.slice(copied);
}
// https://mathiasbynens.be/notes/css-escapes#css
function cssesc(string, options) {
options = merge(options, DEFAULTS);
if (options.quotes !== "single" && options.quotes !== "double") {
options.quotes = "single";
}
var quote = options.quotes === "double" ? '"' : "'";
var isIdentifier = options.isIdentifier;
var firstChar = string.charAt(0);
var output = "";
var counter = 0;
var length = string.length;
while (counter < length) {
var character = string.charAt(counter++);
var codePoint = character.charCodeAt(0);
var value = void 0;
// If it's not a printable ASCII character...
if (codePoint < 0x20 || codePoint > 0x7e) {
if (codePoint >= 0xd800 && codePoint <= 0xdbff && counter < length) {
// It's a high surrogate, and there is a next character.
var extra = string.charCodeAt(counter++);
if ((extra & 0xfc00) === 0xdc00) {
// next character is low surrogate
codePoint = ((codePoint & 0x3ff) << 10) + (extra & 0x3ff) + 0x10000;
}
else {
// It's an unmatched surrogate; only append this code unit, in case
// the next code unit is the high surrogate of a surrogate pair.
counter--;
}
}
value = "\\" + codePoint.toString(16).toUpperCase() + " ";
}
else {
if (options.escapeEverything) {
if (regexAnySingleEscape.test(character)) {
value = "\\" + character;
}
else {
value = "\\" + codePoint.toString(16).toUpperCase() + " ";
}
}
else if (character === "\\" ||
(!isIdentifier &&
((character === '"' && quote === character) ||
(character === "'" && quote === character))) ||
(isIdentifier && regexSingleEscape.test(character))) {
value = "\\" + character;
}
else {
value = character;
}
}
output += value;
}
if (isIdentifier) {
if (/^-[-\d]/.test(output)) {
output = "\\-" + output.slice(1);
}
else if (/\d/.test(firstChar)) {
output = "\\3" + firstChar + " " + output.slice(1);
}
}
output = removeExcessiveSpaces(output);
if (!isIdentifier && options.wrap) {
return quote + output + quote;
}
return output;
}
//# sourceMappingURL=cssesc.js.map
@@ -0,0 +1,17 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = ensureObject;
function ensureObject(obj) {
var props = [];
for (var _i = 1; _i < arguments.length; _i++) {
props[_i - 1] = arguments[_i];
}
while (props.length > 0) {
var prop = props.shift();
if (!obj[prop]) {
obj[prop] = {};
}
obj = obj[prop];
}
}
//# sourceMappingURL=ensureObject.js.map
@@ -0,0 +1,18 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = getProp;
function getProp(obj) {
var props = [];
for (var _i = 1; _i < arguments.length; _i++) {
props[_i - 1] = arguments[_i];
}
while (props.length > 0) {
var prop = props.shift();
if (!obj[prop]) {
return undefined;
}
obj = obj[prop];
}
return obj;
}
//# sourceMappingURL=getProp.js.map
@@ -0,0 +1,20 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.resolveMaxInputLength = exports.MAX_NESTING_DEPTH = exports.resolveMaxNestingDepth = exports.stripComments = exports.ensureObject = exports.getProp = exports.unesc = void 0;
var unesc_1 = require("./unesc");
Object.defineProperty(exports, "unesc", { enumerable: true, get: function () { return __importDefault(unesc_1).default; } });
var getProp_1 = require("./getProp");
Object.defineProperty(exports, "getProp", { enumerable: true, get: function () { return __importDefault(getProp_1).default; } });
var ensureObject_1 = require("./ensureObject");
Object.defineProperty(exports, "ensureObject", { enumerable: true, get: function () { return __importDefault(ensureObject_1).default; } });
var stripComments_1 = require("./stripComments");
Object.defineProperty(exports, "stripComments", { enumerable: true, get: function () { return __importDefault(stripComments_1).default; } });
var maxNestingDepth_1 = require("./maxNestingDepth");
Object.defineProperty(exports, "resolveMaxNestingDepth", { enumerable: true, get: function () { return __importDefault(maxNestingDepth_1).default; } });
Object.defineProperty(exports, "MAX_NESTING_DEPTH", { enumerable: true, get: function () { return maxNestingDepth_1.MAX_NESTING_DEPTH; } });
var maxInputLength_1 = require("./maxInputLength");
Object.defineProperty(exports, "resolveMaxInputLength", { enumerable: true, get: function () { return __importDefault(maxInputLength_1).default; } });
//# sourceMappingURL=index.js.map
@@ -0,0 +1,23 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = resolveMaxInputLength;
/**
* Validate a user-supplied limit on the length of the selector to parse.
*
* No limit applies by default, so falling back on an invalid value, as
* resolveMaxNestingDepth() does, would silently turn off a guard the caller
* asked for. An invalid value is a configuration mistake and throws instead.
*
* @param {unknown} value the limit provided through the `maxInputLength` option
* @returns {number} a non-negative integer limit, or Infinity for no limit
*/
function resolveMaxInputLength(value) {
if (value === undefined || value === Infinity) {
return Infinity;
}
if (Number.isSafeInteger(value) && value >= 0) {
return value;
}
throw new TypeError("maxInputLength must be a non-negative integer or Infinity, received ".concat(String(value), "."));
}
//# sourceMappingURL=maxInputLength.js.map
@@ -0,0 +1,25 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MAX_NESTING_DEPTH = void 0;
exports.default = resolveMaxNestingDepth;
/**
* The default maximum selector nesting depth allowed when parsing or
* serializing a selector. Going beyond this would otherwise recurse deeply
* enough to overflow the call stack (CVE-2026-9358 / CWE-674). Real-world
* selectors never get anywhere near this, so it acts purely as a safety net
* that turns an uncatchable stack overflow into a catchable error.
*/
exports.MAX_NESTING_DEPTH = 256;
/**
* Coerce a user-supplied nesting-depth limit into a safe value. Anything that
* is not a non-negative safe integer (NaN, Infinity, negative numbers, or a
* non-number) would disable or break the guard, so it falls back to the
* default.
*
* @param {unknown} value the limit provided through the `maxNestingDepth` option
* @returns {number} a safe, non-negative integer limit
*/
function resolveMaxNestingDepth(value) {
return Number.isSafeInteger(value) && value >= 0 ? value : exports.MAX_NESTING_DEPTH;
}
//# sourceMappingURL=maxNestingDepth.js.map
@@ -0,0 +1,20 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = stripComments;
function stripComments(str) {
var s = "";
var commentStart = str.indexOf("/*");
var lastEnd = 0;
while (commentStart >= 0) {
s = s + str.slice(lastEnd, commentStart);
var commentEnd = str.indexOf("*/", commentStart + 2);
if (commentEnd < 0) {
return s;
}
lastEnd = commentEnd + 2;
commentStart = str.indexOf("/*", lastEnd);
}
s = s + str.slice(lastEnd);
return s;
}
//# sourceMappingURL=stripComments.js.map
@@ -0,0 +1,76 @@
"use strict";
// Many thanks for this post which made this migration much easier.
// https://mathiasbynens.be/notes/css-escapes
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = unesc;
/**
*
* @param {string} str
* @returns {[string, number]|undefined}
*/
function gobbleHex(str) {
var lower = str.toLowerCase();
var hex = "";
for (var i = 0; i < 6 && lower[i] !== undefined; i++) {
var code = lower.charCodeAt(i);
// check to see if we are dealing with a valid hex char [a-f|0-9]
var valid = (code >= 97 && code <= 102) || (code >= 48 && code <= 57);
// https://drafts.csswg.org/css-syntax/#consume-escaped-code-point
if (!valid) {
break;
}
hex += lower[i];
}
if (hex.length === 0) {
return undefined;
}
var consumed = hex.length;
var next = str[consumed];
if (next === " " || next === "\t" || next === "\n" || next === "\r" || next === "\f") {
// CSS preprocessing treats CRLF as a single newline.
consumed += next === "\r" && str[consumed + 1] === "\n" ? 2 : 1;
}
var codePoint = parseInt(hex, 16);
var isSurrogate = codePoint >= 0xd800 && codePoint <= 0xdfff;
// Add special case for
// "If this number is zero, or is for a surrogate, or is greater than the maximum allowed code point"
// https://drafts.csswg.org/css-syntax/#maximum-allowed-code-point
if (isSurrogate || codePoint === 0x0000 || codePoint > 0x10ffff) {
return ["\uFFFD", consumed];
}
return [String.fromCodePoint(codePoint), consumed];
}
var CONTAINS_ESCAPE = /\\/;
function unesc(str) {
var needToProcess = CONTAINS_ESCAPE.test(str);
if (!needToProcess) {
return str;
}
var ret = "";
for (var i = 0; i < str.length; i++) {
if (str[i] === "\\") {
var gobbled = gobbleHex(str.slice(i + 1, i + 9));
if (gobbled !== undefined) {
ret += gobbled[0];
i += gobbled[1];
continue;
}
// Retain a pair of \\ if double escaped `\\\\`
// https://github.com/postcss/postcss-selector-parser/commit/268c9a7656fb53f543dc620aa5b73a30ec3ff20e
if (str[i + 1] === "\\") {
ret += "\\";
i++;
continue;
}
// if \\ is at the end of the string retain it
// https://github.com/postcss/postcss-selector-parser/commit/01a6b346e3612ce1ab20219acc26abdc259ccefb
if (str.length === i + 1) {
ret += str[i];
}
continue;
}
ret += str[i];
}
return ret;
}
//# sourceMappingURL=unesc.js.map
@@ -0,0 +1,65 @@
{
"name": "postcss-selector-parser",
"description": "Selector parser with built in methods for working with selector strings.",
"version": "7.2.1",
"devDependencies": {
"oxfmt": "^0.74.0",
"oxlint": "^1.69.0",
"postcss": "^8.4.31",
"typescript": "^5.4.0"
},
"main": "dist/index.js",
"types": "postcss-selector-parser.d.ts",
"files": [
"API.md",
"CHANGELOG.md",
"LICENSE-MIT",
"dist",
"postcss-selector-parser.d.ts",
"!**/__tests__",
"!dist/**/*.map"
],
"scripts": {
"clean": "node -e \"require('fs').rmSync('dist',{recursive:true,force:true})\"",
"build": "npm run clean && tsc",
"typecheck": "tsc --noEmit --strict postcss-selector-parser.d.ts postcss-selector-parser.test.ts",
"lint": "oxlint",
"lint:fix": "oxlint --fix",
"format": "oxfmt src",
"format:check": "oxfmt --check src",
"pretests": "npm run build",
"tests": "node --test src/__tests__/*.mjs",
"precoverage": "npm run build",
"coverage": "node --enable-source-maps --test --experimental-test-coverage --test-coverage-exclude=\"**/__tests__/**\" --test-coverage-lines=94 --test-coverage-branches=94 --test-coverage-functions=96 --test-reporter=spec src/__tests__/*.mjs",
"test": "npm run lint && npm run typecheck && npm run coverage",
"prepare": "npm run build",
"release": "npx npmpub"
},
"dependencies": {
"util-deprecate": "^1.0.2"
},
"license": "MIT",
"engines": {
"node": ">=4"
},
"homepage": "https://github.com/postcss/postcss-selector-parser",
"contributors": [
{
"name": "Maxime Thirouin",
"url": "https://moox.io"
},
{
"name": "Ben Briggs",
"email": "beneb.info@gmail.com",
"url": "http://beneb.info"
},
{
"name": "Chris Eppstein",
"email": "chris@eppsteins.net"
}
],
"repository": {
"type": "git",
"url": "https://github.com/postcss/postcss-selector-parser.git"
}
}
@@ -0,0 +1,588 @@
// Type definitions for postcss-selector-parser 2.2.3
// Definitions by: Chris Eppstein <chris@eppsteins.net>
/*~ Note that ES6 modules cannot directly export callable functions.
*~ This file should be imported using the CommonJS-style:
*~ import x = require('someLibrary');
*~
*~ Refer to the documentation to understand common
*~ workarounds for this limitation of ES6 modules.
*/
/*~ This declaration specifies that the function
*~ is the exported object from the file
*/
export = parser;
// A type that's T but not U.
type Diff<T, U> = T extends U ? never : T;
// TODO: Conditional types in TS 1.8 will really clean this up.
declare function parser(processor?: undefined, options?: Partial<parser.Options>): parser.Processor<never>;
declare function parser<Transform>(processor: parser.AsyncProcessor<Transform>, options?: Partial<parser.Options>): parser.Processor<Transform, never>;
declare function parser(processor: parser.AsyncProcessor<void>, options?: Partial<parser.Options>): parser.Processor<never, never>;
declare function parser<Transform>(processor: parser.SyncProcessor<Transform>, options?: Partial<parser.Options>): parser.Processor<Transform>;
declare function parser(processor: parser.SyncProcessor<void>, options?: Partial<parser.Options>): parser.Processor<never>;
declare function parser<Transform>(processor?: parser.SyncProcessor<Transform> | parser.AsyncProcessor<Transform>, options?: Partial<parser.Options>): parser.Processor<Transform>;
/*~ If you want to expose types from your module as well, you can
*~ place them in this block. Often you will want to describe the
*~ shape of the return type of the function; that type should
*~ be declared in here, as this example shows.
*/
declare namespace parser {
/* copied from postcss -- so we don't need to add a dependency */
type ErrorOptions = {
plugin?: string;
word?: string;
index?: number
};
/* the bits we use of postcss.Rule, copied from postcss -- so we don't need to add a dependency */
type PostCSSRuleNode = {
selector: string
/**
* @returns postcss.CssSyntaxError but it's a complex object, caller
* should cast to it if they have a dependency on postcss.
*/
error(message: string, options?: ErrorOptions): Error;
};
/** Accepts a string */
type Selectors = string | PostCSSRuleNode
type ProcessorFn<ReturnType = void> = (root: parser.Root) => ReturnType;
type SyncProcessor<Transform = void> = ProcessorFn<Transform>;
type AsyncProcessor<Transform = void> = ProcessorFn<PromiseLike<Transform>>;
const TAG: "tag";
const STRING: "string";
const SELECTOR: "selector";
const ROOT: "root";
const PSEUDO: "pseudo";
const NESTING: "nesting";
const ID: "id";
const COMMENT: "comment";
const COMBINATOR: "combinator";
const CLASS: "class";
const ATTRIBUTE: "attribute";
const UNIVERSAL: "universal";
interface NodeTypes {
tag: Tag,
string: String,
selector: Selector,
root: Root,
pseudo: Pseudo,
nesting: Nesting,
id: Identifier,
comment: Comment,
combinator: Combinator,
class: ClassName,
attribute: Attribute,
universal: Universal
}
type Node = NodeTypes[keyof NodeTypes];
function isNode(node: any): node is Node;
interface Options {
/**
* Preserve whitespace when true. Default: true;
*/
lossless: boolean;
/**
* When true and a postcss.Rule is passed, set the result of
* processing back onto the rule when done. Default: true.
*/
updateSelector: boolean;
/**
* The maximum selector nesting depth allowed while parsing. Selectors
* nested deeper than this (e.g. `:not(:not(:not(…)))`) raise an error
* instead of overflowing the call stack. Default: 256.
*/
maxNestingDepth: number;
/**
* The maximum length of the selector to parse, as measured by
* `String#length`. A longer selector raises an error before it is
* parsed. Set it when parsing untrusted input. Default: no limit.
*/
maxInputLength: number;
}
interface StringifyOptions {
/**
* The maximum selector nesting depth allowed while serializing.
* Serializing an AST nested deeper than this raises an error instead of
* overflowing the call stack. Default: 256.
*/
maxNestingDepth?: number;
}
class Processor<
TransformType = never,
SyncSelectorsType extends Selectors | never = Selectors
> {
res: Root;
readonly result: String;
ast(selectors: Selectors, options?: Partial<Options>): Promise<Root>;
astSync(selectors: SyncSelectorsType, options?: Partial<Options>): Root;
transform(selectors: Selectors, options?: Partial<Options>): Promise<TransformType>;
transformSync(selectors: SyncSelectorsType, options?: Partial<Options>): TransformType;
process(selectors: Selectors, options?: Partial<Options>): Promise<string>;
processSync(selectors: SyncSelectorsType, options?: Partial<Options>): string;
}
interface ParserOptions {
css: string;
error: (message: string, options: ErrorOptions) => Error;
options: Options;
}
class Parser {
input: ParserOptions;
lossy: boolean;
position: number;
root: Root;
selectors: string;
current: Selector;
constructor(input: ParserOptions);
/**
* Raises an error, if the processor is invoked on
* a postcss Rule node, a better error message is raised.
*/
error(message: string, options?: ErrorOptions): void;
}
interface NodeSource {
start?: {
line: number,
column: number
},
end?: {
line: number,
column: number
}
}
interface SpaceAround {
before: string;
after: string;
}
interface Spaces extends SpaceAround {
[spaceType: string]: string | Partial<SpaceAround> | undefined;
}
interface NodeOptions<Value = string> {
value: Value;
spaces?: Partial<Spaces>;
source?: NodeSource;
sourceIndex?: number;
}
interface Base<
Value extends string | undefined = string,
ParentType extends Container | undefined = Container | undefined
> {
type: keyof NodeTypes;
parent: ParentType;
value: Value;
spaces: Spaces;
source?: NodeSource;
sourceIndex: number;
rawSpaceBefore: string;
rawSpaceAfter: string;
remove(): Node;
replaceWith(...nodes: Node[]): Node;
next(): Node | undefined;
prev(): Node | undefined;
clone(opts?: {[override: string]:any}): this;
/**
* Return whether this node includes the character at the position of the given line and column.
* Returns undefined if the nodes lack sufficient source metadata to determine the position.
* @param line 1-index based line number relative to the start of the selector.
* @param column 1-index based column number relative to the start of the selector.
*/
isAtPosition(line: number, column: number): boolean | undefined;
/**
* Some non-standard syntax doesn't follow normal escaping rules for css,
* this allows the escaped value to be specified directly, allowing illegal characters to be
* directly inserted into css output.
* @param name the property to set
* @param value the unescaped value of the property
* @param valueEscaped optional. the escaped value of the property.
*/
setPropertyAndEscape(name: string, value: any, valueEscaped: string): void;
/**
* When you want a value to passed through to CSS directly. This method
* deletes the corresponding raw value causing the stringifier to fallback
* to the unescaped value.
* @param name the property to set.
* @param value The value that is both escaped and unescaped.
*/
setPropertyWithoutEscape(name: string, value: any): void;
/**
* Some non-standard syntax doesn't follow normal escaping rules for css.
* This allows non standard syntax to be appended to an existing property
* by specifying the escaped value. By specifying the escaped value,
* illegal characters are allowed to be directly inserted into css output.
* @param {string} name the property to set
* @param {any} value the unescaped value of the property
* @param {string} valueEscaped optional. the escaped value of the property.
*/
appendToPropertyAndEscape(name: string, value: any, valueEscaped: string): void;
toString(options?: StringifyOptions): string;
}
interface ContainerOptions extends NodeOptions {
nodes?: Array<Node>;
}
interface Container<
Value extends string | undefined = string,
Child extends Node = Node
> extends Base<Value> {
nodes: Array<Child>;
append(selector: Child): this;
prepend(selector: Child): this;
at(index: number): Child;
/**
* Return the most specific node at the line and column number given.
* The source location is based on the original parsed location, locations aren't
* updated as selector nodes are mutated.
*
* Note that this location is relative to the location of the first character
* of the selector, and not the location of the selector in the overall document
* when used in conjunction with postcss.
*
* If not found, returns undefined.
* @param line The line number of the node to find. (1-based index)
* @param col The column number of the node to find. (1-based index)
*/
atPosition(line: number, column: number): Child;
index(child: Child): number;
readonly first: Child;
readonly last: Child;
readonly length: number;
removeChild(child: Child): this;
removeAll(): this;
empty(): this;
insertAfter(oldNode: Child, newNode: Child, ...restNode: Child[]): this;
insertBefore(oldNode: Child, newNode: Child, ...restNode: Child[]): this;
each(callback: (node: Child, index: number) => boolean | void): boolean | undefined;
walk(
callback: (node: Node, index: number) => boolean | void
): boolean | undefined;
walkAttributes(
callback: (node: Attribute) => boolean | void
): boolean | undefined;
walkClasses(
callback: (node: ClassName) => boolean | void
): boolean | undefined;
walkCombinators(
callback: (node: Combinator) => boolean | void
): boolean | undefined;
walkComments(
callback: (node: Comment) => boolean | void
): boolean | undefined;
walkIds(
callback: (node: Identifier) => boolean | void
): boolean | undefined;
walkNesting(
callback: (node: Nesting) => boolean | void
): boolean | undefined;
walkPseudos(
callback: (node: Pseudo) => boolean | void
): boolean | undefined;
walkTags(callback: (node: Tag) => boolean | void): boolean | undefined;
walkUniversals(callback: (node: Universal) => boolean | void): boolean | undefined;
split(callback: (node: Child) => boolean): [Child[], Child[]];
map<T>(callback: (node: Child) => T): T[];
reduce(
callback: (
previousValue: Child,
currentValue: Child,
currentIndex: number,
array: readonly Child[]
) => Child
): Child;
reduce(
callback: (
previousValue: Child,
currentValue: Child,
currentIndex: number,
array: readonly Child[]
) => Child,
initialValue: Child
): Child;
reduce<T>(
callback: (
previousValue: T,
currentValue: Child,
currentIndex: number,
array: readonly Child[]
) => T,
initialValue: T
): T;
every(callback: (node: Child) => boolean): boolean;
some(callback: (node: Child) => boolean): boolean;
filter(callback: (node: Child) => boolean): Child[];
sort(callback: (nodeA: Child, nodeB: Child) => number): Child[];
toString(options?: StringifyOptions): string;
}
function isContainer(node: any): node is Root | Selector | Pseudo;
interface NamespaceOptions<Value extends string | undefined = string> extends NodeOptions<Value> {
namespace?: string | true;
}
interface Namespace<Value extends string | undefined = string> extends Base<Value> {
/** alias for namespace */
ns: string | true;
/**
* namespace prefix.
*/
namespace: string | true;
/**
* If a namespace exists, prefix the value provided with it, separated by |.
*/
qualifiedName(value: string): string;
/**
* A string representing the namespace suitable for output.
*/
readonly namespaceString: string;
}
function isNamespace(node: any): node is Attribute | Tag;
interface Root extends Container<undefined, Selector> {
type: "root";
/**
* Raises an error, if the processor is invoked on
* a postcss Rule node, a better error message is raised.
*/
error(message: string, options?: ErrorOptions): Error;
nodeAt(line: number, column: number): Node
}
function root(opts: ContainerOptions): Root;
function isRoot(node: any): node is Root;
interface Selector extends Container<string, Node> {
type: "selector";
nodes: Array<Diff<Node, Selector>>;
}
function selector(opts: ContainerOptions): Selector;
function isSelector(node: any): node is Selector;
interface CombinatorRaws {
value?: string;
spaces?: {
before?: string;
after?: string;
};
}
interface Combinator extends Base {
type: "combinator";
raws?: CombinatorRaws;
}
function combinator(opts: NodeOptions): Combinator;
function isCombinator(node: any): node is Combinator;
interface ClassName extends Base {
type: "class";
}
function className(opts: NamespaceOptions): ClassName;
function isClassName(node: any): node is ClassName;
type AttributeOperator = "=" | "~=" | "|=" | "^=" | "$=" | "*=";
type QuoteMark = '"' | "'" | null;
interface PreferredQuoteMarkOptions {
quoteMark?: QuoteMark;
preferCurrentQuoteMark?: boolean;
}
interface SmartQuoteMarkOptions extends PreferredQuoteMarkOptions {
smart?: boolean;
}
interface AttributeOptions extends NamespaceOptions<string | undefined> {
attribute: string;
operator?: AttributeOperator;
insensitive?: boolean;
sensitive?: boolean;
quoteMark?: QuoteMark;
/** @deprecated Use quoteMark instead. */
quoted?: boolean;
spaces?: {
before?: string;
after?: string;
attribute?: Partial<SpaceAround>;
operator?: Partial<SpaceAround>;
value?: Partial<SpaceAround>;
insensitive?: Partial<SpaceAround>;
}
raws: {
unquoted?: string;
attribute?: string;
operator?: string;
value?: string;
insensitive?: string;
insensitiveFlag?: string;
sensitiveFlag?: string;
spaces?: {
attribute?: Partial<Spaces>;
operator?: Partial<Spaces>;
value?: Partial<Spaces>;
insensitive?: Partial<Spaces>;
}
};
}
interface Attribute extends Namespace<string | undefined> {
type: "attribute";
attribute: string;
operator?: AttributeOperator;
insensitive?: boolean;
sensitive?: boolean;
quoteMark: QuoteMark;
quoted?: boolean;
spaces: {
before: string;
after: string;
attribute?: Partial<Spaces>;
operator?: Partial<Spaces>;
value?: Partial<Spaces>;
insensitive?: Partial<Spaces>;
}
raws: {
/** @deprecated The attribute value is unquoted, use that instead.. */
unquoted?: string;
attribute?: string;
operator?: string;
/** The value of the attribute with quotes and escapes. */
value?: string;
insensitive?: string;
insensitiveFlag?: string;
sensitiveFlag?: string;
spaces?: {
attribute?: Partial<Spaces>;
operator?: Partial<Spaces>;
value?: Partial<Spaces>;
insensitive?: Partial<Spaces>;
}
};
/**
* The attribute name after having been qualified with a namespace.
*/
readonly qualifiedAttribute: string;
/**
* The case insensitivity flag or an empty string depending on whether this
* attribute is case insensitive.
*/
readonly insensitiveFlag : 'i' | '';
/**
* The explicit case sensitivity flag (Selectors Level 4 `s`) or an empty
* string depending on whether this attribute is explicitly case sensitive.
*/
readonly sensitiveFlag : 's' | '';
/**
* Returns the attribute's value quoted such that it would be legal to use
* in the value of a css file. The original value's quotation setting
* used for stringification is left unchanged. See `setValue(value, options)`
* if you want to control the quote settings of a new value for the attribute or
* `set quoteMark(mark)` if you want to change the quote settings of the current
* value.
*
* You can also change the quotation used for the current value by setting quoteMark.
**/
getQuotedValue(options?: SmartQuoteMarkOptions): string;
/**
* Set the unescaped value with the specified quotation options. The value
* provided must not include any wrapping quote marks -- those quotes will
* be interpreted as part of the value and escaped accordingly.
* @param value
*/
setValue(value: string, options?: SmartQuoteMarkOptions): void;
/**
* Intelligently select a quoteMark value based on the value's contents. If
* the value is a legal CSS ident, it will not be quoted. Otherwise a quote
* mark will be picked that minimizes the number of escapes.
*
* If there's no clear winner, the quote mark from these options is used,
* then the source quote mark (this is inverted if `preferCurrentQuoteMark` is
* true). If the quoteMark is unspecified, a double quote is used.
**/
smartQuoteMark(options: PreferredQuoteMarkOptions): QuoteMark;
/**
* Selects the preferred quote mark based on the options and the current quote mark value.
* If you want the quote mark to depend on the attribute value, call `smartQuoteMark(opts)`
* instead.
*/
preferredQuoteMark(options: PreferredQuoteMarkOptions): QuoteMark
/**
* returns the offset of the attribute part specified relative to the
* start of the node of the output string.
*
* * "ns" - alias for "namespace"
* * "namespace" - the namespace if it exists.
* * "attribute" - the attribute name
* * "attributeNS" - the start of the attribute or its namespace
* * "operator" - the match operator of the attribute
* * "value" - The value (string or identifier)
* * "insensitive" - the case insensitivity flag;
* @param part One of the possible values inside an attribute.
* @returns -1 if the name is invalid or the value doesn't exist in this attribute.
*/
offsetOf(part: "ns" | "namespace" | "attribute" | "attributeNS" | "operator" | "value" | "insensitive" | "sensitive"): number;
}
function attribute(opts: AttributeOptions): Attribute;
function isAttribute(node: any): node is Attribute;
interface Pseudo extends Container<string, Selector> {
type: "pseudo";
}
function pseudo(opts: ContainerOptions): Pseudo;
/**
* Checks whether the node is the Pseudo subtype of node.
*/
function isPseudo(node: any): node is Pseudo;
/**
* Checks whether the node is, specifically, a pseudo element instead of
* pseudo class.
*/
function isPseudoElement(node: any): node is Pseudo;
/**
* Checks whether the node is, specifically, a pseudo class instead of
* pseudo element.
*/
function isPseudoClass(node: any): node is Pseudo;
interface Tag extends Namespace {
type: "tag";
}
function tag(opts: NamespaceOptions): Tag;
function isTag(node: any): node is Tag;
interface Comment extends Base {
type: "comment";
}
function comment(opts: NodeOptions): Comment;
function isComment(node: any): node is Comment;
interface Identifier extends Base {
type: "id";
}
function id(opts: any): Identifier;
function isIdentifier(node: any): node is Identifier;
interface Nesting extends Base {
type: "nesting";
}
function nesting(opts?: any): Nesting;
function isNesting(node: any): node is Nesting;
interface String extends Base {
type: "string";
}
function string(opts: NodeOptions): String;
function isString(node: any): node is String;
interface Universal extends Base {
type: "universal";
}
function universal(opts?: NamespaceOptions): Universal;
function isUniversal(node: any): node is Universal;
}
@@ -0,0 +1,52 @@
{
"name": "postcss-modules-local-by-default",
"version": "4.2.0",
"description": "A CSS Modules transform to make local scope the default",
"main": "src/index.js",
"author": "Mark Dalgleish",
"license": "MIT",
"files": [
"src"
],
"repository": {
"type": "git",
"url": "https://github.com/css-modules/postcss-modules-local-by-default.git"
},
"engines": {
"node": "^10 || ^12 || >= 14"
},
"keywords": [
"css-modules",
"postcss",
"css",
"postcss-plugin"
],
"scripts": {
"prettier": "prettier -l --ignore-path .gitignore .",
"eslint": "eslint --ignore-path .gitignore .",
"lint": "yarn eslint && yarn prettier",
"test:only": "jest",
"test:watch": "jest --watch",
"test:coverage": "jest --coverage --collectCoverageFrom=\"src/**/*\"",
"test": "yarn test:coverage",
"prepublishOnly": "yarn lint && yarn test"
},
"dependencies": {
"icss-utils": "^5.0.0",
"postcss-selector-parser": "^7.0.0",
"postcss-value-parser": "^4.1.0"
},
"devDependencies": {
"coveralls": "^3.1.0",
"eslint": "^7.10.0",
"eslint-config-prettier": "^6.12.0",
"husky": "^4.3.0",
"jest": "^26.5.2",
"lint-staged": "^10.4.0",
"postcss": "^8.1.0",
"prettier": "^2.1.2"
},
"peerDependencies": {
"postcss": "^8.1.0"
}
}
+732
View File
@@ -0,0 +1,732 @@
"use strict";
const selectorParser = require("postcss-selector-parser");
const valueParser = require("postcss-value-parser");
const { extractICSS } = require("icss-utils");
const IGNORE_FILE_MARKER = "cssmodules-pure-no-check";
const IGNORE_NEXT_LINE_MARKER = "cssmodules-pure-ignore";
const isSpacing = (node) => node.type === "combinator" && node.value === " ";
const isPureCheckDisabled = (root) => {
for (const node of root.nodes) {
if (node.type !== "comment") {
return false;
}
if (node.text.trim().startsWith(IGNORE_FILE_MARKER)) {
return true;
}
}
return false;
};
function getIgnoreComment(node) {
if (!node.parent) {
return;
}
const indexInParent = node.parent.index(node);
for (let i = indexInParent - 1; i >= 0; i--) {
const prevNode = node.parent.nodes[i];
if (prevNode.type === "comment") {
if (prevNode.text.trimStart().startsWith(IGNORE_NEXT_LINE_MARKER)) {
return prevNode;
}
} else {
break;
}
}
}
function normalizeNodeArray(nodes) {
const array = [];
nodes.forEach((x) => {
if (Array.isArray(x)) {
normalizeNodeArray(x).forEach((item) => {
array.push(item);
});
} else if (x) {
array.push(x);
}
});
if (array.length > 0 && isSpacing(array[array.length - 1])) {
array.pop();
}
return array;
}
const isPureSelectorSymbol = Symbol("is-pure-selector");
function localizeNode(rule, mode, localAliasMap) {
const transform = (node, context) => {
if (context.ignoreNextSpacing && !isSpacing(node)) {
throw new Error("Missing whitespace after " + context.ignoreNextSpacing);
}
if (context.enforceNoSpacing && isSpacing(node)) {
throw new Error("Missing whitespace before " + context.enforceNoSpacing);
}
let newNodes;
switch (node.type) {
case "root": {
let resultingGlobal;
context.hasPureGlobals = false;
newNodes = node.nodes.map((n) => {
const nContext = {
global: context.global,
lastWasSpacing: true,
hasLocals: false,
explicit: false,
};
n = transform(n, nContext);
if (typeof resultingGlobal === "undefined") {
resultingGlobal = nContext.global;
} else if (resultingGlobal !== nContext.global) {
throw new Error(
'Inconsistent rule global/local result in rule "' +
node +
'" (multiple selectors must result in the same mode for the rule)'
);
}
if (!nContext.hasLocals) {
context.hasPureGlobals = true;
}
return n;
});
context.global = resultingGlobal;
node.nodes = normalizeNodeArray(newNodes);
break;
}
case "selector": {
newNodes = node.map((childNode) => transform(childNode, context));
node = node.clone();
node.nodes = normalizeNodeArray(newNodes);
break;
}
case "combinator": {
if (isSpacing(node)) {
if (context.ignoreNextSpacing) {
context.ignoreNextSpacing = false;
context.lastWasSpacing = false;
context.enforceNoSpacing = false;
return null;
}
context.lastWasSpacing = true;
return node;
}
break;
}
case "pseudo": {
let childContext;
const isNested = !!node.length;
const isScoped = node.value === ":local" || node.value === ":global";
const isImportExport =
node.value === ":import" || node.value === ":export";
if (isImportExport) {
context.hasLocals = true;
// :local(.foo)
} else if (isNested) {
if (isScoped) {
if (node.nodes.length === 0) {
throw new Error(`${node.value}() can't be empty`);
}
if (context.inside) {
throw new Error(
`A ${node.value} is not allowed inside of a ${context.inside}(...)`
);
}
childContext = {
global: node.value === ":global",
inside: node.value,
hasLocals: false,
explicit: true,
};
newNodes = node
.map((childNode) => transform(childNode, childContext))
.reduce((acc, next) => acc.concat(next.nodes), []);
if (newNodes.length) {
const { before, after } = node.spaces;
const first = newNodes[0];
const last = newNodes[newNodes.length - 1];
first.spaces = { before, after: first.spaces.after };
last.spaces = { before: last.spaces.before, after };
}
node = newNodes;
break;
} else {
childContext = {
global: context.global,
inside: context.inside,
lastWasSpacing: true,
hasLocals: false,
explicit: context.explicit,
};
newNodes = node.map((childNode) => {
const newContext = {
...childContext,
enforceNoSpacing: false,
};
const result = transform(childNode, newContext);
childContext.global = newContext.global;
childContext.hasLocals = newContext.hasLocals;
return result;
});
node = node.clone();
node.nodes = normalizeNodeArray(newNodes);
if (childContext.hasLocals) {
context.hasLocals = true;
}
}
break;
//:local .foo .bar
} else if (isScoped) {
if (context.inside) {
throw new Error(
`A ${node.value} is not allowed inside of a ${context.inside}(...)`
);
}
const addBackSpacing = !!node.spaces.before;
context.ignoreNextSpacing = context.lastWasSpacing
? node.value
: false;
context.enforceNoSpacing = context.lastWasSpacing
? false
: node.value;
context.global = node.value === ":global";
context.explicit = true;
// because this node has spacing that is lost when we remove it
// we make up for it by adding an extra combinator in since adding
// spacing on the parent selector doesn't work
return addBackSpacing
? selectorParser.combinator({ value: " " })
: null;
}
break;
}
case "id":
case "class": {
if (!node.value) {
throw new Error("Invalid class or id selector syntax");
}
if (context.global) {
break;
}
const isImportedValue = localAliasMap.has(node.value);
const isImportedWithExplicitScope = isImportedValue && context.explicit;
if (!isImportedValue || isImportedWithExplicitScope) {
const innerNode = node.clone();
innerNode.spaces = { before: "", after: "" };
node = selectorParser.pseudo({
value: ":local",
nodes: [innerNode],
spaces: node.spaces,
});
context.hasLocals = true;
}
break;
}
case "nesting": {
if (node.value === "&") {
context.hasLocals = rule.parent[isPureSelectorSymbol];
}
}
}
context.lastWasSpacing = false;
context.ignoreNextSpacing = false;
context.enforceNoSpacing = false;
return node;
};
const rootContext = {
global: mode === "global",
hasPureGlobals: false,
};
rootContext.selector = selectorParser((root) => {
transform(root, rootContext);
}).processSync(rule, { updateSelector: false, lossless: true });
return rootContext;
}
function localizeDeclNode(node, context) {
switch (node.type) {
case "word":
if (context.localizeNextItem) {
if (!context.localAliasMap.has(node.value)) {
node.value = ":local(" + node.value + ")";
context.localizeNextItem = false;
}
}
break;
case "function":
if (
context.options &&
context.options.rewriteUrl &&
node.value.toLowerCase() === "url"
) {
node.nodes.map((nestedNode) => {
if (nestedNode.type !== "string" && nestedNode.type !== "word") {
return;
}
let newUrl = context.options.rewriteUrl(
context.global,
nestedNode.value
);
switch (nestedNode.type) {
case "string":
if (nestedNode.quote === "'") {
newUrl = newUrl.replace(/(\\)/g, "\\$1").replace(/'/g, "\\'");
}
if (nestedNode.quote === '"') {
newUrl = newUrl.replace(/(\\)/g, "\\$1").replace(/"/g, '\\"');
}
break;
case "word":
newUrl = newUrl.replace(/("|'|\)|\\)/g, "\\$1");
break;
}
nestedNode.value = newUrl;
});
}
break;
}
return node;
}
// `none` is special value, other is global values
const specialKeywords = [
"none",
"inherit",
"initial",
"revert",
"revert-layer",
"unset",
];
function localizeDeclarationValues(localize, declaration, context) {
const valueNodes = valueParser(declaration.value);
valueNodes.walk((node, index, nodes) => {
if (
node.type === "function" &&
(node.value.toLowerCase() === "var" || node.value.toLowerCase() === "env")
) {
return false;
}
if (
node.type === "word" &&
specialKeywords.includes(node.value.toLowerCase())
) {
return;
}
const subContext = {
options: context.options,
global: context.global,
localizeNextItem: localize && !context.global,
localAliasMap: context.localAliasMap,
};
nodes[index] = localizeDeclNode(node, subContext);
});
declaration.value = valueNodes.toString();
}
// letter
// An uppercase letter or a lowercase letter.
//
// ident-start code point
// A letter, a non-ASCII code point, or U+005F LOW LINE (_).
//
// ident code point
// An ident-start code point, a digit, or U+002D HYPHEN-MINUS (-).
// We don't validate `hex digits`, because we don't need it, it is work of linters.
const validIdent =
/^-?([a-z\u0080-\uFFFF_]|(\\[^\r\n\f])|-(?![0-9]))((\\[^\r\n\f])|[a-z\u0080-\uFFFF_0-9-])*$/i;
/*
The spec defines some keywords that you can use to describe properties such as the timing
function. These are still valid animation names, so as long as there is a property that accepts
a keyword, it is given priority. Only when all the properties that can take a keyword are
exhausted can the animation name be set to the keyword. I.e.
animation: infinite infinite;
The animation will repeat an infinite number of times from the first argument, and will have an
animation name of infinite from the second.
*/
const animationKeywords = {
// animation-direction
$normal: 1,
$reverse: 1,
$alternate: 1,
"$alternate-reverse": 1,
// animation-fill-mode
$forwards: 1,
$backwards: 1,
$both: 1,
// animation-iteration-count
$infinite: 1,
// animation-play-state
$paused: 1,
$running: 1,
// animation-timing-function
$ease: 1,
"$ease-in": 1,
"$ease-out": 1,
"$ease-in-out": 1,
$linear: 1,
"$step-end": 1,
"$step-start": 1,
// Special
$none: Infinity, // No matter how many times you write none, it will never be an animation name
// Global values
$initial: Infinity,
$inherit: Infinity,
$unset: Infinity,
$revert: Infinity,
"$revert-layer": Infinity,
};
function localizeDeclaration(declaration, context) {
const isAnimation = /animation(-name)?$/i.test(declaration.prop);
if (isAnimation) {
let parsedAnimationKeywords = {};
const valueNodes = valueParser(declaration.value).walk((node) => {
// If div-token appeared (represents as comma ','), a possibility of an animation-keywords should be reflesh.
if (node.type === "div") {
parsedAnimationKeywords = {};
return;
} else if (
node.type === "function" &&
node.value.toLowerCase() === "local" &&
node.nodes.length === 1
) {
node.type = "word";
node.value = node.nodes[0].value;
return localizeDeclNode(node, {
options: context.options,
global: context.global,
localizeNextItem: true,
localAliasMap: context.localAliasMap,
});
} else if (node.type === "function") {
// replace `animation: global(example)` with `animation-name: example`
if (node.value.toLowerCase() === "global" && node.nodes.length === 1) {
node.type = "word";
node.value = node.nodes[0].value;
}
// Do not handle nested functions
return false;
}
// Ignore all except word
else if (node.type !== "word") {
return;
}
const value = node.type === "word" ? node.value.toLowerCase() : null;
let shouldParseAnimationName = false;
if (value && validIdent.test(value)) {
if ("$" + value in animationKeywords) {
parsedAnimationKeywords["$" + value] =
"$" + value in parsedAnimationKeywords
? parsedAnimationKeywords["$" + value] + 1
: 0;
shouldParseAnimationName =
parsedAnimationKeywords["$" + value] >=
animationKeywords["$" + value];
} else {
shouldParseAnimationName = true;
}
}
return localizeDeclNode(node, {
options: context.options,
global: context.global,
localizeNextItem: shouldParseAnimationName && !context.global,
localAliasMap: context.localAliasMap,
});
});
declaration.value = valueNodes.toString();
return;
}
if (/url\(/i.test(declaration.value)) {
return localizeDeclarationValues(false, declaration, context);
}
}
const isPureSelector = (context, rule) => {
if (!rule.parent || rule.type === "root") {
return !context.hasPureGlobals;
}
if (rule.type === "rule" && rule[isPureSelectorSymbol]) {
return rule[isPureSelectorSymbol] || isPureSelector(context, rule.parent);
}
return !context.hasPureGlobals || isPureSelector(context, rule.parent);
};
const isNodeWithoutDeclarations = (rule) => {
if (rule.nodes.length > 0) {
return !rule.nodes.every(
(item) =>
item.type === "rule" ||
(item.type === "atrule" && !isNodeWithoutDeclarations(item))
);
}
return true;
};
module.exports = (options = {}) => {
if (
options &&
options.mode &&
options.mode !== "global" &&
options.mode !== "local" &&
options.mode !== "pure"
) {
throw new Error(
'options.mode must be either "global", "local" or "pure" (default "local")'
);
}
const pureMode = options && options.mode === "pure";
const globalMode = options && options.mode === "global";
return {
postcssPlugin: "postcss-modules-local-by-default",
prepare() {
const localAliasMap = new Map();
return {
Once(root) {
const { icssImports } = extractICSS(root, false);
const enforcePureMode = pureMode && !isPureCheckDisabled(root);
Object.keys(icssImports).forEach((key) => {
Object.keys(icssImports[key]).forEach((prop) => {
localAliasMap.set(prop, icssImports[key][prop]);
});
});
root.walkAtRules((atRule) => {
if (/keyframes$/i.test(atRule.name)) {
const globalMatch = /^\s*:global\s*\((.+)\)\s*$/.exec(
atRule.params
);
const localMatch = /^\s*:local\s*\((.+)\)\s*$/.exec(
atRule.params
);
let globalKeyframes = globalMode;
if (globalMatch) {
if (enforcePureMode) {
const ignoreComment = getIgnoreComment(atRule);
if (!ignoreComment) {
throw atRule.error(
"@keyframes :global(...) is not allowed in pure mode"
);
} else {
ignoreComment.remove();
}
}
atRule.params = globalMatch[1];
globalKeyframes = true;
} else if (localMatch) {
atRule.params = localMatch[0];
globalKeyframes = false;
} else if (
atRule.params &&
!globalMode &&
!localAliasMap.has(atRule.params)
) {
atRule.params = ":local(" + atRule.params + ")";
}
atRule.walkDecls((declaration) => {
localizeDeclaration(declaration, {
localAliasMap,
options: options,
global: globalKeyframes,
});
});
} else if (/scope$/i.test(atRule.name)) {
if (atRule.params) {
const ignoreComment = pureMode
? getIgnoreComment(atRule)
: undefined;
if (ignoreComment) {
ignoreComment.remove();
}
atRule.params = atRule.params
.split("to")
.map((item) => {
const selector = item.trim().slice(1, -1).trim();
const context = localizeNode(
selector,
options.mode,
localAliasMap
);
context.options = options;
context.localAliasMap = localAliasMap;
if (
enforcePureMode &&
context.hasPureGlobals &&
!ignoreComment
) {
throw atRule.error(
'Selector in at-rule"' +
selector +
'" is not pure ' +
"(pure selectors must contain at least one local class or id)"
);
}
return `(${context.selector})`;
})
.join(" to ");
}
atRule.nodes.forEach((declaration) => {
if (declaration.type === "decl") {
localizeDeclaration(declaration, {
localAliasMap,
options: options,
global: globalMode,
});
}
});
} else if (atRule.nodes) {
atRule.nodes.forEach((declaration) => {
if (declaration.type === "decl") {
localizeDeclaration(declaration, {
localAliasMap,
options: options,
global: globalMode,
});
}
});
}
});
root.walkRules((rule) => {
if (
rule.parent &&
rule.parent.type === "atrule" &&
/keyframes$/i.test(rule.parent.name)
) {
// ignore keyframe rules
return;
}
const context = localizeNode(rule, options.mode, localAliasMap);
context.options = options;
context.localAliasMap = localAliasMap;
const ignoreComment = enforcePureMode
? getIgnoreComment(rule)
: undefined;
const isNotPure = enforcePureMode && !isPureSelector(context, rule);
if (
isNotPure &&
isNodeWithoutDeclarations(rule) &&
!ignoreComment
) {
throw rule.error(
'Selector "' +
rule.selector +
'" is not pure ' +
"(pure selectors must contain at least one local class or id)"
);
} else if (ignoreComment) {
ignoreComment.remove();
}
if (pureMode) {
rule[isPureSelectorSymbol] = !isNotPure;
}
rule.selector = context.selector;
// Less-syntax mixins parse as rules with no nodes
if (rule.nodes) {
rule.nodes.forEach((declaration) =>
localizeDeclaration(declaration, context)
);
}
});
},
};
},
};
};
module.exports.postcss = true;