From c58145d340db5eda8530579c6c7372b15a16bee4 Mon Sep 17 00:00:00 2001 From: Romain Menke <11521496+romainmenke@users.noreply.github.com> Date: Sat, 29 Jun 2024 22:29:28 +0200 Subject: [PATCH] update eslint (#1412) --- .eslintrc.json | 45 - .github/bin/format-package-json.mjs | 12 +- .github/bin/generate-docs/api-documenter.mjs | 6 +- .github/bin/generate-docs/install.mjs | 6 +- .github/bin/generate-docs/readme.mjs | 8 +- .github/bin/license/allowed.mjs | 2 +- .../bin/list-workspaces/list-workspaces.mjs | 4 +- .../list-modified-files.mjs | 12 +- .github/bin/release-plan/commit.mjs | 10 +- .github/bin/release-plan/discord-announce.mjs | 12 +- .github/bin/release-plan/docs.mjs | 6 +- .../minify-changelog-and-package-json.mjs | 6 +- .github/bin/release-plan/npm-can-publish.mjs | 8 +- .github/bin/release-plan/npm-install.mjs | 6 +- .../release-plan/npm-prepublish-scripts.mjs | 6 +- .github/bin/release-plan/npm-publish.mjs | 6 +- .github/bin/release-plan/npm-version.mjs | 6 +- .github/bin/release-plan/npm-whoami.mjs | 8 +- .../prepare-current-release-plan.mjs | 10 +- .../prepare-next-release-plan.mjs | 4 +- .github/bin/release-plan/release-plan.mjs | 16 +- .github/bin/util/toposort.mjs | 2 +- cli/csstools-cli/dist/cli.cjs | 2 +- cli/csstools-cli/src/cli.ts | 101 +- .../src/plugins/css-blank-pseudo.ts | 4 +- .../src/plugins/css-has-pseudo.ts | 4 +- .../src/plugins/css-prefers-color-scheme.ts | 4 +- .../postcss-attribute-case-insensitive.ts | 4 +- .../src/plugins/postcss-cascade-layers.ts | 4 +- .../src/plugins/postcss-color-function.ts | 4 +- .../postcss-color-functional-notation.ts | 4 +- .../src/plugins/postcss-color-hex-alpha.ts | 4 +- .../src/plugins/postcss-color-mix-function.ts | 4 +- .../plugins/postcss-color-rebeccapurple.ts | 4 +- .../src/plugins/postcss-custom-media.ts | 4 +- .../src/plugins/postcss-custom-properties.ts | 4 +- .../src/plugins/postcss-custom-selectors.ts | 4 +- .../src/plugins/postcss-dir-pseudo-class.ts | 4 +- .../postcss-double-position-gradients.ts | 4 +- .../plugins/postcss-exponential-functions.ts | 4 +- .../src/plugins/postcss-focus-visible.ts | 4 +- .../src/plugins/postcss-focus-within.ts | 4 +- .../plugins/postcss-font-format-keywords.ts | 4 +- .../src/plugins/postcss-gap-properties.ts | 4 +- .../postcss-gradients-interpolation-method.ts | 4 +- .../src/plugins/postcss-hwb-function.ts | 4 +- .../src/plugins/postcss-ic-unit.ts | 4 +- .../src/plugins/postcss-image-set-function.ts | 4 +- .../src/plugins/postcss-is-pseudo-class.ts | 4 +- .../src/plugins/postcss-lab-function.ts | 4 +- .../plugins/postcss-light-dark-function.ts | 4 +- .../postcss-logical-float-and-clear.ts | 4 +- .../src/plugins/postcss-logical-resize.ts | 4 +- .../plugins/postcss-logical-viewport-units.ts | 4 +- .../src/plugins/postcss-logical.ts | 4 +- .../src/plugins/postcss-media-minmax.ts | 4 +- ...edia-queries-aspect-ratio-number-values.ts | 4 +- .../src/plugins/postcss-nested-calc.ts | 4 +- .../src/plugins/postcss-nesting.ts | 4 +- .../postcss-normalize-display-values.ts | 4 +- .../src/plugins/postcss-oklab-function.ts | 4 +- .../src/plugins/postcss-overflow-shorthand.ts | 4 +- cli/csstools-cli/src/plugins/postcss-place.ts | 4 +- .../src/plugins/postcss-preset-env.ts | 4 +- .../plugins/postcss-pseudo-class-any-link.ts | 4 +- .../plugins/postcss-relative-color-syntax.ts | 4 +- .../src/plugins/postcss-scope-pseudo-class.ts | 4 +- .../src/plugins/postcss-selector-not.ts | 4 +- .../postcss-stepped-value-functions.ts | 4 +- .../postcss-text-decoration-shorthand.ts | 4 +- .../postcss-trigonometric-functions.ts | 4 +- .../src/plugins/postcss-unset-value.ts | 4 +- eslint.config.mjs | 100 + .../css-has-pseudo/dist/browser-global.js.map | 2 +- .../css-has-pseudo/src/browser-global.js | 1 - experimental/postcss-nesting/dist/index.cjs | 2 +- experimental/postcss-nesting/dist/index.mjs | 2 +- .../src/lib/ampersand-to-scope.ts | 4 + .../lib/merge-selectors/merge-selectors.ts | 6 +- .../src/lib/rule-within-rule.ts | 6 +- .../src/lib/shift-nodes-before-parent.ts | 2 + knip.json | 3 +- package-lock.json | 532 ++-- package.json | 13 +- packages/base-cli/dist/index.cjs | 2 +- packages/base-cli/dist/index.mjs | 2 +- packages/base-cli/src/args.ts | 4 +- packages/base-cli/src/get-stdin.ts | 8 +- .../src/nodes/layer-name.ts | 8 +- packages/color-helpers/CHANGELOG.md | 4 + packages/color-helpers/dist/index.cjs | 88 +- packages/color-helpers/dist/index.mjs | 84 +- .../src/calculations/multiply-matrices.ts | 62 +- .../src/conversions/d50-to-d65.ts | 16 +- .../src/conversions/d65-to-d50.ts | 16 +- .../src/conversions/lin-2020-to-xyz.ts | 16 +- .../src/conversions/lin-a98rgb-to-xyz.ts | 16 +- .../src/conversions/lin-p3-to-xyz.ts | 16 +- .../src/conversions/lin-pro-photo-to-xyz.ts | 18 +- .../src/conversions/lin-srgb-to-xyz.ts | 15 +- .../src/conversions/oklab-to-xyz.ts | 35 +- .../src/conversions/xyz-to-lin-2020.ts | 16 +- .../src/conversions/xyz-to-lin-a98rgb.ts | 16 +- .../src/conversions/xyz-to-lin-p3.ts | 16 +- .../src/conversions/xyz-to-lin-pro-photo.ts | 18 +- .../src/conversions/xyz-to-lin-srgb.ts | 16 +- .../src/conversions/xyz-to-oklab.ts | 34 +- .../src/functions/named-color.ts | 4 +- packages/css-parser-algorithms/CHANGELOG.md | 4 + packages/css-parser-algorithms/dist/index.cjs | 2 +- .../css-parser-algorithms/dist/index.d.ts | 8 +- packages/css-parser-algorithms/dist/index.mjs | 2 +- .../docs/css-parser-algorithms.api.json | 81 +- ...ss-parser-algorithms.gathernodeancestry.md | 4 +- ...er-algorithms.iswhitespaceorcommentnode.md | 51 + .../docs/css-parser-algorithms.md | 11 + .../src/consume/component-block-function.ts | 4 - packages/css-parser-algorithms/src/index.ts | 1 + ...omma-separated-list-of-component-values.ts | 1 - .../src/parse/list-of-component-values.ts | 1 - .../src/util/node-ancestry.ts | 2 +- .../src/util/type-predicates.ts | 8 + packages/css-tokenizer/CHANGELOG.md | 4 + packages/css-tokenizer/dist/index.cjs | 2 +- packages/css-tokenizer/dist/index.mjs | 2 +- packages/css-tokenizer/src/consume/bad-url.ts | 1 - packages/css-tokenizer/src/consume/comment.ts | 1 - .../src/consume/ident-like-token.ts | 1 - .../src/consume/ident-sequence.ts | 1 - .../css-tokenizer/src/consume/string-token.ts | 1 - .../css-tokenizer/src/consume/url-token.ts | 1 - .../css-tokenizer/src/interfaces/token.ts | 2 + .../css-tokenizer/src/util/clone-tokens.ts | 6 +- .../css-tokenizer/src/util/type-predicates.ts | 2 +- .../test/community/bootstrap-benchmark.mjs | 6 - .../test/community/bootstrap.mjs | 1 - .../test/community/open-props.mjs | 1 - .../test/community/postcss-parser-tests.mjs | 1 - .../test/community/token-types.mjs | 2 - .../test/complex/parse-error.mjs | 1 - .../media-query-list-parser/dist/index.cjs | 2 +- .../media-query-list-parser/dist/index.d.ts | 4 +- .../media-query-list-parser/dist/index.mjs | 2 +- .../docs/media-query-list-parser.api.json | 22 +- ...ry-list-parser.mediainparenswalkerentry.md | 2 +- ...y-list-parser.mediainparenswalkerparent.md | 2 +- .../src/nodes/media-condition-list.ts | 4 +- .../src/nodes/media-feature-comparison.ts | 16 +- .../src/nodes/media-feature-name.ts | 4 +- .../src/nodes/media-feature-value.ts | 19 +- .../src/nodes/media-in-parens.ts | 4 +- .../src/nodes/media-query-modifier.ts | 2 +- .../src/nodes/media-type.ts | 2 +- .../src/parser/parse-media-query.ts | 6 +- packages/postcss-tape/dist/index.cjs | 2 +- packages/postcss-tape/dist/index.mjs | 2 +- .../src/file-contents-or-empty-string.ts | 2 +- packages/postcss-tape/src/index.ts | 124 +- .../src/reduce-css-syntax-error.ts | 1 + .../selector-resolve-nested/dist/index.cjs | 2 +- .../selector-resolve-nested/dist/index.mjs | 2 +- .../src/combinations.ts | 1 - .../src/flatten-nested-selector.ts | 2 + .../src/resolve-nested-selector.ts | 7 +- plugin-packs/postcss-bundler/dist/index.cjs | 2 +- plugin-packs/postcss-bundler/dist/index.mjs | 2 +- .../lib/base64-encoded-import.ts | 6 +- .../src/postcss-import/lib/resolve-id.ts | 2 +- .../postcss-preset-env/dist/index.cjs | 2 +- .../postcss-preset-env/dist/index.mjs | 2 +- plugin-packs/postcss-preset-env/src/index.ts | 10 +- .../postcss-preset-env/src/log/helper.mjs | 2 +- .../test/lib/list-features/array-options.mjs | 16 +- .../test/lib/list-features/client-side.mjs | 4 +- .../src/test/lib/list-features/no-options.mjs | 2 +- .../src/test/lib/list-features/preserve.mjs | 4 +- .../src/test/lib/list-features/stage-0.mjs | 2 +- .../list-features/vendor-implementations.mjs | 6 +- .../postcss-preset-env/src/test/lib/stage.mjs | 14 +- plugin-packs/postcss-preset-env/tsconfig.json | 3 +- .../dist/browser-global.js.map | 2 +- plugins/css-blank-pseudo/dist/browser.cjs.map | 2 +- plugins/css-blank-pseudo/dist/browser.mjs.map | 2 +- .../css-blank-pseudo/src/browser-global.js | 1 - plugins/css-blank-pseudo/src/browser.js | 3 +- plugins/css-blank-pseudo/test/_browser.mjs | 5 +- .../css-has-pseudo/dist/browser-global.js.map | 2 +- plugins/css-has-pseudo/dist/browser.cjs.map | 2 +- plugins/css-has-pseudo/dist/browser.mjs.map | 2 +- plugins/css-has-pseudo/dist/index.cjs | 2 +- plugins/css-has-pseudo/dist/index.mjs | 2 +- plugins/css-has-pseudo/src/browser-global.js | 1 - plugins/css-has-pseudo/src/browser.js | 3 - .../src/is-guarded-by-at-supports.ts | 4 +- .../dist/browser-global.js.map | 2 +- .../dist/browser.cjs.map | 2 +- .../dist/browser.mjs.map | 2 +- .../src/browser-global.js | 1 - .../css-prefers-color-scheme/src/browser.js | 1 - plugins/css-prefers-color-scheme/src/index.ts | 2 +- .../postcss-browser-comments/dist/index.cjs | 2 +- .../postcss-browser-comments/dist/index.mjs | 2 +- plugins/postcss-browser-comments/src/index.ts | 4 +- .../dist/index.cjs | 2 +- .../dist/index.mjs | 2 +- .../src/index.ts | 4 +- plugins/postcss-custom-media/dist/index.cjs | 2 +- plugins/postcss-custom-media/dist/index.mjs | 2 +- .../src/cascade-layers.ts | 1 + plugins/postcss-custom-media/src/index.ts | 2 +- plugins/postcss-custom-media/src/toposort.ts | 6 +- .../postcss-custom-properties/dist/index.cjs | 2 +- .../postcss-custom-properties/dist/index.mjs | 2 +- .../src/cascade-layers.ts | 1 + .../src/is-ignored.ts | 5 +- .../src/is-var-function.ts | 2 +- .../postcss-custom-properties/src/toposort.ts | 11 +- .../src/transform-properties.ts | 1 + .../postcss-custom-selectors/dist/index.cjs | 2 +- .../postcss-custom-selectors/dist/index.mjs | 2 +- .../src/cascade-layers.ts | 1 + plugins/postcss-custom-selectors/src/index.ts | 5 +- .../src/transform-rule.ts | 4 +- plugins/postcss-design-tokens/dist/index.cjs | 2 +- plugins/postcss-design-tokens/dist/index.mjs | 2 +- .../src/data-formats/parse-import.ts | 2 +- .../data-formats/style-dictionary/v3/group.ts | 9 +- .../data-formats/style-dictionary/v3/value.ts | 2 +- .../src/data-formats/toposort/toposort.ts | 12 +- plugins/postcss-design-tokens/src/index.ts | 4 +- .../postcss-dir-pseudo-class/dist/index.cjs | 2 +- .../postcss-dir-pseudo-class/dist/index.mjs | 2 +- plugins/postcss-dir-pseudo-class/src/index.ts | 3 +- .../dist/index.cjs | 2 +- .../dist/index.mjs | 2 +- .../src/index.ts | 24 +- plugins/postcss-env-function/dist/index.cjs | 2 +- plugins/postcss-env-function/dist/index.mjs | 2 +- plugins/postcss-env-function/src/index.js | 4 +- plugins/postcss-extract/src/index.ts | 1 - .../src/selector-engine/combinators/child.ts | 4 +- .../src/selector-engine/matchers/attribute.ts | 2 +- .../dist/browser-global.js.map | 2 +- .../postcss-focus-within/dist/browser.cjs.map | 2 +- .../postcss-focus-within/dist/browser.mjs.map | 2 +- .../src/browser-global.js | 1 - plugins/postcss-focus-within/src/browser.js | 3 +- plugins/postcss-gamut-mapping/src/index.ts | 1 + .../postcss-image-set-function/dist/index.cjs | 2 +- .../postcss-image-set-function/dist/index.mjs | 2 +- .../postcss-image-set-function/src/index.ts | 2 +- .../src/lib/get-media.ts | 2 +- .../src/lib/handle-invalidation.ts | 2 +- .../src/lib/is-comma.ts | 4 +- .../src/lib/process-image-set.ts | 4 +- .../postcss-is-pseudo-class/dist/index.cjs | 2 +- .../postcss-is-pseudo-class/dist/index.mjs | 2 +- plugins/postcss-is-pseudo-class/src/index.ts | 6 +- .../src/split-selectors/complex.ts | 1 + .../complex/child-adjacent-child.ts | 4 +- .../split-selectors/complex/is-in-compound.ts | 35 +- .../complex/is-pseudo-in-first-compound.ts | 16 +- .../compound-selector-order.ts | 10 +- .../src/split-selectors/split-selectors.ts | 10 +- .../postcss-is-pseudo-class/test/basic.css | 4 + .../test/basic.does-not-exist.expect.css | 4 + .../test/basic.expect.css | 4 + .../basic.oncomplex.no-warning.expect.css | 4 + .../test/basic.oncomplex.warning.expect.css | 4 + .../test/basic.preserve.expect.css | 8 + .../basic.with-cloned-declarations.expect.css | 8 + .../src/has-feature.ts | 1 - .../src/transform.ts | 1 - plugins/postcss-logical/dist/index.cjs | 2 +- plugins/postcss-logical/dist/index.mjs | 2 +- .../src/lib/transform-text-align.ts | 3 +- .../src/lib/transform-transition.ts | 2 +- plugins/postcss-media-minmax/src/transform.ts | 2 +- .../src/transform-media-feature-value.ts | 1 - plugins/postcss-minify/src/index.ts | 11 +- plugins/postcss-nested-calc/dist/index.cjs | 2 +- plugins/postcss-nested-calc/dist/index.mjs | 2 +- plugins/postcss-nested-calc/src/index.ts | 2 +- plugins/postcss-nesting/dist/index.cjs | 2 +- plugins/postcss-nesting/dist/index.mjs | 2 +- .../merge-selectors/combinations-of-size-n.ts | 19 +- .../compound-selector-order.ts | 8 +- .../lib/merge-selectors/merge-selectors.ts | 24 +- .../2021/lib/nest-rule-within-rule.ts | 2 +- .../src/editions/2021/lib/rule-within-rule.ts | 2 +- .../shared/lib/shift-nodes-before-parent.ts | 2 + plugins/postcss-nesting/src/index.ts | 1 + .../dist/index.cjs | 2 +- .../dist/index.mjs | 2 +- .../src/index.ts | 68 +- .../src/mappings.ts | 18 +- .../postcss-overflow-shorthand/dist/index.cjs | 2 +- .../postcss-overflow-shorthand/dist/index.mjs | 2 +- .../postcss-overflow-shorthand/src/index.ts | 2 +- plugins/postcss-place/dist/index.cjs | 2 +- plugins/postcss-place/dist/index.mjs | 2 +- .../postcss-place/src/on-css-declaration.ts | 2 +- .../dist/index.cjs | 2 +- .../dist/index.mjs | 2 +- .../scripts/matcher-for-value.mjs | 2 +- .../src/conditions-from-values.ts | 2 +- .../src/index.ts | 1 + .../src/matchers.ts | 2796 ++++++++--------- .../dist/index.cjs | 2 +- .../dist/index.mjs | 2 +- .../src/index.ts | 13 +- plugins/postcss-rebase-url/src/rebase.mjs | 2 +- plugins/postcss-slow-plugins/CHANGELOG.md | 4 + plugins/postcss-slow-plugins/README.md | 62 +- plugins/postcss-slow-plugins/dist/index.cjs | 2 +- plugins/postcss-slow-plugins/dist/index.mjs | 2 +- plugins/postcss-slow-plugins/docs/README.md | 62 +- plugins/postcss-slow-plugins/src/index.ts | 24 +- .../dist/index.cjs | 2 +- .../dist/index.mjs | 2 +- .../src/index.ts | 3 +- plugins/postcss-todo-or-die/dist/index.cjs | 2 +- plugins/postcss-todo-or-die/dist/index.mjs | 2 +- plugins/postcss-todo-or-die/src/index.ts | 18 +- rollup/default.mjs | 2 +- tsconfig.json | 4 +- 326 files changed, 2986 insertions(+), 2798 deletions(-) delete mode 100644 .eslintrc.json create mode 100644 eslint.config.mjs create mode 100644 packages/css-parser-algorithms/docs/css-parser-algorithms.iswhitespaceorcommentnode.md diff --git a/.eslintrc.json b/.eslintrc.json deleted file mode 100644 index 2b884489d..000000000 --- a/.eslintrc.json +++ /dev/null @@ -1,45 +0,0 @@ -{ - "env": { - "es6": true, - "node": true - }, - "extends": "eslint:recommended", - "parserOptions": { - "ecmaVersion": 2022, - "sourceType": "module" - }, - "ignorePatterns": ["**/dist/*"], - "rules": { - "quotes": ["error", "single"], - "comma-dangle": ["error", "always-multiline"], - "semi": ["error", "always"], - "curly": "error", - "brace-style": "error", - "indent": ["error", "tab", { "SwitchCase": 1 }], - "radix": "error", - "space-in-parens": ["error", "never"] - }, - "overrides": [ - { - "files": [ - "**/*.ts", - "**/*.mts", - "**/*.cts" - ], - "extends": [ - "plugin:@typescript-eslint/eslint-recommended", - "plugin:@typescript-eslint/recommended" - ], - "parser": "@typescript-eslint/parser", - "plugins": [ - "@typescript-eslint" - ], - "rules": { - "no-shadow": "off", - "@typescript-eslint/no-shadow": "error", - "@typescript-eslint/array-type": ["error", { "default": "generic" }], - "@typescript-eslint/explicit-function-return-type": "error" - } - } - ] -} diff --git a/.github/bin/format-package-json.mjs b/.github/bin/format-package-json.mjs index 700da456c..1428698df 100644 --- a/.github/bin/format-package-json.mjs +++ b/.github/bin/format-package-json.mjs @@ -57,13 +57,13 @@ const formatted = {}; formatted.funding = [ { - "type": "github", - "url": "https://github.com/sponsors/csstools" + 'type': 'github', + 'url': 'https://github.com/sponsors/csstools', }, { - "type": "opencollective", - "url": "https://opencollective.com/csstools" - } + 'type': 'opencollective', + 'url': 'https://opencollective.com/csstools', + }, ]; delete packageJSONInfo.funding; @@ -75,7 +75,7 @@ const formatted = {}; delete packageJSONInfo.private; formatted.engines = { - node: '^14 || ^16 || >=18' + node: '^14 || ^16 || >=18', }; delete packageJSONInfo.engines; diff --git a/.github/bin/generate-docs/api-documenter.mjs b/.github/bin/generate-docs/api-documenter.mjs index aac3f58d1..7199c98dd 100644 --- a/.github/bin/generate-docs/api-documenter.mjs +++ b/.github/bin/generate-docs/api-documenter.mjs @@ -33,8 +33,8 @@ await new Promise((resolve, reject) => { ], { stdio: 'inherit', - shell: platform === 'win32' - } + shell: platform === 'win32', + }, ); publishCmd.on('close', (code) => { @@ -49,6 +49,6 @@ await new Promise((resolve, reject) => { for (const file of await getFiles('docs', true)) { const fileContents = fs.readFileSync(file, 'utf8').toString(); - const cleanFileContents = fileContents.replace(/\r\n/g, "\n"); + const cleanFileContents = fileContents.replace(/\r\n/g, '\n'); fs.writeFileSync(file, cleanFileContents); } diff --git a/.github/bin/generate-docs/install.mjs b/.github/bin/generate-docs/install.mjs index 7153b1193..a262ed2ed 100644 --- a/.github/bin/generate-docs/install.mjs +++ b/.github/bin/generate-docs/install.mjs @@ -14,12 +14,12 @@ installDoc = installDoc.replaceAll('', path.join(path.basename(path if (packageJSONInfo?.csstools?.assumesToProcessBundledCSS) { installDoc = installDoc.replaceAll('', parallelBuildsNotice(packageJSONInfo.csstools.humanReadableName)); - installDoc = installDoc.replaceAll('', `["@csstools/postcss-bundler"]`); + installDoc = installDoc.replaceAll('', '["@csstools/postcss-bundler"]'); // } else { // Just a filler so that formatting doesn't become too complex. - installDoc = installDoc.replaceAll('', ``); - installDoc = installDoc.replaceAll('', `// Other plugins`); + installDoc = installDoc.replaceAll('', ''); + installDoc = installDoc.replaceAll('', '// Other plugins'); } fs.writeFileSync('./INSTALL.md', installDoc); diff --git a/.github/bin/generate-docs/readme.mjs b/.github/bin/generate-docs/readme.mjs index efc6d5352..30a037e3e 100644 --- a/.github/bin/generate-docs/readme.mjs +++ b/.github/bin/generate-docs/readme.mjs @@ -12,8 +12,8 @@ let exampleFilePaths = []; try { exampleFilePaths = ( await fs.promises.readdir(path.join('test', 'examples'), { recursive: true, withFileTypes: true }) - ).filter(x => x.isFile()).map(x => path.join(x.path, x.name)); -} catch(error) { + ).filter(x => x.isFile()).map(x => path.join(x.parentPath, x.name)); +} catch { // No examples } @@ -60,7 +60,7 @@ readmeDoc = readmeDoc.replace('
', `# [', packageJSONInfo.csstools.specUrl); if (packageJSONInfo?.csstools?.assumesToProcessBundledCSS) { readmeDoc = readmeDoc.replaceAll('', parallelBuildsNotice(packageJSONInfo.csstools.humanReadableName)); } else { - readmeDoc = readmeDoc.replaceAll('', ``); + readmeDoc = readmeDoc.replaceAll('', ''); } for (const exampleFilePath of exampleFilePaths) { diff --git a/.github/bin/license/allowed.mjs b/.github/bin/license/allowed.mjs index 4d96f82c4..41f8597f2 100644 --- a/.github/bin/license/allowed.mjs +++ b/.github/bin/license/allowed.mjs @@ -139,7 +139,7 @@ const osiApproved = [ 'BSL-1.0', 'Artistic-1.0-Perl', 'NPOSL-3.0', - 'BlueOak-1.0.0' // https://github.com/spdx/license-list-XML/commit/d2709ad9c8c3f92989d2e7cadba3af8d1e0bc166 + 'BlueOak-1.0.0', // https://github.com/spdx/license-list-XML/commit/d2709ad9c8c3f92989d2e7cadba3af8d1e0bc166 ]; export const osiApprovedWithCCO = [ diff --git a/.github/bin/list-workspaces/list-workspaces.mjs b/.github/bin/list-workspaces/list-workspaces.mjs index b6c7ea334..683ba8ae4 100644 --- a/.github/bin/list-workspaces/list-workspaces.mjs +++ b/.github/bin/list-workspaces/list-workspaces.mjs @@ -14,12 +14,12 @@ export async function listWorkspaces() { const packageDirs = await getFiles(workspace.slice(0, -2), false); for (const packageDir of packageDirs) { packages.add( - path.resolve(path.join(packageDir, 'package.json')) + path.resolve(path.join(packageDir, 'package.json')), ); } } else { packages.add( - path.resolve(path.join(workspace, 'package.json')) + path.resolve(path.join(workspace, 'package.json')), ); } } diff --git a/.github/bin/modified-workspaces/list-modified-files.mjs b/.github/bin/modified-workspaces/list-modified-files.mjs index 3cbbd0664..6e857e8c7 100644 --- a/.github/bin/modified-workspaces/list-modified-files.mjs +++ b/.github/bin/modified-workspaces/list-modified-files.mjs @@ -8,7 +8,7 @@ export async function listModifiedFilesInPullRequest(repository, pullRequestNumb while (true) { const newFiles = await getPullRequestFiles(repository, pullRequestNumber, page); allFiles.push(...newFiles); - page++ + page++; if (newFiles.length < 100) { break; @@ -21,8 +21,8 @@ export async function listModifiedFilesInPullRequest(repository, pullRequestNumb async function getPullRequestFiles(repository, pullRequestNumber, page) { return await (new Promise((resolve, reject) => { const headers = { - 'User-Agent': 'GitHub Workflow' - } + 'User-Agent': 'GitHub Workflow', + }; if (process.env.GITHUB_TOKEN) { headers['authorization'] = `Bearer ${process.env.GITHUB_TOKEN}`; @@ -33,10 +33,10 @@ async function getPullRequestFiles(repository, pullRequestNumber, page) { port: 443, path: `/repos/${repository}/pulls/${pullRequestNumber}/files?per_page=100&page=${page}`, method: 'GET', - headers: headers + headers: headers, }, (res) => { if (!res.statusCode || (Math.floor(res.statusCode / 100) !== 2)) { - throw new Error(`Unexpected response code "${res.statusCode}" with message "${res.statusMessage}"`) + throw new Error(`Unexpected response code "${res.statusCode}" with message "${res.statusMessage}"`); } let data = []; @@ -46,7 +46,7 @@ async function getPullRequestFiles(repository, pullRequestNumber, page) { res.on('end', () => { resolve( - JSON.parse(Buffer.concat(data).toString()).map((x) => x.filename) + JSON.parse(Buffer.concat(data).toString()).map((x) => x.filename), ); }); diff --git a/.github/bin/release-plan/commit.mjs b/.github/bin/release-plan/commit.mjs index 899e0da05..625a07560 100644 --- a/.github/bin/release-plan/commit.mjs +++ b/.github/bin/release-plan/commit.mjs @@ -13,11 +13,11 @@ export async function commitSingleDirectory(commitMessage, dir) { [ 'commit', '-am', - commitMessage + commitMessage, ], { - cwd: dir - } + cwd: dir, + }, ); let stdoutBuffer = ''; @@ -60,8 +60,8 @@ export async function commitAfterDependencyUpdates() { [ 'commit', '-am', - `set dependencies to newly released versions` - ] + 'set dependencies to newly released versions', + ], ); let stdoutBuffer = ''; diff --git a/.github/bin/release-plan/discord-announce.mjs b/.github/bin/release-plan/discord-announce.mjs index 6a9c9d3db..6ff2a99e5 100644 --- a/.github/bin/release-plan/discord-announce.mjs +++ b/.github/bin/release-plan/discord-announce.mjs @@ -6,8 +6,8 @@ const defaultPayload = { url: '', description: '', color: 3963146, - } - ] + }, + ], }; const BASE_URL = 'https://github.com/csstools/postcss-plugins/tree/main'; const getChangelog = (changelog) => { @@ -19,8 +19,8 @@ const getChangelog = (changelog) => { const text = changelog.slice(firstLineBreakIndex + 1, secondRelease === -1 ? undefined : secondRelease).trim(); // Replace relative links with absolute links - return text.replace( /]\(\//g, `](${ BASE_URL }/` ); -} + return text.replace(/]\(\//g, `](${ BASE_URL }/`); +}; export async function discordAnnounce(workspace) { if (process.env.DEBUG) { @@ -65,14 +65,14 @@ export async function discordAnnounceDryRun() { const discordArgument = process.argv.slice(2).find(arg => arg.includes('--discord=')); if (!discordArgument) { - console.log(`Discord announce webhook URL: not set`); + console.log('Discord announce webhook URL: not set'); return; } const [, webHookUrl] = discordArgument.split('='); if (!webHookUrl) { - console.log(`Discord announce webhook URL: not set`); + console.log('Discord announce webhook URL: not set'); return; } diff --git a/.github/bin/release-plan/docs.mjs b/.github/bin/release-plan/docs.mjs index 63b053ddc..e98df6d8a 100644 --- a/.github/bin/release-plan/docs.mjs +++ b/.github/bin/release-plan/docs.mjs @@ -8,12 +8,12 @@ export async function updateDocumentation(packageDirectory) { [ 'run', 'docs', - '--if-present' + '--if-present', ], { cwd: packageDirectory, - shell: platform === 'win32' - } + shell: platform === 'win32', + }, ); let stdoutBuffer = ''; diff --git a/.github/bin/release-plan/minify-changelog-and-package-json.mjs b/.github/bin/release-plan/minify-changelog-and-package-json.mjs index a7e4e4f3c..45042cc90 100644 --- a/.github/bin/release-plan/minify-changelog-and-package-json.mjs +++ b/.github/bin/release-plan/minify-changelog-and-package-json.mjs @@ -1,5 +1,5 @@ -import fs from 'fs/promises' -import path from 'path' +import fs from 'fs/promises'; +import path from 'path'; export async function minifyChangelogAndPackageJSON(workspace) { const originalPackageInfo = JSON.parse(await fs.readFile(path.join(workspace.path, 'package.json'))); @@ -49,5 +49,5 @@ export async function minifyChangelogAndPackageJSON(workspace) { return async () => { await fs.writeFile(path.join(workspace.path, 'package.json'), JSON.stringify(originalPackageInfo, null, '\t') + '\n'); await fs.writeFile(path.join(workspace.path, 'CHANGELOG.md'), originalChangelog); - } + }; } diff --git a/.github/bin/release-plan/npm-can-publish.mjs b/.github/bin/release-plan/npm-can-publish.mjs index c1993f20b..6a6845081 100644 --- a/.github/bin/release-plan/npm-can-publish.mjs +++ b/.github/bin/release-plan/npm-can-publish.mjs @@ -10,12 +10,12 @@ export async function canPublish(packageName, myName) { 'list', 'collaborators', packageName, - myName + myName, ], { shell: platform === 'win32', - stdio: 'pipe' - } + stdio: 'pipe', + }, ); let result = ''; @@ -43,7 +43,7 @@ export async function canPublish(packageName, myName) { resolve( result.trim().includes(myName) && - result.trim().includes('read-write') + result.trim().includes('read-write'), ); }); }); diff --git a/.github/bin/release-plan/npm-install.mjs b/.github/bin/release-plan/npm-install.mjs index 79a9e979c..1c3c44545 100644 --- a/.github/bin/release-plan/npm-install.mjs +++ b/.github/bin/release-plan/npm-install.mjs @@ -6,11 +6,11 @@ export async function npmInstall() { const installCmd = spawn( 'npm', [ - 'install' + 'install', ], { - shell: platform === 'win32' - } + shell: platform === 'win32', + }, ); installCmd.on('close', (code) => { diff --git a/.github/bin/release-plan/npm-prepublish-scripts.mjs b/.github/bin/release-plan/npm-prepublish-scripts.mjs index 7c9763ba9..2e1f65aba 100644 --- a/.github/bin/release-plan/npm-prepublish-scripts.mjs +++ b/.github/bin/release-plan/npm-prepublish-scripts.mjs @@ -14,13 +14,13 @@ export async function npmPrepublishScripts(packageDirectory, packageName) { [ 'run', 'prepublishOnly', - '--if-present' + '--if-present', ], { stdio: 'inherit', cwd: packageDirectory, - shell: platform === 'win32' - } + shell: platform === 'win32', + }, ); publishCmd.on('close', (code) => { diff --git a/.github/bin/release-plan/npm-publish.mjs b/.github/bin/release-plan/npm-publish.mjs index 9bc045c4f..c56a5102b 100644 --- a/.github/bin/release-plan/npm-publish.mjs +++ b/.github/bin/release-plan/npm-publish.mjs @@ -14,13 +14,13 @@ export async function npmPublish(packageDirectory, packageName) { [ 'publish', '--access', - 'public' + 'public', ], { stdio: 'inherit', cwd: packageDirectory, - shell: platform === 'win32' - } + shell: platform === 'win32', + }, ); publishCmd.on('close', (code) => { diff --git a/.github/bin/release-plan/npm-version.mjs b/.github/bin/release-plan/npm-version.mjs index 8ccab5ae8..827c7f6c6 100644 --- a/.github/bin/release-plan/npm-version.mjs +++ b/.github/bin/release-plan/npm-version.mjs @@ -32,12 +32,12 @@ export async function npmVersion(increment, packageDirectory) { 'npm', [ 'version', - increment + increment, ], { cwd: packageDirectory, - shell: platform === 'win32' - } + shell: platform === 'win32', + }, ); let stdoutBuffer = ''; diff --git a/.github/bin/release-plan/npm-whoami.mjs b/.github/bin/release-plan/npm-whoami.mjs index b72faf3a5..a9f171741 100644 --- a/.github/bin/release-plan/npm-whoami.mjs +++ b/.github/bin/release-plan/npm-whoami.mjs @@ -1,17 +1,17 @@ import { spawn } from 'child_process'; import { platform } from 'process'; -export async function whoami(packageName) { +export async function whoami() { return await new Promise((resolve, reject) => { const whoamiCmd = spawn( 'npm', [ - 'whoami' + 'whoami', ], { shell: platform === 'win32', - stdio: 'pipe' - } + stdio: 'pipe', + }, ); let result = ''; diff --git a/.github/bin/release-plan/prepare-current-release-plan.mjs b/.github/bin/release-plan/prepare-current-release-plan.mjs index 9b646d83e..48d7996e1 100644 --- a/.github/bin/release-plan/prepare-current-release-plan.mjs +++ b/.github/bin/release-plan/prepare-current-release-plan.mjs @@ -1,6 +1,6 @@ import { listWorkspaces } from '../list-workspaces/list-workspaces.mjs'; -import fs from 'fs/promises' -import path from 'path' +import fs from 'fs/promises'; +import path from 'path'; import { currentVersion } from './current-version.mjs'; import { canPublish } from './npm-can-publish.mjs'; import { whoami } from './npm-whoami.mjs'; @@ -8,7 +8,7 @@ import { whoami } from './npm-whoami.mjs'; export async function prepareCurrentReleasePlan() { const iam = await whoami(); if (!iam) { - throw new Error("Could not determine current npm user"); + throw new Error('Could not determine current npm user'); } const workspaces = await listWorkspaces(); @@ -49,7 +49,7 @@ export async function prepareCurrentReleasePlan() { } else if (changelog.includes('Unreleased (major)')) { increment = 'major'; } else { - console.warn("Invalid CHANGELOG.md in", workspace.name); + console.warn('Invalid CHANGELOG.md in', workspace.name); notReleasableNow.set(workspace.name, workspace); continue WORKSPACES_LOOP; } @@ -61,7 +61,7 @@ export async function prepareCurrentReleasePlan() { notReleasableNow.set(workspace.name, workspace); } - console.warn("Current npm user does not have write access for", workspace.name); + console.warn('Current npm user does not have write access for', workspace.name); continue WORKSPACES_LOOP; } diff --git a/.github/bin/release-plan/prepare-next-release-plan.mjs b/.github/bin/release-plan/prepare-next-release-plan.mjs index e7293b54b..abc00df3b 100644 --- a/.github/bin/release-plan/prepare-next-release-plan.mjs +++ b/.github/bin/release-plan/prepare-next-release-plan.mjs @@ -1,5 +1,5 @@ -import fs from 'fs/promises' -import path from 'path' +import fs from 'fs/promises'; +import path from 'path'; import { addUpdatedPackagesToChangelog } from './add-to-changelog.mjs'; export async function prepareNextReleasePlan(needsRelease, notReleasableNow) { diff --git a/.github/bin/release-plan/release-plan.mjs b/.github/bin/release-plan/release-plan.mjs index c39edd167..a78605256 100644 --- a/.github/bin/release-plan/release-plan.mjs +++ b/.github/bin/release-plan/release-plan.mjs @@ -1,5 +1,5 @@ -import fs from 'fs/promises' -import path from 'path' +import fs from 'fs/promises'; +import path from 'path'; import { commitAfterDependencyUpdates, commitSingleDirectory } from './commit.mjs'; import { discordAnnounce, discordAnnounceDryRun } from './discord-announce.mjs'; import { nowFormatted } from './date-format.mjs'; @@ -16,7 +16,7 @@ import { minifyChangelogAndPackageJSON } from './minify-changelog-and-package-js const { needsRelease, notReleasableNow, - maybeNextPlan + maybeNextPlan, } = await prepareCurrentReleasePlan(); if (process.argv.slice(2).includes('--dry-run')) { @@ -39,7 +39,7 @@ for (const workspace of needsRelease.values()) { updateDocumentation(workspace.path), `When releasing ${workspace.name} an error occurred.`, 'This happened during the documentation update and before committing and publishing changes.\n' + - 'Please fix the error and try again from a clean git state.' + 'Please fix the error and try again from a clean git state.', ); // Commit changes @@ -50,7 +50,7 @@ for (const workspace of needsRelease.values()) { ), `When releasing ${workspace.name} an error occurred.`, 'This happened when committing changes.\n' + - 'Please fix the error and try again from a clean git state.' + 'Please fix the error and try again from a clean git state.', ); // Run pre-publish scripts @@ -59,7 +59,7 @@ for (const workspace of needsRelease.values()) { `When releasing ${workspace.name} an error occurred.`, 'This happened while running the pre-publish scripts.\n' + 'A commit with changes relevant to this release has already been made.\n' + - 'Please fix the error and try again.' + 'Please fix the error and try again.', ); const restoreChangelogAndPackageJSON = await minifyChangelogAndPackageJSON(workspace); @@ -70,7 +70,7 @@ for (const workspace of needsRelease.values()) { `When releasing ${workspace.name} an error occurred.`, 'This happened when publishing to npm.\n' + 'A commit with changes relevant to this release has already been made.\n' + - 'Please fix the error and try again.' + 'Please fix the error and try again.', ); await restoreChangelogAndPackageJSON(); @@ -80,7 +80,7 @@ for (const workspace of needsRelease.values()) { discordAnnounce(workspace), `When releasing ${workspace.name} an error occurred.`, 'This happened when announcing the update on Discord.\n' + - 'Committing relevant changes and publishing to npm succeeded.' + 'Committing relevant changes and publishing to npm succeeded.', ); } diff --git a/.github/bin/util/toposort.mjs b/.github/bin/util/toposort.mjs index 0f748732e..ab6d05f51 100644 --- a/.github/bin/util/toposort.mjs +++ b/.github/bin/util/toposort.mjs @@ -48,7 +48,7 @@ export function toposort(nodes, edges) { let nodeRep; try { nodeRep = ', token was: ' + JSON.stringify(node); - } catch (e) { + } catch { nodeRep = ''; } throw new Error('Cyclic dependency' + nodeRep); diff --git a/cli/csstools-cli/dist/cli.cjs b/cli/csstools-cli/dist/cli.cjs index 88b972f65..012bd61a2 100755 --- a/cli/csstools-cli/dist/cli.cjs +++ b/cli/csstools-cli/dist/cli.cjs @@ -1,3 +1,3 @@ #!/usr/bin/env node -"use strict";var s,e=require("css-blank-pseudo"),o=require("postcss"),t=require("path"),i=require("fs"),r=require("css-has-pseudo"),c=require("css-prefers-color-scheme"),n=require("postcss-attribute-case-insensitive"),l=require("@csstools/postcss-cascade-layers"),a=require("@csstools/postcss-color-function"),p=require("postcss-color-functional-notation"),u=require("postcss-color-hex-alpha"),d=require("@csstools/postcss-color-mix-function"),g=require("postcss-color-rebeccapurple"),S=require("postcss-custom-media"),v=require("postcss-custom-properties"),f=require("postcss-custom-selectors"),h=require("postcss-dir-pseudo-class"),m=require("postcss-double-position-gradients"),C=require("@csstools/postcss-exponential-functions"),w=require("postcss-focus-visible"),b=require("postcss-focus-within"),y=require("@csstools/postcss-font-format-keywords"),P=require("postcss-gap-properties"),x=require("@csstools/postcss-gradients-interpolation-method"),L=require("@csstools/postcss-hwb-function"),T=require("@csstools/postcss-ic-unit"),q=require("postcss-image-set-function"),k=require("@csstools/postcss-is-pseudo-class"),M=require("postcss-lab-function"),F=require("@csstools/postcss-light-dark-function"),I=require("postcss-logical"),D=require("@csstools/postcss-logical-float-and-clear"),O=require("@csstools/postcss-logical-resize"),N=require("@csstools/postcss-logical-viewport-units"),A=require("@csstools/postcss-media-minmax"),V=require("@csstools/postcss-media-queries-aspect-ratio-number-values"),E=require("@csstools/postcss-nested-calc"),$=require("postcss-nesting"),z=require("@csstools/postcss-normalize-display-values"),j=require("@csstools/postcss-oklab-function"),U=require("postcss-overflow-shorthand"),W=require("postcss-place"),R=require("postcss-preset-env"),G=require("postcss-pseudo-class-any-link"),H=require("@csstools/postcss-relative-color-syntax"),J=require("@csstools/postcss-scope-pseudo-class"),Q=require("postcss-selector-not"),B=require("@csstools/postcss-stepped-value-functions"),K=require("@csstools/postcss-text-decoration-shorthand"),Y=require("@csstools/postcss-trigonometric-functions"),_=require("@csstools/postcss-unset-value");function parseArguments(e,o,t){const i=e.map((s=>s.trim())).filter((s=>!!s)),r={stdin:!1,stdout:!1,output:void 0,outputDir:void 0,inputs:[],inlineMap:!0,externalMap:!1,replace:!1,pluginOptions:{},debug:!1};let c,n=!1;for(let e=0;e1&&r.output)return console.warn('[error] omit "--output" when processing multiple inputs\n'),t(),s.InvalidArguments;0===r.inputs.length&&(r.stdin=!0),r.output||r.outputDir||r.replace||(r.stdout=!0),r.stdout&&(r.externalMap=!1);let l={};if(c)try{l=JSON.parse(c)}catch(e){return console.warn("[error] plugin options must be valid JSON\n"),t(),s.InvalidArguments}for(const e in l){const i=l[e];if(!o.includes(e))return console.warn(`[error] unknown plugin option: ${e}\n`),t(),s.InvalidArguments;r.pluginOptions[e]=i}return r}async function getStdin(){return new Promise((s=>{let e="",o=!1;if(setTimeout((()=>{o=!0,s("")}),1e4),process.stdin.isTTY){if(o)return;s(e)}else process.stdin.setEncoding("utf8"),process.stdin.on("readable",(()=>{let s;for(;s=process.stdin.read();)e+=s})),process.stdin.on("end",(()=>{o||s(e)}))}))}async function stdinToStdout(s,e,t){let i="";try{const r=await getStdin();r||(t(),process.exit(1));const c=await o([s]).process(r,{from:"stdin",to:"stdout",map:!!e.inlineMap&&{inline:!0}});c.warnings().forEach((s=>{console.warn(s.toString())})),i=c.css}catch(s){s instanceof Error?console.error(e.debug?s:s.message):console.error(s),process.exit(1)}process.stdout.write(i+(e.inlineMap?"\n":"")),process.exit(0)}async function stdinToFs(s,e,r){let c=e.output;!c&&e.outputDir&&(c=t.join(e.outputDir,"output.css")),c||process.exit(0);try{const t=await getStdin();t||(r(),process.exit(1));const n=await o([s]).process(t,{from:"stdin",to:c,map:!(!e.inlineMap&&!e.externalMap)&&{inline:e.inlineMap}});n.warnings().forEach((s=>{console.warn(s.toString())})),e.externalMap&&n.map?await Promise.all([await i.promises.writeFile(c,n.css+(e.inlineMap?"\n":"")),await i.promises.writeFile(`${c}.map`,n.map.toString())]):await i.promises.writeFile(c,n.css+(e.inlineMap?"\n":""))}catch(s){s instanceof Error?console.error(e.debug?s:s.message):console.error(s),process.exit(1)}console.log(`CSS was written to "${t.normalize(c)}"`),process.exit(0)}async function fsToStdout(s,e){let t=[];try{t=await Promise.all(e.inputs.map((async e=>{const t=await i.promises.readFile(e),r=await o([s]).process(t,{from:e,to:"stdout",map:!1});return r.warnings().forEach((s=>{console.warn(s.toString())})),r.css})))}catch(s){s instanceof Error?console.error(e.debug?s:s.message):console.error(s),process.exit(1)}for(const s of t)process.stdout.write(s);process.exit(0)}async function fsToFs(s,e){try{await Promise.all(e.inputs.map((async r=>{let c=e.output;e.outputDir&&(c=t.join(e.outputDir,t.basename(r))),e.replace&&(c=r),c||process.exit(0);const n=await i.promises.readFile(r),l=await o([s]).process(n,{from:r,to:c,map:!(!e.inlineMap&&!e.externalMap)&&{inline:e.inlineMap}});l.warnings().forEach((s=>{console.warn(s.toString())})),e.externalMap&&l.map?await Promise.all([await i.promises.writeFile(c,l.css+(e.inlineMap?"\n":"")),await i.promises.writeFile(`${c}.map`,l.map.toString())]):await i.promises.writeFile(c,l.css+(e.inlineMap?"\n":"")),console.log(`CSS was written to "${t.normalize(c)}"`)})))}catch(s){s instanceof Error?console.error(e.debug?s:s.message):console.error(s),process.exit(1)}process.exit(0)}function helpTextLogger(s,e,o,t=null){let i=[];if(t){const s=Math.max(...Object.keys(t).map((s=>s.length))),e=new Array(s).fill(" ").join("");e.length&&(i=["\nPlugin Options:",...Object.keys(t).map((s=>` ${(s+e).slice(0,e.length)} ${typeof t[s]}`))],i.push(`\n ${JSON.stringify(t,null,2).split("\n").join("\n ")}`))}const r=[`${e}\n`,` ${o}\n`,"Usage:",` ${s} [input.css] [OPTIONS] [-o|--output output.css]`,` ${s} ... [OPTIONS] --dir `,` ${s} ... [OPTIONS] --replace`,"\nOptions:"," -o, --output Output file"," -d, --dir Output directory"," -r, --replace Replace (overwrite) the input file"," -m, --map Create an external sourcemap"," --no-map Disable the default inline sourcemaps"," -p, --plugin-options Stringified JSON object with plugin options"];return i.length>0&&r.push(...i),()=>{console.warn(r.join("\n"))}}async function cli(e,o,t,i=!0){const r=parseArguments(process.argv.slice(i?2:3),o,t);r===s.InvalidArguments&&process.exit(1);const c=e(r.pluginOptions);r.stdin&&r.stdout?await stdinToStdout(c,r,t):r.stdin?await stdinToFs(c,r,t):r.stdout?await fsToStdout(c,r):await fsToFs(c,r)}(s||(s={})).InvalidArguments="INVALID_ARGUMENTS",function main(){switch(process.argv[2]??!1){case"css-blank-pseudo":return void cli(e,["preserve","replaceWith"],helpTextLogger("@csstools/cli css-blank-pseudo","PostCSS Blank Pseudo","Lets you style form elements when they are empty, following the Selectors Level 4 specification.",{preserve:!0,replaceWith:".css-blank"}),!1);case"css-has-pseudo":return void cli(r,["preserve"],helpTextLogger("@csstools/cli css-has-pseudo","PostCSS Has Pseudo","Transforms CSS with :has {}",{preserve:!0}),!1);case"css-prefers-color-scheme":return void cli(c,["preserve","mediaQuery"],helpTextLogger("@csstools/cli css-prefers-color-scheme","Prefers Color Scheme","Lets you use light and dark color schemes in all browsers, following the Media Queries specification.",{preserve:!0,mediaQuery:"color|color-index"}),!1);case"postcss-attribute-case-insensitive":return void cli(n,[],helpTextLogger("@csstools/cli postcss-attribute-case-insensitive","PostCSS Attribute Case Insensitive","Enables support for Case Insensitive Attribute matching in selectors"),!1);case"postcss-cascade-layers":return void cli(l,[],helpTextLogger("@csstools/cli postcss-cascade-layers","PostCSS Cascade Layers","Lets you use `@layer` following the Cascade Layers Specification."),!1);case"postcss-color-function":return void cli(a,["preserve","enableProgressiveCustomProperties"],helpTextLogger("@csstools/cli postcss-color-function","PostCSS Color Function","Lets you use the color() function in CSS.",{preserve:!0,enableProgressiveCustomProperties:!1}),!1);case"postcss-color-mix-function":return void cli(d,["preserve","enableProgressiveCustomProperties"],helpTextLogger("@csstools/cli postcss-color-mix-function","PostCSS Color Mix Function","Lets you use the color-mix() function in CSS.",{preserve:!0,enableProgressiveCustomProperties:!1,subFeatures:{displayP3:!1}}),!1);case"postcss-color-functional-notation":return void cli(p,["preserve"],helpTextLogger("@csstools/cli postcss-color-functional-notation","PostCSS Color Functional Notation","Lets you use space and slash separated color notation in CSS, following the CSS Color specification.",{preserve:!0}),!1);case"postcss-color-hex-alpha":return void cli(u,["preserve"],helpTextLogger("@csstools/cli postcss-color-hex-alpha","PostCSS Color Hex Alpha","Lets you use 4 & 8 character hex color notation in CSS, following the CSS Color Module specification.",{preserve:!0}),!1);case"postcss-color-rebeccapurple":return void cli(g,["preserve"],helpTextLogger("@csstools/cli postcss-color-rebeccapurple","PostCSS RebeccaPurple","Lets you use the rebeccapurple color keyword in CSS.",{preserve:!0}),!1);case"postcss-custom-media":return void cli(S,["preserve"],helpTextLogger("@csstools/cli postcss-custom-media","PostCSS Custom Media","Lets you define @custom-media in CSS following the Custom Media Specification",{preserve:!0}),!1);case"postcss-custom-properties":return void cli(v,["preserve"],helpTextLogger("@csstools/cli postcss-custom-properties","PostCSS Custom Properties","Lets you use Custom Properties in CSS, following the CSS Custom Properties specification.",{preserve:!0}),!1);case"postcss-custom-selectors":return void cli(f,["preserve"],helpTextLogger("@csstools/cli postcss-custom-selectors","PostCSS Custom Selectors","Lets you define @custom-selector in CSS following the Custom Selectors Specification",{preserve:!0}),!1);case"postcss-dir-pseudo-class":return void cli(h,["dir","preserve","shadow"],helpTextLogger("@csstools/cli postcss-dir-pseudo-class","PostCSS Dir Pseudo Class","Lets you style by directionality using the `:dir()` pseudo-class in CSS",{dir:"ltr",preserve:!0,shadow:!0}),!1);case"postcss-double-position-gradients":return void cli(m,["preserve","enableProgressiveCustomProperties"],helpTextLogger("@csstools/cli postcss-double-position-gradients","PostCSS Double Position Gradients","Lets you use double-position gradients in CSS, following the CSS Image Values and Replaced Content specification",{preserve:!0,enableProgressiveCustomProperties:!1}),!1);case"postcss-exponential-functions":return void cli(C,["preserve"],helpTextLogger("@csstools/cli postcss-exponential-functions","PostCSS Exponential Functions","Lets you use the `pow()`, `sqrt()`, `hypot()`, `log()`, `exp()` functions following the CSS Values 4 Specification.",{preserve:!0}),!1);case"postcss-focus-visible":return void cli(w,["preserve","replaceWith"],helpTextLogger("@csstools/cli postcss-focus-visible","PostCSS Focus Visible","Lets you use the `:focus-visible` pseudo-class in CSS, following the Selectors Level 4 specification.",{preserve:!0,replaceWith:".focus-visible"}),!1);case"postcss-focus-within":return void cli(b,["preserve","replaceWith"],helpTextLogger("@csstools/cli postcss-focus-within","PostCSS Focus Within","Lets you use the `:focus-within` pseudo-class in CSS, following the Selectors Level 4 specification.",{preserve:!0,replaceWith:".focus-within"}),!1);case"postcss-font-format-keywords":return void cli(y,["preserve"],helpTextLogger("@csstools/cli postcss-font-format-keywords","PostCSS Font Format Keyword","Lets you use unquoted format on @font-face CSS definitions.",{preserve:!0}),!1);case"postcss-gap-properties":return void cli(P,["preserve"],helpTextLogger("@csstools/cli postcss-gap-properties","PostCSS Gap Properties","Lets you use the gap, column-gap, and row-gap shorthand properties in CSS, following the CSS Grid Layout specification.",{preserve:!0}),!1);case"postcss-gradients-interpolation-method":return void cli(x,["preserve","enableProgressiveCustomProperties"],helpTextLogger("@csstools/cli postcss-gradients-interpolation-method","PostCSS Gradients Interpolation Method","Lets you use different interpolation methods in CSS gradient functions.",{preserve:!0,enableProgressiveCustomProperties:!1}),!1);case"postcss-hwb-function":return void cli(L,["preserve"],helpTextLogger("@csstools/cli postcss-hwb-function","PostCSS HWB function","Convert hwb() to rgb()",{preserve:!0}),!1);case"postcss-ic-unit":return void cli(T,["preserve","enableProgressiveCustomProperties"],helpTextLogger("@csstools/cli postcss-ic-unit","PostCSS IC Unit","Lets you use the ic length unit.",{preserve:!0,enableProgressiveCustomProperties:!1}),!1);case"postcss-image-set-function":return void cli(q,["oninvalid","preserve"],helpTextLogger("@csstools/cli postcss-image-set-function","PostCSS Image Set Function","Lets you display resolution-dependent images using the image-set() function in CSS, following the CSS Images specification.",{preserve:!0,oninvalid:"ignore|warn|throw"}),!1);case"postcss-is-pseudo-class":return void cli(k,["onComplexSelector","preserve","specificityMatchingName"],helpTextLogger("@csstools/cli postcss-is-pseudo-class","PostCSS Is Pseudo Class","Lets you use the :is pseudo class function, following the CSS Selector specification.",{onComplexSelector:"warning",preserve:!0,specificityMatchingName:"does-not-exist"}),!1);case"postcss-lab-function":return void cli(M,["preserve","enableProgressiveCustomProperties","subFeatures"],helpTextLogger("@csstools/cli postcss-lab-function","PostCSS Lab function","Convert lab() to rgb()",{preserve:!0,enableProgressiveCustomProperties:!1,subFeatures:{displayP3:!1}}),!1);case"postcss-light-dark-function":return void cli(F,["preserve"],helpTextLogger("@csstools/cli postcss-light-dark-function","PostCSS Light Dark function","Use the light-dark() color function in CSS",{preserve:!0}),!1);case"postcss-logical":return void cli(I,["inlineDirection","blockDirection"],helpTextLogger("@csstools/cli postcss-logical","PostCSS Logical","Lets you use logical, rather than physical, direction and dimension mappings in CSS, following the CSS Logical Properties and Values specification.",{inlineDirection:"left-to-right",blockDirection:"top-to-bottom"}),!1);case"postcss-logical-float-and-clear":return void cli(D,["inlineDirection","blockDirection"],helpTextLogger("@csstools/cli postcss-logical-float-and-clear","PostCSS Logical Float And Clear","Lets you use flow-relative (inline-start and inline-end) values for float and clear, following the CSS Logical Properties and Values specification.",{inlineDirection:"left-to-right"}),!1);case"postcss-logical-resize":return void cli(O,["inlineDirection"],helpTextLogger("@csstools/cli postcss-logical-resize","PostCSS Logical Resize","Lets you use logical values in the resize property, following the CSS Logical Properties and Values specification.",{inlineDirection:"left-to-right"}),!1);case"postcss-logical-viewport-units":return void cli(N,["inlineDirection","preserve"],helpTextLogger("@csstools/cli postcss-viewport-units","PostCSS Logical Viewport Units","Lets you use vb and vi length units in CSS, following the CSS Values and Units Module Level 4 specification.",{inlineDirection:"left-to-right",preserve:!0}),!1);case"postcss-media-minmax":return void cli(A,[],helpTextLogger("@csstools/cli postcss-media-minmax","PostCSS Media MinMax","Lets you use the range notation in CSS media queries.",{}),!1);case"postcss-media-queries-aspect-ratio-number-values":return void cli(V,[],helpTextLogger("@csstools/cli postcss-media-queries-aspect-ratio-number-values","PostCSS Media Queries Aspect-Ratio Number Values","Lets you use number values in aspect-ratio media queries.",{}),!1);case"postcss-nested-calc":return void cli(E,["preserve"],helpTextLogger("@csstools/cli postcss-nested-calc","PostCSS Nested Calc","Lets you use nested calc() expressions in CSS.",{preserve:!0}),!1);case"postcss-nesting":return void cli($,["noIsPseudoSelector"],helpTextLogger("@csstools/cli postcss-nesting","PostCSS Nesting","Lets you nest style rules inside each other, following the CSS Nesting specification.",{noIsPseudoSelector:!0}),!1);case"postcss-normalize-display-values":return void cli(z,["preserve"],helpTextLogger("@csstools/cli postcss-normalize-display-values","PostCSS Normalize Display Values","Lets you use two values display syntax for inner and outer display types.",{preserve:!0}),!1);case"postcss-oklab-function":return void cli(j,["preserve","enableProgressiveCustomProperties","subFeatures"],helpTextLogger("@csstools/cli postcss-oklab-function","PostCSS OKLab Function","Lets you use oklab() and oklch() color functions in CSS.",{preserve:!0,enableProgressiveCustomProperties:!1,subFeatures:{displayP3:!1}}),!1);case"postcss-overflow-shorthand":return void cli(U,["preserve"],helpTextLogger("@csstools/cli postcss-overflow-shorthand","PostCSS Overflow Shorthand","Lets you use the `overflow` shorthand in CSS, following the CSS Overflow specification.",{preserve:!0}),!1);case"postcss-place":return void cli(W,["preserve"],helpTextLogger("@csstools/cli postcss-place","PostCSS Place","Lets you use place-* properties as shorthands for align-* and justify-*, following the CSS Box Alignment specification.",{preserve:!0}),!1);case"postcss-preset-env":return void cli(R,["stage","minimumVendorImplementations","features","env","browsers","autoprefixer","preserve","logical","enableClientSidePolyfills","debug"],helpTextLogger("@csstools/cli postcss-preset-env","PostCSS Preset Env","Lets you convert modern CSS into something most browsers can understand, determining the polyfills you need based on your targeted browsers or runtime environments.",{stage:0,minimumVendorImplementations:2,features:{"blank-pseudo-class":{preserve:!1},"color-functional-notation":{preserve:!0}},env:"production",browsers:"last 2 versions",autoprefixer:{grid:!0},preserve:!1,logical:{inlineDirection:"left-to-right",blockDirection:"top-to-bottom"},enableClientSidePolyfills:!1,debug:!1}),!1);case"postcss-pseudo-class-any-link":return void cli(G,["preserve"],helpTextLogger("@csstools/cli postcss-pseudo-class-any-link","PostCSS Pseudo Class Any Link","Lets you :any-link pseudo-class in CSS, following the Selectors specification.",{preserve:!0}),!1);case"postcss-scope-pseudo-class":return void cli(J,["preserve"],helpTextLogger("@csstools/cli postcss-scope-pseudo-class","PostCSS Scope Pseudo Class","Lets you use the Reference Element Pseudo-class: :scope.",{preserve:!0}),!1);case"postcss-relative-color-syntax":return void cli(H,["preserve","enableProgressiveCustomProperties","subFeatures"],helpTextLogger("@csstools/cli postcss-relative-color-syntax","PostCSS Relative Color Syntax","Lets you use the relative color syntax in CSS color functions.",{preserve:!0,enableProgressiveCustomProperties:!1,subFeatures:{displayP3:!1}}),!1);case"postcss-selector-not":return void cli(Q,[],helpTextLogger("@csstools/cli postcss-selector-not","PostCSS Selector Not","Transforms :not() W3C CSS level 4 pseudo classes to :not() CSS level 3 selectors following the Selectors 4 Specification"),!1);case"postcss-stepped-value-functions":return void cli(B,["preserve","onInvalid"],helpTextLogger("@csstools/cli postcss-stepped-value-functions","PostCSS Stepped Value Functions","Lets you use round(), mod() and rem() functions.",{preserve:!1,onInvalid:"warn"}),!1);case"postcss-text-decoration-shorthand":return void cli(K,["preserve"],helpTextLogger("@csstools/cli postcss-text-decoration-shorthand","PostCSS Text Decoration Shorthand","Lets you use text-decoration in it's shorthand form in CSS.",{preserve:!0}),!1);case"postcss-trigonometric-functions":return void cli(Y,["preserve"],helpTextLogger("@csstools/cli postcss-trigonometric-functions","PostCSS Trigonometric Functions","Lets you use `sin`, `cos`, `tan`, `asin`, `acos`, `atan` and `atan2` to be able to compute trigonometric relationships following the CSS Values 4 specification.",{preserve:!0}),!1);case"postcss-unset-value":return void cli(_,["preserve"],helpTextLogger("@csstools/cli postcss-unset-value","PostCSS Stepped Unset Value","Use the unset keyword in CSS.",{preserve:!1}),!1);default:{const s=["CSSTools CLI\n"," Transform CSS with any plugin from https://github.com/csstools/postcss-plugins\n","Usage:"," @csstools/csstools-cli postcss-preset-env [input.css] [OPTIONS] [-o|--output output.css]"," @csstools/csstools-cli postcss-preset-env ... [OPTIONS] --dir "," @csstools/csstools-cli postcss-preset-env ... [OPTIONS] --replace","\nAvailable Plugins:"," postcss-preset-env"," css-blank-pseudo"," css-has-pseudo"," css-prefers-color-scheme"," postcss-attribute-case-insensitive"," postcss-cascade-layers"," postcss-color-function"," postcss-color-functional-notation"," postcss-color-hex-alpha"," postcss-color-mix-function"," postcss-color-rebeccapurple"," postcss-custom-media"," postcss-custom-properties"," postcss-custom-selectors"," postcss-dir-pseudo-class"," postcss-double-position-gradients"," postcss-exponential-functions"," postcss-focus-visible"," postcss-focus-within"," postcss-font-format-keywords"," postcss-gap-properties"," postcss-gradients-interpolation-method"," postcss-hwb-function"," postcss-ic-unit"," postcss-image-set-function"," postcss-is-pseudo-class"," postcss-lab-function"," postcss-light-dark-function"," postcss-logical"," postcss-logical-float-and-clear"," postcss-logical-resize"," postcss-logical-viewport-units"," postcss-media-minmax"," postcss-media-queries-aspect-ratio-number-values"," postcss-nested-calc"," postcss-nesting"," postcss-normalize-display-values"," postcss-oklab-function"," postcss-overflow-shorthand"," postcss-place"," postcss-pseudo-class-any-link"," postcss-relative-color-syntax"," postcss-scope-pseudo-class"," postcss-selector-not"," postcss-stepped-value-functions"," postcss-text-decoration-shorthand"," postcss-trigonometric-functions"," postcss-unset-value","\nPlugin Help:"," @csstools/csstools-cli "," @csstools/csstools-cli postcss-preset-env"];console.warn(s.join("\n"))}}}(); +"use strict";var s,e=require("css-blank-pseudo"),o=require("postcss"),t=require("path"),i=require("fs"),c=require("css-has-pseudo"),r=require("css-prefers-color-scheme"),n=require("postcss-attribute-case-insensitive"),a=require("@csstools/postcss-cascade-layers"),l=require("@csstools/postcss-color-function"),p=require("postcss-color-functional-notation"),u=require("postcss-color-hex-alpha"),d=require("@csstools/postcss-color-mix-function"),g=require("postcss-color-rebeccapurple"),f=require("postcss-custom-media"),S=require("postcss-custom-properties"),h=require("postcss-custom-selectors"),v=require("postcss-dir-pseudo-class"),m=require("postcss-double-position-gradients"),w=require("@csstools/postcss-exponential-functions"),C=require("postcss-focus-visible"),y=require("postcss-focus-within"),P=require("@csstools/postcss-font-format-keywords"),b=require("postcss-gap-properties"),x=require("@csstools/postcss-gradients-interpolation-method"),L=require("@csstools/postcss-hwb-function"),T=require("@csstools/postcss-ic-unit"),F=require("postcss-image-set-function"),q=require("@csstools/postcss-is-pseudo-class"),k=require("postcss-lab-function"),M=require("@csstools/postcss-light-dark-function"),I=require("postcss-logical"),D=require("@csstools/postcss-logical-float-and-clear"),N=require("@csstools/postcss-logical-resize"),O=require("@csstools/postcss-logical-viewport-units"),A=require("@csstools/postcss-media-minmax"),V=require("@csstools/postcss-media-queries-aspect-ratio-number-values"),E=require("@csstools/postcss-nested-calc"),z=require("postcss-nesting"),R=require("@csstools/postcss-normalize-display-values"),$=require("@csstools/postcss-oklab-function"),U=require("postcss-overflow-shorthand"),W=require("postcss-place"),G=require("postcss-preset-env"),j=require("postcss-pseudo-class-any-link"),H=require("@csstools/postcss-relative-color-syntax"),B=require("@csstools/postcss-scope-pseudo-class"),K=require("postcss-selector-not"),Q=require("@csstools/postcss-stepped-value-functions"),J=require("@csstools/postcss-text-decoration-shorthand"),Y=require("@csstools/postcss-trigonometric-functions"),_=require("@csstools/postcss-unset-value");function parseArguments(e,o,t){const i=e.map((s=>s.trim())).filter((s=>!!s)),c={stdin:!1,stdout:!1,output:void 0,outputDir:void 0,inputs:[],inlineMap:!0,externalMap:!1,replace:!1,pluginOptions:{},debug:!1};let r,n=!1;for(let e=0;e1&&c.output)return console.warn('[error] omit "--output" when processing multiple inputs\n'),t(),s.InvalidArguments;0===c.inputs.length&&(c.stdin=!0),c.output||c.outputDir||c.replace||(c.stdout=!0),c.stdout&&(c.externalMap=!1);let a={};if(r)try{a=JSON.parse(r)}catch{return console.warn("[error] plugin options must be valid JSON\n"),t(),s.InvalidArguments}for(const e in a){const i=a[e];if(!o.includes(e))return console.warn(`[error] unknown plugin option: ${e}\n`),t(),s.InvalidArguments;c.pluginOptions[e]=i}return c}async function getStdin(){return new Promise((s=>{let e="",o=!1;if(setTimeout((()=>{o=!0,s("")}),1e4),process.stdin.isTTY){if(o)return;s(e)}else process.stdin.setEncoding("utf8"),process.stdin.on("readable",(()=>{let s="";for(;s=process.stdin.read();)e+=s??""})),process.stdin.on("end",(()=>{o||s(e)}))}))}async function stdinToStdout(s,e,t){let i="";try{const c=await getStdin();c||(t(),process.exit(1));const r=await o([s]).process(c,{from:"stdin",to:"stdout",map:!!e.inlineMap&&{inline:!0}});r.warnings().forEach((s=>{console.warn(s.toString())})),i=r.css}catch(s){s instanceof Error?console.error(e.debug?s:s.message):console.error(s),process.exit(1)}process.stdout.write(i+(e.inlineMap?"\n":"")),process.exit(0)}async function stdinToFs(s,e,c){let r=e.output;!r&&e.outputDir&&(r=t.join(e.outputDir,"output.css")),r||process.exit(0);try{const t=await getStdin();t||(c(),process.exit(1));const n=await o([s]).process(t,{from:"stdin",to:r,map:!(!e.inlineMap&&!e.externalMap)&&{inline:e.inlineMap}});n.warnings().forEach((s=>{console.warn(s.toString())})),e.externalMap&&n.map?await Promise.all([await i.promises.writeFile(r,n.css+(e.inlineMap?"\n":"")),await i.promises.writeFile(`${r}.map`,n.map.toString())]):await i.promises.writeFile(r,n.css+(e.inlineMap?"\n":""))}catch(s){s instanceof Error?console.error(e.debug?s:s.message):console.error(s),process.exit(1)}console.log(`CSS was written to "${t.normalize(r)}"`),process.exit(0)}async function fsToStdout(s,e){let t=[];try{t=await Promise.all(e.inputs.map((async e=>{const t=await i.promises.readFile(e),c=await o([s]).process(t,{from:e,to:"stdout",map:!1});return c.warnings().forEach((s=>{console.warn(s.toString())})),c.css})))}catch(s){s instanceof Error?console.error(e.debug?s:s.message):console.error(s),process.exit(1)}for(const s of t)process.stdout.write(s);process.exit(0)}async function fsToFs(s,e){try{await Promise.all(e.inputs.map((async c=>{let r=e.output;e.outputDir&&(r=t.join(e.outputDir,t.basename(c))),e.replace&&(r=c),r||process.exit(0);const n=await i.promises.readFile(c),a=await o([s]).process(n,{from:c,to:r,map:!(!e.inlineMap&&!e.externalMap)&&{inline:e.inlineMap}});a.warnings().forEach((s=>{console.warn(s.toString())})),e.externalMap&&a.map?await Promise.all([await i.promises.writeFile(r,a.css+(e.inlineMap?"\n":"")),await i.promises.writeFile(`${r}.map`,a.map.toString())]):await i.promises.writeFile(r,a.css+(e.inlineMap?"\n":"")),console.log(`CSS was written to "${t.normalize(r)}"`)})))}catch(s){s instanceof Error?console.error(e.debug?s:s.message):console.error(s),process.exit(1)}process.exit(0)}function helpTextLogger(s,e,o,t=null){let i=[];if(t){const s=Math.max(...Object.keys(t).map((s=>s.length))),e=new Array(s).fill(" ").join("");e.length&&(i=["\nPlugin Options:",...Object.keys(t).map((s=>` ${(s+e).slice(0,e.length)} ${typeof t[s]}`))],i.push(`\n ${JSON.stringify(t,null,2).split("\n").join("\n ")}`))}const c=[`${e}\n`,` ${o}\n`,"Usage:",` ${s} [input.css] [OPTIONS] [-o|--output output.css]`,` ${s} ... [OPTIONS] --dir `,` ${s} ... [OPTIONS] --replace`,"\nOptions:"," -o, --output Output file"," -d, --dir Output directory"," -r, --replace Replace (overwrite) the input file"," -m, --map Create an external sourcemap"," --no-map Disable the default inline sourcemaps"," -p, --plugin-options Stringified JSON object with plugin options"];return i.length>0&&c.push(...i),()=>{console.warn(c.join("\n"))}}async function cli(e,o,t,i=!0){const c=parseArguments(process.argv.slice(i?2:3),o,t);c===s.InvalidArguments&&process.exit(1);const r=e(c.pluginOptions);c.stdin&&c.stdout?await stdinToStdout(r,c,t):c.stdin?await stdinToFs(r,c,t):c.stdout?await fsToStdout(r,c):await fsToFs(r,c)}async function cssBlankPseudo(){await cli(e,["preserve","replaceWith"],helpTextLogger("@csstools/cli css-blank-pseudo","PostCSS Blank Pseudo","Lets you style form elements when they are empty, following the Selectors Level 4 specification.",{preserve:!0,replaceWith:".css-blank"}),!1)}async function cssHasPseudo(){await cli(c,["preserve"],helpTextLogger("@csstools/cli css-has-pseudo","PostCSS Has Pseudo","Transforms CSS with :has {}",{preserve:!0}),!1)}async function cssPrefersColorScheme(){await cli(r,["preserve","mediaQuery"],helpTextLogger("@csstools/cli css-prefers-color-scheme","Prefers Color Scheme","Lets you use light and dark color schemes in all browsers, following the Media Queries specification.",{preserve:!0,mediaQuery:"color|color-index"}),!1)}async function postcssAttributeCaseInsensitive(){await cli(n,[],helpTextLogger("@csstools/cli postcss-attribute-case-insensitive","PostCSS Attribute Case Insensitive","Enables support for Case Insensitive Attribute matching in selectors"),!1)}async function postcssCascadeLayers(){await cli(a,[],helpTextLogger("@csstools/cli postcss-cascade-layers","PostCSS Cascade Layers","Lets you use `@layer` following the Cascade Layers Specification."),!1)}async function postcssColorFunction(){await cli(l,["preserve","enableProgressiveCustomProperties"],helpTextLogger("@csstools/cli postcss-color-function","PostCSS Color Function","Lets you use the color() function in CSS.",{preserve:!0,enableProgressiveCustomProperties:!1}),!1)}async function postcssColorFunctionalNotation(){await cli(p,["preserve"],helpTextLogger("@csstools/cli postcss-color-functional-notation","PostCSS Color Functional Notation","Lets you use space and slash separated color notation in CSS, following the CSS Color specification.",{preserve:!0}),!1)}async function postcssColorHexAlpha(){await cli(u,["preserve"],helpTextLogger("@csstools/cli postcss-color-hex-alpha","PostCSS Color Hex Alpha","Lets you use 4 & 8 character hex color notation in CSS, following the CSS Color Module specification.",{preserve:!0}),!1)}async function postcssColorMixFunction(){await cli(d,["preserve","enableProgressiveCustomProperties"],helpTextLogger("@csstools/cli postcss-color-mix-function","PostCSS Color Mix Function","Lets you use the color-mix() function in CSS.",{preserve:!0,enableProgressiveCustomProperties:!1,subFeatures:{displayP3:!1}}),!1)}async function postcssColorRebeccaPurple(){await cli(g,["preserve"],helpTextLogger("@csstools/cli postcss-color-rebeccapurple","PostCSS RebeccaPurple","Lets you use the rebeccapurple color keyword in CSS.",{preserve:!0}),!1)}async function postcssCustomMedia(){await cli(f,["preserve"],helpTextLogger("@csstools/cli postcss-custom-media","PostCSS Custom Media","Lets you define @custom-media in CSS following the Custom Media Specification",{preserve:!0}),!1)}async function postcssCustomProperties(){await cli(S,["preserve"],helpTextLogger("@csstools/cli postcss-custom-properties","PostCSS Custom Properties","Lets you use Custom Properties in CSS, following the CSS Custom Properties specification.",{preserve:!0}),!1)}async function postcssCustomSelectors(){await cli(h,["preserve"],helpTextLogger("@csstools/cli postcss-custom-selectors","PostCSS Custom Selectors","Lets you define @custom-selector in CSS following the Custom Selectors Specification",{preserve:!0}),!1)}async function postcssDirPseudoClass(){await cli(v,["dir","preserve","shadow"],helpTextLogger("@csstools/cli postcss-dir-pseudo-class","PostCSS Dir Pseudo Class","Lets you style by directionality using the `:dir()` pseudo-class in CSS",{dir:"ltr",preserve:!0,shadow:!0}),!1)}async function postcssDoublePositionGradients(){await cli(m,["preserve","enableProgressiveCustomProperties"],helpTextLogger("@csstools/cli postcss-double-position-gradients","PostCSS Double Position Gradients","Lets you use double-position gradients in CSS, following the CSS Image Values and Replaced Content specification",{preserve:!0,enableProgressiveCustomProperties:!1}),!1)}async function postcssExponentialFunctions(){await cli(w,["preserve"],helpTextLogger("@csstools/cli postcss-exponential-functions","PostCSS Exponential Functions","Lets you use the `pow()`, `sqrt()`, `hypot()`, `log()`, `exp()` functions following the CSS Values 4 Specification.",{preserve:!0}),!1)}async function postcssFocusVisible(){await cli(C,["preserve","replaceWith"],helpTextLogger("@csstools/cli postcss-focus-visible","PostCSS Focus Visible","Lets you use the `:focus-visible` pseudo-class in CSS, following the Selectors Level 4 specification.",{preserve:!0,replaceWith:".focus-visible"}),!1)}async function postcssFocusWithin(){await cli(y,["preserve","replaceWith"],helpTextLogger("@csstools/cli postcss-focus-within","PostCSS Focus Within","Lets you use the `:focus-within` pseudo-class in CSS, following the Selectors Level 4 specification.",{preserve:!0,replaceWith:".focus-within"}),!1)}async function postcssFontFormatKeywords(){await cli(P,["preserve"],helpTextLogger("@csstools/cli postcss-font-format-keywords","PostCSS Font Format Keyword","Lets you use unquoted format on @font-face CSS definitions.",{preserve:!0}),!1)}async function postcssGapProperties(){await cli(b,["preserve"],helpTextLogger("@csstools/cli postcss-gap-properties","PostCSS Gap Properties","Lets you use the gap, column-gap, and row-gap shorthand properties in CSS, following the CSS Grid Layout specification.",{preserve:!0}),!1)}async function postcssGradientsInterpolationMethod(){await cli(x,["preserve","enableProgressiveCustomProperties"],helpTextLogger("@csstools/cli postcss-gradients-interpolation-method","PostCSS Gradients Interpolation Method","Lets you use different interpolation methods in CSS gradient functions.",{preserve:!0,enableProgressiveCustomProperties:!1}),!1)}async function postcssHWBFunction(){await cli(L,["preserve"],helpTextLogger("@csstools/cli postcss-hwb-function","PostCSS HWB function","Convert hwb() to rgb()",{preserve:!0}),!1)}async function postcssICUnit(){await cli(T,["preserve","enableProgressiveCustomProperties"],helpTextLogger("@csstools/cli postcss-ic-unit","PostCSS IC Unit","Lets you use the ic length unit.",{preserve:!0,enableProgressiveCustomProperties:!1}),!1)}async function postcssImageSetFunction(){await cli(F,["oninvalid","preserve"],helpTextLogger("@csstools/cli postcss-image-set-function","PostCSS Image Set Function","Lets you display resolution-dependent images using the image-set() function in CSS, following the CSS Images specification.",{preserve:!0,oninvalid:"ignore|warn|throw"}),!1)}async function postcssIsPseudoClass(){await cli(q,["onComplexSelector","preserve","specificityMatchingName"],helpTextLogger("@csstools/cli postcss-is-pseudo-class","PostCSS Is Pseudo Class","Lets you use the :is pseudo class function, following the CSS Selector specification.",{onComplexSelector:"warning",preserve:!0,specificityMatchingName:"does-not-exist"}),!1)}async function postcssLabFunction(){await cli(k,["preserve","enableProgressiveCustomProperties","subFeatures"],helpTextLogger("@csstools/cli postcss-lab-function","PostCSS Lab function","Convert lab() to rgb()",{preserve:!0,enableProgressiveCustomProperties:!1,subFeatures:{displayP3:!1}}),!1)}async function postcssLightDarkFunction(){await cli(M,["preserve"],helpTextLogger("@csstools/cli postcss-light-dark-function","PostCSS Light Dark function","Use the light-dark() color function in CSS",{preserve:!0}),!1)}async function postcssLogical$1(){await cli(I,["inlineDirection","blockDirection"],helpTextLogger("@csstools/cli postcss-logical","PostCSS Logical","Lets you use logical, rather than physical, direction and dimension mappings in CSS, following the CSS Logical Properties and Values specification.",{inlineDirection:"left-to-right",blockDirection:"top-to-bottom"}),!1)}async function postcssLogical(){await cli(D,["inlineDirection","blockDirection"],helpTextLogger("@csstools/cli postcss-logical-float-and-clear","PostCSS Logical Float And Clear","Lets you use flow-relative (inline-start and inline-end) values for float and clear, following the CSS Logical Properties and Values specification.",{inlineDirection:"left-to-right"}),!1)}async function postcssLogicalResize(){await cli(N,["inlineDirection"],helpTextLogger("@csstools/cli postcss-logical-resize","PostCSS Logical Resize","Lets you use logical values in the resize property, following the CSS Logical Properties and Values specification.",{inlineDirection:"left-to-right"}),!1)}async function postcssLogicalViewportUnits(){await cli(O,["inlineDirection","preserve"],helpTextLogger("@csstools/cli postcss-viewport-units","PostCSS Logical Viewport Units","Lets you use vb and vi length units in CSS, following the CSS Values and Units Module Level 4 specification.",{inlineDirection:"left-to-right",preserve:!0}),!1)}async function postcssMediaMinMax(){await cli(A,[],helpTextLogger("@csstools/cli postcss-media-minmax","PostCSS Media MinMax","Lets you use the range notation in CSS media queries.",{}),!1)}async function postcssMediaQueriesAspectRatioNumberValues(){await cli(V,[],helpTextLogger("@csstools/cli postcss-media-queries-aspect-ratio-number-values","PostCSS Media Queries Aspect-Ratio Number Values","Lets you use number values in aspect-ratio media queries.",{}),!1)}async function postcssNestedCalc(){await cli(E,["preserve"],helpTextLogger("@csstools/cli postcss-nested-calc","PostCSS Nested Calc","Lets you use nested calc() expressions in CSS.",{preserve:!0}),!1)}async function postcssNesting(){await cli(z,["noIsPseudoSelector"],helpTextLogger("@csstools/cli postcss-nesting","PostCSS Nesting","Lets you nest style rules inside each other, following the CSS Nesting specification.",{noIsPseudoSelector:!0}),!1)}async function postcssNormalizeDisplayValues(){await cli(R,["preserve"],helpTextLogger("@csstools/cli postcss-normalize-display-values","PostCSS Normalize Display Values","Lets you use two values display syntax for inner and outer display types.",{preserve:!0}),!1)}async function postcssOKLabFunction(){await cli($,["preserve","enableProgressiveCustomProperties","subFeatures"],helpTextLogger("@csstools/cli postcss-oklab-function","PostCSS OKLab Function","Lets you use oklab() and oklch() color functions in CSS.",{preserve:!0,enableProgressiveCustomProperties:!1,subFeatures:{displayP3:!1}}),!1)}async function postcssOverflowShorthand(){await cli(U,["preserve"],helpTextLogger("@csstools/cli postcss-overflow-shorthand","PostCSS Overflow Shorthand","Lets you use the `overflow` shorthand in CSS, following the CSS Overflow specification.",{preserve:!0}),!1)}async function postcssPlace(){await cli(W,["preserve"],helpTextLogger("@csstools/cli postcss-place","PostCSS Place","Lets you use place-* properties as shorthands for align-* and justify-*, following the CSS Box Alignment specification.",{preserve:!0}),!1)}async function postcssPresetEnv(){await cli(G,["stage","minimumVendorImplementations","features","env","browsers","autoprefixer","preserve","logical","enableClientSidePolyfills","debug"],helpTextLogger("@csstools/cli postcss-preset-env","PostCSS Preset Env","Lets you convert modern CSS into something most browsers can understand, determining the polyfills you need based on your targeted browsers or runtime environments.",{stage:0,minimumVendorImplementations:2,features:{"blank-pseudo-class":{preserve:!1},"color-functional-notation":{preserve:!0}},env:"production",browsers:"last 2 versions",autoprefixer:{grid:!0},preserve:!1,logical:{inlineDirection:"left-to-right",blockDirection:"top-to-bottom"},enableClientSidePolyfills:!1,debug:!1}),!1)}async function postcssPseudoClassAnyLink(){await cli(j,["preserve"],helpTextLogger("@csstools/cli postcss-pseudo-class-any-link","PostCSS Pseudo Class Any Link","Lets you :any-link pseudo-class in CSS, following the Selectors specification.",{preserve:!0}),!1)}async function postcssRelativeColorSyntax(){await cli(H,["preserve","enableProgressiveCustomProperties","subFeatures"],helpTextLogger("@csstools/cli postcss-relative-color-syntax","PostCSS Relative Color Syntax","Lets you use the relative color syntax in CSS color functions.",{preserve:!0,enableProgressiveCustomProperties:!1,subFeatures:{displayP3:!1}}),!1)}async function postcssScopePseudoClass(){await cli(B,["preserve"],helpTextLogger("@csstools/cli postcss-scope-pseudo-class","PostCSS Scope Pseudo Class","Lets you use the Reference Element Pseudo-class: :scope.",{preserve:!0}),!1)}async function postcssSelectorNot(){await cli(K,[],helpTextLogger("@csstools/cli postcss-selector-not","PostCSS Selector Not","Transforms :not() W3C CSS level 4 pseudo classes to :not() CSS level 3 selectors following the Selectors 4 Specification"),!1)}async function postcssSteppedValueFunctions(){await cli(Q,["preserve","onInvalid"],helpTextLogger("@csstools/cli postcss-stepped-value-functions","PostCSS Stepped Value Functions","Lets you use round(), mod() and rem() functions.",{preserve:!1,onInvalid:"warn"}),!1)}async function postcssTextDecorationShorthand(){await cli(J,["preserve"],helpTextLogger("@csstools/cli postcss-text-decoration-shorthand","PostCSS Text Decoration Shorthand","Lets you use text-decoration in it's shorthand form in CSS.",{preserve:!0}),!1)}async function postcssTrigonometricFunctions(){await cli(Y,["preserve"],helpTextLogger("@csstools/cli postcss-trigonometric-functions","PostCSS Trigonometric Functions","Lets you use `sin`, `cos`, `tan`, `asin`, `acos`, `atan` and `atan2` to be able to compute trigonometric relationships following the CSS Values 4 specification.",{preserve:!0}),!1)}async function postcssUnsetValue(){await cli(_,["preserve"],helpTextLogger("@csstools/cli postcss-unset-value","PostCSS Stepped Unset Value","Use the unset keyword in CSS.",{preserve:!1}),!1)}(s||(s={})).InvalidArguments="INVALID_ARGUMENTS",async function main(){switch(process.argv[2]??!1){case"css-blank-pseudo":return void await cssBlankPseudo();case"css-has-pseudo":return void await cssHasPseudo();case"css-prefers-color-scheme":return void await cssPrefersColorScheme();case"postcss-attribute-case-insensitive":return void await postcssAttributeCaseInsensitive();case"postcss-cascade-layers":return void await postcssCascadeLayers();case"postcss-color-function":return void await postcssColorFunction();case"postcss-color-mix-function":return void await postcssColorMixFunction();case"postcss-color-functional-notation":return void await postcssColorFunctionalNotation();case"postcss-color-hex-alpha":return void await postcssColorHexAlpha();case"postcss-color-rebeccapurple":return void await postcssColorRebeccaPurple();case"postcss-custom-media":return void await postcssCustomMedia();case"postcss-custom-properties":return void await postcssCustomProperties();case"postcss-custom-selectors":return void await postcssCustomSelectors();case"postcss-dir-pseudo-class":return void await postcssDirPseudoClass();case"postcss-double-position-gradients":return void await postcssDoublePositionGradients();case"postcss-exponential-functions":return void await postcssExponentialFunctions();case"postcss-focus-visible":return void await postcssFocusVisible();case"postcss-focus-within":return void await postcssFocusWithin();case"postcss-font-format-keywords":return void await postcssFontFormatKeywords();case"postcss-gap-properties":return void await postcssGapProperties();case"postcss-gradients-interpolation-method":return void await postcssGradientsInterpolationMethod();case"postcss-hwb-function":return void await postcssHWBFunction();case"postcss-ic-unit":return void await postcssICUnit();case"postcss-image-set-function":return void await postcssImageSetFunction();case"postcss-is-pseudo-class":return void await postcssIsPseudoClass();case"postcss-lab-function":return void await postcssLabFunction();case"postcss-light-dark-function":return void await postcssLightDarkFunction();case"postcss-logical":return void await postcssLogical$1();case"postcss-logical-float-and-clear":return void await postcssLogical();case"postcss-logical-resize":return void await postcssLogicalResize();case"postcss-logical-viewport-units":return void await postcssLogicalViewportUnits();case"postcss-media-minmax":return void await postcssMediaMinMax();case"postcss-media-queries-aspect-ratio-number-values":return void await postcssMediaQueriesAspectRatioNumberValues();case"postcss-nested-calc":return void await postcssNestedCalc();case"postcss-nesting":return void await postcssNesting();case"postcss-normalize-display-values":return void await postcssNormalizeDisplayValues();case"postcss-oklab-function":return void await postcssOKLabFunction();case"postcss-overflow-shorthand":return void await postcssOverflowShorthand();case"postcss-place":return void await postcssPlace();case"postcss-preset-env":return void await postcssPresetEnv();case"postcss-pseudo-class-any-link":return void await postcssPseudoClassAnyLink();case"postcss-scope-pseudo-class":return void await postcssScopePseudoClass();case"postcss-relative-color-syntax":return void await postcssRelativeColorSyntax();case"postcss-selector-not":return void await postcssSelectorNot();case"postcss-stepped-value-functions":return void await postcssSteppedValueFunctions();case"postcss-text-decoration-shorthand":return void await postcssTextDecorationShorthand();case"postcss-trigonometric-functions":return void await postcssTrigonometricFunctions();case"postcss-unset-value":return void await postcssUnsetValue();default:{const s=["CSSTools CLI\n"," Transform CSS with any plugin from https://github.com/csstools/postcss-plugins\n","Usage:"," @csstools/csstools-cli postcss-preset-env [input.css] [OPTIONS] [-o|--output output.css]"," @csstools/csstools-cli postcss-preset-env ... [OPTIONS] --dir "," @csstools/csstools-cli postcss-preset-env ... [OPTIONS] --replace","\nAvailable Plugins:"," postcss-preset-env"," css-blank-pseudo"," css-has-pseudo"," css-prefers-color-scheme"," postcss-attribute-case-insensitive"," postcss-cascade-layers"," postcss-color-function"," postcss-color-functional-notation"," postcss-color-hex-alpha"," postcss-color-mix-function"," postcss-color-rebeccapurple"," postcss-custom-media"," postcss-custom-properties"," postcss-custom-selectors"," postcss-dir-pseudo-class"," postcss-double-position-gradients"," postcss-exponential-functions"," postcss-focus-visible"," postcss-focus-within"," postcss-font-format-keywords"," postcss-gap-properties"," postcss-gradients-interpolation-method"," postcss-hwb-function"," postcss-ic-unit"," postcss-image-set-function"," postcss-is-pseudo-class"," postcss-lab-function"," postcss-light-dark-function"," postcss-logical"," postcss-logical-float-and-clear"," postcss-logical-resize"," postcss-logical-viewport-units"," postcss-media-minmax"," postcss-media-queries-aspect-ratio-number-values"," postcss-nested-calc"," postcss-nesting"," postcss-normalize-display-values"," postcss-oklab-function"," postcss-overflow-shorthand"," postcss-place"," postcss-pseudo-class-any-link"," postcss-relative-color-syntax"," postcss-scope-pseudo-class"," postcss-selector-not"," postcss-stepped-value-functions"," postcss-text-decoration-shorthand"," postcss-trigonometric-functions"," postcss-unset-value","\nPlugin Help:"," @csstools/csstools-cli "," @csstools/csstools-cli postcss-preset-env"];console.warn(s.join("\n"))}}}(); diff --git a/cli/csstools-cli/src/cli.ts b/cli/csstools-cli/src/cli.ts index b780ffaf8..8a2f9343c 100644 --- a/cli/csstools-cli/src/cli.ts +++ b/cli/csstools-cli/src/cli.ts @@ -47,152 +47,153 @@ import postcssTextDecorationShorthand from './plugins/postcss-text-decoration-sh import postcssTrigonometricFunctions from './plugins/postcss-trigonometric-functions'; import postcssUnsetValue from './plugins/postcss-unset-value'; -main(); -function main(): void { +void main(); + +async function main(): Promise { switch (process.argv[2] ?? false) { case 'css-blank-pseudo': - cssBlankPseudo(); + await cssBlankPseudo(); return; case 'css-has-pseudo': - cssHasPseudo(); + await cssHasPseudo(); return; case 'css-prefers-color-scheme': - cssPrefersColorScheme(); + await cssPrefersColorScheme(); return; case 'postcss-attribute-case-insensitive': - postcssAttributeCaseInsensitive(); + await postcssAttributeCaseInsensitive(); return; case 'postcss-cascade-layers': - postcssCascadeLayers(); + await postcssCascadeLayers(); return; case 'postcss-color-function': - postcssColorFunction(); + await postcssColorFunction(); return; case 'postcss-color-mix-function': - postcssColorMixFunction(); + await postcssColorMixFunction(); return; case 'postcss-color-functional-notation': - postcssColorFunctionalNotation(); + await postcssColorFunctionalNotation(); return; case 'postcss-color-hex-alpha': - postcssColorHexAlpha(); + await postcssColorHexAlpha(); return; case 'postcss-color-rebeccapurple': - postcssColorRebeccaPurple(); + await postcssColorRebeccaPurple(); return; case 'postcss-custom-media': - postcssCustomMedia(); + await postcssCustomMedia(); return; case 'postcss-custom-properties': - postcssCustomProperties(); + await postcssCustomProperties(); return; case 'postcss-custom-selectors': - postcssCustomSelectors(); + await postcssCustomSelectors(); return; case 'postcss-dir-pseudo-class': - postcssDirPseudoClass(); + await postcssDirPseudoClass(); return; case 'postcss-double-position-gradients': - postcssDoublePositionGradients(); + await postcssDoublePositionGradients(); return; case 'postcss-exponential-functions': - postcssExponentialFunctions(); + await postcssExponentialFunctions(); return; case 'postcss-focus-visible': - postcssFocusVisible(); + await postcssFocusVisible(); return; case 'postcss-focus-within': - postcssFocusWithin(); + await postcssFocusWithin(); return; case 'postcss-font-format-keywords': - postcssFontFormatKeywords(); + await postcssFontFormatKeywords(); return; case 'postcss-gap-properties': - postcssGapProperties(); + await postcssGapProperties(); return; case 'postcss-gradients-interpolation-method': - postcssGradientsInterpolationMethod(); + await postcssGradientsInterpolationMethod(); return; case 'postcss-hwb-function': - postcssHWBFunction(); + await postcssHWBFunction(); return; case 'postcss-ic-unit': - postcssICUnit(); + await postcssICUnit(); return; case 'postcss-image-set-function': - postcssImageSetFunction(); + await postcssImageSetFunction(); return; case 'postcss-is-pseudo-class': - postcssIsPseudoClass(); + await postcssIsPseudoClass(); return; case 'postcss-lab-function': - postcssLabFunction(); + await postcssLabFunction(); return; case 'postcss-light-dark-function': - postcssLightDarkFunction(); + await postcssLightDarkFunction(); return; case 'postcss-logical': - postcssLogical(); + await postcssLogical(); return; case 'postcss-logical-float-and-clear': - postcssLogicalFloatAndClear(); + await postcssLogicalFloatAndClear(); return; case 'postcss-logical-resize': - postcssLogicalResize(); + await postcssLogicalResize(); return; case 'postcss-logical-viewport-units': - postcssLogicalViewportUnits(); + await postcssLogicalViewportUnits(); return; case 'postcss-media-minmax': - postcssMediaMinMax(); + await postcssMediaMinMax(); return; case 'postcss-media-queries-aspect-ratio-number-values': - postcssMediaQueriesAspectRatioNumberValues(); + await postcssMediaQueriesAspectRatioNumberValues(); return; case 'postcss-nested-calc': - postcssNestedCalc(); + await postcssNestedCalc(); return; case 'postcss-nesting': - postcssNesting(); + await postcssNesting(); return; case 'postcss-normalize-display-values': - postcssNormalizeDisplayValues(); + await postcssNormalizeDisplayValues(); return; case 'postcss-oklab-function': - postcssOKLabFunction(); + await postcssOKLabFunction(); return; case 'postcss-overflow-shorthand': - postcssOverflowShorthand(); + await postcssOverflowShorthand(); return; case 'postcss-place': - postcssPlace(); + await postcssPlace(); return; case 'postcss-preset-env': - postcssPresetEnv(); + await postcssPresetEnv(); return; case 'postcss-pseudo-class-any-link': - postcssPseudoClassAnyLink(); + await postcssPseudoClassAnyLink(); return; case 'postcss-scope-pseudo-class': - postcssScopePseudoClass(); + await postcssScopePseudoClass(); return; case 'postcss-relative-color-syntax': - postcssRelativeColorSyntax(); + await postcssRelativeColorSyntax(); return; case 'postcss-selector-not': - postcssSelectorNot(); + await postcssSelectorNot(); return; case 'postcss-stepped-value-functions': - postcssSteppedValueFunctions(); + await postcssSteppedValueFunctions(); return; case 'postcss-text-decoration-shorthand': - postcssTextDecorationShorthand(); + await postcssTextDecorationShorthand(); return; case 'postcss-trigonometric-functions': - postcssTrigonometricFunctions(); + await postcssTrigonometricFunctions(); return; case 'postcss-unset-value': - postcssUnsetValue(); + await postcssUnsetValue(); return; default: { diff --git a/cli/csstools-cli/src/plugins/css-blank-pseudo.ts b/cli/csstools-cli/src/plugins/css-blank-pseudo.ts index 09d0ce7d8..5e54bc074 100644 --- a/cli/csstools-cli/src/plugins/css-blank-pseudo.ts +++ b/cli/csstools-cli/src/plugins/css-blank-pseudo.ts @@ -1,8 +1,8 @@ import plugin from 'css-blank-pseudo'; import { cli, helpTextLogger } from '@csstools/base-cli'; -export default function cssBlankPseudo(): void { - cli( +export default async function cssBlankPseudo(): Promise { + await cli( plugin, ['preserve', 'replaceWith'], helpTextLogger( diff --git a/cli/csstools-cli/src/plugins/css-has-pseudo.ts b/cli/csstools-cli/src/plugins/css-has-pseudo.ts index f38e17943..b170d6aa6 100644 --- a/cli/csstools-cli/src/plugins/css-has-pseudo.ts +++ b/cli/csstools-cli/src/plugins/css-has-pseudo.ts @@ -1,8 +1,8 @@ import plugin from 'css-has-pseudo'; import { cli, helpTextLogger } from '@csstools/base-cli'; -export default function cssHasPseudo(): void { - cli( +export default async function cssHasPseudo(): Promise { + await cli( plugin, ['preserve'], helpTextLogger( diff --git a/cli/csstools-cli/src/plugins/css-prefers-color-scheme.ts b/cli/csstools-cli/src/plugins/css-prefers-color-scheme.ts index 7a8e98d4e..4fccf9a60 100644 --- a/cli/csstools-cli/src/plugins/css-prefers-color-scheme.ts +++ b/cli/csstools-cli/src/plugins/css-prefers-color-scheme.ts @@ -1,8 +1,8 @@ import plugin from 'css-prefers-color-scheme'; import { cli, helpTextLogger } from '@csstools/base-cli'; -export default function cssPrefersColorScheme(): void { - cli( +export default async function cssPrefersColorScheme(): Promise { + await cli( plugin, ['preserve', 'mediaQuery'], helpTextLogger( diff --git a/cli/csstools-cli/src/plugins/postcss-attribute-case-insensitive.ts b/cli/csstools-cli/src/plugins/postcss-attribute-case-insensitive.ts index 0d09c3a9f..e5416d7c3 100644 --- a/cli/csstools-cli/src/plugins/postcss-attribute-case-insensitive.ts +++ b/cli/csstools-cli/src/plugins/postcss-attribute-case-insensitive.ts @@ -1,8 +1,8 @@ import plugin from 'postcss-attribute-case-insensitive'; import { cli, helpTextLogger } from '@csstools/base-cli'; -export default function postcssAttributeCaseInsensitive(): void { - cli( +export default async function postcssAttributeCaseInsensitive(): Promise { + await cli( plugin, [], helpTextLogger( diff --git a/cli/csstools-cli/src/plugins/postcss-cascade-layers.ts b/cli/csstools-cli/src/plugins/postcss-cascade-layers.ts index 0b312a80d..869141a25 100644 --- a/cli/csstools-cli/src/plugins/postcss-cascade-layers.ts +++ b/cli/csstools-cli/src/plugins/postcss-cascade-layers.ts @@ -1,8 +1,8 @@ import plugin from '@csstools/postcss-cascade-layers'; import { cli, helpTextLogger } from '@csstools/base-cli'; -export default function postcssCascadeLayers(): void { - cli( +export default async function postcssCascadeLayers(): Promise { + await cli( plugin, [], helpTextLogger( diff --git a/cli/csstools-cli/src/plugins/postcss-color-function.ts b/cli/csstools-cli/src/plugins/postcss-color-function.ts index bcc8ba21d..fbe7f4bf7 100644 --- a/cli/csstools-cli/src/plugins/postcss-color-function.ts +++ b/cli/csstools-cli/src/plugins/postcss-color-function.ts @@ -1,8 +1,8 @@ import plugin from '@csstools/postcss-color-function'; import { cli, helpTextLogger } from '@csstools/base-cli'; -export default function postcssColorFunction(): void { - cli( +export default async function postcssColorFunction(): Promise { + await cli( plugin, ['preserve', 'enableProgressiveCustomProperties'], helpTextLogger( diff --git a/cli/csstools-cli/src/plugins/postcss-color-functional-notation.ts b/cli/csstools-cli/src/plugins/postcss-color-functional-notation.ts index 9cfd53a72..70f23c740 100644 --- a/cli/csstools-cli/src/plugins/postcss-color-functional-notation.ts +++ b/cli/csstools-cli/src/plugins/postcss-color-functional-notation.ts @@ -1,8 +1,8 @@ import plugin from 'postcss-color-functional-notation'; import { cli, helpTextLogger } from '@csstools/base-cli'; -export default function postcssColorFunctionalNotation(): void { - cli( +export default async function postcssColorFunctionalNotation(): Promise { + await cli( plugin, ['preserve'], helpTextLogger( diff --git a/cli/csstools-cli/src/plugins/postcss-color-hex-alpha.ts b/cli/csstools-cli/src/plugins/postcss-color-hex-alpha.ts index 686ccce50..16de47c1a 100644 --- a/cli/csstools-cli/src/plugins/postcss-color-hex-alpha.ts +++ b/cli/csstools-cli/src/plugins/postcss-color-hex-alpha.ts @@ -1,8 +1,8 @@ import plugin from 'postcss-color-hex-alpha'; import { cli, helpTextLogger } from '@csstools/base-cli'; -export default function postcssColorHexAlpha(): void { - cli( +export default async function postcssColorHexAlpha(): Promise { + await cli( plugin, ['preserve'], helpTextLogger( diff --git a/cli/csstools-cli/src/plugins/postcss-color-mix-function.ts b/cli/csstools-cli/src/plugins/postcss-color-mix-function.ts index 11497da65..711361a49 100644 --- a/cli/csstools-cli/src/plugins/postcss-color-mix-function.ts +++ b/cli/csstools-cli/src/plugins/postcss-color-mix-function.ts @@ -1,8 +1,8 @@ import plugin from '@csstools/postcss-color-mix-function'; import { cli, helpTextLogger } from '@csstools/base-cli'; -export default function postcssColorMixFunction(): void { - cli( +export default async function postcssColorMixFunction(): Promise { + await cli( plugin, ['preserve', 'enableProgressiveCustomProperties'], helpTextLogger( diff --git a/cli/csstools-cli/src/plugins/postcss-color-rebeccapurple.ts b/cli/csstools-cli/src/plugins/postcss-color-rebeccapurple.ts index 0fd0d3a8a..49adc84f0 100644 --- a/cli/csstools-cli/src/plugins/postcss-color-rebeccapurple.ts +++ b/cli/csstools-cli/src/plugins/postcss-color-rebeccapurple.ts @@ -1,8 +1,8 @@ import plugin from 'postcss-color-rebeccapurple'; import { cli, helpTextLogger } from '@csstools/base-cli'; -export default function postcssColorRebeccaPurple(): void { - cli( +export default async function postcssColorRebeccaPurple(): Promise { + await cli( plugin, ['preserve'], helpTextLogger( diff --git a/cli/csstools-cli/src/plugins/postcss-custom-media.ts b/cli/csstools-cli/src/plugins/postcss-custom-media.ts index 865fd59f4..151e02b29 100644 --- a/cli/csstools-cli/src/plugins/postcss-custom-media.ts +++ b/cli/csstools-cli/src/plugins/postcss-custom-media.ts @@ -1,8 +1,8 @@ import plugin from 'postcss-custom-media'; import { cli, helpTextLogger } from '@csstools/base-cli'; -export default function postcssCustomMedia(): void { - cli( +export default async function postcssCustomMedia(): Promise { + await cli( plugin, ['preserve'], helpTextLogger( diff --git a/cli/csstools-cli/src/plugins/postcss-custom-properties.ts b/cli/csstools-cli/src/plugins/postcss-custom-properties.ts index b9debfbfb..94e20ab6a 100644 --- a/cli/csstools-cli/src/plugins/postcss-custom-properties.ts +++ b/cli/csstools-cli/src/plugins/postcss-custom-properties.ts @@ -1,8 +1,8 @@ import plugin from 'postcss-custom-properties'; import { cli, helpTextLogger } from '@csstools/base-cli'; -export default function postcssCustomProperties(): void { - cli( +export default async function postcssCustomProperties(): Promise { + await cli( plugin, ['preserve'], helpTextLogger( diff --git a/cli/csstools-cli/src/plugins/postcss-custom-selectors.ts b/cli/csstools-cli/src/plugins/postcss-custom-selectors.ts index 388cae389..3d915bda8 100644 --- a/cli/csstools-cli/src/plugins/postcss-custom-selectors.ts +++ b/cli/csstools-cli/src/plugins/postcss-custom-selectors.ts @@ -1,8 +1,8 @@ import plugin from 'postcss-custom-selectors'; import { cli, helpTextLogger } from '@csstools/base-cli'; -export default function postcssCustomSelectors(): void { - cli( +export default async function postcssCustomSelectors(): Promise { + await cli( plugin, ['preserve'], helpTextLogger( diff --git a/cli/csstools-cli/src/plugins/postcss-dir-pseudo-class.ts b/cli/csstools-cli/src/plugins/postcss-dir-pseudo-class.ts index 0d96eace9..7fadce045 100644 --- a/cli/csstools-cli/src/plugins/postcss-dir-pseudo-class.ts +++ b/cli/csstools-cli/src/plugins/postcss-dir-pseudo-class.ts @@ -1,8 +1,8 @@ import plugin from 'postcss-dir-pseudo-class'; import { cli, helpTextLogger } from '@csstools/base-cli'; -export default function postcssDirPseudoClass(): void { - cli( +export default async function postcssDirPseudoClass(): Promise { + await cli( plugin, ['dir', 'preserve', 'shadow'], helpTextLogger( diff --git a/cli/csstools-cli/src/plugins/postcss-double-position-gradients.ts b/cli/csstools-cli/src/plugins/postcss-double-position-gradients.ts index 90d524fb6..24f3b7555 100644 --- a/cli/csstools-cli/src/plugins/postcss-double-position-gradients.ts +++ b/cli/csstools-cli/src/plugins/postcss-double-position-gradients.ts @@ -1,8 +1,8 @@ import plugin from 'postcss-double-position-gradients'; import { cli, helpTextLogger } from '@csstools/base-cli'; -export default function postcssDoublePositionGradients(): void { - cli( +export default async function postcssDoublePositionGradients(): Promise { + await cli( plugin, ['preserve', 'enableProgressiveCustomProperties'], helpTextLogger( diff --git a/cli/csstools-cli/src/plugins/postcss-exponential-functions.ts b/cli/csstools-cli/src/plugins/postcss-exponential-functions.ts index a4b3a7108..43b40abd6 100644 --- a/cli/csstools-cli/src/plugins/postcss-exponential-functions.ts +++ b/cli/csstools-cli/src/plugins/postcss-exponential-functions.ts @@ -1,8 +1,8 @@ import plugin from '@csstools/postcss-exponential-functions'; import { cli, helpTextLogger } from '@csstools/base-cli'; -export default function postcssExponentialFunctions(): void { - cli( +export default async function postcssExponentialFunctions(): Promise { + await cli( plugin, ['preserve'], helpTextLogger( diff --git a/cli/csstools-cli/src/plugins/postcss-focus-visible.ts b/cli/csstools-cli/src/plugins/postcss-focus-visible.ts index 672a64fdc..6e812151f 100644 --- a/cli/csstools-cli/src/plugins/postcss-focus-visible.ts +++ b/cli/csstools-cli/src/plugins/postcss-focus-visible.ts @@ -1,8 +1,8 @@ import plugin from 'postcss-focus-visible'; import { cli, helpTextLogger } from '@csstools/base-cli'; -export default function postcssFocusVisible(): void { - cli( +export default async function postcssFocusVisible(): Promise { + await cli( plugin, ['preserve', 'replaceWith'], helpTextLogger( diff --git a/cli/csstools-cli/src/plugins/postcss-focus-within.ts b/cli/csstools-cli/src/plugins/postcss-focus-within.ts index 2ff9753de..d96a8d9f9 100644 --- a/cli/csstools-cli/src/plugins/postcss-focus-within.ts +++ b/cli/csstools-cli/src/plugins/postcss-focus-within.ts @@ -1,8 +1,8 @@ import plugin from 'postcss-focus-within'; import { cli, helpTextLogger } from '@csstools/base-cli'; -export default function postcssFocusWithin(): void { - cli( +export default async function postcssFocusWithin(): Promise { + await cli( plugin, ['preserve', 'replaceWith'], helpTextLogger( diff --git a/cli/csstools-cli/src/plugins/postcss-font-format-keywords.ts b/cli/csstools-cli/src/plugins/postcss-font-format-keywords.ts index 093529d4b..ab1c17ea7 100644 --- a/cli/csstools-cli/src/plugins/postcss-font-format-keywords.ts +++ b/cli/csstools-cli/src/plugins/postcss-font-format-keywords.ts @@ -1,8 +1,8 @@ import plugin from '@csstools/postcss-font-format-keywords'; import { cli, helpTextLogger } from '@csstools/base-cli'; -export default function postcssFontFormatKeywords(): void { - cli( +export default async function postcssFontFormatKeywords(): Promise { + await cli( plugin, ['preserve'], helpTextLogger( diff --git a/cli/csstools-cli/src/plugins/postcss-gap-properties.ts b/cli/csstools-cli/src/plugins/postcss-gap-properties.ts index 9a47721e0..1153b5a5e 100644 --- a/cli/csstools-cli/src/plugins/postcss-gap-properties.ts +++ b/cli/csstools-cli/src/plugins/postcss-gap-properties.ts @@ -1,8 +1,8 @@ import plugin from 'postcss-gap-properties'; import { cli, helpTextLogger } from '@csstools/base-cli'; -export default function postcssGapProperties(): void { - cli( +export default async function postcssGapProperties(): Promise { + await cli( plugin, ['preserve'], helpTextLogger( diff --git a/cli/csstools-cli/src/plugins/postcss-gradients-interpolation-method.ts b/cli/csstools-cli/src/plugins/postcss-gradients-interpolation-method.ts index 4bded80d8..2fc63761d 100644 --- a/cli/csstools-cli/src/plugins/postcss-gradients-interpolation-method.ts +++ b/cli/csstools-cli/src/plugins/postcss-gradients-interpolation-method.ts @@ -1,8 +1,8 @@ import plugin from '@csstools/postcss-gradients-interpolation-method'; import { cli, helpTextLogger } from '@csstools/base-cli'; -export default function postcssGradientsInterpolationMethod(): void { - cli( +export default async function postcssGradientsInterpolationMethod(): Promise { + await cli( plugin, ['preserve', 'enableProgressiveCustomProperties'], helpTextLogger( diff --git a/cli/csstools-cli/src/plugins/postcss-hwb-function.ts b/cli/csstools-cli/src/plugins/postcss-hwb-function.ts index d2bb611d1..fd386defd 100644 --- a/cli/csstools-cli/src/plugins/postcss-hwb-function.ts +++ b/cli/csstools-cli/src/plugins/postcss-hwb-function.ts @@ -1,8 +1,8 @@ import plugin from '@csstools/postcss-hwb-function'; import { cli, helpTextLogger } from '@csstools/base-cli'; -export default function postcssHWBFunction(): void { - cli( +export default async function postcssHWBFunction(): Promise { + await cli( plugin, ['preserve'], helpTextLogger( diff --git a/cli/csstools-cli/src/plugins/postcss-ic-unit.ts b/cli/csstools-cli/src/plugins/postcss-ic-unit.ts index f978d51d0..91395da7c 100644 --- a/cli/csstools-cli/src/plugins/postcss-ic-unit.ts +++ b/cli/csstools-cli/src/plugins/postcss-ic-unit.ts @@ -1,8 +1,8 @@ import plugin from '@csstools/postcss-ic-unit'; import { cli, helpTextLogger } from '@csstools/base-cli'; -export default function postcssICUnit(): void { - cli( +export default async function postcssICUnit(): Promise { + await cli( plugin, ['preserve', 'enableProgressiveCustomProperties'], helpTextLogger( diff --git a/cli/csstools-cli/src/plugins/postcss-image-set-function.ts b/cli/csstools-cli/src/plugins/postcss-image-set-function.ts index c250f0f9d..b178f3060 100644 --- a/cli/csstools-cli/src/plugins/postcss-image-set-function.ts +++ b/cli/csstools-cli/src/plugins/postcss-image-set-function.ts @@ -1,8 +1,8 @@ import plugin from 'postcss-image-set-function'; import { cli, helpTextLogger } from '@csstools/base-cli'; -export default function postcssImageSetFunction(): void { - cli( +export default async function postcssImageSetFunction(): Promise { + await cli( plugin, ['oninvalid', 'preserve'], helpTextLogger( diff --git a/cli/csstools-cli/src/plugins/postcss-is-pseudo-class.ts b/cli/csstools-cli/src/plugins/postcss-is-pseudo-class.ts index 885c5ded8..95e7fd16e 100644 --- a/cli/csstools-cli/src/plugins/postcss-is-pseudo-class.ts +++ b/cli/csstools-cli/src/plugins/postcss-is-pseudo-class.ts @@ -1,8 +1,8 @@ import plugin from '@csstools/postcss-is-pseudo-class'; import { cli, helpTextLogger } from '@csstools/base-cli'; -export default function postcssIsPseudoClass(): void { - cli( +export default async function postcssIsPseudoClass(): Promise { + await cli( plugin, ['onComplexSelector', 'preserve', 'specificityMatchingName'], helpTextLogger( diff --git a/cli/csstools-cli/src/plugins/postcss-lab-function.ts b/cli/csstools-cli/src/plugins/postcss-lab-function.ts index 01d6a3d83..1806112b1 100644 --- a/cli/csstools-cli/src/plugins/postcss-lab-function.ts +++ b/cli/csstools-cli/src/plugins/postcss-lab-function.ts @@ -1,8 +1,8 @@ import plugin from 'postcss-lab-function'; import { cli, helpTextLogger } from '@csstools/base-cli'; -export default function postcssLabFunction(): void { - cli( +export default async function postcssLabFunction(): Promise { + await cli( plugin, ['preserve', 'enableProgressiveCustomProperties', 'subFeatures'], helpTextLogger( diff --git a/cli/csstools-cli/src/plugins/postcss-light-dark-function.ts b/cli/csstools-cli/src/plugins/postcss-light-dark-function.ts index b8e9be594..3c18ebc4f 100644 --- a/cli/csstools-cli/src/plugins/postcss-light-dark-function.ts +++ b/cli/csstools-cli/src/plugins/postcss-light-dark-function.ts @@ -1,8 +1,8 @@ import plugin from '@csstools/postcss-light-dark-function'; import { cli, helpTextLogger } from '@csstools/base-cli'; -export default function postcssLightDarkFunction(): void { - cli( +export default async function postcssLightDarkFunction(): Promise { + await cli( plugin, ['preserve'], helpTextLogger( diff --git a/cli/csstools-cli/src/plugins/postcss-logical-float-and-clear.ts b/cli/csstools-cli/src/plugins/postcss-logical-float-and-clear.ts index 851a304b8..bc50b046a 100644 --- a/cli/csstools-cli/src/plugins/postcss-logical-float-and-clear.ts +++ b/cli/csstools-cli/src/plugins/postcss-logical-float-and-clear.ts @@ -1,8 +1,8 @@ import plugin from '@csstools/postcss-logical-float-and-clear'; import { cli, helpTextLogger } from '@csstools/base-cli'; -export default function postcssLogical(): void { - cli( +export default async function postcssLogical(): Promise { + await cli( plugin, ['inlineDirection', 'blockDirection'], helpTextLogger( diff --git a/cli/csstools-cli/src/plugins/postcss-logical-resize.ts b/cli/csstools-cli/src/plugins/postcss-logical-resize.ts index 7d2fd11ab..629629a06 100644 --- a/cli/csstools-cli/src/plugins/postcss-logical-resize.ts +++ b/cli/csstools-cli/src/plugins/postcss-logical-resize.ts @@ -1,8 +1,8 @@ import plugin from '@csstools/postcss-logical-resize'; import { cli, helpTextLogger } from '@csstools/base-cli'; -export default function postcssLogicalResize(): void { - cli( +export default async function postcssLogicalResize(): Promise { + await cli( plugin, ['inlineDirection'], helpTextLogger( diff --git a/cli/csstools-cli/src/plugins/postcss-logical-viewport-units.ts b/cli/csstools-cli/src/plugins/postcss-logical-viewport-units.ts index 64036f585..edd4f0090 100644 --- a/cli/csstools-cli/src/plugins/postcss-logical-viewport-units.ts +++ b/cli/csstools-cli/src/plugins/postcss-logical-viewport-units.ts @@ -1,8 +1,8 @@ import plugin from '@csstools/postcss-logical-viewport-units'; import { cli, helpTextLogger } from '@csstools/base-cli'; -export default function postcssLogicalViewportUnits(): void { - cli( +export default async function postcssLogicalViewportUnits(): Promise { + await cli( plugin, ['inlineDirection', 'preserve'], helpTextLogger( diff --git a/cli/csstools-cli/src/plugins/postcss-logical.ts b/cli/csstools-cli/src/plugins/postcss-logical.ts index ad9624c06..d893da31f 100644 --- a/cli/csstools-cli/src/plugins/postcss-logical.ts +++ b/cli/csstools-cli/src/plugins/postcss-logical.ts @@ -1,8 +1,8 @@ import plugin from 'postcss-logical'; import { cli, helpTextLogger } from '@csstools/base-cli'; -export default function postcssLogical(): void { - cli( +export default async function postcssLogical(): Promise { + await cli( plugin, ['inlineDirection', 'blockDirection'], helpTextLogger( diff --git a/cli/csstools-cli/src/plugins/postcss-media-minmax.ts b/cli/csstools-cli/src/plugins/postcss-media-minmax.ts index eb9bd13a9..60a7d9b9c 100644 --- a/cli/csstools-cli/src/plugins/postcss-media-minmax.ts +++ b/cli/csstools-cli/src/plugins/postcss-media-minmax.ts @@ -1,8 +1,8 @@ import plugin from '@csstools/postcss-media-minmax'; import { cli, helpTextLogger } from '@csstools/base-cli'; -export default function postcssMediaMinMax(): void { - cli( +export default async function postcssMediaMinMax(): Promise { + await cli( plugin, [], helpTextLogger( diff --git a/cli/csstools-cli/src/plugins/postcss-media-queries-aspect-ratio-number-values.ts b/cli/csstools-cli/src/plugins/postcss-media-queries-aspect-ratio-number-values.ts index a20763e33..53040f4e6 100644 --- a/cli/csstools-cli/src/plugins/postcss-media-queries-aspect-ratio-number-values.ts +++ b/cli/csstools-cli/src/plugins/postcss-media-queries-aspect-ratio-number-values.ts @@ -1,8 +1,8 @@ import plugin from '@csstools/postcss-media-queries-aspect-ratio-number-values'; import { cli, helpTextLogger } from '@csstools/base-cli'; -export default function postcssMediaQueriesAspectRatioNumberValues(): void { - cli( +export default async function postcssMediaQueriesAspectRatioNumberValues(): Promise { + await cli( plugin, [], helpTextLogger( diff --git a/cli/csstools-cli/src/plugins/postcss-nested-calc.ts b/cli/csstools-cli/src/plugins/postcss-nested-calc.ts index 7c822a76a..c5bb67675 100644 --- a/cli/csstools-cli/src/plugins/postcss-nested-calc.ts +++ b/cli/csstools-cli/src/plugins/postcss-nested-calc.ts @@ -1,8 +1,8 @@ import plugin from '@csstools/postcss-nested-calc'; import { cli, helpTextLogger } from '@csstools/base-cli'; -export default function postcssNestedCalc(): void { - cli( +export default async function postcssNestedCalc(): Promise { + await cli( plugin, ['preserve'], helpTextLogger( diff --git a/cli/csstools-cli/src/plugins/postcss-nesting.ts b/cli/csstools-cli/src/plugins/postcss-nesting.ts index 1a45dfa04..bae9be449 100644 --- a/cli/csstools-cli/src/plugins/postcss-nesting.ts +++ b/cli/csstools-cli/src/plugins/postcss-nesting.ts @@ -1,8 +1,8 @@ import plugin from 'postcss-nesting'; import { cli, helpTextLogger } from '@csstools/base-cli'; -export default function postcssNesting(): void { - cli( +export default async function postcssNesting(): Promise { + await cli( plugin, ['noIsPseudoSelector'], helpTextLogger( diff --git a/cli/csstools-cli/src/plugins/postcss-normalize-display-values.ts b/cli/csstools-cli/src/plugins/postcss-normalize-display-values.ts index 72c1d015e..93113d95a 100644 --- a/cli/csstools-cli/src/plugins/postcss-normalize-display-values.ts +++ b/cli/csstools-cli/src/plugins/postcss-normalize-display-values.ts @@ -1,8 +1,8 @@ import plugin from '@csstools/postcss-normalize-display-values'; import { cli, helpTextLogger } from '@csstools/base-cli'; -export default function postcssNormalizeDisplayValues(): void { - cli( +export default async function postcssNormalizeDisplayValues(): Promise { + await cli( plugin, ['preserve'], helpTextLogger( diff --git a/cli/csstools-cli/src/plugins/postcss-oklab-function.ts b/cli/csstools-cli/src/plugins/postcss-oklab-function.ts index e533b3792..2f66809a6 100644 --- a/cli/csstools-cli/src/plugins/postcss-oklab-function.ts +++ b/cli/csstools-cli/src/plugins/postcss-oklab-function.ts @@ -1,8 +1,8 @@ import plugin from '@csstools/postcss-oklab-function'; import { cli, helpTextLogger } from '@csstools/base-cli'; -export default function postcssOKLabFunction(): void { - cli( +export default async function postcssOKLabFunction(): Promise { + await cli( plugin, ['preserve', 'enableProgressiveCustomProperties', 'subFeatures'], helpTextLogger( diff --git a/cli/csstools-cli/src/plugins/postcss-overflow-shorthand.ts b/cli/csstools-cli/src/plugins/postcss-overflow-shorthand.ts index efb2db881..3a8830ca7 100644 --- a/cli/csstools-cli/src/plugins/postcss-overflow-shorthand.ts +++ b/cli/csstools-cli/src/plugins/postcss-overflow-shorthand.ts @@ -1,8 +1,8 @@ import plugin from 'postcss-overflow-shorthand'; import { cli, helpTextLogger } from '@csstools/base-cli'; -export default function postcssOverflowShorthand(): void { - cli( +export default async function postcssOverflowShorthand(): Promise { + await cli( plugin, ['preserve'], helpTextLogger( diff --git a/cli/csstools-cli/src/plugins/postcss-place.ts b/cli/csstools-cli/src/plugins/postcss-place.ts index 2b1f0c8c5..2d52f646f 100644 --- a/cli/csstools-cli/src/plugins/postcss-place.ts +++ b/cli/csstools-cli/src/plugins/postcss-place.ts @@ -1,8 +1,8 @@ import plugin from 'postcss-place'; import { cli, helpTextLogger } from '@csstools/base-cli'; -export default function postcssPlace(): void { - cli( +export default async function postcssPlace(): Promise { + await cli( plugin, ['preserve'], helpTextLogger( diff --git a/cli/csstools-cli/src/plugins/postcss-preset-env.ts b/cli/csstools-cli/src/plugins/postcss-preset-env.ts index 420db8f49..5d1b88576 100644 --- a/cli/csstools-cli/src/plugins/postcss-preset-env.ts +++ b/cli/csstools-cli/src/plugins/postcss-preset-env.ts @@ -1,8 +1,8 @@ import plugin from 'postcss-preset-env'; import { cli, helpTextLogger } from '@csstools/base-cli'; -export default function postcssPresetEnv(): void { - cli( +export default async function postcssPresetEnv(): Promise { + await cli( plugin, [ 'stage', diff --git a/cli/csstools-cli/src/plugins/postcss-pseudo-class-any-link.ts b/cli/csstools-cli/src/plugins/postcss-pseudo-class-any-link.ts index dfd97785c..9430eac36 100644 --- a/cli/csstools-cli/src/plugins/postcss-pseudo-class-any-link.ts +++ b/cli/csstools-cli/src/plugins/postcss-pseudo-class-any-link.ts @@ -1,8 +1,8 @@ import plugin from 'postcss-pseudo-class-any-link'; import { cli, helpTextLogger } from '@csstools/base-cli'; -export default function postcssPseudoClassAnyLink(): void { - cli( +export default async function postcssPseudoClassAnyLink(): Promise { + await cli( plugin, ['preserve'], helpTextLogger( diff --git a/cli/csstools-cli/src/plugins/postcss-relative-color-syntax.ts b/cli/csstools-cli/src/plugins/postcss-relative-color-syntax.ts index 0aeb839d1..bf58c01ab 100644 --- a/cli/csstools-cli/src/plugins/postcss-relative-color-syntax.ts +++ b/cli/csstools-cli/src/plugins/postcss-relative-color-syntax.ts @@ -1,8 +1,8 @@ import plugin from '@csstools/postcss-relative-color-syntax'; import { cli, helpTextLogger } from '@csstools/base-cli'; -export default function postcssRelativeColorSyntax(): void { - cli( +export default async function postcssRelativeColorSyntax(): Promise { + await cli( plugin, ['preserve', 'enableProgressiveCustomProperties', 'subFeatures'], helpTextLogger( diff --git a/cli/csstools-cli/src/plugins/postcss-scope-pseudo-class.ts b/cli/csstools-cli/src/plugins/postcss-scope-pseudo-class.ts index b5e51d212..df8a2f40f 100644 --- a/cli/csstools-cli/src/plugins/postcss-scope-pseudo-class.ts +++ b/cli/csstools-cli/src/plugins/postcss-scope-pseudo-class.ts @@ -1,8 +1,8 @@ import plugin from '@csstools/postcss-scope-pseudo-class'; import { cli, helpTextLogger } from '@csstools/base-cli'; -export default function postcssScopePseudoClass(): void { - cli( +export default async function postcssScopePseudoClass(): Promise { + await cli( plugin, ['preserve'], helpTextLogger( diff --git a/cli/csstools-cli/src/plugins/postcss-selector-not.ts b/cli/csstools-cli/src/plugins/postcss-selector-not.ts index fd6dd3665..679159903 100644 --- a/cli/csstools-cli/src/plugins/postcss-selector-not.ts +++ b/cli/csstools-cli/src/plugins/postcss-selector-not.ts @@ -1,8 +1,8 @@ import plugin from 'postcss-selector-not'; import { cli, helpTextLogger } from '@csstools/base-cli'; -export default function postcssSelectorNot(): void { - cli( +export default async function postcssSelectorNot(): Promise { + await cli( plugin, [], helpTextLogger( diff --git a/cli/csstools-cli/src/plugins/postcss-stepped-value-functions.ts b/cli/csstools-cli/src/plugins/postcss-stepped-value-functions.ts index 5c12d1985..4440fc6ac 100644 --- a/cli/csstools-cli/src/plugins/postcss-stepped-value-functions.ts +++ b/cli/csstools-cli/src/plugins/postcss-stepped-value-functions.ts @@ -1,8 +1,8 @@ import plugin from '@csstools/postcss-stepped-value-functions'; import { cli, helpTextLogger } from '@csstools/base-cli'; -export default function postcssSteppedValueFunctions(): void { - cli( +export default async function postcssSteppedValueFunctions(): Promise { + await cli( plugin, ['preserve', 'onInvalid'], helpTextLogger( diff --git a/cli/csstools-cli/src/plugins/postcss-text-decoration-shorthand.ts b/cli/csstools-cli/src/plugins/postcss-text-decoration-shorthand.ts index 6d435c270..0289cf193 100644 --- a/cli/csstools-cli/src/plugins/postcss-text-decoration-shorthand.ts +++ b/cli/csstools-cli/src/plugins/postcss-text-decoration-shorthand.ts @@ -1,8 +1,8 @@ import plugin from '@csstools/postcss-text-decoration-shorthand'; import { cli, helpTextLogger } from '@csstools/base-cli'; -export default function postcssTextDecorationShorthand(): void { - cli( +export default async function postcssTextDecorationShorthand(): Promise { + await cli( plugin, ['preserve'], helpTextLogger( diff --git a/cli/csstools-cli/src/plugins/postcss-trigonometric-functions.ts b/cli/csstools-cli/src/plugins/postcss-trigonometric-functions.ts index 95da599de..da8f40a12 100644 --- a/cli/csstools-cli/src/plugins/postcss-trigonometric-functions.ts +++ b/cli/csstools-cli/src/plugins/postcss-trigonometric-functions.ts @@ -1,8 +1,8 @@ import plugin from '@csstools/postcss-trigonometric-functions'; import { cli, helpTextLogger } from '@csstools/base-cli'; -export default function postcssTrigonometricFunctions(): void { - cli( +export default async function postcssTrigonometricFunctions(): Promise { + await cli( plugin, ['preserve'], helpTextLogger( diff --git a/cli/csstools-cli/src/plugins/postcss-unset-value.ts b/cli/csstools-cli/src/plugins/postcss-unset-value.ts index 60d0d774f..ab57d8388 100644 --- a/cli/csstools-cli/src/plugins/postcss-unset-value.ts +++ b/cli/csstools-cli/src/plugins/postcss-unset-value.ts @@ -1,8 +1,8 @@ import plugin from '@csstools/postcss-unset-value'; import { cli, helpTextLogger } from '@csstools/base-cli'; -export default function postcssUnsetValue(): void { - cli( +export default async function postcssUnsetValue(): Promise { + await cli( plugin, ['preserve'], helpTextLogger( diff --git a/eslint.config.mjs b/eslint.config.mjs new file mode 100644 index 000000000..69f4b3aa0 --- /dev/null +++ b/eslint.config.mjs @@ -0,0 +1,100 @@ +import js from '@eslint/js'; +import globals from 'globals'; +import tseslint from 'typescript-eslint'; + +export default [ + js.configs.recommended, + { + ignores: [ + '**/dist/*', + 'sites/**', + 'e2e/**', + ], + }, + ...tseslint.configs.recommendedTypeChecked.map((config) => { + return { + ...config, + files: [ + '**/*.ts', + '**/*.cts', + '**/*.mts', + ], + }; + }), + { + files: [ + '**/*.js', + '**/*.cjs', + '**/*.mjs', + ], + + languageOptions: { + globals: { + ...globals.node, + }, + ecmaVersion: 2022, + sourceType: 'module', + }, + + rules: { + quotes: ['error', 'single'], + 'comma-dangle': ['error', 'always-multiline'], + semi: ['error', 'always'], + curly: 'error', + 'brace-style': 'error', + + indent: ['error', 'tab', { + SwitchCase: 1, + }], + + radix: 'error', + 'space-in-parens': ['error', 'never'], + + 'no-empty': ['error', { + 'allowEmptyCatch': true, + }], + }, + }, + { + files: [ + '**/src/browser.js', + '**/src/browser-global.js', + ], + languageOptions: { + globals: { + ...globals.browser, + }, + ecmaVersion: 2022, + sourceType: 'module', + }, + rules: { + 'no-unused-vars': ['error', { 'caughtErrorsIgnorePattern': '_' }], + 'no-constant-condition': 'off', + }, + }, + { + files: [ + '**/*.ts', + '**/*.cts', + '**/*.mts', + ], + languageOptions: { + parserOptions: { + projectService: true, + tsconfigRootDir: import.meta.dirname, + }, + }, + rules: { + 'no-shadow': 'off', + '@typescript-eslint/no-shadow': 'error', + + '@typescript-eslint/array-type': ['error', { + default: 'generic', + }], + + '@typescript-eslint/explicit-function-return-type': 'error', + '@typescript-eslint/no-base-to-string': 'off', + '@typescript-eslint/no-non-null-assertion': 'error', + }, + }, +]; diff --git a/experimental/css-has-pseudo/dist/browser-global.js.map b/experimental/css-has-pseudo/dist/browser-global.js.map index 868d43567..cdbe287d8 100644 --- a/experimental/css-has-pseudo/dist/browser-global.js.map +++ b/experimental/css-has-pseudo/dist/browser-global.js.map @@ -1 +1 @@ -{"version":3,"file":"browser-global.js","sources":["../src/browser-global.js","../src/browser.js"],"sourcesContent":["/* global self */\nimport { default as cssHasPseudo } from './browser';\nself.cssHasPseudo = cssHasPseudo;\n","export default function cssHasPseudo() {\n\tconsole.log('\"@csstools/css-has-pseudo-experimental\" is no longer supported. Please use \"css-has-pseudo\" instead.');\n}\n"],"names":["self","cssHasPseudo","console","log"],"mappings":"AAEAA,KAAKC,aCFU,SAASA,eACvBC,QAAQC,IAAI,uGACb"} \ No newline at end of file +{"version":3,"file":"browser-global.js","sources":["../src/browser-global.js","../src/browser.js"],"sourcesContent":["import { default as cssHasPseudo } from './browser';\nself.cssHasPseudo = cssHasPseudo;\n","export default function cssHasPseudo() {\n\tconsole.log('\"@csstools/css-has-pseudo-experimental\" is no longer supported. Please use \"css-has-pseudo\" instead.');\n}\n"],"names":["self","cssHasPseudo","console","log"],"mappings":"AACAA,KAAKC,aCDU,SAASA,eACvBC,QAAQC,IAAI,uGACb"} \ No newline at end of file diff --git a/experimental/css-has-pseudo/src/browser-global.js b/experimental/css-has-pseudo/src/browser-global.js index c2abec111..addc6a1b9 100644 --- a/experimental/css-has-pseudo/src/browser-global.js +++ b/experimental/css-has-pseudo/src/browser-global.js @@ -1,3 +1,2 @@ -/* global self */ import { default as cssHasPseudo } from './browser'; self.cssHasPseudo = cssHasPseudo; diff --git a/experimental/postcss-nesting/dist/index.cjs b/experimental/postcss-nesting/dist/index.cjs index 323956326..c5ff7c519 100644 --- a/experimental/postcss-nesting/dist/index.cjs +++ b/experimental/postcss-nesting/dist/index.cjs @@ -1 +1 @@ -"use strict";var e=require("postcss-selector-parser");function ampersandToScope(t,n){let r,o=t.parent;for(;o;){if("rule"===o.type)return;o=o.parent}try{r=e().astSync(t.selector)}catch(e){return void t.warn(n,`Failed to parse selector : "${t.selector}" with message: "${e.message}"`)}r&&(r.walkNesting((t=>{"root"===t.parent?.parent?.type?t.replaceWith(e.pseudo({value:":scope"})):t.replaceWith(e.pseudo({value:":is",nodes:[e.pseudo({value:":root"}),e.pseudo({value:":host"})]}))})),t.selector=r.toString())}function cleanupParent(e){if(!e.nodes.length)return void e.remove();const t=e.nodes.filter((e=>"comment"===e.type));t.length===e.nodes.length&&e.replaceWith(...t)}function shiftNodesBeforeParent(e,t){const n=t.index(e);if(n){const e=t.cloneBefore().removeAll().append(t.nodes.slice(0,n));e.raws.semicolon=!0,cleanupParent(e)}t.before(e),t.raws.semicolon=!0}function mergeSelectors(t,n,r,o){const s=[];if(0===o.length)return;const i=e().astSync(`:is(${r.join(",")})`);for(let r=0;r{"nesting"===e.type&&(a=!0)})),!a){const s=l.nodes[0];let i=!1;if(s.each((e=>"combinator"===e.type&&(i=!0,!1))),0===r){let e=!1;s.each((t=>"tag"===t.type&&(e=!0,!1))),e&&t.warn(n,`Invalid nested rule : "${o[r]}"`)}i||s.insertBefore(s.at(0),e.combinator({value:" "})),s.insertBefore(s.at(0),e.nesting({}))}l.walk((e=>{"nesting"===e.type&&e.replaceWith(i.clone({}))})),s.push(l.toString())}return s}function groupDeclarations(e){let t=-1;e.each(((n,r)=>{if("decl"===n.type){if(-1===t)return void(t=r);if(t===r-1)return void(t=r);n.remove(),e.insertAfter(t,n),t=e.index(n)}}))}function transformRuleWithinRule(e,t,n){let r=[];try{r=mergeSelectors(e,n,t.selectors,e.selectors)}catch(r){return void e.warn(n,`Failed to transform selectors : "${t.selector}" / "${e.selector}" with message: "${r.message}"`)}groupDeclarations(t),shiftNodesBeforeParent(e,t),e.selectors=r;"rule"===e.type&&"rule"===t.type&&e.selector===t.selector&&e.append(...t.nodes),cleanupParent(t)}var t=["container","document","media","supports","layer"];function atruleWithinRule(e,t,n,r){if(groupDeclarations(t),shiftNodesBeforeParent(e,t),e.nodes){const o=t.clone().removeAll().append(e.nodes);e.append(o),cleanupParent(t),r(o,n)}}function isAtruleWithinRule(e){return t.includes(e.name)}function comma(e){const t=[];let n="",r=!1,o=0,s=!1,i=!1;for(const l of e)i?i=!1:"\\"===l?i=!0:s?l===s&&(s=!1):'"'===l||"'"===l?s=l:"("===l?o+=1:")"===l?o>0&&(o-=1):0===o&&","===l&&(r=!0),r?(""!==n&&t.push(n.trim()),n="",r=!1):n+=l;return t.push(n.trim()),t}function transformAtruleWithinAtrule(e,t){var n,r;groupDeclarations(t),shiftNodesBeforeParent(e,t),e.params=(n=t.params,r=e.params,comma(n).map((e=>comma(r).map((t=>`${e} and ${t}`)).join(", "))).join(", ")),cleanupParent(t)}function isAtruleWithinAtrule(e,n){return t.includes(e.name)&&e.name===n.name}function isAtRule(e){return e&&"atrule"===e.type}function isRule(e){return e&&"rule"===e.type}function walk(e,t){e.each((e=>{const n=e.parent;isRule(e)&&e.selector.trim()&&isRule(n)&&n.selector.trim()?transformRuleWithinRule(e,n,t):isAtRule(e)&&isRule(n)&&n.selector.trim()&&isAtruleWithinRule(e)?atruleWithinRule(e,n,t,walk):isAtRule(e)&&isAtRule(n)&&isAtruleWithinAtrule(e,n)&&transformAtruleWithinAtrule(e,n),"nodes"in e&&e.nodes.length&&walk(e,t)}))}const creator=()=>({postcssPlugin:"postcss-nesting",Rule(e,{result:t}){walk(e,t),e.selector.trim().includes("&")&&ersandToScope(e,t)}});creator.postcss=!0,module.exports=creator; +"use strict";var e=require("postcss-selector-parser");function ampersandToScope(t,n){let r,o=t.parent;for(;o;){if("rule"===o.type)return;o=o.parent}try{r=e().astSync(t.selector)}catch(e){if(!(e instanceof Error))throw e;return void t.warn(n,`Failed to parse selector : "${t.selector}" with message: "${e.message}"`)}r&&(r.walkNesting((t=>{"root"===t.parent?.parent?.type?t.replaceWith(e.pseudo({value:":scope"})):t.replaceWith(e.pseudo({value:":is",nodes:[e.pseudo({value:":root"}),e.pseudo({value:":host"})]}))})),t.selector=r.toString())}function cleanupParent(e){if(!e.nodes.length)return void e.remove();const t=e.nodes.filter((e=>"comment"===e.type));t.length===e.nodes.length&&e.replaceWith(...t)}function shiftNodesBeforeParent(e,t){const n=t.index(e);if(n){const e=t.cloneBefore().removeAll().append(t.nodes.slice(0,n));e.raws.semicolon=!0,cleanupParent(e)}t.before(e),t.raws.semicolon=!0}function mergeSelectors(t,n,r,o){const s=[];if(0===o.length)return;const i=e().astSync(`:is(${r.join(",")})`);for(let r=0;r{"nesting"===e.type&&(a=!0)})),!a){const s=l.nodes[0];let i=!1;if(s.each((e=>"combinator"===e.type&&(i=!0,!1))),0===r){let e=!1;s.each((t=>"tag"===t.type&&(e=!0,!1))),e&&t.warn(n,`Invalid nested rule : "${o[r]}"`)}i||s.insertBefore(s.at(0),e.combinator({value:" "})),s.insertBefore(s.at(0),e.nesting({}))}l.walk((e=>{"nesting"===e.type&&e.replaceWith(i.clone({}))})),s.push(l.toString())}return s}function groupDeclarations(e){let t=-1;e.each(((n,r)=>{if("decl"===n.type){if(-1===t)return void(t=r);if(t===r-1)return void(t=r);n.remove(),e.insertAfter(t,n),t=e.index(n)}}))}function transformRuleWithinRule(e,t,n){let r=[];try{r=mergeSelectors(e,n,t.selectors,e.selectors)}catch(r){if(!(r instanceof Error))throw r;return void e.warn(n,`Failed to transform selectors : "${t.selector}" / "${e.selector}" with message: "${r.message}"`)}groupDeclarations(t),shiftNodesBeforeParent(e,t),e.selectors=r;"rule"===e.type&&"rule"===t.type&&e.selector===t.selector&&e.append(...t.nodes),cleanupParent(t)}var t=["container","document","media","supports","layer"];function atruleWithinRule(e,t,n,r){if(groupDeclarations(t),shiftNodesBeforeParent(e,t),e.nodes){const o=t.clone().removeAll().append(e.nodes);e.append(o),cleanupParent(t),r(o,n)}}function isAtruleWithinRule(e){return t.includes(e.name)}function comma(e){const t=[];let n="",r=!1,o=0,s=!1,i=!1;for(const l of e)i?i=!1:"\\"===l?i=!0:s?l===s&&(s=!1):'"'===l||"'"===l?s=l:"("===l?o+=1:")"===l?o>0&&(o-=1):0===o&&","===l&&(r=!0),r?(""!==n&&t.push(n.trim()),n="",r=!1):n+=l;return t.push(n.trim()),t}function transformAtruleWithinAtrule(e,t){var n,r;groupDeclarations(t),shiftNodesBeforeParent(e,t),e.params=(n=t.params,r=e.params,comma(n).map((e=>comma(r).map((t=>`${e} and ${t}`)).join(", "))).join(", ")),cleanupParent(t)}function isAtruleWithinAtrule(e,n){return t.includes(e.name)&&e.name===n.name}function isAtRule(e){return e&&"atrule"===e.type}function isRule(e){return e&&"rule"===e.type}function walk(e,t){e.each((e=>{const n=e.parent;isRule(e)&&e.selector.trim()&&isRule(n)&&n.selector.trim()?transformRuleWithinRule(e,n,t):isAtRule(e)&&isRule(n)&&n.selector.trim()&&isAtruleWithinRule(e)?atruleWithinRule(e,n,t,walk):isAtRule(e)&&isAtRule(n)&&isAtruleWithinAtrule(e,n)&&transformAtruleWithinAtrule(e,n),"nodes"in e&&e.nodes.length&&walk(e,t)}))}const creator=()=>({postcssPlugin:"postcss-nesting",Rule(e,{result:t}){walk(e,t),e.selector.trim().includes("&")&&ersandToScope(e,t)}});creator.postcss=!0,module.exports=creator; diff --git a/experimental/postcss-nesting/dist/index.mjs b/experimental/postcss-nesting/dist/index.mjs index ebd787d73..8244c7578 100644 --- a/experimental/postcss-nesting/dist/index.mjs +++ b/experimental/postcss-nesting/dist/index.mjs @@ -1 +1 @@ -import e from"postcss-selector-parser";function ampersandToScope(t,n){let r,o=t.parent;for(;o;){if("rule"===o.type)return;o=o.parent}try{r=e().astSync(t.selector)}catch(e){return void t.warn(n,`Failed to parse selector : "${t.selector}" with message: "${e.message}"`)}r&&(r.walkNesting((t=>{"root"===t.parent?.parent?.type?t.replaceWith(e.pseudo({value:":scope"})):t.replaceWith(e.pseudo({value:":is",nodes:[e.pseudo({value:":root"}),e.pseudo({value:":host"})]}))})),t.selector=r.toString())}function cleanupParent(e){if(!e.nodes.length)return void e.remove();const t=e.nodes.filter((e=>"comment"===e.type));t.length===e.nodes.length&&e.replaceWith(...t)}function shiftNodesBeforeParent(e,t){const n=t.index(e);if(n){const e=t.cloneBefore().removeAll().append(t.nodes.slice(0,n));e.raws.semicolon=!0,cleanupParent(e)}t.before(e),t.raws.semicolon=!0}function mergeSelectors(t,n,r,o){const s=[];if(0===o.length)return;const i=e().astSync(`:is(${r.join(",")})`);for(let r=0;r{"nesting"===e.type&&(a=!0)})),!a){const s=l.nodes[0];let i=!1;if(s.each((e=>"combinator"===e.type&&(i=!0,!1))),0===r){let e=!1;s.each((t=>"tag"===t.type&&(e=!0,!1))),e&&t.warn(n,`Invalid nested rule : "${o[r]}"`)}i||s.insertBefore(s.at(0),e.combinator({value:" "})),s.insertBefore(s.at(0),e.nesting({}))}l.walk((e=>{"nesting"===e.type&&e.replaceWith(i.clone({}))})),s.push(l.toString())}return s}function groupDeclarations(e){let t=-1;e.each(((n,r)=>{if("decl"===n.type){if(-1===t)return void(t=r);if(t===r-1)return void(t=r);n.remove(),e.insertAfter(t,n),t=e.index(n)}}))}function transformRuleWithinRule(e,t,n){let r=[];try{r=mergeSelectors(e,n,t.selectors,e.selectors)}catch(r){return void e.warn(n,`Failed to transform selectors : "${t.selector}" / "${e.selector}" with message: "${r.message}"`)}groupDeclarations(t),shiftNodesBeforeParent(e,t),e.selectors=r;"rule"===e.type&&"rule"===t.type&&e.selector===t.selector&&e.append(...t.nodes),cleanupParent(t)}var t=["container","document","media","supports","layer"];function atruleWithinRule(e,t,n,r){if(groupDeclarations(t),shiftNodesBeforeParent(e,t),e.nodes){const o=t.clone().removeAll().append(e.nodes);e.append(o),cleanupParent(t),r(o,n)}}function isAtruleWithinRule(e){return t.includes(e.name)}function comma(e){const t=[];let n="",r=!1,o=0,s=!1,i=!1;for(const l of e)i?i=!1:"\\"===l?i=!0:s?l===s&&(s=!1):'"'===l||"'"===l?s=l:"("===l?o+=1:")"===l?o>0&&(o-=1):0===o&&","===l&&(r=!0),r?(""!==n&&t.push(n.trim()),n="",r=!1):n+=l;return t.push(n.trim()),t}function transformAtruleWithinAtrule(e,t){var n,r;groupDeclarations(t),shiftNodesBeforeParent(e,t),e.params=(n=t.params,r=e.params,comma(n).map((e=>comma(r).map((t=>`${e} and ${t}`)).join(", "))).join(", ")),cleanupParent(t)}function isAtruleWithinAtrule(e,n){return t.includes(e.name)&&e.name===n.name}function isAtRule(e){return e&&"atrule"===e.type}function isRule(e){return e&&"rule"===e.type}function walk(e,t){e.each((e=>{const n=e.parent;isRule(e)&&e.selector.trim()&&isRule(n)&&n.selector.trim()?transformRuleWithinRule(e,n,t):isAtRule(e)&&isRule(n)&&n.selector.trim()&&isAtruleWithinRule(e)?atruleWithinRule(e,n,t,walk):isAtRule(e)&&isAtRule(n)&&isAtruleWithinAtrule(e,n)&&transformAtruleWithinAtrule(e,n),"nodes"in e&&e.nodes.length&&walk(e,t)}))}const creator=()=>({postcssPlugin:"postcss-nesting",Rule(e,{result:t}){walk(e,t),e.selector.trim().includes("&")&&ersandToScope(e,t)}});creator.postcss=!0;export{creator as default}; +import e from"postcss-selector-parser";function ampersandToScope(t,n){let r,o=t.parent;for(;o;){if("rule"===o.type)return;o=o.parent}try{r=e().astSync(t.selector)}catch(e){if(!(e instanceof Error))throw e;return void t.warn(n,`Failed to parse selector : "${t.selector}" with message: "${e.message}"`)}r&&(r.walkNesting((t=>{"root"===t.parent?.parent?.type?t.replaceWith(e.pseudo({value:":scope"})):t.replaceWith(e.pseudo({value:":is",nodes:[e.pseudo({value:":root"}),e.pseudo({value:":host"})]}))})),t.selector=r.toString())}function cleanupParent(e){if(!e.nodes.length)return void e.remove();const t=e.nodes.filter((e=>"comment"===e.type));t.length===e.nodes.length&&e.replaceWith(...t)}function shiftNodesBeforeParent(e,t){const n=t.index(e);if(n){const e=t.cloneBefore().removeAll().append(t.nodes.slice(0,n));e.raws.semicolon=!0,cleanupParent(e)}t.before(e),t.raws.semicolon=!0}function mergeSelectors(t,n,r,o){const s=[];if(0===o.length)return;const i=e().astSync(`:is(${r.join(",")})`);for(let r=0;r{"nesting"===e.type&&(a=!0)})),!a){const s=l.nodes[0];let i=!1;if(s.each((e=>"combinator"===e.type&&(i=!0,!1))),0===r){let e=!1;s.each((t=>"tag"===t.type&&(e=!0,!1))),e&&t.warn(n,`Invalid nested rule : "${o[r]}"`)}i||s.insertBefore(s.at(0),e.combinator({value:" "})),s.insertBefore(s.at(0),e.nesting({}))}l.walk((e=>{"nesting"===e.type&&e.replaceWith(i.clone({}))})),s.push(l.toString())}return s}function groupDeclarations(e){let t=-1;e.each(((n,r)=>{if("decl"===n.type){if(-1===t)return void(t=r);if(t===r-1)return void(t=r);n.remove(),e.insertAfter(t,n),t=e.index(n)}}))}function transformRuleWithinRule(e,t,n){let r=[];try{r=mergeSelectors(e,n,t.selectors,e.selectors)}catch(r){if(!(r instanceof Error))throw r;return void e.warn(n,`Failed to transform selectors : "${t.selector}" / "${e.selector}" with message: "${r.message}"`)}groupDeclarations(t),shiftNodesBeforeParent(e,t),e.selectors=r;"rule"===e.type&&"rule"===t.type&&e.selector===t.selector&&e.append(...t.nodes),cleanupParent(t)}var t=["container","document","media","supports","layer"];function atruleWithinRule(e,t,n,r){if(groupDeclarations(t),shiftNodesBeforeParent(e,t),e.nodes){const o=t.clone().removeAll().append(e.nodes);e.append(o),cleanupParent(t),r(o,n)}}function isAtruleWithinRule(e){return t.includes(e.name)}function comma(e){const t=[];let n="",r=!1,o=0,s=!1,i=!1;for(const l of e)i?i=!1:"\\"===l?i=!0:s?l===s&&(s=!1):'"'===l||"'"===l?s=l:"("===l?o+=1:")"===l?o>0&&(o-=1):0===o&&","===l&&(r=!0),r?(""!==n&&t.push(n.trim()),n="",r=!1):n+=l;return t.push(n.trim()),t}function transformAtruleWithinAtrule(e,t){var n,r;groupDeclarations(t),shiftNodesBeforeParent(e,t),e.params=(n=t.params,r=e.params,comma(n).map((e=>comma(r).map((t=>`${e} and ${t}`)).join(", "))).join(", ")),cleanupParent(t)}function isAtruleWithinAtrule(e,n){return t.includes(e.name)&&e.name===n.name}function isAtRule(e){return e&&"atrule"===e.type}function isRule(e){return e&&"rule"===e.type}function walk(e,t){e.each((e=>{const n=e.parent;isRule(e)&&e.selector.trim()&&isRule(n)&&n.selector.trim()?transformRuleWithinRule(e,n,t):isAtRule(e)&&isRule(n)&&n.selector.trim()&&isAtruleWithinRule(e)?atruleWithinRule(e,n,t,walk):isAtRule(e)&&isAtRule(n)&&isAtruleWithinAtrule(e,n)&&transformAtruleWithinAtrule(e,n),"nodes"in e&&e.nodes.length&&walk(e,t)}))}const creator=()=>({postcssPlugin:"postcss-nesting",Rule(e,{result:t}){walk(e,t),e.selector.trim().includes("&")&&ersandToScope(e,t)}});creator.postcss=!0;export{creator as default}; diff --git a/experimental/postcss-nesting/src/lib/ampersand-to-scope.ts b/experimental/postcss-nesting/src/lib/ampersand-to-scope.ts index 6376c88dd..c4efc52e7 100644 --- a/experimental/postcss-nesting/src/lib/ampersand-to-scope.ts +++ b/experimental/postcss-nesting/src/lib/ampersand-to-scope.ts @@ -16,6 +16,10 @@ export default function ampersandToScope(rule: Rule, result: Result): void { try { selectorAST = parser().astSync(rule.selector); } catch (err) { + if (!(err instanceof Error)) { + throw err; + } + rule.warn(result, `Failed to parse selector : "${rule.selector}" with message: "${err.message}"`); return; } diff --git a/experimental/postcss-nesting/src/lib/merge-selectors/merge-selectors.ts b/experimental/postcss-nesting/src/lib/merge-selectors/merge-selectors.ts index a34309793..90f584bb6 100644 --- a/experimental/postcss-nesting/src/lib/merge-selectors/merge-selectors.ts +++ b/experimental/postcss-nesting/src/lib/merge-selectors/merge-selectors.ts @@ -2,7 +2,7 @@ import type { Node, Result } from 'postcss'; import parser from 'postcss-selector-parser'; export default function mergeSelectors(node: Node, postcssResult: Result, fromSelectors: Array, toSelectors: Array): Array { - const result = []; + const result: Array = []; if (toSelectors.length === 0) { return; } @@ -51,9 +51,11 @@ export default function mergeSelectors(node: Node, postcssResult: Result, fromSe } if (startsWithCombinator) { - selectorAST.insertBefore(selectorAST.at(0) , parser.nesting({})); + // eslint-disable-next-line @typescript-eslint/no-unsafe-argument + selectorAST.insertBefore(selectorAST.at(0), parser.nesting({})); } else { selectorAST.insertBefore(selectorAST.at(0), parser.combinator({value: ' '})); + // eslint-disable-next-line @typescript-eslint/no-unsafe-argument selectorAST.insertBefore(selectorAST.at(0), parser.nesting({})); } } diff --git a/experimental/postcss-nesting/src/lib/rule-within-rule.ts b/experimental/postcss-nesting/src/lib/rule-within-rule.ts index c7aeaea77..6169ea90c 100644 --- a/experimental/postcss-nesting/src/lib/rule-within-rule.ts +++ b/experimental/postcss-nesting/src/lib/rule-within-rule.ts @@ -5,11 +5,15 @@ import type { Result, Rule } from 'postcss'; import groupDeclarations from './group-declarations.js'; export default function transformRuleWithinRule(node: Rule, parent: Rule, result: Result): void { - let selectors = []; + let selectors: Array = []; try { selectors = mergeSelectors(node, result, parent.selectors, node.selectors); } catch (err) { + if (!(err instanceof Error)) { + throw err; + } + node.warn(result, `Failed to transform selectors : "${parent.selector}" / "${node.selector}" with message: "${err.message}"`); return; } diff --git a/experimental/postcss-nesting/src/lib/shift-nodes-before-parent.ts b/experimental/postcss-nesting/src/lib/shift-nodes-before-parent.ts index 745fa0a29..4a9f484d0 100644 --- a/experimental/postcss-nesting/src/lib/shift-nodes-before-parent.ts +++ b/experimental/postcss-nesting/src/lib/shift-nodes-before-parent.ts @@ -7,11 +7,13 @@ export default function shiftNodesBeforeParent(node: ChildNode, parent: Containe // conditionally move previous siblings into a clone of the parent if (index) { const newParent = parent.cloneBefore().removeAll().append(parent.nodes.slice(0, index)); + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access newParent.raws.semicolon = true; /* nested rules end with "}" and do not have this flag set */ cleanupParent(newParent); } // move the current node before the parent (and after the conditional clone) parent.before(node); + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access parent.raws.semicolon = true; /* nested rules end with "}" and do not have this flag set */ } diff --git a/knip.json b/knip.json index a1c674a8d..bbb8659f0 100644 --- a/knip.json +++ b/knip.json @@ -4,7 +4,8 @@ ".": { "entry": [ ".github/bin/**/*.mjs", - "rollup/**/*.mjs" + "rollup/**/*.mjs", + "eslint.config.mjs" ] }, "packages/*": { diff --git a/package-lock.json b/package-lock.json index e6d5e171a..7f203badf 100644 --- a/package-lock.json +++ b/package-lock.json @@ -28,6 +28,7 @@ "devDependencies": { "@babel/core": "^7.24.7", "@babel/preset-env": "^7.24.7", + "@eslint/js": "^9.5.0", "@microsoft/api-documenter": "^7.25.3", "@microsoft/api-extractor": "^7.47.0", "@rollup/plugin-babel": "^6.0.3", @@ -36,13 +37,13 @@ "@rollup/plugin-terser": "^0.4.3", "@rollup/plugin-typescript": "^11.1.6", "@stryker-mutator/core": "^8.2.6", - "@typescript-eslint/eslint-plugin": "^7.13.0", - "@typescript-eslint/parser": "^7.13.0", - "eslint": "^8.57.0", + "eslint": "^9.5.0", + "globals": "^15.6.0", "knip": "^5.20.0", "rollup": "^4.17.2", "tslib": "^2.6.3", - "typescript": "^5.4.5" + "typescript": "^5.4.5", + "typescript-eslint": "^8.0.0-alpha.36" }, "engines": { "node": "^14 || ^16 || >=18" @@ -1145,6 +1146,15 @@ "@babel/core": "^7.0.0-0" } }, + "node_modules/@babel/plugin-transform-classes/node_modules/globals": { + "version": "11.12.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-11.12.0.tgz", + "integrity": "sha512-WOBp/EEGUiIsJSp7wcv/y6MO+lV9UoncWqxuFfm8eBwzWNgyfBd6Gz+IeKQ9jCmyhoH99g15M3T+QaVHFjizVA==", + "dev": true, + "engines": { + "node": ">=4" + } + }, "node_modules/@babel/plugin-transform-computed-properties": { "version": "7.24.7", "resolved": "https://registry.npmjs.org/@babel/plugin-transform-computed-properties/-/plugin-transform-computed-properties-7.24.7.tgz", @@ -1980,6 +1990,15 @@ "node": ">=6.9.0" } }, + "node_modules/@babel/traverse/node_modules/globals": { + "version": "11.12.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-11.12.0.tgz", + "integrity": "sha512-WOBp/EEGUiIsJSp7wcv/y6MO+lV9UoncWqxuFfm8eBwzWNgyfBd6Gz+IeKQ9jCmyhoH99g15M3T+QaVHFjizVA==", + "dev": true, + "engines": { + "node": ">=4" + } + }, "node_modules/@babel/types": { "version": "7.24.7", "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.24.7.tgz", @@ -2304,6 +2323,18 @@ "eslint": "^6.0.0 || ^7.0.0 || >=8.0.0" } }, + "node_modules/@eslint-community/eslint-utils/node_modules/eslint-visitor-keys": { + "version": "3.4.3", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.4.3.tgz", + "integrity": "sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag==", + "dev": true, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, "node_modules/@eslint-community/regexpp": { "version": "4.11.0", "resolved": "https://registry.npmjs.org/@eslint-community/regexpp/-/regexpp-4.11.0.tgz", @@ -2313,16 +2344,42 @@ "node": "^12.0.0 || ^14.0.0 || >=16.0.0" } }, + "node_modules/@eslint/config-array": { + "version": "0.17.0", + "resolved": "https://registry.npmjs.org/@eslint/config-array/-/config-array-0.17.0.tgz", + "integrity": "sha512-A68TBu6/1mHHuc5YJL0U0VVeGNiklLAL6rRmhTCP2B5XjWLMnrX+HkO+IAXyHvks5cyyY1jjK5ITPQ1HGS2EVA==", + "dev": true, + "dependencies": { + "@eslint/object-schema": "^2.1.4", + "debug": "^4.3.1", + "minimatch": "^3.1.2" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, + "node_modules/@eslint/config-array/node_modules/minimatch": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", + "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", + "dev": true, + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, "node_modules/@eslint/eslintrc": { - "version": "2.1.4", - "resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-2.1.4.tgz", - "integrity": "sha512-269Z39MS6wVJtsoUl10L60WdkhJVdPG24Q4eZTH3nnF6lpvSShEK3wQjDX9JRWAUPvPh7COouPpU9IrqaZFvtQ==", + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-3.1.0.tgz", + "integrity": "sha512-4Bfj15dVJdoy3RfZmmo86RK1Fwzn6SstsvK9JS+BaVKqC6QQQQyXekNaC+g+LKNgkQ+2VhGAzm6hO40AhMR3zQ==", "dev": true, "dependencies": { "ajv": "^6.12.4", "debug": "^4.3.2", - "espree": "^9.6.0", - "globals": "^13.19.0", + "espree": "^10.0.1", + "globals": "^14.0.0", "ignore": "^5.2.0", "import-fresh": "^3.2.1", "js-yaml": "^4.1.0", @@ -2330,7 +2387,7 @@ "strip-json-comments": "^3.1.1" }, "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" }, "funding": { "url": "https://opencollective.com/eslint" @@ -2359,15 +2416,12 @@ "dev": true }, "node_modules/@eslint/eslintrc/node_modules/globals": { - "version": "13.24.0", - "resolved": "https://registry.npmjs.org/globals/-/globals-13.24.0.tgz", - "integrity": "sha512-AhO5QUcj8llrbG09iWhPU2B204J1xnPeL8kQmVorSsy+Sjj1sk8gIyh6cUocGmH4L0UuhAJy+hJMRA4mgA4mFQ==", + "version": "14.0.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-14.0.0.tgz", + "integrity": "sha512-oahGvuMGQlPw/ivIYBjVSrWAfWLBeku5tpPE2fOPLi+WHffIWbuh2tCjhyQhTBPMf5E9jDEH4FOmTYgYwbKwtQ==", "dev": true, - "dependencies": { - "type-fest": "^0.20.2" - }, "engines": { - "node": ">=8" + "node": ">=18" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" @@ -2403,40 +2457,22 @@ "node": "*" } }, - "node_modules/@eslint/eslintrc/node_modules/type-fest": { - "version": "0.20.2", - "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.20.2.tgz", - "integrity": "sha512-Ne+eE4r0/iWnpAxD852z3A+N0Bt5RN//NjJwRd2VFHEmrywxf5vsZlh4R6lixl6B+wz/8d+maTSAkN1FIkI3LQ==", - "dev": true, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, "node_modules/@eslint/js": { - "version": "8.57.0", - "resolved": "https://registry.npmjs.org/@eslint/js/-/js-8.57.0.tgz", - "integrity": "sha512-Ys+3g2TaW7gADOJzPt83SJtCDhMjndcDMFVQ/Tj9iA1BfJzFKD9mAUXT3OenpuPHbI6P/myECxRJrofUsDx/5g==", + "version": "9.6.0", + "resolved": "https://registry.npmjs.org/@eslint/js/-/js-9.6.0.tgz", + "integrity": "sha512-D9B0/3vNg44ZeWbYMpBoXqNP4j6eQD5vNwIlGAuFRRzK/WtT/jvDQW3Bi9kkf3PMDMlM7Yi+73VLUsn5bJcl8A==", "dev": true, "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" } }, - "node_modules/@humanwhocodes/config-array": { - "version": "0.11.14", - "resolved": "https://registry.npmjs.org/@humanwhocodes/config-array/-/config-array-0.11.14.tgz", - "integrity": "sha512-3T8LkOmg45BV5FICb15QQMsyUSWrQ8AygVfC7ZG32zOalnqrilm018ZVCw0eapXux8FtA33q8PSRSstjee3jSg==", - "deprecated": "Use @eslint/config-array instead", + "node_modules/@eslint/object-schema": { + "version": "2.1.4", + "resolved": "https://registry.npmjs.org/@eslint/object-schema/-/object-schema-2.1.4.tgz", + "integrity": "sha512-BsWiH1yFGjXXS2yvrf5LyuoSIIbPrGUWob917o+BTKuZ7qJdxX8aJLRxs1fS9n6r7vESrq1OUqb68dANcFXuQQ==", "dev": true, - "dependencies": { - "@humanwhocodes/object-schema": "^2.0.2", - "debug": "^4.3.1", - "minimatch": "^3.0.5" - }, "engines": { - "node": ">=10.10.0" + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" } }, "node_modules/@humanwhocodes/module-importer": { @@ -2452,12 +2488,18 @@ "url": "https://github.com/sponsors/nzakas" } }, - "node_modules/@humanwhocodes/object-schema": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/@humanwhocodes/object-schema/-/object-schema-2.0.3.tgz", - "integrity": "sha512-93zYdMES/c1D69yZiKDBj0V24vqNzB/koF26KPaagAfd3P/4gUlh3Dys5ogAK+Exi9QyzlD8x/08Zt7wIKcDcA==", - "deprecated": "Use @eslint/object-schema instead", - "dev": true + "node_modules/@humanwhocodes/retry": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/@humanwhocodes/retry/-/retry-0.3.0.tgz", + "integrity": "sha512-d2CGZR2o7fS6sWB7DG/3a95bGKQyHMACZ5aW8qGkkqQpUoZV6C0X7Pc7l4ZNMZkfNBf4VWNe9E1jRsf0G146Ew==", + "dev": true, + "engines": { + "node": ">=18.18" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/nzakas" + } }, "node_modules/@inquirer/figures": { "version": "1.0.3", @@ -3692,31 +3734,31 @@ } }, "node_modules/@typescript-eslint/eslint-plugin": { - "version": "7.14.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-7.14.1.tgz", - "integrity": "sha512-aAJd6bIf2vvQRjUG3ZkNXkmBpN+J7Wd0mfQiiVCJMu9Z5GcZZdcc0j8XwN/BM97Fl7e3SkTXODSk4VehUv7CGw==", + "version": "8.0.0-alpha.36", + "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.0.0-alpha.36.tgz", + "integrity": "sha512-Zt9x8YkczT509hphDxgKUlgC/JMyf/49U6idIPgOdo9Z11/jV5MaphxeKTEGTM+Ztqtx+XxprPICDgZFZZLdfQ==", "dev": true, "dependencies": { "@eslint-community/regexpp": "^4.10.0", - "@typescript-eslint/scope-manager": "7.14.1", - "@typescript-eslint/type-utils": "7.14.1", - "@typescript-eslint/utils": "7.14.1", - "@typescript-eslint/visitor-keys": "7.14.1", + "@typescript-eslint/scope-manager": "8.0.0-alpha.36", + "@typescript-eslint/type-utils": "8.0.0-alpha.36", + "@typescript-eslint/utils": "8.0.0-alpha.36", + "@typescript-eslint/visitor-keys": "8.0.0-alpha.36", "graphemer": "^1.4.0", "ignore": "^5.3.1", "natural-compare": "^1.4.0", "ts-api-utils": "^1.3.0" }, "engines": { - "node": "^18.18.0 || >=20.0.0" + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" }, "funding": { "type": "opencollective", "url": "https://opencollective.com/typescript-eslint" }, "peerDependencies": { - "@typescript-eslint/parser": "^7.0.0", - "eslint": "^8.56.0" + "@typescript-eslint/parser": "^8.0.0 || ^8.0.0-alpha.0", + "eslint": "^8.57.0 || ^9.0.0" }, "peerDependenciesMeta": { "typescript": { @@ -3725,26 +3767,26 @@ } }, "node_modules/@typescript-eslint/parser": { - "version": "7.14.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-7.14.1.tgz", - "integrity": "sha512-8lKUOebNLcR0D7RvlcloOacTOWzOqemWEWkKSVpMZVF/XVcwjPR+3MD08QzbW9TCGJ+DwIc6zUSGZ9vd8cO1IA==", + "version": "8.0.0-alpha.36", + "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-8.0.0-alpha.36.tgz", + "integrity": "sha512-DruwS9XPHbNsswczBkVQovefdWE5rNl1WBgywV3Z9gbNAzezk4OFHYMmmKO9ELHWED8ylXZ02m0Nr1g4xRhs5A==", "dev": true, "dependencies": { - "@typescript-eslint/scope-manager": "7.14.1", - "@typescript-eslint/types": "7.14.1", - "@typescript-eslint/typescript-estree": "7.14.1", - "@typescript-eslint/visitor-keys": "7.14.1", + "@typescript-eslint/scope-manager": "8.0.0-alpha.36", + "@typescript-eslint/types": "8.0.0-alpha.36", + "@typescript-eslint/typescript-estree": "8.0.0-alpha.36", + "@typescript-eslint/visitor-keys": "8.0.0-alpha.36", "debug": "^4.3.4" }, "engines": { - "node": "^18.18.0 || >=20.0.0" + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" }, "funding": { "type": "opencollective", "url": "https://opencollective.com/typescript-eslint" }, "peerDependencies": { - "eslint": "^8.56.0" + "eslint": "^8.57.0 || ^9.0.0" }, "peerDependenciesMeta": { "typescript": { @@ -3753,16 +3795,16 @@ } }, "node_modules/@typescript-eslint/scope-manager": { - "version": "7.14.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-7.14.1.tgz", - "integrity": "sha512-gPrFSsoYcsffYXTOZ+hT7fyJr95rdVe4kGVX1ps/dJ+DfmlnjFN/GcMxXcVkeHDKqsq6uAcVaQaIi3cFffmAbA==", + "version": "8.0.0-alpha.36", + "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-8.0.0-alpha.36.tgz", + "integrity": "sha512-uNpmffI+3Krh8k7lKQcs4XsrKO22eJUHRko+s6spnRc3i5FsZOZr2+VbmtJsliOraUKZJ275IqLVzyaCPO+gJA==", "dev": true, "dependencies": { - "@typescript-eslint/types": "7.14.1", - "@typescript-eslint/visitor-keys": "7.14.1" + "@typescript-eslint/types": "8.0.0-alpha.36", + "@typescript-eslint/visitor-keys": "8.0.0-alpha.36" }, "engines": { - "node": "^18.18.0 || >=20.0.0" + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" }, "funding": { "type": "opencollective", @@ -3770,26 +3812,23 @@ } }, "node_modules/@typescript-eslint/type-utils": { - "version": "7.14.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-7.14.1.tgz", - "integrity": "sha512-/MzmgNd3nnbDbOi3LfasXWWe292+iuo+umJ0bCCMCPc1jLO/z2BQmWUUUXvXLbrQey/JgzdF/OV+I5bzEGwJkQ==", + "version": "8.0.0-alpha.36", + "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-8.0.0-alpha.36.tgz", + "integrity": "sha512-Xap1FaM08TJ11umNFAEd+tpSr9F4K/rs4LhnlGlkA7TugWKdrBBnUOmE+U/XVZRmPjA3KnJ/whNcq5bQf7++mw==", "dev": true, "dependencies": { - "@typescript-eslint/typescript-estree": "7.14.1", - "@typescript-eslint/utils": "7.14.1", + "@typescript-eslint/typescript-estree": "8.0.0-alpha.36", + "@typescript-eslint/utils": "8.0.0-alpha.36", "debug": "^4.3.4", "ts-api-utils": "^1.3.0" }, "engines": { - "node": "^18.18.0 || >=20.0.0" + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" }, "funding": { "type": "opencollective", "url": "https://opencollective.com/typescript-eslint" }, - "peerDependencies": { - "eslint": "^8.56.0" - }, "peerDependenciesMeta": { "typescript": { "optional": true @@ -3797,12 +3836,12 @@ } }, "node_modules/@typescript-eslint/types": { - "version": "7.14.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-7.14.1.tgz", - "integrity": "sha512-mL7zNEOQybo5R3AavY+Am7KLv8BorIv7HCYS5rKoNZKQD9tsfGUpO4KdAn3sSUvTiS4PQkr2+K0KJbxj8H9NDg==", + "version": "8.0.0-alpha.36", + "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.0.0-alpha.36.tgz", + "integrity": "sha512-D+w5uE8Y83K/P5VQZyKKi4pwTL2YkWOwtQOVJQI38Rp8f3pmY+Jmcps3wkSFSJK8wifTlvoHwwIBf1FsdCW/EA==", "dev": true, "engines": { - "node": "^18.18.0 || >=20.0.0" + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" }, "funding": { "type": "opencollective", @@ -3810,13 +3849,13 @@ } }, "node_modules/@typescript-eslint/typescript-estree": { - "version": "7.14.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-7.14.1.tgz", - "integrity": "sha512-k5d0VuxViE2ulIO6FbxxSZaxqDVUyMbXcidC8rHvii0I56XZPv8cq+EhMns+d/EVIL41sMXqRbK3D10Oza1bbA==", + "version": "8.0.0-alpha.36", + "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-8.0.0-alpha.36.tgz", + "integrity": "sha512-1K2kj/CyMCDQlXubWJYx4aP5sUSi4OWeD7Z2MAOsoO2/EbPtHxdepqneYt20oR8TO5FUcXz3cV5BNUVAMoH6qg==", "dev": true, "dependencies": { - "@typescript-eslint/types": "7.14.1", - "@typescript-eslint/visitor-keys": "7.14.1", + "@typescript-eslint/types": "8.0.0-alpha.36", + "@typescript-eslint/visitor-keys": "8.0.0-alpha.36", "debug": "^4.3.4", "globby": "^11.1.0", "is-glob": "^4.0.3", @@ -3825,7 +3864,7 @@ "ts-api-utils": "^1.3.0" }, "engines": { - "node": "^18.18.0 || >=20.0.0" + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" }, "funding": { "type": "opencollective", @@ -3874,49 +3913,55 @@ } }, "node_modules/@typescript-eslint/utils": { - "version": "7.14.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-7.14.1.tgz", - "integrity": "sha512-CMmVVELns3nak3cpJhZosDkm63n+DwBlDX8g0k4QUa9BMnF+lH2lr3d130M1Zt1xxmB3LLk3NV7KQCq86ZBBhQ==", + "version": "8.0.0-alpha.36", + "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-8.0.0-alpha.36.tgz", + "integrity": "sha512-ITYdcfB6FSnGhrPpxBAB7/q/jvhfe1MTYgwvpLfTeqExQUTnSEiBlHS/oyFkTnxvLxUbCSiBbAKOv69FgGYnEA==", "dev": true, "dependencies": { "@eslint-community/eslint-utils": "^4.4.0", - "@typescript-eslint/scope-manager": "7.14.1", - "@typescript-eslint/types": "7.14.1", - "@typescript-eslint/typescript-estree": "7.14.1" + "@typescript-eslint/scope-manager": "8.0.0-alpha.36", + "@typescript-eslint/types": "8.0.0-alpha.36", + "@typescript-eslint/typescript-estree": "8.0.0-alpha.36" }, "engines": { - "node": "^18.18.0 || >=20.0.0" + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" }, "funding": { "type": "opencollective", "url": "https://opencollective.com/typescript-eslint" }, "peerDependencies": { - "eslint": "^8.56.0" + "eslint": "^8.57.0 || ^9.0.0" } }, "node_modules/@typescript-eslint/visitor-keys": { - "version": "7.14.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-7.14.1.tgz", - "integrity": "sha512-Crb+F75U1JAEtBeQGxSKwI60hZmmzaqA3z9sYsVm8X7W5cwLEm5bRe0/uXS6+MR/y8CVpKSR/ontIAIEPFcEkA==", + "version": "8.0.0-alpha.36", + "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-8.0.0-alpha.36.tgz", + "integrity": "sha512-V1LYF9mdUeMl/6rtbhCpYGkXKlx+zKh1Y09kEPtitvMDjA3Sb17Ph5OCckVkQCet2GjxrMZtpn1bTobZa8eD0Q==", "dev": true, "dependencies": { - "@typescript-eslint/types": "7.14.1", + "@typescript-eslint/types": "8.0.0-alpha.36", "eslint-visitor-keys": "^3.4.3" }, "engines": { - "node": "^18.18.0 || >=20.0.0" + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" }, "funding": { "type": "opencollective", "url": "https://opencollective.com/typescript-eslint" } }, - "node_modules/@ungap/structured-clone": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/@ungap/structured-clone/-/structured-clone-1.2.0.tgz", - "integrity": "sha512-zuVdFrMJiuCDQUMCzQaD6KL28MjnqqN8XnAqiEq9PNm/hCPTSGfrXCOfwj1ow4LFb/tNymJPwsNbVePc1xFqrQ==", - "dev": true + "node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys": { + "version": "3.4.3", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.4.3.tgz", + "integrity": "sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag==", + "dev": true, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } }, "node_modules/@webref/css": { "version": "6.12.15", @@ -4939,18 +4984,6 @@ "node": ">=8" } }, - "node_modules/doctrine": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/doctrine/-/doctrine-3.0.0.tgz", - "integrity": "sha512-yS+Q5i3hBf7GBkd4KG8a7eBNNWNGLTaEwwYWUijIYM7zrlYDM0BFXHjjPWlWZ1Rg7UaddZeIDmi9jF3HmqiQ2w==", - "dev": true, - "dependencies": { - "esutils": "^2.0.2" - }, - "engines": { - "node": ">=6.0.0" - } - }, "node_modules/eastasianwidth": { "version": "0.2.0", "resolved": "https://registry.npmjs.org/eastasianwidth/-/eastasianwidth-0.2.0.tgz", @@ -5067,41 +5100,37 @@ } }, "node_modules/eslint": { - "version": "8.57.0", - "resolved": "https://registry.npmjs.org/eslint/-/eslint-8.57.0.tgz", - "integrity": "sha512-dZ6+mexnaTIbSBZWgou51U6OmzIhYM2VcNdtiTtI7qPNZm35Akpr0f6vtw3w1Kmn5PYo+tZVfh13WrhpS6oLqQ==", + "version": "9.6.0", + "resolved": "https://registry.npmjs.org/eslint/-/eslint-9.6.0.tgz", + "integrity": "sha512-ElQkdLMEEqQNM9Njff+2Y4q2afHk7JpkPvrd7Xh7xefwgQynqPxwf55J7di9+MEibWUGdNjFF9ITG9Pck5M84w==", "dev": true, "dependencies": { "@eslint-community/eslint-utils": "^4.2.0", "@eslint-community/regexpp": "^4.6.1", - "@eslint/eslintrc": "^2.1.4", - "@eslint/js": "8.57.0", - "@humanwhocodes/config-array": "^0.11.14", + "@eslint/config-array": "^0.17.0", + "@eslint/eslintrc": "^3.1.0", + "@eslint/js": "9.6.0", "@humanwhocodes/module-importer": "^1.0.1", + "@humanwhocodes/retry": "^0.3.0", "@nodelib/fs.walk": "^1.2.8", - "@ungap/structured-clone": "^1.2.0", "ajv": "^6.12.4", "chalk": "^4.0.0", "cross-spawn": "^7.0.2", "debug": "^4.3.2", - "doctrine": "^3.0.0", "escape-string-regexp": "^4.0.0", - "eslint-scope": "^7.2.2", - "eslint-visitor-keys": "^3.4.3", - "espree": "^9.6.1", - "esquery": "^1.4.2", + "eslint-scope": "^8.0.1", + "eslint-visitor-keys": "^4.0.0", + "espree": "^10.1.0", + "esquery": "^1.5.0", "esutils": "^2.0.2", "fast-deep-equal": "^3.1.3", - "file-entry-cache": "^6.0.1", + "file-entry-cache": "^8.0.0", "find-up": "^5.0.0", "glob-parent": "^6.0.2", - "globals": "^13.19.0", - "graphemer": "^1.4.0", "ignore": "^5.2.0", "imurmurhash": "^0.1.4", "is-glob": "^4.0.0", "is-path-inside": "^3.0.3", - "js-yaml": "^4.1.0", "json-stable-stringify-without-jsonify": "^1.0.1", "levn": "^0.4.1", "lodash.merge": "^4.6.2", @@ -5115,35 +5144,35 @@ "eslint": "bin/eslint.js" }, "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" }, "funding": { - "url": "https://opencollective.com/eslint" + "url": "https://eslint.org/donate" } }, "node_modules/eslint-scope": { - "version": "7.2.2", - "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-7.2.2.tgz", - "integrity": "sha512-dOt21O7lTMhDM+X9mB4GX+DZrZtCUJPL/wlcTqxyrx5IvO0IYtILdtrQGQp+8n5S0gwSVmOf9NQrjMOgfQZlIg==", + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-8.0.1.tgz", + "integrity": "sha512-pL8XjgP4ZOmmwfFE8mEhSxA7ZY4C+LWyqjQ3o4yWkkmD0qcMT9kkW3zWHOczhWcjTSgqycYAgwSlXvZltv65og==", "dev": true, "dependencies": { "esrecurse": "^4.3.0", "estraverse": "^5.2.0" }, "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" }, "funding": { "url": "https://opencollective.com/eslint" } }, "node_modules/eslint-visitor-keys": { - "version": "3.4.3", - "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.4.3.tgz", - "integrity": "sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag==", + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-4.0.0.tgz", + "integrity": "sha512-OtIRv/2GyiF6o/d8K7MYKKbXrOUBIK6SfkIRM4Z0dY3w+LiQ0vy3F57m0Z71bjbyeiWFiHJ8brqnmE6H6/jEuw==", "dev": true, "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" }, "funding": { "url": "https://opencollective.com/eslint" @@ -5180,12 +5209,6 @@ "url": "https://github.com/chalk/ansi-styles?sponsor=1" } }, - "node_modules/eslint/node_modules/argparse": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", - "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==", - "dev": true - }, "node_modules/eslint/node_modules/chalk": { "version": "4.1.2", "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", @@ -5232,33 +5255,6 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/eslint/node_modules/globals": { - "version": "13.24.0", - "resolved": "https://registry.npmjs.org/globals/-/globals-13.24.0.tgz", - "integrity": "sha512-AhO5QUcj8llrbG09iWhPU2B204J1xnPeL8kQmVorSsy+Sjj1sk8gIyh6cUocGmH4L0UuhAJy+hJMRA4mgA4mFQ==", - "dev": true, - "dependencies": { - "type-fest": "^0.20.2" - }, - "engines": { - "node": ">=8" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/eslint/node_modules/js-yaml": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.0.tgz", - "integrity": "sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA==", - "dev": true, - "dependencies": { - "argparse": "^2.0.1" - }, - "bin": { - "js-yaml": "bin/js-yaml.js" - } - }, "node_modules/eslint/node_modules/json-schema-traverse": { "version": "0.4.1", "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", @@ -5289,30 +5285,18 @@ "node": ">=8" } }, - "node_modules/eslint/node_modules/type-fest": { - "version": "0.20.2", - "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.20.2.tgz", - "integrity": "sha512-Ne+eE4r0/iWnpAxD852z3A+N0Bt5RN//NjJwRd2VFHEmrywxf5vsZlh4R6lixl6B+wz/8d+maTSAkN1FIkI3LQ==", - "dev": true, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, "node_modules/espree": { - "version": "9.6.1", - "resolved": "https://registry.npmjs.org/espree/-/espree-9.6.1.tgz", - "integrity": "sha512-oruZaFkjorTpF32kDSI5/75ViwGeZginGGy2NoOSg3Q9bnwlnmDm4HLnkl0RE3n+njDXR037aY1+x58Z/zFdwQ==", + "version": "10.1.0", + "resolved": "https://registry.npmjs.org/espree/-/espree-10.1.0.tgz", + "integrity": "sha512-M1M6CpiE6ffoigIOWYO9UDP8TMUw9kqb21tf+08IgDYjCsOvCuDt4jQcZmoYxx+w7zlKw9/N0KXfto+I8/FrXA==", "dev": true, "dependencies": { - "acorn": "^8.9.0", + "acorn": "^8.12.0", "acorn-jsx": "^5.3.2", - "eslint-visitor-keys": "^3.4.1" + "eslint-visitor-keys": "^4.0.0" }, "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" }, "funding": { "url": "https://opencollective.com/eslint" @@ -5531,15 +5515,15 @@ } }, "node_modules/file-entry-cache": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-6.0.1.tgz", - "integrity": "sha512-7Gps/XWymbLk2QLYK4NzpMOrYjMhdIxXuIvy2QBsLE6ljuodKvdkWs/cpyJJ3CVIVpH0Oi1Hvg1ovbMzLdFBBg==", + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-8.0.0.tgz", + "integrity": "sha512-XXTUwCvisa5oacNGRP9SfNtYBNAMi+RPwBFmblZEF7N7swHYQS6/Zfk7SRwx4D5j3CH211YNRco1DEMNVfZCnQ==", "dev": true, "dependencies": { - "flat-cache": "^3.0.4" + "flat-cache": "^4.0.0" }, "engines": { - "node": "^10.12.0 || >=12.0.0" + "node": ">=16.0.0" } }, "node_modules/file-url": { @@ -5592,17 +5576,16 @@ } }, "node_modules/flat-cache": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-3.2.0.tgz", - "integrity": "sha512-CYcENa+FtcUKLmhhqyctpclsq7QF38pKjZHsGNiSQF5r4FtoKDWabFDl3hzaEQMvT1LHEysw5twgLvpYYb4vbw==", + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-4.0.1.tgz", + "integrity": "sha512-f7ccFPK3SXFHpx15UIGyRJ/FJQctuKZ0zVuN3frBo4HnK3cay9VEW0R6yPYFHC0AgqhukPzKjq22t5DmAyqGyw==", "dev": true, "dependencies": { "flatted": "^3.2.9", - "keyv": "^4.5.3", - "rimraf": "^3.0.2" + "keyv": "^4.5.4" }, "engines": { - "node": "^10.12.0 || >=12.0.0" + "node": ">=16" } }, "node_modules/flatted": { @@ -5653,12 +5636,6 @@ "node": ">=6 <7 || >=8" } }, - "node_modules/fs.realpath": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", - "integrity": "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==", - "dev": true - }, "node_modules/fsevents": { "version": "2.3.3", "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", @@ -5891,12 +5868,15 @@ } }, "node_modules/globals": { - "version": "11.12.0", - "resolved": "https://registry.npmjs.org/globals/-/globals-11.12.0.tgz", - "integrity": "sha512-WOBp/EEGUiIsJSp7wcv/y6MO+lV9UoncWqxuFfm8eBwzWNgyfBd6Gz+IeKQ9jCmyhoH99g15M3T+QaVHFjizVA==", + "version": "15.6.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-15.6.0.tgz", + "integrity": "sha512-UzcJi88Hw//CurUIRa9Jxb0vgOCcuD/MNjwmXp633cyaRKkCWACkoqHCtfZv43b1kqXGg/fpOa8bwgacCeXsVg==", "dev": true, "engines": { - "node": ">=4" + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/globby": { @@ -6149,17 +6129,6 @@ "node": ">=8" } }, - "node_modules/inflight": { - "version": "1.0.6", - "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", - "integrity": "sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==", - "deprecated": "This module is not supported, and leaks memory. Do not use it. Check out lru-cache if you want a good and tested way to coalesce async requests by a key value, which is much more comprehensive and powerful.", - "dev": true, - "dependencies": { - "once": "^1.3.0", - "wrappy": "1" - } - }, "node_modules/inherits": { "version": "2.0.4", "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", @@ -7373,15 +7342,6 @@ "node": ">=8" } }, - "node_modules/path-is-absolute": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", - "integrity": "sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==", - "dev": true, - "engines": { - "node": ">=0.10.0" - } - }, "node_modules/path-key": { "version": "3.1.1", "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", @@ -7464,9 +7424,9 @@ } }, "node_modules/postcss": { - "version": "8.4.38", - "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.4.38.tgz", - "integrity": "sha512-Wglpdk03BSfXkHoQa3b/oulrotAkwrlLDRSOb9D0bN86FdRyE9lppSp33aHNPgBa0JKCoB+drFLZkQoRRYae5A==", + "version": "8.4.39", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.4.39.tgz", + "integrity": "sha512-0vzE+lAiG7hZl1/9I8yzKLx3aR9Xbof3fBHKunvMfOCYAtMhrsnccJY2iTURb9EZd5+pLuiNV9/c/GZJOHsgIw==", "funding": [ { "type": "opencollective", @@ -7483,7 +7443,7 @@ ], "dependencies": { "nanoid": "^3.3.7", - "picocolors": "^1.0.0", + "picocolors": "^1.0.1", "source-map-js": "^1.2.0" }, "engines": { @@ -7492,9 +7452,9 @@ }, "node_modules/postcss-8.4": { "name": "postcss", - "version": "8.4.38", - "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.4.38.tgz", - "integrity": "sha512-Wglpdk03BSfXkHoQa3b/oulrotAkwrlLDRSOb9D0bN86FdRyE9lppSp33aHNPgBa0JKCoB+drFLZkQoRRYae5A==", + "version": "8.4.39", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.4.39.tgz", + "integrity": "sha512-0vzE+lAiG7hZl1/9I8yzKLx3aR9Xbof3fBHKunvMfOCYAtMhrsnccJY2iTURb9EZd5+pLuiNV9/c/GZJOHsgIw==", "funding": [ { "type": "opencollective", @@ -7511,7 +7471,7 @@ ], "dependencies": { "nanoid": "^3.3.7", - "picocolors": "^1.0.0", + "picocolors": "^1.0.1", "source-map-js": "^1.2.0" }, "engines": { @@ -8128,55 +8088,6 @@ "integrity": "sha512-q1b3N5QkRUWUl7iyylaaj3kOpIT0N2i9MqIEQXP73GVsN9cw3fdx8X63cEmWhJGi2PPCF23Ijp7ktmd39rawIA==", "dev": true }, - "node_modules/rimraf": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-3.0.2.tgz", - "integrity": "sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA==", - "deprecated": "Rimraf versions prior to v4 are no longer supported", - "dev": true, - "dependencies": { - "glob": "^7.1.3" - }, - "bin": { - "rimraf": "bin.js" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, - "node_modules/rimraf/node_modules/glob": { - "version": "7.2.3", - "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", - "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", - "deprecated": "Glob versions prior to v9 are no longer supported", - "dev": true, - "dependencies": { - "fs.realpath": "^1.0.0", - "inflight": "^1.0.4", - "inherits": "2", - "minimatch": "^3.1.1", - "once": "^1.3.0", - "path-is-absolute": "^1.0.0" - }, - "engines": { - "node": "*" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, - "node_modules/rimraf/node_modules/minimatch": { - "version": "3.1.2", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", - "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", - "dev": true, - "dependencies": { - "brace-expansion": "^1.1.7" - }, - "engines": { - "node": "*" - } - }, "node_modules/rollup": { "version": "4.18.0", "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.18.0.tgz", @@ -9162,6 +9073,29 @@ "node": ">=14.17" } }, + "node_modules/typescript-eslint": { + "version": "8.0.0-alpha.36", + "resolved": "https://registry.npmjs.org/typescript-eslint/-/typescript-eslint-8.0.0-alpha.36.tgz", + "integrity": "sha512-QPIwkUDMoTZmCCXcnyOfEJo3ymxfF8sSla7ZtNr1qqRY/wxMBe4htWDHj9y+iDOYsAusl37MPsBDKqyazacTVA==", + "dev": true, + "dependencies": { + "@typescript-eslint/eslint-plugin": "8.0.0-alpha.36", + "@typescript-eslint/parser": "8.0.0-alpha.36", + "@typescript-eslint/utils": "8.0.0-alpha.36" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, "node_modules/unbzip2-stream": { "version": "1.4.3", "resolved": "https://registry.npmjs.org/unbzip2-stream/-/unbzip2-stream-1.4.3.tgz", diff --git a/package.json b/package.json index 3518308ed..dfc7f3119 100644 --- a/package.json +++ b/package.json @@ -28,27 +28,28 @@ "devDependencies": { "@babel/core": "^7.24.7", "@babel/preset-env": "^7.24.7", - "@microsoft/api-extractor": "^7.47.0", + "@eslint/js": "^9.5.0", "@microsoft/api-documenter": "^7.25.3", + "@microsoft/api-extractor": "^7.47.0", "@rollup/plugin-babel": "^6.0.3", "@rollup/plugin-commonjs": "^26.0.1", "@rollup/plugin-node-resolve": "^15.2.3", "@rollup/plugin-terser": "^0.4.3", "@rollup/plugin-typescript": "^11.1.6", "@stryker-mutator/core": "^8.2.6", - "@typescript-eslint/eslint-plugin": "^7.13.0", - "@typescript-eslint/parser": "^7.13.0", - "eslint": "^8.57.0", + "eslint": "^9.5.0", + "globals": "^15.6.0", "knip": "^5.20.0", "rollup": "^4.17.2", "tslib": "^2.6.3", - "typescript": "^5.4.5" + "typescript": "^5.4.5", + "typescript-eslint": "^8.0.0-alpha.36" }, "scripts": { "build": "npm run build --workspaces --if-present", "clean": "npm run clean --workspaces --if-present", "docs": "npm run docs --workspaces --if-present", - "lint": "npm run lint --workspaces --if-present && eslint ./ --ext .js --ext .mjs --ext .cjs --ext .ts --ext .mts --no-error-on-unmatched-pattern && bash .github/bin/detect-executable-files/detect-executable-files.sh && node .github/bin/license/check-license.mjs", + "lint": "npm run lint --workspaces --if-present && eslint ./ && bash .github/bin/detect-executable-files/detect-executable-files.sh && node .github/bin/license/check-license.mjs", "new-plugin": "node ./.github/bin/new-plugin.mjs", "release-plan": "node .github/bin/release-plan/release-plan.mjs", "release-plan:dry-run": "node .github/bin/release-plan/release-plan.mjs --dry-run", diff --git a/packages/base-cli/dist/index.cjs b/packages/base-cli/dist/index.cjs index 93991e78b..c657f3b3b 100644 --- a/packages/base-cli/dist/index.cjs +++ b/packages/base-cli/dist/index.cjs @@ -1 +1 @@ -"use strict";var t,e=require("postcss"),n=require("path"),s=require("fs");function parseArguments(e,n,s){const i=e.map((t=>t.trim())).filter((t=>!!t)),o={stdin:!1,stdout:!1,output:void 0,outputDir:void 0,inputs:[],inlineMap:!0,externalMap:!1,replace:!1,pluginOptions:{},debug:!1};let r,a=!1;for(let e=0;e1&&o.output)return console.warn('[error] omit "--output" when processing multiple inputs\n'),s(),t.InvalidArguments;0===o.inputs.length&&(o.stdin=!0),o.output||o.outputDir||o.replace||(o.stdout=!0),o.stdout&&(o.externalMap=!1);let p={};if(r)try{p=JSON.parse(r)}catch(e){return console.warn("[error] plugin options must be valid JSON\n"),s(),t.InvalidArguments}for(const e in p){const i=p[e];if(!n.includes(e))return console.warn(`[error] unknown plugin option: ${e}\n`),s(),t.InvalidArguments;o.pluginOptions[e]=i}return o}async function getStdin(){return new Promise((t=>{let e="",n=!1;if(setTimeout((()=>{n=!0,t("")}),1e4),process.stdin.isTTY){if(n)return;t(e)}else process.stdin.setEncoding("utf8"),process.stdin.on("readable",(()=>{let t;for(;t=process.stdin.read();)e+=t})),process.stdin.on("end",(()=>{n||t(e)}))}))}async function stdinToStdout(t,n,s){let i="";try{const o=await getStdin();o||(s(),process.exit(1));const r=await e([t]).process(o,{from:"stdin",to:"stdout",map:!!n.inlineMap&&{inline:!0}});r.warnings().forEach((t=>{console.warn(t.toString())})),i=r.css}catch(t){t instanceof Error?console.error(n.debug?t:t.message):console.error(t),process.exit(1)}process.stdout.write(i+(n.inlineMap?"\n":"")),process.exit(0)}async function stdinToFs(t,i,o){let r=i.output;!r&&i.outputDir&&(r=n.join(i.outputDir,"output.css")),r||process.exit(0);try{const n=await getStdin();n||(o(),process.exit(1));const a=await e([t]).process(n,{from:"stdin",to:r,map:!(!i.inlineMap&&!i.externalMap)&&{inline:i.inlineMap}});a.warnings().forEach((t=>{console.warn(t.toString())})),i.externalMap&&a.map?await Promise.all([await s.promises.writeFile(r,a.css+(i.inlineMap?"\n":"")),await s.promises.writeFile(`${r}.map`,a.map.toString())]):await s.promises.writeFile(r,a.css+(i.inlineMap?"\n":""))}catch(t){t instanceof Error?console.error(i.debug?t:t.message):console.error(t),process.exit(1)}console.log(`CSS was written to "${n.normalize(r)}"`),process.exit(0)}async function fsToStdout(t,n){let i=[];try{i=await Promise.all(n.inputs.map((async n=>{const i=await s.promises.readFile(n),o=await e([t]).process(i,{from:n,to:"stdout",map:!1});return o.warnings().forEach((t=>{console.warn(t.toString())})),o.css})))}catch(t){t instanceof Error?console.error(n.debug?t:t.message):console.error(t),process.exit(1)}for(const t of i)process.stdout.write(t);process.exit(0)}async function fsToFs(t,i){try{await Promise.all(i.inputs.map((async o=>{let r=i.output;i.outputDir&&(r=n.join(i.outputDir,n.basename(o))),i.replace&&(r=o),r||process.exit(0);const a=await s.promises.readFile(o),p=await e([t]).process(a,{from:o,to:r,map:!(!i.inlineMap&&!i.externalMap)&&{inline:i.inlineMap}});p.warnings().forEach((t=>{console.warn(t.toString())})),i.externalMap&&p.map?await Promise.all([await s.promises.writeFile(r,p.css+(i.inlineMap?"\n":"")),await s.promises.writeFile(`${r}.map`,p.map.toString())]):await s.promises.writeFile(r,p.css+(i.inlineMap?"\n":"")),console.log(`CSS was written to "${n.normalize(r)}"`)})))}catch(t){t instanceof Error?console.error(i.debug?t:t.message):console.error(t),process.exit(1)}process.exit(0)}!function(t){t.InvalidArguments="INVALID_ARGUMENTS"}(t||(t={})),exports.cli=async function cli(e,n,s,i=!0){const o=parseArguments(process.argv.slice(i?2:3),n,s);o===t.InvalidArguments&&process.exit(1);const r=e(o.pluginOptions);o.stdin&&o.stdout?await stdinToStdout(r,o,s):o.stdin?await stdinToFs(r,o,s):o.stdout?await fsToStdout(r,o):await fsToFs(r,o)},exports.helpTextLogger=function helpTextLogger(t,e,n,s=null){let i=[];if(s){const t=Math.max(...Object.keys(s).map((t=>t.length))),e=new Array(t).fill(" ").join("");e.length&&(i=["\nPlugin Options:",...Object.keys(s).map((t=>` ${(t+e).slice(0,e.length)} ${typeof s[t]}`))],i.push(`\n ${JSON.stringify(s,null,2).split("\n").join("\n ")}`))}const o=[`${e}\n`,` ${n}\n`,"Usage:",` ${t} [input.css] [OPTIONS] [-o|--output output.css]`,` ${t} ... [OPTIONS] --dir `,` ${t} ... [OPTIONS] --replace`,"\nOptions:"," -o, --output Output file"," -d, --dir Output directory"," -r, --replace Replace (overwrite) the input file"," -m, --map Create an external sourcemap"," --no-map Disable the default inline sourcemaps"," -p, --plugin-options Stringified JSON object with plugin options"];return i.length>0&&o.push(...i),()=>{console.warn(o.join("\n"))}},exports.parseArguments=parseArguments; +"use strict";var t,e=require("postcss"),n=require("path"),s=require("fs");function parseArguments(e,n,s){const i=e.map((t=>t.trim())).filter((t=>!!t)),o={stdin:!1,stdout:!1,output:void 0,outputDir:void 0,inputs:[],inlineMap:!0,externalMap:!1,replace:!1,pluginOptions:{},debug:!1};let r,a=!1;for(let e=0;e1&&o.output)return console.warn('[error] omit "--output" when processing multiple inputs\n'),s(),t.InvalidArguments;0===o.inputs.length&&(o.stdin=!0),o.output||o.outputDir||o.replace||(o.stdout=!0),o.stdout&&(o.externalMap=!1);let p={};if(r)try{p=JSON.parse(r)}catch{return console.warn("[error] plugin options must be valid JSON\n"),s(),t.InvalidArguments}for(const e in p){const i=p[e];if(!n.includes(e))return console.warn(`[error] unknown plugin option: ${e}\n`),s(),t.InvalidArguments;o.pluginOptions[e]=i}return o}async function getStdin(){return new Promise((t=>{let e="",n=!1;if(setTimeout((()=>{n=!0,t("")}),1e4),process.stdin.isTTY){if(n)return;t(e)}else process.stdin.setEncoding("utf8"),process.stdin.on("readable",(()=>{let t="";for(;t=process.stdin.read();)e+=t??""})),process.stdin.on("end",(()=>{n||t(e)}))}))}async function stdinToStdout(t,n,s){let i="";try{const o=await getStdin();o||(s(),process.exit(1));const r=await e([t]).process(o,{from:"stdin",to:"stdout",map:!!n.inlineMap&&{inline:!0}});r.warnings().forEach((t=>{console.warn(t.toString())})),i=r.css}catch(t){t instanceof Error?console.error(n.debug?t:t.message):console.error(t),process.exit(1)}process.stdout.write(i+(n.inlineMap?"\n":"")),process.exit(0)}async function stdinToFs(t,i,o){let r=i.output;!r&&i.outputDir&&(r=n.join(i.outputDir,"output.css")),r||process.exit(0);try{const n=await getStdin();n||(o(),process.exit(1));const a=await e([t]).process(n,{from:"stdin",to:r,map:!(!i.inlineMap&&!i.externalMap)&&{inline:i.inlineMap}});a.warnings().forEach((t=>{console.warn(t.toString())})),i.externalMap&&a.map?await Promise.all([await s.promises.writeFile(r,a.css+(i.inlineMap?"\n":"")),await s.promises.writeFile(`${r}.map`,a.map.toString())]):await s.promises.writeFile(r,a.css+(i.inlineMap?"\n":""))}catch(t){t instanceof Error?console.error(i.debug?t:t.message):console.error(t),process.exit(1)}console.log(`CSS was written to "${n.normalize(r)}"`),process.exit(0)}async function fsToStdout(t,n){let i=[];try{i=await Promise.all(n.inputs.map((async n=>{const i=await s.promises.readFile(n),o=await e([t]).process(i,{from:n,to:"stdout",map:!1});return o.warnings().forEach((t=>{console.warn(t.toString())})),o.css})))}catch(t){t instanceof Error?console.error(n.debug?t:t.message):console.error(t),process.exit(1)}for(const t of i)process.stdout.write(t);process.exit(0)}async function fsToFs(t,i){try{await Promise.all(i.inputs.map((async o=>{let r=i.output;i.outputDir&&(r=n.join(i.outputDir,n.basename(o))),i.replace&&(r=o),r||process.exit(0);const a=await s.promises.readFile(o),p=await e([t]).process(a,{from:o,to:r,map:!(!i.inlineMap&&!i.externalMap)&&{inline:i.inlineMap}});p.warnings().forEach((t=>{console.warn(t.toString())})),i.externalMap&&p.map?await Promise.all([await s.promises.writeFile(r,p.css+(i.inlineMap?"\n":"")),await s.promises.writeFile(`${r}.map`,p.map.toString())]):await s.promises.writeFile(r,p.css+(i.inlineMap?"\n":"")),console.log(`CSS was written to "${n.normalize(r)}"`)})))}catch(t){t instanceof Error?console.error(i.debug?t:t.message):console.error(t),process.exit(1)}process.exit(0)}!function(t){t.InvalidArguments="INVALID_ARGUMENTS"}(t||(t={})),exports.cli=async function cli(e,n,s,i=!0){const o=parseArguments(process.argv.slice(i?2:3),n,s);o===t.InvalidArguments&&process.exit(1);const r=e(o.pluginOptions);o.stdin&&o.stdout?await stdinToStdout(r,o,s):o.stdin?await stdinToFs(r,o,s):o.stdout?await fsToStdout(r,o):await fsToFs(r,o)},exports.helpTextLogger=function helpTextLogger(t,e,n,s=null){let i=[];if(s){const t=Math.max(...Object.keys(s).map((t=>t.length))),e=new Array(t).fill(" ").join("");e.length&&(i=["\nPlugin Options:",...Object.keys(s).map((t=>` ${(t+e).slice(0,e.length)} ${typeof s[t]}`))],i.push(`\n ${JSON.stringify(s,null,2).split("\n").join("\n ")}`))}const o=[`${e}\n`,` ${n}\n`,"Usage:",` ${t} [input.css] [OPTIONS] [-o|--output output.css]`,` ${t} ... [OPTIONS] --dir `,` ${t} ... [OPTIONS] --replace`,"\nOptions:"," -o, --output Output file"," -d, --dir Output directory"," -r, --replace Replace (overwrite) the input file"," -m, --map Create an external sourcemap"," --no-map Disable the default inline sourcemaps"," -p, --plugin-options Stringified JSON object with plugin options"];return i.length>0&&o.push(...i),()=>{console.warn(o.join("\n"))}},exports.parseArguments=parseArguments; diff --git a/packages/base-cli/dist/index.mjs b/packages/base-cli/dist/index.mjs index 2bc75e97a..a65a269ac 100644 --- a/packages/base-cli/dist/index.mjs +++ b/packages/base-cli/dist/index.mjs @@ -1 +1 @@ -import t from"postcss";import e from"path";import{promises as n}from"fs";var o;function parseArguments(t,e,n){const s=t.map((t=>t.trim())).filter((t=>!!t)),i={stdin:!1,stdout:!1,output:void 0,outputDir:void 0,inputs:[],inlineMap:!0,externalMap:!1,replace:!1,pluginOptions:{},debug:!1};let r,a=!1;for(let t=0;t1&&i.output)return console.warn('[error] omit "--output" when processing multiple inputs\n'),n(),o.InvalidArguments;0===i.inputs.length&&(i.stdin=!0),i.output||i.outputDir||i.replace||(i.stdout=!0),i.stdout&&(i.externalMap=!1);let p={};if(r)try{p=JSON.parse(r)}catch(t){return console.warn("[error] plugin options must be valid JSON\n"),n(),o.InvalidArguments}for(const t in p){const s=p[t];if(!e.includes(t))return console.warn(`[error] unknown plugin option: ${t}\n`),n(),o.InvalidArguments;i.pluginOptions[t]=s}return i}async function getStdin(){return new Promise((t=>{let e="",n=!1;if(setTimeout((()=>{n=!0,t("")}),1e4),process.stdin.isTTY){if(n)return;t(e)}else process.stdin.setEncoding("utf8"),process.stdin.on("readable",(()=>{let t;for(;t=process.stdin.read();)e+=t})),process.stdin.on("end",(()=>{n||t(e)}))}))}async function stdinToStdout(e,n,o){let s="";try{const i=await getStdin();i||(o(),process.exit(1));const r=await t([e]).process(i,{from:"stdin",to:"stdout",map:!!n.inlineMap&&{inline:!0}});r.warnings().forEach((t=>{console.warn(t.toString())})),s=r.css}catch(t){t instanceof Error?console.error(n.debug?t:t.message):console.error(t),process.exit(1)}process.stdout.write(s+(n.inlineMap?"\n":"")),process.exit(0)}async function stdinToFs(o,s,i){let r=s.output;!r&&s.outputDir&&(r=e.join(s.outputDir,"output.css")),r||process.exit(0);try{const e=await getStdin();e||(i(),process.exit(1));const a=await t([o]).process(e,{from:"stdin",to:r,map:!(!s.inlineMap&&!s.externalMap)&&{inline:s.inlineMap}});a.warnings().forEach((t=>{console.warn(t.toString())})),s.externalMap&&a.map?await Promise.all([await n.writeFile(r,a.css+(s.inlineMap?"\n":"")),await n.writeFile(`${r}.map`,a.map.toString())]):await n.writeFile(r,a.css+(s.inlineMap?"\n":""))}catch(t){t instanceof Error?console.error(s.debug?t:t.message):console.error(t),process.exit(1)}console.log(`CSS was written to "${e.normalize(r)}"`),process.exit(0)}async function fsToStdout(e,o){let s=[];try{s=await Promise.all(o.inputs.map((async o=>{const s=await n.readFile(o),i=await t([e]).process(s,{from:o,to:"stdout",map:!1});return i.warnings().forEach((t=>{console.warn(t.toString())})),i.css})))}catch(t){t instanceof Error?console.error(o.debug?t:t.message):console.error(t),process.exit(1)}for(const t of s)process.stdout.write(t);process.exit(0)}async function fsToFs(o,s){try{await Promise.all(s.inputs.map((async i=>{let r=s.output;s.outputDir&&(r=e.join(s.outputDir,e.basename(i))),s.replace&&(r=i),r||process.exit(0);const a=await n.readFile(i),p=await t([o]).process(a,{from:i,to:r,map:!(!s.inlineMap&&!s.externalMap)&&{inline:s.inlineMap}});p.warnings().forEach((t=>{console.warn(t.toString())})),s.externalMap&&p.map?await Promise.all([await n.writeFile(r,p.css+(s.inlineMap?"\n":"")),await n.writeFile(`${r}.map`,p.map.toString())]):await n.writeFile(r,p.css+(s.inlineMap?"\n":"")),console.log(`CSS was written to "${e.normalize(r)}"`)})))}catch(t){t instanceof Error?console.error(s.debug?t:t.message):console.error(t),process.exit(1)}process.exit(0)}function helpTextLogger(t,e,n,o=null){let s=[];if(o){const t=Math.max(...Object.keys(o).map((t=>t.length))),e=new Array(t).fill(" ").join("");e.length&&(s=["\nPlugin Options:",...Object.keys(o).map((t=>` ${(t+e).slice(0,e.length)} ${typeof o[t]}`))],s.push(`\n ${JSON.stringify(o,null,2).split("\n").join("\n ")}`))}const i=[`${e}\n`,` ${n}\n`,"Usage:",` ${t} [input.css] [OPTIONS] [-o|--output output.css]`,` ${t} ... [OPTIONS] --dir `,` ${t} ... [OPTIONS] --replace`,"\nOptions:"," -o, --output Output file"," -d, --dir Output directory"," -r, --replace Replace (overwrite) the input file"," -m, --map Create an external sourcemap"," --no-map Disable the default inline sourcemaps"," -p, --plugin-options Stringified JSON object with plugin options"];return s.length>0&&i.push(...s),()=>{console.warn(i.join("\n"))}}async function cli(t,e,n,s=!0){const i=parseArguments(process.argv.slice(s?2:3),e,n);i===o.InvalidArguments&&process.exit(1);const r=t(i.pluginOptions);i.stdin&&i.stdout?await stdinToStdout(r,i,n):i.stdin?await stdinToFs(r,i,n):i.stdout?await fsToStdout(r,i):await fsToFs(r,i)}!function(t){t.InvalidArguments="INVALID_ARGUMENTS"}(o||(o={}));export{cli,helpTextLogger,parseArguments}; +import t from"postcss";import e from"path";import{promises as n}from"fs";var o;function parseArguments(t,e,n){const s=t.map((t=>t.trim())).filter((t=>!!t)),i={stdin:!1,stdout:!1,output:void 0,outputDir:void 0,inputs:[],inlineMap:!0,externalMap:!1,replace:!1,pluginOptions:{},debug:!1};let r,a=!1;for(let t=0;t1&&i.output)return console.warn('[error] omit "--output" when processing multiple inputs\n'),n(),o.InvalidArguments;0===i.inputs.length&&(i.stdin=!0),i.output||i.outputDir||i.replace||(i.stdout=!0),i.stdout&&(i.externalMap=!1);let p={};if(r)try{p=JSON.parse(r)}catch{return console.warn("[error] plugin options must be valid JSON\n"),n(),o.InvalidArguments}for(const t in p){const s=p[t];if(!e.includes(t))return console.warn(`[error] unknown plugin option: ${t}\n`),n(),o.InvalidArguments;i.pluginOptions[t]=s}return i}async function getStdin(){return new Promise((t=>{let e="",n=!1;if(setTimeout((()=>{n=!0,t("")}),1e4),process.stdin.isTTY){if(n)return;t(e)}else process.stdin.setEncoding("utf8"),process.stdin.on("readable",(()=>{let t="";for(;t=process.stdin.read();)e+=t??""})),process.stdin.on("end",(()=>{n||t(e)}))}))}async function stdinToStdout(e,n,o){let s="";try{const i=await getStdin();i||(o(),process.exit(1));const r=await t([e]).process(i,{from:"stdin",to:"stdout",map:!!n.inlineMap&&{inline:!0}});r.warnings().forEach((t=>{console.warn(t.toString())})),s=r.css}catch(t){t instanceof Error?console.error(n.debug?t:t.message):console.error(t),process.exit(1)}process.stdout.write(s+(n.inlineMap?"\n":"")),process.exit(0)}async function stdinToFs(o,s,i){let r=s.output;!r&&s.outputDir&&(r=e.join(s.outputDir,"output.css")),r||process.exit(0);try{const e=await getStdin();e||(i(),process.exit(1));const a=await t([o]).process(e,{from:"stdin",to:r,map:!(!s.inlineMap&&!s.externalMap)&&{inline:s.inlineMap}});a.warnings().forEach((t=>{console.warn(t.toString())})),s.externalMap&&a.map?await Promise.all([await n.writeFile(r,a.css+(s.inlineMap?"\n":"")),await n.writeFile(`${r}.map`,a.map.toString())]):await n.writeFile(r,a.css+(s.inlineMap?"\n":""))}catch(t){t instanceof Error?console.error(s.debug?t:t.message):console.error(t),process.exit(1)}console.log(`CSS was written to "${e.normalize(r)}"`),process.exit(0)}async function fsToStdout(e,o){let s=[];try{s=await Promise.all(o.inputs.map((async o=>{const s=await n.readFile(o),i=await t([e]).process(s,{from:o,to:"stdout",map:!1});return i.warnings().forEach((t=>{console.warn(t.toString())})),i.css})))}catch(t){t instanceof Error?console.error(o.debug?t:t.message):console.error(t),process.exit(1)}for(const t of s)process.stdout.write(t);process.exit(0)}async function fsToFs(o,s){try{await Promise.all(s.inputs.map((async i=>{let r=s.output;s.outputDir&&(r=e.join(s.outputDir,e.basename(i))),s.replace&&(r=i),r||process.exit(0);const a=await n.readFile(i),p=await t([o]).process(a,{from:i,to:r,map:!(!s.inlineMap&&!s.externalMap)&&{inline:s.inlineMap}});p.warnings().forEach((t=>{console.warn(t.toString())})),s.externalMap&&p.map?await Promise.all([await n.writeFile(r,p.css+(s.inlineMap?"\n":"")),await n.writeFile(`${r}.map`,p.map.toString())]):await n.writeFile(r,p.css+(s.inlineMap?"\n":"")),console.log(`CSS was written to "${e.normalize(r)}"`)})))}catch(t){t instanceof Error?console.error(s.debug?t:t.message):console.error(t),process.exit(1)}process.exit(0)}function helpTextLogger(t,e,n,o=null){let s=[];if(o){const t=Math.max(...Object.keys(o).map((t=>t.length))),e=new Array(t).fill(" ").join("");e.length&&(s=["\nPlugin Options:",...Object.keys(o).map((t=>` ${(t+e).slice(0,e.length)} ${typeof o[t]}`))],s.push(`\n ${JSON.stringify(o,null,2).split("\n").join("\n ")}`))}const i=[`${e}\n`,` ${n}\n`,"Usage:",` ${t} [input.css] [OPTIONS] [-o|--output output.css]`,` ${t} ... [OPTIONS] --dir `,` ${t} ... [OPTIONS] --replace`,"\nOptions:"," -o, --output Output file"," -d, --dir Output directory"," -r, --replace Replace (overwrite) the input file"," -m, --map Create an external sourcemap"," --no-map Disable the default inline sourcemaps"," -p, --plugin-options Stringified JSON object with plugin options"];return s.length>0&&i.push(...s),()=>{console.warn(i.join("\n"))}}async function cli(t,e,n,s=!0){const i=parseArguments(process.argv.slice(s?2:3),e,n);i===o.InvalidArguments&&process.exit(1);const r=t(i.pluginOptions);i.stdin&&i.stdout?await stdinToStdout(r,i,n):i.stdin?await stdinToFs(r,i,n):i.stdout?await fsToStdout(r,i):await fsToFs(r,i)}!function(t){t.InvalidArguments="INVALID_ARGUMENTS"}(o||(o={}));export{cli,helpTextLogger,parseArguments}; diff --git a/packages/base-cli/src/args.ts b/packages/base-cli/src/args.ts index 44e870ebd..b626d08d1 100644 --- a/packages/base-cli/src/args.ts +++ b/packages/base-cli/src/args.ts @@ -145,8 +145,8 @@ export function parseArguments(args: Array, allowedPluginOpts: Array; + } catch { // Stryker disable next-line all console.warn('[error] plugin options must be valid JSON\n'); // Stryker disable next-line all diff --git a/packages/base-cli/src/get-stdin.ts b/packages/base-cli/src/get-stdin.ts index 1c0e36436..15904b64a 100644 --- a/packages/base-cli/src/get-stdin.ts +++ b/packages/base-cli/src/get-stdin.ts @@ -1,6 +1,6 @@ export async function getStdin(): Promise { return new Promise((resolve: (str: string) => void) => { - let data = ''; + let data: string = ''; let timedOut = false; setTimeout(() => { timedOut = true; @@ -17,10 +17,10 @@ export async function getStdin(): Promise { process.stdin.setEncoding('utf8'); process.stdin.on('readable', () => { - let chunk; + let chunk: string | null = ''; - while ((chunk = process.stdin.read())) { - data += chunk; + while ((chunk = process.stdin.read() as string | null)) { + data += chunk ?? ''; } }); diff --git a/packages/cascade-layer-name-parser/src/nodes/layer-name.ts b/packages/cascade-layer-name-parser/src/nodes/layer-name.ts index 8e94d432d..0d76406a2 100644 --- a/packages/cascade-layer-name-parser/src/nodes/layer-name.ts +++ b/packages/cascade-layer-name-parser/src/nodes/layer-name.ts @@ -47,18 +47,18 @@ export class LayerName { } segments(): Array { - return this.parts.filter((x) => { + return this.parts.filter((x): x is TokenIdent => { return isTokenIdent(x); }).map((x) => { - return (x as TokenIdent)[4].value; + return x[4].value; }); } name(): string { - return this.parts.filter((x) => { + return this.parts.filter((x): x is TokenIdent | TokenDelim => { return isTokenIdent(x) || isTokenDelim(x); }).map((x) => { - return (x as TokenIdent | TokenDelim)[1]; + return x[1]; }).join(''); } diff --git a/packages/color-helpers/CHANGELOG.md b/packages/color-helpers/CHANGELOG.md index be466bbe8..527c68f28 100644 --- a/packages/color-helpers/CHANGELOG.md +++ b/packages/color-helpers/CHANGELOG.md @@ -1,5 +1,9 @@ # Changes to Color Helpers +### Unreleased (patch) + +- Optimize matrix multiplication + ### 4.2.0 _April 21, 2024_ diff --git a/packages/color-helpers/dist/index.cjs b/packages/color-helpers/dist/index.cjs index 866bd1dfe..aef73c91c 100644 --- a/packages/color-helpers/dist/index.cjs +++ b/packages/color-helpers/dist/index.cjs @@ -1,19 +1,10 @@ -"use strict"; -/** - * Simple matrix (and vector) multiplication - * Warning: No error handling for incompatible dimensions! - * @author Lea Verou 2020 MIT License - * - * @license W3C https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document - * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/multiply-matrices.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). - * @see https://github.com/w3c/csswg-drafts/blob/main/css-color-4/multiply-matrices.js - */function multiplyMatrices(t,o){const _=t.length;let e,n;e=Array.isArray(t[0])?t:[t],n=Array.isArray(o[0])?o:o.map((t=>[t]));const r=n[0].length,a=n[0].map(((t,o)=>n.map((t=>t[o]))));let i=e.map((t=>a.map((o=>Array.isArray(t)?t.reduce(((t,_,e)=>t+_*(o[e]||0)),0):o.reduce(((o,_)=>o+_*t),0)))));return 1===_&&(i=i[0]),1===r?i.map((t=>t[0])):i} +"use strict";function multiplyMatrices(t,o){return[t[0]*o[0]+t[1]*o[1]+t[2]*o[2],t[3]*o[0]+t[4]*o[1]+t[5]*o[2],t[6]*o[0]+t[7]*o[1]+t[8]*o[2]]}const t=[1.0479297925449969,.022946870601609652,-.05019226628920524,.02962780877005599,.9904344267538799,-.017073799063418826,-.009243040646204504,.015055191490298152,.7518742814281371]; /** * Bradford chromatic adaptation from D65 to D50 * @license W3C https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). * @see http://www.brucelindbloom.com/index.html?Eqn_ChromAdapt.html - */function D65_to_D50(t){return multiplyMatrices([[1.0479297925449969,.022946870601609652,-.05019226628920524],[.02962780877005599,.9904344267538799,-.017073799063418826],[-.009243040646204504,.015055191490298152,.7518742814281371]],t)} + */function D65_to_D50(o){return multiplyMatrices(t,o)} /** * @param {number} hue - Hue as degrees 0..360 * @param {number} sat - Saturation as percentage 0..100 @@ -23,7 +14,7 @@ * @license W3C https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/hslToRgb.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). * @see https://github.com/w3c/csswg-drafts/blob/main/css-color-4/hslToRgb.js - */function HSL_to_sRGB(t){let o=t[0],_=t[1],e=t[2];function f(t){const n=(t+o/30)%12,r=_*Math.min(e,1-e);return e-r*Math.max(-1,Math.min(n-3,9-n,1))}return o%=360,o<0&&(o+=360),_/=100,e/=100,[f(0),f(8),f(4)]} + */function HSL_to_sRGB(t){let o=t[0],_=t[1],n=t[2];function f(t){const e=(t+o/30)%12,r=_*Math.min(n,1-n);return n-r*Math.max(-1,Math.min(e-3,9-e,1))}return o%=360,o<0&&(o+=360),_/=100,n/=100,[f(0),f(8),f(4)]} /** * @param {number} hue - Hue as degrees 0..360 * @param {number} white - Whiteness as percentage 0..100 @@ -33,29 +24,30 @@ * @license W3C https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/hwbToRgb.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). * @see https://github.com/w3c/csswg-drafts/blob/main/css-color-4/hwbToRgb.js - */function HWB_to_sRGB(t){const o=t[0];let _=t[1],e=t[2];if(_/=100,e/=100,_+e>=1){const t=_/(_+e);return[t,t,t]}const n=HSL_to_sRGB([o,100,50]);for(let t=0;t<3;t++)n[t]*=1-_-e,n[t]+=_;return n} + */function HWB_to_sRGB(t){const o=t[0];let _=t[1],n=t[2];if(_/=100,n/=100,_+n>=1){const t=_/(_+n);return[t,t,t]}const e=HSL_to_sRGB([o,100,50]);for(let t=0;t<3;t++)e[t]*=1-_-n,e[t]+=_;return e} /** * @license W3C https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). - */const t=[.3457/.3585,1,.2958/.3585]; + */const o=[.3457/.3585,1,.2958/.3585]; /** * Convert Lab to D50-adapted XYZ * @license W3C https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). * @see http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html - */function Lab_to_XYZ(o){const _=24389/27,e=216/24389,n=[];n[1]=(o[0]+16)/116,n[0]=o[1]/500+n[1],n[2]=n[1]-o[2]/200;return[Math.pow(n[0],3)>e?Math.pow(n[0],3):(116*n[0]-16)/_,o[0]>8?Math.pow((o[0]+16)/116,3):o[0]/_,Math.pow(n[2],3)>e?Math.pow(n[2],3):(116*n[2]-16)/_].map(((o,_)=>o*t[_]))} + */function Lab_to_XYZ(t){const _=24389/27,n=216/24389,e=[];e[1]=(t[0]+16)/116,e[0]=t[1]/500+e[1],e[2]=e[1]-t[2]/200;return[Math.pow(e[0],3)>n?Math.pow(e[0],3):(116*e[0]-16)/_,t[0]>8?Math.pow((t[0]+16)/116,3):t[0]/_,Math.pow(e[2],3)>n?Math.pow(e[2],3):(116*e[2]-16)/_].map(((t,_)=>t*o[_]))} /** * @license W3C https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). * @see https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js - */function OKLCH_to_OKLab(t){return[t[0],t[1]*Math.cos(t[2]*Math.PI/180),t[1]*Math.sin(t[2]*Math.PI/180)]} + */function OKLCH_to_OKLab(t){return[t[0],t[1]*Math.cos(t[2]*Math.PI/180),t[1]*Math.sin(t[2]*Math.PI/180)]}const _=[1.2268798758459243,-.5578149944602171,.2813910456659647,-.0405757452148008,1.112286803280317,-.0717110580655164,-.0763729366746601,-.4214933324022432,1.5869240198367816],n=[1,.3963377773761749,.2158037573099136,1,-.1055613458156586,-.0638541728258133,1,-.0894841775298119,-1.2914855480194092]; /** * Given OKLab, convert to XYZ relative to D65 * * @license W3C https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). * @see https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js - */function OKLab_to_XYZ(t){const o=multiplyMatrices([[1,.3963377773761749,.2158037573099136],[1,-.1055613458156586,-.0638541728258133],[1,-.0894841775298119,-1.2914855480194092]],t);return multiplyMatrices([[1.2268798758459243,-.5578149944602171,.2813910456659647],[-.0405757452148008,1.112286803280317,-.0717110580655164],[-.0763729366746601,-.4214933324022432,1.5869240198367816]],o.map((t=>t**3)))} + */ +function OKLab_to_XYZ(t){const o=multiplyMatrices(n,t);return multiplyMatrices(_,[o[0]**3,o[1]**3,o[2]**3])} /** * Convert an array of rec2020 RGB values in the range 0.0 - 1.0 * to linear light (un-companded) form. @@ -63,7 +55,7 @@ * * @license W3C https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). - */function lin_2020(t){const o=1.09929682680944;return t.map((function(t){const _=t<0?-1:1,e=Math.abs(t);return e<.08124285829863151?t/4.5:_*Math.pow((e+o-1)/o,1/.45)}))} + */function lin_2020(t){const o=1.09929682680944;return t.map((function(t){const _=t<0?-1:1,n=Math.abs(t);return n<.08124285829863151?t/4.5:_*Math.pow((n+o-1)/o,1/.45)}))}const e=[63426534/99577255,20160776/139408157,47086771/278816314,26158966/99577255,.677998071518871,8267143/139408157,0,19567812/697040785,1.0609850577107909]; /** * Convert an array of linear-light rec2020 values to CIE XYZ * using D65 (no chromatic adaptation) @@ -90,7 +82,7 @@ function lin_sRGB(t){return t.map((function(t){const o=t<0?-1:1,_=Math.abs(t);re * * @license W3C https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). - */function lin_P3(t){return lin_sRGB(t)} + */function lin_P3(t){return lin_sRGB(t)}const r=[608311/1250200,189793/714400,198249/1000160,35783/156275,247089/357200,198249/2500400,0,32229/714400,5220557/5000800]; /** * Convert an array of linear-light display-p3 values to CIE XYZ * using D65 (no chromatic adaptation) @@ -98,7 +90,7 @@ function lin_sRGB(t){return t.map((function(t){const o=t<0?-1:1,_=Math.abs(t);re * @license W3C https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). * @see http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html - */function lin_P3_to_XYZ(t){return multiplyMatrices([[608311/1250200,189793/714400,198249/1000160],[35783/156275,247089/357200,198249/2500400],[0,32229/714400,5220557/5000800]],t)} + */function lin_P3_to_XYZ(t){return multiplyMatrices(r,t)} /** * Convert an array of prophoto-rgb values where in-gamut Colors are in the * range [0.0 - 1.0] to linear light (un-companded) form. Transfer curve is @@ -106,25 +98,46 @@ function lin_sRGB(t){return t.map((function(t){const o=t<0?-1:1,_=Math.abs(t);re * * @license W3C https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). - */ + */const a=[.7977666449006423,.13518129740053308,.0313477341283922,.2880748288194013,.711835234241873,8993693872564e-17,0,0,.8251046025104602]; +/** + * Convert an array of linear-light prophoto-rgb values to CIE D50 XYZ. + * Matrix cannot be expressed in rational form, but is calculated to 64 bit accuracy. + * + * @license W3C https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document + * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). + * @see see https://github.com/w3c/csswg-drafts/issues/7675 + */const i=[573536/994567,263643/1420810,187206/994567,591459/1989134,6239551/9945670,374412/4972835,53769/1989134,351524/4972835,4929758/4972835]; +/** + * Convert an array of linear-light a98-rgb values to CIE XYZ + * http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html + * has greater numerical precision than section 4.3.5.3 of + * https://www.adobe.com/digitalimag/pdfs/AdobeRGB1998.pdf + * but the values below were calculated from first principles + * from the chromaticity coordinates of R G B W + * + * @license W3C https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document + * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). + * @see http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html + * @see https://www.adobe.com/digitalimag/pdfs/AdobeRGB1998.pdf + * @see https://github.com/w3c/csswg-drafts/blob/main/css-color-4/matrixmaker.html + */const s=[506752/1228815,87881/245763,12673/70218,87098/409605,175762/245763,12673/175545,7918/409605,87881/737289,1001167/1053270]; /** * Convert an array of linear-light sRGB values to CIE XYZ * using sRGB's own white, D65 (no chromatic adaptation) * * @license W3C https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). - */ -function lin_sRGB_to_XYZ(t){return multiplyMatrices([[506752/1228815,87881/245763,12673/70218],[87098/409605,175762/245763,12673/175545],[7918/409605,87881/737289,1001167/1053270]],t)} + */function lin_sRGB_to_XYZ(t){return multiplyMatrices(s,t)}const l=[.955473421488075,-.02309845494876471,.06325924320057072,-.0283697093338637,1.0099953980813041,.021041441191917323,.012314014864481998,-.020507649298898964,1.330365926242124]; /** * Bradford chromatic adaptation from D50 to D65 * * @license W3C https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). - */function D50_to_D65(t){return multiplyMatrices([[.955473421488075,-.02309845494876471,.06325924320057072],[-.0283697093338637,1.0099953980813041,.021041441191917323],[.012314014864481998,-.020507649298898964,1.330365926242124]],t)} + */function D50_to_D65(t){return multiplyMatrices(l,t)}const u=[12831/3959,-329/214,-1974/3959,-851781/878810,1648619/878810,36519/878810,705/12673,-2585/12673,705/667]; /** * @license W3C https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). - */function XYZ_to_lin_sRGB(t){return multiplyMatrices([[12831/3959,-329/214,-1974/3959],[-851781/878810,1648619/878810,36519/878810],[705/12673,-2585/12673,705/667]],t)} + */function XYZ_to_lin_sRGB(t){return multiplyMatrices(u,t)} /** * Convert an array of linear-light sRGB values in the range 0.0-1.0 to gamma corrected form * Extended transfer function: @@ -148,13 +161,13 @@ function lin_sRGB_to_XYZ(t){return multiplyMatrices([[506752/1228815,87881/24576 * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/utilities.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). * * @see https://github.com/w3c/csswg-drafts/blob/main/css-color-4/better-rgbToHsl.js - */function sRGB_to_HSL(t){const o=t[0],_=t[1],e=t[2],n=Math.max(o,_,e),r=Math.min(o,_,e),a=(r+n)/2,i=n-r;let l=NaN,s=0;if(0!==Math.round(1e5*i)){switch(s=0===Math.round(1e5*a)||1e5===Math.round(1e5*a)?0:(n-a)/Math.min(a,1-a),n){case o:l=(_-e)/i+(_=360&&(l-=360),[l,100*s,100*a]} + */function sRGB_to_HSL(t){const o=t[0],_=t[1],n=t[2],e=Math.max(o,_,n),r=Math.min(o,_,n),a=(r+e)/2,i=e-r;let s=NaN,l=0;if(0!==Math.round(1e5*i)){switch(l=0===Math.round(1e5*a)||1e5===Math.round(1e5*a)?0:(e-a)/Math.min(a,1-a),e){case o:s=(_-n)/i+(_=360&&(s-=360),[s,100*l,100*a]}const c=[446124/178915,-333277/357830,-72051/178915,-14852/17905,63121/35810,423/17905,11844/330415,-50337/660830,316169/330415]; /** * Convert XYZ to linear-light P3 * * @license W3C https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). - */function XYZ_to_lin_P3(t){return multiplyMatrices([[446124/178915,-333277/357830,-72051/178915],[-14852/17905,63121/35810,423/17905],[11844/330415,-50337/660830,316169/330415]],t)} + */function XYZ_to_lin_P3(t){return multiplyMatrices(c,t)} /** * Convert an array of linear-light display-p3 RGB in the range 0.0-1.0 * to gamma corrected form @@ -168,14 +181,15 @@ function lin_sRGB_to_XYZ(t){return multiplyMatrices([[506752/1228815,87881/24576 * * @license W3C https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). - */function XYZ_to_Lab(o){const _=216/24389,e=24389/27,n=o.map(((o,_)=>o/t[_])).map((t=>t>_?Math.cbrt(t):(e*t+16)/116));return[116*n[1]-16,500*(n[0]-n[1]),200*(n[1]-n[2])]} + */function XYZ_to_Lab(t){const _=216/24389,n=24389/27,e=t.map(((t,_)=>t/o[_])).map((t=>t>_?Math.cbrt(t):(n*t+16)/116));return[116*e[1]-16,500*(e[0]-e[1]),200*(e[1]-e[2])]}const p=[.819022437996703,.3619062600528904,-.1288737815209879,.0329836539323885,.9292868615863434,.0361446663506424,.0481771893596242,.2642395317527308,.6335478284694309],m=[.210454268309314,.7936177747023054,-.0040720430116193,1.9779985324311684,-2.42859224204858,.450593709617411,.0259040424655478,.7827717124575296,-.8086757549230774]; /** * @license W3C https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). * * XYZ <-> LMS matrices recalculated for consistent reference white * @see https://github.com/w3c/csswg-drafts/issues/6642#issuecomment-943521484 - */function XYZ_to_OKLab(t){const o=multiplyMatrices([[.819022437996703,.3619062600528904,-.1288737815209879],[.0329836539323885,.9292868615863434,.0361446663506424],[.0481771893596242,.2642395317527308,.6335478284694309]],t);return multiplyMatrices([[.210454268309314,.7936177747023054,-.0040720430116193],[1.9779985324311684,-2.42859224204858,.450593709617411],[.0259040424655478,.7827717124575296,-.8086757549230774]],o.map((t=>Math.cbrt(t))))} + */ +function XYZ_to_OKLab(t){const o=multiplyMatrices(p,t);return multiplyMatrices(m,[Math.cbrt(o[0]),Math.cbrt(o[1]),Math.cbrt(o[2])])} /** * @license W3C https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). @@ -184,12 +198,18 @@ function lin_sRGB_to_XYZ(t){return multiplyMatrices([[506752/1228815,87881/24576 * @license W3C https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). * @see https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js - */function OKLab_to_OKLCH(t){const o=180*Math.atan2(t[2],t[1])/Math.PI;return[t[0],Math.sqrt(t[1]**2+t[2]**2),o>=0?o:o+360]} + */function OKLab_to_OKLCH(t){const o=180*Math.atan2(t[2],t[1])/Math.PI;return[t[0],Math.sqrt(t[1]**2+t[2]**2),o>=0?o:o+360]}const h=[1829569/896150,-506331/896150,-308931/896150,-851781/878810,1648619/878810,36519/878810,16779/1248040,-147721/1248040,1266979/1248040]; /** * Convert XYZ to linear-light a98-rgb * * @license W3C https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). + */const D=[30757411/17917100,-6372589/17917100,-4539589/17917100,-.666684351832489,1.616481236634939,467509/29648200,792561/44930125,-1921689/44930125,.942103121235474]; +/** + * Convert XYZ to linear-light rec2020 + * + * @license W3C https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document + * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). */ /** * Convert an array of linear-light rec2020 RGB in the range 0.0-1.0 @@ -198,7 +218,7 @@ function lin_sRGB_to_XYZ(t){return multiplyMatrices([[506752/1228815,87881/24576 * @license W3C https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). */ -function gam_2020(t){const o=1.09929682680944;return t.map((function(t){const _=t<0?-1:1,e=Math.abs(t);return e>.018053968510807?_*(o*Math.pow(e,.45)-(o-1)):4.5*t}))} +function gam_2020(t){const o=1.09929682680944;return t.map((function(t){const _=t<0?-1:1,n=Math.abs(t);return n>.018053968510807?_*(o*Math.pow(n,.45)-(o-1)):4.5*t}))}const X=[1.3457868816471583,-.25557208737979464,-.05110186497554526,-.5446307051249019,1.5082477428451468,.02052744743642139,0,0,1.2119675456389452]; /** * Convert D50 XYZ to linear-light prophoto-rgb * @@ -214,7 +234,7 @@ function gam_2020(t){const o=1.09929682680944;return t.map((function(t){const _= * @license W3C https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). */ -function gam_ProPhoto(t){const o=1/512;return t.map((function(t){const _=t<0?-1:1,e=Math.abs(t);return e>=o?_*Math.pow(e,1/1.8):16*t}))}function inGamut(t){const[o,_,e]=t;return o>=-1e-4&&o<=1.0001&&_>=-1e-4&&_<=1.0001&&e>=-1e-4&&e<=1.0001}function clip(t){return t.map((t=>t<0?0:t>1?1:t))} +function gam_ProPhoto(t){const o=1/512;return t.map((function(t){const _=t<0?-1:1,n=Math.abs(t);return n>=o?_*Math.pow(n,1/1.8):16*t}))}function inGamut(t){const[o,_,n]=t;return o>=-1e-4&&o<=1.0001&&_>=-1e-4&&_<=1.0001&&n>=-1e-4&&n<=1.0001}function clip(t){return t.map((t=>t<0?0:t>1?1:t))} /** * @description Calculate deltaE OK which is the simple root sum of squares * @param {number[]} reference - Array of OKLab values: L as 0..1, a and b as -1..1 @@ -224,7 +244,7 @@ function gam_ProPhoto(t){const o=1/512;return t.map((function(t){const _=t<0?-1: * @license W3C https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/deltaEOK.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). * @see https://github.com/w3c/csswg-drafts/blob/main/css-color-4/deltaEOK.js - */function deltaEOK(t,o){const[_,e,n]=t,[r,a,i]=o,l=_-r,s=e-a,u=n-i;return Math.sqrt(l**2+s**2+u**2)}const o=.02,_=1e-4;function rayTraceBox(t,o){let _=1/0,e=-1/0;const n=[];for(let r=0;r<3;r++){const a=t[r],i=o[r]-a;n.push(i);const l=0,s=1;if(i){const t=1/i,o=(l-a)*t,n=(s-a)*t;e=Math.max(Math.min(o,n),e),_=Math.min(Math.max(o,n),_)}else if(as)return!1}return!(e>_||_<0)&&(e<0&&(e=_),!!isFinite(e)&&[t[0]+n[0]*e,t[1]+n[1]*e,t[2]+n[2]*e])}function luminance(t){const[o,_,e]=t.map((t=>t<=.03928?t/12.92:Math.pow((t+.055)/1.055,2.4)));return.2126*o+.7152*_+.0722*e}exports.HSL_to_XYZ_D50=function HSL_to_XYZ_D50(t){let o=t;return o=HSL_to_sRGB(o),o=lin_sRGB(o),o=lin_sRGB_to_XYZ(o),o=D65_to_D50(o),o},exports.HWB_to_XYZ_D50=function HWB_to_XYZ_D50(t){let o=t;return o=HWB_to_sRGB(o),o=lin_sRGB(o),o=lin_sRGB_to_XYZ(o),o=D65_to_D50(o),o},exports.LCH_to_XYZ_D50=function LCH_to_XYZ_D50(t){let o=t;var _;return o=[(_=o)[0],_[1]*Math.cos(_[2]*Math.PI/180),_[1]*Math.sin(_[2]*Math.PI/180)],o=Lab_to_XYZ(o),o},exports.Lab_to_XYZ_D50=function Lab_to_XYZ_D50(t){let o=t;return o=Lab_to_XYZ(o),o},exports.OKLCH_to_OKLab=OKLCH_to_OKLab,exports.OKLCH_to_XYZ_D50=function OKLCH_to_XYZ_D50(t){let o=t;return o=OKLCH_to_OKLab(o),o=OKLab_to_XYZ(o),o=D65_to_D50(o),o},exports.OKLab_to_OKLCH=OKLab_to_OKLCH,exports.OKLab_to_XYZ=OKLab_to_XYZ,exports.OKLab_to_XYZ_D50=function OKLab_to_XYZ_D50(t){let o=t;return o=OKLab_to_XYZ(o),o=D65_to_D50(o),o},exports.P3_to_XYZ_D50=function P3_to_XYZ_D50(t){let o=t;return o=lin_P3(o),o=lin_P3_to_XYZ(o),o=D65_to_D50(o),o},exports.ProPhoto_RGB_to_XYZ_D50=function ProPhoto_RGB_to_XYZ_D50(t){let o=t;return o=o.map((function(t){const o=t<0?-1:1,_=Math.abs(t);return _<=.03125?t/16:o*Math.pow(_,1.8)})),o=multiplyMatrices([[.7977666449006423,.13518129740053308,.0313477341283922],[.2880748288194013,.711835234241873,8993693872564e-17],[0,0,.8251046025104602]],o),o},exports.XYZ_D50_to_HSL=function XYZ_D50_to_HSL(t){let o=t;return o=D50_to_D65(o),o=XYZ_to_lin_sRGB(o),o=gam_sRGB(o),o=sRGB_to_HSL(o),o},exports.XYZ_D50_to_HWB=function XYZ_D50_to_HWB(t){let o=t;o=D50_to_D65(o),o=XYZ_to_lin_sRGB(o);const _=gam_sRGB(o);o=sRGB_to_HSL(_);const e=Math.min(_[0],_[1],_[2]),n=1-Math.max(_[0],_[1],_[2]);return[o[0],100*e,100*n]},exports.XYZ_D50_to_LCH=function XYZ_D50_to_LCH(t){let o=t;return o=XYZ_to_Lab(o),o=Lab_to_LCH(o),o},exports.XYZ_D50_to_Lab=function XYZ_D50_to_Lab(t){let o=t;return o=XYZ_to_Lab(o),o},exports.XYZ_D50_to_OKLCH=function XYZ_D50_to_OKLCH(t){let o=t;return o=D50_to_D65(o),o=XYZ_to_OKLab(o),o=OKLab_to_OKLCH(o),o},exports.XYZ_D50_to_OKLab=function XYZ_D50_to_OKLab(t){let o=t;return o=D50_to_D65(o),o=XYZ_to_OKLab(o),o},exports.XYZ_D50_to_P3=function XYZ_D50_to_P3(t){let o=t;return o=D50_to_D65(o),o=XYZ_to_lin_P3(o),o=gam_P3(o),o},exports.XYZ_D50_to_ProPhoto=function XYZ_D50_to_ProPhoto(t){let o=t;return o=multiplyMatrices([[1.3457868816471583,-.25557208737979464,-.05110186497554526],[-.5446307051249019,1.5082477428451468,.02052744743642139],[0,0,1.2119675456389452]],o),o=gam_ProPhoto(o),o},exports.XYZ_D50_to_XYZ_D50=function XYZ_D50_to_XYZ_D50(t){return t},exports.XYZ_D50_to_XYZ_D65=function XYZ_D50_to_XYZ_D65(t){let o=t;return o=D50_to_D65(o),o},exports.XYZ_D50_to_a98_RGB=function XYZ_D50_to_a98_RGB(t){let o=t;return o=D50_to_D65(o),o=multiplyMatrices([[1829569/896150,-506331/896150,-308931/896150],[-851781/878810,1648619/878810,36519/878810],[16779/1248040,-147721/1248040,1266979/1248040]],o),o=o.map((function(t){const o=t<0?-1:1,_=Math.abs(t);return o*Math.pow(_,256/563)})),o},exports.XYZ_D50_to_lin_sRGB=function XYZ_D50_to_lin_sRGB(t){let o=t;return o=D50_to_D65(o),o=XYZ_to_lin_sRGB(o),o},exports.XYZ_D50_to_rec_2020=function XYZ_D50_to_rec_2020(t){let o=t;return o=D50_to_D65(o),o=multiplyMatrices([[30757411/17917100,-6372589/17917100,-4539589/17917100],[-.666684351832489,1.616481236634939,467509/29648200],[792561/44930125,-1921689/44930125,.942103121235474]],o),o=gam_2020(o),o},exports.XYZ_D50_to_sRGB=function XYZ_D50_to_sRGB(t){let o=t;return o=D50_to_D65(o),o=XYZ_to_lin_sRGB(o),o=gam_sRGB(o),o},exports.XYZ_D65_to_XYZ_D50=function XYZ_D65_to_XYZ_D50(t){let o=t;return o=D65_to_D50(o),o},exports.XYZ_to_OKLab=XYZ_to_OKLab,exports.XYZ_to_lin_P3=XYZ_to_lin_P3,exports.XYZ_to_lin_sRGB=XYZ_to_lin_sRGB,exports.a98_RGB_to_XYZ_D50=function a98_RGB_to_XYZ_D50(t){let o=t;return o=o.map((function(t){const o=t<0?-1:1,_=Math.abs(t);return o*Math.pow(_,563/256)})),o=multiplyMatrices([[573536/994567,263643/1420810,187206/994567],[591459/1989134,6239551/9945670,374412/4972835],[53769/1989134,351524/4972835,4929758/4972835]],o),o=D65_to_D50(o),o},exports.clip=clip,exports.contrast_ratio_wcag_2_1=function contrast_ratio_wcag_2_1(t,o){const _=luminance(t),e=luminance(o);return(Math.max(_,e)+.05)/(Math.min(_,e)+.05)},exports.gam_P3=gam_P3,exports.gam_sRGB=gam_sRGB,exports.inGamut=inGamut,exports.lin_P3=lin_P3,exports.lin_P3_to_XYZ=lin_P3_to_XYZ,exports.lin_sRGB=lin_sRGB,exports.lin_sRGB_to_XYZ=lin_sRGB_to_XYZ,exports.lin_sRGB_to_XYZ_D50=function lin_sRGB_to_XYZ_D50(t){let o=t;return o=lin_sRGB_to_XYZ(o),o=D65_to_D50(o),o},exports.mapGamut=function mapGamut(t,e,n){const r=t;let a=clip(e(r)),i=deltaEOK(OKLCH_to_OKLab(n(a)),OKLCH_to_OKLab(r));if(i_;){const t=(l+s)/2;if(r[1]=t,u&&inGamut(e(r)))l=t;else if(a=clip(e(r)),i=deltaEOK(OKLCH_to_OKLab(n(a)),OKLCH_to_OKLab(r)),il)return!1}return!(n>_||_<0)&&(n<0&&(n=_),!!isFinite(n)&&[t[0]+e[0]*n,t[1]+e[1]*n,t[2]+e[2]*n])}function luminance(t){const[o,_,n]=t.map((t=>t<=.03928?t/12.92:Math.pow((t+.055)/1.055,2.4)));return.2126*o+.7152*_+.0722*n}exports.HSL_to_XYZ_D50=function HSL_to_XYZ_D50(t){let o=t;return o=HSL_to_sRGB(o),o=lin_sRGB(o),o=lin_sRGB_to_XYZ(o),o=D65_to_D50(o),o},exports.HWB_to_XYZ_D50=function HWB_to_XYZ_D50(t){let o=t;return o=HWB_to_sRGB(o),o=lin_sRGB(o),o=lin_sRGB_to_XYZ(o),o=D65_to_D50(o),o},exports.LCH_to_XYZ_D50=function LCH_to_XYZ_D50(t){let o=t;var _;return o=[(_=o)[0],_[1]*Math.cos(_[2]*Math.PI/180),_[1]*Math.sin(_[2]*Math.PI/180)],o=Lab_to_XYZ(o),o},exports.Lab_to_XYZ_D50=function Lab_to_XYZ_D50(t){let o=t;return o=Lab_to_XYZ(o),o},exports.OKLCH_to_OKLab=OKLCH_to_OKLab,exports.OKLCH_to_XYZ_D50=function OKLCH_to_XYZ_D50(t){let o=t;return o=OKLCH_to_OKLab(o),o=OKLab_to_XYZ(o),o=D65_to_D50(o),o},exports.OKLab_to_OKLCH=OKLab_to_OKLCH,exports.OKLab_to_XYZ=OKLab_to_XYZ,exports.OKLab_to_XYZ_D50=function OKLab_to_XYZ_D50(t){let o=t;return o=OKLab_to_XYZ(o),o=D65_to_D50(o),o},exports.P3_to_XYZ_D50=function P3_to_XYZ_D50(t){let o=t;return o=lin_P3(o),o=lin_P3_to_XYZ(o),o=D65_to_D50(o),o},exports.ProPhoto_RGB_to_XYZ_D50=function ProPhoto_RGB_to_XYZ_D50(t){let o=t;return o=o.map((function(t){const o=t<0?-1:1,_=Math.abs(t);return _<=.03125?t/16:o*Math.pow(_,1.8)})),o=multiplyMatrices(a,o),o},exports.XYZ_D50_to_HSL=function XYZ_D50_to_HSL(t){let o=t;return o=D50_to_D65(o),o=XYZ_to_lin_sRGB(o),o=gam_sRGB(o),o=sRGB_to_HSL(o),o},exports.XYZ_D50_to_HWB=function XYZ_D50_to_HWB(t){let o=t;o=D50_to_D65(o),o=XYZ_to_lin_sRGB(o);const _=gam_sRGB(o);o=sRGB_to_HSL(_);const n=Math.min(_[0],_[1],_[2]),e=1-Math.max(_[0],_[1],_[2]);return[o[0],100*n,100*e]},exports.XYZ_D50_to_LCH=function XYZ_D50_to_LCH(t){let o=t;return o=XYZ_to_Lab(o),o=Lab_to_LCH(o),o},exports.XYZ_D50_to_Lab=function XYZ_D50_to_Lab(t){let o=t;return o=XYZ_to_Lab(o),o},exports.XYZ_D50_to_OKLCH=function XYZ_D50_to_OKLCH(t){let o=t;return o=D50_to_D65(o),o=XYZ_to_OKLab(o),o=OKLab_to_OKLCH(o),o},exports.XYZ_D50_to_OKLab=function XYZ_D50_to_OKLab(t){let o=t;return o=D50_to_D65(o),o=XYZ_to_OKLab(o),o},exports.XYZ_D50_to_P3=function XYZ_D50_to_P3(t){let o=t;return o=D50_to_D65(o),o=XYZ_to_lin_P3(o),o=gam_P3(o),o},exports.XYZ_D50_to_ProPhoto=function XYZ_D50_to_ProPhoto(t){let o=t;return o=multiplyMatrices(X,o),o=gam_ProPhoto(o),o},exports.XYZ_D50_to_XYZ_D50=function XYZ_D50_to_XYZ_D50(t){return t},exports.XYZ_D50_to_XYZ_D65=function XYZ_D50_to_XYZ_D65(t){let o=t;return o=D50_to_D65(o),o},exports.XYZ_D50_to_a98_RGB=function XYZ_D50_to_a98_RGB(t){let o=t;return o=D50_to_D65(o),o=multiplyMatrices(h,o),o=o.map((function(t){const o=t<0?-1:1,_=Math.abs(t);return o*Math.pow(_,256/563)})),o},exports.XYZ_D50_to_lin_sRGB=function XYZ_D50_to_lin_sRGB(t){let o=t;return o=D50_to_D65(o),o=XYZ_to_lin_sRGB(o),o},exports.XYZ_D50_to_rec_2020=function XYZ_D50_to_rec_2020(t){let o=t;return o=D50_to_D65(o),o=multiplyMatrices(D,o),o=gam_2020(o),o},exports.XYZ_D50_to_sRGB=function XYZ_D50_to_sRGB(t){let o=t;return o=D50_to_D65(o),o=XYZ_to_lin_sRGB(o),o=gam_sRGB(o),o},exports.XYZ_D65_to_XYZ_D50=function XYZ_D65_to_XYZ_D50(t){let o=t;return o=D65_to_D50(o),o},exports.XYZ_to_OKLab=XYZ_to_OKLab,exports.XYZ_to_lin_P3=XYZ_to_lin_P3,exports.XYZ_to_lin_sRGB=XYZ_to_lin_sRGB,exports.a98_RGB_to_XYZ_D50=function a98_RGB_to_XYZ_D50(t){let o=t;return o=o.map((function(t){const o=t<0?-1:1,_=Math.abs(t);return o*Math.pow(_,563/256)})),o=multiplyMatrices(i,o),o=D65_to_D50(o),o},exports.clip=clip,exports.contrast_ratio_wcag_2_1=function contrast_ratio_wcag_2_1(t,o){const _=luminance(t),n=luminance(o);return(Math.max(_,n)+.05)/(Math.min(_,n)+.05)},exports.gam_P3=gam_P3,exports.gam_sRGB=gam_sRGB,exports.inGamut=inGamut,exports.lin_P3=lin_P3,exports.lin_P3_to_XYZ=lin_P3_to_XYZ,exports.lin_sRGB=lin_sRGB,exports.lin_sRGB_to_XYZ=lin_sRGB_to_XYZ,exports.lin_sRGB_to_XYZ_D50=function lin_sRGB_to_XYZ_D50(t){let o=t;return o=lin_sRGB_to_XYZ(o),o=D65_to_D50(o),o},exports.mapGamut=function mapGamut(t,o,_){const n=t;let e=clip(o(n)),r=deltaEOK(OKLCH_to_OKLab(_(e)),OKLCH_to_OKLab(n));if(rZ;){const t=(a+i)/2;if(n[1]=t,s&&inGamut(o(n)))a=t;else if(e=clip(o(n)),r=deltaEOK(OKLCH_to_OKLab(_(e)),OKLCH_to_OKLab(n)),r0){const t=_(r);t[0]=e,t[2]=n,r=o(t)}const i=rayTraceBox(a,r.slice());if(!i)break;r=i.slice()}return clip(r)},exports.namedColors={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]},exports.rec_2020_to_XYZ_D50=function rec_2020_to_XYZ_D50(t){let o=t;return o=lin_2020(o),o=multiplyMatrices([[63426534/99577255,20160776/139408157,47086771/278816314],[26158966/99577255,.677998071518871,8267143/139408157],[0,19567812/697040785,1.0609850577107909]],o),o=D65_to_D50(o),o},exports.sRGB_to_XYZ_D50=function sRGB_to_XYZ_D50(t){let o=t;return o=lin_sRGB(o),o=lin_sRGB_to_XYZ(o),o=D65_to_D50(o),o}; + */,exports.mapGamutRayTrace=function mapGamutRayTrace(t,o,_){const n=t[0],e=t[2];let r=o(t);const a=o([n,0,e]);for(let t=0;t<4;t++){if(t>0){const t=_(r);t[0]=n,t[2]=e,r=o(t)}const i=rayTraceBox(a,r.slice());if(!i)break;r=i.slice()}return clip(r)},exports.namedColors={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]},exports.rec_2020_to_XYZ_D50=function rec_2020_to_XYZ_D50(t){let o=t;return o=lin_2020(o),o=multiplyMatrices(e,o),o=D65_to_D50(o),o},exports.sRGB_to_XYZ_D50=function sRGB_to_XYZ_D50(t){let o=t;return o=lin_sRGB(o),o=lin_sRGB_to_XYZ(o),o=D65_to_D50(o),o}; diff --git a/packages/color-helpers/dist/index.mjs b/packages/color-helpers/dist/index.mjs index 660ec0284..c5f779a02 100644 --- a/packages/color-helpers/dist/index.mjs +++ b/packages/color-helpers/dist/index.mjs @@ -1,19 +1,10 @@ -/** - * Simple matrix (and vector) multiplication - * Warning: No error handling for incompatible dimensions! - * @author Lea Verou 2020 MIT License - * - * @license W3C https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document - * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/multiply-matrices.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). - * @see https://github.com/w3c/csswg-drafts/blob/main/css-color-4/multiply-matrices.js - */ -function multiplyMatrices(t,n){const _=t.length;let o,e;o=Array.isArray(t[0])?t:[t],e=Array.isArray(n[0])?n:n.map((t=>[t]));const r=e[0].length,a=e[0].map(((t,n)=>e.map((t=>t[n]))));let i=o.map((t=>a.map((n=>Array.isArray(t)?t.reduce(((t,_,o)=>t+_*(n[o]||0)),0):n.reduce(((n,_)=>n+_*t),0)))));return 1===_&&(i=i[0]),1===r?i.map((t=>t[0])):i} +function multiplyMatrices(t,n){return[t[0]*n[0]+t[1]*n[1]+t[2]*n[2],t[3]*n[0]+t[4]*n[1]+t[5]*n[2],t[6]*n[0]+t[7]*n[1]+t[8]*n[2]]}const t=[1.0479297925449969,.022946870601609652,-.05019226628920524,.02962780877005599,.9904344267538799,-.017073799063418826,-.009243040646204504,.015055191490298152,.7518742814281371]; /** * Bradford chromatic adaptation from D65 to D50 * @license W3C https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). * @see http://www.brucelindbloom.com/index.html?Eqn_ChromAdapt.html - */function D65_to_D50(t){return multiplyMatrices([[1.0479297925449969,.022946870601609652,-.05019226628920524],[.02962780877005599,.9904344267538799,-.017073799063418826],[-.009243040646204504,.015055191490298152,.7518742814281371]],t)} + */function D65_to_D50(n){return multiplyMatrices(t,n)} /** * @param {number} hue - Hue as degrees 0..360 * @param {number} sat - Saturation as percentage 0..100 @@ -37,25 +28,26 @@ function multiplyMatrices(t,n){const _=t.length;let o,e;o=Array.isArray(t[0])?t: /** * @license W3C https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). - */const t=[.3457/.3585,1,.2958/.3585]; + */const n=[.3457/.3585,1,.2958/.3585]; /** * Convert Lab to D50-adapted XYZ * @license W3C https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). * @see http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html - */function Lab_to_XYZ(n){const _=24389/27,o=216/24389,e=[];e[1]=(n[0]+16)/116,e[0]=n[1]/500+e[1],e[2]=e[1]-n[2]/200;return[Math.pow(e[0],3)>o?Math.pow(e[0],3):(116*e[0]-16)/_,n[0]>8?Math.pow((n[0]+16)/116,3):n[0]/_,Math.pow(e[2],3)>o?Math.pow(e[2],3):(116*e[2]-16)/_].map(((n,_)=>n*t[_]))} + */function Lab_to_XYZ(t){const _=24389/27,o=216/24389,e=[];e[1]=(t[0]+16)/116,e[0]=t[1]/500+e[1],e[2]=e[1]-t[2]/200;return[Math.pow(e[0],3)>o?Math.pow(e[0],3):(116*e[0]-16)/_,t[0]>8?Math.pow((t[0]+16)/116,3):t[0]/_,Math.pow(e[2],3)>o?Math.pow(e[2],3):(116*e[2]-16)/_].map(((t,_)=>t*n[_]))} /** * @license W3C https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). * @see https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js - */function OKLCH_to_OKLab(t){return[t[0],t[1]*Math.cos(t[2]*Math.PI/180),t[1]*Math.sin(t[2]*Math.PI/180)]} + */function OKLCH_to_OKLab(t){return[t[0],t[1]*Math.cos(t[2]*Math.PI/180),t[1]*Math.sin(t[2]*Math.PI/180)]}const _=[1.2268798758459243,-.5578149944602171,.2813910456659647,-.0405757452148008,1.112286803280317,-.0717110580655164,-.0763729366746601,-.4214933324022432,1.5869240198367816],o=[1,.3963377773761749,.2158037573099136,1,-.1055613458156586,-.0638541728258133,1,-.0894841775298119,-1.2914855480194092]; /** * Given OKLab, convert to XYZ relative to D65 * * @license W3C https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). * @see https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js - */function OKLab_to_XYZ(t){const n=multiplyMatrices([[1,.3963377773761749,.2158037573099136],[1,-.1055613458156586,-.0638541728258133],[1,-.0894841775298119,-1.2914855480194092]],t);return multiplyMatrices([[1.2268798758459243,-.5578149944602171,.2813910456659647],[-.0405757452148008,1.112286803280317,-.0717110580655164],[-.0763729366746601,-.4214933324022432,1.5869240198367816]],n.map((t=>t**3)))} + */ +function OKLab_to_XYZ(t){const n=multiplyMatrices(o,t);return multiplyMatrices(_,[n[0]**3,n[1]**3,n[2]**3])} /** * Convert an array of rec2020 RGB values in the range 0.0 - 1.0 * to linear light (un-companded) form. @@ -63,7 +55,7 @@ function multiplyMatrices(t,n){const _=t.length;let o,e;o=Array.isArray(t[0])?t: * * @license W3C https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). - */function lin_2020(t){const n=1.09929682680944;return t.map((function(t){const _=t<0?-1:1,o=Math.abs(t);return o<.08124285829863151?t/4.5:_*Math.pow((o+n-1)/n,1/.45)}))} + */function lin_2020(t){const n=1.09929682680944;return t.map((function(t){const _=t<0?-1:1,o=Math.abs(t);return o<.08124285829863151?t/4.5:_*Math.pow((o+n-1)/n,1/.45)}))}const e=[63426534/99577255,20160776/139408157,47086771/278816314,26158966/99577255,.677998071518871,8267143/139408157,0,19567812/697040785,1.0609850577107909]; /** * Convert an array of linear-light rec2020 values to CIE XYZ * using D65 (no chromatic adaptation) @@ -90,7 +82,7 @@ function lin_sRGB(t){return t.map((function(t){const n=t<0?-1:1,_=Math.abs(t);re * * @license W3C https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). - */function lin_P3(t){return lin_sRGB(t)} + */function lin_P3(t){return lin_sRGB(t)}const r=[608311/1250200,189793/714400,198249/1000160,35783/156275,247089/357200,198249/2500400,0,32229/714400,5220557/5000800]; /** * Convert an array of linear-light display-p3 values to CIE XYZ * using D65 (no chromatic adaptation) @@ -98,7 +90,7 @@ function lin_sRGB(t){return t.map((function(t){const n=t<0?-1:1,_=Math.abs(t);re * @license W3C https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). * @see http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html - */function lin_P3_to_XYZ(t){return multiplyMatrices([[608311/1250200,189793/714400,198249/1000160],[35783/156275,247089/357200,198249/2500400],[0,32229/714400,5220557/5000800]],t)} + */function lin_P3_to_XYZ(t){return multiplyMatrices(r,t)} /** * Convert an array of prophoto-rgb values where in-gamut Colors are in the * range [0.0 - 1.0] to linear light (un-companded) form. Transfer curve is @@ -106,25 +98,46 @@ function lin_sRGB(t){return t.map((function(t){const n=t<0?-1:1,_=Math.abs(t);re * * @license W3C https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). - */ + */const a=[.7977666449006423,.13518129740053308,.0313477341283922,.2880748288194013,.711835234241873,8993693872564e-17,0,0,.8251046025104602]; +/** + * Convert an array of linear-light prophoto-rgb values to CIE D50 XYZ. + * Matrix cannot be expressed in rational form, but is calculated to 64 bit accuracy. + * + * @license W3C https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document + * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). + * @see see https://github.com/w3c/csswg-drafts/issues/7675 + */const i=[573536/994567,263643/1420810,187206/994567,591459/1989134,6239551/9945670,374412/4972835,53769/1989134,351524/4972835,4929758/4972835]; +/** + * Convert an array of linear-light a98-rgb values to CIE XYZ + * http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html + * has greater numerical precision than section 4.3.5.3 of + * https://www.adobe.com/digitalimag/pdfs/AdobeRGB1998.pdf + * but the values below were calculated from first principles + * from the chromaticity coordinates of R G B W + * + * @license W3C https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document + * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). + * @see http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html + * @see https://www.adobe.com/digitalimag/pdfs/AdobeRGB1998.pdf + * @see https://github.com/w3c/csswg-drafts/blob/main/css-color-4/matrixmaker.html + */const l=[506752/1228815,87881/245763,12673/70218,87098/409605,175762/245763,12673/175545,7918/409605,87881/737289,1001167/1053270]; /** * Convert an array of linear-light sRGB values to CIE XYZ * using sRGB's own white, D65 (no chromatic adaptation) * * @license W3C https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). - */ -function lin_sRGB_to_XYZ(t){return multiplyMatrices([[506752/1228815,87881/245763,12673/70218],[87098/409605,175762/245763,12673/175545],[7918/409605,87881/737289,1001167/1053270]],t)} + */function lin_sRGB_to_XYZ(t){return multiplyMatrices(l,t)}const u=[.955473421488075,-.02309845494876471,.06325924320057072,-.0283697093338637,1.0099953980813041,.021041441191917323,.012314014864481998,-.020507649298898964,1.330365926242124]; /** * Bradford chromatic adaptation from D50 to D65 * * @license W3C https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). - */function D50_to_D65(t){return multiplyMatrices([[.955473421488075,-.02309845494876471,.06325924320057072],[-.0283697093338637,1.0099953980813041,.021041441191917323],[.012314014864481998,-.020507649298898964,1.330365926242124]],t)} + */function D50_to_D65(t){return multiplyMatrices(u,t)}const c=[12831/3959,-329/214,-1974/3959,-851781/878810,1648619/878810,36519/878810,705/12673,-2585/12673,705/667]; /** * @license W3C https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). - */function XYZ_to_lin_sRGB(t){return multiplyMatrices([[12831/3959,-329/214,-1974/3959],[-851781/878810,1648619/878810,36519/878810],[705/12673,-2585/12673,705/667]],t)} + */function XYZ_to_lin_sRGB(t){return multiplyMatrices(c,t)} /** * Convert an array of linear-light sRGB values in the range 0.0-1.0 to gamma corrected form * Extended transfer function: @@ -148,13 +161,13 @@ function lin_sRGB_to_XYZ(t){return multiplyMatrices([[506752/1228815,87881/24576 * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/utilities.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). * * @see https://github.com/w3c/csswg-drafts/blob/main/css-color-4/better-rgbToHsl.js - */function sRGB_to_HSL(t){const n=t[0],_=t[1],o=t[2],e=Math.max(n,_,o),r=Math.min(n,_,o),a=(r+e)/2,i=e-r;let l=NaN,u=0;if(0!==Math.round(1e5*i)){switch(u=0===Math.round(1e5*a)||1e5===Math.round(1e5*a)?0:(e-a)/Math.min(a,1-a),e){case n:l=(_-o)/i+(_=360&&(l-=360),[l,100*u,100*a]} + */function sRGB_to_HSL(t){const n=t[0],_=t[1],o=t[2],e=Math.max(n,_,o),r=Math.min(n,_,o),a=(r+e)/2,i=e-r;let l=NaN,u=0;if(0!==Math.round(1e5*i)){switch(u=0===Math.round(1e5*a)||1e5===Math.round(1e5*a)?0:(e-a)/Math.min(a,1-a),e){case n:l=(_-o)/i+(_=360&&(l-=360),[l,100*u,100*a]}const s=[446124/178915,-333277/357830,-72051/178915,-14852/17905,63121/35810,423/17905,11844/330415,-50337/660830,316169/330415]; /** * Convert XYZ to linear-light P3 * * @license W3C https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). - */function XYZ_to_lin_P3(t){return multiplyMatrices([[446124/178915,-333277/357830,-72051/178915],[-14852/17905,63121/35810,423/17905],[11844/330415,-50337/660830,316169/330415]],t)} + */function XYZ_to_lin_P3(t){return multiplyMatrices(s,t)} /** * Convert an array of linear-light display-p3 RGB in the range 0.0-1.0 * to gamma corrected form @@ -168,14 +181,15 @@ function lin_sRGB_to_XYZ(t){return multiplyMatrices([[506752/1228815,87881/24576 * * @license W3C https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). - */function XYZ_to_Lab(n){const _=216/24389,o=24389/27,e=n.map(((n,_)=>n/t[_])).map((t=>t>_?Math.cbrt(t):(o*t+16)/116));return[116*e[1]-16,500*(e[0]-e[1]),200*(e[1]-e[2])]} + */function XYZ_to_Lab(t){const _=216/24389,o=24389/27,e=t.map(((t,_)=>t/n[_])).map((t=>t>_?Math.cbrt(t):(o*t+16)/116));return[116*e[1]-16,500*(e[0]-e[1]),200*(e[1]-e[2])]}const m=[.819022437996703,.3619062600528904,-.1288737815209879,.0329836539323885,.9292868615863434,.0361446663506424,.0481771893596242,.2642395317527308,.6335478284694309],h=[.210454268309314,.7936177747023054,-.0040720430116193,1.9779985324311684,-2.42859224204858,.450593709617411,.0259040424655478,.7827717124575296,-.8086757549230774]; /** * @license W3C https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). * * XYZ <-> LMS matrices recalculated for consistent reference white * @see https://github.com/w3c/csswg-drafts/issues/6642#issuecomment-943521484 - */function XYZ_to_OKLab(t){const n=multiplyMatrices([[.819022437996703,.3619062600528904,-.1288737815209879],[.0329836539323885,.9292868615863434,.0361446663506424],[.0481771893596242,.2642395317527308,.6335478284694309]],t);return multiplyMatrices([[.210454268309314,.7936177747023054,-.0040720430116193],[1.9779985324311684,-2.42859224204858,.450593709617411],[.0259040424655478,.7827717124575296,-.8086757549230774]],n.map((t=>Math.cbrt(t))))} + */ +function XYZ_to_OKLab(t){const n=multiplyMatrices(m,t);return multiplyMatrices(h,[Math.cbrt(n[0]),Math.cbrt(n[1]),Math.cbrt(n[2])])} /** * @license W3C https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). @@ -184,12 +198,18 @@ function lin_sRGB_to_XYZ(t){return multiplyMatrices([[506752/1228815,87881/24576 * @license W3C https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). * @see https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js - */function OKLab_to_OKLCH(t){const n=180*Math.atan2(t[2],t[1])/Math.PI;return[t[0],Math.sqrt(t[1]**2+t[2]**2),n>=0?n:n+360]} + */function OKLab_to_OKLCH(t){const n=180*Math.atan2(t[2],t[1])/Math.PI;return[t[0],Math.sqrt(t[1]**2+t[2]**2),n>=0?n:n+360]}const D=[1829569/896150,-506331/896150,-308931/896150,-851781/878810,1648619/878810,36519/878810,16779/1248040,-147721/1248040,1266979/1248040]; /** * Convert XYZ to linear-light a98-rgb * * @license W3C https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). + */const X=[30757411/17917100,-6372589/17917100,-4539589/17917100,-.666684351832489,1.616481236634939,467509/29648200,792561/44930125,-1921689/44930125,.942103121235474]; +/** + * Convert XYZ to linear-light rec2020 + * + * @license W3C https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document + * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). */ /** * Convert an array of linear-light rec2020 RGB in the range 0.0-1.0 @@ -198,7 +218,7 @@ function lin_sRGB_to_XYZ(t){return multiplyMatrices([[506752/1228815,87881/24576 * @license W3C https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). */ -function gam_2020(t){const n=1.09929682680944;return t.map((function(t){const _=t<0?-1:1,o=Math.abs(t);return o>.018053968510807?_*(n*Math.pow(o,.45)-(n-1)):4.5*t}))} +function gam_2020(t){const n=1.09929682680944;return t.map((function(t){const _=t<0?-1:1,o=Math.abs(t);return o>.018053968510807?_*(n*Math.pow(o,.45)-(n-1)):4.5*t}))}const Y=[1.3457868816471583,-.25557208737979464,-.05110186497554526,-.5446307051249019,1.5082477428451468,.02052744743642139,0,0,1.2119675456389452]; /** * Convert D50 XYZ to linear-light prophoto-rgb * @@ -214,7 +234,7 @@ function gam_2020(t){const n=1.09929682680944;return t.map((function(t){const _= * @license W3C https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). */ -function gam_ProPhoto(t){const n=1/512;return t.map((function(t){const _=t<0?-1:1,o=Math.abs(t);return o>=n?_*Math.pow(o,1/1.8):16*t}))}function sRGB_to_XYZ_D50(t){let n=t;return n=lin_sRGB(n),n=lin_sRGB_to_XYZ(n),n=D65_to_D50(n),n}function XYZ_D50_to_sRGB(t){let n=t;return n=D50_to_D65(n),n=XYZ_to_lin_sRGB(n),n=gam_sRGB(n),n}function HSL_to_XYZ_D50(t){let n=t;return n=HSL_to_sRGB(n),n=lin_sRGB(n),n=lin_sRGB_to_XYZ(n),n=D65_to_D50(n),n}function XYZ_D50_to_HSL(t){let n=t;return n=D50_to_D65(n),n=XYZ_to_lin_sRGB(n),n=gam_sRGB(n),n=sRGB_to_HSL(n),n}function HWB_to_XYZ_D50(t){let n=t;return n=HWB_to_sRGB(n),n=lin_sRGB(n),n=lin_sRGB_to_XYZ(n),n=D65_to_D50(n),n}function XYZ_D50_to_HWB(t){let n=t;n=D50_to_D65(n),n=XYZ_to_lin_sRGB(n);const _=gam_sRGB(n);n=sRGB_to_HSL(_);const o=Math.min(_[0],_[1],_[2]),e=1-Math.max(_[0],_[1],_[2]);return[n[0],100*o,100*e]}function Lab_to_XYZ_D50(t){let n=t;return n=Lab_to_XYZ(n),n}function XYZ_D50_to_Lab(t){let n=t;return n=XYZ_to_Lab(n),n}function LCH_to_XYZ_D50(t){let n=t;var _;return n=[(_=n)[0],_[1]*Math.cos(_[2]*Math.PI/180),_[1]*Math.sin(_[2]*Math.PI/180)],n=Lab_to_XYZ(n),n}function XYZ_D50_to_LCH(t){let n=t;return n=XYZ_to_Lab(n),n=Lab_to_LCH(n),n}function OKLab_to_XYZ_D50(t){let n=t;return n=OKLab_to_XYZ(n),n=D65_to_D50(n),n}function XYZ_D50_to_OKLab(t){let n=t;return n=D50_to_D65(n),n=XYZ_to_OKLab(n),n}function OKLCH_to_XYZ_D50(t){let n=t;return n=OKLCH_to_OKLab(n),n=OKLab_to_XYZ(n),n=D65_to_D50(n),n}function XYZ_D50_to_OKLCH(t){let n=t;return n=D50_to_D65(n),n=XYZ_to_OKLab(n),n=OKLab_to_OKLCH(n),n}function lin_sRGB_to_XYZ_D50(t){let n=t;return n=lin_sRGB_to_XYZ(n),n=D65_to_D50(n),n}function XYZ_D50_to_lin_sRGB(t){let n=t;return n=D50_to_D65(n),n=XYZ_to_lin_sRGB(n),n}function a98_RGB_to_XYZ_D50(t){let n=t;return n=n.map((function(t){const n=t<0?-1:1,_=Math.abs(t);return n*Math.pow(_,563/256)})),n=multiplyMatrices([[573536/994567,263643/1420810,187206/994567],[591459/1989134,6239551/9945670,374412/4972835],[53769/1989134,351524/4972835,4929758/4972835]],n),n=D65_to_D50(n),n}function XYZ_D50_to_a98_RGB(t){let n=t;return n=D50_to_D65(n),n=multiplyMatrices([[1829569/896150,-506331/896150,-308931/896150],[-851781/878810,1648619/878810,36519/878810],[16779/1248040,-147721/1248040,1266979/1248040]],n),n=n.map((function(t){const n=t<0?-1:1,_=Math.abs(t);return n*Math.pow(_,256/563)})),n}function P3_to_XYZ_D50(t){let n=t;return n=lin_P3(n),n=lin_P3_to_XYZ(n),n=D65_to_D50(n),n}function XYZ_D50_to_P3(t){let n=t;return n=D50_to_D65(n),n=XYZ_to_lin_P3(n),n=gam_P3(n),n}function rec_2020_to_XYZ_D50(t){let n=t;return n=lin_2020(n),n=multiplyMatrices([[63426534/99577255,20160776/139408157,47086771/278816314],[26158966/99577255,.677998071518871,8267143/139408157],[0,19567812/697040785,1.0609850577107909]],n),n=D65_to_D50(n),n}function XYZ_D50_to_rec_2020(t){let n=t;return n=D50_to_D65(n),n=multiplyMatrices([[30757411/17917100,-6372589/17917100,-4539589/17917100],[-.666684351832489,1.616481236634939,467509/29648200],[792561/44930125,-1921689/44930125,.942103121235474]],n),n=gam_2020(n),n}function ProPhoto_RGB_to_XYZ_D50(t){let n=t;return n=n.map((function(t){const n=t<0?-1:1,_=Math.abs(t);return _<=.03125?t/16:n*Math.pow(_,1.8)})),n=multiplyMatrices([[.7977666449006423,.13518129740053308,.0313477341283922],[.2880748288194013,.711835234241873,8993693872564e-17],[0,0,.8251046025104602]],n),n}function XYZ_D50_to_ProPhoto(t){let n=t;return n=multiplyMatrices([[1.3457868816471583,-.25557208737979464,-.05110186497554526],[-.5446307051249019,1.5082477428451468,.02052744743642139],[0,0,1.2119675456389452]],n),n=gam_ProPhoto(n),n}function XYZ_D65_to_XYZ_D50(t){let n=t;return n=D65_to_D50(n),n}function XYZ_D50_to_XYZ_D65(t){let n=t;return n=D50_to_D65(n),n}function XYZ_D50_to_XYZ_D50(t){return t}function inGamut(t){const[n,_,o]=t;return n>=-1e-4&&n<=1.0001&&_>=-1e-4&&_<=1.0001&&o>=-1e-4&&o<=1.0001}function clip(t){return t.map((t=>t<0?0:t>1?1:t))} +function gam_ProPhoto(t){const n=1/512;return t.map((function(t){const _=t<0?-1:1,o=Math.abs(t);return o>=n?_*Math.pow(o,1/1.8):16*t}))}function sRGB_to_XYZ_D50(t){let n=t;return n=lin_sRGB(n),n=lin_sRGB_to_XYZ(n),n=D65_to_D50(n),n}function XYZ_D50_to_sRGB(t){let n=t;return n=D50_to_D65(n),n=XYZ_to_lin_sRGB(n),n=gam_sRGB(n),n}function HSL_to_XYZ_D50(t){let n=t;return n=HSL_to_sRGB(n),n=lin_sRGB(n),n=lin_sRGB_to_XYZ(n),n=D65_to_D50(n),n}function XYZ_D50_to_HSL(t){let n=t;return n=D50_to_D65(n),n=XYZ_to_lin_sRGB(n),n=gam_sRGB(n),n=sRGB_to_HSL(n),n}function HWB_to_XYZ_D50(t){let n=t;return n=HWB_to_sRGB(n),n=lin_sRGB(n),n=lin_sRGB_to_XYZ(n),n=D65_to_D50(n),n}function XYZ_D50_to_HWB(t){let n=t;n=D50_to_D65(n),n=XYZ_to_lin_sRGB(n);const _=gam_sRGB(n);n=sRGB_to_HSL(_);const o=Math.min(_[0],_[1],_[2]),e=1-Math.max(_[0],_[1],_[2]);return[n[0],100*o,100*e]}function Lab_to_XYZ_D50(t){let n=t;return n=Lab_to_XYZ(n),n}function XYZ_D50_to_Lab(t){let n=t;return n=XYZ_to_Lab(n),n}function LCH_to_XYZ_D50(t){let n=t;var _;return n=[(_=n)[0],_[1]*Math.cos(_[2]*Math.PI/180),_[1]*Math.sin(_[2]*Math.PI/180)],n=Lab_to_XYZ(n),n}function XYZ_D50_to_LCH(t){let n=t;return n=XYZ_to_Lab(n),n=Lab_to_LCH(n),n}function OKLab_to_XYZ_D50(t){let n=t;return n=OKLab_to_XYZ(n),n=D65_to_D50(n),n}function XYZ_D50_to_OKLab(t){let n=t;return n=D50_to_D65(n),n=XYZ_to_OKLab(n),n}function OKLCH_to_XYZ_D50(t){let n=t;return n=OKLCH_to_OKLab(n),n=OKLab_to_XYZ(n),n=D65_to_D50(n),n}function XYZ_D50_to_OKLCH(t){let n=t;return n=D50_to_D65(n),n=XYZ_to_OKLab(n),n=OKLab_to_OKLCH(n),n}function lin_sRGB_to_XYZ_D50(t){let n=t;return n=lin_sRGB_to_XYZ(n),n=D65_to_D50(n),n}function XYZ_D50_to_lin_sRGB(t){let n=t;return n=D50_to_D65(n),n=XYZ_to_lin_sRGB(n),n}function a98_RGB_to_XYZ_D50(t){let n=t;return n=n.map((function(t){const n=t<0?-1:1,_=Math.abs(t);return n*Math.pow(_,563/256)})),n=multiplyMatrices(i,n),n=D65_to_D50(n),n}function XYZ_D50_to_a98_RGB(t){let n=t;return n=D50_to_D65(n),n=multiplyMatrices(D,n),n=n.map((function(t){const n=t<0?-1:1,_=Math.abs(t);return n*Math.pow(_,256/563)})),n}function P3_to_XYZ_D50(t){let n=t;return n=lin_P3(n),n=lin_P3_to_XYZ(n),n=D65_to_D50(n),n}function XYZ_D50_to_P3(t){let n=t;return n=D50_to_D65(n),n=XYZ_to_lin_P3(n),n=gam_P3(n),n}function rec_2020_to_XYZ_D50(t){let n=t;return n=lin_2020(n),n=multiplyMatrices(e,n),n=D65_to_D50(n),n}function XYZ_D50_to_rec_2020(t){let n=t;return n=D50_to_D65(n),n=multiplyMatrices(X,n),n=gam_2020(n),n}function ProPhoto_RGB_to_XYZ_D50(t){let n=t;return n=n.map((function(t){const n=t<0?-1:1,_=Math.abs(t);return _<=.03125?t/16:n*Math.pow(_,1.8)})),n=multiplyMatrices(a,n),n}function XYZ_D50_to_ProPhoto(t){let n=t;return n=multiplyMatrices(Y,n),n=gam_ProPhoto(n),n}function XYZ_D65_to_XYZ_D50(t){let n=t;return n=D65_to_D50(n),n}function XYZ_D50_to_XYZ_D65(t){let n=t;return n=D50_to_D65(n),n}function XYZ_D50_to_XYZ_D50(t){return t}function inGamut(t){const[n,_,o]=t;return n>=-1e-4&&n<=1.0001&&_>=-1e-4&&_<=1.0001&&o>=-1e-4&&o<=1.0001}function clip(t){return t.map((t=>t<0?0:t>1?1:t))} /** * @description Calculate deltaE OK which is the simple root sum of squares * @param {number[]} reference - Array of OKLab values: L as 0..1, a and b as -1..1 @@ -224,7 +244,7 @@ function gam_ProPhoto(t){const n=1/512;return t.map((function(t){const _=t<0?-1: * @license W3C https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/deltaEOK.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). * @see https://github.com/w3c/csswg-drafts/blob/main/css-color-4/deltaEOK.js - */function deltaEOK(t,n){const[_,o,e]=t,[r,a,i]=n,l=_-r,u=o-a,c=e-i;return Math.sqrt(l**2+u**2+c**2)}const n=.02,_=1e-4;function mapGamut(t,o,e){const r=t;let a=clip(o(r)),i=deltaEOK(OKLCH_to_OKLab(e(a)),OKLCH_to_OKLab(r));if(i_;){const t=(l+u)/2;if(r[1]=t,c&&inGamut(o(r)))l=t;else if(a=clip(o(r)),i=deltaEOK(OKLCH_to_OKLab(e(a)),OKLCH_to_OKLab(r)),ib;){const t=(a+i)/2;if(o[1]=t,l&&inGamut(n(o)))a=t;else if(e=clip(n(o)),r=deltaEOK(OKLCH_to_OKLab(_(e)),OKLCH_to_OKLab(o)),r0){const t=_(r);t[0]=o,t[2]=e,r=n(t)}const i=rayTraceBox(a,r.slice());if(!i)break;r=i.slice()}return clip(r)}function rayTraceBox(t,n){let _=1/0,o=-1/0;const e=[];for(let r=0;r<3;r++){const a=t[r],i=n[r]-a;e.push(i);const l=0,u=1;if(i){const t=1/i,n=(l-a)*t,e=(u-a)*t;o=Math.max(Math.min(n,e),o),_=Math.min(Math.max(n,e),_)}else if(au)return!1}return!(o>_||_<0)&&(o<0&&(o=_),!!isFinite(o)&&[t[0]+e[0]*o,t[1]+e[1]*o,t[2]+e[2]*o])}const o={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]};function luminance(t){const[n,_,o]=t.map((t=>t<=.03928?t/12.92:Math.pow((t+.055)/1.055,2.4)));return.2126*n+.7152*_+.0722*o}function contrast_ratio_wcag_2_1(t,n){const _=luminance(t),o=luminance(n);return(Math.max(_,o)+.05)/(Math.min(_,o)+.05)}export{HSL_to_XYZ_D50,HWB_to_XYZ_D50,LCH_to_XYZ_D50,Lab_to_XYZ_D50,OKLCH_to_OKLab,OKLCH_to_XYZ_D50,OKLab_to_OKLCH,OKLab_to_XYZ,OKLab_to_XYZ_D50,P3_to_XYZ_D50,ProPhoto_RGB_to_XYZ_D50,XYZ_D50_to_HSL,XYZ_D50_to_HWB,XYZ_D50_to_LCH,XYZ_D50_to_Lab,XYZ_D50_to_OKLCH,XYZ_D50_to_OKLab,XYZ_D50_to_P3,XYZ_D50_to_ProPhoto,XYZ_D50_to_XYZ_D50,XYZ_D50_to_XYZ_D65,XYZ_D50_to_a98_RGB,XYZ_D50_to_lin_sRGB,XYZ_D50_to_rec_2020,XYZ_D50_to_sRGB,XYZ_D65_to_XYZ_D50,XYZ_to_OKLab,XYZ_to_lin_P3,XYZ_to_lin_sRGB,a98_RGB_to_XYZ_D50,clip,contrast_ratio_wcag_2_1,gam_P3,gam_sRGB,inGamut,lin_P3,lin_P3_to_XYZ,lin_sRGB,lin_sRGB_to_XYZ,lin_sRGB_to_XYZ_D50,mapGamut,mapGamutRayTrace,o as namedColors,rec_2020_to_XYZ_D50,sRGB_to_XYZ_D50}; + */function mapGamutRayTrace(t,n,_){const o=t[0],e=t[2];let r=n(t);const a=n([o,0,e]);for(let t=0;t<4;t++){if(t>0){const t=_(r);t[0]=o,t[2]=e,r=n(t)}const i=rayTraceBox(a,r.slice());if(!i)break;r=i.slice()}return clip(r)}function rayTraceBox(t,n){let _=1/0,o=-1/0;const e=[];for(let r=0;r<3;r++){const a=t[r],i=n[r]-a;e.push(i);const l=0,u=1;if(i){const t=1/i,n=(l-a)*t,e=(u-a)*t;o=Math.max(Math.min(n,e),o),_=Math.min(Math.max(n,e),_)}else if(au)return!1}return!(o>_||_<0)&&(o<0&&(o=_),!!isFinite(o)&&[t[0]+e[0]*o,t[1]+e[1]*o,t[2]+e[2]*o])}const p={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]};function luminance(t){const[n,_,o]=t.map((t=>t<=.03928?t/12.92:Math.pow((t+.055)/1.055,2.4)));return.2126*n+.7152*_+.0722*o}function contrast_ratio_wcag_2_1(t,n){const _=luminance(t),o=luminance(n);return(Math.max(_,o)+.05)/(Math.min(_,o)+.05)}export{HSL_to_XYZ_D50,HWB_to_XYZ_D50,LCH_to_XYZ_D50,Lab_to_XYZ_D50,OKLCH_to_OKLab,OKLCH_to_XYZ_D50,OKLab_to_OKLCH,OKLab_to_XYZ,OKLab_to_XYZ_D50,P3_to_XYZ_D50,ProPhoto_RGB_to_XYZ_D50,XYZ_D50_to_HSL,XYZ_D50_to_HWB,XYZ_D50_to_LCH,XYZ_D50_to_Lab,XYZ_D50_to_OKLCH,XYZ_D50_to_OKLab,XYZ_D50_to_P3,XYZ_D50_to_ProPhoto,XYZ_D50_to_XYZ_D50,XYZ_D50_to_XYZ_D65,XYZ_D50_to_a98_RGB,XYZ_D50_to_lin_sRGB,XYZ_D50_to_rec_2020,XYZ_D50_to_sRGB,XYZ_D65_to_XYZ_D50,XYZ_to_OKLab,XYZ_to_lin_P3,XYZ_to_lin_sRGB,a98_RGB_to_XYZ_D50,clip,contrast_ratio_wcag_2_1,gam_P3,gam_sRGB,inGamut,lin_P3,lin_P3_to_XYZ,lin_sRGB,lin_sRGB_to_XYZ,lin_sRGB_to_XYZ_D50,mapGamut,mapGamutRayTrace,p as namedColors,rec_2020_to_XYZ_D50,sRGB_to_XYZ_D50}; diff --git a/packages/color-helpers/src/calculations/multiply-matrices.ts b/packages/color-helpers/src/calculations/multiply-matrices.ts index 318c7177e..b63a1437b 100644 --- a/packages/color-helpers/src/calculations/multiply-matrices.ts +++ b/packages/color-helpers/src/calculations/multiply-matrices.ts @@ -1,49 +1,15 @@ -/** - * Simple matrix (and vector) multiplication - * Warning: No error handling for incompatible dimensions! - * @author Lea Verou 2020 MIT License - * - * @license W3C https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document - * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/multiply-matrices.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). - * @see https://github.com/w3c/csswg-drafts/blob/main/css-color-4/multiply-matrices.js - */ -// A is m x n. B is n x p. product is m x p. -export function multiplyMatrices(a: Array> | Array, b: Array> | Array): Array> | Array { - const m = a.length; - - let A: Array>; - if (!Array.isArray(a[0])) { - // A is vector, convert to [[a, b, c, ...]] - A = [a as Array]; - } else { - A = a as Array>; - } - - let B: Array>; - if (!Array.isArray(b[0])) { - // B is vector, convert to [[a], [b], [c], ...]] - B = (b as Array).map(x => [x]); - } else { - B = b as Array>; - } - - const p = B[0].length; - const B_cols = B[0].map((_, i) => B.map(x => x[i])); // transpose B - let product: Array> | Array = A.map(row => B_cols.map(col => { - if (!Array.isArray(row)) { - return col.reduce((d, f) => d + f * row, 0); - } - - return row.reduce((d, f, i) => d + f * (col[i] || 0), 0); - })); - - if (m === 1) { - product = product[0]; // Avoid [[a, b, c, ...]] - } - - if (p === 1) { - return (product as Array>).map(x => x[0]); // Avoid [[a], [b], [c], ...]] - } - - return product; +import { Color } from '../types/color'; + +export type Matrix = [ + number, number, number, + number, number, number, + number, number, number, +]; + +export function multiplyMatrices(a: Matrix, b: Color): Color { + return [ + a[0] * b[0] + a[1] * b[1] + a[2] * b[2], + a[3] * b[0] + a[4] * b[1] + a[5] * b[2], + a[6] * b[0] + a[7] * b[1] + a[8] * b[2], + ]; } diff --git a/packages/color-helpers/src/conversions/d50-to-d65.ts b/packages/color-helpers/src/conversions/d50-to-d65.ts index 23eb69d5b..91da0a717 100644 --- a/packages/color-helpers/src/conversions/d50-to-d65.ts +++ b/packages/color-helpers/src/conversions/d50-to-d65.ts @@ -1,5 +1,11 @@ import type { Color } from '../types/color'; -import { multiplyMatrices } from '../calculations/multiply-matrices'; +import { Matrix, multiplyMatrices } from '../calculations/multiply-matrices'; + +const M: Matrix = [ + 0.955473421488075, -0.02309845494876471, 0.06325924320057072, + -0.0283697093338637, 1.0099953980813041, 0.021041441191917323, + 0.012314014864481998, -0.020507649298898964, 1.330365926242124, +]; /** * Bradford chromatic adaptation from D50 to D65 @@ -8,11 +14,5 @@ import { multiplyMatrices } from '../calculations/multiply-matrices'; * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). */ export function D50_to_D65(XYZ: Color): Color { - const M = [ - [0.955473421488075, -0.02309845494876471, 0.06325924320057072], - [-0.0283697093338637, 1.0099953980813041, 0.021041441191917323], - [0.012314014864481998, -0.020507649298898964, 1.330365926242124], - ]; - - return multiplyMatrices(M, XYZ) as Color; + return multiplyMatrices(M, XYZ); } diff --git a/packages/color-helpers/src/conversions/d65-to-d50.ts b/packages/color-helpers/src/conversions/d65-to-d50.ts index f8665d797..f4a914814 100644 --- a/packages/color-helpers/src/conversions/d65-to-d50.ts +++ b/packages/color-helpers/src/conversions/d65-to-d50.ts @@ -1,5 +1,11 @@ import type { Color } from '../types/color'; -import { multiplyMatrices } from '../calculations/multiply-matrices'; +import { Matrix, multiplyMatrices } from '../calculations/multiply-matrices'; + +const M: Matrix = [ + 1.0479297925449969, 0.022946870601609652, -0.05019226628920524, + 0.02962780877005599, 0.9904344267538799, -0.017073799063418826, + -0.009243040646204504, 0.015055191490298152, 0.7518742814281371, +]; /** * Bradford chromatic adaptation from D65 to D50 @@ -12,11 +18,5 @@ export function D65_to_D50(XYZ: Color): Color { // - convert from XYZ to retinal cone domain // - scale components from one reference white to another // - convert back to XYZ - const M = [ - [1.0479297925449969, 0.022946870601609652, -0.05019226628920524], - [0.02962780877005599, 0.9904344267538799, -0.017073799063418826], - [-0.009243040646204504, 0.015055191490298152, 0.7518742814281371], - ]; - - return multiplyMatrices(M, XYZ) as Color; + return multiplyMatrices(M, XYZ); } diff --git a/packages/color-helpers/src/conversions/lin-2020-to-xyz.ts b/packages/color-helpers/src/conversions/lin-2020-to-xyz.ts index 177e8d78d..fdbba96e4 100644 --- a/packages/color-helpers/src/conversions/lin-2020-to-xyz.ts +++ b/packages/color-helpers/src/conversions/lin-2020-to-xyz.ts @@ -1,5 +1,11 @@ import type { Color } from '../types/color'; -import { multiplyMatrices } from '../calculations/multiply-matrices'; +import { Matrix, multiplyMatrices } from '../calculations/multiply-matrices'; + +const M: Matrix = [ + 63426534 / 99577255, 20160776 / 139408157, 47086771 / 278816314, + 26158966 / 99577255, 472592308 / 697040785, 8267143 / 139408157, + 0 / 1, 19567812 / 697040785, 295819943 / 278816314, +]; /** * Convert an array of linear-light rec2020 values to CIE XYZ @@ -10,12 +16,6 @@ import { multiplyMatrices } from '../calculations/multiply-matrices'; * @see http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html */ export function lin_2020_to_XYZ(rgb: Color): Color { - const M = [ - [63426534 / 99577255, 20160776 / 139408157, 47086771 / 278816314], - [26158966 / 99577255, 472592308 / 697040785, 8267143 / 139408157], - [0 / 1, 19567812 / 697040785, 295819943 / 278816314], - ]; // 0 is actually calculated as 4.994106574466076e-17 - - return multiplyMatrices(M, rgb) as Color; + return multiplyMatrices(M, rgb); } diff --git a/packages/color-helpers/src/conversions/lin-a98rgb-to-xyz.ts b/packages/color-helpers/src/conversions/lin-a98rgb-to-xyz.ts index c7cbd5940..9cb09fbe6 100644 --- a/packages/color-helpers/src/conversions/lin-a98rgb-to-xyz.ts +++ b/packages/color-helpers/src/conversions/lin-a98rgb-to-xyz.ts @@ -1,5 +1,11 @@ import type { Color } from '../types/color'; -import { multiplyMatrices } from '../calculations/multiply-matrices'; +import { Matrix, multiplyMatrices } from '../calculations/multiply-matrices'; + +const M: Matrix = [ + 573536 / 994567, 263643 / 1420810, 187206 / 994567, + 591459 / 1989134, 6239551 / 9945670, 374412 / 4972835, + 53769 / 1989134, 351524 / 4972835, 4929758 / 4972835, +]; /** * Convert an array of linear-light a98-rgb values to CIE XYZ @@ -16,11 +22,5 @@ import { multiplyMatrices } from '../calculations/multiply-matrices'; * @see https://github.com/w3c/csswg-drafts/blob/main/css-color-4/matrixmaker.html */ export function lin_a98rgb_to_XYZ(rgb: Color): Color { - const M = [ - [573536 / 994567, 263643 / 1420810, 187206 / 994567], - [591459 / 1989134, 6239551 / 9945670, 374412 / 4972835], - [53769 / 1989134, 351524 / 4972835, 4929758 / 4972835], - ]; - - return multiplyMatrices(M, rgb) as Color; + return multiplyMatrices(M, rgb); } diff --git a/packages/color-helpers/src/conversions/lin-p3-to-xyz.ts b/packages/color-helpers/src/conversions/lin-p3-to-xyz.ts index b2b660511..03c5b3b39 100644 --- a/packages/color-helpers/src/conversions/lin-p3-to-xyz.ts +++ b/packages/color-helpers/src/conversions/lin-p3-to-xyz.ts @@ -1,5 +1,11 @@ import type { Color } from '../types/color'; -import { multiplyMatrices } from '../calculations/multiply-matrices'; +import { Matrix, multiplyMatrices } from '../calculations/multiply-matrices'; + +const M: Matrix = [ + 608311 / 1250200, 189793 / 714400, 198249 / 1000160, + 35783 / 156275, 247089 / 357200, 198249 / 2500400, + 0 / 1, 32229 / 714400, 5220557 / 5000800, +]; /** * Convert an array of linear-light display-p3 values to CIE XYZ @@ -10,11 +16,5 @@ import { multiplyMatrices } from '../calculations/multiply-matrices'; * @see http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html */ export function lin_P3_to_XYZ(rgb: Color): Color { - const M = [ - [608311 / 1250200, 189793 / 714400, 198249 / 1000160], - [35783 / 156275, 247089 / 357200, 198249 / 2500400], - [0 / 1, 32229 / 714400, 5220557 / 5000800], - ]; - - return multiplyMatrices(M, rgb) as Color; + return multiplyMatrices(M, rgb); } diff --git a/packages/color-helpers/src/conversions/lin-pro-photo-to-xyz.ts b/packages/color-helpers/src/conversions/lin-pro-photo-to-xyz.ts index 1b4f064d5..af17d5af0 100644 --- a/packages/color-helpers/src/conversions/lin-pro-photo-to-xyz.ts +++ b/packages/color-helpers/src/conversions/lin-pro-photo-to-xyz.ts @@ -1,5 +1,13 @@ +/* eslint-disable no-loss-of-precision */ + import type { Color } from '../types/color'; -import { multiplyMatrices } from '../calculations/multiply-matrices'; +import { Matrix, multiplyMatrices } from '../calculations/multiply-matrices'; + +const M: Matrix = [ + 0.79776664490064230, 0.13518129740053308, 0.03134773412839220, + 0.28807482881940130, 0.71183523424187300, 0.00008993693872564, + 0.00000000000000000, 0.00000000000000000, 0.82510460251046020, +]; /** * Convert an array of linear-light prophoto-rgb values to CIE D50 XYZ. @@ -10,11 +18,5 @@ import { multiplyMatrices } from '../calculations/multiply-matrices'; * @see see https://github.com/w3c/csswg-drafts/issues/7675 */ export function lin_ProPhoto_to_XYZ(rgb: Color): Color { - const M = [ - [0.79776664490064230, 0.13518129740053308, 0.03134773412839220], - [0.28807482881940130, 0.71183523424187300, 0.00008993693872564], - [0.00000000000000000, 0.00000000000000000, 0.82510460251046020], - ]; - - return multiplyMatrices(M, rgb) as Color; + return multiplyMatrices(M, rgb); } diff --git a/packages/color-helpers/src/conversions/lin-srgb-to-xyz.ts b/packages/color-helpers/src/conversions/lin-srgb-to-xyz.ts index 2e8988303..1a91e9a55 100644 --- a/packages/color-helpers/src/conversions/lin-srgb-to-xyz.ts +++ b/packages/color-helpers/src/conversions/lin-srgb-to-xyz.ts @@ -1,5 +1,11 @@ import type { Color } from '../types/color'; -import { multiplyMatrices } from '../calculations/multiply-matrices'; +import { Matrix, multiplyMatrices } from '../calculations/multiply-matrices'; + +const M: Matrix = [ + 506752 / 1228815, 87881 / 245763, 12673 / 70218, + 87098 / 409605, 175762 / 245763, 12673 / 175545, + 7918 / 409605, 87881 / 737289, 1001167 / 1053270, +]; /** * Convert an array of linear-light sRGB values to CIE XYZ @@ -9,10 +15,5 @@ import { multiplyMatrices } from '../calculations/multiply-matrices'; * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). */ export function lin_sRGB_to_XYZ(rgb: Color): Color { - const M = [ - [506752 / 1228815, 87881 / 245763, 12673 / 70218], - [87098 / 409605, 175762 / 245763, 12673 / 175545], - [7918 / 409605, 87881 / 737289, 1001167 / 1053270], - ]; - return multiplyMatrices(M, rgb) as Color; + return multiplyMatrices(M, rgb); } diff --git a/packages/color-helpers/src/conversions/oklab-to-xyz.ts b/packages/color-helpers/src/conversions/oklab-to-xyz.ts index 20e5ede78..052d1728f 100644 --- a/packages/color-helpers/src/conversions/oklab-to-xyz.ts +++ b/packages/color-helpers/src/conversions/oklab-to-xyz.ts @@ -1,5 +1,16 @@ import type { Color } from '../types/color'; -import { multiplyMatrices } from '../calculations/multiply-matrices'; +import { Matrix, multiplyMatrices } from '../calculations/multiply-matrices'; + +const LMStoXYZ: Matrix = [ + 1.2268798758459243, -0.5578149944602171, 0.2813910456659647, + -0.0405757452148008, 1.1122868032803170, -0.0717110580655164, + -0.0763729366746601, -0.4214933324022432, 1.5869240198367816, +]; +const OKLabtoLMS: Matrix = [ + 1.0000000000000000, 0.3963377773761749, 0.2158037573099136, + 1.0000000000000000, -0.1055613458156586, -0.0638541728258133, + 1.0000000000000000, -0.0894841775298119, -1.2914855480194092, +]; /** * Given OKLab, convert to XYZ relative to D65 @@ -9,18 +20,14 @@ import { multiplyMatrices } from '../calculations/multiply-matrices'; * @see https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js */ export function OKLab_to_XYZ(OKLab: Color): Color { - const LMStoXYZ = [ - [1.2268798758459243, -0.5578149944602171, 0.2813910456659647], - [-0.0405757452148008, 1.1122868032803170, -0.0717110580655164], - [-0.0763729366746601, -0.4214933324022432, 1.5869240198367816], - ]; - const OKLabtoLMS = [ - [1.0000000000000000, 0.3963377773761749, 0.2158037573099136], - [1.0000000000000000, -0.1055613458156586, -0.0638541728258133], - [1.0000000000000000, -0.0894841775298119, -1.2914855480194092], - ]; - - const LMSnl = multiplyMatrices(OKLabtoLMS, OKLab) as Color; + const LMSnl = multiplyMatrices(OKLabtoLMS, OKLab); - return multiplyMatrices(LMStoXYZ, LMSnl.map(c => c ** 3)) as Color; + return multiplyMatrices( + LMStoXYZ, + [ + LMSnl[0] ** 3, + LMSnl[1] ** 3, + LMSnl[2] ** 3, + ], + ); } diff --git a/packages/color-helpers/src/conversions/xyz-to-lin-2020.ts b/packages/color-helpers/src/conversions/xyz-to-lin-2020.ts index 04280e07c..8267639ef 100644 --- a/packages/color-helpers/src/conversions/xyz-to-lin-2020.ts +++ b/packages/color-helpers/src/conversions/xyz-to-lin-2020.ts @@ -1,5 +1,11 @@ import type { Color } from '../types/color'; -import { multiplyMatrices } from '../calculations/multiply-matrices'; +import { Matrix, multiplyMatrices } from '../calculations/multiply-matrices'; + +const M: Matrix = [ + 30757411 / 17917100, -6372589 / 17917100, -4539589 / 17917100, + -19765991 / 29648200, 47925759 / 29648200, 467509 / 29648200, + 792561 / 44930125, -1921689 / 44930125, 42328811 / 44930125, +]; /** * Convert XYZ to linear-light rec2020 @@ -8,11 +14,5 @@ import { multiplyMatrices } from '../calculations/multiply-matrices'; * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). */ export function XYZ_to_lin_2020(XYZ: Color): Color { - const M = [ - [30757411 / 17917100, -6372589 / 17917100, -4539589 / 17917100], - [-19765991 / 29648200, 47925759 / 29648200, 467509 / 29648200], - [792561 / 44930125, -1921689 / 44930125, 42328811 / 44930125], - ]; - - return multiplyMatrices(M, XYZ) as Color; + return multiplyMatrices(M, XYZ); } diff --git a/packages/color-helpers/src/conversions/xyz-to-lin-a98rgb.ts b/packages/color-helpers/src/conversions/xyz-to-lin-a98rgb.ts index 4d504bd44..fe583d361 100644 --- a/packages/color-helpers/src/conversions/xyz-to-lin-a98rgb.ts +++ b/packages/color-helpers/src/conversions/xyz-to-lin-a98rgb.ts @@ -1,5 +1,11 @@ import type { Color } from '../types/color'; -import { multiplyMatrices } from '../calculations/multiply-matrices'; +import { Matrix, multiplyMatrices } from '../calculations/multiply-matrices'; + +const M: Matrix = [ + 1829569 / 896150, -506331 / 896150, -308931 / 896150, + -851781 / 878810, 1648619 / 878810, 36519 / 878810, + 16779 / 1248040, -147721 / 1248040, 1266979 / 1248040, +]; /** * Convert XYZ to linear-light a98-rgb @@ -8,11 +14,5 @@ import { multiplyMatrices } from '../calculations/multiply-matrices'; * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). */ export function XYZ_to_lin_a98rgb(XYZ: Color): Color { - const M = [ - [1829569 / 896150, -506331 / 896150, -308931 / 896150], - [-851781 / 878810, 1648619 / 878810, 36519 / 878810], - [16779 / 1248040, -147721 / 1248040, 1266979 / 1248040], - ]; - - return multiplyMatrices(M, XYZ) as Color; + return multiplyMatrices(M, XYZ); } diff --git a/packages/color-helpers/src/conversions/xyz-to-lin-p3.ts b/packages/color-helpers/src/conversions/xyz-to-lin-p3.ts index 20024744d..af48729d8 100644 --- a/packages/color-helpers/src/conversions/xyz-to-lin-p3.ts +++ b/packages/color-helpers/src/conversions/xyz-to-lin-p3.ts @@ -1,5 +1,11 @@ import type { Color } from '../types/color'; -import { multiplyMatrices } from '../calculations/multiply-matrices'; +import { Matrix, multiplyMatrices } from '../calculations/multiply-matrices'; + +const M: Matrix = [ + 446124 / 178915, -333277 / 357830, -72051 / 178915, + -14852 / 17905, 63121 / 35810, 423 / 17905, + 11844 / 330415, -50337 / 660830, 316169 / 330415, +]; /** * Convert XYZ to linear-light P3 @@ -8,11 +14,5 @@ import { multiplyMatrices } from '../calculations/multiply-matrices'; * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). */ export function XYZ_to_lin_P3(XYZ: Color): Color { - const M = [ - [446124 / 178915, -333277 / 357830, -72051 / 178915], - [-14852 / 17905, 63121 / 35810, 423 / 17905], - [11844 / 330415, -50337 / 660830, 316169 / 330415], - ]; - - return multiplyMatrices(M, XYZ) as Color; + return multiplyMatrices(M, XYZ); } diff --git a/packages/color-helpers/src/conversions/xyz-to-lin-pro-photo.ts b/packages/color-helpers/src/conversions/xyz-to-lin-pro-photo.ts index b2af7f023..4e3633023 100644 --- a/packages/color-helpers/src/conversions/xyz-to-lin-pro-photo.ts +++ b/packages/color-helpers/src/conversions/xyz-to-lin-pro-photo.ts @@ -1,5 +1,13 @@ +/* eslint-disable no-loss-of-precision */ + import type { Color } from '../types/color'; -import { multiplyMatrices } from '../calculations/multiply-matrices'; +import { Matrix, multiplyMatrices } from '../calculations/multiply-matrices'; + +const M: Matrix = [ + 1.34578688164715830, -0.25557208737979464, -0.05110186497554526, + -0.54463070512490190, 1.50824774284514680, 0.02052744743642139, + 0.00000000000000000, 0.00000000000000000, 1.21196754563894520, +]; /** * Convert D50 XYZ to linear-light prophoto-rgb @@ -9,11 +17,5 @@ import { multiplyMatrices } from '../calculations/multiply-matrices'; * @see http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html */ export function XYZ_to_lin_ProPhoto(XYZ: Color): Color { - const M = [ - [1.34578688164715830, -0.25557208737979464, -0.05110186497554526], - [-0.54463070512490190, 1.50824774284514680, 0.02052744743642139], - [0.00000000000000000, 0.00000000000000000, 1.21196754563894520], - ]; - - return multiplyMatrices(M, XYZ) as Color; + return multiplyMatrices(M, XYZ); } diff --git a/packages/color-helpers/src/conversions/xyz-to-lin-srgb.ts b/packages/color-helpers/src/conversions/xyz-to-lin-srgb.ts index 8a2e1f609..582153c26 100644 --- a/packages/color-helpers/src/conversions/xyz-to-lin-srgb.ts +++ b/packages/color-helpers/src/conversions/xyz-to-lin-srgb.ts @@ -1,16 +1,16 @@ import type { Color } from '../types/color'; -import { multiplyMatrices } from '../calculations/multiply-matrices'; +import { Matrix, multiplyMatrices } from '../calculations/multiply-matrices'; + +const M: Matrix = [ + 12831 / 3959, -329 / 214, -1974 / 3959, + -851781 / 878810, 1648619 / 878810, 36519 / 878810, + 705 / 12673, -2585 / 12673, 705 / 667, +]; /** * @license W3C https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document * @copyright This software or document includes material copied from or derived from https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). */ export function XYZ_to_lin_sRGB(XYZ: Color): Color { - const M = [ - [12831 / 3959, -329 / 214, -1974 / 3959], - [-851781 / 878810, 1648619 / 878810, 36519 / 878810], - [705 / 12673, -2585 / 12673, 705 / 667], - ]; - - return multiplyMatrices(M, XYZ) as Color; + return multiplyMatrices(M, XYZ); } diff --git a/packages/color-helpers/src/conversions/xyz-to-oklab.ts b/packages/color-helpers/src/conversions/xyz-to-oklab.ts index 5611bbd61..4ffc03f9e 100644 --- a/packages/color-helpers/src/conversions/xyz-to-oklab.ts +++ b/packages/color-helpers/src/conversions/xyz-to-oklab.ts @@ -1,5 +1,16 @@ import type { Color } from '../types/color'; -import { multiplyMatrices } from '../calculations/multiply-matrices'; +import { Matrix, multiplyMatrices } from '../calculations/multiply-matrices'; + +const XYZtoLMS: Matrix = [ + 0.8190224379967030, 0.3619062600528904, -0.1288737815209879, + 0.0329836539323885, 0.9292868615863434, 0.0361446663506424, + 0.0481771893596242, 0.2642395317527308, 0.6335478284694309, +]; +const LMStoOKLab: Matrix = [ + 0.2104542683093140, 0.7936177747023054, -0.0040720430116193, + 1.9779985324311684, -2.4285922420485799, 0.4505937096174110, + 0.0259040424655478, 0.7827717124575296, -0.8086757549230774, +]; /** * @license W3C https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document @@ -10,18 +21,15 @@ import { multiplyMatrices } from '../calculations/multiply-matrices'; */ export function XYZ_to_OKLab(XYZ: Color): Color { // Given XYZ relative to D65, convert to OKLab - const XYZtoLMS = [ - [0.8190224379967030, 0.3619062600528904, -0.1288737815209879], - [0.0329836539323885, 0.9292868615863434, 0.0361446663506424], - [0.0481771893596242, 0.2642395317527308, 0.6335478284694309], - ]; - const LMStoOKLab = [ - [0.2104542683093140, 0.7936177747023054, -0.0040720430116193], - [1.9779985324311684, -2.4285922420485799, 0.4505937096174110], - [0.0259040424655478, 0.7827717124575296, -0.8086757549230774], - ]; + const LMS = multiplyMatrices(XYZtoLMS, XYZ); - const LMS = multiplyMatrices(XYZtoLMS, XYZ) as Color; - return multiplyMatrices(LMStoOKLab, LMS.map(c => Math.cbrt(c))) as Color; + return multiplyMatrices( + LMStoOKLab, + [ + Math.cbrt(LMS[0]), + Math.cbrt(LMS[1]), + Math.cbrt(LMS[2]), + ], + ); // L in range [0,1]. For use in CSS, multiply by 100 and add a percent } diff --git a/packages/css-color-parser/src/functions/named-color.ts b/packages/css-color-parser/src/functions/named-color.ts index 62d06d46a..aef8708c5 100644 --- a/packages/css-color-parser/src/functions/named-color.ts +++ b/packages/css-color-parser/src/functions/named-color.ts @@ -1,10 +1,10 @@ import type { ColorData } from '../color-data'; import { ColorNotation } from '../color-notation'; import { SyntaxFlag } from '../color-data'; -import { namedColors } from '@csstools/color-helpers'; +import { Color, namedColors } from '@csstools/color-helpers'; import { toLowerCaseAZ } from '../util/to-lower-case-a-z'; -const namedColorsMap = new Map(); +const namedColorsMap: Map = new Map(); for (const [name, color] of Object.entries(namedColors)) { namedColorsMap.set(name, color); } diff --git a/packages/css-parser-algorithms/CHANGELOG.md b/packages/css-parser-algorithms/CHANGELOG.md index ca064bae4..b031e9bf2 100644 --- a/packages/css-parser-algorithms/CHANGELOG.md +++ b/packages/css-parser-algorithms/CHANGELOG.md @@ -1,5 +1,9 @@ # Changes to CSS Parser Algorithms +### Unreleased (minor) + +- Add `isWhiteSpaceOrCommentNode` utility function. + ### 2.6.3 _May 4, 2024_ diff --git a/packages/css-parser-algorithms/dist/index.cjs b/packages/css-parser-algorithms/dist/index.cjs index 25eb6c2da..790cfebc6 100644 --- a/packages/css-parser-algorithms/dist/index.cjs +++ b/packages/css-parser-algorithms/dist/index.cjs @@ -1 +1 @@ -"use strict";var e,n=require("@csstools/css-tokenizer");function walkerIndexGenerator(e){let n=e.slice();return(e,o,t)=>{let s=-1;for(let i=n.indexOf(o);i=e.length)?-1:(n=e.slice(),s)}}function consumeComponentValue(e,o){const t=o[0];if(n.isTokenOpenParen(t)||n.isTokenOpenCurly(t)||n.isTokenOpenSquare(t)){const n=consumeSimpleBlock(e,o);return{advance:n.advance,node:n.node}}if(n.isTokenFunction(t)){const n=consumeFunction(e,o);return{advance:n.advance,node:n.node}}if(n.isTokenWhitespace(t)){const n=consumeWhitespace(e,o);return{advance:n.advance,node:n.node}}if(n.isTokenComment(t)){const n=consumeComment(e,o);return{advance:n.advance,node:n.node}}return{advance:1,node:new TokenNode(t)}}exports.ComponentValueType=void 0,(e=exports.ComponentValueType||(exports.ComponentValueType={})).Function="function",e.SimpleBlock="simple-block",e.Whitespace="whitespace",e.Comment="comment",e.Token="token";class ContainerNodeBaseClass{value=[];indexOf(e){return this.value.indexOf(e)}at(e){if("number"==typeof e)return e<0&&(e=this.value.length+e),this.value[e]}forEach(e,n){if(0===this.value.length)return;const o=walkerIndexGenerator(this.value);let t=0;for(;t!1!==e(n,o)&&((!("walk"in n.node)||!this.value.includes(n.node)||!1!==n.node.walk(e,n.state))&&void 0)),n)}}class FunctionNode extends ContainerNodeBaseClass{type=exports.ComponentValueType.Function;name;endToken;constructor(e,n,o){super(),this.name=e,this.endToken=n,this.value=o}getName(){return this.name[4].value}normalize(){n.isTokenEOF(this.endToken)&&(this.endToken=[n.TokenType.CloseParen,")",-1,-1,void 0])}tokens(){return n.isTokenEOF(this.endToken)?[this.name,...this.value.flatMap((e=>e.tokens()))]:[this.name,...this.value.flatMap((e=>e.tokens())),this.endToken]}toString(){const e=this.value.map((e=>n.isToken(e)?n.stringify(e):e.toString())).join("");return n.stringify(this.name)+e+n.stringify(this.endToken)}toJSON(){return{type:this.type,name:this.getName(),tokens:this.tokens(),value:this.value.map((e=>e.toJSON()))}}isFunctionNode(){return FunctionNode.isFunctionNode(this)}static isFunctionNode(e){return!!e&&(e instanceof FunctionNode&&e.type===exports.ComponentValueType.Function)}}function consumeFunction(e,o){const t=[];let s=1;for(;;){const i=o[s];if(!i||n.isTokenEOF(i))return e.onParseError(new n.ParseError("Unexpected EOF while consuming a function.",o[0][2],o[o.length-1][3],["5.4.9. Consume a function","Unexpected EOF"])),{advance:o.length,node:new FunctionNode(o[0],i,t)};if(n.isTokenCloseParen(i))return{advance:s+1,node:new FunctionNode(o[0],i,t)};if(n.isTokenWhiteSpaceOrComment(i)){const n=consumeAllCommentsAndWhitespace(e,o.slice(s));s+=n.advance,t.push(...n.nodes);continue}const r=consumeComponentValue(e,o.slice(s));s+=r.advance,t.push(r.node)}}class SimpleBlockNode extends ContainerNodeBaseClass{type=exports.ComponentValueType.SimpleBlock;startToken;endToken;constructor(e,n,o){super(),this.startToken=e,this.endToken=n,this.value=o}normalize(){if(n.isTokenEOF(this.endToken)){const e=n.mirrorVariant(this.startToken);e&&(this.endToken=e)}}tokens(){return n.isTokenEOF(this.endToken)?[this.startToken,...this.value.flatMap((e=>e.tokens()))]:[this.startToken,...this.value.flatMap((e=>e.tokens())),this.endToken]}toString(){const e=this.value.map((e=>n.isToken(e)?n.stringify(e):e.toString())).join("");return n.stringify(this.startToken)+e+n.stringify(this.endToken)}toJSON(){return{type:this.type,startToken:this.startToken,tokens:this.tokens(),value:this.value.map((e=>e.toJSON()))}}isSimpleBlockNode(){return SimpleBlockNode.isSimpleBlockNode(this)}static isSimpleBlockNode(e){return!!e&&(e instanceof SimpleBlockNode&&e.type===exports.ComponentValueType.SimpleBlock)}}function consumeSimpleBlock(e,o){const t=n.mirrorVariantType(o[0][0]);if(!t)throw new Error("Failed to parse, a mirror variant must exist for all block open tokens.");const s=[];let i=1;for(;;){const r=o[i];if(!r||n.isTokenEOF(r))return e.onParseError(new n.ParseError("Unexpected EOF while consuming a simple block.",o[0][2],o[o.length-1][3],["5.4.8. Consume a simple block","Unexpected EOF"])),{advance:o.length,node:new SimpleBlockNode(o[0],r,s)};if(r[0]===t)return{advance:i+1,node:new SimpleBlockNode(o[0],r,s)};if(n.isTokenWhiteSpaceOrComment(r)){const n=consumeAllCommentsAndWhitespace(e,o.slice(i));i+=n.advance,s.push(...n.nodes);continue}const a=consumeComponentValue(e,o.slice(i));i+=a.advance,s.push(a.node)}}class WhitespaceNode{type=exports.ComponentValueType.Whitespace;value;constructor(e){this.value=e}tokens(){return this.value}toString(){return n.stringify(...this.value)}toJSON(){return{type:this.type,tokens:this.tokens()}}isWhitespaceNode(){return WhitespaceNode.isWhitespaceNode(this)}static isWhitespaceNode(e){return!!e&&(e instanceof WhitespaceNode&&e.type===exports.ComponentValueType.Whitespace)}}function consumeWhitespace(e,o){let t=0;for(;;){const e=o[t];if(!n.isTokenWhitespace(e))return{advance:t,node:new WhitespaceNode(o.slice(0,t))};t++}}class CommentNode{type=exports.ComponentValueType.Comment;value;constructor(e){this.value=e}tokens(){return[this.value]}toString(){return n.stringify(this.value)}toJSON(){return{type:this.type,tokens:this.tokens()}}isCommentNode(){return CommentNode.isCommentNode(this)}static isCommentNode(e){return!!e&&(e instanceof CommentNode&&e.type===exports.ComponentValueType.Comment)}}function consumeComment(e,n){return{advance:1,node:new CommentNode(n[0])}}function consumeAllCommentsAndWhitespace(e,o){const t=[];let s=0;for(;;)if(n.isTokenWhitespace(o[s])){const e=consumeWhitespace(0,o.slice(s));s+=e.advance,t.push(e.node)}else{if(!n.isTokenComment(o[s]))return{advance:s,nodes:t};t.push(new CommentNode(o[s])),s++}}class TokenNode{type=exports.ComponentValueType.Token;value;constructor(e){this.value=e}tokens(){return[this.value]}toString(){return this.value[1]}toJSON(){return{type:this.type,tokens:this.tokens()}}isTokenNod(){return TokenNode.isTokenNode(this)}static isTokenNode(e){return!!e&&(e instanceof TokenNode&&e.type===exports.ComponentValueType.Token)}}function forEach(e,n,o){if(0===e.length)return;const t=walkerIndexGenerator(e);let s=0;for(;s!1!==n(o,t)&&((!("walk"in o.node)||!e.includes(o.node)||!1!==o.node.walk(n,o.state))&&void 0)),o)}exports.CommentNode=CommentNode,exports.ContainerNodeBaseClass=ContainerNodeBaseClass,exports.FunctionNode=FunctionNode,exports.SimpleBlockNode=SimpleBlockNode,exports.TokenNode=TokenNode,exports.WhitespaceNode=WhitespaceNode,exports.forEach=forEach,exports.gatherNodeAncestry=function gatherNodeAncestry(e){const n=new Map;return e.walk((e=>{Array.isArray(e.node)?e.node.forEach((o=>{n.set(o,e.parent)})):n.set(e.node,e.parent)})),n},exports.isCommentNode=function isCommentNode(e){return CommentNode.isCommentNode(e)},exports.isFunctionNode=function isFunctionNode(e){return FunctionNode.isFunctionNode(e)},exports.isSimpleBlockNode=function isSimpleBlockNode(e){return SimpleBlockNode.isSimpleBlockNode(e)},exports.isTokenNode=function isTokenNode(e){return TokenNode.isTokenNode(e)},exports.isWhitespaceNode=function isWhitespaceNode(e){return WhitespaceNode.isWhitespaceNode(e)},exports.parseCommaSeparatedListOfComponentValues=function parseCommaSeparatedListOfComponentValues(e,o){const t={onParseError:o?.onParseError??(()=>{})},s=[...e];if(0===e.length)return[];n.isTokenEOF(s[s.length-1])&&s.push([n.TokenType.EOF,"",s[s.length-1][2],s[s.length-1][3],void 0]);const i=[];let r=[],a=0;for(;;){if(!s[a]||n.isTokenEOF(s[a]))return r.length&&i.push(r),i;if(n.isTokenComma(s[a])){i.push(r),r=[],a++;continue}const o=consumeComponentValue(t,e.slice(a));r.push(o.node),a+=o.advance}},exports.parseComponentValue=function parseComponentValue(e,o){const t={onParseError:o?.onParseError??(()=>{})},s=[...e];n.isTokenEOF(s[s.length-1])&&s.push([n.TokenType.EOF,"",s[s.length-1][2],s[s.length-1][3],void 0]);const i=consumeComponentValue(t,s);if(n.isTokenEOF(s[Math.min(i.advance,s.length-1)]))return i.node;t.onParseError(new n.ParseError("Expected EOF after parsing a component value.",e[0][2],e[e.length-1][3],["5.3.9. Parse a component value","Expected EOF"]))},exports.parseListOfComponentValues=function parseListOfComponentValues(e,o){const t={onParseError:o?.onParseError??(()=>{})},s=[...e];n.isTokenEOF(s[s.length-1])&&s.push([n.TokenType.EOF,"",s[s.length-1][2],s[s.length-1][3],void 0]);const i=[];let r=0;for(;;){if(!s[r]||n.isTokenEOF(s[r]))return i;const e=consumeComponentValue(t,s.slice(r));i.push(e.node),r+=e.advance}},exports.replaceComponentValues=function replaceComponentValues(e,n){for(let o=0;o{if("number"!=typeof o)return;const t=n(e.node);t&&(Array.isArray(t)?e.parent.value.splice(o,1,...t):e.parent.value.splice(o,1,t))}))}return e},exports.sourceIndices=function sourceIndices(e){if(Array.isArray(e)){const n=e[0];if(!n)return[0,0];const o=e[e.length-1]||n;return[sourceIndices(n)[0],sourceIndices(o)[1]]}const n=e.tokens(),o=n[0],t=n[n.length-1];return o&&t?[o[2],t[3]]:[0,0]},exports.stringify=function stringify(e){return e.map((e=>e.map((e=>n.stringify(...e.tokens()))).join(""))).join(",")},exports.walk=walk,exports.walkerIndexGenerator=walkerIndexGenerator; +"use strict";var e,n=require("@csstools/css-tokenizer");function walkerIndexGenerator(e){let n=e.slice();return(e,o,t)=>{let s=-1;for(let i=n.indexOf(o);i=e.length)?-1:(n=e.slice(),s)}}function consumeComponentValue(e,o){const t=o[0];if(n.isTokenOpenParen(t)||n.isTokenOpenCurly(t)||n.isTokenOpenSquare(t)){const n=consumeSimpleBlock(e,o);return{advance:n.advance,node:n.node}}if(n.isTokenFunction(t)){const n=consumeFunction(e,o);return{advance:n.advance,node:n.node}}if(n.isTokenWhitespace(t)){const n=consumeWhitespace(e,o);return{advance:n.advance,node:n.node}}if(n.isTokenComment(t)){const n=consumeComment(e,o);return{advance:n.advance,node:n.node}}return{advance:1,node:new TokenNode(t)}}exports.ComponentValueType=void 0,(e=exports.ComponentValueType||(exports.ComponentValueType={})).Function="function",e.SimpleBlock="simple-block",e.Whitespace="whitespace",e.Comment="comment",e.Token="token";class ContainerNodeBaseClass{value=[];indexOf(e){return this.value.indexOf(e)}at(e){if("number"==typeof e)return e<0&&(e=this.value.length+e),this.value[e]}forEach(e,n){if(0===this.value.length)return;const o=walkerIndexGenerator(this.value);let t=0;for(;t!1!==e(n,o)&&((!("walk"in n.node)||!this.value.includes(n.node)||!1!==n.node.walk(e,n.state))&&void 0)),n)}}class FunctionNode extends ContainerNodeBaseClass{type=exports.ComponentValueType.Function;name;endToken;constructor(e,n,o){super(),this.name=e,this.endToken=n,this.value=o}getName(){return this.name[4].value}normalize(){n.isTokenEOF(this.endToken)&&(this.endToken=[n.TokenType.CloseParen,")",-1,-1,void 0])}tokens(){return n.isTokenEOF(this.endToken)?[this.name,...this.value.flatMap((e=>e.tokens()))]:[this.name,...this.value.flatMap((e=>e.tokens())),this.endToken]}toString(){const e=this.value.map((e=>n.isToken(e)?n.stringify(e):e.toString())).join("");return n.stringify(this.name)+e+n.stringify(this.endToken)}toJSON(){return{type:this.type,name:this.getName(),tokens:this.tokens(),value:this.value.map((e=>e.toJSON()))}}isFunctionNode(){return FunctionNode.isFunctionNode(this)}static isFunctionNode(e){return!!e&&(e instanceof FunctionNode&&e.type===exports.ComponentValueType.Function)}}function consumeFunction(e,o){const t=[];let s=1;for(;;){const i=o[s];if(!i||n.isTokenEOF(i))return e.onParseError(new n.ParseError("Unexpected EOF while consuming a function.",o[0][2],o[o.length-1][3],["5.4.9. Consume a function","Unexpected EOF"])),{advance:o.length,node:new FunctionNode(o[0],i,t)};if(n.isTokenCloseParen(i))return{advance:s+1,node:new FunctionNode(o[0],i,t)};if(n.isTokenWhiteSpaceOrComment(i)){const n=consumeAllCommentsAndWhitespace(e,o.slice(s));s+=n.advance,t.push(...n.nodes);continue}const r=consumeComponentValue(e,o.slice(s));s+=r.advance,t.push(r.node)}}class SimpleBlockNode extends ContainerNodeBaseClass{type=exports.ComponentValueType.SimpleBlock;startToken;endToken;constructor(e,n,o){super(),this.startToken=e,this.endToken=n,this.value=o}normalize(){if(n.isTokenEOF(this.endToken)){const e=n.mirrorVariant(this.startToken);e&&(this.endToken=e)}}tokens(){return n.isTokenEOF(this.endToken)?[this.startToken,...this.value.flatMap((e=>e.tokens()))]:[this.startToken,...this.value.flatMap((e=>e.tokens())),this.endToken]}toString(){const e=this.value.map((e=>n.isToken(e)?n.stringify(e):e.toString())).join("");return n.stringify(this.startToken)+e+n.stringify(this.endToken)}toJSON(){return{type:this.type,startToken:this.startToken,tokens:this.tokens(),value:this.value.map((e=>e.toJSON()))}}isSimpleBlockNode(){return SimpleBlockNode.isSimpleBlockNode(this)}static isSimpleBlockNode(e){return!!e&&(e instanceof SimpleBlockNode&&e.type===exports.ComponentValueType.SimpleBlock)}}function consumeSimpleBlock(e,o){const t=n.mirrorVariantType(o[0][0]);if(!t)throw new Error("Failed to parse, a mirror variant must exist for all block open tokens.");const s=[];let i=1;for(;;){const r=o[i];if(!r||n.isTokenEOF(r))return e.onParseError(new n.ParseError("Unexpected EOF while consuming a simple block.",o[0][2],o[o.length-1][3],["5.4.8. Consume a simple block","Unexpected EOF"])),{advance:o.length,node:new SimpleBlockNode(o[0],r,s)};if(r[0]===t)return{advance:i+1,node:new SimpleBlockNode(o[0],r,s)};if(n.isTokenWhiteSpaceOrComment(r)){const n=consumeAllCommentsAndWhitespace(e,o.slice(i));i+=n.advance,s.push(...n.nodes);continue}const a=consumeComponentValue(e,o.slice(i));i+=a.advance,s.push(a.node)}}class WhitespaceNode{type=exports.ComponentValueType.Whitespace;value;constructor(e){this.value=e}tokens(){return this.value}toString(){return n.stringify(...this.value)}toJSON(){return{type:this.type,tokens:this.tokens()}}isWhitespaceNode(){return WhitespaceNode.isWhitespaceNode(this)}static isWhitespaceNode(e){return!!e&&(e instanceof WhitespaceNode&&e.type===exports.ComponentValueType.Whitespace)}}function consumeWhitespace(e,o){let t=0;for(;;){const e=o[t];if(!n.isTokenWhitespace(e))return{advance:t,node:new WhitespaceNode(o.slice(0,t))};t++}}class CommentNode{type=exports.ComponentValueType.Comment;value;constructor(e){this.value=e}tokens(){return[this.value]}toString(){return n.stringify(this.value)}toJSON(){return{type:this.type,tokens:this.tokens()}}isCommentNode(){return CommentNode.isCommentNode(this)}static isCommentNode(e){return!!e&&(e instanceof CommentNode&&e.type===exports.ComponentValueType.Comment)}}function consumeComment(e,n){return{advance:1,node:new CommentNode(n[0])}}function consumeAllCommentsAndWhitespace(e,o){const t=[];let s=0;for(;;)if(n.isTokenWhitespace(o[s])){const e=consumeWhitespace(0,o.slice(s));s+=e.advance,t.push(e.node)}else{if(!n.isTokenComment(o[s]))return{advance:s,nodes:t};t.push(new CommentNode(o[s])),s++}}class TokenNode{type=exports.ComponentValueType.Token;value;constructor(e){this.value=e}tokens(){return[this.value]}toString(){return this.value[1]}toJSON(){return{type:this.type,tokens:this.tokens()}}isTokenNod(){return TokenNode.isTokenNode(this)}static isTokenNode(e){return!!e&&(e instanceof TokenNode&&e.type===exports.ComponentValueType.Token)}}function forEach(e,n,o){if(0===e.length)return;const t=walkerIndexGenerator(e);let s=0;for(;s!1!==n(o,t)&&((!("walk"in o.node)||!e.includes(o.node)||!1!==o.node.walk(n,o.state))&&void 0)),o)}function isWhitespaceNode(e){return WhitespaceNode.isWhitespaceNode(e)}function isCommentNode(e){return CommentNode.isCommentNode(e)}exports.CommentNode=CommentNode,exports.ContainerNodeBaseClass=ContainerNodeBaseClass,exports.FunctionNode=FunctionNode,exports.SimpleBlockNode=SimpleBlockNode,exports.TokenNode=TokenNode,exports.WhitespaceNode=WhitespaceNode,exports.forEach=forEach,exports.gatherNodeAncestry=function gatherNodeAncestry(e){const n=new Map;return e.walk((e=>{Array.isArray(e.node)?e.node.forEach((o=>{n.set(o,e.parent)})):n.set(e.node,e.parent)})),n},exports.isCommentNode=isCommentNode,exports.isFunctionNode=function isFunctionNode(e){return FunctionNode.isFunctionNode(e)},exports.isSimpleBlockNode=function isSimpleBlockNode(e){return SimpleBlockNode.isSimpleBlockNode(e)},exports.isTokenNode=function isTokenNode(e){return TokenNode.isTokenNode(e)},exports.isWhiteSpaceOrCommentNode=function isWhiteSpaceOrCommentNode(e){return isWhitespaceNode(e)||isCommentNode(e)},exports.isWhitespaceNode=isWhitespaceNode,exports.parseCommaSeparatedListOfComponentValues=function parseCommaSeparatedListOfComponentValues(e,o){const t={onParseError:o?.onParseError??(()=>{})},s=[...e];if(0===e.length)return[];n.isTokenEOF(s[s.length-1])&&s.push([n.TokenType.EOF,"",s[s.length-1][2],s[s.length-1][3],void 0]);const i=[];let r=[],a=0;for(;;){if(!s[a]||n.isTokenEOF(s[a]))return r.length&&i.push(r),i;if(n.isTokenComma(s[a])){i.push(r),r=[],a++;continue}const o=consumeComponentValue(t,e.slice(a));r.push(o.node),a+=o.advance}},exports.parseComponentValue=function parseComponentValue(e,o){const t={onParseError:o?.onParseError??(()=>{})},s=[...e];n.isTokenEOF(s[s.length-1])&&s.push([n.TokenType.EOF,"",s[s.length-1][2],s[s.length-1][3],void 0]);const i=consumeComponentValue(t,s);if(n.isTokenEOF(s[Math.min(i.advance,s.length-1)]))return i.node;t.onParseError(new n.ParseError("Expected EOF after parsing a component value.",e[0][2],e[e.length-1][3],["5.3.9. Parse a component value","Expected EOF"]))},exports.parseListOfComponentValues=function parseListOfComponentValues(e,o){const t={onParseError:o?.onParseError??(()=>{})},s=[...e];n.isTokenEOF(s[s.length-1])&&s.push([n.TokenType.EOF,"",s[s.length-1][2],s[s.length-1][3],void 0]);const i=[];let r=0;for(;;){if(!s[r]||n.isTokenEOF(s[r]))return i;const e=consumeComponentValue(t,s.slice(r));i.push(e.node),r+=e.advance}},exports.replaceComponentValues=function replaceComponentValues(e,n){for(let o=0;o{if("number"!=typeof o)return;const t=n(e.node);t&&(Array.isArray(t)?e.parent.value.splice(o,1,...t):e.parent.value.splice(o,1,t))}))}return e},exports.sourceIndices=function sourceIndices(e){if(Array.isArray(e)){const n=e[0];if(!n)return[0,0];const o=e[e.length-1]||n;return[sourceIndices(n)[0],sourceIndices(o)[1]]}const n=e.tokens(),o=n[0],t=n[n.length-1];return o&&t?[o[2],t[3]]:[0,0]},exports.stringify=function stringify(e){return e.map((e=>e.map((e=>n.stringify(...e.tokens()))).join(""))).join(",")},exports.walk=walk,exports.walkerIndexGenerator=walkerIndexGenerator; diff --git a/packages/css-parser-algorithms/dist/index.d.ts b/packages/css-parser-algorithms/dist/index.d.ts index 9889d9eae..23d6c120d 100644 --- a/packages/css-parser-algorithms/dist/index.d.ts +++ b/packages/css-parser-algorithms/dist/index.d.ts @@ -300,7 +300,7 @@ export declare class FunctionNode extends ContainerNodeBaseClass { */ export declare function gatherNodeAncestry(node: { walk(cb: (entry: { - node: Array | unknown; + node: unknown; parent: unknown; }, index: number | string) => boolean | void): false | undefined; }): Map; @@ -335,6 +335,12 @@ export declare function isTokenNode(x: unknown): x is TokenNode; */ export declare function isWhitespaceNode(x: unknown): x is WhitespaceNode; +/** + * Check if the current object is a `WhiteSpaceNode` or a `CommentNode`. + * This is a type guard. + */ +export declare function isWhiteSpaceOrCommentNode(x: unknown): x is WhitespaceNode | CommentNode; + /** * Parse a comma-separated list of component values. * diff --git a/packages/css-parser-algorithms/dist/index.mjs b/packages/css-parser-algorithms/dist/index.mjs index ecbde0ccf..251c8ffe4 100644 --- a/packages/css-parser-algorithms/dist/index.mjs +++ b/packages/css-parser-algorithms/dist/index.mjs @@ -1 +1 @@ -import{isTokenEOF as e,TokenType as n,isToken as t,stringify as o,mirrorVariant as s,isTokenOpenParen as i,isTokenOpenCurly as r,isTokenOpenSquare as a,isTokenFunction as c,isTokenWhitespace as u,isTokenComment as l,ParseError as d,isTokenCloseParen as h,isTokenWhiteSpaceOrComment as p,mirrorVariantType as m,isTokenComma as k}from"@csstools/css-tokenizer";var f;function walkerIndexGenerator(e){let n=e.slice();return(e,t,o)=>{let s=-1;for(let i=n.indexOf(t);i=e.length)?-1:(n=e.slice(),s)}}function consumeComponentValue(e,n){const t=n[0];if(i(t)||r(t)||a(t)){const t=consumeSimpleBlock(e,n);return{advance:t.advance,node:t.node}}if(c(t)){const t=consumeFunction(e,n);return{advance:t.advance,node:t.node}}if(u(t)){const t=consumeWhitespace(e,n);return{advance:t.advance,node:t.node}}if(l(t)){const t=consumeComment(e,n);return{advance:t.advance,node:t.node}}return{advance:1,node:new TokenNode(t)}}!function(e){e.Function="function",e.SimpleBlock="simple-block",e.Whitespace="whitespace",e.Comment="comment",e.Token="token"}(f||(f={}));class ContainerNodeBaseClass{value=[];indexOf(e){return this.value.indexOf(e)}at(e){if("number"==typeof e)return e<0&&(e=this.value.length+e),this.value[e]}forEach(e,n){if(0===this.value.length)return;const t=walkerIndexGenerator(this.value);let o=0;for(;o!1!==e(n,t)&&((!("walk"in n.node)||!this.value.includes(n.node)||!1!==n.node.walk(e,n.state))&&void 0)),n)}}class FunctionNode extends ContainerNodeBaseClass{type=f.Function;name;endToken;constructor(e,n,t){super(),this.name=e,this.endToken=n,this.value=t}getName(){return this.name[4].value}normalize(){e(this.endToken)&&(this.endToken=[n.CloseParen,")",-1,-1,void 0])}tokens(){return e(this.endToken)?[this.name,...this.value.flatMap((e=>e.tokens()))]:[this.name,...this.value.flatMap((e=>e.tokens())),this.endToken]}toString(){const e=this.value.map((e=>t(e)?o(e):e.toString())).join("");return o(this.name)+e+o(this.endToken)}toJSON(){return{type:this.type,name:this.getName(),tokens:this.tokens(),value:this.value.map((e=>e.toJSON()))}}isFunctionNode(){return FunctionNode.isFunctionNode(this)}static isFunctionNode(e){return!!e&&(e instanceof FunctionNode&&e.type===f.Function)}}function consumeFunction(n,t){const o=[];let s=1;for(;;){const i=t[s];if(!i||e(i))return n.onParseError(new d("Unexpected EOF while consuming a function.",t[0][2],t[t.length-1][3],["5.4.9. Consume a function","Unexpected EOF"])),{advance:t.length,node:new FunctionNode(t[0],i,o)};if(h(i))return{advance:s+1,node:new FunctionNode(t[0],i,o)};if(p(i)){const e=consumeAllCommentsAndWhitespace(n,t.slice(s));s+=e.advance,o.push(...e.nodes);continue}const r=consumeComponentValue(n,t.slice(s));s+=r.advance,o.push(r.node)}}class SimpleBlockNode extends ContainerNodeBaseClass{type=f.SimpleBlock;startToken;endToken;constructor(e,n,t){super(),this.startToken=e,this.endToken=n,this.value=t}normalize(){if(e(this.endToken)){const e=s(this.startToken);e&&(this.endToken=e)}}tokens(){return e(this.endToken)?[this.startToken,...this.value.flatMap((e=>e.tokens()))]:[this.startToken,...this.value.flatMap((e=>e.tokens())),this.endToken]}toString(){const e=this.value.map((e=>t(e)?o(e):e.toString())).join("");return o(this.startToken)+e+o(this.endToken)}toJSON(){return{type:this.type,startToken:this.startToken,tokens:this.tokens(),value:this.value.map((e=>e.toJSON()))}}isSimpleBlockNode(){return SimpleBlockNode.isSimpleBlockNode(this)}static isSimpleBlockNode(e){return!!e&&(e instanceof SimpleBlockNode&&e.type===f.SimpleBlock)}}function consumeSimpleBlock(n,t){const o=m(t[0][0]);if(!o)throw new Error("Failed to parse, a mirror variant must exist for all block open tokens.");const s=[];let i=1;for(;;){const r=t[i];if(!r||e(r))return n.onParseError(new d("Unexpected EOF while consuming a simple block.",t[0][2],t[t.length-1][3],["5.4.8. Consume a simple block","Unexpected EOF"])),{advance:t.length,node:new SimpleBlockNode(t[0],r,s)};if(r[0]===o)return{advance:i+1,node:new SimpleBlockNode(t[0],r,s)};if(p(r)){const e=consumeAllCommentsAndWhitespace(n,t.slice(i));i+=e.advance,s.push(...e.nodes);continue}const a=consumeComponentValue(n,t.slice(i));i+=a.advance,s.push(a.node)}}class WhitespaceNode{type=f.Whitespace;value;constructor(e){this.value=e}tokens(){return this.value}toString(){return o(...this.value)}toJSON(){return{type:this.type,tokens:this.tokens()}}isWhitespaceNode(){return WhitespaceNode.isWhitespaceNode(this)}static isWhitespaceNode(e){return!!e&&(e instanceof WhitespaceNode&&e.type===f.Whitespace)}}function consumeWhitespace(e,n){let t=0;for(;;){const e=n[t];if(!u(e))return{advance:t,node:new WhitespaceNode(n.slice(0,t))};t++}}class CommentNode{type=f.Comment;value;constructor(e){this.value=e}tokens(){return[this.value]}toString(){return o(this.value)}toJSON(){return{type:this.type,tokens:this.tokens()}}isCommentNode(){return CommentNode.isCommentNode(this)}static isCommentNode(e){return!!e&&(e instanceof CommentNode&&e.type===f.Comment)}}function consumeComment(e,n){return{advance:1,node:new CommentNode(n[0])}}function consumeAllCommentsAndWhitespace(e,n){const t=[];let o=0;for(;;)if(u(n[o])){const e=consumeWhitespace(0,n.slice(o));o+=e.advance,t.push(e.node)}else{if(!l(n[o]))return{advance:o,nodes:t};t.push(new CommentNode(n[o])),o++}}class TokenNode{type=f.Token;value;constructor(e){this.value=e}tokens(){return[this.value]}toString(){return this.value[1]}toJSON(){return{type:this.type,tokens:this.tokens()}}isTokenNod(){return TokenNode.isTokenNode(this)}static isTokenNode(e){return!!e&&(e instanceof TokenNode&&e.type===f.Token)}}function parseComponentValue(t,o){const s={onParseError:o?.onParseError??(()=>{})},i=[...t];e(i[i.length-1])&&i.push([n.EOF,"",i[i.length-1][2],i[i.length-1][3],void 0]);const r=consumeComponentValue(s,i);if(e(i[Math.min(r.advance,i.length-1)]))return r.node;s.onParseError(new d("Expected EOF after parsing a component value.",t[0][2],t[t.length-1][3],["5.3.9. Parse a component value","Expected EOF"]))}function parseListOfComponentValues(t,o){const s={onParseError:o?.onParseError??(()=>{})},i=[...t];e(i[i.length-1])&&i.push([n.EOF,"",i[i.length-1][2],i[i.length-1][3],void 0]);const r=[];let a=0;for(;;){if(!i[a]||e(i[a]))return r;const n=consumeComponentValue(s,i.slice(a));r.push(n.node),a+=n.advance}}function parseCommaSeparatedListOfComponentValues(t,o){const s={onParseError:o?.onParseError??(()=>{})},i=[...t];if(0===t.length)return[];e(i[i.length-1])&&i.push([n.EOF,"",i[i.length-1][2],i[i.length-1][3],void 0]);const r=[];let a=[],c=0;for(;;){if(!i[c]||e(i[c]))return a.length&&r.push(a),r;if(k(i[c])){r.push(a),a=[],c++;continue}const n=consumeComponentValue(s,t.slice(c));a.push(n.node),c+=n.advance}}function gatherNodeAncestry(e){const n=new Map;return e.walk((e=>{Array.isArray(e.node)?e.node.forEach((t=>{n.set(t,e.parent)})):n.set(e.node,e.parent)})),n}function forEach(e,n,t){if(0===e.length)return;const o=walkerIndexGenerator(e);let s=0;for(;s!1!==n(t,o)&&((!("walk"in t.node)||!e.includes(t.node)||!1!==t.node.walk(n,t.state))&&void 0)),t)}function replaceComponentValues(e,n){for(let t=0;t{if("number"!=typeof t)return;const o=n(e.node);o&&(Array.isArray(o)?e.parent.value.splice(t,1,...o):e.parent.value.splice(t,1,o))}))}return e}function stringify(e){return e.map((e=>e.map((e=>o(...e.tokens()))).join(""))).join(",")}function isSimpleBlockNode(e){return SimpleBlockNode.isSimpleBlockNode(e)}function isFunctionNode(e){return FunctionNode.isFunctionNode(e)}function isWhitespaceNode(e){return WhitespaceNode.isWhitespaceNode(e)}function isCommentNode(e){return CommentNode.isCommentNode(e)}function isTokenNode(e){return TokenNode.isTokenNode(e)}function sourceIndices(e){if(Array.isArray(e)){const n=e[0];if(!n)return[0,0];const t=e[e.length-1]||n;return[sourceIndices(n)[0],sourceIndices(t)[1]]}const n=e.tokens(),t=n[0],o=n[n.length-1];return t&&o?[t[2],o[3]]:[0,0]}export{CommentNode,f as ComponentValueType,ContainerNodeBaseClass,FunctionNode,SimpleBlockNode,TokenNode,WhitespaceNode,forEach,gatherNodeAncestry,isCommentNode,isFunctionNode,isSimpleBlockNode,isTokenNode,isWhitespaceNode,parseCommaSeparatedListOfComponentValues,parseComponentValue,parseListOfComponentValues,replaceComponentValues,sourceIndices,stringify,walk,walkerIndexGenerator}; +import{isTokenEOF as e,TokenType as n,isToken as t,stringify as o,mirrorVariant as s,isTokenOpenParen as i,isTokenOpenCurly as r,isTokenOpenSquare as a,isTokenFunction as c,isTokenWhitespace as u,isTokenComment as l,ParseError as d,isTokenCloseParen as h,isTokenWhiteSpaceOrComment as p,mirrorVariantType as m,isTokenComma as k}from"@csstools/css-tokenizer";var f;function walkerIndexGenerator(e){let n=e.slice();return(e,t,o)=>{let s=-1;for(let i=n.indexOf(t);i=e.length)?-1:(n=e.slice(),s)}}function consumeComponentValue(e,n){const t=n[0];if(i(t)||r(t)||a(t)){const t=consumeSimpleBlock(e,n);return{advance:t.advance,node:t.node}}if(c(t)){const t=consumeFunction(e,n);return{advance:t.advance,node:t.node}}if(u(t)){const t=consumeWhitespace(e,n);return{advance:t.advance,node:t.node}}if(l(t)){const t=consumeComment(e,n);return{advance:t.advance,node:t.node}}return{advance:1,node:new TokenNode(t)}}!function(e){e.Function="function",e.SimpleBlock="simple-block",e.Whitespace="whitespace",e.Comment="comment",e.Token="token"}(f||(f={}));class ContainerNodeBaseClass{value=[];indexOf(e){return this.value.indexOf(e)}at(e){if("number"==typeof e)return e<0&&(e=this.value.length+e),this.value[e]}forEach(e,n){if(0===this.value.length)return;const t=walkerIndexGenerator(this.value);let o=0;for(;o!1!==e(n,t)&&((!("walk"in n.node)||!this.value.includes(n.node)||!1!==n.node.walk(e,n.state))&&void 0)),n)}}class FunctionNode extends ContainerNodeBaseClass{type=f.Function;name;endToken;constructor(e,n,t){super(),this.name=e,this.endToken=n,this.value=t}getName(){return this.name[4].value}normalize(){e(this.endToken)&&(this.endToken=[n.CloseParen,")",-1,-1,void 0])}tokens(){return e(this.endToken)?[this.name,...this.value.flatMap((e=>e.tokens()))]:[this.name,...this.value.flatMap((e=>e.tokens())),this.endToken]}toString(){const e=this.value.map((e=>t(e)?o(e):e.toString())).join("");return o(this.name)+e+o(this.endToken)}toJSON(){return{type:this.type,name:this.getName(),tokens:this.tokens(),value:this.value.map((e=>e.toJSON()))}}isFunctionNode(){return FunctionNode.isFunctionNode(this)}static isFunctionNode(e){return!!e&&(e instanceof FunctionNode&&e.type===f.Function)}}function consumeFunction(n,t){const o=[];let s=1;for(;;){const i=t[s];if(!i||e(i))return n.onParseError(new d("Unexpected EOF while consuming a function.",t[0][2],t[t.length-1][3],["5.4.9. Consume a function","Unexpected EOF"])),{advance:t.length,node:new FunctionNode(t[0],i,o)};if(h(i))return{advance:s+1,node:new FunctionNode(t[0],i,o)};if(p(i)){const e=consumeAllCommentsAndWhitespace(n,t.slice(s));s+=e.advance,o.push(...e.nodes);continue}const r=consumeComponentValue(n,t.slice(s));s+=r.advance,o.push(r.node)}}class SimpleBlockNode extends ContainerNodeBaseClass{type=f.SimpleBlock;startToken;endToken;constructor(e,n,t){super(),this.startToken=e,this.endToken=n,this.value=t}normalize(){if(e(this.endToken)){const e=s(this.startToken);e&&(this.endToken=e)}}tokens(){return e(this.endToken)?[this.startToken,...this.value.flatMap((e=>e.tokens()))]:[this.startToken,...this.value.flatMap((e=>e.tokens())),this.endToken]}toString(){const e=this.value.map((e=>t(e)?o(e):e.toString())).join("");return o(this.startToken)+e+o(this.endToken)}toJSON(){return{type:this.type,startToken:this.startToken,tokens:this.tokens(),value:this.value.map((e=>e.toJSON()))}}isSimpleBlockNode(){return SimpleBlockNode.isSimpleBlockNode(this)}static isSimpleBlockNode(e){return!!e&&(e instanceof SimpleBlockNode&&e.type===f.SimpleBlock)}}function consumeSimpleBlock(n,t){const o=m(t[0][0]);if(!o)throw new Error("Failed to parse, a mirror variant must exist for all block open tokens.");const s=[];let i=1;for(;;){const r=t[i];if(!r||e(r))return n.onParseError(new d("Unexpected EOF while consuming a simple block.",t[0][2],t[t.length-1][3],["5.4.8. Consume a simple block","Unexpected EOF"])),{advance:t.length,node:new SimpleBlockNode(t[0],r,s)};if(r[0]===o)return{advance:i+1,node:new SimpleBlockNode(t[0],r,s)};if(p(r)){const e=consumeAllCommentsAndWhitespace(n,t.slice(i));i+=e.advance,s.push(...e.nodes);continue}const a=consumeComponentValue(n,t.slice(i));i+=a.advance,s.push(a.node)}}class WhitespaceNode{type=f.Whitespace;value;constructor(e){this.value=e}tokens(){return this.value}toString(){return o(...this.value)}toJSON(){return{type:this.type,tokens:this.tokens()}}isWhitespaceNode(){return WhitespaceNode.isWhitespaceNode(this)}static isWhitespaceNode(e){return!!e&&(e instanceof WhitespaceNode&&e.type===f.Whitespace)}}function consumeWhitespace(e,n){let t=0;for(;;){const e=n[t];if(!u(e))return{advance:t,node:new WhitespaceNode(n.slice(0,t))};t++}}class CommentNode{type=f.Comment;value;constructor(e){this.value=e}tokens(){return[this.value]}toString(){return o(this.value)}toJSON(){return{type:this.type,tokens:this.tokens()}}isCommentNode(){return CommentNode.isCommentNode(this)}static isCommentNode(e){return!!e&&(e instanceof CommentNode&&e.type===f.Comment)}}function consumeComment(e,n){return{advance:1,node:new CommentNode(n[0])}}function consumeAllCommentsAndWhitespace(e,n){const t=[];let o=0;for(;;)if(u(n[o])){const e=consumeWhitespace(0,n.slice(o));o+=e.advance,t.push(e.node)}else{if(!l(n[o]))return{advance:o,nodes:t};t.push(new CommentNode(n[o])),o++}}class TokenNode{type=f.Token;value;constructor(e){this.value=e}tokens(){return[this.value]}toString(){return this.value[1]}toJSON(){return{type:this.type,tokens:this.tokens()}}isTokenNod(){return TokenNode.isTokenNode(this)}static isTokenNode(e){return!!e&&(e instanceof TokenNode&&e.type===f.Token)}}function parseComponentValue(t,o){const s={onParseError:o?.onParseError??(()=>{})},i=[...t];e(i[i.length-1])&&i.push([n.EOF,"",i[i.length-1][2],i[i.length-1][3],void 0]);const r=consumeComponentValue(s,i);if(e(i[Math.min(r.advance,i.length-1)]))return r.node;s.onParseError(new d("Expected EOF after parsing a component value.",t[0][2],t[t.length-1][3],["5.3.9. Parse a component value","Expected EOF"]))}function parseListOfComponentValues(t,o){const s={onParseError:o?.onParseError??(()=>{})},i=[...t];e(i[i.length-1])&&i.push([n.EOF,"",i[i.length-1][2],i[i.length-1][3],void 0]);const r=[];let a=0;for(;;){if(!i[a]||e(i[a]))return r;const n=consumeComponentValue(s,i.slice(a));r.push(n.node),a+=n.advance}}function parseCommaSeparatedListOfComponentValues(t,o){const s={onParseError:o?.onParseError??(()=>{})},i=[...t];if(0===t.length)return[];e(i[i.length-1])&&i.push([n.EOF,"",i[i.length-1][2],i[i.length-1][3],void 0]);const r=[];let a=[],c=0;for(;;){if(!i[c]||e(i[c]))return a.length&&r.push(a),r;if(k(i[c])){r.push(a),a=[],c++;continue}const n=consumeComponentValue(s,t.slice(c));a.push(n.node),c+=n.advance}}function gatherNodeAncestry(e){const n=new Map;return e.walk((e=>{Array.isArray(e.node)?e.node.forEach((t=>{n.set(t,e.parent)})):n.set(e.node,e.parent)})),n}function forEach(e,n,t){if(0===e.length)return;const o=walkerIndexGenerator(e);let s=0;for(;s!1!==n(t,o)&&((!("walk"in t.node)||!e.includes(t.node)||!1!==t.node.walk(n,t.state))&&void 0)),t)}function replaceComponentValues(e,n){for(let t=0;t{if("number"!=typeof t)return;const o=n(e.node);o&&(Array.isArray(o)?e.parent.value.splice(t,1,...o):e.parent.value.splice(t,1,o))}))}return e}function stringify(e){return e.map((e=>e.map((e=>o(...e.tokens()))).join(""))).join(",")}function isSimpleBlockNode(e){return SimpleBlockNode.isSimpleBlockNode(e)}function isFunctionNode(e){return FunctionNode.isFunctionNode(e)}function isWhitespaceNode(e){return WhitespaceNode.isWhitespaceNode(e)}function isCommentNode(e){return CommentNode.isCommentNode(e)}function isWhiteSpaceOrCommentNode(e){return isWhitespaceNode(e)||isCommentNode(e)}function isTokenNode(e){return TokenNode.isTokenNode(e)}function sourceIndices(e){if(Array.isArray(e)){const n=e[0];if(!n)return[0,0];const t=e[e.length-1]||n;return[sourceIndices(n)[0],sourceIndices(t)[1]]}const n=e.tokens(),t=n[0],o=n[n.length-1];return t&&o?[t[2],o[3]]:[0,0]}export{CommentNode,f as ComponentValueType,ContainerNodeBaseClass,FunctionNode,SimpleBlockNode,TokenNode,WhitespaceNode,forEach,gatherNodeAncestry,isCommentNode,isFunctionNode,isSimpleBlockNode,isTokenNode,isWhiteSpaceOrCommentNode,isWhitespaceNode,parseCommaSeparatedListOfComponentValues,parseComponentValue,parseListOfComponentValues,replaceComponentValues,sourceIndices,stringify,walk,walkerIndexGenerator}; diff --git a/packages/css-parser-algorithms/docs/css-parser-algorithms.api.json b/packages/css-parser-algorithms/docs/css-parser-algorithms.api.json index b2400a8f6..86cdb00d8 100644 --- a/packages/css-parser-algorithms/docs/css-parser-algorithms.api.json +++ b/packages/css-parser-algorithms/docs/css-parser-algorithms.api.json @@ -1542,16 +1542,7 @@ }, { "kind": "Content", - "text": "{\n walk(cb: (entry: {\n node: " - }, - { - "kind": "Reference", - "text": "Array", - "canonicalReference": "!Array:interface" - }, - { - "kind": "Content", - "text": " | unknown;\n parent: unknown;\n }, index: number | string) => boolean | void): false | undefined;\n}" + "text": "{\n walk(cb: (entry: {\n node: unknown;\n parent: unknown;\n }, index: number | string) => boolean | void): false | undefined;\n}" }, { "kind": "Content", @@ -1573,8 +1564,8 @@ ], "fileUrlPath": "dist/_types/util/node-ancestry.d.ts", "returnTypeTokenRange": { - "startIndex": 5, - "endIndex": 7 + "startIndex": 3, + "endIndex": 5 }, "releaseTag": "Public", "overloadIndex": 1, @@ -1583,7 +1574,7 @@ "parameterName": "node", "parameterTypeTokenRange": { "startIndex": 1, - "endIndex": 4 + "endIndex": 2 }, "isOptional": false } @@ -1865,6 +1856,70 @@ ], "name": "isWhitespaceNode" }, + { + "kind": "Function", + "canonicalReference": "@csstools/css-parser-algorithms!isWhiteSpaceOrCommentNode:function(1)", + "docComment": "/**\n * Check if the current object is a `WhiteSpaceNode` or a `CommentNode`. This is a type guard.\n */\n", + "excerptTokens": [ + { + "kind": "Content", + "text": "export declare function isWhiteSpaceOrCommentNode(x: " + }, + { + "kind": "Content", + "text": "unknown" + }, + { + "kind": "Content", + "text": "): " + }, + { + "kind": "Reference", + "text": "x", + "canonicalReference": "@csstools/css-parser-algorithms!~x" + }, + { + "kind": "Content", + "text": " is " + }, + { + "kind": "Reference", + "text": "WhitespaceNode", + "canonicalReference": "@csstools/css-parser-algorithms!WhitespaceNode:class" + }, + { + "kind": "Content", + "text": " | " + }, + { + "kind": "Reference", + "text": "CommentNode", + "canonicalReference": "@csstools/css-parser-algorithms!CommentNode:class" + }, + { + "kind": "Content", + "text": ";" + } + ], + "fileUrlPath": "dist/_types/util/type-predicates.d.ts", + "returnTypeTokenRange": { + "startIndex": 3, + "endIndex": 8 + }, + "releaseTag": "Public", + "overloadIndex": 1, + "parameters": [ + { + "parameterName": "x", + "parameterTypeTokenRange": { + "startIndex": 1, + "endIndex": 2 + }, + "isOptional": false + } + ], + "name": "isWhiteSpaceOrCommentNode" + }, { "kind": "Function", "canonicalReference": "@csstools/css-parser-algorithms!parseCommaSeparatedListOfComponentValues:function(1)", diff --git a/packages/css-parser-algorithms/docs/css-parser-algorithms.gathernodeancestry.md b/packages/css-parser-algorithms/docs/css-parser-algorithms.gathernodeancestry.md index 5bdeafe70..bd7b80fc0 100644 --- a/packages/css-parser-algorithms/docs/css-parser-algorithms.gathernodeancestry.md +++ b/packages/css-parser-algorithms/docs/css-parser-algorithms.gathernodeancestry.md @@ -11,7 +11,7 @@ AST nodes do not have a `parent` property or method. This makes it harder to tra ```typescript export declare function gatherNodeAncestry(node: { walk(cb: (entry: { - node: Array | unknown; + node: unknown; parent: unknown; }, index: number | string) => boolean | void): false | undefined; }): Map; @@ -42,7 +42,7 @@ node -{ walk(cb: (entry: { node: Array<unknown> \| unknown; parent: unknown; }, index: number \| string) => boolean \| void): false \| undefined; } +{ walk(cb: (entry: { node: unknown; parent: unknown; }, index: number \| string) => boolean \| void): false \| undefined; } diff --git a/packages/css-parser-algorithms/docs/css-parser-algorithms.iswhitespaceorcommentnode.md b/packages/css-parser-algorithms/docs/css-parser-algorithms.iswhitespaceorcommentnode.md new file mode 100644 index 000000000..061c796b1 --- /dev/null +++ b/packages/css-parser-algorithms/docs/css-parser-algorithms.iswhitespaceorcommentnode.md @@ -0,0 +1,51 @@ + + +[Home](./index.md) > [@csstools/css-parser-algorithms](./css-parser-algorithms.md) > [isWhiteSpaceOrCommentNode](./css-parser-algorithms.iswhitespaceorcommentnode.md) + +## isWhiteSpaceOrCommentNode() function + +Check if the current object is a `WhiteSpaceNode` or a `CommentNode`. This is a type guard. + +**Signature:** + +```typescript +export declare function isWhiteSpaceOrCommentNode(x: unknown): x is WhitespaceNode | CommentNode; +``` + +## Parameters + + + +
+ +Parameter + + + + +Type + + + + +Description + + +
+ +x + + + + +unknown + + + + + +
+**Returns:** + +x is [WhitespaceNode](./css-parser-algorithms.whitespacenode.md) \| [CommentNode](./css-parser-algorithms.commentnode.md) + diff --git a/packages/css-parser-algorithms/docs/css-parser-algorithms.md b/packages/css-parser-algorithms/docs/css-parser-algorithms.md index 621006102..ac0c4cfae 100644 --- a/packages/css-parser-algorithms/docs/css-parser-algorithms.md +++ b/packages/css-parser-algorithms/docs/css-parser-algorithms.md @@ -280,6 +280,17 @@ Check if the current object is a `TokenNode`. This is a type guard. Check if the current object is a `WhitespaceNode`. This is a type guard. + + + +[isWhiteSpaceOrCommentNode(x)](./css-parser-algorithms.iswhitespaceorcommentnode.md) + + + + +Check if the current object is a `WhiteSpaceNode` or a `CommentNode`. This is a type guard. + + diff --git a/packages/css-parser-algorithms/src/consume/component-block-function.ts b/packages/css-parser-algorithms/src/consume/component-block-function.ts index 5d90dfdf1..e3c15d695 100644 --- a/packages/css-parser-algorithms/src/consume/component-block-function.ts +++ b/packages/css-parser-algorithms/src/consume/component-block-function.ts @@ -297,7 +297,6 @@ function consumeFunction(ctx: Context, tokens: Array): { advance: numb let i = 1; - // eslint-disable-next-line no-constant-condition while (true) { const token = tokens[i]; if (!token || isTokenEOF(token)) { @@ -476,7 +475,6 @@ function consumeSimpleBlock(ctx: Context, tokens: Array): { advance: n let i = 1; - // eslint-disable-next-line no-constant-condition while (true) { const token = tokens[i]; if (!token || isTokenEOF(token)) { @@ -587,7 +585,6 @@ export class WhitespaceNode { function consumeWhitespace(ctx: Context, tokens: Array): { advance: number, node: WhitespaceNode } { let i = 0; - // eslint-disable-next-line no-constant-condition while (true) { const token = tokens[i]; if (!isTokenWhitespace(token)) { @@ -683,7 +680,6 @@ function consumeAllCommentsAndWhitespace(ctx: Context, tokens: Array): let i = 0; - // eslint-disable-next-line no-constant-condition while (true) { if (isTokenWhitespace(tokens[i])) { const result = consumeWhitespace(ctx, tokens.slice(i)); diff --git a/packages/css-parser-algorithms/src/index.ts b/packages/css-parser-algorithms/src/index.ts index b73e2cccd..63105670a 100644 --- a/packages/css-parser-algorithms/src/index.ts +++ b/packages/css-parser-algorithms/src/index.ts @@ -102,5 +102,6 @@ export { isSimpleBlockNode, isTokenNode, isWhitespaceNode, + isWhiteSpaceOrCommentNode, } from './util/type-predicates'; export { sourceIndices } from './util/source-indices'; diff --git a/packages/css-parser-algorithms/src/parse/comma-separated-list-of-component-values.ts b/packages/css-parser-algorithms/src/parse/comma-separated-list-of-component-values.ts index f60713b0e..d000f7a31 100644 --- a/packages/css-parser-algorithms/src/parse/comma-separated-list-of-component-values.ts +++ b/packages/css-parser-algorithms/src/parse/comma-separated-list-of-component-values.ts @@ -42,7 +42,6 @@ export function parseCommaSeparatedListOfComponentValues(tokens: Array let i = 0; - // eslint-disable-next-line no-constant-condition while (true) { if (!tokensCopy[i] || isTokenEOF(tokensCopy[i])) { if (list.length) { diff --git a/packages/css-parser-algorithms/src/parse/list-of-component-values.ts b/packages/css-parser-algorithms/src/parse/list-of-component-values.ts index 1995a09b6..933795c3f 100644 --- a/packages/css-parser-algorithms/src/parse/list-of-component-values.ts +++ b/packages/css-parser-algorithms/src/parse/list-of-component-values.ts @@ -37,7 +37,6 @@ export function parseListOfComponentValues(tokens: Array, options?: { let i = 0; - // eslint-disable-next-line no-constant-condition while (true) { if (!tokensCopy[i] || isTokenEOF(tokensCopy[i])) { return list; diff --git a/packages/css-parser-algorithms/src/util/node-ancestry.ts b/packages/css-parser-algorithms/src/util/node-ancestry.ts index e4b603d1e..8db5b663d 100644 --- a/packages/css-parser-algorithms/src/util/node-ancestry.ts +++ b/packages/css-parser-algorithms/src/util/node-ancestry.ts @@ -24,7 +24,7 @@ * }); * ``` */ -export function gatherNodeAncestry(node: { walk(cb: (entry: { node: Array | unknown, parent: unknown }, index: number | string) => boolean | void): false | undefined }): Map { +export function gatherNodeAncestry(node: { walk(cb: (entry: { node: unknown, parent: unknown }, index: number | string) => boolean | void): false | undefined }): Map { const ancestry: Map = new Map(); node.walk((entry) => { diff --git a/packages/css-parser-algorithms/src/util/type-predicates.ts b/packages/css-parser-algorithms/src/util/type-predicates.ts index 0ca75e334..e46ce35c9 100644 --- a/packages/css-parser-algorithms/src/util/type-predicates.ts +++ b/packages/css-parser-algorithms/src/util/type-predicates.ts @@ -32,6 +32,14 @@ export function isCommentNode(x: unknown): x is CommentNode { return CommentNode.isCommentNode(x); } +/** + * Check if the current object is a `WhiteSpaceNode` or a `CommentNode`. + * This is a type guard. + */ +export function isWhiteSpaceOrCommentNode(x: unknown): x is WhitespaceNode | CommentNode { + return isWhitespaceNode(x) || isCommentNode(x); +} + /** * Check if the current object is a `TokenNode`. * This is a type guard. diff --git a/packages/css-tokenizer/CHANGELOG.md b/packages/css-tokenizer/CHANGELOG.md index 7307ef278..d88af36a6 100644 --- a/packages/css-tokenizer/CHANGELOG.md +++ b/packages/css-tokenizer/CHANGELOG.md @@ -1,5 +1,9 @@ # Changes to CSS Tokenizer +### Unreleased (patch) + +- Optimize `cloneTokens` + ### 2.3.1 _May 4, 2024_ diff --git a/packages/css-tokenizer/dist/index.cjs b/packages/css-tokenizer/dist/index.cjs index e83b1dd23..eafa89e9a 100644 --- a/packages/css-tokenizer/dist/index.cjs +++ b/packages/css-tokenizer/dist/index.cjs @@ -1 +1 @@ -"use strict";class ParseError extends Error{sourceStart;sourceEnd;parserState;constructor(e,o,n,r){super(e),this.name="ParseError",this.sourceStart=o,this.sourceEnd=n,this.parserState=r}}class Reader{cursor=0;source="";codePointSource=[];representationIndices=[-1];length=0;representationStart=0;representationEnd=-1;constructor(e){this.source=e;{let o=-1,n="";for(n of e)o+=n.length,this.codePointSource.push(n.codePointAt(0)),this.representationIndices.push(o)}this.length=this.codePointSource.length}advanceCodePoint(e=1){this.cursor=this.cursor+e,this.representationEnd=this.representationIndices[this.cursor]}readCodePoint(e=1){const o=this.codePointSource[this.cursor];return void 0!==o&&(this.cursor=this.cursor+e,this.representationEnd=this.representationIndices[this.cursor],o)}unreadCodePoint(e=1){this.cursor=this.cursor-e,this.representationEnd=this.representationIndices[this.cursor]}resetRepresentation(){this.representationStart=this.representationIndices[this.cursor]+1,this.representationEnd=-1}}const e=39,o=42,n=8,r=13,t=9,i=58,s=44,c=64,a=127,u=33,d=12,p=46,T=62,P=45,S=31,C=69,k=101,l=123,f=40,x=91,m=60,h=10,y=11,E=95,v=1114111,g=0,I=35,O=37,U=43,D=34,w=65533,R=92,A=125,L=41,N=93,b=59,q=14,W=47,F=32,H=117,B=85,V=114,z=82,K=108,M=76,$=63,J=48,_=70;function checkIfFourCodePointsWouldStartCDO(e){return e.codePointSource[e.cursor]===m&&e.codePointSource[e.cursor+1]===u&&e.codePointSource[e.cursor+2]===P&&e.codePointSource[e.cursor+3]===P}function isDigitCodePoint(e){return e>=48&&e<=57}function isUppercaseLetterCodePoint(e){return e>=65&&e<=90}function isLowercaseLetterCodePoint(e){return e>=97&&e<=122}function isHexDigitCodePoint(e){return isDigitCodePoint(e)||e>=97&&e<=102||e>=65&&e<=70}function isLetterCodePoint(e){return isLowercaseLetterCodePoint(e)||isUppercaseLetterCodePoint(e)}function isIdentStartCodePoint(e){return isLetterCodePoint(e)||isNonASCII_IdentCodePoint(e)||e===E}function isIdentCodePoint(e){return isIdentStartCodePoint(e)||isDigitCodePoint(e)||e===P}function isNonASCII_IdentCodePoint(e){return 183===e||8204===e||8205===e||8255===e||8256===e||8204===e||(192<=e&&e<=214||216<=e&&e<=246||248<=e&&e<=893||895<=e&&e<=8191||8304<=e&&e<=8591||11264<=e&&e<=12271||12289<=e&&e<=55295||63744<=e&&e<=64975||65008<=e&&e<=65533||e>=65536)}function isNewLine(e){return 10===e||13===e||12===e}function isWhitespace(e){return 32===e||10===e||9===e||13===e||12===e}function checkIfTwoCodePointsAreAValidEscape(e){return e.codePointSource[e.cursor]===R&&!isNewLine(e.codePointSource[e.cursor+1])}function checkIfThreeCodePointsWouldStartAnIdentSequence(e,o){return o.codePointSource[o.cursor]===P?o.codePointSource[o.cursor+1]===P||(!!isIdentStartCodePoint(o.codePointSource[o.cursor+1])||o.codePointSource[o.cursor+1]===R&&!isNewLine(o.codePointSource[o.cursor+2])):!!isIdentStartCodePoint(o.codePointSource[o.cursor])||checkIfTwoCodePointsAreAValidEscape(o)}function checkIfThreeCodePointsWouldStartANumber(e){return e.codePointSource[e.cursor]===U||e.codePointSource[e.cursor]===P?!!isDigitCodePoint(e.codePointSource[e.cursor+1])||e.codePointSource[e.cursor+1]===p&&isDigitCodePoint(e.codePointSource[e.cursor+2]):e.codePointSource[e.cursor]===p?isDigitCodePoint(e.codePointSource[e.cursor+1]):isDigitCodePoint(e.codePointSource[e.cursor])}function checkIfTwoCodePointsStartAComment(e){return e.codePointSource[e.cursor]===W&&e.codePointSource[e.cursor+1]===o}function checkIfThreeCodePointsWouldStartCDC(e){return e.codePointSource[e.cursor]===P&&e.codePointSource[e.cursor+1]===P&&e.codePointSource[e.cursor+2]===T}var j,Q,G;function consumeComment(e,n){for(n.advanceCodePoint(2);;){const r=n.readCodePoint();if(!1===r){e.onParseError(new ParseError("Unexpected EOF while consuming a comment.",n.representationStart,n.representationEnd,["4.3.2. Consume comments","Unexpected EOF"]));break}if(r===o&&(void 0!==n.codePointSource[n.cursor]&&n.codePointSource[n.cursor]===W)){n.advanceCodePoint();break}}return[exports.TokenType.Comment,n.source.slice(n.representationStart,n.representationEnd+1),n.representationStart,n.representationEnd,void 0]}function consumeEscapedCodePoint(e,o){const n=o.readCodePoint();if(!1===n)return e.onParseError(new ParseError("Unexpected EOF while consuming an escaped code point.",o.representationStart,o.representationEnd,["4.3.7. Consume an escaped code point","Unexpected EOF"])),w;if(isHexDigitCodePoint(n)){const e=[n];for(;void 0!==o.codePointSource[o.cursor]&&isHexDigitCodePoint(o.codePointSource[o.cursor])&&e.length<6;)e.push(o.codePointSource[o.cursor]),o.advanceCodePoint();isWhitespace(o.codePointSource[o.cursor])&&o.advanceCodePoint();const t=parseInt(String.fromCodePoint(...e),16);return 0===t?w:(r=t)>=55296&&r<=57343||t>v?w:t}var r;return n}function consumeIdentSequence(e,o){const n=[];for(;;)if(isIdentCodePoint(o.codePointSource[o.cursor]))n.push(o.codePointSource[o.cursor]),o.advanceCodePoint();else{if(!checkIfTwoCodePointsAreAValidEscape(o))return n;o.advanceCodePoint(),n.push(consumeEscapedCodePoint(e,o))}}function consumeHashToken(e,o){if(o.advanceCodePoint(),void 0!==o.codePointSource[o.cursor]&&(isIdentCodePoint(o.codePointSource[o.cursor])||checkIfTwoCodePointsAreAValidEscape(o))){let n=exports.HashType.Unrestricted;checkIfThreeCodePointsWouldStartAnIdentSequence(0,o)&&(n=exports.HashType.ID);const r=consumeIdentSequence(e,o);return[exports.TokenType.Hash,o.source.slice(o.representationStart,o.representationEnd+1),o.representationStart,o.representationEnd,{value:String.fromCodePoint(...r),type:n}]}return[exports.TokenType.Delim,"#",o.representationStart,o.representationEnd,{value:"#"}]}function consumeNumber(e,o){let n=exports.NumberType.Integer;for(o.codePointSource[o.cursor]!==U&&o.codePointSource[o.cursor]!==P||o.advanceCodePoint();isDigitCodePoint(o.codePointSource[o.cursor]);)o.advanceCodePoint();if(o.codePointSource[o.cursor]===p&&isDigitCodePoint(o.codePointSource[o.cursor+1]))for(o.advanceCodePoint(2),n=exports.NumberType.Number;isDigitCodePoint(o.codePointSource[o.cursor]);)o.advanceCodePoint();if(o.codePointSource[o.cursor]===k||o.codePointSource[o.cursor]===C){if(isDigitCodePoint(o.codePointSource[o.cursor+1]))o.advanceCodePoint(2);else{if(o.codePointSource[o.cursor+1]!==P&&o.codePointSource[o.cursor+1]!==U||!isDigitCodePoint(o.codePointSource[o.cursor+2]))return n;o.advanceCodePoint(3)}for(n=exports.NumberType.Number;isDigitCodePoint(o.codePointSource[o.cursor]);)o.advanceCodePoint()}return n}function consumeNumericToken(e,o){let n;{const e=o.codePointSource[o.cursor];e===P?n="-":e===U&&(n="+")}const r=consumeNumber(0,o),t=parseFloat(o.source.slice(o.representationStart,o.representationEnd+1));if(checkIfThreeCodePointsWouldStartAnIdentSequence(0,o)){const i=consumeIdentSequence(e,o);return[exports.TokenType.Dimension,o.source.slice(o.representationStart,o.representationEnd+1),o.representationStart,o.representationEnd,{value:t,signCharacter:n,type:r,unit:String.fromCodePoint(...i)}]}return o.codePointSource[o.cursor]===O?(o.advanceCodePoint(),[exports.TokenType.Percentage,o.source.slice(o.representationStart,o.representationEnd+1),o.representationStart,o.representationEnd,{value:t,signCharacter:n}]):[exports.TokenType.Number,o.source.slice(o.representationStart,o.representationEnd+1),o.representationStart,o.representationEnd,{value:t,signCharacter:n,type:r}]}function consumeWhiteSpace(e){for(;isWhitespace(e.codePointSource[e.cursor]);)e.advanceCodePoint();return[exports.TokenType.Whitespace,e.source.slice(e.representationStart,e.representationEnd+1),e.representationStart,e.representationEnd,void 0]}function consumeStringToken(e,o){let n="";const r=o.readCodePoint();for(;;){const t=o.readCodePoint();if(!1===t)return e.onParseError(new ParseError("Unexpected EOF while consuming a string token.",o.representationStart,o.representationEnd,["4.3.5. Consume a string token","Unexpected EOF"])),[exports.TokenType.String,o.source.slice(o.representationStart,o.representationEnd+1),o.representationStart,o.representationEnd,{value:n}];if(isNewLine(t))return e.onParseError(new ParseError("Unexpected newline while consuming a string token.",o.representationStart,o.representationEnd,["4.3.5. Consume a string token","Unexpected newline"])),o.unreadCodePoint(),[exports.TokenType.BadString,o.source.slice(o.representationStart,o.representationEnd+1),o.representationStart,o.representationEnd,void 0];if(t===r)return[exports.TokenType.String,o.source.slice(o.representationStart,o.representationEnd+1),o.representationStart,o.representationEnd,{value:n}];if(t!==R)n+=String.fromCodePoint(t);else{if(void 0===o.codePointSource[o.cursor])continue;if(isNewLine(o.codePointSource[o.cursor])){o.advanceCodePoint();continue}n+=String.fromCodePoint(consumeEscapedCodePoint(e,o))}}}function checkIfCodePointsMatchURLIdent(e){return!(3!==e.length||e[0]!==H&&e[0]!==B||e[1]!==V&&e[1]!==z||e[2]!==K&&e[2]!==M)}function consumeBadURL(e,o){for(;;){if(void 0===o.codePointSource[o.cursor])return;if(o.codePointSource[o.cursor]===L)return void o.advanceCodePoint();checkIfTwoCodePointsAreAValidEscape(o)?(o.advanceCodePoint(),consumeEscapedCodePoint(e,o)):o.advanceCodePoint()}}function consumeUrlToken(o,r){for(;isWhitespace(r.codePointSource[r.cursor]);)r.advanceCodePoint();let t="";for(;;){if(void 0===r.codePointSource[r.cursor])return o.onParseError(new ParseError("Unexpected EOF while consuming a url token.",r.representationStart,r.representationEnd,["4.3.6. Consume a url token","Unexpected EOF"])),[exports.TokenType.URL,r.source.slice(r.representationStart,r.representationEnd+1),r.representationStart,r.representationEnd,{value:t}];if(r.codePointSource[r.cursor]===L)return r.advanceCodePoint(),[exports.TokenType.URL,r.source.slice(r.representationStart,r.representationEnd+1),r.representationStart,r.representationEnd,{value:t}];if(isWhitespace(r.codePointSource[r.cursor])){for(r.advanceCodePoint();isWhitespace(r.codePointSource[r.cursor]);)r.advanceCodePoint();return void 0===r.codePointSource[r.cursor]?(o.onParseError(new ParseError("Unexpected EOF while consuming a url token.",r.representationStart,r.representationEnd,["4.3.6. Consume a url token","Consume as much whitespace as possible","Unexpected EOF"])),[exports.TokenType.URL,r.source.slice(r.representationStart,r.representationEnd+1),r.representationStart,r.representationEnd,{value:t}]):r.codePointSource[r.cursor]===L?(r.advanceCodePoint(),[exports.TokenType.URL,r.source.slice(r.representationStart,r.representationEnd+1),r.representationStart,r.representationEnd,{value:t}]):(consumeBadURL(o,r),[exports.TokenType.BadURL,r.source.slice(r.representationStart,r.representationEnd+1),r.representationStart,r.representationEnd,void 0])}if(r.codePointSource[r.cursor]===D||r.codePointSource[r.cursor]===e||r.codePointSource[r.cursor]===f||((i=r.codePointSource[r.cursor])===y||i===a||g<=i&&i<=n||q<=i&&i<=S))return consumeBadURL(o,r),o.onParseError(new ParseError("Unexpected character while consuming a url token.",r.representationStart,r.representationEnd,["4.3.6. Consume a url token","Unexpected U+0022 QUOTATION MARK (\"), U+0027 APOSTROPHE ('), U+0028 LEFT PARENTHESIS (() or non-printable code point"])),[exports.TokenType.BadURL,r.source.slice(r.representationStart,r.representationEnd+1),r.representationStart,r.representationEnd,void 0];if(r.codePointSource[r.cursor]===R){if(checkIfTwoCodePointsAreAValidEscape(r)){r.advanceCodePoint(),t+=String.fromCodePoint(consumeEscapedCodePoint(o,r));continue}return consumeBadURL(o,r),o.onParseError(new ParseError("Invalid escape sequence while consuming a url token.",r.representationStart,r.representationEnd,["4.3.6. Consume a url token","U+005C REVERSE SOLIDUS (\\)","The input stream does not start with a valid escape sequence"])),[exports.TokenType.BadURL,r.source.slice(r.representationStart,r.representationEnd+1),r.representationStart,r.representationEnd,void 0]}t+=String.fromCodePoint(r.codePointSource[r.cursor]),r.advanceCodePoint()}var i}function consumeIdentLikeToken(o,n){const r=consumeIdentSequence(o,n);if(n.codePointSource[n.cursor]!==f)return[exports.TokenType.Ident,n.source.slice(n.representationStart,n.representationEnd+1),n.representationStart,n.representationEnd,{value:String.fromCodePoint(...r)}];if(checkIfCodePointsMatchURLIdent(r)){n.advanceCodePoint();let t=0;for(;;){const o=isWhitespace(n.codePointSource[n.cursor]),i=isWhitespace(n.codePointSource[n.cursor+1]);if(o&&i){t+=1,n.advanceCodePoint(1);continue}const s=o?n.codePointSource[n.cursor+1]:n.codePointSource[n.cursor];if(s===D||s===e)return t>0&&n.unreadCodePoint(t),[exports.TokenType.Function,n.source.slice(n.representationStart,n.representationEnd+1),n.representationStart,n.representationEnd,{value:String.fromCodePoint(...r)}];break}return consumeUrlToken(o,n)}return n.advanceCodePoint(),[exports.TokenType.Function,n.source.slice(n.representationStart,n.representationEnd+1),n.representationStart,n.representationEnd,{value:String.fromCodePoint(...r)}]}function checkIfThreeCodePointsWouldStartAUnicodeRange(e){return!(e.codePointSource[e.cursor]!==H&&e.codePointSource[e.cursor]!==B||e.codePointSource[e.cursor+1]!==U||e.codePointSource[e.cursor+2]!==$&&!isHexDigitCodePoint(e.codePointSource[e.cursor+2]))}function consumeUnicodeRangeToken(e,o){o.advanceCodePoint(2);const n=[],r=[];for(;void 0!==o.codePointSource[o.cursor]&&n.length<6&&isHexDigitCodePoint(o.codePointSource[o.cursor]);)n.push(o.codePointSource[o.cursor]),o.advanceCodePoint();for(;void 0!==o.codePointSource[o.cursor]&&n.length<6&&o.codePointSource[o.cursor]===$;)0===r.length&&r.push(...n),n.push(J),r.push(_),o.advanceCodePoint();if(!r.length&&o.codePointSource[o.cursor]===P&&isHexDigitCodePoint(o.codePointSource[o.cursor+1]))for(o.advanceCodePoint();void 0!==o.codePointSource[o.cursor]&&r.length<6&&isHexDigitCodePoint(o.codePointSource[o.cursor]);)r.push(o.codePointSource[o.cursor]),o.advanceCodePoint();if(!r.length){const e=parseInt(String.fromCodePoint(...n),16);return[exports.TokenType.UnicodeRange,o.source.slice(o.representationStart,o.representationEnd+1),o.representationStart,o.representationEnd,{startOfRange:e,endOfRange:e}]}const t=parseInt(String.fromCodePoint(...n),16),i=parseInt(String.fromCodePoint(...r),16);return[exports.TokenType.UnicodeRange,o.source.slice(o.representationStart,o.representationEnd+1),o.representationStart,o.representationEnd,{startOfRange:t,endOfRange:i}]}function tokenizer(o,n){const a=o.css.valueOf(),u=o.unicodeRangesAllowed??!1,T=new Reader(a),S={onParseError:n?.onParseError??noop};return{nextToken:function nextToken(){T.resetRepresentation();const o=T.codePointSource[T.cursor];if(void 0===o)return[exports.TokenType.EOF,"",-1,-1,void 0];if(o===W&&checkIfTwoCodePointsStartAComment(T))return consumeComment(S,T);if(u&&(o===H||o===B)&&checkIfThreeCodePointsWouldStartAUnicodeRange(T))return consumeUnicodeRangeToken(0,T);if(isIdentStartCodePoint(o))return consumeIdentLikeToken(S,T);if(isDigitCodePoint(o))return consumeNumericToken(S,T);switch(o){case s:return T.advanceCodePoint(),[exports.TokenType.Comma,",",T.representationStart,T.representationEnd,void 0];case i:return T.advanceCodePoint(),[exports.TokenType.Colon,":",T.representationStart,T.representationEnd,void 0];case b:return T.advanceCodePoint(),[exports.TokenType.Semicolon,";",T.representationStart,T.representationEnd,void 0];case f:return T.advanceCodePoint(),[exports.TokenType.OpenParen,"(",T.representationStart,T.representationEnd,void 0];case L:return T.advanceCodePoint(),[exports.TokenType.CloseParen,")",T.representationStart,T.representationEnd,void 0];case x:return T.advanceCodePoint(),[exports.TokenType.OpenSquare,"[",T.representationStart,T.representationEnd,void 0];case N:return T.advanceCodePoint(),[exports.TokenType.CloseSquare,"]",T.representationStart,T.representationEnd,void 0];case l:return T.advanceCodePoint(),[exports.TokenType.OpenCurly,"{",T.representationStart,T.representationEnd,void 0];case A:return T.advanceCodePoint(),[exports.TokenType.CloseCurly,"}",T.representationStart,T.representationEnd,void 0];case e:case D:return consumeStringToken(S,T);case I:return consumeHashToken(S,T);case U:case p:return checkIfThreeCodePointsWouldStartANumber(T)?consumeNumericToken(S,T):(T.advanceCodePoint(),[exports.TokenType.Delim,T.source[T.representationStart],T.representationStart,T.representationEnd,{value:T.source[T.representationStart]}]);case h:case r:case d:case t:case F:return consumeWhiteSpace(T);case P:return checkIfThreeCodePointsWouldStartANumber(T)?consumeNumericToken(S,T):checkIfThreeCodePointsWouldStartCDC(T)?(T.advanceCodePoint(3),[exports.TokenType.CDC,"--\x3e",T.representationStart,T.representationEnd,void 0]):checkIfThreeCodePointsWouldStartAnIdentSequence(0,T)?consumeIdentLikeToken(S,T):(T.advanceCodePoint(),[exports.TokenType.Delim,"-",T.representationStart,T.representationEnd,{value:"-"}]);case m:return checkIfFourCodePointsWouldStartCDO(T)?(T.advanceCodePoint(4),[exports.TokenType.CDO,"\x3c!--",T.representationStart,T.representationEnd,void 0]):(T.advanceCodePoint(),[exports.TokenType.Delim,"<",T.representationStart,T.representationEnd,{value:"<"}]);case c:if(T.advanceCodePoint(),checkIfThreeCodePointsWouldStartAnIdentSequence(0,T)){const e=consumeIdentSequence(S,T);return[exports.TokenType.AtKeyword,T.source.slice(T.representationStart,T.representationEnd+1),T.representationStart,T.representationEnd,{value:String.fromCodePoint(...e)}]}return[exports.TokenType.Delim,"@",T.representationStart,T.representationEnd,{value:"@"}];case R:return checkIfTwoCodePointsAreAValidEscape(T)?consumeIdentLikeToken(S,T):(T.advanceCodePoint(),S.onParseError(new ParseError('Invalid escape sequence after "\\"',T.representationStart,T.representationEnd,["4.3.1. Consume a token","U+005C REVERSE SOLIDUS (\\)","The input stream does not start with a valid escape sequence"])),[exports.TokenType.Delim,"\\",T.representationStart,T.representationEnd,{value:"\\"}])}return T.advanceCodePoint(),[exports.TokenType.Delim,T.source[T.representationStart],T.representationStart,T.representationEnd,{value:T.source[T.representationStart]}]},endOfFile:function endOfFile(){return void 0===T.codePointSource[T.cursor]}}}function noop(){}function ensureThatValueRoundTripsAsIdent(e){let o=0;e[0]===P&&e[1]===P?o=2:e[0]===P&&e[1]?(o=2,isIdentStartCodePoint(e[1])||(o+=insertEscapedCodePoint(e,1,e[1]))):isIdentStartCodePoint(e[0])?o=1:(o=1,o+=insertEscapedCodePoint(e,0,e[0]));for(let n=o;n=48&&e<=57}function isUppercaseLetterCodePoint(e){return e>=65&&e<=90}function isLowercaseLetterCodePoint(e){return e>=97&&e<=122}function isHexDigitCodePoint(e){return isDigitCodePoint(e)||e>=97&&e<=102||e>=65&&e<=70}function isLetterCodePoint(e){return isLowercaseLetterCodePoint(e)||isUppercaseLetterCodePoint(e)}function isIdentStartCodePoint(e){return isLetterCodePoint(e)||isNonASCII_IdentCodePoint(e)||e===v}function isIdentCodePoint(e){return isIdentStartCodePoint(e)||isDigitCodePoint(e)||e===S}function isNonASCII_IdentCodePoint(e){return 183===e||8204===e||8205===e||8255===e||8256===e||8204===e||(192<=e&&e<=214||216<=e&&e<=246||248<=e&&e<=893||895<=e&&e<=8191||8304<=e&&e<=8591||11264<=e&&e<=12271||12289<=e&&e<=55295||63744<=e&&e<=64975||65008<=e&&e<=65533||e>=65536)}function isNewLine(e){return 10===e||13===e||12===e}function isWhitespace(e){return 32===e||10===e||9===e||13===e||12===e}function checkIfTwoCodePointsAreAValidEscape(e){return e.codePointSource[e.cursor]===A&&!isNewLine(e.codePointSource[e.cursor+1])}function checkIfThreeCodePointsWouldStartAnIdentSequence(e,o){return o.codePointSource[o.cursor]===S?o.codePointSource[o.cursor+1]===S||(!!isIdentStartCodePoint(o.codePointSource[o.cursor+1])||o.codePointSource[o.cursor+1]===A&&!isNewLine(o.codePointSource[o.cursor+2])):!!isIdentStartCodePoint(o.codePointSource[o.cursor])||checkIfTwoCodePointsAreAValidEscape(o)}function checkIfThreeCodePointsWouldStartANumber(e){return e.codePointSource[e.cursor]===D||e.codePointSource[e.cursor]===S?!!isDigitCodePoint(e.codePointSource[e.cursor+1])||e.codePointSource[e.cursor+1]===T&&isDigitCodePoint(e.codePointSource[e.cursor+2]):e.codePointSource[e.cursor]===T?isDigitCodePoint(e.codePointSource[e.cursor+1]):isDigitCodePoint(e.codePointSource[e.cursor])}function checkIfTwoCodePointsStartAComment(e){return e.codePointSource[e.cursor]===F&&e.codePointSource[e.cursor+1]===n}function checkIfThreeCodePointsWouldStartCDC(e){return e.codePointSource[e.cursor]===S&&e.codePointSource[e.cursor+1]===S&&e.codePointSource[e.cursor+2]===P}var Q,G,X;function consumeComment(e,o){for(o.advanceCodePoint(2);;){const r=o.readCodePoint();if(!1===r){e.onParseError(new ParseError("Unexpected EOF while consuming a comment.",o.representationStart,o.representationEnd,["4.3.2. Consume comments","Unexpected EOF"]));break}if(r===n&&(void 0!==o.codePointSource[o.cursor]&&o.codePointSource[o.cursor]===F)){o.advanceCodePoint();break}}return[exports.TokenType.Comment,o.source.slice(o.representationStart,o.representationEnd+1),o.representationStart,o.representationEnd,void 0]}function consumeEscapedCodePoint(e,o){const n=o.readCodePoint();if(!1===n)return e.onParseError(new ParseError("Unexpected EOF while consuming an escaped code point.",o.representationStart,o.representationEnd,["4.3.7. Consume an escaped code point","Unexpected EOF"])),R;if(isHexDigitCodePoint(n)){const e=[n];for(;void 0!==o.codePointSource[o.cursor]&&isHexDigitCodePoint(o.codePointSource[o.cursor])&&e.length<6;)e.push(o.codePointSource[o.cursor]),o.advanceCodePoint();isWhitespace(o.codePointSource[o.cursor])&&o.advanceCodePoint();const t=parseInt(String.fromCodePoint(...e),16);return 0===t?R:(r=t)>=55296&&r<=57343||t>g?R:t}var r;return n}function consumeIdentSequence(e,o){const n=[];for(;;)if(isIdentCodePoint(o.codePointSource[o.cursor]))n.push(o.codePointSource[o.cursor]),o.advanceCodePoint();else{if(!checkIfTwoCodePointsAreAValidEscape(o))return n;o.advanceCodePoint(),n.push(consumeEscapedCodePoint(e,o))}}function consumeHashToken(e,o){if(o.advanceCodePoint(),void 0!==o.codePointSource[o.cursor]&&(isIdentCodePoint(o.codePointSource[o.cursor])||checkIfTwoCodePointsAreAValidEscape(o))){let n=exports.HashType.Unrestricted;checkIfThreeCodePointsWouldStartAnIdentSequence(0,o)&&(n=exports.HashType.ID);const r=consumeIdentSequence(e,o);return[exports.TokenType.Hash,o.source.slice(o.representationStart,o.representationEnd+1),o.representationStart,o.representationEnd,{value:String.fromCodePoint(...r),type:n}]}return[exports.TokenType.Delim,"#",o.representationStart,o.representationEnd,{value:"#"}]}function consumeNumber(e,o){let n=exports.NumberType.Integer;for(o.codePointSource[o.cursor]!==D&&o.codePointSource[o.cursor]!==S||o.advanceCodePoint();isDigitCodePoint(o.codePointSource[o.cursor]);)o.advanceCodePoint();if(o.codePointSource[o.cursor]===T&&isDigitCodePoint(o.codePointSource[o.cursor+1]))for(o.advanceCodePoint(2),n=exports.NumberType.Number;isDigitCodePoint(o.codePointSource[o.cursor]);)o.advanceCodePoint();if(o.codePointSource[o.cursor]===l||o.codePointSource[o.cursor]===k){if(isDigitCodePoint(o.codePointSource[o.cursor+1]))o.advanceCodePoint(2);else{if(o.codePointSource[o.cursor+1]!==S&&o.codePointSource[o.cursor+1]!==D||!isDigitCodePoint(o.codePointSource[o.cursor+2]))return n;o.advanceCodePoint(3)}for(n=exports.NumberType.Number;isDigitCodePoint(o.codePointSource[o.cursor]);)o.advanceCodePoint()}return n}function consumeNumericToken(e,o){let n;{const e=o.codePointSource[o.cursor];e===S?n="-":e===D&&(n="+")}const r=consumeNumber(0,o),t=parseFloat(o.source.slice(o.representationStart,o.representationEnd+1));if(checkIfThreeCodePointsWouldStartAnIdentSequence(0,o)){const i=consumeIdentSequence(e,o);return[exports.TokenType.Dimension,o.source.slice(o.representationStart,o.representationEnd+1),o.representationStart,o.representationEnd,{value:t,signCharacter:n,type:r,unit:String.fromCodePoint(...i)}]}return o.codePointSource[o.cursor]===U?(o.advanceCodePoint(),[exports.TokenType.Percentage,o.source.slice(o.representationStart,o.representationEnd+1),o.representationStart,o.representationEnd,{value:t,signCharacter:n}]):[exports.TokenType.Number,o.source.slice(o.representationStart,o.representationEnd+1),o.representationStart,o.representationEnd,{value:t,signCharacter:n,type:r}]}function consumeWhiteSpace(e){for(;isWhitespace(e.codePointSource[e.cursor]);)e.advanceCodePoint();return[exports.TokenType.Whitespace,e.source.slice(e.representationStart,e.representationEnd+1),e.representationStart,e.representationEnd,void 0]}function consumeStringToken(e,o){let n="";const r=o.readCodePoint();for(;;){const t=o.readCodePoint();if(!1===t)return e.onParseError(new ParseError("Unexpected EOF while consuming a string token.",o.representationStart,o.representationEnd,["4.3.5. Consume a string token","Unexpected EOF"])),[exports.TokenType.String,o.source.slice(o.representationStart,o.representationEnd+1),o.representationStart,o.representationEnd,{value:n}];if(isNewLine(t))return e.onParseError(new ParseError("Unexpected newline while consuming a string token.",o.representationStart,o.representationEnd,["4.3.5. Consume a string token","Unexpected newline"])),o.unreadCodePoint(),[exports.TokenType.BadString,o.source.slice(o.representationStart,o.representationEnd+1),o.representationStart,o.representationEnd,void 0];if(t===r)return[exports.TokenType.String,o.source.slice(o.representationStart,o.representationEnd+1),o.representationStart,o.representationEnd,{value:n}];if(t!==A)n+=String.fromCodePoint(t);else{if(void 0===o.codePointSource[o.cursor])continue;if(isNewLine(o.codePointSource[o.cursor])){o.advanceCodePoint();continue}n+=String.fromCodePoint(consumeEscapedCodePoint(e,o))}}}function checkIfCodePointsMatchURLIdent(e){return!(3!==e.length||e[0]!==B&&e[0]!==V||e[1]!==z&&e[1]!==K||e[2]!==M&&e[2]!==$)}function consumeBadURL(e,o){for(;;){if(void 0===o.codePointSource[o.cursor])return;if(o.codePointSource[o.cursor]===N)return void o.advanceCodePoint();checkIfTwoCodePointsAreAValidEscape(o)?(o.advanceCodePoint(),consumeEscapedCodePoint(e,o)):o.advanceCodePoint()}}function consumeUrlToken(e,n){for(;isWhitespace(n.codePointSource[n.cursor]);)n.advanceCodePoint();let t="";for(;;){if(void 0===n.codePointSource[n.cursor])return e.onParseError(new ParseError("Unexpected EOF while consuming a url token.",n.representationStart,n.representationEnd,["4.3.6. Consume a url token","Unexpected EOF"])),[exports.TokenType.URL,n.source.slice(n.representationStart,n.representationEnd+1),n.representationStart,n.representationEnd,{value:t}];if(n.codePointSource[n.cursor]===N)return n.advanceCodePoint(),[exports.TokenType.URL,n.source.slice(n.representationStart,n.representationEnd+1),n.representationStart,n.representationEnd,{value:t}];if(isWhitespace(n.codePointSource[n.cursor])){for(n.advanceCodePoint();isWhitespace(n.codePointSource[n.cursor]);)n.advanceCodePoint();return void 0===n.codePointSource[n.cursor]?(e.onParseError(new ParseError("Unexpected EOF while consuming a url token.",n.representationStart,n.representationEnd,["4.3.6. Consume a url token","Consume as much whitespace as possible","Unexpected EOF"])),[exports.TokenType.URL,n.source.slice(n.representationStart,n.representationEnd+1),n.representationStart,n.representationEnd,{value:t}]):n.codePointSource[n.cursor]===N?(n.advanceCodePoint(),[exports.TokenType.URL,n.source.slice(n.representationStart,n.representationEnd+1),n.representationStart,n.representationEnd,{value:t}]):(consumeBadURL(e,n),[exports.TokenType.BadURL,n.source.slice(n.representationStart,n.representationEnd+1),n.representationStart,n.representationEnd,void 0])}if(n.codePointSource[n.cursor]===w||n.codePointSource[n.cursor]===o||n.codePointSource[n.cursor]===x||((i=n.codePointSource[n.cursor])===E||i===u||I<=i&&i<=r||W<=i&&i<=C))return consumeBadURL(e,n),e.onParseError(new ParseError("Unexpected character while consuming a url token.",n.representationStart,n.representationEnd,["4.3.6. Consume a url token","Unexpected U+0022 QUOTATION MARK (\"), U+0027 APOSTROPHE ('), U+0028 LEFT PARENTHESIS (() or non-printable code point"])),[exports.TokenType.BadURL,n.source.slice(n.representationStart,n.representationEnd+1),n.representationStart,n.representationEnd,void 0];if(n.codePointSource[n.cursor]===A){if(checkIfTwoCodePointsAreAValidEscape(n)){n.advanceCodePoint(),t+=String.fromCodePoint(consumeEscapedCodePoint(e,n));continue}return consumeBadURL(e,n),e.onParseError(new ParseError("Invalid escape sequence while consuming a url token.",n.representationStart,n.representationEnd,["4.3.6. Consume a url token","U+005C REVERSE SOLIDUS (\\)","The input stream does not start with a valid escape sequence"])),[exports.TokenType.BadURL,n.source.slice(n.representationStart,n.representationEnd+1),n.representationStart,n.representationEnd,void 0]}t+=String.fromCodePoint(n.codePointSource[n.cursor]),n.advanceCodePoint()}var i}function consumeIdentLikeToken(e,n){const r=consumeIdentSequence(e,n);if(n.codePointSource[n.cursor]!==x)return[exports.TokenType.Ident,n.source.slice(n.representationStart,n.representationEnd+1),n.representationStart,n.representationEnd,{value:String.fromCodePoint(...r)}];if(checkIfCodePointsMatchURLIdent(r)){n.advanceCodePoint();let t=0;for(;;){const e=isWhitespace(n.codePointSource[n.cursor]),i=isWhitespace(n.codePointSource[n.cursor+1]);if(e&&i){t+=1,n.advanceCodePoint(1);continue}const s=e?n.codePointSource[n.cursor+1]:n.codePointSource[n.cursor];if(s===w||s===o)return t>0&&n.unreadCodePoint(t),[exports.TokenType.Function,n.source.slice(n.representationStart,n.representationEnd+1),n.representationStart,n.representationEnd,{value:String.fromCodePoint(...r)}];break}return consumeUrlToken(e,n)}return n.advanceCodePoint(),[exports.TokenType.Function,n.source.slice(n.representationStart,n.representationEnd+1),n.representationStart,n.representationEnd,{value:String.fromCodePoint(...r)}]}function checkIfThreeCodePointsWouldStartAUnicodeRange(e){return!(e.codePointSource[e.cursor]!==B&&e.codePointSource[e.cursor]!==V||e.codePointSource[e.cursor+1]!==D||e.codePointSource[e.cursor+2]!==J&&!isHexDigitCodePoint(e.codePointSource[e.cursor+2]))}function consumeUnicodeRangeToken(e,o){o.advanceCodePoint(2);const n=[],r=[];for(;void 0!==o.codePointSource[o.cursor]&&n.length<6&&isHexDigitCodePoint(o.codePointSource[o.cursor]);)n.push(o.codePointSource[o.cursor]),o.advanceCodePoint();for(;void 0!==o.codePointSource[o.cursor]&&n.length<6&&o.codePointSource[o.cursor]===J;)0===r.length&&r.push(...n),n.push(_),r.push(j),o.advanceCodePoint();if(!r.length&&o.codePointSource[o.cursor]===S&&isHexDigitCodePoint(o.codePointSource[o.cursor+1]))for(o.advanceCodePoint();void 0!==o.codePointSource[o.cursor]&&r.length<6&&isHexDigitCodePoint(o.codePointSource[o.cursor]);)r.push(o.codePointSource[o.cursor]),o.advanceCodePoint();if(!r.length){const e=parseInt(String.fromCodePoint(...n),16);return[exports.TokenType.UnicodeRange,o.source.slice(o.representationStart,o.representationEnd+1),o.representationStart,o.representationEnd,{startOfRange:e,endOfRange:e}]}const t=parseInt(String.fromCodePoint(...n),16),i=parseInt(String.fromCodePoint(...r),16);return[exports.TokenType.UnicodeRange,o.source.slice(o.representationStart,o.representationEnd+1),o.representationStart,o.representationEnd,{startOfRange:t,endOfRange:i}]}function tokenizer(e,n){const r=e.css.valueOf(),u=e.unicodeRangesAllowed??!1,d=new Reader(r),P={onParseError:n?.onParseError??noop};return{nextToken:function nextToken(){d.resetRepresentation();const e=d.codePointSource[d.cursor];if(void 0===e)return[exports.TokenType.EOF,"",-1,-1,void 0];if(e===F&&checkIfTwoCodePointsStartAComment(d))return consumeComment(P,d);if(u&&(e===B||e===V)&&checkIfThreeCodePointsWouldStartAUnicodeRange(d))return consumeUnicodeRangeToken(0,d);if(isIdentStartCodePoint(e))return consumeIdentLikeToken(P,d);if(isDigitCodePoint(e))return consumeNumericToken(P,d);switch(e){case c:return d.advanceCodePoint(),[exports.TokenType.Comma,",",d.representationStart,d.representationEnd,void 0];case s:return d.advanceCodePoint(),[exports.TokenType.Colon,":",d.representationStart,d.representationEnd,void 0];case q:return d.advanceCodePoint(),[exports.TokenType.Semicolon,";",d.representationStart,d.representationEnd,void 0];case x:return d.advanceCodePoint(),[exports.TokenType.OpenParen,"(",d.representationStart,d.representationEnd,void 0];case N:return d.advanceCodePoint(),[exports.TokenType.CloseParen,")",d.representationStart,d.representationEnd,void 0];case m:return d.advanceCodePoint(),[exports.TokenType.OpenSquare,"[",d.representationStart,d.representationEnd,void 0];case b:return d.advanceCodePoint(),[exports.TokenType.CloseSquare,"]",d.representationStart,d.representationEnd,void 0];case f:return d.advanceCodePoint(),[exports.TokenType.OpenCurly,"{",d.representationStart,d.representationEnd,void 0];case L:return d.advanceCodePoint(),[exports.TokenType.CloseCurly,"}",d.representationStart,d.representationEnd,void 0];case o:case w:return consumeStringToken(P,d);case O:return consumeHashToken(P,d);case D:case T:return checkIfThreeCodePointsWouldStartANumber(d)?consumeNumericToken(P,d):(d.advanceCodePoint(),[exports.TokenType.Delim,d.source[d.representationStart],d.representationStart,d.representationEnd,{value:d.source[d.representationStart]}]);case y:case t:case p:case i:case H:return consumeWhiteSpace(d);case S:return checkIfThreeCodePointsWouldStartANumber(d)?consumeNumericToken(P,d):checkIfThreeCodePointsWouldStartCDC(d)?(d.advanceCodePoint(3),[exports.TokenType.CDC,"--\x3e",d.representationStart,d.representationEnd,void 0]):checkIfThreeCodePointsWouldStartAnIdentSequence(0,d)?consumeIdentLikeToken(P,d):(d.advanceCodePoint(),[exports.TokenType.Delim,"-",d.representationStart,d.representationEnd,{value:"-"}]);case h:return checkIfFourCodePointsWouldStartCDO(d)?(d.advanceCodePoint(4),[exports.TokenType.CDO,"\x3c!--",d.representationStart,d.representationEnd,void 0]):(d.advanceCodePoint(),[exports.TokenType.Delim,"<",d.representationStart,d.representationEnd,{value:"<"}]);case a:if(d.advanceCodePoint(),checkIfThreeCodePointsWouldStartAnIdentSequence(0,d)){const e=consumeIdentSequence(P,d);return[exports.TokenType.AtKeyword,d.source.slice(d.representationStart,d.representationEnd+1),d.representationStart,d.representationEnd,{value:String.fromCodePoint(...e)}]}return[exports.TokenType.Delim,"@",d.representationStart,d.representationEnd,{value:"@"}];case A:return checkIfTwoCodePointsAreAValidEscape(d)?consumeIdentLikeToken(P,d):(d.advanceCodePoint(),P.onParseError(new ParseError('Invalid escape sequence after "\\"',d.representationStart,d.representationEnd,["4.3.1. Consume a token","U+005C REVERSE SOLIDUS (\\)","The input stream does not start with a valid escape sequence"])),[exports.TokenType.Delim,"\\",d.representationStart,d.representationEnd,{value:"\\"}])}return d.advanceCodePoint(),[exports.TokenType.Delim,d.source[d.representationStart],d.representationStart,d.representationEnd,{value:d.source[d.representationStart]}]},endOfFile:function endOfFile(){return void 0===d.codePointSource[d.cursor]}}}function noop(){}function ensureThatValueRoundTripsAsIdent(e){let o=0;e[0]===S&&e[1]===S?o=2:e[0]===S&&e[1]?(o=2,isIdentStartCodePoint(e[1])||(o+=insertEscapedCodePoint(e,1,e[1]))):isIdentStartCodePoint(e[0])?o=1:(o=1,o+=insertEscapedCodePoint(e,0,e[0]));for(let n=o;n=48&&e<=57}function isUppercaseLetterCodePoint(e){return e>=65&&e<=90}function isLowercaseLetterCodePoint(e){return e>=97&&e<=122}function isHexDigitCodePoint(e){return isDigitCodePoint(e)||e>=97&&e<=102||e>=65&&e<=70}function isLetterCodePoint(e){return isLowercaseLetterCodePoint(e)||isUppercaseLetterCodePoint(e)}function isIdentStartCodePoint(e){return isLetterCodePoint(e)||isNonASCII_IdentCodePoint(e)||e===T}function isIdentCodePoint(e){return isIdentStartCodePoint(e)||isDigitCodePoint(e)||e===S}function isNonASCII_IdentCodePoint(e){return 183===e||8204===e||8205===e||8255===e||8256===e||8204===e||(192<=e&&e<=214||216<=e&&e<=246||248<=e&&e<=893||895<=e&&e<=8191||8304<=e&&e<=8591||11264<=e&&e<=12271||12289<=e&&e<=55295||63744<=e&&e<=64975||65008<=e&&e<=65533||e>=65536)}function isNewLine(e){return 10===e||13===e||12===e}function isWhitespace(e){return 32===e||10===e||9===e||13===e||12===e}function checkIfTwoCodePointsAreAValidEscape(e){return e.codePointSource[e.cursor]===L&&!isNewLine(e.codePointSource[e.cursor+1])}function checkIfThreeCodePointsWouldStartAnIdentSequence(e,n){return n.codePointSource[n.cursor]===S?n.codePointSource[n.cursor+1]===S||(!!isIdentStartCodePoint(n.codePointSource[n.cursor+1])||n.codePointSource[n.cursor+1]===L&&!isNewLine(n.codePointSource[n.cursor+2])):!!isIdentStartCodePoint(n.codePointSource[n.cursor])||checkIfTwoCodePointsAreAValidEscape(n)}function checkIfThreeCodePointsWouldStartANumber(e){return e.codePointSource[e.cursor]===w||e.codePointSource[e.cursor]===S?!!isDigitCodePoint(e.codePointSource[e.cursor+1])||e.codePointSource[e.cursor+1]===P&&isDigitCodePoint(e.codePointSource[e.cursor+2]):e.codePointSource[e.cursor]===P?isDigitCodePoint(e.codePointSource[e.cursor+1]):isDigitCodePoint(e.codePointSource[e.cursor])}function checkIfTwoCodePointsStartAComment(e){return e.codePointSource[e.cursor]===F&&e.codePointSource[e.cursor+1]===n}function checkIfThreeCodePointsWouldStartCDC(e){return e.codePointSource[e.cursor]===S&&e.codePointSource[e.cursor+1]===S&&e.codePointSource[e.cursor+2]===p}var j,Q,G;function mirrorVariantType(e){switch(e){case j.OpenParen:return j.CloseParen;case j.CloseParen:return j.OpenParen;case j.OpenCurly:return j.CloseCurly;case j.CloseCurly:return j.OpenCurly;case j.OpenSquare:return j.CloseSquare;case j.CloseSquare:return j.OpenSquare;default:return null}}function mirrorVariant(e){switch(e[0]){case j.OpenParen:return[j.CloseParen,")",-1,-1,void 0];case j.CloseParen:return[j.OpenParen,"(",-1,-1,void 0];case j.OpenCurly:return[j.CloseCurly,"}",-1,-1,void 0];case j.CloseCurly:return[j.OpenCurly,"{",-1,-1,void 0];case j.OpenSquare:return[j.CloseSquare,"]",-1,-1,void 0];case j.CloseSquare:return[j.OpenSquare,"[",-1,-1,void 0];default:return null}}function consumeComment(e,o){for(o.advanceCodePoint(2);;){const r=o.readCodePoint();if(!1===r){e.onParseError(new ParseError("Unexpected EOF while consuming a comment.",o.representationStart,o.representationEnd,["4.3.2. Consume comments","Unexpected EOF"]));break}if(r===n&&(void 0!==o.codePointSource[o.cursor]&&o.codePointSource[o.cursor]===F)){o.advanceCodePoint();break}}return[j.Comment,o.source.slice(o.representationStart,o.representationEnd+1),o.representationStart,o.representationEnd,void 0]}function consumeEscapedCodePoint(e,n){const o=n.readCodePoint();if(!1===o)return e.onParseError(new ParseError("Unexpected EOF while consuming an escaped code point.",n.representationStart,n.representationEnd,["4.3.7. Consume an escaped code point","Unexpected EOF"])),A;if(isHexDigitCodePoint(o)){const e=[o];for(;void 0!==n.codePointSource[n.cursor]&&isHexDigitCodePoint(n.codePointSource[n.cursor])&&e.length<6;)e.push(n.codePointSource[n.cursor]),n.advanceCodePoint();isWhitespace(n.codePointSource[n.cursor])&&n.advanceCodePoint();const t=parseInt(String.fromCodePoint(...e),16);return 0===t?A:(r=t)>=55296&&r<=57343||t>I?A:t}var r;return o}function consumeIdentSequence(e,n){const o=[];for(;;)if(isIdentCodePoint(n.codePointSource[n.cursor]))o.push(n.codePointSource[n.cursor]),n.advanceCodePoint();else{if(!checkIfTwoCodePointsAreAValidEscape(n))return o;n.advanceCodePoint(),o.push(consumeEscapedCodePoint(e,n))}}function consumeHashToken(e,n){if(n.advanceCodePoint(),void 0!==n.codePointSource[n.cursor]&&(isIdentCodePoint(n.codePointSource[n.cursor])||checkIfTwoCodePointsAreAValidEscape(n))){let o=G.Unrestricted;checkIfThreeCodePointsWouldStartAnIdentSequence(0,n)&&(o=G.ID);const r=consumeIdentSequence(e,n);return[j.Hash,n.source.slice(n.representationStart,n.representationEnd+1),n.representationStart,n.representationEnd,{value:String.fromCodePoint(...r),type:o}]}return[j.Delim,"#",n.representationStart,n.representationEnd,{value:"#"}]}function consumeNumber(e,n){let o=Q.Integer;for(n.codePointSource[n.cursor]!==w&&n.codePointSource[n.cursor]!==S||n.advanceCodePoint();isDigitCodePoint(n.codePointSource[n.cursor]);)n.advanceCodePoint();if(n.codePointSource[n.cursor]===P&&isDigitCodePoint(n.codePointSource[n.cursor+1]))for(n.advanceCodePoint(2),o=Q.Number;isDigitCodePoint(n.codePointSource[n.cursor]);)n.advanceCodePoint();if(n.codePointSource[n.cursor]===f||n.codePointSource[n.cursor]===l){if(isDigitCodePoint(n.codePointSource[n.cursor+1]))n.advanceCodePoint(2);else{if(n.codePointSource[n.cursor+1]!==S&&n.codePointSource[n.cursor+1]!==w||!isDigitCodePoint(n.codePointSource[n.cursor+2]))return o;n.advanceCodePoint(3)}for(o=Q.Number;isDigitCodePoint(n.codePointSource[n.cursor]);)n.advanceCodePoint()}return o}function consumeNumericToken(e,n){let o;{const e=n.codePointSource[n.cursor];e===S?o="-":e===w&&(o="+")}const r=consumeNumber(0,n),t=parseFloat(n.source.slice(n.representationStart,n.representationEnd+1));if(checkIfThreeCodePointsWouldStartAnIdentSequence(0,n)){const i=consumeIdentSequence(e,n);return[j.Dimension,n.source.slice(n.representationStart,n.representationEnd+1),n.representationStart,n.representationEnd,{value:t,signCharacter:o,type:r,unit:String.fromCodePoint(...i)}]}return n.codePointSource[n.cursor]===D?(n.advanceCodePoint(),[j.Percentage,n.source.slice(n.representationStart,n.representationEnd+1),n.representationStart,n.representationEnd,{value:t,signCharacter:o}]):[j.Number,n.source.slice(n.representationStart,n.representationEnd+1),n.representationStart,n.representationEnd,{value:t,signCharacter:o,type:r}]}function consumeWhiteSpace(e){for(;isWhitespace(e.codePointSource[e.cursor]);)e.advanceCodePoint();return[j.Whitespace,e.source.slice(e.representationStart,e.representationEnd+1),e.representationStart,e.representationEnd,void 0]}function consumeStringToken(e,n){let o="";const r=n.readCodePoint();for(;;){const t=n.readCodePoint();if(!1===t)return e.onParseError(new ParseError("Unexpected EOF while consuming a string token.",n.representationStart,n.representationEnd,["4.3.5. Consume a string token","Unexpected EOF"])),[j.String,n.source.slice(n.representationStart,n.representationEnd+1),n.representationStart,n.representationEnd,{value:o}];if(isNewLine(t))return e.onParseError(new ParseError("Unexpected newline while consuming a string token.",n.representationStart,n.representationEnd,["4.3.5. Consume a string token","Unexpected newline"])),n.unreadCodePoint(),[j.BadString,n.source.slice(n.representationStart,n.representationEnd+1),n.representationStart,n.representationEnd,void 0];if(t===r)return[j.String,n.source.slice(n.representationStart,n.representationEnd+1),n.representationStart,n.representationEnd,{value:o}];if(t!==L)o+=String.fromCodePoint(t);else{if(void 0===n.codePointSource[n.cursor])continue;if(isNewLine(n.codePointSource[n.cursor])){n.advanceCodePoint();continue}o+=String.fromCodePoint(consumeEscapedCodePoint(e,n))}}}function checkIfCodePointsMatchURLIdent(e){return!(3!==e.length||e[0]!==H&&e[0]!==B||e[1]!==V&&e[1]!==K||e[2]!==z&&e[2]!==M)}function consumeBadURL(e,n){for(;;){if(void 0===n.codePointSource[n.cursor])return;if(n.codePointSource[n.cursor]===q)return void n.advanceCodePoint();checkIfTwoCodePointsAreAValidEscape(n)?(n.advanceCodePoint(),consumeEscapedCodePoint(e,n)):n.advanceCodePoint()}}function consumeUrlToken(n,r){for(;isWhitespace(r.codePointSource[r.cursor]);)r.advanceCodePoint();let t="";for(;;){if(void 0===r.codePointSource[r.cursor])return n.onParseError(new ParseError("Unexpected EOF while consuming a url token.",r.representationStart,r.representationEnd,["4.3.6. Consume a url token","Unexpected EOF"])),[j.URL,r.source.slice(r.representationStart,r.representationEnd+1),r.representationStart,r.representationEnd,{value:t}];if(r.codePointSource[r.cursor]===q)return r.advanceCodePoint(),[j.URL,r.source.slice(r.representationStart,r.representationEnd+1),r.representationStart,r.representationEnd,{value:t}];if(isWhitespace(r.codePointSource[r.cursor])){for(r.advanceCodePoint();isWhitespace(r.codePointSource[r.cursor]);)r.advanceCodePoint();return void 0===r.codePointSource[r.cursor]?(n.onParseError(new ParseError("Unexpected EOF while consuming a url token.",r.representationStart,r.representationEnd,["4.3.6. Consume a url token","Consume as much whitespace as possible","Unexpected EOF"])),[j.URL,r.source.slice(r.representationStart,r.representationEnd+1),r.representationStart,r.representationEnd,{value:t}]):r.codePointSource[r.cursor]===q?(r.advanceCodePoint(),[j.URL,r.source.slice(r.representationStart,r.representationEnd+1),r.representationStart,r.representationEnd,{value:t}]):(consumeBadURL(n,r),[j.BadURL,r.source.slice(r.representationStart,r.representationEnd+1),r.representationStart,r.representationEnd,void 0])}if(r.codePointSource[r.cursor]===R||r.codePointSource[r.cursor]===e||r.codePointSource[r.cursor]===h||((i=r.codePointSource[r.cursor])===g||i===a||O<=i&&i<=o||x<=i&&i<=C))return consumeBadURL(n,r),n.onParseError(new ParseError("Unexpected character while consuming a url token.",r.representationStart,r.representationEnd,["4.3.6. Consume a url token","Unexpected U+0022 QUOTATION MARK (\"), U+0027 APOSTROPHE ('), U+0028 LEFT PARENTHESIS (() or non-printable code point"])),[j.BadURL,r.source.slice(r.representationStart,r.representationEnd+1),r.representationStart,r.representationEnd,void 0];if(r.codePointSource[r.cursor]===L){if(checkIfTwoCodePointsAreAValidEscape(r)){r.advanceCodePoint(),t+=String.fromCodePoint(consumeEscapedCodePoint(n,r));continue}return consumeBadURL(n,r),n.onParseError(new ParseError("Invalid escape sequence while consuming a url token.",r.representationStart,r.representationEnd,["4.3.6. Consume a url token","U+005C REVERSE SOLIDUS (\\)","The input stream does not start with a valid escape sequence"])),[j.BadURL,r.source.slice(r.representationStart,r.representationEnd+1),r.representationStart,r.representationEnd,void 0]}t+=String.fromCodePoint(r.codePointSource[r.cursor]),r.advanceCodePoint()}var i}function consumeIdentLikeToken(n,o){const r=consumeIdentSequence(n,o);if(o.codePointSource[o.cursor]!==h)return[j.Ident,o.source.slice(o.representationStart,o.representationEnd+1),o.representationStart,o.representationEnd,{value:String.fromCodePoint(...r)}];if(checkIfCodePointsMatchURLIdent(r)){o.advanceCodePoint();let t=0;for(;;){const n=isWhitespace(o.codePointSource[o.cursor]),i=isWhitespace(o.codePointSource[o.cursor+1]);if(n&&i){t+=1,o.advanceCodePoint(1);continue}const s=n?o.codePointSource[o.cursor+1]:o.codePointSource[o.cursor];if(s===R||s===e)return t>0&&o.unreadCodePoint(t),[j.Function,o.source.slice(o.representationStart,o.representationEnd+1),o.representationStart,o.representationEnd,{value:String.fromCodePoint(...r)}];break}return consumeUrlToken(n,o)}return o.advanceCodePoint(),[j.Function,o.source.slice(o.representationStart,o.representationEnd+1),o.representationStart,o.representationEnd,{value:String.fromCodePoint(...r)}]}function checkIfThreeCodePointsWouldStartAUnicodeRange(e){return!(e.codePointSource[e.cursor]!==H&&e.codePointSource[e.cursor]!==B||e.codePointSource[e.cursor+1]!==w||e.codePointSource[e.cursor+2]!==$&&!isHexDigitCodePoint(e.codePointSource[e.cursor+2]))}function consumeUnicodeRangeToken(e,n){n.advanceCodePoint(2);const o=[],r=[];for(;void 0!==n.codePointSource[n.cursor]&&o.length<6&&isHexDigitCodePoint(n.codePointSource[n.cursor]);)o.push(n.codePointSource[n.cursor]),n.advanceCodePoint();for(;void 0!==n.codePointSource[n.cursor]&&o.length<6&&n.codePointSource[n.cursor]===$;)0===r.length&&r.push(...o),o.push(J),r.push(_),n.advanceCodePoint();if(!r.length&&n.codePointSource[n.cursor]===S&&isHexDigitCodePoint(n.codePointSource[n.cursor+1]))for(n.advanceCodePoint();void 0!==n.codePointSource[n.cursor]&&r.length<6&&isHexDigitCodePoint(n.codePointSource[n.cursor]);)r.push(n.codePointSource[n.cursor]),n.advanceCodePoint();if(!r.length){const e=parseInt(String.fromCodePoint(...o),16);return[j.UnicodeRange,n.source.slice(n.representationStart,n.representationEnd+1),n.representationStart,n.representationEnd,{startOfRange:e,endOfRange:e}]}const t=parseInt(String.fromCodePoint(...o),16),i=parseInt(String.fromCodePoint(...r),16);return[j.UnicodeRange,n.source.slice(n.representationStart,n.representationEnd+1),n.representationStart,n.representationEnd,{startOfRange:t,endOfRange:i}]}function tokenize(e,n){const o=tokenizer(e,n),r=[];{for(;!o.endOfFile();){const e=o.nextToken();e&&r.push(e)}const e=o.nextToken();e&&r.push(e)}return r}function tokenizer(n,o){const a=n.css.valueOf(),u=n.unicodeRangesAllowed??!1,p=new Reader(a),C={onParseError:o?.onParseError??noop};return{nextToken:function nextToken(){p.resetRepresentation();const n=p.codePointSource[p.cursor];if(void 0===n)return[j.EOF,"",-1,-1,void 0];if(n===F&&checkIfTwoCodePointsStartAComment(p))return consumeComment(C,p);if(u&&(n===H||n===B)&&checkIfThreeCodePointsWouldStartAUnicodeRange(p))return consumeUnicodeRangeToken(0,p);if(isIdentStartCodePoint(n))return consumeIdentLikeToken(C,p);if(isDigitCodePoint(n))return consumeNumericToken(C,p);switch(n){case s:return p.advanceCodePoint(),[j.Comma,",",p.representationStart,p.representationEnd,void 0];case i:return p.advanceCodePoint(),[j.Colon,":",p.representationStart,p.representationEnd,void 0];case N:return p.advanceCodePoint(),[j.Semicolon,";",p.representationStart,p.representationEnd,void 0];case h:return p.advanceCodePoint(),[j.OpenParen,"(",p.representationStart,p.representationEnd,void 0];case q:return p.advanceCodePoint(),[j.CloseParen,")",p.representationStart,p.representationEnd,void 0];case k:return p.advanceCodePoint(),[j.OpenSquare,"[",p.representationStart,p.representationEnd,void 0];case W:return p.advanceCodePoint(),[j.CloseSquare,"]",p.representationStart,p.representationEnd,void 0];case m:return p.advanceCodePoint(),[j.OpenCurly,"{",p.representationStart,p.representationEnd,void 0];case y:return p.advanceCodePoint(),[j.CloseCurly,"}",p.representationStart,p.representationEnd,void 0];case e:case R:return consumeStringToken(C,p);case U:return consumeHashToken(C,p);case w:case P:return checkIfThreeCodePointsWouldStartANumber(p)?consumeNumericToken(C,p):(p.advanceCodePoint(),[j.Delim,p.source[p.representationStart],p.representationStart,p.representationEnd,{value:p.source[p.representationStart]}]);case v:case r:case d:case t:case b:return consumeWhiteSpace(p);case S:return checkIfThreeCodePointsWouldStartANumber(p)?consumeNumericToken(C,p):checkIfThreeCodePointsWouldStartCDC(p)?(p.advanceCodePoint(3),[j.CDC,"--\x3e",p.representationStart,p.representationEnd,void 0]):checkIfThreeCodePointsWouldStartAnIdentSequence(0,p)?consumeIdentLikeToken(C,p):(p.advanceCodePoint(),[j.Delim,"-",p.representationStart,p.representationEnd,{value:"-"}]);case E:return checkIfFourCodePointsWouldStartCDO(p)?(p.advanceCodePoint(4),[j.CDO,"\x3c!--",p.representationStart,p.representationEnd,void 0]):(p.advanceCodePoint(),[j.Delim,"<",p.representationStart,p.representationEnd,{value:"<"}]);case c:if(p.advanceCodePoint(),checkIfThreeCodePointsWouldStartAnIdentSequence(0,p)){const e=consumeIdentSequence(C,p);return[j.AtKeyword,p.source.slice(p.representationStart,p.representationEnd+1),p.representationStart,p.representationEnd,{value:String.fromCodePoint(...e)}]}return[j.Delim,"@",p.representationStart,p.representationEnd,{value:"@"}];case L:return checkIfTwoCodePointsAreAValidEscape(p)?consumeIdentLikeToken(C,p):(p.advanceCodePoint(),C.onParseError(new ParseError('Invalid escape sequence after "\\"',p.representationStart,p.representationEnd,["4.3.1. Consume a token","U+005C REVERSE SOLIDUS (\\)","The input stream does not start with a valid escape sequence"])),[j.Delim,"\\",p.representationStart,p.representationEnd,{value:"\\"}])}return p.advanceCodePoint(),[j.Delim,p.source[p.representationStart],p.representationStart,p.representationEnd,{value:p.source[p.representationStart]}]},endOfFile:function endOfFile(){return void 0===p.codePointSource[p.cursor]}}}function noop(){}function mutateIdent(e,n){const o=[];for(const e of n)o.push(e.codePointAt(0));const r=String.fromCodePoint(...ensureThatValueRoundTripsAsIdent(o));e[1]=r,e[4].value=n}function mutateUnit(e,n){const o=[];for(const e of n)o.push(e.codePointAt(0));const r=ensureThatValueRoundTripsAsIdent(o);101===r[0]&&insertEscapedCodePoint(r,0,r[0]);const t=String.fromCodePoint(...r),i="+"===e[4].signCharacter?e[4].signCharacter:"",s=e[4].value.toString();e[1]=`${i}${s}${t}`,e[4].unit=n}function ensureThatValueRoundTripsAsIdent(e){let n=0;e[0]===S&&e[1]===S?n=2:e[0]===S&&e[1]?(n=2,isIdentStartCodePoint(e[1])||(n+=insertEscapedCodePoint(e,1,e[1]))):isIdentStartCodePoint(e[0])?n=1:(n=1,n+=insertEscapedCodePoint(e,0,e[0]));for(let o=n;o=48&&e<=57}function isUppercaseLetterCodePoint(e){return e>=65&&e<=90}function isLowercaseLetterCodePoint(e){return e>=97&&e<=122}function isHexDigitCodePoint(e){return isDigitCodePoint(e)||e>=97&&e<=102||e>=65&&e<=70}function isLetterCodePoint(e){return isLowercaseLetterCodePoint(e)||isUppercaseLetterCodePoint(e)}function isIdentStartCodePoint(e){return isLetterCodePoint(e)||isNonASCII_IdentCodePoint(e)||e===I}function isIdentCodePoint(e){return isIdentStartCodePoint(e)||isDigitCodePoint(e)||e===C}function isNonASCII_IdentCodePoint(e){return 183===e||8204===e||8205===e||8255===e||8256===e||8204===e||(192<=e&&e<=214||216<=e&&e<=246||248<=e&&e<=893||895<=e&&e<=8191||8304<=e&&e<=8591||11264<=e&&e<=12271||12289<=e&&e<=55295||63744<=e&&e<=64975||65008<=e&&e<=65533||e>=65536)}function isNewLine(e){return 10===e||13===e||12===e}function isWhitespace(e){return 32===e||10===e||9===e||13===e||12===e}function checkIfTwoCodePointsAreAValidEscape(e){return e.codePointSource[e.cursor]===y&&!isNewLine(e.codePointSource[e.cursor+1])}function checkIfThreeCodePointsWouldStartAnIdentSequence(e,n){return n.codePointSource[n.cursor]===C?n.codePointSource[n.cursor+1]===C||(!!isIdentStartCodePoint(n.codePointSource[n.cursor+1])||n.codePointSource[n.cursor+1]===y&&!isNewLine(n.codePointSource[n.cursor+2])):!!isIdentStartCodePoint(n.codePointSource[n.cursor])||checkIfTwoCodePointsAreAValidEscape(n)}function checkIfThreeCodePointsWouldStartANumber(e){return e.codePointSource[e.cursor]===R||e.codePointSource[e.cursor]===C?!!isDigitCodePoint(e.codePointSource[e.cursor+1])||e.codePointSource[e.cursor+1]===p&&isDigitCodePoint(e.codePointSource[e.cursor+2]):e.codePointSource[e.cursor]===p?isDigitCodePoint(e.codePointSource[e.cursor+1]):isDigitCodePoint(e.codePointSource[e.cursor])}function checkIfTwoCodePointsStartAComment(e){return e.codePointSource[e.cursor]===b&&e.codePointSource[e.cursor+1]===o}function checkIfThreeCodePointsWouldStartCDC(e){return e.codePointSource[e.cursor]===C&&e.codePointSource[e.cursor+1]===C&&e.codePointSource[e.cursor+2]===S}var Q,G,X;function mirrorVariantType(e){switch(e){case Q.OpenParen:return Q.CloseParen;case Q.CloseParen:return Q.OpenParen;case Q.OpenCurly:return Q.CloseCurly;case Q.CloseCurly:return Q.OpenCurly;case Q.OpenSquare:return Q.CloseSquare;case Q.CloseSquare:return Q.OpenSquare;default:return null}}function mirrorVariant(e){switch(e[0]){case Q.OpenParen:return[Q.CloseParen,")",-1,-1,void 0];case Q.CloseParen:return[Q.OpenParen,"(",-1,-1,void 0];case Q.OpenCurly:return[Q.CloseCurly,"}",-1,-1,void 0];case Q.CloseCurly:return[Q.OpenCurly,"{",-1,-1,void 0];case Q.OpenSquare:return[Q.CloseSquare,"]",-1,-1,void 0];case Q.CloseSquare:return[Q.OpenSquare,"[",-1,-1,void 0];default:return null}}function consumeComment(e,n){for(n.advanceCodePoint(2);;){const r=n.readCodePoint();if(!1===r){e.onParseError(new ParseError("Unexpected EOF while consuming a comment.",n.representationStart,n.representationEnd,["4.3.2. Consume comments","Unexpected EOF"]));break}if(r===o&&(void 0!==n.codePointSource[n.cursor]&&n.codePointSource[n.cursor]===b)){n.advanceCodePoint();break}}return[Q.Comment,n.source.slice(n.representationStart,n.representationEnd+1),n.representationStart,n.representationEnd,void 0]}function consumeEscapedCodePoint(e,n){const o=n.readCodePoint();if(!1===o)return e.onParseError(new ParseError("Unexpected EOF while consuming an escaped code point.",n.representationStart,n.representationEnd,["4.3.7. Consume an escaped code point","Unexpected EOF"])),L;if(isHexDigitCodePoint(o)){const e=[o];for(;void 0!==n.codePointSource[n.cursor]&&isHexDigitCodePoint(n.codePointSource[n.cursor])&&e.length<6;)e.push(n.codePointSource[n.cursor]),n.advanceCodePoint();isWhitespace(n.codePointSource[n.cursor])&&n.advanceCodePoint();const t=parseInt(String.fromCodePoint(...e),16);return 0===t?L:(r=t)>=55296&&r<=57343||t>O?L:t}var r;return o}function consumeIdentSequence(e,n){const o=[];for(;;)if(isIdentCodePoint(n.codePointSource[n.cursor]))o.push(n.codePointSource[n.cursor]),n.advanceCodePoint();else{if(!checkIfTwoCodePointsAreAValidEscape(n))return o;n.advanceCodePoint(),o.push(consumeEscapedCodePoint(e,n))}}function consumeHashToken(e,n){if(n.advanceCodePoint(),void 0!==n.codePointSource[n.cursor]&&(isIdentCodePoint(n.codePointSource[n.cursor])||checkIfTwoCodePointsAreAValidEscape(n))){let o=X.Unrestricted;checkIfThreeCodePointsWouldStartAnIdentSequence(0,n)&&(o=X.ID);const r=consumeIdentSequence(e,n);return[Q.Hash,n.source.slice(n.representationStart,n.representationEnd+1),n.representationStart,n.representationEnd,{value:String.fromCodePoint(...r),type:o}]}return[Q.Delim,"#",n.representationStart,n.representationEnd,{value:"#"}]}function consumeNumber(e,n){let o=G.Integer;for(n.codePointSource[n.cursor]!==R&&n.codePointSource[n.cursor]!==C||n.advanceCodePoint();isDigitCodePoint(n.codePointSource[n.cursor]);)n.advanceCodePoint();if(n.codePointSource[n.cursor]===p&&isDigitCodePoint(n.codePointSource[n.cursor+1]))for(n.advanceCodePoint(2),o=G.Number;isDigitCodePoint(n.codePointSource[n.cursor]);)n.advanceCodePoint();if(n.codePointSource[n.cursor]===m||n.codePointSource[n.cursor]===f){if(isDigitCodePoint(n.codePointSource[n.cursor+1]))n.advanceCodePoint(2);else{if(n.codePointSource[n.cursor+1]!==C&&n.codePointSource[n.cursor+1]!==R||!isDigitCodePoint(n.codePointSource[n.cursor+2]))return o;n.advanceCodePoint(3)}for(o=G.Number;isDigitCodePoint(n.codePointSource[n.cursor]);)n.advanceCodePoint()}return o}function consumeNumericToken(e,n){let o;{const e=n.codePointSource[n.cursor];e===C?o="-":e===R&&(o="+")}const r=consumeNumber(0,n),t=parseFloat(n.source.slice(n.representationStart,n.representationEnd+1));if(checkIfThreeCodePointsWouldStartAnIdentSequence(0,n)){const i=consumeIdentSequence(e,n);return[Q.Dimension,n.source.slice(n.representationStart,n.representationEnd+1),n.representationStart,n.representationEnd,{value:t,signCharacter:o,type:r,unit:String.fromCodePoint(...i)}]}return n.codePointSource[n.cursor]===w?(n.advanceCodePoint(),[Q.Percentage,n.source.slice(n.representationStart,n.representationEnd+1),n.representationStart,n.representationEnd,{value:t,signCharacter:o}]):[Q.Number,n.source.slice(n.representationStart,n.representationEnd+1),n.representationStart,n.representationEnd,{value:t,signCharacter:o,type:r}]}function consumeWhiteSpace(e){for(;isWhitespace(e.codePointSource[e.cursor]);)e.advanceCodePoint();return[Q.Whitespace,e.source.slice(e.representationStart,e.representationEnd+1),e.representationStart,e.representationEnd,void 0]}function consumeStringToken(e,n){let o="";const r=n.readCodePoint();for(;;){const t=n.readCodePoint();if(!1===t)return e.onParseError(new ParseError("Unexpected EOF while consuming a string token.",n.representationStart,n.representationEnd,["4.3.5. Consume a string token","Unexpected EOF"])),[Q.String,n.source.slice(n.representationStart,n.representationEnd+1),n.representationStart,n.representationEnd,{value:o}];if(isNewLine(t))return e.onParseError(new ParseError("Unexpected newline while consuming a string token.",n.representationStart,n.representationEnd,["4.3.5. Consume a string token","Unexpected newline"])),n.unreadCodePoint(),[Q.BadString,n.source.slice(n.representationStart,n.representationEnd+1),n.representationStart,n.representationEnd,void 0];if(t===r)return[Q.String,n.source.slice(n.representationStart,n.representationEnd+1),n.representationStart,n.representationEnd,{value:o}];if(t!==y)o+=String.fromCodePoint(t);else{if(void 0===n.codePointSource[n.cursor])continue;if(isNewLine(n.codePointSource[n.cursor])){n.advanceCodePoint();continue}o+=String.fromCodePoint(consumeEscapedCodePoint(e,n))}}}function checkIfCodePointsMatchURLIdent(e){return!(3!==e.length||e[0]!==B&&e[0]!==V||e[1]!==K&&e[1]!==z||e[2]!==M&&e[2]!==$)}function consumeBadURL(e,n){for(;;){if(void 0===n.codePointSource[n.cursor])return;if(n.codePointSource[n.cursor]===W)return void n.advanceCodePoint();checkIfTwoCodePointsAreAValidEscape(n)?(n.advanceCodePoint(),consumeEscapedCodePoint(e,n)):n.advanceCodePoint()}}function consumeUrlToken(e,o){for(;isWhitespace(o.codePointSource[o.cursor]);)o.advanceCodePoint();let t="";for(;;){if(void 0===o.codePointSource[o.cursor])return e.onParseError(new ParseError("Unexpected EOF while consuming a url token.",o.representationStart,o.representationEnd,["4.3.6. Consume a url token","Unexpected EOF"])),[Q.URL,o.source.slice(o.representationStart,o.representationEnd+1),o.representationStart,o.representationEnd,{value:t}];if(o.codePointSource[o.cursor]===W)return o.advanceCodePoint(),[Q.URL,o.source.slice(o.representationStart,o.representationEnd+1),o.representationStart,o.representationEnd,{value:t}];if(isWhitespace(o.codePointSource[o.cursor])){for(o.advanceCodePoint();isWhitespace(o.codePointSource[o.cursor]);)o.advanceCodePoint();return void 0===o.codePointSource[o.cursor]?(e.onParseError(new ParseError("Unexpected EOF while consuming a url token.",o.representationStart,o.representationEnd,["4.3.6. Consume a url token","Consume as much whitespace as possible","Unexpected EOF"])),[Q.URL,o.source.slice(o.representationStart,o.representationEnd+1),o.representationStart,o.representationEnd,{value:t}]):o.codePointSource[o.cursor]===W?(o.advanceCodePoint(),[Q.URL,o.source.slice(o.representationStart,o.representationEnd+1),o.representationStart,o.representationEnd,{value:t}]):(consumeBadURL(e,o),[Q.BadURL,o.source.slice(o.representationStart,o.representationEnd+1),o.representationStart,o.representationEnd,void 0])}if(o.codePointSource[o.cursor]===A||o.codePointSource[o.cursor]===n||o.codePointSource[o.cursor]===k||((i=o.codePointSource[o.cursor])===T||i===u||U<=i&&i<=r||F<=i&&i<=l))return consumeBadURL(e,o),e.onParseError(new ParseError("Unexpected character while consuming a url token.",o.representationStart,o.representationEnd,["4.3.6. Consume a url token","Unexpected U+0022 QUOTATION MARK (\"), U+0027 APOSTROPHE ('), U+0028 LEFT PARENTHESIS (() or non-printable code point"])),[Q.BadURL,o.source.slice(o.representationStart,o.representationEnd+1),o.representationStart,o.representationEnd,void 0];if(o.codePointSource[o.cursor]===y){if(checkIfTwoCodePointsAreAValidEscape(o)){o.advanceCodePoint(),t+=String.fromCodePoint(consumeEscapedCodePoint(e,o));continue}return consumeBadURL(e,o),e.onParseError(new ParseError("Invalid escape sequence while consuming a url token.",o.representationStart,o.representationEnd,["4.3.6. Consume a url token","U+005C REVERSE SOLIDUS (\\)","The input stream does not start with a valid escape sequence"])),[Q.BadURL,o.source.slice(o.representationStart,o.representationEnd+1),o.representationStart,o.representationEnd,void 0]}t+=String.fromCodePoint(o.codePointSource[o.cursor]),o.advanceCodePoint()}var i}function consumeIdentLikeToken(e,o){const r=consumeIdentSequence(e,o);if(o.codePointSource[o.cursor]!==k)return[Q.Ident,o.source.slice(o.representationStart,o.representationEnd+1),o.representationStart,o.representationEnd,{value:String.fromCodePoint(...r)}];if(checkIfCodePointsMatchURLIdent(r)){o.advanceCodePoint();let t=0;for(;;){const e=isWhitespace(o.codePointSource[o.cursor]),i=isWhitespace(o.codePointSource[o.cursor+1]);if(e&&i){t+=1,o.advanceCodePoint(1);continue}const s=e?o.codePointSource[o.cursor+1]:o.codePointSource[o.cursor];if(s===A||s===n)return t>0&&o.unreadCodePoint(t),[Q.Function,o.source.slice(o.representationStart,o.representationEnd+1),o.representationStart,o.representationEnd,{value:String.fromCodePoint(...r)}];break}return consumeUrlToken(e,o)}return o.advanceCodePoint(),[Q.Function,o.source.slice(o.representationStart,o.representationEnd+1),o.representationStart,o.representationEnd,{value:String.fromCodePoint(...r)}]}function checkIfThreeCodePointsWouldStartAUnicodeRange(e){return!(e.codePointSource[e.cursor]!==B&&e.codePointSource[e.cursor]!==V||e.codePointSource[e.cursor+1]!==R||e.codePointSource[e.cursor+2]!==J&&!isHexDigitCodePoint(e.codePointSource[e.cursor+2]))}function consumeUnicodeRangeToken(e,n){n.advanceCodePoint(2);const o=[],r=[];for(;void 0!==n.codePointSource[n.cursor]&&o.length<6&&isHexDigitCodePoint(n.codePointSource[n.cursor]);)o.push(n.codePointSource[n.cursor]),n.advanceCodePoint();for(;void 0!==n.codePointSource[n.cursor]&&o.length<6&&n.codePointSource[n.cursor]===J;)0===r.length&&r.push(...o),o.push(_),r.push(j),n.advanceCodePoint();if(!r.length&&n.codePointSource[n.cursor]===C&&isHexDigitCodePoint(n.codePointSource[n.cursor+1]))for(n.advanceCodePoint();void 0!==n.codePointSource[n.cursor]&&r.length<6&&isHexDigitCodePoint(n.codePointSource[n.cursor]);)r.push(n.codePointSource[n.cursor]),n.advanceCodePoint();if(!r.length){const e=parseInt(String.fromCodePoint(...o),16);return[Q.UnicodeRange,n.source.slice(n.representationStart,n.representationEnd+1),n.representationStart,n.representationEnd,{startOfRange:e,endOfRange:e}]}const t=parseInt(String.fromCodePoint(...o),16),i=parseInt(String.fromCodePoint(...r),16);return[Q.UnicodeRange,n.source.slice(n.representationStart,n.representationEnd+1),n.representationStart,n.representationEnd,{startOfRange:t,endOfRange:i}]}function tokenize(e,n){const o=tokenizer(e,n),r=[];{for(;!o.endOfFile();){const e=o.nextToken();e&&r.push(e)}const e=o.nextToken();e&&r.push(e)}return r}function tokenizer(e,o){const r=e.css.valueOf(),u=e.unicodeRangesAllowed??!1,d=new Reader(r),S={onParseError:o?.onParseError??noop};return{nextToken:function nextToken(){d.resetRepresentation();const e=d.codePointSource[d.cursor];if(void 0===e)return[Q.EOF,"",-1,-1,void 0];if(e===b&&checkIfTwoCodePointsStartAComment(d))return consumeComment(S,d);if(u&&(e===B||e===V)&&checkIfThreeCodePointsWouldStartAUnicodeRange(d))return consumeUnicodeRangeToken(0,d);if(isIdentStartCodePoint(e))return consumeIdentLikeToken(S,d);if(isDigitCodePoint(e))return consumeNumericToken(S,d);switch(e){case c:return d.advanceCodePoint(),[Q.Comma,",",d.representationStart,d.representationEnd,void 0];case s:return d.advanceCodePoint(),[Q.Colon,":",d.representationStart,d.representationEnd,void 0];case x:return d.advanceCodePoint(),[Q.Semicolon,";",d.representationStart,d.representationEnd,void 0];case k:return d.advanceCodePoint(),[Q.OpenParen,"(",d.representationStart,d.representationEnd,void 0];case W:return d.advanceCodePoint(),[Q.CloseParen,")",d.representationStart,d.representationEnd,void 0];case E:return d.advanceCodePoint(),[Q.OpenSquare,"[",d.representationStart,d.representationEnd,void 0];case N:return d.advanceCodePoint(),[Q.CloseSquare,"]",d.representationStart,d.representationEnd,void 0];case h:return d.advanceCodePoint(),[Q.OpenCurly,"{",d.representationStart,d.representationEnd,void 0];case q:return d.advanceCodePoint(),[Q.CloseCurly,"}",d.representationStart,d.representationEnd,void 0];case n:case A:return consumeStringToken(S,d);case D:return consumeHashToken(S,d);case R:case p:return checkIfThreeCodePointsWouldStartANumber(d)?consumeNumericToken(S,d):(d.advanceCodePoint(),[Q.Delim,d.source[d.representationStart],d.representationStart,d.representationEnd,{value:d.source[d.representationStart]}]);case g:case t:case P:case i:case H:return consumeWhiteSpace(d);case C:return checkIfThreeCodePointsWouldStartANumber(d)?consumeNumericToken(S,d):checkIfThreeCodePointsWouldStartCDC(d)?(d.advanceCodePoint(3),[Q.CDC,"--\x3e",d.representationStart,d.representationEnd,void 0]):checkIfThreeCodePointsWouldStartAnIdentSequence(0,d)?consumeIdentLikeToken(S,d):(d.advanceCodePoint(),[Q.Delim,"-",d.representationStart,d.representationEnd,{value:"-"}]);case v:return checkIfFourCodePointsWouldStartCDO(d)?(d.advanceCodePoint(4),[Q.CDO,"\x3c!--",d.representationStart,d.representationEnd,void 0]):(d.advanceCodePoint(),[Q.Delim,"<",d.representationStart,d.representationEnd,{value:"<"}]);case a:if(d.advanceCodePoint(),checkIfThreeCodePointsWouldStartAnIdentSequence(0,d)){const e=consumeIdentSequence(S,d);return[Q.AtKeyword,d.source.slice(d.representationStart,d.representationEnd+1),d.representationStart,d.representationEnd,{value:String.fromCodePoint(...e)}]}return[Q.Delim,"@",d.representationStart,d.representationEnd,{value:"@"}];case y:return checkIfTwoCodePointsAreAValidEscape(d)?consumeIdentLikeToken(S,d):(d.advanceCodePoint(),S.onParseError(new ParseError('Invalid escape sequence after "\\"',d.representationStart,d.representationEnd,["4.3.1. Consume a token","U+005C REVERSE SOLIDUS (\\)","The input stream does not start with a valid escape sequence"])),[Q.Delim,"\\",d.representationStart,d.representationEnd,{value:"\\"}])}return d.advanceCodePoint(),[Q.Delim,d.source[d.representationStart],d.representationStart,d.representationEnd,{value:d.source[d.representationStart]}]},endOfFile:function endOfFile(){return void 0===d.codePointSource[d.cursor]}}}function noop(){}function mutateIdent(e,n){const o=[];for(const e of n)o.push(e.codePointAt(0));const r=String.fromCodePoint(...ensureThatValueRoundTripsAsIdent(o));e[1]=r,e[4].value=n}function mutateUnit(e,n){const o=[];for(const e of n)o.push(e.codePointAt(0));const r=ensureThatValueRoundTripsAsIdent(o);101===r[0]&&insertEscapedCodePoint(r,0,r[0]);const t=String.fromCodePoint(...r),i="+"===e[4].signCharacter?e[4].signCharacter:"",s=e[4].value.toString();e[1]=`${i}${s}${t}`,e[4].unit=n}function ensureThatValueRoundTripsAsIdent(e){let n=0;e[0]===C&&e[1]===C?n=2:e[0]===C&&e[1]?(n=2,isIdentStartCodePoint(e[1])||(n+=insertEscapedCodePoint(e,1,e[1]))):isIdentStartCodePoint(e[0])?n=1:(n=1,n+=insertEscapedCodePoint(e,0,e[0]));for(let o=n;o { const result: Array = []; - // eslint-disable-next-line no-constant-condition while (true) { if (isIdentCodePoint(reader.codePointSource[reader.cursor])) { result.push(reader.codePointSource[reader.cursor]); diff --git a/packages/css-tokenizer/src/consume/string-token.ts b/packages/css-tokenizer/src/consume/string-token.ts index 4acd21e69..5c1d63e43 100644 --- a/packages/css-tokenizer/src/consume/string-token.ts +++ b/packages/css-tokenizer/src/consume/string-token.ts @@ -12,7 +12,6 @@ export function consumeStringToken(ctx: Context, reader: CodePointReader): Token const first = reader.readCodePoint(); - // eslint-disable-next-line no-constant-condition while (true) { const next = reader.readCodePoint(); if (next === false) { diff --git a/packages/css-tokenizer/src/consume/url-token.ts b/packages/css-tokenizer/src/consume/url-token.ts index 2b51546c9..f4c29079a 100644 --- a/packages/css-tokenizer/src/consume/url-token.ts +++ b/packages/css-tokenizer/src/consume/url-token.ts @@ -16,7 +16,6 @@ export function consumeUrlToken(ctx: Context, reader: CodePointReader): TokenURL let string = ''; - // eslint-disable-next-line no-constant-condition while (true) { if (reader.codePointSource[reader.cursor] === undefined) { ctx.onParseError(new ParseError( diff --git a/packages/css-tokenizer/src/interfaces/token.ts b/packages/css-tokenizer/src/interfaces/token.ts index 6c86a7fb8..a026429a4 100644 --- a/packages/css-tokenizer/src/interfaces/token.ts +++ b/packages/css-tokenizer/src/interfaces/token.ts @@ -1,3 +1,5 @@ +/* eslint-disable @typescript-eslint/no-empty-object-type */ + /** * All possible CSS token types */ diff --git a/packages/css-tokenizer/src/util/clone-tokens.ts b/packages/css-tokenizer/src/util/clone-tokens.ts index 83883bdc3..8a9a47702 100644 --- a/packages/css-tokenizer/src/util/clone-tokens.ts +++ b/packages/css-tokenizer/src/util/clone-tokens.ts @@ -1,13 +1,15 @@ import { CSSToken } from '../interfaces/token'; +const supportsStructuredClone = (typeof globalThis !== 'undefined') && 'structuredClone' in globalThis; + /** * Deep clone a list of tokens. * Useful for mutations without altering the original list. */ export function cloneTokens(tokens: Array): Array { - if ((typeof globalThis !== 'undefined') && 'structuredClone' in globalThis) { + if (supportsStructuredClone) { return structuredClone(tokens); } - return JSON.parse(JSON.stringify(tokens)); + return JSON.parse(JSON.stringify(tokens)) as Array; } diff --git a/packages/css-tokenizer/src/util/type-predicates.ts b/packages/css-tokenizer/src/util/type-predicates.ts index 01bf9486b..564612ef4 100644 --- a/packages/css-tokenizer/src/util/type-predicates.ts +++ b/packages/css-tokenizer/src/util/type-predicates.ts @@ -20,7 +20,7 @@ export function isToken(x: any): x is CSSToken { // eslint-disable-line @typescr return false; } - if (!tokenTypes.includes(x[0])) { + if (!tokenTypes.includes(x[0] as TokenType)) { return false; } diff --git a/packages/css-tokenizer/test/community/bootstrap-benchmark.mjs b/packages/css-tokenizer/test/community/bootstrap-benchmark.mjs index b2e5e65aa..6e9f14588 100644 --- a/packages/css-tokenizer/test/community/bootstrap-benchmark.mjs +++ b/packages/css-tokenizer/test/community/bootstrap-benchmark.mjs @@ -119,7 +119,6 @@ function csstoolsLargeSource() { }, ); - // eslint-disable-next-line no-constant-condition while (true) { const token = t.nextToken(); if (token[0] === TokenType.EOF) { @@ -162,7 +161,6 @@ function csstoolsSmallSource() { }, ); - // eslint-disable-next-line no-constant-condition while (true) { const token = t.nextToken(); if (token[0] === TokenType.EOF) { @@ -207,7 +205,6 @@ function csstoolsTinySource() { }, ); - // eslint-disable-next-line no-constant-condition while (true) { const token = t.nextToken(); if (token[0] === TokenType.EOF) { @@ -244,7 +241,6 @@ function postcssLargeSource() { }, ); - // eslint-disable-next-line no-constant-condition while (true) { const token = t.nextToken(); if (!token) { @@ -281,7 +277,6 @@ function postcssSmallSource() { }, ); - // eslint-disable-next-line no-constant-condition while (true) { const token = t.nextToken(); if (!token) { @@ -321,7 +316,6 @@ function postcssTinySource() { }, ); - // eslint-disable-next-line no-constant-condition while (true) { const token = t.nextToken(); if (!token) { diff --git a/packages/css-tokenizer/test/community/bootstrap.mjs b/packages/css-tokenizer/test/community/bootstrap.mjs index 2e7f34e21..ef70430b6 100644 --- a/packages/css-tokenizer/test/community/bootstrap.mjs +++ b/packages/css-tokenizer/test/community/bootstrap.mjs @@ -16,7 +16,6 @@ import fs from 'fs'; }, ); - // eslint-disable-next-line no-constant-condition while (true) { const token = t.nextToken(); if (token[0] === TokenType.EOF) { diff --git a/packages/css-tokenizer/test/community/open-props.mjs b/packages/css-tokenizer/test/community/open-props.mjs index 83ec89d9c..3c605fa74 100644 --- a/packages/css-tokenizer/test/community/open-props.mjs +++ b/packages/css-tokenizer/test/community/open-props.mjs @@ -16,7 +16,6 @@ import fs from 'fs'; }, ); - // eslint-disable-next-line no-constant-condition while (true) { const token = t.nextToken(); if (token[0] === TokenType.EOF) { diff --git a/packages/css-tokenizer/test/community/postcss-parser-tests.mjs b/packages/css-tokenizer/test/community/postcss-parser-tests.mjs index 84f1d3ded..5936a65e9 100644 --- a/packages/css-tokenizer/test/community/postcss-parser-tests.mjs +++ b/packages/css-tokenizer/test/community/postcss-parser-tests.mjs @@ -17,7 +17,6 @@ eachTest((name, css) => { const tokens = []; - // eslint-disable-next-line no-constant-condition while (true) { const token = t.nextToken(); if (token[0] === TokenType.EOF) { diff --git a/packages/css-tokenizer/test/community/token-types.mjs b/packages/css-tokenizer/test/community/token-types.mjs index df3103232..0b4724757 100644 --- a/packages/css-tokenizer/test/community/token-types.mjs +++ b/packages/css-tokenizer/test/community/token-types.mjs @@ -56,7 +56,6 @@ ${openPropsSource} let tokens = []; - // eslint-disable-next-line no-constant-condition while (true) { const token = t.nextToken(); tokens.push(token); @@ -130,7 +129,6 @@ function csstoolsTokenToTypeWithSubIdentifiers(token) { let tokens = []; - // eslint-disable-next-line no-constant-condition while (true) { const token = t.nextToken(); if (!token) { diff --git a/packages/css-tokenizer/test/complex/parse-error.mjs b/packages/css-tokenizer/test/complex/parse-error.mjs index 9b8f5f1cf..20ec7ee0d 100644 --- a/packages/css-tokenizer/test/complex/parse-error.mjs +++ b/packages/css-tokenizer/test/complex/parse-error.mjs @@ -14,7 +14,6 @@ import assert from 'assert'; }, ); - // eslint-disable-next-line no-constant-condition while (true) { const token = t.nextToken(); if (token[0] === TokenType.EOF) { diff --git a/packages/media-query-list-parser/dist/index.cjs b/packages/media-query-list-parser/dist/index.cjs index 702e5c1e0..c1ce34115 100644 --- a/packages/media-query-list-parser/dist/index.cjs +++ b/packages/media-query-list-parser/dist/index.cjs @@ -1 +1 @@ -"use strict";var e,t=require("@csstools/css-parser-algorithms"),i=require("@csstools/css-tokenizer");exports.NodeType=void 0,(e=exports.NodeType||(exports.NodeType={})).CustomMedia="custom-media",e.GeneralEnclosed="general-enclosed",e.MediaAnd="media-and",e.MediaCondition="media-condition",e.MediaConditionListWithAnd="media-condition-list-and",e.MediaConditionListWithOr="media-condition-list-or",e.MediaFeature="media-feature",e.MediaFeatureBoolean="mf-boolean",e.MediaFeatureName="mf-name",e.MediaFeaturePlain="mf-plain",e.MediaFeatureRangeNameValue="mf-range-name-value",e.MediaFeatureRangeValueName="mf-range-value-name",e.MediaFeatureRangeValueNameValue="mf-range-value-name-value",e.MediaFeatureValue="mf-value",e.MediaInParens="media-in-parens",e.MediaNot="media-not",e.MediaOr="media-or",e.MediaQueryWithType="media-query-with-type",e.MediaQueryWithoutType="media-query-without-type",e.MediaQueryInvalid="media-query-invalid";class MediaCondition{type=exports.NodeType.MediaCondition;media;constructor(e){this.media=e}tokens(){return this.media.tokens()}toString(){return this.media.toString()}indexOf(e){return e===this.media?"media":-1}at(e){if("media"===e)return this.media}walk(e,t){let i;return t&&(i={...t}),!1!==e({node:this.media,parent:this,state:i},"media")&&this.media.walk(e,i)}toJSON(){return{type:this.type,media:this.media.toJSON()}}isMediaCondition(){return MediaCondition.isMediaCondition(this)}static isMediaCondition(e){return!!e&&(e instanceof MediaCondition&&e.type===exports.NodeType.MediaCondition)}}class MediaInParens{type=exports.NodeType.MediaInParens;media;before;after;constructor(e,t=[],i=[]){this.media=e,this.before=t,this.after=i}tokens(){return[...this.before,...this.media.tokens(),...this.after]}toString(){return i.stringify(...this.before)+this.media.toString()+i.stringify(...this.after)}indexOf(e){return e===this.media?"media":-1}at(e){if("media"===e)return this.media}walk(e,t){let i;return t&&(i={...t}),!1!==e({node:this.media,parent:this,state:i},"media")&&("walk"in this.media?this.media.walk(e,i):void 0)}toJSON(){return{type:this.type,media:this.media.toJSON(),before:this.before,after:this.after}}isMediaInParens(){return MediaInParens.isMediaInParens(this)}static isMediaInParens(e){return!!e&&(e instanceof MediaInParens&&e.type===exports.NodeType.MediaInParens)}}class MediaQueryWithType{type=exports.NodeType.MediaQueryWithType;modifier;mediaType;and=void 0;media=void 0;constructor(e,t,i,a){this.modifier=e,this.mediaType=t,i&&a&&(this.and=i,this.media=a)}getModifier(){if(!this.modifier.length)return"";for(let e=0;ee.tokens()))}toString(){return this.media.map((e=>e.toString())).join("")}walk(e,i){if(0===this.media.length)return;const a=t.walkerIndexGenerator(this.media);let r=0;for(;re.tokens())),...this.after]}toString(){return i.stringify(...this.before)+this.leading.toString()+this.list.map((e=>e.toString())).join("")+i.stringify(...this.after)}indexOf(e){return e===this.leading?"leading":"media-and"===e.type?this.list.indexOf(e):-1}at(e){return"leading"===e?this.leading:"number"==typeof e?(e<0&&(e=this.list.length+e),this.list[e]):void 0}walk(e,i){let a;if(i&&(a={...i}),!1===e({node:this.leading,parent:this,state:a},"leading"))return!1;if("walk"in this.leading&&!1===this.leading.walk(e,a))return!1;if(0===this.list.length)return;const r=t.walkerIndexGenerator(this.list);let n=0;for(;ne.toJSON())),before:this.before,after:this.after}}isMediaConditionListWithAnd(){return MediaConditionListWithAnd.isMediaConditionListWithAnd(this)}static isMediaConditionListWithAnd(e){return!!e&&(e instanceof MediaConditionListWithAnd&&e.type===exports.NodeType.MediaConditionListWithAnd)}}class MediaConditionListWithOr{type=exports.NodeType.MediaConditionListWithOr;leading;list;before;after;constructor(e,t,i=[],a=[]){this.leading=e,this.list=t,this.before=i,this.after=a}tokens(){return[...this.before,...this.leading.tokens(),...this.list.flatMap((e=>e.tokens())),...this.after]}toString(){return i.stringify(...this.before)+this.leading.toString()+this.list.map((e=>e.toString())).join("")+i.stringify(...this.after)}indexOf(e){return e===this.leading?"leading":"media-or"===e.type?this.list.indexOf(e):-1}at(e){return"leading"===e?this.leading:"number"==typeof e?(e<0&&(e=this.list.length+e),this.list[e]):void 0}walk(e,i){let a;if(i&&(a={...i}),!1===e({node:this.leading,parent:this,state:a},"leading"))return!1;if("walk"in this.leading&&!1===this.leading.walk(e,a))return!1;if(0===this.list.length)return;const r=t.walkerIndexGenerator(this.list);let n=0;for(;ne.toJSON())),before:this.before,after:this.after}}isMediaConditionListWithOr(){return MediaConditionListWithOr.isMediaConditionListWithOr(this)}static isMediaConditionListWithOr(e){return!!e&&(e instanceof MediaConditionListWithOr&&e.type===exports.NodeType.MediaConditionListWithOr)}}function isNumber(e){return!!(t.isTokenNode(e)&&i.isTokenNumber(e.value)||t.isFunctionNode(e)&&a.has(e.getName().toLowerCase()))}const a=new Set(["abs","acos","asin","atan","atan2","calc","clamp","cos","exp","hypot","log","max","min","mod","pow","rem","round","sign","sin","sqrt","tan"]);function isDimension(e){return t.isTokenNode(e)&&i.isTokenDimension(e.value)}function isIdent(e){return t.isTokenNode(e)&&i.isTokenIdent(e.value)}function isEnvironmentVariable(e){return t.isFunctionNode(e)&&"env"===e.getName().toLowerCase()}class MediaFeatureName{type=exports.NodeType.MediaFeatureName;name;before;after;constructor(e,t=[],i=[]){this.name=e,this.before=t,this.after=i}getName(){return this.name.value[4].value}getNameToken(){return this.name.value}tokens(){return[...this.before,...this.name.tokens(),...this.after]}toString(){return i.stringify(...this.before)+this.name.toString()+i.stringify(...this.after)}indexOf(e){return e===this.name?"name":-1}at(e){if("name"===e)return this.name}toJSON(){return{type:this.type,name:this.getName(),tokens:this.tokens()}}isMediaFeatureName(){return MediaFeatureName.isMediaFeatureName(this)}static isMediaFeatureName(e){return!!e&&(e instanceof MediaFeatureName&&e.type===exports.NodeType.MediaFeatureName)}}function parseMediaFeatureName(e){let i=-1;for(let a=0;ae.tokens())),e.slice(i+1).flatMap((e=>e.tokens())))}class MediaFeatureBoolean{type=exports.NodeType.MediaFeatureBoolean;name;constructor(e){this.name=e}getName(){return this.name.getName()}getNameToken(){return this.name.getNameToken()}tokens(){return this.name.tokens()}toString(){return this.name.toString()}indexOf(e){return e===this.name?"name":-1}at(e){if("name"===e)return this.name}toJSON(){return{type:this.type,name:this.name.toJSON(),tokens:this.tokens()}}isMediaFeatureBoolean(){return MediaFeatureBoolean.isMediaFeatureBoolean(this)}static isMediaFeatureBoolean(e){return!!e&&(e instanceof MediaFeatureBoolean&&e.type===exports.NodeType.MediaFeatureBoolean)}}function parseMediaFeatureBoolean(e){const t=parseMediaFeatureName(e);return!1===t?t:new MediaFeatureBoolean(t)}class MediaFeatureValue{type=exports.NodeType.MediaFeatureValue;value;before;after;constructor(e,t=[],i=[]){Array.isArray(e)&&1===e.length?this.value=e[0]:this.value=e,this.before=t,this.after=i}tokens(){return Array.isArray(this.value)?[...this.before,...this.value.flatMap((e=>e.tokens())),...this.after]:[...this.before,...this.value.tokens(),...this.after]}toString(){return Array.isArray(this.value)?i.stringify(...this.before)+this.value.map((e=>e.toString())).join("")+i.stringify(...this.after):i.stringify(...this.before)+this.value.toString()+i.stringify(...this.after)}indexOf(e){return e===this.value?"value":-1}at(e){return"value"===e?this.value:Array.isArray(this.value)&&"number"==typeof e?(e<0&&(e=this.value.length+e),this.value[e]):void 0}walk(e,i){if(Array.isArray(this.value)){if(0===this.value.length)return;const a=t.walkerIndexGenerator(this.value);let r=0;for(;re.toJSON())),tokens:this.tokens()}:{type:this.type,value:this.value.toJSON(),tokens:this.tokens()}}isMediaFeatureValue(){return MediaFeatureValue.isMediaFeatureValue(this)}static isMediaFeatureValue(e){return!!e&&(e instanceof MediaFeatureValue&&e.type===exports.NodeType.MediaFeatureValue)}}function parseMediaFeatureValue(e,i=!1){let a=-1,r=-1;for(let n=0;ne.tokens())),e.slice(r+1).flatMap((e=>e.tokens())))}function matchesRatioExactly(e){let t=-1,i=-1;const a=matchesRatio(e);if(-1===a)return-1;t=a[0],i=a[1];for(let t=i+1;t2)return!1;if(!i.isTokenDelim(e[0]))return!1;if(1===e.length)switch(e[0][4].value){case exports.MediaFeatureEQ.EQ:return exports.MediaFeatureEQ.EQ;case exports.MediaFeatureLT.LT:return exports.MediaFeatureLT.LT;case exports.MediaFeatureGT.GT:return exports.MediaFeatureGT.GT;default:return!1}if(!i.isTokenDelim(e[1]))return!1;if(e[1][4].value!==exports.MediaFeatureEQ.EQ)return!1;switch(e[0][4].value){case exports.MediaFeatureLT.LT:return exports.MediaFeatureLT.LT_OR_EQ;case exports.MediaFeatureGT.GT:return exports.MediaFeatureGT.GT_OR_EQ;default:return!1}}exports.MediaFeatureLT=void 0,(r=exports.MediaFeatureLT||(exports.MediaFeatureLT={})).LT="<",r.LT_OR_EQ="<=",exports.MediaFeatureGT=void 0,(n=exports.MediaFeatureGT||(exports.MediaFeatureGT={})).GT=">",n.GT_OR_EQ=">=",exports.MediaFeatureEQ=void 0,(exports.MediaFeatureEQ||(exports.MediaFeatureEQ={})).EQ="=";class MediaFeatureRangeNameValue{type=exports.NodeType.MediaFeatureRangeNameValue;name;operator;value;constructor(e,t,i){this.name=e,this.operator=t,this.value=i}operatorKind(){return comparisonFromTokens(this.operator)}getName(){return this.name.getName()}getNameToken(){return this.name.getNameToken()}tokens(){return[...this.name.tokens(),...this.operator,...this.value.tokens()]}toString(){return this.name.toString()+i.stringify(...this.operator)+this.value.toString()}indexOf(e){return e===this.name?"name":e===this.value?"value":-1}at(e){return"name"===e?this.name:"value"===e?this.value:void 0}walk(e,t){let i;return t&&(i={...t}),!1!==e({node:this.value,parent:this,state:i},"value")&&("walk"in this.value?this.value.walk(e,i):void 0)}toJSON(){return{type:this.type,name:this.name.toJSON(),value:this.value.toJSON(),tokens:this.tokens()}}isMediaFeatureRangeNameValue(){return MediaFeatureRangeNameValue.isMediaFeatureRangeNameValue(this)}static isMediaFeatureRangeNameValue(e){return!!e&&(e instanceof MediaFeatureRangeNameValue&&e.type===exports.NodeType.MediaFeatureRangeNameValue)}}class MediaFeatureRangeValueName{type=exports.NodeType.MediaFeatureRangeValueName;name;operator;value;constructor(e,t,i){this.name=e,this.operator=t,this.value=i}operatorKind(){return comparisonFromTokens(this.operator)}getName(){return this.name.getName()}getNameToken(){return this.name.getNameToken()}tokens(){return[...this.value.tokens(),...this.operator,...this.name.tokens()]}toString(){return this.value.toString()+i.stringify(...this.operator)+this.name.toString()}indexOf(e){return e===this.name?"name":e===this.value?"value":-1}at(e){return"name"===e?this.name:"value"===e?this.value:void 0}walk(e,t){let i;return t&&(i={...t}),!1!==e({node:this.value,parent:this,state:i},"value")&&("walk"in this.value?this.value.walk(e,i):void 0)}toJSON(){return{type:this.type,name:this.name.toJSON(),value:this.value.toJSON(),tokens:this.tokens()}}isMediaFeatureRangeValueName(){return MediaFeatureRangeValueName.isMediaFeatureRangeValueName(this)}static isMediaFeatureRangeValueName(e){return!!e&&(e instanceof MediaFeatureRangeValueName&&e.type===exports.NodeType.MediaFeatureRangeValueName)}}class MediaFeatureRangeValueNameValue{type=exports.NodeType.MediaFeatureRangeValueNameValue;name;valueOne;valueOneOperator;valueTwo;valueTwoOperator;constructor(e,t,i,a,r){this.name=e,this.valueOne=t,this.valueOneOperator=i,this.valueTwo=a,this.valueTwoOperator=r}valueOneOperatorKind(){return comparisonFromTokens(this.valueOneOperator)}valueTwoOperatorKind(){return comparisonFromTokens(this.valueTwoOperator)}getName(){return this.name.getName()}getNameToken(){return this.name.getNameToken()}tokens(){return[...this.valueOne.tokens(),...this.valueOneOperator,...this.name.tokens(),...this.valueTwoOperator,...this.valueTwo.tokens()]}toString(){return this.valueOne.toString()+i.stringify(...this.valueOneOperator)+this.name.toString()+i.stringify(...this.valueTwoOperator)+this.valueTwo.toString()}indexOf(e){return e===this.name?"name":e===this.valueOne?"valueOne":e===this.valueTwo?"valueTwo":-1}at(e){return"name"===e?this.name:"valueOne"===e?this.valueOne:"valueTwo"===e?this.valueTwo:void 0}walk(e,t){let i;return t&&(i={...t}),!1!==e({node:this.valueOne,parent:this,state:i},"valueOne")&&((!("walk"in this.valueOne)||!1!==this.valueOne.walk(e,i))&&(t&&(i={...t}),!1!==e({node:this.valueTwo,parent:this,state:i},"valueTwo")&&((!("walk"in this.valueTwo)||!1!==this.valueTwo.walk(e,i))&&void 0)))}toJSON(){return{type:this.type,name:this.name.toJSON(),valueOne:this.valueOne.toJSON(),valueTwo:this.valueTwo.toJSON(),tokens:this.tokens()}}isMediaFeatureRangeValueNameValue(){return MediaFeatureRangeValueNameValue.isMediaFeatureRangeValueNameValue(this)}static isMediaFeatureRangeValueNameValue(e){return!!e&&(e instanceof MediaFeatureRangeValueNameValue&&e.type===exports.NodeType.MediaFeatureRangeValueNameValue)}}function parseMediaFeatureRange(e){let a=!1,r=!1;for(let n=0;ne.tokens())),-1!==r&&(o=e.slice(a+1,r+1).flatMap((e=>e.tokens())))):-1!==r&&(o=e.slice(0,r+1).flatMap((e=>e.tokens())));const u=parseMediaConditionWithoutOr(e.slice(Math.max(a,r,n)+1));return!1===u?new MediaQueryWithType(s,[...o,...e.slice(r+1).flatMap((e=>e.tokens()))]):new MediaQueryWithType(s,o,e.slice(r+1,n+1).flatMap((e=>e.tokens())),u)}}function parseMediaConditionListWithOr(e){let i=!1;const a=[];let r=-1,n=-1;for(let s=0;se.tokens())),e.slice(n+1).flatMap((e=>e.tokens())))}function parseMediaConditionListWithAnd(e){let i=!1;const a=[];let r=-1,n=-1;for(let s=0;se.tokens())),e.slice(n+1).flatMap((e=>e.tokens())))}function parseMediaCondition(e){const t=parseMediaNot(e);if(!1!==t)return new MediaCondition(t);const i=parseMediaConditionListWithAnd(e);if(!1!==i)return new MediaCondition(i);const a=parseMediaConditionListWithOr(e);if(!1!==a)return new MediaCondition(a);const r=parseMediaInParens(e);return!1!==r&&new MediaCondition(r)}function parseMediaConditionWithoutOr(e){const t=parseMediaNot(e);if(!1!==t)return new MediaCondition(t);const i=parseMediaConditionListWithAnd(e);if(!1!==i)return new MediaCondition(i);const a=parseMediaInParens(e);return!1!==a&&new MediaCondition(a)}function parseMediaInParens(e){let a=-1;for(let i=0;ie.tokens())),r.startToken],s=[r.endToken,...e.slice(a+1).flatMap((e=>e.tokens()))],o=parseMediaFeature(r,n,s);if(!1!==o)return new MediaInParens(o);const u=parseMediaCondition(r.value);return!1!==u?new MediaInParens(u,n,s):new MediaInParens(new GeneralEnclosed(r),e.slice(0,a).flatMap((e=>e.tokens())),e.slice(a+1).flatMap((e=>e.tokens())))}function parseMediaInParensFromSimpleBlock(e){if(!i.isTokenOpenParen(e.startToken))return!1;const t=parseMediaFeature(e,[e.startToken],[e.endToken]);if(!1!==t)return new MediaInParens(t);const a=parseMediaCondition(e.value);return!1!==a?new MediaInParens(a,[e.startToken],[e.endToken]):new MediaInParens(new GeneralEnclosed(e))}exports.MediaQueryModifier=void 0,(s=exports.MediaQueryModifier||(exports.MediaQueryModifier={})).Not="not",s.Only="only";const o=/^not$/i;function parseMediaNot(e){let i=!1,a=null;for(let r=0;re.tokens())),t)}}}return a||!1}const u=/^or$/i;function parseMediaOr(e){let i=!1;for(let a=0;ae.tokens())),t)}}return!1}}return!1}const d=/^and$/i;function parseMediaAnd(e){let i=!1;for(let a=0;ae.tokens())),t)}}return!1}}return!1}function parseFromTokens(e,i){const a=t.parseCommaSeparatedListOfComponentValues(e,{onParseError:i?.onParseError});return a.map(((e,t)=>{const r=parseMediaQuery(e);return!1===r&&!0===i?.preserveInvalidMediaQueries?new MediaQueryInvalid(a[t]):r})).filter((e=>!!e))}class CustomMedia{type=exports.NodeType.CustomMedia;name;mediaQueryList=null;trueOrFalseKeyword=null;constructor(e,t,i){this.name=e,this.mediaQueryList=t,this.trueOrFalseKeyword=i??null}getName(){for(let e=0;ee.toJSON()))}}isCustomMedia(){return CustomMedia.isCustomMedia(this)}static isCustomMedia(e){return!!e&&(e instanceof CustomMedia&&e.type===exports.NodeType.CustomMedia)}}function parseCustomMediaFromTokens(e,t){let a=[],r=e;for(let t=0;te.tokens()))}toString(){return this.media.map((e=>e.toString())).join("")}walk(e,i){if(0===this.media.length)return;const a=t.walkerIndexGenerator(this.media);let r=0;for(;re.tokens())),...this.after]}toString(){return i.stringify(...this.before)+this.leading.toString()+this.list.map((e=>e.toString())).join("")+i.stringify(...this.after)}indexOf(e){return e===this.leading?"leading":e.type===exports.NodeType.MediaAnd?this.list.indexOf(e):-1}at(e){return"leading"===e?this.leading:"number"==typeof e?(e<0&&(e=this.list.length+e),this.list[e]):void 0}walk(e,i){let a;if(i&&(a={...i}),!1===e({node:this.leading,parent:this,state:a},"leading"))return!1;if("walk"in this.leading&&!1===this.leading.walk(e,a))return!1;if(0===this.list.length)return;const r=t.walkerIndexGenerator(this.list);let n=0;for(;ne.toJSON())),before:this.before,after:this.after}}isMediaConditionListWithAnd(){return MediaConditionListWithAnd.isMediaConditionListWithAnd(this)}static isMediaConditionListWithAnd(e){return!!e&&(e instanceof MediaConditionListWithAnd&&e.type===exports.NodeType.MediaConditionListWithAnd)}}class MediaConditionListWithOr{type=exports.NodeType.MediaConditionListWithOr;leading;list;before;after;constructor(e,t,i=[],a=[]){this.leading=e,this.list=t,this.before=i,this.after=a}tokens(){return[...this.before,...this.leading.tokens(),...this.list.flatMap((e=>e.tokens())),...this.after]}toString(){return i.stringify(...this.before)+this.leading.toString()+this.list.map((e=>e.toString())).join("")+i.stringify(...this.after)}indexOf(e){return e===this.leading?"leading":e.type===exports.NodeType.MediaOr?this.list.indexOf(e):-1}at(e){return"leading"===e?this.leading:"number"==typeof e?(e<0&&(e=this.list.length+e),this.list[e]):void 0}walk(e,i){let a;if(i&&(a={...i}),!1===e({node:this.leading,parent:this,state:a},"leading"))return!1;if("walk"in this.leading&&!1===this.leading.walk(e,a))return!1;if(0===this.list.length)return;const r=t.walkerIndexGenerator(this.list);let n=0;for(;ne.toJSON())),before:this.before,after:this.after}}isMediaConditionListWithOr(){return MediaConditionListWithOr.isMediaConditionListWithOr(this)}static isMediaConditionListWithOr(e){return!!e&&(e instanceof MediaConditionListWithOr&&e.type===exports.NodeType.MediaConditionListWithOr)}}function isNumber(e){return!!(t.isTokenNode(e)&&i.isTokenNumber(e.value)||t.isFunctionNode(e)&&a.has(e.getName().toLowerCase()))}const a=new Set(["abs","acos","asin","atan","atan2","calc","clamp","cos","exp","hypot","log","max","min","mod","pow","rem","round","sign","sin","sqrt","tan"]);function isDimension(e){return t.isTokenNode(e)&&i.isTokenDimension(e.value)}function isIdent(e){return t.isTokenNode(e)&&i.isTokenIdent(e.value)}function isEnvironmentVariable(e){return t.isFunctionNode(e)&&"env"===e.getName().toLowerCase()}class MediaFeatureName{type=exports.NodeType.MediaFeatureName;name;before;after;constructor(e,t=[],i=[]){this.name=e,this.before=t,this.after=i}getName(){return this.name.value[4].value}getNameToken(){return this.name.value}tokens(){return[...this.before,...this.name.tokens(),...this.after]}toString(){return i.stringify(...this.before)+this.name.toString()+i.stringify(...this.after)}indexOf(e){return e===this.name?"name":-1}at(e){if("name"===e)return this.name}toJSON(){return{type:this.type,name:this.getName(),tokens:this.tokens()}}isMediaFeatureName(){return MediaFeatureName.isMediaFeatureName(this)}static isMediaFeatureName(e){return!!e&&(e instanceof MediaFeatureName&&e.type===exports.NodeType.MediaFeatureName)}}function parseMediaFeatureName(e){let i=-1;for(let a=0;ae.tokens())),e.slice(i+1).flatMap((e=>e.tokens())))}class MediaFeatureBoolean{type=exports.NodeType.MediaFeatureBoolean;name;constructor(e){this.name=e}getName(){return this.name.getName()}getNameToken(){return this.name.getNameToken()}tokens(){return this.name.tokens()}toString(){return this.name.toString()}indexOf(e){return e===this.name?"name":-1}at(e){if("name"===e)return this.name}toJSON(){return{type:this.type,name:this.name.toJSON(),tokens:this.tokens()}}isMediaFeatureBoolean(){return MediaFeatureBoolean.isMediaFeatureBoolean(this)}static isMediaFeatureBoolean(e){return!!e&&(e instanceof MediaFeatureBoolean&&e.type===exports.NodeType.MediaFeatureBoolean)}}function parseMediaFeatureBoolean(e){const t=parseMediaFeatureName(e);return!1===t?t:new MediaFeatureBoolean(t)}class MediaFeatureValue{type=exports.NodeType.MediaFeatureValue;value;before;after;constructor(e,t=[],i=[]){Array.isArray(e)&&1===e.length?this.value=e[0]:this.value=e,this.before=t,this.after=i}tokens(){return Array.isArray(this.value)?[...this.before,...this.value.flatMap((e=>e.tokens())),...this.after]:[...this.before,...this.value.tokens(),...this.after]}toString(){return Array.isArray(this.value)?i.stringify(...this.before)+this.value.map((e=>e.toString())).join("")+i.stringify(...this.after):i.stringify(...this.before)+this.value.toString()+i.stringify(...this.after)}indexOf(e){return e===this.value?"value":-1}at(e){return"value"===e?this.value:Array.isArray(this.value)&&"number"==typeof e?(e<0&&(e=this.value.length+e),this.value[e]):void 0}walk(e,i){if(Array.isArray(this.value)){if(0===this.value.length)return;const a=t.walkerIndexGenerator(this.value);let r=0;for(;re.toJSON())),tokens:this.tokens()}:{type:this.type,value:this.value.toJSON(),tokens:this.tokens()}}isMediaFeatureValue(){return MediaFeatureValue.isMediaFeatureValue(this)}static isMediaFeatureValue(e){return!!e&&(e instanceof MediaFeatureValue&&e.type===exports.NodeType.MediaFeatureValue)}}function parseMediaFeatureValue(e,i=!1){let a=-1,r=-1;for(let n=0;ne.tokens())),e.slice(r+1).flatMap((e=>e.tokens())))}function matchesRatioExactly(e){let i=-1,a=-1;const r=matchesRatio(e);if(-1===r)return-1;i=r[0],a=r[1];for(let i=a+1;i",n.GT_OR_EQ=">=",exports.MediaFeatureEQ=void 0,(exports.MediaFeatureEQ||(exports.MediaFeatureEQ={})).EQ="=";class MediaFeatureRangeNameValue{type=exports.NodeType.MediaFeatureRangeNameValue;name;operator;value;constructor(e,t,i){this.name=e,this.operator=t,this.value=i}operatorKind(){return comparisonFromTokens(this.operator)}getName(){return this.name.getName()}getNameToken(){return this.name.getNameToken()}tokens(){return[...this.name.tokens(),...this.operator,...this.value.tokens()]}toString(){return this.name.toString()+i.stringify(...this.operator)+this.value.toString()}indexOf(e){return e===this.name?"name":e===this.value?"value":-1}at(e){return"name"===e?this.name:"value"===e?this.value:void 0}walk(e,t){let i;return t&&(i={...t}),!1!==e({node:this.value,parent:this,state:i},"value")&&("walk"in this.value?this.value.walk(e,i):void 0)}toJSON(){return{type:this.type,name:this.name.toJSON(),value:this.value.toJSON(),tokens:this.tokens()}}isMediaFeatureRangeNameValue(){return MediaFeatureRangeNameValue.isMediaFeatureRangeNameValue(this)}static isMediaFeatureRangeNameValue(e){return!!e&&(e instanceof MediaFeatureRangeNameValue&&e.type===exports.NodeType.MediaFeatureRangeNameValue)}}class MediaFeatureRangeValueName{type=exports.NodeType.MediaFeatureRangeValueName;name;operator;value;constructor(e,t,i){this.name=e,this.operator=t,this.value=i}operatorKind(){return comparisonFromTokens(this.operator)}getName(){return this.name.getName()}getNameToken(){return this.name.getNameToken()}tokens(){return[...this.value.tokens(),...this.operator,...this.name.tokens()]}toString(){return this.value.toString()+i.stringify(...this.operator)+this.name.toString()}indexOf(e){return e===this.name?"name":e===this.value?"value":-1}at(e){return"name"===e?this.name:"value"===e?this.value:void 0}walk(e,t){let i;return t&&(i={...t}),!1!==e({node:this.value,parent:this,state:i},"value")&&("walk"in this.value?this.value.walk(e,i):void 0)}toJSON(){return{type:this.type,name:this.name.toJSON(),value:this.value.toJSON(),tokens:this.tokens()}}isMediaFeatureRangeValueName(){return MediaFeatureRangeValueName.isMediaFeatureRangeValueName(this)}static isMediaFeatureRangeValueName(e){return!!e&&(e instanceof MediaFeatureRangeValueName&&e.type===exports.NodeType.MediaFeatureRangeValueName)}}class MediaFeatureRangeValueNameValue{type=exports.NodeType.MediaFeatureRangeValueNameValue;name;valueOne;valueOneOperator;valueTwo;valueTwoOperator;constructor(e,t,i,a,r){this.name=e,this.valueOne=t,this.valueOneOperator=i,this.valueTwo=a,this.valueTwoOperator=r}valueOneOperatorKind(){return comparisonFromTokens(this.valueOneOperator)}valueTwoOperatorKind(){return comparisonFromTokens(this.valueTwoOperator)}getName(){return this.name.getName()}getNameToken(){return this.name.getNameToken()}tokens(){return[...this.valueOne.tokens(),...this.valueOneOperator,...this.name.tokens(),...this.valueTwoOperator,...this.valueTwo.tokens()]}toString(){return this.valueOne.toString()+i.stringify(...this.valueOneOperator)+this.name.toString()+i.stringify(...this.valueTwoOperator)+this.valueTwo.toString()}indexOf(e){return e===this.name?"name":e===this.valueOne?"valueOne":e===this.valueTwo?"valueTwo":-1}at(e){return"name"===e?this.name:"valueOne"===e?this.valueOne:"valueTwo"===e?this.valueTwo:void 0}walk(e,t){let i;return t&&(i={...t}),!1!==e({node:this.valueOne,parent:this,state:i},"valueOne")&&((!("walk"in this.valueOne)||!1!==this.valueOne.walk(e,i))&&(t&&(i={...t}),!1!==e({node:this.valueTwo,parent:this,state:i},"valueTwo")&&((!("walk"in this.valueTwo)||!1!==this.valueTwo.walk(e,i))&&void 0)))}toJSON(){return{type:this.type,name:this.name.toJSON(),valueOne:this.valueOne.toJSON(),valueTwo:this.valueTwo.toJSON(),tokens:this.tokens()}}isMediaFeatureRangeValueNameValue(){return MediaFeatureRangeValueNameValue.isMediaFeatureRangeValueNameValue(this)}static isMediaFeatureRangeValueNameValue(e){return!!e&&(e instanceof MediaFeatureRangeValueNameValue&&e.type===exports.NodeType.MediaFeatureRangeValueNameValue)}}function parseMediaFeatureRange(e){let a=!1,r=!1;for(let n=0;ne.tokens())),-1!==r&&(o=e.slice(a+1,r+1).flatMap((e=>e.tokens())))):-1!==r&&(o=e.slice(0,r+1).flatMap((e=>e.tokens())));const u=parseMediaConditionWithoutOr(e.slice(Math.max(a,r,n)+1));return!1===u?new MediaQueryWithType(s,[...o,...e.slice(r+1).flatMap((e=>e.tokens()))]):new MediaQueryWithType(s,o,e.slice(r+1,n+1).flatMap((e=>e.tokens())),u)}}function parseMediaConditionListWithOr(e){let i=!1;const a=[];let r=-1,n=-1;for(let s=0;se.tokens())),e.slice(n+1).flatMap((e=>e.tokens())))}function parseMediaConditionListWithAnd(e){let i=!1;const a=[];let r=-1,n=-1;for(let s=0;se.tokens())),e.slice(n+1).flatMap((e=>e.tokens())))}function parseMediaCondition(e){const t=parseMediaNot(e);if(!1!==t)return new MediaCondition(t);const i=parseMediaConditionListWithAnd(e);if(!1!==i)return new MediaCondition(i);const a=parseMediaConditionListWithOr(e);if(!1!==a)return new MediaCondition(a);const r=parseMediaInParens(e);return!1!==r&&new MediaCondition(r)}function parseMediaConditionWithoutOr(e){const t=parseMediaNot(e);if(!1!==t)return new MediaCondition(t);const i=parseMediaConditionListWithAnd(e);if(!1!==i)return new MediaCondition(i);const a=parseMediaInParens(e);return!1!==a&&new MediaCondition(a)}function parseMediaInParens(e){let a=-1;for(let i=0;ie.tokens())),r.startToken],s=[r.endToken,...e.slice(a+1).flatMap((e=>e.tokens()))],o=parseMediaFeature(r,n,s);if(!1!==o)return new MediaInParens(o);const u=parseMediaCondition(r.value);return!1!==u?new MediaInParens(u,n,s):new MediaInParens(new GeneralEnclosed(r),e.slice(0,a).flatMap((e=>e.tokens())),e.slice(a+1).flatMap((e=>e.tokens())))}function parseMediaInParensFromSimpleBlock(e){if(!i.isTokenOpenParen(e.startToken))return!1;const t=parseMediaFeature(e,[e.startToken],[e.endToken]);if(!1!==t)return new MediaInParens(t);const a=parseMediaCondition(e.value);return!1!==a?new MediaInParens(a,[e.startToken],[e.endToken]):new MediaInParens(new GeneralEnclosed(e))}exports.MediaQueryModifier=void 0,(s=exports.MediaQueryModifier||(exports.MediaQueryModifier={})).Not="not",s.Only="only";const o=/^not$/i;function parseMediaNot(e){let i=!1,a=null;for(let r=0;re.tokens())),t)}}}return a||!1}const u=/^or$/i;function parseMediaOr(e){let i=!1;for(let a=0;ae.tokens())),t)}}return!1}}return!1}const d=/^and$/i;function parseMediaAnd(e){let i=!1;for(let a=0;ae.tokens())),t)}}return!1}}return!1}function parseFromTokens(e,i){const a=t.parseCommaSeparatedListOfComponentValues(e,{onParseError:i?.onParseError});return a.map(((e,t)=>{const r=parseMediaQuery(e);return!1===r&&!0===i?.preserveInvalidMediaQueries?new MediaQueryInvalid(a[t]):r})).filter((e=>!!e))}class CustomMedia{type=exports.NodeType.CustomMedia;name;mediaQueryList=null;trueOrFalseKeyword=null;constructor(e,t,i){this.name=e,this.mediaQueryList=t,this.trueOrFalseKeyword=i??null}getName(){for(let e=0;ee.toJSON()))}}isCustomMedia(){return CustomMedia.isCustomMedia(this)}static isCustomMedia(e){return!!e&&(e instanceof CustomMedia&&e.type===exports.NodeType.CustomMedia)}}function parseCustomMediaFromTokens(e,t){let a=[],r=e;for(let t=0;te.tokens()))}toString(){return this.media.map((e=>e.toString())).join("")}walk(t,i){if(0===this.media.length)return;const a=e(this.media);let n=0;for(;ne.tokens())),...this.after]}toString(){return l(...this.before)+this.leading.toString()+this.list.map((e=>e.toString())).join("")+l(...this.after)}indexOf(e){return e===this.leading?"leading":"media-and"===e.type?this.list.indexOf(e):-1}at(e){return"leading"===e?this.leading:"number"==typeof e?(e<0&&(e=this.list.length+e),this.list[e]):void 0}walk(t,i){let a;if(i&&(a={...i}),!1===t({node:this.leading,parent:this,state:a},"leading"))return!1;if("walk"in this.leading&&!1===this.leading.walk(t,a))return!1;if(0===this.list.length)return;const n=e(this.list);let r=0;for(;re.toJSON())),before:this.before,after:this.after}}isMediaConditionListWithAnd(){return MediaConditionListWithAnd.isMediaConditionListWithAnd(this)}static isMediaConditionListWithAnd(e){return!!e&&(e instanceof MediaConditionListWithAnd&&e.type===w.MediaConditionListWithAnd)}}class MediaConditionListWithOr{type=w.MediaConditionListWithOr;leading;list;before;after;constructor(e,t,i=[],a=[]){this.leading=e,this.list=t,this.before=i,this.after=a}tokens(){return[...this.before,...this.leading.tokens(),...this.list.flatMap((e=>e.tokens())),...this.after]}toString(){return l(...this.before)+this.leading.toString()+this.list.map((e=>e.toString())).join("")+l(...this.after)}indexOf(e){return e===this.leading?"leading":"media-or"===e.type?this.list.indexOf(e):-1}at(e){return"leading"===e?this.leading:"number"==typeof e?(e<0&&(e=this.list.length+e),this.list[e]):void 0}walk(t,i){let a;if(i&&(a={...i}),!1===t({node:this.leading,parent:this,state:a},"leading"))return!1;if("walk"in this.leading&&!1===this.leading.walk(t,a))return!1;if(0===this.list.length)return;const n=e(this.list);let r=0;for(;re.toJSON())),before:this.before,after:this.after}}isMediaConditionListWithOr(){return MediaConditionListWithOr.isMediaConditionListWithOr(this)}static isMediaConditionListWithOr(e){return!!e&&(e instanceof MediaConditionListWithOr&&e.type===w.MediaConditionListWithOr)}}function isNumber(e){return!!(t(e)&&f(e.value)||i(e)&&O.has(e.getName().toLowerCase()))}const O=new Set(["abs","acos","asin","atan","atan2","calc","clamp","cos","exp","hypot","log","max","min","mod","pow","rem","round","sign","sin","sqrt","tan"]);function isDimension(e){return t(e)&&c(e.value)}function isIdent(e){return t(e)&&h(e.value)}function isEnvironmentVariable(e){return i(e)&&"env"===e.getName().toLowerCase()}class MediaFeatureName{type=w.MediaFeatureName;name;before;after;constructor(e,t=[],i=[]){this.name=e,this.before=t,this.after=i}getName(){return this.name.value[4].value}getNameToken(){return this.name.value}tokens(){return[...this.before,...this.name.tokens(),...this.after]}toString(){return l(...this.before)+this.name.toString()+l(...this.after)}indexOf(e){return e===this.name?"name":-1}at(e){if("name"===e)return this.name}toJSON(){return{type:this.type,name:this.getName(),tokens:this.tokens()}}isMediaFeatureName(){return MediaFeatureName.isMediaFeatureName(this)}static isMediaFeatureName(e){return!!e&&(e instanceof MediaFeatureName&&e.type===w.MediaFeatureName)}}function parseMediaFeatureName(e){let t=-1;for(let i=0;ie.tokens())),e.slice(t+1).flatMap((e=>e.tokens())))}class MediaFeatureBoolean{type=w.MediaFeatureBoolean;name;constructor(e){this.name=e}getName(){return this.name.getName()}getNameToken(){return this.name.getNameToken()}tokens(){return this.name.tokens()}toString(){return this.name.toString()}indexOf(e){return e===this.name?"name":-1}at(e){if("name"===e)return this.name}toJSON(){return{type:this.type,name:this.name.toJSON(),tokens:this.tokens()}}isMediaFeatureBoolean(){return MediaFeatureBoolean.isMediaFeatureBoolean(this)}static isMediaFeatureBoolean(e){return!!e&&(e instanceof MediaFeatureBoolean&&e.type===w.MediaFeatureBoolean)}}function parseMediaFeatureBoolean(e){const t=parseMediaFeatureName(e);return!1===t?t:new MediaFeatureBoolean(t)}class MediaFeatureValue{type=w.MediaFeatureValue;value;before;after;constructor(e,t=[],i=[]){Array.isArray(e)&&1===e.length?this.value=e[0]:this.value=e,this.before=t,this.after=i}tokens(){return Array.isArray(this.value)?[...this.before,...this.value.flatMap((e=>e.tokens())),...this.after]:[...this.before,...this.value.tokens(),...this.after]}toString(){return Array.isArray(this.value)?l(...this.before)+this.value.map((e=>e.toString())).join("")+l(...this.after):l(...this.before)+this.value.toString()+l(...this.after)}indexOf(e){return e===this.value?"value":-1}at(e){return"value"===e?this.value:Array.isArray(this.value)&&"number"==typeof e?(e<0&&(e=this.value.length+e),this.value[e]):void 0}walk(t,i){if(Array.isArray(this.value)){if(0===this.value.length)return;const a=e(this.value);let n=0;for(;ne.toJSON())),tokens:this.tokens()}:{type:this.type,value:this.value.toJSON(),tokens:this.tokens()}}isMediaFeatureValue(){return MediaFeatureValue.isMediaFeatureValue(this)}static isMediaFeatureValue(e){return!!e&&(e instanceof MediaFeatureValue&&e.type===w.MediaFeatureValue)}}function parseMediaFeatureValue(e,t=!1){let i=-1,n=-1;for(let r=0;re.tokens())),e.slice(n+1).flatMap((e=>e.tokens())))}function matchesRatioExactly(e){let t=-1,i=-1;const a=matchesRatio(e);if(-1===a)return-1;t=a[0],i=a[1];for(let t=i+1;t2)return!1;if(!M(e[0]))return!1;if(1===e.length)switch(e[0][4].value){case S.EQ:return S.EQ;case T.LT:return T.LT;case C.GT:return C.GT;default:return!1}if(!M(e[1]))return!1;if(e[1][4].value!==S.EQ)return!1;switch(e[0][4].value){case T.LT:return T.LT_OR_EQ;case C.GT:return C.GT_OR_EQ;default:return!1}}function invertComparison(e){switch(e){case S.EQ:return S.EQ;case T.LT:return C.GT;case T.LT_OR_EQ:return C.GT_OR_EQ;case C.GT:return T.LT;case C.GT_OR_EQ:return T.LT_OR_EQ;default:return!1}}!function(e){e.LT="<",e.LT_OR_EQ="<="}(T||(T={})),function(e){e.GT=">",e.GT_OR_EQ=">="}(C||(C={})),function(e){e.EQ="="}(S||(S={}));class MediaFeatureRangeNameValue{type=w.MediaFeatureRangeNameValue;name;operator;value;constructor(e,t,i){this.name=e,this.operator=t,this.value=i}operatorKind(){return comparisonFromTokens(this.operator)}getName(){return this.name.getName()}getNameToken(){return this.name.getNameToken()}tokens(){return[...this.name.tokens(),...this.operator,...this.value.tokens()]}toString(){return this.name.toString()+l(...this.operator)+this.value.toString()}indexOf(e){return e===this.name?"name":e===this.value?"value":-1}at(e){return"name"===e?this.name:"value"===e?this.value:void 0}walk(e,t){let i;return t&&(i={...t}),!1!==e({node:this.value,parent:this,state:i},"value")&&("walk"in this.value?this.value.walk(e,i):void 0)}toJSON(){return{type:this.type,name:this.name.toJSON(),value:this.value.toJSON(),tokens:this.tokens()}}isMediaFeatureRangeNameValue(){return MediaFeatureRangeNameValue.isMediaFeatureRangeNameValue(this)}static isMediaFeatureRangeNameValue(e){return!!e&&(e instanceof MediaFeatureRangeNameValue&&e.type===w.MediaFeatureRangeNameValue)}}class MediaFeatureRangeValueName{type=w.MediaFeatureRangeValueName;name;operator;value;constructor(e,t,i){this.name=e,this.operator=t,this.value=i}operatorKind(){return comparisonFromTokens(this.operator)}getName(){return this.name.getName()}getNameToken(){return this.name.getNameToken()}tokens(){return[...this.value.tokens(),...this.operator,...this.name.tokens()]}toString(){return this.value.toString()+l(...this.operator)+this.name.toString()}indexOf(e){return e===this.name?"name":e===this.value?"value":-1}at(e){return"name"===e?this.name:"value"===e?this.value:void 0}walk(e,t){let i;return t&&(i={...t}),!1!==e({node:this.value,parent:this,state:i},"value")&&("walk"in this.value?this.value.walk(e,i):void 0)}toJSON(){return{type:this.type,name:this.name.toJSON(),value:this.value.toJSON(),tokens:this.tokens()}}isMediaFeatureRangeValueName(){return MediaFeatureRangeValueName.isMediaFeatureRangeValueName(this)}static isMediaFeatureRangeValueName(e){return!!e&&(e instanceof MediaFeatureRangeValueName&&e.type===w.MediaFeatureRangeValueName)}}class MediaFeatureRangeValueNameValue{type=w.MediaFeatureRangeValueNameValue;name;valueOne;valueOneOperator;valueTwo;valueTwoOperator;constructor(e,t,i,a,n){this.name=e,this.valueOne=t,this.valueOneOperator=i,this.valueTwo=a,this.valueTwoOperator=n}valueOneOperatorKind(){return comparisonFromTokens(this.valueOneOperator)}valueTwoOperatorKind(){return comparisonFromTokens(this.valueTwoOperator)}getName(){return this.name.getName()}getNameToken(){return this.name.getNameToken()}tokens(){return[...this.valueOne.tokens(),...this.valueOneOperator,...this.name.tokens(),...this.valueTwoOperator,...this.valueTwo.tokens()]}toString(){return this.valueOne.toString()+l(...this.valueOneOperator)+this.name.toString()+l(...this.valueTwoOperator)+this.valueTwo.toString()}indexOf(e){return e===this.name?"name":e===this.valueOne?"valueOne":e===this.valueTwo?"valueTwo":-1}at(e){return"name"===e?this.name:"valueOne"===e?this.valueOne:"valueTwo"===e?this.valueTwo:void 0}walk(e,t){let i;return t&&(i={...t}),!1!==e({node:this.valueOne,parent:this,state:i},"valueOne")&&((!("walk"in this.valueOne)||!1!==this.valueOne.walk(e,i))&&(t&&(i={...t}),!1!==e({node:this.valueTwo,parent:this,state:i},"valueTwo")&&((!("walk"in this.valueTwo)||!1!==this.valueTwo.walk(e,i))&&void 0)))}toJSON(){return{type:this.type,name:this.name.toJSON(),valueOne:this.valueOne.toJSON(),valueTwo:this.valueTwo.toJSON(),tokens:this.tokens()}}isMediaFeatureRangeValueNameValue(){return MediaFeatureRangeValueNameValue.isMediaFeatureRangeValueNameValue(this)}static isMediaFeatureRangeValueNameValue(e){return!!e&&(e instanceof MediaFeatureRangeValueNameValue&&e.type===w.MediaFeatureRangeValueNameValue)}}function parseMediaFeatureRange(e){let t=!1,i=!1;for(let n=0;ne.tokens())),-1!==a&&(u=e.slice(i+1,a+1).flatMap((e=>e.tokens())))):-1!==a&&(u=e.slice(0,a+1).flatMap((e=>e.tokens())));const d=parseMediaConditionWithoutOr(e.slice(Math.max(i,a,n)+1));return!1===d?new MediaQueryWithType(r,[...u,...e.slice(a+1).flatMap((e=>e.tokens()))]):new MediaQueryWithType(r,u,e.slice(a+1,n+1).flatMap((e=>e.tokens())),d)}}function parseMediaConditionListWithOr(e){let t=!1;const i=[];let n=-1,r=-1;for(let s=0;se.tokens())),e.slice(r+1).flatMap((e=>e.tokens())))}function parseMediaConditionListWithAnd(e){let t=!1;const i=[];let n=-1,r=-1;for(let s=0;se.tokens())),e.slice(r+1).flatMap((e=>e.tokens())))}function parseMediaCondition(e){const t=parseMediaNot(e);if(!1!==t)return new MediaCondition(t);const i=parseMediaConditionListWithAnd(e);if(!1!==i)return new MediaCondition(i);const a=parseMediaConditionListWithOr(e);if(!1!==a)return new MediaCondition(a);const n=parseMediaInParens(e);return!1!==n&&new MediaCondition(n)}function parseMediaConditionWithoutOr(e){const t=parseMediaNot(e);if(!1!==t)return new MediaCondition(t);const i=parseMediaConditionListWithAnd(e);if(!1!==i)return new MediaCondition(i);const a=parseMediaInParens(e);return!1!==a&&new MediaCondition(a)}function parseMediaInParens(e){let t=-1;for(let i=0;ie.tokens())),i.startToken],r=[i.endToken,...e.slice(t+1).flatMap((e=>e.tokens()))],s=parseMediaFeature(i,n,r);if(!1!==s)return new MediaInParens(s);const o=parseMediaCondition(i.value);return!1!==o?new MediaInParens(o,n,r):new MediaInParens(new GeneralEnclosed(i),e.slice(0,t).flatMap((e=>e.tokens())),e.slice(t+1).flatMap((e=>e.tokens())))}function parseMediaInParensFromSimpleBlock(e){if(!v(e.startToken))return!1;const t=parseMediaFeature(e,[e.startToken],[e.endToken]);if(!1!==t)return new MediaInParens(t);const i=parseMediaCondition(e.value);return!1!==i?new MediaInParens(i,[e.startToken],[e.endToken]):new MediaInParens(new GeneralEnclosed(e))}!function(e){e.Not="not",e.Only="only"}(Q||(Q={}));const W=/^not$/i;function parseMediaNot(e){let t=!1,i=null;for(let n=0;ne.tokens())),t)}}}return i||!1}const V=/^or$/i;function parseMediaOr(e){let t=!1;for(let i=0;ie.tokens())),t)}}return!1}}return!1}const L=/^and$/i;function parseMediaAnd(e){let t=!1;for(let i=0;ie.tokens())),t)}}return!1}}return!1}function parseFromTokens(e,t){const i=d(e,{onParseError:t?.onParseError});return i.map(((e,a)=>{const n=parseMediaQuery(e);return!1===n&&!0===t?.preserveInvalidMediaQueries?new MediaQueryInvalid(i[a]):n})).filter((e=>!!e))}function parse(e,t){const i=g({css:e},{onParseError:t?.onParseError}),a=[];for(;!i.endOfFile();)a.push(i.nextToken());return a.push(i.nextToken()),parseFromTokens(a,t)}class CustomMedia{type=w.CustomMedia;name;mediaQueryList=null;trueOrFalseKeyword=null;constructor(e,t,i){this.name=e,this.mediaQueryList=t,this.trueOrFalseKeyword=i??null}getName(){for(let e=0;ee.toJSON()))}}isCustomMedia(){return CustomMedia.isCustomMedia(this)}static isCustomMedia(e){return!!e&&(e instanceof CustomMedia&&e.type===w.CustomMedia)}}function parseCustomMediaFromTokens(e,t){let i=[],a=e;for(let t=0;te.tokens()))}toString(){return this.media.map((e=>e.toString())).join("")}walk(t,i){if(0===this.media.length)return;const a=e(this.media);let n=0;for(;ne.tokens())),...this.after]}toString(){return h(...this.before)+this.leading.toString()+this.list.map((e=>e.toString())).join("")+h(...this.after)}indexOf(e){return e===this.leading?"leading":e.type===O.MediaAnd?this.list.indexOf(e):-1}at(e){return"leading"===e?this.leading:"number"==typeof e?(e<0&&(e=this.list.length+e),this.list[e]):void 0}walk(t,i){let a;if(i&&(a={...i}),!1===t({node:this.leading,parent:this,state:a},"leading"))return!1;if("walk"in this.leading&&!1===this.leading.walk(t,a))return!1;if(0===this.list.length)return;const n=e(this.list);let r=0;for(;re.toJSON())),before:this.before,after:this.after}}isMediaConditionListWithAnd(){return MediaConditionListWithAnd.isMediaConditionListWithAnd(this)}static isMediaConditionListWithAnd(e){return!!e&&(e instanceof MediaConditionListWithAnd&&e.type===O.MediaConditionListWithAnd)}}class MediaConditionListWithOr{type=O.MediaConditionListWithOr;leading;list;before;after;constructor(e,t,i=[],a=[]){this.leading=e,this.list=t,this.before=i,this.after=a}tokens(){return[...this.before,...this.leading.tokens(),...this.list.flatMap((e=>e.tokens())),...this.after]}toString(){return h(...this.before)+this.leading.toString()+this.list.map((e=>e.toString())).join("")+h(...this.after)}indexOf(e){return e===this.leading?"leading":e.type===O.MediaOr?this.list.indexOf(e):-1}at(e){return"leading"===e?this.leading:"number"==typeof e?(e<0&&(e=this.list.length+e),this.list[e]):void 0}walk(t,i){let a;if(i&&(a={...i}),!1===t({node:this.leading,parent:this,state:a},"leading"))return!1;if("walk"in this.leading&&!1===this.leading.walk(t,a))return!1;if(0===this.list.length)return;const n=e(this.list);let r=0;for(;re.toJSON())),before:this.before,after:this.after}}isMediaConditionListWithOr(){return MediaConditionListWithOr.isMediaConditionListWithOr(this)}static isMediaConditionListWithOr(e){return!!e&&(e instanceof MediaConditionListWithOr&&e.type===O.MediaConditionListWithOr)}}function isNumber(e){return!!(t(e)&&c(e.value)||i(e)&&T.has(e.getName().toLowerCase()))}const T=new Set(["abs","acos","asin","atan","atan2","calc","clamp","cos","exp","hypot","log","max","min","mod","pow","rem","round","sign","sin","sqrt","tan"]);function isDimension(e){return t(e)&&M(e.value)}function isIdent(e){return t(e)&&m(e.value)}function isEnvironmentVariable(e){return i(e)&&"env"===e.getName().toLowerCase()}class MediaFeatureName{type=O.MediaFeatureName;name;before;after;constructor(e,t=[],i=[]){this.name=e,this.before=t,this.after=i}getName(){return this.name.value[4].value}getNameToken(){return this.name.value}tokens(){return[...this.before,...this.name.tokens(),...this.after]}toString(){return h(...this.before)+this.name.toString()+h(...this.after)}indexOf(e){return e===this.name?"name":-1}at(e){if("name"===e)return this.name}toJSON(){return{type:this.type,name:this.getName(),tokens:this.tokens()}}isMediaFeatureName(){return MediaFeatureName.isMediaFeatureName(this)}static isMediaFeatureName(e){return!!e&&(e instanceof MediaFeatureName&&e.type===O.MediaFeatureName)}}function parseMediaFeatureName(e){let t=-1;for(let i=0;ie.tokens())),e.slice(t+1).flatMap((e=>e.tokens())))}class MediaFeatureBoolean{type=O.MediaFeatureBoolean;name;constructor(e){this.name=e}getName(){return this.name.getName()}getNameToken(){return this.name.getNameToken()}tokens(){return this.name.tokens()}toString(){return this.name.toString()}indexOf(e){return e===this.name?"name":-1}at(e){if("name"===e)return this.name}toJSON(){return{type:this.type,name:this.name.toJSON(),tokens:this.tokens()}}isMediaFeatureBoolean(){return MediaFeatureBoolean.isMediaFeatureBoolean(this)}static isMediaFeatureBoolean(e){return!!e&&(e instanceof MediaFeatureBoolean&&e.type===O.MediaFeatureBoolean)}}function parseMediaFeatureBoolean(e){const t=parseMediaFeatureName(e);return!1===t?t:new MediaFeatureBoolean(t)}class MediaFeatureValue{type=O.MediaFeatureValue;value;before;after;constructor(e,t=[],i=[]){Array.isArray(e)&&1===e.length?this.value=e[0]:this.value=e,this.before=t,this.after=i}tokens(){return Array.isArray(this.value)?[...this.before,...this.value.flatMap((e=>e.tokens())),...this.after]:[...this.before,...this.value.tokens(),...this.after]}toString(){return Array.isArray(this.value)?h(...this.before)+this.value.map((e=>e.toString())).join("")+h(...this.after):h(...this.before)+this.value.toString()+h(...this.after)}indexOf(e){return e===this.value?"value":-1}at(e){return"value"===e?this.value:Array.isArray(this.value)&&"number"==typeof e?(e<0&&(e=this.value.length+e),this.value[e]):void 0}walk(t,i){if(Array.isArray(this.value)){if(0===this.value.length)return;const a=e(this.value);let n=0;for(;ne.toJSON())),tokens:this.tokens()}:{type:this.type,value:this.value.toJSON(),tokens:this.tokens()}}isMediaFeatureValue(){return MediaFeatureValue.isMediaFeatureValue(this)}static isMediaFeatureValue(e){return!!e&&(e instanceof MediaFeatureValue&&e.type===O.MediaFeatureValue)}}function parseMediaFeatureValue(e,t=!1){let i=-1,n=-1;for(let r=0;re.tokens())),e.slice(n+1).flatMap((e=>e.tokens())))}function matchesRatioExactly(e){let t=-1,i=-1;const a=matchesRatio(e);if(-1===a)return-1;t=a[0],i=a[1];for(let t=i+1;t",e.GT_OR_EQ=">="}(S||(S={})),function(e){e.EQ="="}(Q||(Q={}));class MediaFeatureRangeNameValue{type=O.MediaFeatureRangeNameValue;name;operator;value;constructor(e,t,i){this.name=e,this.operator=t,this.value=i}operatorKind(){return comparisonFromTokens(this.operator)}getName(){return this.name.getName()}getNameToken(){return this.name.getNameToken()}tokens(){return[...this.name.tokens(),...this.operator,...this.value.tokens()]}toString(){return this.name.toString()+h(...this.operator)+this.value.toString()}indexOf(e){return e===this.name?"name":e===this.value?"value":-1}at(e){return"name"===e?this.name:"value"===e?this.value:void 0}walk(e,t){let i;return t&&(i={...t}),!1!==e({node:this.value,parent:this,state:i},"value")&&("walk"in this.value?this.value.walk(e,i):void 0)}toJSON(){return{type:this.type,name:this.name.toJSON(),value:this.value.toJSON(),tokens:this.tokens()}}isMediaFeatureRangeNameValue(){return MediaFeatureRangeNameValue.isMediaFeatureRangeNameValue(this)}static isMediaFeatureRangeNameValue(e){return!!e&&(e instanceof MediaFeatureRangeNameValue&&e.type===O.MediaFeatureRangeNameValue)}}class MediaFeatureRangeValueName{type=O.MediaFeatureRangeValueName;name;operator;value;constructor(e,t,i){this.name=e,this.operator=t,this.value=i}operatorKind(){return comparisonFromTokens(this.operator)}getName(){return this.name.getName()}getNameToken(){return this.name.getNameToken()}tokens(){return[...this.value.tokens(),...this.operator,...this.name.tokens()]}toString(){return this.value.toString()+h(...this.operator)+this.name.toString()}indexOf(e){return e===this.name?"name":e===this.value?"value":-1}at(e){return"name"===e?this.name:"value"===e?this.value:void 0}walk(e,t){let i;return t&&(i={...t}),!1!==e({node:this.value,parent:this,state:i},"value")&&("walk"in this.value?this.value.walk(e,i):void 0)}toJSON(){return{type:this.type,name:this.name.toJSON(),value:this.value.toJSON(),tokens:this.tokens()}}isMediaFeatureRangeValueName(){return MediaFeatureRangeValueName.isMediaFeatureRangeValueName(this)}static isMediaFeatureRangeValueName(e){return!!e&&(e instanceof MediaFeatureRangeValueName&&e.type===O.MediaFeatureRangeValueName)}}class MediaFeatureRangeValueNameValue{type=O.MediaFeatureRangeValueNameValue;name;valueOne;valueOneOperator;valueTwo;valueTwoOperator;constructor(e,t,i,a,n){this.name=e,this.valueOne=t,this.valueOneOperator=i,this.valueTwo=a,this.valueTwoOperator=n}valueOneOperatorKind(){return comparisonFromTokens(this.valueOneOperator)}valueTwoOperatorKind(){return comparisonFromTokens(this.valueTwoOperator)}getName(){return this.name.getName()}getNameToken(){return this.name.getNameToken()}tokens(){return[...this.valueOne.tokens(),...this.valueOneOperator,...this.name.tokens(),...this.valueTwoOperator,...this.valueTwo.tokens()]}toString(){return this.valueOne.toString()+h(...this.valueOneOperator)+this.name.toString()+h(...this.valueTwoOperator)+this.valueTwo.toString()}indexOf(e){return e===this.name?"name":e===this.valueOne?"valueOne":e===this.valueTwo?"valueTwo":-1}at(e){return"name"===e?this.name:"valueOne"===e?this.valueOne:"valueTwo"===e?this.valueTwo:void 0}walk(e,t){let i;return t&&(i={...t}),!1!==e({node:this.valueOne,parent:this,state:i},"valueOne")&&((!("walk"in this.valueOne)||!1!==this.valueOne.walk(e,i))&&(t&&(i={...t}),!1!==e({node:this.valueTwo,parent:this,state:i},"valueTwo")&&((!("walk"in this.valueTwo)||!1!==this.valueTwo.walk(e,i))&&void 0)))}toJSON(){return{type:this.type,name:this.name.toJSON(),valueOne:this.valueOne.toJSON(),valueTwo:this.valueTwo.toJSON(),tokens:this.tokens()}}isMediaFeatureRangeValueNameValue(){return MediaFeatureRangeValueNameValue.isMediaFeatureRangeValueNameValue(this)}static isMediaFeatureRangeValueNameValue(e){return!!e&&(e instanceof MediaFeatureRangeValueNameValue&&e.type===O.MediaFeatureRangeValueNameValue)}}function parseMediaFeatureRange(e){let t=!1,i=!1;for(let n=0;ne.tokens())),-1!==a&&(s=e.slice(i+1,a+1).flatMap((e=>e.tokens())))):-1!==a&&(s=e.slice(0,a+1).flatMap((e=>e.tokens())));const d=parseMediaConditionWithoutOr(e.slice(Math.max(i,a,n)+1));return!1===d?new MediaQueryWithType(r,[...s,...e.slice(a+1).flatMap((e=>e.tokens()))]):new MediaQueryWithType(r,s,e.slice(a+1,n+1).flatMap((e=>e.tokens())),d)}}function parseMediaConditionListWithOr(e){let t=!1;const i=[];let n=-1,r=-1;for(let s=0;se.tokens())),e.slice(r+1).flatMap((e=>e.tokens())))}function parseMediaConditionListWithAnd(e){let t=!1;const i=[];let n=-1,r=-1;for(let s=0;se.tokens())),e.slice(r+1).flatMap((e=>e.tokens())))}function parseMediaCondition(e){const t=parseMediaNot(e);if(!1!==t)return new MediaCondition(t);const i=parseMediaConditionListWithAnd(e);if(!1!==i)return new MediaCondition(i);const a=parseMediaConditionListWithOr(e);if(!1!==a)return new MediaCondition(a);const n=parseMediaInParens(e);return!1!==n&&new MediaCondition(n)}function parseMediaConditionWithoutOr(e){const t=parseMediaNot(e);if(!1!==t)return new MediaCondition(t);const i=parseMediaConditionListWithAnd(e);if(!1!==i)return new MediaCondition(i);const a=parseMediaInParens(e);return!1!==a&&new MediaCondition(a)}function parseMediaInParens(e){let t=-1;for(let i=0;ie.tokens())),i.startToken],r=[i.endToken,...e.slice(t+1).flatMap((e=>e.tokens()))],s=parseMediaFeature(i,n,r);if(!1!==s)return new MediaInParens(s);const o=parseMediaCondition(i.value);return!1!==o?new MediaInParens(o,n,r):new MediaInParens(new GeneralEnclosed(i),e.slice(0,t).flatMap((e=>e.tokens())),e.slice(t+1).flatMap((e=>e.tokens())))}function parseMediaInParensFromSimpleBlock(e){if(!g(e.startToken))return!1;const t=parseMediaFeature(e,[e.startToken],[e.endToken]);if(!1!==t)return new MediaInParens(t);const i=parseMediaCondition(e.value);return!1!==i?new MediaInParens(i,[e.startToken],[e.endToken]):new MediaInParens(new GeneralEnclosed(e))}!function(e){e.Not="not",e.Only="only"}(W||(W={}));const V=/^not$/i;function parseMediaNot(e){let t=!1,i=null;for(let n=0;ne.tokens())),t)}}}return i||!1}const L=/^or$/i;function parseMediaOr(e){let t=!1;for(let i=0;ie.tokens())),t)}}return!1}}return!1}const R=/^and$/i;function parseMediaAnd(e){let t=!1;for(let i=0;ie.tokens())),t)}}return!1}}return!1}function parseFromTokens(e,t){const i=l(e,{onParseError:t?.onParseError});return i.map(((e,a)=>{const n=parseMediaQuery(e);return!1===n&&!0===t?.preserveInvalidMediaQueries?new MediaQueryInvalid(i[a]):n})).filter((e=>!!e))}function parse(e,t){const i=k({css:e},{onParseError:t?.onParseError}),a=[];for(;!i.endOfFile();)a.push(i.nextToken());return a.push(i.nextToken()),parseFromTokens(a,t)}class CustomMedia{type=O.CustomMedia;name;mediaQueryList=null;trueOrFalseKeyword=null;constructor(e,t,i){this.name=e,this.mediaQueryList=t,this.trueOrFalseKeyword=i??null}getName(){for(let e=0;ee.toJSON()))}}isCustomMedia(){return CustomMedia.isCustomMedia(this)}static isCustomMedia(e){return!!e&&(e instanceof CustomMedia&&e.type===O.CustomMedia)}}function parseCustomMediaFromTokens(e,t){let i=[],a=e;for(let t=0;t, [MediaAnd](./media-query-list-parser.mediaand.md), [MediaNot](./media-query-list-parser.medianot.md), [MediaOr](./media-query-list-parser.mediaor.md), [MediaConditionList](./media-query-list-parser.mediaconditionlist.md), [MediaCondition](./media-query-list-parser.mediacondition.md), [MediaFeatureBoolean](./media-query-list-parser.mediafeatureboolean.md), [MediaFeatureName](./media-query-list-parser.mediafeaturename.md), [MediaFeaturePlain](./media-query-list-parser.mediafeatureplain.md), [MediaFeatureRange](./media-query-list-parser.mediafeaturerange.md), [MediaFeatureValue](./media-query-list-parser.mediafeaturevalue.md), [MediaFeature](./media-query-list-parser.mediafeature.md), [MediaInParens](./media-query-list-parser.mediainparens.md) diff --git a/packages/media-query-list-parser/docs/media-query-list-parser.mediainparenswalkerparent.md b/packages/media-query-list-parser/docs/media-query-list-parser.mediainparenswalkerparent.md index 29ef868dd..225367094 100644 --- a/packages/media-query-list-parser/docs/media-query-list-parser.mediainparenswalkerparent.md +++ b/packages/media-query-list-parser/docs/media-query-list-parser.mediainparenswalkerparent.md @@ -7,7 +7,7 @@ **Signature:** ```typescript -export type MediaInParensWalkerParent = ContainerNode | GeneralEnclosed | MediaAnd | MediaNot | MediaOr | MediaConditionList | MediaCondition | MediaFeatureBoolean | MediaFeatureName | MediaFeaturePlain | MediaFeatureRange | MediaFeatureValue | MediaFeature | GeneralEnclosed | MediaInParens; +export type MediaInParensWalkerParent = ContainerNode | GeneralEnclosed | MediaAnd | MediaNot | MediaOr | MediaConditionList | MediaCondition | MediaFeatureBoolean | MediaFeatureName | MediaFeaturePlain | MediaFeatureRange | MediaFeatureValue | MediaFeature | MediaInParens; ``` **References:** [GeneralEnclosed](./media-query-list-parser.generalenclosed.md), [MediaAnd](./media-query-list-parser.mediaand.md), [MediaNot](./media-query-list-parser.medianot.md), [MediaOr](./media-query-list-parser.mediaor.md), [MediaConditionList](./media-query-list-parser.mediaconditionlist.md), [MediaCondition](./media-query-list-parser.mediacondition.md), [MediaFeatureBoolean](./media-query-list-parser.mediafeatureboolean.md), [MediaFeatureName](./media-query-list-parser.mediafeaturename.md), [MediaFeaturePlain](./media-query-list-parser.mediafeatureplain.md), [MediaFeatureRange](./media-query-list-parser.mediafeaturerange.md), [MediaFeatureValue](./media-query-list-parser.mediafeaturevalue.md), [MediaFeature](./media-query-list-parser.mediafeature.md), [MediaInParens](./media-query-list-parser.mediainparens.md) diff --git a/packages/media-query-list-parser/src/nodes/media-condition-list.ts b/packages/media-query-list-parser/src/nodes/media-condition-list.ts index 30afb66c5..cc4aef190 100644 --- a/packages/media-query-list-parser/src/nodes/media-condition-list.ts +++ b/packages/media-query-list-parser/src/nodes/media-condition-list.ts @@ -40,7 +40,7 @@ export class MediaConditionListWithAnd { return 'leading'; } - if (item.type === 'media-and') { + if (item.type === NodeType.MediaAnd) { return this.list.indexOf(item as MediaAnd); } @@ -174,7 +174,7 @@ export class MediaConditionListWithOr { return 'leading'; } - if (item.type === 'media-or') { + if (item.type === NodeType.MediaOr) { return this.list.indexOf(item as MediaOr); } diff --git a/packages/media-query-list-parser/src/nodes/media-feature-comparison.ts b/packages/media-query-list-parser/src/nodes/media-feature-comparison.ts index 1ba97f75a..984286d85 100644 --- a/packages/media-query-list-parser/src/nodes/media-feature-comparison.ts +++ b/packages/media-query-list-parser/src/nodes/media-feature-comparison.ts @@ -25,18 +25,18 @@ export function matchesComparison(componentValues: Array): false if (componentValue.type === ComponentValueType.Token) { const token = componentValue.value as CSSToken; if (isTokenDelim(token)) { - if (token[4].value === MediaFeatureEQ.EQ) { + if ((token[4].value as MediaFeatureComparison) === MediaFeatureEQ.EQ) { if (firstTokenIndex !== -1) { return [firstTokenIndex, i]; } return [i, i]; } - if (token[4].value === MediaFeatureLT.LT) { + if ((token[4].value as MediaFeatureComparison) === MediaFeatureLT.LT) { firstTokenIndex = i; continue; } - if (token[4].value === MediaFeatureGT.GT) { + if ((token[4].value as MediaFeatureComparison) === MediaFeatureGT.GT) { firstTokenIndex = i; continue; } @@ -54,9 +54,7 @@ export function matchesComparison(componentValues: Array): false } export function comparisonFromTokens(tokens: [TokenDelim, TokenDelim] | [TokenDelim]): MediaFeatureComparison | false { - // eslint-disable-next-line @typescript-eslint/ban-ts-comment - /* @ts-ignore */ - if (tokens.length === 0 || tokens.length > 2) { + if (tokens.length !== 1 && tokens.length !== 2) { return false; } @@ -65,7 +63,7 @@ export function comparisonFromTokens(tokens: [TokenDelim, TokenDelim] | [TokenDe } if (tokens.length === 1) { - switch (tokens[0][4].value) { + switch (tokens[0][4].value as MediaFeatureComparison) { case MediaFeatureEQ.EQ: return MediaFeatureEQ.EQ; case MediaFeatureLT.LT: @@ -81,11 +79,11 @@ export function comparisonFromTokens(tokens: [TokenDelim, TokenDelim] | [TokenDe return false; } - if (tokens[1][4].value !== MediaFeatureEQ.EQ) { + if ((tokens[1][4].value as MediaFeatureComparison) !== MediaFeatureEQ.EQ) { return false; } - switch (tokens[0][4].value) { + switch (tokens[0][4].value as MediaFeatureComparison) { case MediaFeatureLT.LT: return MediaFeatureLT.LT_OR_EQ; case MediaFeatureGT.GT: diff --git a/packages/media-query-list-parser/src/nodes/media-feature-name.ts b/packages/media-query-list-parser/src/nodes/media-feature-name.ts index d716921ca..d9ecb1a82 100644 --- a/packages/media-query-list-parser/src/nodes/media-feature-name.ts +++ b/packages/media-query-list-parser/src/nodes/media-feature-name.ts @@ -17,12 +17,12 @@ export class MediaFeatureName { } getName(): string { - const token = (((this.name as TokenNode).value as CSSToken) as TokenIdent); + const token = (((this.name as TokenNode).value) as TokenIdent); return token[4].value; } getNameToken(): CSSToken { - const token = (((this.name as TokenNode).value as CSSToken) as TokenIdent); + const token = (((this.name as TokenNode).value) as TokenIdent); return token; } diff --git a/packages/media-query-list-parser/src/nodes/media-feature-value.ts b/packages/media-query-list-parser/src/nodes/media-feature-value.ts index c61ae4258..5b0d50044 100644 --- a/packages/media-query-list-parser/src/nodes/media-feature-value.ts +++ b/packages/media-query-list-parser/src/nodes/media-feature-value.ts @@ -1,8 +1,9 @@ -import { ComponentValue, ComponentValueType, ContainerNode, walkerIndexGenerator } from '@csstools/css-parser-algorithms'; +import { ComponentValue, ComponentValueType, ContainerNode, isTokenNode, walkerIndexGenerator } from '@csstools/css-parser-algorithms'; import { CSSToken, stringify } from '@csstools/css-tokenizer'; import { isDimension, isEnvironmentVariable, isIdent, isNumber } from '../util/component-value-is'; import { NodeType } from '../util/node-type'; import { isTokenDelim } from '@csstools/css-tokenizer'; +import { isWhiteSpaceOrCommentNode } from '@csstools/css-parser-algorithms'; export class MediaFeatureValue { type = NodeType.MediaFeatureValue; @@ -243,11 +244,7 @@ export function matchesRatioExactly(componentValues: Array): -1 for (let i = secondNumber+1; i < componentValues.length; i++) { const componentValue = componentValues[i]; - if (componentValue.type === 'whitespace') { - continue; - } - - if (componentValue.type === 'comment') { + if (isWhiteSpaceOrCommentNode(componentValue)) { continue; } @@ -263,16 +260,12 @@ export function matchesRatio(componentValues: Array): -1 | [numb for (let i = 0; i < componentValues.length; i++) { const componentValue = componentValues[i]; - if (componentValue.type === 'whitespace') { - continue; - } - - if (componentValue.type === 'comment') { + if (isWhiteSpaceOrCommentNode(componentValue)) { continue; } - if (componentValue.type === 'token') { - const token = componentValue.value as CSSToken; + if (isTokenNode(componentValue)) { + const token = componentValue.value; if (isTokenDelim(token) && token[4].value === '/') { if (firstNumber === -1) { return -1; diff --git a/packages/media-query-list-parser/src/nodes/media-in-parens.ts b/packages/media-query-list-parser/src/nodes/media-in-parens.ts index 610b1910b..e19be20c7 100644 --- a/packages/media-query-list-parser/src/nodes/media-in-parens.ts +++ b/packages/media-query-list-parser/src/nodes/media-in-parens.ts @@ -102,5 +102,5 @@ export class MediaInParens { } } -export type MediaInParensWalkerEntry = ComponentValue | GeneralEnclosed | MediaAnd | MediaNot | MediaOr | MediaConditionList | MediaCondition | MediaFeatureBoolean | MediaFeatureName | MediaFeaturePlain | MediaFeatureRange | MediaFeatureValue | MediaFeature | GeneralEnclosed | MediaInParens; -export type MediaInParensWalkerParent = ContainerNode | GeneralEnclosed | MediaAnd | MediaNot | MediaOr | MediaConditionList | MediaCondition | MediaFeatureBoolean | MediaFeatureName | MediaFeaturePlain | MediaFeatureRange | MediaFeatureValue | MediaFeature | GeneralEnclosed | MediaInParens; +export type MediaInParensWalkerEntry = ComponentValue | GeneralEnclosed | MediaAnd | MediaNot | MediaOr | MediaConditionList | MediaCondition | MediaFeatureBoolean | MediaFeatureName | MediaFeaturePlain | MediaFeatureRange | MediaFeatureValue | MediaFeature | MediaInParens; +export type MediaInParensWalkerParent = ContainerNode | GeneralEnclosed | MediaAnd | MediaNot | MediaOr | MediaConditionList | MediaCondition | MediaFeatureBoolean | MediaFeatureName | MediaFeaturePlain | MediaFeatureRange | MediaFeatureValue | MediaFeature | MediaInParens; diff --git a/packages/media-query-list-parser/src/nodes/media-query-modifier.ts b/packages/media-query-list-parser/src/nodes/media-query-modifier.ts index a2d86e168..d3d8d0721 100644 --- a/packages/media-query-list-parser/src/nodes/media-query-modifier.ts +++ b/packages/media-query-list-parser/src/nodes/media-query-modifier.ts @@ -11,7 +11,7 @@ export function modifierFromToken(token: TokenIdent): MediaQueryModifier | false } const matchingValue = token[4].value.toLowerCase(); - switch (matchingValue) { + switch (matchingValue as MediaQueryModifier) { case MediaQueryModifier.Not: return MediaQueryModifier.Not; case MediaQueryModifier.Only: diff --git a/packages/media-query-list-parser/src/nodes/media-type.ts b/packages/media-query-list-parser/src/nodes/media-type.ts index 001aa4368..4b57f4ba0 100644 --- a/packages/media-query-list-parser/src/nodes/media-type.ts +++ b/packages/media-query-list-parser/src/nodes/media-type.ts @@ -29,7 +29,7 @@ export function typeFromToken(token: TokenIdent): MediaType | false { } const matchingValue = token[4].value.toLowerCase(); - switch (matchingValue) { + switch (matchingValue as MediaType) { case MediaType.All: return MediaType.All; case MediaType.Print: diff --git a/packages/media-query-list-parser/src/parser/parse-media-query.ts b/packages/media-query-list-parser/src/parser/parse-media-query.ts index a42617d3e..081c31edf 100644 --- a/packages/media-query-list-parser/src/parser/parse-media-query.ts +++ b/packages/media-query-list-parser/src/parser/parse-media-query.ts @@ -28,7 +28,7 @@ export function parseMediaQuery(componentValues: Array): MediaQu let andIndex = -1; for (let i = 0; i < componentValues.length; i++) { - const componentValue = componentValues[i] as ComponentValue; + const componentValue = componentValues[i]; if (isWhitespaceNode(componentValue)) { continue; } @@ -449,7 +449,7 @@ function parseMediaOr(componentValues: Array): { advance: number if (sawOr && isSimpleBlockNode(componentValue)) { componentValue.normalize(); - const media = parseMediaInParensFromSimpleBlock(componentValue as SimpleBlockNode); + const media = parseMediaInParensFromSimpleBlock(componentValue); if (media === false) { return false; } @@ -502,7 +502,7 @@ function parseMediaAnd(componentValues: Array): { advance: numbe if (sawAnd && isSimpleBlockNode(componentValue)) { componentValue.normalize(); - const media = parseMediaInParensFromSimpleBlock(componentValue as SimpleBlockNode); + const media = parseMediaInParensFromSimpleBlock(componentValue); if (media === false) { return false; } diff --git a/packages/postcss-tape/dist/index.cjs b/packages/postcss-tape/dist/index.cjs index cd1e86f65..e61942995 100644 --- a/packages/postcss-tape/dist/index.cjs +++ b/packages/postcss-tape/dist/index.cjs @@ -1,3 +1,3 @@ /* node:coverage disable */ -"use strict";var e=require("node:assert/strict"),s=require("node:fs/promises"),t=require("node:fs"),n=require("node:path"),o=require("postcss"),r=require("postcss-8.4"),i=require("node:test"),a=require("node:url");const noopPlugin=()=>({postcssPlugin:"noop-plugin",Once(){}});async function fileContentsOrEmptyString(e){try{return await s.readFile(e,"utf8")}catch(e){return""}}function reduceInformationInCssSyntaxError(e){process.env.DEBUG||(delete e.source,e.input&&delete e.input.source,delete e.postcssNode)}noopPlugin.postcss=!0;const c={postcssPlugin:"declaration-cloner",Declaration(e){"to-clone"===e.prop&&e.cloneBefore({prop:"cloned"})}},p={postcssPlugin:"rule-cloner",prepare(){const e=new WeakSet;return{postcssPlugin:"rule-cloner",RuleExit(s){e.has(s)||"to-clone"===s.selector&&(e.add(s),s.cloneBefore({selector:"cloned"}))}}}},l={postcssPlugin:"at-rule-cloner",prepare(){const e=new WeakSet;return{postcssPlugin:"at-rule-cloner",AtRuleExit(s){if(!e.has(s))return"to-clone"===s.params?(e.add(s),void s.cloneBefore({params:"cloned"})):"to-clone"===s.name?(e.add(s),void s.cloneBefore({name:"cloned"})):void 0}}}};class PackageDescriptionError extends Error{constructor(e,s){super(e),this.name="PackageDescriptionError",this.stack=`${this.name}: ${this.message}\n at "${s}" (${a.pathToFileURL(n.resolve("package.json"))}:1:1)`}}class OutcomeError extends Error{constructor(e,s){super(e),this.name="OutcomeError",this.stack=`${this.name}: ${this.message}\n at ${a.pathToFileURL(n.resolve(s))}:1:1`}}exports.atRuleClonerPlugin=l,exports.declarationClonerPlugin=c,exports.postcssTape=function postcssTape(a,c){c=c??{},i("`postcss` flag is set on exported plugin creator",(()=>{e.equal(a.postcss,!0)})),i("exported plugin creator is a function",(()=>{e.equal(typeof a,"function")})),i("`postcssPlugin` is set on a plugin instance",(()=>{const s=a();e.ok(s.postcssPlugin),e.equal(typeof s.postcssPlugin,"string")})),i("package.json",(async t=>{const n=await s.readFile("./package.json","utf-8"),o=JSON.parse(n);await t.test('includes "postcss-plugin" keyword',(()=>{e.ok(o.keywords?.includes("postcss-plugin"),new PackageDescriptionError('Missing "postcss-plugin" keyword in package.json',"keywords"))})),await t.test('name starts with "postcss-"',{skip:c?.skipPackageNameCheck},(()=>{let s=o.name;if(s.startsWith("@")){s=o.name.split("/").slice(1).join("/")}e.ok(s.startsWith("postcss-"),new PackageDescriptionError(`package name "${s}" does not start with "postcss-"`,"name"))})),await t.test("`postcss` is a peer dependency and not a direct dependency",{skip:"postcssTapeSelfTest"in a},(()=>{e.ok(Object.keys(Object(o.peerDependencies)).includes("postcss"),new PackageDescriptionError('"postcss" must be listed in "peerDependencies"',"peerDependencies")),e.ok(!Object.keys(Object(o.dependencies)).includes("postcss"),new PackageDescriptionError('"postcss" must not be listed in "dependencies"',"dependencies"))}))}));const p=a().postcssPlugin;return async c=>{await i(p,(async i=>{for(const p in c)await i.test(p,(async i=>{const l=c[p];l.before&&await l.before();const u=n.join(".","test",...p.split(":")[0].split(n.posix.sep)),d=n.join(".","test",...p.replace(/:/g,".").split(n.posix.sep)),g="css";let m=`${u}.${g}`,w=`${d}.expect.${g}`,f=`${d}.result.${g}`;l.source&&(m=n.join(".","test",l.source)),l.expect&&(w=n.join(".","test",l.expect)),l.result&&(f=n.join(".","test",l.result));const k=l.plugins??[a(l.options)],h=await fileContentsOrEmptyString(m),y=await fileContentsOrEmptyString(w);let E;try{E=await o(k).process(h,{from:m,to:f,map:{inline:!1,annotation:!1}})}catch(e){if(reduceInformationInCssSyntaxError(e),l.exception&&l.exception.test(e.message))return;throw e}e.ok(!l.exception,new OutcomeError(`expected an exception matching "${l.exception}"`,m));const x=E.css.toString();{const e=[s.writeFile(f,x,"utf8")];process.env.REWRITE_EXPECTS&&e.push(s.writeFile(w,x,"utf8")),await Promise.all(e)}y||e.ok(t.existsSync(w),new OutcomeError(`Missing expect file: "${w}"`,m)),await i.test("has expected output",(()=>{e.deepEqual(x,y),e.deepEqual(E.warnings().length,l.warnings??0,`Unexpected number warnings:\n${E.warnings()}`)})),await i.test("sourcemaps",(async()=>{e.ok(!E.map.toJSON().sources.includes(""),'Sourcemap is broken. This is most likely a newly created PostCSS AST Node without a value for "source". See: https://github.com/postcss/postcss/blob/main/docs/guidelines/plugin.md#24-set-nodesource-for-new-nodes')})),l.after&&await l.after(),await i.test("output is parsable with PostCSS",(async()=>{const s=await fileContentsOrEmptyString(f),t=await o([noopPlugin()]).process(s,{from:f,to:f,map:{inline:!1,annotation:!1}});e.deepEqual(t.warnings(),[],"Unexpected warnings on second pass")})),await i.test("The oldest and current PostCSS version produce the same result",{skip:o([noopPlugin()]).version===r([noopPlugin()]).version},(async()=>{const s=await r(k).process(h,{from:m,to:f,map:{inline:!1,annotation:!1}});e.deepEqual(s.css.toString(),x)}))}))}))}},exports.ruleClonerPlugin=p; +"use strict";var e=require("node:assert/strict"),s=require("node:fs/promises"),t=require("node:fs"),n=require("node:path"),o=require("postcss"),r=require("postcss-8.4"),i=require("node:test"),a=require("node:url");const noopPlugin=()=>({postcssPlugin:"noop-plugin",Once(){}});async function fileContentsOrEmptyString(e){try{return await s.readFile(e,"utf8")}catch{return""}}function reduceInformationInCssSyntaxError(e){process.env.DEBUG||(delete e.source,e.input&&delete e.input.source,delete e.postcssNode)}noopPlugin.postcss=!0;const c={postcssPlugin:"declaration-cloner",Declaration(e){"to-clone"===e.prop&&e.cloneBefore({prop:"cloned"})}},p={postcssPlugin:"rule-cloner",prepare(){const e=new WeakSet;return{postcssPlugin:"rule-cloner",RuleExit(s){e.has(s)||"to-clone"===s.selector&&(e.add(s),s.cloneBefore({selector:"cloned"}))}}}},l={postcssPlugin:"at-rule-cloner",prepare(){const e=new WeakSet;return{postcssPlugin:"at-rule-cloner",AtRuleExit(s){if(!e.has(s))return"to-clone"===s.params?(e.add(s),void s.cloneBefore({params:"cloned"})):"to-clone"===s.name?(e.add(s),void s.cloneBefore({name:"cloned"})):void 0}}}};class PackageDescriptionError extends Error{constructor(e,s){super(e),this.name="PackageDescriptionError",this.stack=`${this.name}: ${this.message}\n at "${s}" (${a.pathToFileURL(n.resolve("package.json")).href}:1:1)`}}class OutcomeError extends Error{constructor(e,s){super(e),this.name="OutcomeError",this.stack=`${this.name}: ${this.message}\n at ${a.pathToFileURL(n.resolve(s)).href}:1:1`}}exports.atRuleClonerPlugin=l,exports.declarationClonerPlugin=c,exports.postcssTape=function postcssTape(a,c){return async p=>{c=c??{},await i("`postcss` flag is set on exported plugin creator",(()=>{e.equal(a.postcss,!0)})),await i("exported plugin creator is a function",(()=>{e.equal(typeof a,"function")})),await i("`postcssPlugin` is set on a plugin instance",(()=>{const s=a();e.ok(s.postcssPlugin),e.equal(typeof s.postcssPlugin,"string")})),await i("package.json",(async t=>{const n=await s.readFile("./package.json","utf-8"),o=JSON.parse(n);await t.test('includes "postcss-plugin" keyword',(()=>{e.ok(Array.isArray(o.keywords)&&o.keywords?.includes("postcss-plugin"),new PackageDescriptionError('Missing "postcss-plugin" keyword in package.json',"keywords"))})),await t.test('name starts with "postcss-"',{skip:c?.skipPackageNameCheck},(()=>{let s="string"==typeof o.name?o.name:"";if(s.startsWith("@")){const e=s.split("/");s=e.slice(1).join("/")}e.ok(s.startsWith("postcss-"),new PackageDescriptionError(`package name "${s}" does not start with "postcss-"`,"name"))})),await t.test("`postcss` is a peer dependency and not a direct dependency",{skip:"postcssTapeSelfTest"in a},(()=>{e.ok(Object.keys(Object(o.peerDependencies)).includes("postcss"),new PackageDescriptionError('"postcss" must be listed in "peerDependencies"',"peerDependencies")),e.ok(!Object.keys(Object(o.dependencies)).includes("postcss"),new PackageDescriptionError('"postcss" must not be listed in "dependencies"',"dependencies"))}))}));const l=a().postcssPlugin;await i(l,(async i=>{for(const c in p)await i.test(c,(async i=>{const l=p[c];l.before&&await l.before();const u=n.join(".","test",...c.split(":")[0].split(n.posix.sep)),d=n.join(".","test",...c.replace(/:/g,".").split(n.posix.sep)),g="css";let w=`${u}.${g}`,m=`${d}.expect.${g}`,f=`${d}.result.${g}`;l.source&&(w=n.join(".","test",l.source)),l.expect&&(m=n.join(".","test",l.expect)),l.result&&(f=n.join(".","test",l.result));const k=l.plugins??[a(l.options)],h=await fileContentsOrEmptyString(w),y=await fileContentsOrEmptyString(m);let E;try{E=await o(k).process(h,{from:w,to:f,map:{inline:!1,annotation:!1}})}catch(e){if(!(e instanceof Error))throw e;if(reduceInformationInCssSyntaxError(e),l.exception&&l.exception.test(e.message))return;throw e}e.ok(!l.exception,new OutcomeError(`expected an exception matching "${l.exception}"`,w));const x=E.css.toString();{const e=[s.writeFile(f,x,"utf8")];process.env.REWRITE_EXPECTS&&e.push(s.writeFile(m,x,"utf8")),await Promise.all(e)}y||e.ok(t.existsSync(m),new OutcomeError(`Missing expect file: "${m}"`,w)),await i.test("has expected output",(()=>{e.deepEqual(x,y),e.deepEqual(E.warnings().length,l.warnings??0,`Unexpected number warnings:\n${E.warnings().toString()}`)})),await i.test("sourcemaps",(()=>{e.ok(!E.map.toJSON().sources.includes(""),'Sourcemap is broken. This is most likely a newly created PostCSS AST Node without a value for "source". See: https://github.com/postcss/postcss/blob/main/docs/guidelines/plugin.md#24-set-nodesource-for-new-nodes')})),l.after&&await l.after(),await i.test("output is parsable with PostCSS",(async()=>{const s=await fileContentsOrEmptyString(f),t=await o([noopPlugin()]).process(s,{from:f,to:f,map:{inline:!1,annotation:!1}});e.deepEqual(t.warnings(),[],"Unexpected warnings on second pass")})),await i.test("The oldest and current PostCSS version produce the same result",{skip:o([noopPlugin()]).version===r([noopPlugin()]).version},(async()=>{const s=await r(k).process(h,{from:w,to:f,map:{inline:!1,annotation:!1}});e.deepEqual(s.css.toString(),x)}))}))}))}},exports.ruleClonerPlugin=p; /* node:coverage enable */ diff --git a/packages/postcss-tape/dist/index.mjs b/packages/postcss-tape/dist/index.mjs index 06ca07539..b046d0df5 100644 --- a/packages/postcss-tape/dist/index.mjs +++ b/packages/postcss-tape/dist/index.mjs @@ -1,3 +1,3 @@ /* node:coverage disable */ -import e from"node:assert/strict";import s from"node:fs/promises";import t from"node:fs";import o from"node:path";import n from"postcss";import r from"postcss-8.4";import i from"node:test";import a from"node:url";const noopPlugin=()=>({postcssPlugin:"noop-plugin",Once(){}});async function fileContentsOrEmptyString(e){try{return await s.readFile(e,"utf8")}catch(e){return""}}function reduceInformationInCssSyntaxError(e){process.env.DEBUG||(delete e.source,e.input&&delete e.input.source,delete e.postcssNode)}function postcssTape(a,c){c=c??{},i("`postcss` flag is set on exported plugin creator",(()=>{e.equal(a.postcss,!0)})),i("exported plugin creator is a function",(()=>{e.equal(typeof a,"function")})),i("`postcssPlugin` is set on a plugin instance",(()=>{const s=a();e.ok(s.postcssPlugin),e.equal(typeof s.postcssPlugin,"string")})),i("package.json",(async t=>{const o=await s.readFile("./package.json","utf-8"),n=JSON.parse(o);await t.test('includes "postcss-plugin" keyword',(()=>{e.ok(n.keywords?.includes("postcss-plugin"),new PackageDescriptionError('Missing "postcss-plugin" keyword in package.json',"keywords"))})),await t.test('name starts with "postcss-"',{skip:c?.skipPackageNameCheck},(()=>{let s=n.name;if(s.startsWith("@")){s=n.name.split("/").slice(1).join("/")}e.ok(s.startsWith("postcss-"),new PackageDescriptionError(`package name "${s}" does not start with "postcss-"`,"name"))})),await t.test("`postcss` is a peer dependency and not a direct dependency",{skip:"postcssTapeSelfTest"in a},(()=>{e.ok(Object.keys(Object(n.peerDependencies)).includes("postcss"),new PackageDescriptionError('"postcss" must be listed in "peerDependencies"',"peerDependencies")),e.ok(!Object.keys(Object(n.dependencies)).includes("postcss"),new PackageDescriptionError('"postcss" must not be listed in "dependencies"',"dependencies"))}))}));const p=a().postcssPlugin;return async c=>{await i(p,(async i=>{for(const p in c)await i.test(p,(async i=>{const l=c[p];l.before&&await l.before();const u=o.join(".","test",...p.split(":")[0].split(o.posix.sep)),d=o.join(".","test",...p.replace(/:/g,".").split(o.posix.sep)),m="css";let g=`${u}.${m}`,f=`${d}.expect.${m}`,w=`${d}.result.${m}`;l.source&&(g=o.join(".","test",l.source)),l.expect&&(f=o.join(".","test",l.expect)),l.result&&(w=o.join(".","test",l.result));const k=l.plugins??[a(l.options)],h=await fileContentsOrEmptyString(g),y=await fileContentsOrEmptyString(f);let E;try{E=await n(k).process(h,{from:g,to:w,map:{inline:!1,annotation:!1}})}catch(e){if(reduceInformationInCssSyntaxError(e),l.exception&&l.exception.test(e.message))return;throw e}e.ok(!l.exception,new OutcomeError(`expected an exception matching "${l.exception}"`,g));const x=E.css.toString();{const e=[s.writeFile(w,x,"utf8")];process.env.REWRITE_EXPECTS&&e.push(s.writeFile(f,x,"utf8")),await Promise.all(e)}y||e.ok(t.existsSync(f),new OutcomeError(`Missing expect file: "${f}"`,g)),await i.test("has expected output",(()=>{e.deepEqual(x,y),e.deepEqual(E.warnings().length,l.warnings??0,`Unexpected number warnings:\n${E.warnings()}`)})),await i.test("sourcemaps",(async()=>{e.ok(!E.map.toJSON().sources.includes(""),'Sourcemap is broken. This is most likely a newly created PostCSS AST Node without a value for "source". See: https://github.com/postcss/postcss/blob/main/docs/guidelines/plugin.md#24-set-nodesource-for-new-nodes')})),l.after&&await l.after(),await i.test("output is parsable with PostCSS",(async()=>{const s=await fileContentsOrEmptyString(w),t=await n([noopPlugin()]).process(s,{from:w,to:w,map:{inline:!1,annotation:!1}});e.deepEqual(t.warnings(),[],"Unexpected warnings on second pass")})),await i.test("The oldest and current PostCSS version produce the same result",{skip:n([noopPlugin()]).version===r([noopPlugin()]).version},(async()=>{const s=await r(k).process(h,{from:g,to:w,map:{inline:!1,annotation:!1}});e.deepEqual(s.css.toString(),x)}))}))}))}}noopPlugin.postcss=!0;const c={postcssPlugin:"declaration-cloner",Declaration(e){"to-clone"===e.prop&&e.cloneBefore({prop:"cloned"})}},p={postcssPlugin:"rule-cloner",prepare(){const e=new WeakSet;return{postcssPlugin:"rule-cloner",RuleExit(s){e.has(s)||"to-clone"===s.selector&&(e.add(s),s.cloneBefore({selector:"cloned"}))}}}},l={postcssPlugin:"at-rule-cloner",prepare(){const e=new WeakSet;return{postcssPlugin:"at-rule-cloner",AtRuleExit(s){if(!e.has(s))return"to-clone"===s.params?(e.add(s),void s.cloneBefore({params:"cloned"})):"to-clone"===s.name?(e.add(s),void s.cloneBefore({name:"cloned"})):void 0}}}};class PackageDescriptionError extends Error{constructor(e,s){super(e),this.name="PackageDescriptionError",this.stack=`${this.name}: ${this.message}\n at "${s}" (${a.pathToFileURL(o.resolve("package.json"))}:1:1)`}}class OutcomeError extends Error{constructor(e,s){super(e),this.name="OutcomeError",this.stack=`${this.name}: ${this.message}\n at ${a.pathToFileURL(o.resolve(s))}:1:1`}}export{l as atRuleClonerPlugin,c as declarationClonerPlugin,postcssTape,p as ruleClonerPlugin}; +import e from"node:assert/strict";import s from"node:fs/promises";import t from"node:fs";import o from"node:path";import n from"postcss";import r from"postcss-8.4";import i from"node:test";import a from"node:url";const noopPlugin=()=>({postcssPlugin:"noop-plugin",Once(){}});async function fileContentsOrEmptyString(e){try{return await s.readFile(e,"utf8")}catch{return""}}function reduceInformationInCssSyntaxError(e){process.env.DEBUG||(delete e.source,e.input&&delete e.input.source,delete e.postcssNode)}function postcssTape(a,c){return async p=>{c=c??{},await i("`postcss` flag is set on exported plugin creator",(()=>{e.equal(a.postcss,!0)})),await i("exported plugin creator is a function",(()=>{e.equal(typeof a,"function")})),await i("`postcssPlugin` is set on a plugin instance",(()=>{const s=a();e.ok(s.postcssPlugin),e.equal(typeof s.postcssPlugin,"string")})),await i("package.json",(async t=>{const o=await s.readFile("./package.json","utf-8"),n=JSON.parse(o);await t.test('includes "postcss-plugin" keyword',(()=>{e.ok(Array.isArray(n.keywords)&&n.keywords?.includes("postcss-plugin"),new PackageDescriptionError('Missing "postcss-plugin" keyword in package.json',"keywords"))})),await t.test('name starts with "postcss-"',{skip:c?.skipPackageNameCheck},(()=>{let s="string"==typeof n.name?n.name:"";if(s.startsWith("@")){const e=s.split("/");s=e.slice(1).join("/")}e.ok(s.startsWith("postcss-"),new PackageDescriptionError(`package name "${s}" does not start with "postcss-"`,"name"))})),await t.test("`postcss` is a peer dependency and not a direct dependency",{skip:"postcssTapeSelfTest"in a},(()=>{e.ok(Object.keys(Object(n.peerDependencies)).includes("postcss"),new PackageDescriptionError('"postcss" must be listed in "peerDependencies"',"peerDependencies")),e.ok(!Object.keys(Object(n.dependencies)).includes("postcss"),new PackageDescriptionError('"postcss" must not be listed in "dependencies"',"dependencies"))}))}));const l=a().postcssPlugin;await i(l,(async i=>{for(const c in p)await i.test(c,(async i=>{const l=p[c];l.before&&await l.before();const u=o.join(".","test",...c.split(":")[0].split(o.posix.sep)),d=o.join(".","test",...c.replace(/:/g,".").split(o.posix.sep)),m="css";let g=`${u}.${m}`,w=`${d}.expect.${m}`,f=`${d}.result.${m}`;l.source&&(g=o.join(".","test",l.source)),l.expect&&(w=o.join(".","test",l.expect)),l.result&&(f=o.join(".","test",l.result));const k=l.plugins??[a(l.options)],h=await fileContentsOrEmptyString(g),y=await fileContentsOrEmptyString(w);let E;try{E=await n(k).process(h,{from:g,to:f,map:{inline:!1,annotation:!1}})}catch(e){if(!(e instanceof Error))throw e;if(reduceInformationInCssSyntaxError(e),l.exception&&l.exception.test(e.message))return;throw e}e.ok(!l.exception,new OutcomeError(`expected an exception matching "${l.exception}"`,g));const x=E.css.toString();{const e=[s.writeFile(f,x,"utf8")];process.env.REWRITE_EXPECTS&&e.push(s.writeFile(w,x,"utf8")),await Promise.all(e)}y||e.ok(t.existsSync(w),new OutcomeError(`Missing expect file: "${w}"`,g)),await i.test("has expected output",(()=>{e.deepEqual(x,y),e.deepEqual(E.warnings().length,l.warnings??0,`Unexpected number warnings:\n${E.warnings().toString()}`)})),await i.test("sourcemaps",(()=>{e.ok(!E.map.toJSON().sources.includes(""),'Sourcemap is broken. This is most likely a newly created PostCSS AST Node without a value for "source". See: https://github.com/postcss/postcss/blob/main/docs/guidelines/plugin.md#24-set-nodesource-for-new-nodes')})),l.after&&await l.after(),await i.test("output is parsable with PostCSS",(async()=>{const s=await fileContentsOrEmptyString(f),t=await n([noopPlugin()]).process(s,{from:f,to:f,map:{inline:!1,annotation:!1}});e.deepEqual(t.warnings(),[],"Unexpected warnings on second pass")})),await i.test("The oldest and current PostCSS version produce the same result",{skip:n([noopPlugin()]).version===r([noopPlugin()]).version},(async()=>{const s=await r(k).process(h,{from:g,to:f,map:{inline:!1,annotation:!1}});e.deepEqual(s.css.toString(),x)}))}))}))}}noopPlugin.postcss=!0;const c={postcssPlugin:"declaration-cloner",Declaration(e){"to-clone"===e.prop&&e.cloneBefore({prop:"cloned"})}},p={postcssPlugin:"rule-cloner",prepare(){const e=new WeakSet;return{postcssPlugin:"rule-cloner",RuleExit(s){e.has(s)||"to-clone"===s.selector&&(e.add(s),s.cloneBefore({selector:"cloned"}))}}}},l={postcssPlugin:"at-rule-cloner",prepare(){const e=new WeakSet;return{postcssPlugin:"at-rule-cloner",AtRuleExit(s){if(!e.has(s))return"to-clone"===s.params?(e.add(s),void s.cloneBefore({params:"cloned"})):"to-clone"===s.name?(e.add(s),void s.cloneBefore({name:"cloned"})):void 0}}}};class PackageDescriptionError extends Error{constructor(e,s){super(e),this.name="PackageDescriptionError",this.stack=`${this.name}: ${this.message}\n at "${s}" (${a.pathToFileURL(o.resolve("package.json")).href}:1:1)`}}class OutcomeError extends Error{constructor(e,s){super(e),this.name="OutcomeError",this.stack=`${this.name}: ${this.message}\n at ${a.pathToFileURL(o.resolve(s)).href}:1:1`}}export{l as atRuleClonerPlugin,c as declarationClonerPlugin,postcssTape,p as ruleClonerPlugin}; /* node:coverage enable */ diff --git a/packages/postcss-tape/src/file-contents-or-empty-string.ts b/packages/postcss-tape/src/file-contents-or-empty-string.ts index 253681e97..e43dd3885 100644 --- a/packages/postcss-tape/src/file-contents-or-empty-string.ts +++ b/packages/postcss-tape/src/file-contents-or-empty-string.ts @@ -3,7 +3,7 @@ import fs from 'node:fs/promises'; export async function fileContentsOrEmptyString(path: string): Promise { try { return await fs.readFile(path, 'utf8'); - } catch (error) { + } catch { return ''; } } diff --git a/packages/postcss-tape/src/index.ts b/packages/postcss-tape/src/index.ts index a12f9fa4f..a2fbe33ee 100644 --- a/packages/postcss-tape/src/index.ts +++ b/packages/postcss-tape/src/index.ts @@ -72,76 +72,76 @@ export type Options = { * Create a test suite for a PostCSS plugin. */ export function postcssTape(pluginCreator: PluginCreator, runOptions?: Options): (options: Record) => Promise { - runOptions = runOptions ?? {}; - - // Plugin conforms to https://github.com/postcss/postcss/blob/main/docs/guidelines/plugin.md - test('`postcss` flag is set on exported plugin creator', () => { - assert.equal(pluginCreator.postcss, true); - }); + // Test cases + return async (options: Record) => { + runOptions = runOptions ?? {}; - test('exported plugin creator is a function', () => { - assert.equal(typeof pluginCreator, 'function'); - }); + // Plugin conforms to https://github.com/postcss/postcss/blob/main/docs/guidelines/plugin.md + await test('`postcss` flag is set on exported plugin creator', () => { + assert.equal(pluginCreator.postcss, true); + }); - test('`postcssPlugin` is set on a plugin instance', () => { - // https://github.com/postcss/postcss/blob/main/docs/guidelines/plugin.md#15-set-pluginpostcssplugin-with-plugin-name - // Set plugin.postcssPlugin with plugin name + await test('exported plugin creator is a function', () => { + assert.equal(typeof pluginCreator, 'function'); + }); - const plugin = pluginCreator() as Plugin; + await test('`postcssPlugin` is set on a plugin instance', () => { + // https://github.com/postcss/postcss/blob/main/docs/guidelines/plugin.md#15-set-pluginpostcssplugin-with-plugin-name + // Set plugin.postcssPlugin with plugin name - assert.ok(plugin.postcssPlugin); - assert.equal(typeof plugin.postcssPlugin, 'string'); - }); + const plugin = pluginCreator() as Plugin; - test('package.json', async (t) => { - const packageData = await fs.readFile('./package.json', 'utf-8'); - const packageInfo = JSON.parse(packageData); + assert.ok(plugin.postcssPlugin); + assert.equal(typeof plugin.postcssPlugin, 'string'); + }); - await t.test('includes "postcss-plugin" keyword', () => { - // https://github.com/postcss/postcss/blob/main/docs/guidelines/plugin.md#54-include-postcss-plugin-keyword-in-packagejson - // Include postcss-plugin keyword in package.json + await test('package.json', async (t) => { + const packageData = await fs.readFile('./package.json', 'utf-8'); + const packageInfo: Record = JSON.parse(packageData) as Record; - assert.ok( - packageInfo.keywords?.includes('postcss-plugin'), - new PackageDescriptionError('Missing "postcss-plugin" keyword in package.json', 'keywords'), - ); - }); + await t.test('includes "postcss-plugin" keyword', () => { + // https://github.com/postcss/postcss/blob/main/docs/guidelines/plugin.md#54-include-postcss-plugin-keyword-in-packagejson + // Include postcss-plugin keyword in package.json - await t.test('name starts with "postcss-"', { skip: runOptions?.skipPackageNameCheck }, () => { - // https://github.com/postcss/postcss/blob/main/docs/guidelines/plugin.md#11-clear-name-with-postcss--prefix - // Clear name with postcss- prefix + assert.ok( + Array.isArray(packageInfo.keywords) && packageInfo.keywords?.includes('postcss-plugin'), + new PackageDescriptionError('Missing "postcss-plugin" keyword in package.json', 'keywords'), + ); + }); - let packageName = packageInfo.name; - if (packageName.startsWith('@')) { - const parts = packageInfo.name.split('/'); - packageName = parts.slice(1).join('/'); - } + await t.test('name starts with "postcss-"', { skip: runOptions?.skipPackageNameCheck }, () => { + // https://github.com/postcss/postcss/blob/main/docs/guidelines/plugin.md#11-clear-name-with-postcss--prefix + // Clear name with postcss- prefix - assert.ok( - packageName.startsWith('postcss-'), - new PackageDescriptionError(`package name "${packageName}" does not start with "postcss-"`, 'name'), - ); - }); + let packageName = typeof packageInfo.name === 'string' ? packageInfo.name : ''; + if (packageName.startsWith('@')) { + const parts = packageName.split('/'); + packageName = parts.slice(1).join('/'); + } - await t.test('`postcss` is a peer dependency and not a direct dependency', { skip: ('postcssTapeSelfTest' in pluginCreator) }, () => { - // https://github.com/postcss/postcss/blob/main/docs/guidelines/plugin.md#14-keep-postcss-to-peerdependencies - // Keep postcss to peerDependencies - - assert.ok( - Object.keys(Object(packageInfo.peerDependencies)).includes('postcss'), - new PackageDescriptionError('"postcss" must be listed in "peerDependencies"', 'peerDependencies'), - ); - assert.ok( - !Object.keys(Object(packageInfo.dependencies)).includes('postcss'), - new PackageDescriptionError('"postcss" must not be listed in "dependencies"', 'dependencies'), - ); + assert.ok( + packageName.startsWith('postcss-'), + new PackageDescriptionError(`package name "${packageName}" does not start with "postcss-"`, 'name'), + ); + }); + + await t.test('`postcss` is a peer dependency and not a direct dependency', { skip: ('postcssTapeSelfTest' in pluginCreator) }, () => { + // https://github.com/postcss/postcss/blob/main/docs/guidelines/plugin.md#14-keep-postcss-to-peerdependencies + // Keep postcss to peerDependencies + + assert.ok( + Object.keys(Object(packageInfo.peerDependencies) as Record).includes('postcss'), + new PackageDescriptionError('"postcss" must be listed in "peerDependencies"', 'peerDependencies'), + ); + assert.ok( + !Object.keys(Object(packageInfo.dependencies) as Record).includes('postcss'), + new PackageDescriptionError('"postcss" must not be listed in "dependencies"', 'dependencies'), + ); + }); }); - }); - const pluginName = (pluginCreator() as Plugin).postcssPlugin; + const pluginName = (pluginCreator() as Plugin).postcssPlugin; - // Test cases - return async (options: Record) => { await test(pluginName, async (t1) => { for (const testCaseLabel in options) { await t1.test(testCaseLabel, async (t2) => { @@ -187,6 +187,10 @@ export function postcssTape(pluginCreator: PluginCreator, runOptions?: }, }); } catch (err) { + if (!(err instanceof Error)) { + throw err; + } + reduceInformationInCssSyntaxError(err); if (testCaseOptions.exception && testCaseOptions.exception.test(err.message)) { // expected an exception and got one. @@ -228,11 +232,11 @@ export function postcssTape(pluginCreator: PluginCreator, runOptions?: assert.deepEqual(resultString, expected); // Assert that warnings have the expected amount. - assert.deepEqual(result.warnings().length, testCaseOptions.warnings ?? 0, `Unexpected number warnings:\n${result.warnings()}`); + assert.deepEqual(result.warnings().length, testCaseOptions.warnings ?? 0, `Unexpected number warnings:\n${result.warnings().toString()}`); }); // Assert result sourcemaps with recent PostCSS. - await t2.test('sourcemaps', async () => { + await t2.test('sourcemaps', () => { assert.ok(!result.map.toJSON().sources.includes(''), 'Sourcemap is broken. This is most likely a newly created PostCSS AST Node without a value for "source". See: https://github.com/postcss/postcss/blob/main/docs/guidelines/plugin.md#24-set-nodesource-for-new-nodes'); }); @@ -352,7 +356,7 @@ class PackageDescriptionError extends Error { super(message); this.name = 'PackageDescriptionError'; - this.stack = `${this.name}: ${this.message}\n at "${key}" (${url.pathToFileURL(path.resolve('package.json'))}:1:1)`; + this.stack = `${this.name}: ${this.message}\n at "${key}" (${url.pathToFileURL(path.resolve('package.json')).href}:1:1)`; } } @@ -361,6 +365,6 @@ class OutcomeError extends Error { super(message); this.name = 'OutcomeError'; - this.stack = `${this.name}: ${this.message}\n at ${url.pathToFileURL(path.resolve(sourceFile))}:1:1`; + this.stack = `${this.name}: ${this.message}\n at ${url.pathToFileURL(path.resolve(sourceFile)).href}:1:1`; } } diff --git a/packages/postcss-tape/src/reduce-css-syntax-error.ts b/packages/postcss-tape/src/reduce-css-syntax-error.ts index ca7f0b6fc..57dd49382 100644 --- a/packages/postcss-tape/src/reduce-css-syntax-error.ts +++ b/packages/postcss-tape/src/reduce-css-syntax-error.ts @@ -10,6 +10,7 @@ export function reduceInformationInCssSyntaxError(err: CssSyntaxError | TypeErro // @ts-expect-error "input" is also added on "TypeError" if (err.input) { // @ts-expect-error "input" is also added on "TypeError" + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access delete err.input.source; } diff --git a/packages/selector-resolve-nested/dist/index.cjs b/packages/selector-resolve-nested/dist/index.cjs index 754d81ac4..a7cc20c2d 100644 --- a/packages/selector-resolve-nested/dist/index.cjs +++ b/packages/selector-resolve-nested/dist/index.cjs @@ -1 +1 @@ -"use strict";var e=require("postcss-selector-parser");function sourceFrom(e){return{sourceIndex:e.sourceIndex??0,source:e.source}}function sortCompoundSelectorsInsideComplexSelector(o){const t=[];let r=[];o.each((o=>{if("combinator"===o.type)return t.push(r,[o]),void(r=[]);if(e.isPseudoElement(o))return t.push(r),void(r=[o]);if("universal"===o.type&&r.find((e=>"universal"===e.type)))o.remove();else{if("tag"===o.type&&r.find((e=>"tag"===e.type))){o.remove();const t=e.selector({value:"",...sourceFrom(o)});t.append(o);const n=e.pseudo({value:":is",...sourceFrom(o)});return n.append(t),void r.push(n)}r.push(o)}})),t.push(r);const n=[];for(let e=0;eselectorTypeOrder(e)-selectorTypeOrder(o))),n.push(...o)}o.removeAll();for(let e=n.length-1;e>=0;e--)n[e].remove(),o.prepend(n[e])}function selectorTypeOrder(t){return e.isPseudoElement(t)?o.pseudoElement:o[t.type]}const o={universal:0,tag:1,pseudoElement:2,nesting:3,id:4,class:5,attribute:6,pseudo:7,comment:8};function prepareParentSelectors(o,t=!1){if(t||!isCompoundSelector(o.nodes)){const t=e.pseudo({value:":is",...sourceFrom(o)});return o.nodes.forEach((e=>{t.append(e.clone())})),[t]}return o.nodes[0].nodes.map((e=>e.clone()))}function isCompoundSelector(o){return 1===o.length&&!o[0].nodes.some((o=>"combinator"===o.type||e.isPseudoElement(o)))}function combinationsWithSizeN(e,o){if(o<2)throw new Error("n must be greater than 1");if(e.length<2)throw new Error("s must be greater than 1");if(Math.pow(e.length,o)>1e4)throw new Error("Too many combinations when trying to resolve a nested selector with lists, reduce the complexity of your selectors");const t=[];for(let e=0;e=0;s--){let o=t[s];if(o>=e.length){if(o=0,t[s]=0,0===s)return r;t[s-1]+=1}n[s]=e[o].clone()}r.push(n),t[t.length-1]++}}exports.flattenNestedSelector=function flattenNestedSelector(o,t){const r=[];for(let n=0;n{o=!0,l++})),o?"combinator"===s.nodes[0]?.type&&(s.prepend(e.nesting({...sourceFrom(s)})),l++):(s.prepend(e.combinator({value:" ",...sourceFrom(s)})),s.prepend(e.nesting({...sourceFrom(s)})),l++)}let p=[];if(l>1&&t.nodes.length>1)p=combinationsWithSizeN(t.nodes,l),c=p.length;else{c=t.nodes.length;for(let e=0;e{const r=p[e][o];o++,t.replaceWith(...r.nodes)})),r.push(t)}}const n=e.root({value:"",...sourceFrom(o)});return r.forEach((e=>{n.append(e)})),n},exports.resolveNestedSelector=function resolveNestedSelector(o,t){const r=[];for(let n=0;n(o=!0,!1))),o?"combinator"===s.nodes[0]?.type&&s.prepend(e.nesting({...sourceFrom(s)})):(s.prepend(e.combinator({value:" ",...sourceFrom(s)})),s.prepend(e.nesting({...sourceFrom(s)})))}{const e=new Set;s.walkNesting((o=>{const r=o.parent;e.add(r),"pseudo"===r.parent?.type&&":has"===r.parent.value?.toLowerCase()?o.replaceWith(...prepareParentSelectors(t,!0)):o.replaceWith(...prepareParentSelectors(t))}));for(const o of e)sortCompoundSelectorsInsideComplexSelector(o)}s.walk((e=>{"combinator"===e.type&&""!==e.value.trim()?(e.rawSpaceAfter=" ",e.rawSpaceBefore=" "):(e.rawSpaceAfter="",e.rawSpaceBefore="")})),r.push(s)}const n=e.root({value:"",...sourceFrom(o)});return r.forEach((e=>{n.append(e)})),n}; +"use strict";var e=require("postcss-selector-parser");function sourceFrom(e){return{sourceIndex:e.sourceIndex??0,source:e.source}}function sortCompoundSelectorsInsideComplexSelector(o){const t=[];let r=[];o.each((o=>{if("combinator"===o.type)return t.push(r,[o]),void(r=[]);if(e.isPseudoElement(o))return t.push(r),void(r=[o]);if("universal"===o.type&&r.find((e=>"universal"===e.type)))o.remove();else{if("tag"===o.type&&r.find((e=>"tag"===e.type))){o.remove();const t=e.selector({value:"",...sourceFrom(o)});t.append(o);const n=e.pseudo({value:":is",...sourceFrom(o)});return n.append(t),void r.push(n)}r.push(o)}})),t.push(r);const n=[];for(let e=0;eselectorTypeOrder(e)-selectorTypeOrder(o))),n.push(...o)}o.removeAll();for(let e=n.length-1;e>=0;e--)n[e].remove(),o.prepend(n[e])}function selectorTypeOrder(t){return e.isPseudoElement(t)?o.pseudoElement:o[t.type]}const o={universal:0,tag:1,pseudoElement:2,nesting:3,id:4,class:5,attribute:6,pseudo:7,comment:8};function prepareParentSelectors(o,t=!1){if(t||!isCompoundSelector(o.nodes)){const t=e.pseudo({value:":is",...sourceFrom(o)});return o.nodes.forEach((e=>{t.append(e.clone())})),[t]}return o.nodes[0].nodes.map((e=>e.clone()))}function isCompoundSelector(o){return 1===o.length&&!o[0].nodes.some((o=>"combinator"===o.type||e.isPseudoElement(o)))}function combinationsWithSizeN(e,o){if(o<2)throw new Error("n must be greater than 1");if(e.length<2)throw new Error("s must be greater than 1");if(Math.pow(e.length,o)>1e4)throw new Error("Too many combinations when trying to resolve a nested selector with lists, reduce the complexity of your selectors");const t=[];for(let e=0;e=0;s--){let o=t[s];if(o>=e.length){if(o=0,t[s]=0,0===s)return r;t[s-1]+=1}n[s]=e[o].clone()}r.push(n),t[t.length-1]++}}exports.flattenNestedSelector=function flattenNestedSelector(o,t){const r=[];for(let n=0;n{o=!0,l++})),o?"combinator"===s.nodes[0]?.type&&(s.prepend(e.nesting({...sourceFrom(s)})),l++):(s.prepend(e.combinator({value:" ",...sourceFrom(s)})),s.prepend(e.nesting({...sourceFrom(s)})),l++)}let p=[];if(l>1&&t.nodes.length>1)p=combinationsWithSizeN(t.nodes,l),c=p.length;else{c=t.nodes.length;for(let e=0;e{const r=p[e][o];o++,t.replaceWith(...r.nodes)})),r.push(t)}}const n=e.root({value:"",...sourceFrom(o)});return r.forEach((e=>{n.append(e)})),n},exports.resolveNestedSelector=function resolveNestedSelector(o,t){const r=[];for(let n=0;n(o=!0,!1))),o?"combinator"===s.nodes[0]?.type&&s.prepend(e.nesting({...sourceFrom(s)})):(s.prepend(e.combinator({value:" ",...sourceFrom(s)})),s.prepend(e.nesting({...sourceFrom(s)})))}{const e=new Set;s.walkNesting((o=>{const r=o.parent;r&&(e.add(r),"pseudo"===r.parent?.type&&":has"===r.parent.value?.toLowerCase()?o.replaceWith(...prepareParentSelectors(t,!0)):o.replaceWith(...prepareParentSelectors(t)))}));for(const o of e)sortCompoundSelectorsInsideComplexSelector(o)}s.walk((e=>{"combinator"===e.type&&""!==e.value.trim()?(e.rawSpaceAfter=" ",e.rawSpaceBefore=" "):(e.rawSpaceAfter="",e.rawSpaceBefore="")})),r.push(s)}const n=e.root({value:"",...sourceFrom(o)});return r.forEach((e=>{n.append(e)})),n}; diff --git a/packages/selector-resolve-nested/dist/index.mjs b/packages/selector-resolve-nested/dist/index.mjs index ec2a460d5..9f4ae5d5d 100644 --- a/packages/selector-resolve-nested/dist/index.mjs +++ b/packages/selector-resolve-nested/dist/index.mjs @@ -1 +1 @@ -import e from"postcss-selector-parser";function sourceFrom(e){return{sourceIndex:e.sourceIndex??0,source:e.source}}function sortCompoundSelectorsInsideComplexSelector(o){const t=[];let r=[];o.each((o=>{if("combinator"===o.type)return t.push(r,[o]),void(r=[]);if(e.isPseudoElement(o))return t.push(r),void(r=[o]);if("universal"===o.type&&r.find((e=>"universal"===e.type)))o.remove();else{if("tag"===o.type&&r.find((e=>"tag"===e.type))){o.remove();const t=e.selector({value:"",...sourceFrom(o)});t.append(o);const n=e.pseudo({value:":is",...sourceFrom(o)});return n.append(t),void r.push(n)}r.push(o)}})),t.push(r);const n=[];for(let e=0;eselectorTypeOrder(e)-selectorTypeOrder(o))),n.push(...o)}o.removeAll();for(let e=n.length-1;e>=0;e--)n[e].remove(),o.prepend(n[e])}function selectorTypeOrder(t){return e.isPseudoElement(t)?o.pseudoElement:o[t.type]}const o={universal:0,tag:1,pseudoElement:2,nesting:3,id:4,class:5,attribute:6,pseudo:7,comment:8};function resolveNestedSelector(o,t){const r=[];for(let n=0;n(o=!0,!1))),o?"combinator"===s.nodes[0]?.type&&s.prepend(e.nesting({...sourceFrom(s)})):(s.prepend(e.combinator({value:" ",...sourceFrom(s)})),s.prepend(e.nesting({...sourceFrom(s)})))}{const e=new Set;s.walkNesting((o=>{const r=o.parent;e.add(r),"pseudo"===r.parent?.type&&":has"===r.parent.value?.toLowerCase()?o.replaceWith(...prepareParentSelectors(t,!0)):o.replaceWith(...prepareParentSelectors(t))}));for(const o of e)sortCompoundSelectorsInsideComplexSelector(o)}s.walk((e=>{"combinator"===e.type&&""!==e.value.trim()?(e.rawSpaceAfter=" ",e.rawSpaceBefore=" "):(e.rawSpaceAfter="",e.rawSpaceBefore="")})),r.push(s)}const n=e.root({value:"",...sourceFrom(o)});return r.forEach((e=>{n.append(e)})),n}function prepareParentSelectors(o,t=!1){if(t||!isCompoundSelector(o.nodes)){const t=e.pseudo({value:":is",...sourceFrom(o)});return o.nodes.forEach((e=>{t.append(e.clone())})),[t]}return o.nodes[0].nodes.map((e=>e.clone()))}function isCompoundSelector(o){return 1===o.length&&!o[0].nodes.some((o=>"combinator"===o.type||e.isPseudoElement(o)))}function combinationsWithSizeN(e,o){if(o<2)throw new Error("n must be greater than 1");if(e.length<2)throw new Error("s must be greater than 1");if(Math.pow(e.length,o)>1e4)throw new Error("Too many combinations when trying to resolve a nested selector with lists, reduce the complexity of your selectors");const t=[];for(let e=0;e=0;s--){let o=t[s];if(o>=e.length){if(o=0,t[s]=0,0===s)return r;t[s-1]+=1}n[s]=e[o].clone()}r.push(n),t[t.length-1]++}}function flattenNestedSelector(o,t){const r=[];for(let n=0;n{o=!0,l++})),o?"combinator"===s.nodes[0]?.type&&(s.prepend(e.nesting({...sourceFrom(s)})),l++):(s.prepend(e.combinator({value:" ",...sourceFrom(s)})),s.prepend(e.nesting({...sourceFrom(s)})),l++)}let p=[];if(l>1&&t.nodes.length>1)p=combinationsWithSizeN(t.nodes,l),c=p.length;else{c=t.nodes.length;for(let e=0;e{const r=p[e][o];o++,t.replaceWith(...r.nodes)})),r.push(t)}}const n=e.root({value:"",...sourceFrom(o)});return r.forEach((e=>{n.append(e)})),n}export{flattenNestedSelector,resolveNestedSelector}; +import e from"postcss-selector-parser";function sourceFrom(e){return{sourceIndex:e.sourceIndex??0,source:e.source}}function sortCompoundSelectorsInsideComplexSelector(o){const t=[];let r=[];o.each((o=>{if("combinator"===o.type)return t.push(r,[o]),void(r=[]);if(e.isPseudoElement(o))return t.push(r),void(r=[o]);if("universal"===o.type&&r.find((e=>"universal"===e.type)))o.remove();else{if("tag"===o.type&&r.find((e=>"tag"===e.type))){o.remove();const t=e.selector({value:"",...sourceFrom(o)});t.append(o);const n=e.pseudo({value:":is",...sourceFrom(o)});return n.append(t),void r.push(n)}r.push(o)}})),t.push(r);const n=[];for(let e=0;eselectorTypeOrder(e)-selectorTypeOrder(o))),n.push(...o)}o.removeAll();for(let e=n.length-1;e>=0;e--)n[e].remove(),o.prepend(n[e])}function selectorTypeOrder(t){return e.isPseudoElement(t)?o.pseudoElement:o[t.type]}const o={universal:0,tag:1,pseudoElement:2,nesting:3,id:4,class:5,attribute:6,pseudo:7,comment:8};function resolveNestedSelector(o,t){const r=[];for(let n=0;n(o=!0,!1))),o?"combinator"===s.nodes[0]?.type&&s.prepend(e.nesting({...sourceFrom(s)})):(s.prepend(e.combinator({value:" ",...sourceFrom(s)})),s.prepend(e.nesting({...sourceFrom(s)})))}{const e=new Set;s.walkNesting((o=>{const r=o.parent;r&&(e.add(r),"pseudo"===r.parent?.type&&":has"===r.parent.value?.toLowerCase()?o.replaceWith(...prepareParentSelectors(t,!0)):o.replaceWith(...prepareParentSelectors(t)))}));for(const o of e)sortCompoundSelectorsInsideComplexSelector(o)}s.walk((e=>{"combinator"===e.type&&""!==e.value.trim()?(e.rawSpaceAfter=" ",e.rawSpaceBefore=" "):(e.rawSpaceAfter="",e.rawSpaceBefore="")})),r.push(s)}const n=e.root({value:"",...sourceFrom(o)});return r.forEach((e=>{n.append(e)})),n}function prepareParentSelectors(o,t=!1){if(t||!isCompoundSelector(o.nodes)){const t=e.pseudo({value:":is",...sourceFrom(o)});return o.nodes.forEach((e=>{t.append(e.clone())})),[t]}return o.nodes[0].nodes.map((e=>e.clone()))}function isCompoundSelector(o){return 1===o.length&&!o[0].nodes.some((o=>"combinator"===o.type||e.isPseudoElement(o)))}function combinationsWithSizeN(e,o){if(o<2)throw new Error("n must be greater than 1");if(e.length<2)throw new Error("s must be greater than 1");if(Math.pow(e.length,o)>1e4)throw new Error("Too many combinations when trying to resolve a nested selector with lists, reduce the complexity of your selectors");const t=[];for(let e=0;e=0;s--){let o=t[s];if(o>=e.length){if(o=0,t[s]=0,0===s)return r;t[s-1]+=1}n[s]=e[o].clone()}r.push(n),t[t.length-1]++}}function flattenNestedSelector(o,t){const r=[];for(let n=0;n{o=!0,l++})),o?"combinator"===s.nodes[0]?.type&&(s.prepend(e.nesting({...sourceFrom(s)})),l++):(s.prepend(e.combinator({value:" ",...sourceFrom(s)})),s.prepend(e.nesting({...sourceFrom(s)})),l++)}let p=[];if(l>1&&t.nodes.length>1)p=combinationsWithSizeN(t.nodes,l),c=p.length;else{c=t.nodes.length;for(let e=0;e{const r=p[e][o];o++,t.replaceWith(...r.nodes)})),r.push(t)}}const n=e.root({value:"",...sourceFrom(o)});return r.forEach((e=>{n.append(e)})),n}export{flattenNestedSelector,resolveNestedSelector}; diff --git a/packages/selector-resolve-nested/src/combinations.ts b/packages/selector-resolve-nested/src/combinations.ts index b9412cdbb..f13462cb9 100644 --- a/packages/selector-resolve-nested/src/combinations.ts +++ b/packages/selector-resolve-nested/src/combinations.ts @@ -49,7 +49,6 @@ export function combinationsWithSizeN(set: Array, n: number): Array> = []; - // eslint-disable-next-line no-constant-condition while (true) { const ss: Array = []; for (let i = n - 1; i >= 0; i--) { diff --git a/packages/selector-resolve-nested/src/flatten-nested-selector.ts b/packages/selector-resolve-nested/src/flatten-nested-selector.ts index 02ecdc487..314ae474c 100644 --- a/packages/selector-resolve-nested/src/flatten-nested-selector.ts +++ b/packages/selector-resolve-nested/src/flatten-nested-selector.ts @@ -31,9 +31,11 @@ export function flattenNestedSelector(selector: Root, parentSelector: Root): Roo if (!isNestContaining) { selectorAST.prepend(parser.combinator({ value: ' ', ...sourceFrom(selectorAST) })); + // eslint-disable-next-line @typescript-eslint/no-unsafe-argument selectorAST.prepend(parser.nesting({ ...sourceFrom(selectorAST) })); nestingCounter++; } else if (selectorAST.nodes[0]?.type === 'combinator') { + // eslint-disable-next-line @typescript-eslint/no-unsafe-argument selectorAST.prepend(parser.nesting({ ...sourceFrom(selectorAST) })); nestingCounter++; } diff --git a/packages/selector-resolve-nested/src/resolve-nested-selector.ts b/packages/selector-resolve-nested/src/resolve-nested-selector.ts index 189210e96..922f673ed 100644 --- a/packages/selector-resolve-nested/src/resolve-nested-selector.ts +++ b/packages/selector-resolve-nested/src/resolve-nested-selector.ts @@ -25,8 +25,10 @@ export function resolveNestedSelector(selector: Root, parentSelector: Root): Roo if (!isNestContaining) { selectorAST.prepend(parser.combinator({ value: ' ', ...sourceFrom(selectorAST) })); + // eslint-disable-next-line @typescript-eslint/no-unsafe-argument selectorAST.prepend(parser.nesting({ ...sourceFrom(selectorAST) })); } else if (selectorAST.nodes[0]?.type === 'combinator') { + // eslint-disable-next-line @typescript-eslint/no-unsafe-argument selectorAST.prepend(parser.nesting({ ...sourceFrom(selectorAST) })); } } @@ -35,7 +37,10 @@ export function resolveNestedSelector(selector: Root, parentSelector: Root): Roo const needsSorting = new Set>(); selectorAST.walkNesting((node) => { - const parent = node.parent!; + const parent = node.parent; + + if (!parent) return; + needsSorting.add(parent); if (parent.parent?.type === 'pseudo' && parent.parent.value?.toLowerCase() === ':has') { diff --git a/plugin-packs/postcss-bundler/dist/index.cjs b/plugin-packs/postcss-bundler/dist/index.cjs index 82c4f8e6a..741109ff2 100644 --- a/plugin-packs/postcss-bundler/dist/index.cjs +++ b/plugin-packs/postcss-bundler/dist/index.cjs @@ -1 +1 @@ -"use strict";var e=require("@csstools/css-parser-algorithms"),t=require("@csstools/css-tokenizer"),s=require("path"),o=require("module"),n=require("fs/promises"),r=require("@csstools/postcss-rebase-url");function isWarning(e){return"warning"===e.type}function isNodesStatement(e){return"nodes"===e.type}function isImportStatement(e){return"import"===e.type}function isPreImportStatement(e){return"pre-import"===e.type}const i=/^data:text\/css(?:;(?:base64|plain))?,/i,a=/^data:text\/css;base64,/i,c=/^data:text\/css;plain,/i;function isValidDataURL(e){return!!e&&i.test(e)}const p=/^charset$/i,u=/^import$/i,l=/^url$/i,m=/^layer$/i,d=/^supports$/i;function parseAtImport(s){const o=t.tokenize({css:s});if(2===o.length&&(t.isTokenString(o[0])||t.isTokenURL(o[0]))){let e=o[0][4].value;return e=stripHash(e),!!e&&{uri:e,fullUri:o[0][1]}}const n=e.parseListOfComponentValues(o);let r,i,a,c="",p="";for(let s=0;s{const i=parseStylesheet(e,t,s,o,n);if(r.charset&&i.charset&&r.charset.params.toLowerCase()!==i.charset.params.toLowerCase())throw i.charset.error(`Incompatible @charset statements:\n ${i.charset.params} specified in ${i.charset.source?.input.file}\n ${r.charset.params} specified in ${r.charset.source?.input.file}`);!r.charset&&i.charset&&(r.charset=i.charset),r.statements.push(...i.statements)})),r;let i,a,c=[],l=[];for(let r=0;r({postcssPlugin:"noop-plugin",Once(){}});async function parseStyles(e,t,s,o,n,r){const i=parseStylesheet(e,t,s,o,n);{let t,s,o;const n=[];for(const a of i.statements)isImportStatement(a)&&isProcessableURL(a.uri)&&(t&&s&&o||([t,s,o]=createRequire(a.node,e),t&&s&&o))&&n.push(resolveImportId(e,a,r,t,s,o));n.length&&await Promise.all(n)}for(let e=0;e{if(isWarning(s)||isPreImportStatement(s)||!s.conditions?.length)return;if(isImportStatement(s))return void(s.node.params=base64EncodedConditionalImport(s.fullUri,s.conditions));const n=s.nodes;if(!n.length)return;const r=n[0].parent;if(!r)return;const i=[];for(const e of s.conditions){if(void 0!==e.media){const o=t({name:"media",params:e.media,source:s.importingNode?.source??r.source});i.push(o)}if(void 0!==e.supports){const o=t({name:"supports",params:"("+e.supports+")",source:s.importingNode?.source??r.source});i.push(o)}if(void 0!==e.layer){const o=t({name:"layer",params:e.layer,source:s.importingNode?.source??r.source});i.push(o)}}const a=i[0];if(!a)return;for(let e=0;e{e.parent=void 0})),c.append(n),e.statements[o]={type:"nodes",nodes:[a],conditions:s.conditions,from:s.from,importingNode:s.importingNode}}))}function applyStyles(e,t){t.nodes=[],e.charset&&(e.charset.parent=void 0,t.append(e.charset)),e.statements.forEach((e=>{isImportStatement(e)?(e.node.parent=void 0,t.append(e.node)):isNodesStatement(e)&&e.nodes.forEach((e=>{e.parent=void 0,t.append(e)}))}))}function postProcess(e,t){let s=-1,o=-1,n=-1;for(let t=0;t({postcssPlugin:"postcss-bundler",async Once(e,{result:t,atRule:s,postcss:o}){const n=await parseStyles(t,e,null,[],[],o);postProcess(n,s),applyConditions(n,s),applyStyles(n,e)}});creator$1.postcss=!0;const creator=()=>({postcssPlugin:"postcss-bundler",plugins:[creator$1(),r()]});creator.postcss=!0,module.exports=creator; +"use strict";var e=require("@csstools/css-parser-algorithms"),t=require("@csstools/css-tokenizer"),s=require("path"),o=require("module"),n=require("fs/promises"),r=require("@csstools/postcss-rebase-url");function isWarning(e){return"warning"===e.type}function isNodesStatement(e){return"nodes"===e.type}function isImportStatement(e){return"import"===e.type}function isPreImportStatement(e){return"pre-import"===e.type}const i=/^data:text\/css(?:;(?:base64|plain))?,/i,a=/^data:text\/css;base64,/i,c=/^data:text\/css;plain,/i;function isValidDataURL(e){return!!e&&i.test(e)}const p=/^charset$/i,u=/^import$/i,l=/^url$/i,m=/^layer$/i,d=/^supports$/i;function parseAtImport(s){const o=t.tokenize({css:s});if(2===o.length&&(t.isTokenString(o[0])||t.isTokenURL(o[0]))){let e=o[0][4].value;return e=stripHash(e),!!e&&{uri:e,fullUri:o[0][1]}}const n=e.parseListOfComponentValues(o);let r,i,a,c="",p="";for(let s=0;s{const i=parseStylesheet(e,t,s,o,n);if(r.charset&&i.charset&&r.charset.params.toLowerCase()!==i.charset.params.toLowerCase())throw i.charset.error(`Incompatible @charset statements:\n ${i.charset.params} specified in ${i.charset.source?.input.file}\n ${r.charset.params} specified in ${r.charset.source?.input.file}`);!r.charset&&i.charset&&(r.charset=i.charset),r.statements.push(...i.statements)})),r;let i,a,c=[],l=[];for(let r=0;r({postcssPlugin:"noop-plugin",Once(){}});async function parseStyles(e,t,s,o,n,r){const i=parseStylesheet(e,t,s,o,n);{let t,s,o;const n=[];for(const a of i.statements)isImportStatement(a)&&isProcessableURL(a.uri)&&(t&&s&&o||([t,s,o]=createRequire(a.node,e),t&&s&&o))&&n.push(resolveImportId(e,a,r,t,s,o));n.length&&await Promise.all(n)}for(let e=0;e{if(isWarning(s)||isPreImportStatement(s)||!s.conditions?.length)return;if(isImportStatement(s))return void(s.node.params=base64EncodedConditionalImport(s.fullUri,s.conditions));const n=s.nodes;if(!n.length)return;const r=n[0].parent;if(!r)return;const i=[];for(const e of s.conditions){if(void 0!==e.media){const o=t({name:"media",params:e.media,source:s.importingNode?.source??r.source});i.push(o)}if(void 0!==e.supports){const o=t({name:"supports",params:"("+e.supports+")",source:s.importingNode?.source??r.source});i.push(o)}if(void 0!==e.layer){const o=t({name:"layer",params:e.layer,source:s.importingNode?.source??r.source});i.push(o)}}const a=i[0];if(!a)return;for(let e=0;e{e.parent=void 0})),c.append(n),e.statements[o]={type:"nodes",nodes:[a],conditions:s.conditions,from:s.from,importingNode:s.importingNode}}))}function applyStyles(e,t){t.nodes=[],e.charset&&(e.charset.parent=void 0,t.append(e.charset)),e.statements.forEach((e=>{isImportStatement(e)?(e.node.parent=void 0,t.append(e.node)):isNodesStatement(e)&&e.nodes.forEach((e=>{e.parent=void 0,t.append(e)}))}))}function postProcess(e,t){let s=-1,o=-1,n=-1;for(let t=0;t({postcssPlugin:"postcss-bundler",async Once(e,{result:t,atRule:s,postcss:o}){const n=await parseStyles(t,e,null,[],[],o);postProcess(n,s),applyConditions(n,s),applyStyles(n,e)}});creator$1.postcss=!0;const creator=()=>({postcssPlugin:"postcss-bundler",plugins:[creator$1(),r()]});creator.postcss=!0,module.exports=creator; diff --git a/plugin-packs/postcss-bundler/dist/index.mjs b/plugin-packs/postcss-bundler/dist/index.mjs index e9606786d..0ee1f31f8 100644 --- a/plugin-packs/postcss-bundler/dist/index.mjs +++ b/plugin-packs/postcss-bundler/dist/index.mjs @@ -1 +1 @@ -import{parseListOfComponentValues as e,isWhitespaceNode as t,isCommentNode as s,isTokenNode as o,isFunctionNode as r,stringify as n}from"@csstools/css-parser-algorithms";import{tokenize as i,isTokenString as a,isTokenURL as c,isTokenIdent as p}from"@csstools/css-tokenizer";import u from"path";import l from"module";import m from"fs/promises";import d from"@csstools/postcss-rebase-url";function isWarning(e){return"warning"===e.type}function isNodesStatement(e){return"nodes"===e.type}function isImportStatement(e){return"import"===e.type}function isPreImportStatement(e){return"pre-import"===e.type}const f=/^data:text\/css(?:;(?:base64|plain))?,/i,h=/^data:text\/css;base64,/i,y=/^data:text\/css;plain,/i;function isValidDataURL(e){return!!e&&f.test(e)}const g=/^charset$/i,v=/^import$/i,I=/^url$/i,S=/^layer$/i,b=/^supports$/i;function parseAtImport(u){const l=i({css:u});if(2===l.length&&(a(l[0])||c(l[0]))){let e=l[0][4].value;return e=stripHash(e),!!e&&{uri:e,fullUri:l[0][1]}}const m=e(l);let d,f,h,y="",g="";for(let e=0;e{const i=parseStylesheet(e,t,s,o,r);if(n.charset&&i.charset&&n.charset.params.toLowerCase()!==i.charset.params.toLowerCase())throw i.charset.error(`Incompatible @charset statements:\n ${i.charset.params} specified in ${i.charset.source?.input.file}\n ${n.charset.params} specified in ${n.charset.source?.input.file}`);!n.charset&&i.charset&&(n.charset=i.charset),n.statements.push(...i.statements)})),n;let i,a,c=[],p=[];for(let n=0;n({postcssPlugin:"noop-plugin",Once(){}});async function parseStyles(e,t,s,o,r,n){const i=parseStylesheet(e,t,s,o,r);{let t,s,o;const r=[];for(const a of i.statements)isImportStatement(a)&&isProcessableURL(a.uri)&&(t&&s&&o||([t,s,o]=createRequire(a.node,e),t&&s&&o))&&r.push(resolveImportId(e,a,n,t,s,o));r.length&&await Promise.all(r)}for(let e=0;e{if(isWarning(s)||isPreImportStatement(s)||!s.conditions?.length)return;if(isImportStatement(s))return void(s.node.params=base64EncodedConditionalImport(s.fullUri,s.conditions));const r=s.nodes;if(!r.length)return;const n=r[0].parent;if(!n)return;const i=[];for(const e of s.conditions){if(void 0!==e.media){const o=t({name:"media",params:e.media,source:s.importingNode?.source??n.source});i.push(o)}if(void 0!==e.supports){const o=t({name:"supports",params:"("+e.supports+")",source:s.importingNode?.source??n.source});i.push(o)}if(void 0!==e.layer){const o=t({name:"layer",params:e.layer,source:s.importingNode?.source??n.source});i.push(o)}}const a=i[0];if(!a)return;for(let e=0;e{e.parent=void 0})),c.append(r),e.statements[o]={type:"nodes",nodes:[a],conditions:s.conditions,from:s.from,importingNode:s.importingNode}}))}function applyStyles(e,t){t.nodes=[],e.charset&&(e.charset.parent=void 0,t.append(e.charset)),e.statements.forEach((e=>{isImportStatement(e)?(e.node.parent=void 0,t.append(e.node)):isNodesStatement(e)&&e.nodes.forEach((e=>{e.parent=void 0,t.append(e)}))}))}function postProcess(e,t){let s=-1,o=-1,r=-1;for(let t=0;t({postcssPlugin:"postcss-bundler",async Once(e,{result:t,atRule:s,postcss:o}){const r=await parseStyles(t,e,null,[],[],o);postProcess(r,s),applyConditions(r,s),applyStyles(r,e)}});creator$1.postcss=!0;const creator=()=>({postcssPlugin:"postcss-bundler",plugins:[creator$1(),d()]});creator.postcss=!0;export{creator as default}; +import{parseListOfComponentValues as e,isWhitespaceNode as t,isCommentNode as s,isTokenNode as o,isFunctionNode as r,stringify as n}from"@csstools/css-parser-algorithms";import{tokenize as i,isTokenString as a,isTokenURL as c,isTokenIdent as p}from"@csstools/css-tokenizer";import u from"path";import l from"module";import m from"fs/promises";import d from"@csstools/postcss-rebase-url";function isWarning(e){return"warning"===e.type}function isNodesStatement(e){return"nodes"===e.type}function isImportStatement(e){return"import"===e.type}function isPreImportStatement(e){return"pre-import"===e.type}const f=/^data:text\/css(?:;(?:base64|plain))?,/i,h=/^data:text\/css;base64,/i,y=/^data:text\/css;plain,/i;function isValidDataURL(e){return!!e&&f.test(e)}const g=/^charset$/i,v=/^import$/i,I=/^url$/i,S=/^layer$/i,b=/^supports$/i;function parseAtImport(u){const l=i({css:u});if(2===l.length&&(a(l[0])||c(l[0]))){let e=l[0][4].value;return e=stripHash(e),!!e&&{uri:e,fullUri:l[0][1]}}const m=e(l);let d,f,h,y="",g="";for(let e=0;e{const i=parseStylesheet(e,t,s,o,r);if(n.charset&&i.charset&&n.charset.params.toLowerCase()!==i.charset.params.toLowerCase())throw i.charset.error(`Incompatible @charset statements:\n ${i.charset.params} specified in ${i.charset.source?.input.file}\n ${n.charset.params} specified in ${n.charset.source?.input.file}`);!n.charset&&i.charset&&(n.charset=i.charset),n.statements.push(...i.statements)})),n;let i,a,c=[],p=[];for(let n=0;n({postcssPlugin:"noop-plugin",Once(){}});async function parseStyles(e,t,s,o,r,n){const i=parseStylesheet(e,t,s,o,r);{let t,s,o;const r=[];for(const a of i.statements)isImportStatement(a)&&isProcessableURL(a.uri)&&(t&&s&&o||([t,s,o]=createRequire(a.node,e),t&&s&&o))&&r.push(resolveImportId(e,a,n,t,s,o));r.length&&await Promise.all(r)}for(let e=0;e{if(isWarning(s)||isPreImportStatement(s)||!s.conditions?.length)return;if(isImportStatement(s))return void(s.node.params=base64EncodedConditionalImport(s.fullUri,s.conditions));const r=s.nodes;if(!r.length)return;const n=r[0].parent;if(!n)return;const i=[];for(const e of s.conditions){if(void 0!==e.media){const o=t({name:"media",params:e.media,source:s.importingNode?.source??n.source});i.push(o)}if(void 0!==e.supports){const o=t({name:"supports",params:"("+e.supports+")",source:s.importingNode?.source??n.source});i.push(o)}if(void 0!==e.layer){const o=t({name:"layer",params:e.layer,source:s.importingNode?.source??n.source});i.push(o)}}const a=i[0];if(!a)return;for(let e=0;e{e.parent=void 0})),c.append(r),e.statements[o]={type:"nodes",nodes:[a],conditions:s.conditions,from:s.from,importingNode:s.importingNode}}))}function applyStyles(e,t){t.nodes=[],e.charset&&(e.charset.parent=void 0,t.append(e.charset)),e.statements.forEach((e=>{isImportStatement(e)?(e.node.parent=void 0,t.append(e.node)):isNodesStatement(e)&&e.nodes.forEach((e=>{e.parent=void 0,t.append(e)}))}))}function postProcess(e,t){let s=-1,o=-1,r=-1;for(let t=0;t({postcssPlugin:"postcss-bundler",async Once(e,{result:t,atRule:s,postcss:o}){const r=await parseStyles(t,e,null,[],[],o);postProcess(r,s),applyConditions(r,s),applyStyles(r,e)}});creator$1.postcss=!0;const creator=()=>({postcssPlugin:"postcss-bundler",plugins:[creator$1(),d()]});creator.postcss=!0;export{creator as default}; diff --git a/plugin-packs/postcss-bundler/src/postcss-import/lib/base64-encoded-import.ts b/plugin-packs/postcss-bundler/src/postcss-import/lib/base64-encoded-import.ts index 64978db90..6b30e8f6d 100644 --- a/plugin-packs/postcss-bundler/src/postcss-import/lib/base64-encoded-import.ts +++ b/plugin-packs/postcss-bundler/src/postcss-import/lib/base64-encoded-import.ts @@ -8,7 +8,11 @@ import { formatImportPrelude } from './format-import-prelude'; // Each import can define a single group of conditions and a single cascade layer. export function base64EncodedConditionalImport(prelude: string, conditions: Array): string { conditions.reverse(); - const first = conditions.pop()!; + const first = conditions.pop(); + if (!first) { + return prelude; + } + let params = `${prelude} ${formatImportPrelude( first.layer, first.media, diff --git a/plugin-packs/postcss-bundler/src/postcss-import/lib/resolve-id.ts b/plugin-packs/postcss-bundler/src/postcss-import/lib/resolve-id.ts index b941ce5c5..b4f9b0e20 100644 --- a/plugin-packs/postcss-bundler/src/postcss-import/lib/resolve-id.ts +++ b/plugin-packs/postcss-bundler/src/postcss-import/lib/resolve-id.ts @@ -7,7 +7,7 @@ export function resolveId(node: Node, require: NodeRequire, id: string, base: st if (id.startsWith('node_modules:')) { try { resolvedPath = require.resolve(id.slice(13)); - } catch (_) { + } catch { throw node.error( `Failed to find '${id}'`, ); diff --git a/plugin-packs/postcss-preset-env/dist/index.cjs b/plugin-packs/postcss-preset-env/dist/index.cjs index 3095497b7..efbea11ac 100644 --- a/plugin-packs/postcss-preset-env/dist/index.cjs +++ b/plugin-packs/postcss-preset-env/dist/index.cjs @@ -1 +1 @@ -"use strict";var s=require("autoprefixer"),e=require("cssdb"),o=require("browserslist"),t=require("@csstools/postcss-initial"),i=require("postcss-pseudo-class-any-link"),r=require("css-blank-pseudo"),a=require("postcss-page-break"),c=require("@csstools/postcss-cascade-layers"),n=require("postcss-attribute-case-insensitive"),p=require("postcss-clamp"),l=require("@csstools/postcss-color-function"),u=require("postcss-color-functional-notation"),m=require("@csstools/postcss-color-mix-function"),d=require("postcss-custom-media"),g=require("postcss-custom-properties"),f=require("postcss-custom-selectors"),b=require("postcss-dir-pseudo-class"),h=require("@csstools/postcss-normalize-display-values"),v=require("postcss-double-position-gradients"),N=require("@csstools/postcss-exponential-functions"),y=require("@csstools/postcss-logical-float-and-clear"),k=require("postcss-focus-visible"),w=require("postcss-focus-within"),q=require("@csstools/postcss-font-format-keywords"),x=require("postcss-font-variant"),F=require("@csstools/postcss-gamut-mapping"),O=require("postcss-gap-properties"),$=require("@csstools/postcss-gradients-interpolation-method"),S=require("css-has-pseudo"),P=require("postcss-color-hex-alpha"),C=require("@csstools/postcss-hwb-function"),I=require("@csstools/postcss-ic-unit"),B=require("postcss-image-set-function"),E=require("@csstools/postcss-is-pseudo-class"),A=require("postcss-lab-function"),L=require("@csstools/postcss-light-dark-function"),U=require("@csstools/postcss-logical-overflow"),_=require("@csstools/postcss-logical-overscroll-behavior"),j=require("postcss-logical"),D=require("@csstools/postcss-logical-resize"),M=require("@csstools/postcss-logical-viewport-units"),z=require("@csstools/postcss-media-queries-aspect-ratio-number-values"),R=require("@csstools/postcss-media-minmax"),V=require("@csstools/postcss-nested-calc"),T=require("postcss-nesting"),H=require("postcss-selector-not"),W=require("@csstools/postcss-oklab-function"),G=require("postcss-opacity-percentage"),K=require("postcss-overflow-shorthand"),Z=require("postcss-replace-overflow-wrap"),Q=require("postcss-place"),J=require("css-prefers-color-scheme"),X=require("@csstools/postcss-progressive-custom-properties"),Y=require("postcss-color-rebeccapurple"),ss=require("@csstools/postcss-relative-color-syntax"),es=require("@csstools/postcss-scope-pseudo-class"),os=require("@csstools/postcss-stepped-value-functions"),ts=require("@csstools/postcss-text-decoration-shorthand"),is=require("@csstools/postcss-trigonometric-functions"),rs=require("@csstools/postcss-unset-value");const as={"blank-pseudo-class":"https://github.com/csstools/postcss-plugins/blob/main/plugins/css-blank-pseudo/README.md#browser","focus-visible-pseudo-class":"https://github.com/WICG/focus-visible","focus-within-pseudo-class":"https://github.com/csstools/postcss-plugins/blob/main/plugins/postcss-focus-within/README.md#browser","has-pseudo-class":"https://github.com/csstools/postcss-plugins/blob/main/plugins/css-has-pseudo/README.md#browser","prefers-color-scheme-query":"https://github.com/csstools/postcss-plugins/blob/main/plugins/css-prefers-color-scheme/README.md#browser"},cs=["blank-pseudo-class","focus-visible-pseudo-class","focus-within-pseudo-class","has-pseudo-class","prefers-color-scheme-query"];function logFeaturesList(s,e,o){if(e.debug){o.log("Enabling the following feature(s):");const t=[],i=[];!1!==e.autoprefixer&&i.push(" autoprefixer"),s.forEach((s=>{s.id.startsWith("before")||s.id.startsWith("after")?i.push(` ${s.id} (injected via options)`):i.push(` ${s.id}`),void 0!==as[s.id]&&t.push(s.id)})),i.sort(((s,e)=>s.localeCompare(e))),t.sort(((s,e)=>s.localeCompare(e))),i.forEach((s=>o.log(s))),t.length&&(o.log("These feature(s) need a browser library to work:"),t.forEach((s=>o.log(` ${s}: ${as[s]}`))))}}function initializeSharedOptions(s){if("preserve"in s){const e={};return e.preserve=s.preserve,e}return!1}function clamp(s,e,o){return Math.max(s,Math.min(e,o))}const ns=2,ps=5;function stageFromOptions(s,e){let o=ns;if(void 0===s.stage)return e.log(`Using features from Stage ${o} (default)`),o;if(!1===s.stage)o=ps;else{let e=parseInt(s.stage,10);Number.isNaN(e)&&(e=0),o=clamp(0,e,ps)}return o===ps?e.log('Stage has been disabled, features will be handled via the "features" option.'):e.log(`Using features from Stage ${o}`),o}const ls=Symbol("insertBefore"),us=Symbol("insertAfter"),ms=Symbol("insertOrder"),ds=Symbol("plugin");function getTransformedInsertions(s,e,o){if("insertBefore"!==o&&"insertAfter"!==o)return[];const t="insertBefore"===o?ls:us,i=[];for(const o in e){if(!Object.hasOwnProperty.call(e,o))continue;if(!s.find((s=>s.id===o)))continue;let r=e[o];Array.isArray(r)||(r=[r]);for(let s=0;sfeatureIsInsertedOrHasAPlugin(s))).sort(((s,e)=>featureIsLess(s,e)))}const ws=["and_chr","and_ff","android","chrome","edge","firefox","ie","ios_saf","op_mini","op_mob","opera","safari","samsung"];function getUnsupportedBrowsersByFeature(s){if(!s)return[];if(!("browser_support"in s))return["> 0%"];const e=[];return ws.forEach((o=>{if("op_mini"===o&&void 0===s.browser_support[o])return void e.push("op_mini all");const t=s.browser_support[o];"string"==typeof t&&qs.test(t)?e.push(`${o} < ${s.browser_support[o]}`):e.push(`${o} >= 1`)})),e}const qs=/^[0-9|.]+$/;function getOptionsForBrowsersByFeature(s,e,o,t,i){switch(e.id){case"is-pseudo-class":return{onComplexSelector:"warning"};case"nesting-rules":if(needsOptionFor(o.find((s=>"is-pseudo-class"===s.id)),s))return i.log('Disabling :is on "nesting-rules" due to lack of browser support.'),{noIsPseudoSelector:!0};return{};case"any-link-pseudo-class":if(s.find((s=>s.startsWith("ie ")||s.startsWith("edge "))))return i.log('Adding area[href] fallbacks for ":any-link" support in Edge and IE.'),{subFeatures:{areaHrefNeedsFixing:!0}};return{};case"logical-properties-and-values":case"float-clear-logical-values":case"logical-resize":case"logical-viewport-units":case"logical-overflow":case"logical-overscroll-behavior":return"logical"in t?t.logical:{};default:return{}}}function needsOptionFor(s,e){const t=getUnsupportedBrowsersByFeature(s),i=o(t,{ignoreUnknownVersions:!0});return!!e.some((s=>i.some((e=>e===s))))}function formatPolyfillableFeature(s){const e=getUnsupportedBrowsersByFeature(s);if(s[ls]||s[us]){let o=s.id;return o=s.insertBefore?`before-${o}`:`after-${o}`,{browsers:e,vendors_implementations:s.vendors_implementations,plugin:s[ds],id:o,stage:ps+1}}return{browsers:e,vendors_implementations:s.vendors_implementations,plugin:ks.get(s.id),id:s.id,stage:s.stage}}function formatStagedFeature(s,e,o,t,i,r,a){let c,n;return c=getOptionsForBrowsersByFeature(e,t,s,r,a),c=i?Object.assign({},c,i,featureOptions(o,t.id)):Object.assign({},c,featureOptions(o,t.id)),"progressive-custom-properties"!==t.id&&(c.enableProgressiveCustomProperties=!1),"overflow-wrap-property"===t.id&&"preserve"in c&&(c.method=c.preserve?"copy":"replace"),n=t.plugin.postcss&&"function"==typeof t.plugin?t.plugin(c):t.plugin&&t.plugin.default&&"function"==typeof t.plugin.default&&t.plugin.default.postcss?t.plugin.default(c):t.plugin,{browsers:t.browsers,vendors_implementations:t.vendors_implementations,plugin:n,pluginOptions:c,id:t.id}}function featureOptions(s,e){if(!(e in s))return;const o=s[e];return Array.isArray(o)?o[1]:o}function intOrZero(s){const e=parseInt(s,10);return Number.isNaN(e)?0:e}const xs=new Set(["progressive-custom-properties"]);function listFeatures(s,e,t,i){const r=Object(e.features),a="enableClientSidePolyfills"in e&&e.enableClientSidePolyfills,c=Object(e.insertBefore),n=Object(e.insertAfter),p=e.browsers?void 0:e.env,l=e.browsers,u=clamp(0,intOrZero(e.minimumVendorImplementations),3);u>0&&i.log(`Using features with ${u} or more vendor implementations`);const m=stageFromOptions(e,i),d=prepareFeaturesList([...s,{id:"progressive-custom-properties"}],c,n).map((s=>formatPolyfillableFeature(s))).filter((s=>!!xs.has(s.id)||(0===u||(!(!s[ls]&&!s[us])||(u<=s.vendors_implementations||(!0===featureEnabledByOptions(r,s.id)?(i.log(` ${s.id} does not meet the required vendor implementations but has been enabled by options`),!0):(i.log(` ${s.id} with ${s.vendors_implementations} vendor implementations has been disabled`),!1))))))),g=o(l,{env:p,ignoreUnknownVersions:!0}).filter((s=>ws.includes(s.split(" ")[0])));return d.filter((s=>{if(xs.has(s.id))return!0;const e=s.stage>=m,o=a||!cs.includes(s.id),t=featureEnabledByOptions(r,s.id),c=!1===t,n=!0===t||e&&o;return c?i.log(` ${s.id} has been disabled by options`):e?o||i.log(` ${s.id} has been disabled by "enableClientSidePolyfills: false".`):n?i.log(` ${s.id} does not meet the required stage but has been enabled by options`):i.log(` ${s.id} with stage ${s.stage} has been disabled`),!c&&n})).map((o=>formatStagedFeature(s,g,r,o,t,e,i))).filter((s=>{if(xs.has(s.id))return!0;const e=featureEnabledByOptions(r,s.id);if(!0===e||!1===e)return e;const t=o(s.browsers,{ignoreUnknownVersions:!0}),a=g.some((s=>t.some((e=>e===s))));return a||i.log(`${s.id} disabled due to browser support`),a}))}function featureEnabledByOptions(s,e){if(!(e in s))return"auto";const o=s[e];return Array.isArray(o)?!0===o[0]||!1!==o[0]&&"auto":Boolean(o)}class Logger{constructor(){this.logs=[]}log(s){this.logs.push(s)}resetLogger(){this.logs.length=0}dumpLogs(s){s&&s.warn(this.logs.join("\n")),this.resetLogger()}}var Fs=[{packageName:"css-blank-pseudo",id:"blank-pseudo-class",importName:"postcssBlankPseudo"},{packageName:"css-has-pseudo",id:"has-pseudo-class",importName:"postcssHasPseudo"},{packageName:"css-prefers-color-scheme",id:"prefers-color-scheme-query",importName:"postcssPrefersColorScheme"},{packageName:"postcss-attribute-case-insensitive",id:"case-insensitive-attributes",importName:"postcssAttributeCaseInsensitive"},{packageName:"postcss-clamp",id:"clamp",importName:"postcssClamp"},{packageName:"@csstools/postcss-color-mix-function",id:"color-mix",importName:"postcssColorMixFunction"},{packageName:"@csstools/postcss-color-function",id:"color-function",importName:"postcssColorFunction"},{packageName:"postcss-color-functional-notation",id:"color-functional-notation",importName:"postcssColorFunctionalNotation"},{packageName:"postcss-color-hex-alpha",id:"hexadecimal-alpha-notation",importName:"postcssColorHexAlpha"},{packageName:"postcss-color-rebeccapurple",id:"rebeccapurple-color",importName:"postcssColorRebeccapurple"},{packageName:"postcss-custom-media",id:"custom-media-queries",importName:"postcssCustomMedia"},{packageName:"postcss-custom-properties",id:"custom-properties",importName:"postcssCustomProperties"},{packageName:"postcss-custom-selectors",id:"custom-selectors",importName:"postcssCustomSelectors"},{packageName:"postcss-dir-pseudo-class",id:"dir-pseudo-class",importName:"postcssDirPseudoClass"},{packageName:"postcss-double-position-gradients",id:"double-position-gradients",importName:"postcssDoublePositionGradients"},{packageName:"@csstools/postcss-exponential-functions",id:"exponential-functions",importName:"postcssExponentialFunctions"},{packageName:"postcss-focus-visible",id:"focus-visible-pseudo-class",importName:"postcssFocusVisible"},{packageName:"postcss-focus-within",id:"focus-within-pseudo-class",importName:"postcssFocusWithin"},{packageName:"@csstools/postcss-font-format-keywords",id:"font-format-keywords",importName:"postcssFontFormatKeywords"},{packageName:"postcss-font-variant",id:"font-variant-property",importName:"postcssFontVariant"},{packageName:"@csstools/postcss-gamut-mapping",id:"gamut-mapping",importName:"postcssGamutMapping"},{packageName:"postcss-gap-properties",id:"gap-properties",importName:"postcssGapProperties"},{packageName:"@csstools/postcss-gradients-interpolation-method",id:"gradients-interpolation-method",importName:"postcssGradientsInterpolationMethod"},{packageName:"@csstools/postcss-hwb-function",id:"hwb-function",importName:"postcssHWBFunction"},{packageName:"@csstools/postcss-ic-unit",id:"ic-unit",importName:"postcssICUnit"},{packageName:"postcss-image-set-function",id:"image-set-function",importName:"postcssImageSetFunction"},{packageName:"@csstools/postcss-initial",id:"all-property",importName:"postcssInitial"},{packageName:"@csstools/postcss-is-pseudo-class",id:"is-pseudo-class",importName:"postcssIsPseudoClass"},{packageName:"@csstools/postcss-scope-pseudo-class",id:"scope-pseudo-class",importName:"postcssScopePseudoClass"},{packageName:"postcss-lab-function",id:"lab-function",importName:"postcssLabFunction"},{packageName:"@csstools/postcss-light-dark-function",id:"light-dark-function",importName:"postcssLightDarkFunction"},{packageName:"postcss-logical",id:"logical-properties-and-values",importName:"postcssLogical"},{packageName:"@csstools/postcss-logical-float-and-clear",id:"float-clear-logical-values",importName:"postcssLogicalFloatAndClear"},{packageName:"@csstools/postcss-logical-overflow",id:"logical-overflow",importName:"postcssLogicalOverflow"},{packageName:"@csstools/postcss-logical-overscroll-behavior",id:"logical-overscroll-behavior",importName:"postcssLogicalOverscrollBehavor"},{packageName:"@csstools/postcss-logical-resize",id:"logical-resize",importName:"postcssLogicalResize"},{packageName:"@csstools/postcss-logical-viewport-units",id:"logical-viewport-units",importName:"postcssLogicalViewportUnits"},{packageName:"@csstools/postcss-media-minmax",id:"media-query-ranges",importName:"postcssMediaMinmax"},{packageName:"@csstools/postcss-media-queries-aspect-ratio-number-values",id:"media-queries-aspect-ratio-number-values",importName:"postcssMediaQueriesAspectRatioNumberValues"},{packageName:"postcss-nesting",id:"nesting-rules",importName:"postcssNesting"},{packageName:"@csstools/postcss-normalize-display-values",id:"display-two-values",importName:"postcssNormalizeDisplayValues"},{packageName:"@csstools/postcss-oklab-function",id:"oklab-function",importName:"postcssOKLabFunction"},{packageName:"@csstools/postcss-relative-color-syntax",id:"relative-color-syntax",importName:"postcssRelativeColorSyntax"},{packageName:"postcss-opacity-percentage",id:"opacity-percentage",importName:"postcssOpacityPercentage"},{packageName:"postcss-overflow-shorthand",id:"overflow-property",importName:"postcssOverflowShorthand"},{packageName:"postcss-page-break",id:"break-properties",importName:"postcssPageBreak"},{packageName:"postcss-place",id:"place-properties",importName:"postcssPlace"},{packageName:"postcss-pseudo-class-any-link",id:"any-link-pseudo-class",importName:"postcssPseudoClassAnyLink"},{packageName:"postcss-replace-overflow-wrap",id:"overflow-wrap-property",importName:"postcssReplaceOverflowWrap"},{packageName:"postcss-selector-not",id:"not-pseudo-class",importName:"postcssSelectorNot"},{packageName:"@csstools/postcss-stepped-value-functions",id:"stepped-value-functions",importName:"postcssSteppedValueFunctions"},{packageName:"postcss-system-ui-font-family",importedPackage:"../patch/postcss-system-ui-font-family.mjs",id:"system-ui-font-family",importName:"postcssFontFamilySystemUI"},{packageName:"@csstools/postcss-unset-value",id:"unset-value",importName:"postcssUnsetValue"},{packageName:"@csstools/postcss-cascade-layers",id:"cascade-layers",importName:"postcssCascadeLayers"},{packageName:"@csstools/postcss-trigonometric-functions",id:"trigonometric-functions",importName:"postcssTrigonometricFunctions"},{packageName:"@csstools/postcss-nested-calc",id:"nested-calc",importName:"postcssNestedCalc"},{packageName:"@csstools/postcss-text-decoration-shorthand",id:"text-decoration-shorthand",importName:"postcssTextDecorationShorthand"},{packageName:"@csstools/postcss-progressive-custom-properties",id:"progressive-custom-properties",importName:"postcssProgressiveCustomProperties",omitTypedOptions:!0,omitDocs:!0}];function getPackageNamesToIds(){const s={};return Fs.forEach((e=>{s[e.packageName]=e.id})),s}function pluginIdHelp(s,e,o){const t=Fs.map((s=>s.id)),i=Fs.map((s=>s.packageName)),r=getPackageNamesToIds();s.forEach((s=>{if(t.includes(s))return;const a=[...t.map((e=>[e,levenshteinDistance(s,e)])),...i.map((e=>[r[e],levenshteinDistance(s,e)]))].sort(((s,e)=>s[1]-e[1])).filter((s=>s[1]<10)),c=new Set;for(let s=0;s=3));s++);if(!c.size)return void e.warn(o,`Unknown feature: "${s}", see the list of features https://github.com/csstools/postcss-plugins/blob/main/plugin-packs/postcss-preset-env/FEATURES.md`);let n='"';n+=Array.from(c).join('", "'),n+='"',e.warn(o,`Unknown feature: "${s}", did you mean one of: ${n}`)}))}function levenshteinDistance(s,e){if(!s.length)return e.length;if(!e.length)return s.length;const o=[];for(let t=0;t<=e.length;t++){o[t]=[t];for(let i=1;i<=s.length;i++)o[t][i]=0===t?i:Math.min(o[t-1][i]+1,o[t][i-1]+1,o[t-1][i-1]+(s[i-1]===e[t-1]?0:1))}return o[e.length][s.length]}const creator=o=>{const t=new Logger,i=Object(o),r=Object.keys(Object(i.features)),a=i.browsers?void 0:i.env,c=i.browsers,n=initializeSharedOptions(i),p=listFeatures(e,i,n,t),l=p.map((s=>s.plugin));!1!==i.autoprefixer&&l.push(s(Object.assign({env:a,overrideBrowserslist:c},i.autoprefixer))),logFeaturesList(p,i,t);const internalPlugin=()=>({postcssPlugin:"postcss-preset-env",OnceExit(s,{result:e}){pluginIdHelp(r,s,e),i.debug&&t.dumpLogs(e),t.resetLogger()}});return internalPlugin.postcss=!0,{postcssPlugin:"postcss-preset-env",plugins:[...l,internalPlugin()]}};creator.postcss=!0,module.exports=creator; +"use strict";var s=require("autoprefixer"),e=require("cssdb"),o=require("browserslist"),t=require("@csstools/postcss-initial"),i=require("postcss-pseudo-class-any-link"),r=require("css-blank-pseudo"),a=require("postcss-page-break"),c=require("@csstools/postcss-cascade-layers"),n=require("postcss-attribute-case-insensitive"),p=require("postcss-clamp"),l=require("@csstools/postcss-color-function"),u=require("postcss-color-functional-notation"),m=require("@csstools/postcss-color-mix-function"),d=require("postcss-custom-media"),g=require("postcss-custom-properties"),f=require("postcss-custom-selectors"),b=require("postcss-dir-pseudo-class"),h=require("@csstools/postcss-normalize-display-values"),v=require("postcss-double-position-gradients"),N=require("@csstools/postcss-exponential-functions"),y=require("@csstools/postcss-logical-float-and-clear"),k=require("postcss-focus-visible"),w=require("postcss-focus-within"),q=require("@csstools/postcss-font-format-keywords"),x=require("postcss-font-variant"),F=require("@csstools/postcss-gamut-mapping"),O=require("postcss-gap-properties"),$=require("@csstools/postcss-gradients-interpolation-method"),S=require("css-has-pseudo"),P=require("postcss-color-hex-alpha"),C=require("@csstools/postcss-hwb-function"),I=require("@csstools/postcss-ic-unit"),B=require("postcss-image-set-function"),E=require("@csstools/postcss-is-pseudo-class"),A=require("postcss-lab-function"),L=require("@csstools/postcss-light-dark-function"),U=require("@csstools/postcss-logical-overflow"),_=require("@csstools/postcss-logical-overscroll-behavior"),j=require("postcss-logical"),D=require("@csstools/postcss-logical-resize"),M=require("@csstools/postcss-logical-viewport-units"),z=require("@csstools/postcss-media-queries-aspect-ratio-number-values"),R=require("@csstools/postcss-media-minmax"),V=require("@csstools/postcss-nested-calc"),T=require("postcss-nesting"),H=require("postcss-selector-not"),W=require("@csstools/postcss-oklab-function"),G=require("postcss-opacity-percentage"),K=require("postcss-overflow-shorthand"),Z=require("postcss-replace-overflow-wrap"),Q=require("postcss-place"),J=require("css-prefers-color-scheme"),X=require("@csstools/postcss-progressive-custom-properties"),Y=require("postcss-color-rebeccapurple"),ss=require("@csstools/postcss-relative-color-syntax"),es=require("@csstools/postcss-scope-pseudo-class"),os=require("@csstools/postcss-stepped-value-functions"),ts=require("@csstools/postcss-text-decoration-shorthand"),is=require("@csstools/postcss-trigonometric-functions"),rs=require("@csstools/postcss-unset-value");const as={"blank-pseudo-class":"https://github.com/csstools/postcss-plugins/blob/main/plugins/css-blank-pseudo/README.md#browser","focus-visible-pseudo-class":"https://github.com/WICG/focus-visible","focus-within-pseudo-class":"https://github.com/csstools/postcss-plugins/blob/main/plugins/postcss-focus-within/README.md#browser","has-pseudo-class":"https://github.com/csstools/postcss-plugins/blob/main/plugins/css-has-pseudo/README.md#browser","prefers-color-scheme-query":"https://github.com/csstools/postcss-plugins/blob/main/plugins/css-prefers-color-scheme/README.md#browser"},cs=["blank-pseudo-class","focus-visible-pseudo-class","focus-within-pseudo-class","has-pseudo-class","prefers-color-scheme-query"];function logFeaturesList(s,e,o){if(e.debug){o.log("Enabling the following feature(s):");const t=[],i=[];!1!==e.autoprefixer&&i.push(" autoprefixer"),s.forEach((s=>{s.id.startsWith("before")||s.id.startsWith("after")?i.push(` ${s.id} (injected via options)`):i.push(` ${s.id}`),void 0!==as[s.id]&&t.push(s.id)})),i.sort(((s,e)=>s.localeCompare(e))),t.sort(((s,e)=>s.localeCompare(e))),i.forEach((s=>o.log(s))),t.length&&(o.log("These feature(s) need a browser library to work:"),t.forEach((s=>o.log(` ${s}: ${as[s]}`))))}}function initializeSharedOptions(s){if("preserve"in s){const e={};return e.preserve=s.preserve,e}return!1}function clamp(s,e,o){return Math.max(s,Math.min(e,o))}const ns=2,ps=5;function stageFromOptions(s,e){let o=ns;if(void 0===s.stage)return e.log(`Using features from Stage ${o} (default)`),o;if(!1===s.stage)o=ps;else{let e=parseInt(s.stage,10);Number.isNaN(e)&&(e=0),o=clamp(0,e,ps)}return o===ps?e.log('Stage has been disabled, features will be handled via the "features" option.'):e.log(`Using features from Stage ${o}`),o}const ls=Symbol("insertBefore"),us=Symbol("insertAfter"),ms=Symbol("insertOrder"),ds=Symbol("plugin");function getTransformedInsertions(s,e,o){if("insertBefore"!==o&&"insertAfter"!==o)return[];const t="insertBefore"===o?ls:us,i=[];for(const o in e){if(!Object.hasOwnProperty.call(e,o))continue;if(!s.find((s=>s.id===o)))continue;let r=e[o];Array.isArray(r)||(r=[r]);for(let s=0;sfeatureIsInsertedOrHasAPlugin(s))).sort(((s,e)=>featureIsLess(s,e)))}const ws=["and_chr","and_ff","android","chrome","edge","firefox","ie","ios_saf","op_mini","op_mob","opera","safari","samsung"];function getUnsupportedBrowsersByFeature(s){if(!s)return[];if(!("browser_support"in s))return["> 0%"];const e=[];return ws.forEach((o=>{if("op_mini"===o&&void 0===s.browser_support[o])return void e.push("op_mini all");const t=s.browser_support[o];"string"==typeof t&&qs.test(t)?e.push(`${o} < ${s.browser_support[o]}`):e.push(`${o} >= 1`)})),e}const qs=/^[0-9|.]+$/;function getOptionsForBrowsersByFeature(s,e,o,t,i){switch(e.id){case"is-pseudo-class":return{onComplexSelector:"warning"};case"nesting-rules":if(needsOptionFor(o.find((s=>"is-pseudo-class"===s.id)),s))return i.log('Disabling :is on "nesting-rules" due to lack of browser support.'),{noIsPseudoSelector:!0};return{};case"any-link-pseudo-class":if(s.find((s=>s.startsWith("ie ")||s.startsWith("edge "))))return i.log('Adding area[href] fallbacks for ":any-link" support in Edge and IE.'),{subFeatures:{areaHrefNeedsFixing:!0}};return{};case"logical-properties-and-values":case"float-clear-logical-values":case"logical-resize":case"logical-viewport-units":case"logical-overflow":case"logical-overscroll-behavior":return"logical"in t?t.logical:{};default:return{}}}function needsOptionFor(s,e){const t=getUnsupportedBrowsersByFeature(s),i=o(t,{ignoreUnknownVersions:!0});return!!e.some((s=>i.some((e=>e===s))))}function formatPolyfillableFeature(s){const e=getUnsupportedBrowsersByFeature(s);if(s[ls]||s[us]){let o=s.id;return o=s.insertBefore?`before-${o}`:`after-${o}`,{browsers:e,vendors_implementations:s.vendors_implementations,plugin:s[ds],id:o,stage:ps+1}}return{browsers:e,vendors_implementations:s.vendors_implementations,plugin:ks.get(s.id),id:s.id,stage:s.stage}}function formatStagedFeature(s,e,o,t,i,r,a){let c,n;return c=getOptionsForBrowsersByFeature(e,t,s,r,a),c=i?Object.assign({},c,i,featureOptions(o,t.id)):Object.assign({},c,featureOptions(o,t.id)),"progressive-custom-properties"!==t.id&&(c.enableProgressiveCustomProperties=!1),"overflow-wrap-property"===t.id&&"preserve"in c&&(c.method=c.preserve?"copy":"replace"),n=t.plugin.postcss&&"function"==typeof t.plugin?t.plugin(c):t.plugin&&t.plugin.default&&"function"==typeof t.plugin.default&&t.plugin.default.postcss?t.plugin.default(c):t.plugin,{browsers:t.browsers,vendors_implementations:t.vendors_implementations,plugin:n,pluginOptions:c,id:t.id}}function featureOptions(s,e){if(!(e in s))return;const o=s[e];return Array.isArray(o)?o[1]:o}function intOrZero(s){const e=parseInt(s,10);return Number.isNaN(e)?0:e}const xs=new Set(["progressive-custom-properties"]);function listFeatures(s,e,t,i){const r=Object(e.features),a="enableClientSidePolyfills"in e&&e.enableClientSidePolyfills,c=Object(e.insertBefore),n=Object(e.insertAfter),p=e.browsers?void 0:e.env,l=e.browsers,u=clamp(0,intOrZero(e.minimumVendorImplementations),3);u>0&&i.log(`Using features with ${u} or more vendor implementations`);const m=stageFromOptions(e,i),d=prepareFeaturesList([...s,{id:"progressive-custom-properties"}],c,n).map((s=>formatPolyfillableFeature(s))).filter((s=>!!xs.has(s.id)||(0===u||(!(!s[ls]&&!s[us])||(u<=s.vendors_implementations||(!0===featureEnabledByOptions(r,s.id)?(i.log(` ${s.id} does not meet the required vendor implementations but has been enabled by options`),!0):(i.log(` ${s.id} with ${s.vendors_implementations} vendor implementations has been disabled`),!1))))))),g=o(l,{env:p,ignoreUnknownVersions:!0}).filter((s=>ws.includes(s.split(" ")[0])));return d.filter((s=>{if(xs.has(s.id))return!0;const e=s.stage>=m,o=a||!cs.includes(s.id),t=featureEnabledByOptions(r,s.id),c=!1===t,n=!0===t||e&&o;return c?i.log(` ${s.id} has been disabled by options`):e?o||i.log(` ${s.id} has been disabled by "enableClientSidePolyfills: false".`):n?i.log(` ${s.id} does not meet the required stage but has been enabled by options`):i.log(` ${s.id} with stage ${s.stage} has been disabled`),!c&&n})).map((o=>formatStagedFeature(s,g,r,o,t,e,i))).filter((s=>{if(xs.has(s.id))return!0;const e=featureEnabledByOptions(r,s.id);if(!0===e||!1===e)return e;const t=o(s.browsers,{ignoreUnknownVersions:!0}),a=g.some((s=>t.some((e=>e===s))));return a||i.log(`${s.id} disabled due to browser support`),a}))}function featureEnabledByOptions(s,e){if(!(e in s))return"auto";const o=s[e];return Array.isArray(o)?!0===o[0]||!1!==o[0]&&"auto":Boolean(o)}class Logger{constructor(){this.logs=[]}log(s){this.logs.push(s)}resetLogger(){this.logs.length=0}emitLogs(s){s&&s.warn(this.logs.join("\n")),this.resetLogger()}}var Fs=[{packageName:"css-blank-pseudo",id:"blank-pseudo-class",importName:"postcssBlankPseudo"},{packageName:"css-has-pseudo",id:"has-pseudo-class",importName:"postcssHasPseudo"},{packageName:"css-prefers-color-scheme",id:"prefers-color-scheme-query",importName:"postcssPrefersColorScheme"},{packageName:"postcss-attribute-case-insensitive",id:"case-insensitive-attributes",importName:"postcssAttributeCaseInsensitive"},{packageName:"postcss-clamp",id:"clamp",importName:"postcssClamp"},{packageName:"@csstools/postcss-color-mix-function",id:"color-mix",importName:"postcssColorMixFunction"},{packageName:"@csstools/postcss-color-function",id:"color-function",importName:"postcssColorFunction"},{packageName:"postcss-color-functional-notation",id:"color-functional-notation",importName:"postcssColorFunctionalNotation"},{packageName:"postcss-color-hex-alpha",id:"hexadecimal-alpha-notation",importName:"postcssColorHexAlpha"},{packageName:"postcss-color-rebeccapurple",id:"rebeccapurple-color",importName:"postcssColorRebeccapurple"},{packageName:"postcss-custom-media",id:"custom-media-queries",importName:"postcssCustomMedia"},{packageName:"postcss-custom-properties",id:"custom-properties",importName:"postcssCustomProperties"},{packageName:"postcss-custom-selectors",id:"custom-selectors",importName:"postcssCustomSelectors"},{packageName:"postcss-dir-pseudo-class",id:"dir-pseudo-class",importName:"postcssDirPseudoClass"},{packageName:"postcss-double-position-gradients",id:"double-position-gradients",importName:"postcssDoublePositionGradients"},{packageName:"@csstools/postcss-exponential-functions",id:"exponential-functions",importName:"postcssExponentialFunctions"},{packageName:"postcss-focus-visible",id:"focus-visible-pseudo-class",importName:"postcssFocusVisible"},{packageName:"postcss-focus-within",id:"focus-within-pseudo-class",importName:"postcssFocusWithin"},{packageName:"@csstools/postcss-font-format-keywords",id:"font-format-keywords",importName:"postcssFontFormatKeywords"},{packageName:"postcss-font-variant",id:"font-variant-property",importName:"postcssFontVariant"},{packageName:"@csstools/postcss-gamut-mapping",id:"gamut-mapping",importName:"postcssGamutMapping"},{packageName:"postcss-gap-properties",id:"gap-properties",importName:"postcssGapProperties"},{packageName:"@csstools/postcss-gradients-interpolation-method",id:"gradients-interpolation-method",importName:"postcssGradientsInterpolationMethod"},{packageName:"@csstools/postcss-hwb-function",id:"hwb-function",importName:"postcssHWBFunction"},{packageName:"@csstools/postcss-ic-unit",id:"ic-unit",importName:"postcssICUnit"},{packageName:"postcss-image-set-function",id:"image-set-function",importName:"postcssImageSetFunction"},{packageName:"@csstools/postcss-initial",id:"all-property",importName:"postcssInitial"},{packageName:"@csstools/postcss-is-pseudo-class",id:"is-pseudo-class",importName:"postcssIsPseudoClass"},{packageName:"@csstools/postcss-scope-pseudo-class",id:"scope-pseudo-class",importName:"postcssScopePseudoClass"},{packageName:"postcss-lab-function",id:"lab-function",importName:"postcssLabFunction"},{packageName:"@csstools/postcss-light-dark-function",id:"light-dark-function",importName:"postcssLightDarkFunction"},{packageName:"postcss-logical",id:"logical-properties-and-values",importName:"postcssLogical"},{packageName:"@csstools/postcss-logical-float-and-clear",id:"float-clear-logical-values",importName:"postcssLogicalFloatAndClear"},{packageName:"@csstools/postcss-logical-overflow",id:"logical-overflow",importName:"postcssLogicalOverflow"},{packageName:"@csstools/postcss-logical-overscroll-behavior",id:"logical-overscroll-behavior",importName:"postcssLogicalOverscrollBehavor"},{packageName:"@csstools/postcss-logical-resize",id:"logical-resize",importName:"postcssLogicalResize"},{packageName:"@csstools/postcss-logical-viewport-units",id:"logical-viewport-units",importName:"postcssLogicalViewportUnits"},{packageName:"@csstools/postcss-media-minmax",id:"media-query-ranges",importName:"postcssMediaMinmax"},{packageName:"@csstools/postcss-media-queries-aspect-ratio-number-values",id:"media-queries-aspect-ratio-number-values",importName:"postcssMediaQueriesAspectRatioNumberValues"},{packageName:"postcss-nesting",id:"nesting-rules",importName:"postcssNesting"},{packageName:"@csstools/postcss-normalize-display-values",id:"display-two-values",importName:"postcssNormalizeDisplayValues"},{packageName:"@csstools/postcss-oklab-function",id:"oklab-function",importName:"postcssOKLabFunction"},{packageName:"@csstools/postcss-relative-color-syntax",id:"relative-color-syntax",importName:"postcssRelativeColorSyntax"},{packageName:"postcss-opacity-percentage",id:"opacity-percentage",importName:"postcssOpacityPercentage"},{packageName:"postcss-overflow-shorthand",id:"overflow-property",importName:"postcssOverflowShorthand"},{packageName:"postcss-page-break",id:"break-properties",importName:"postcssPageBreak"},{packageName:"postcss-place",id:"place-properties",importName:"postcssPlace"},{packageName:"postcss-pseudo-class-any-link",id:"any-link-pseudo-class",importName:"postcssPseudoClassAnyLink"},{packageName:"postcss-replace-overflow-wrap",id:"overflow-wrap-property",importName:"postcssReplaceOverflowWrap"},{packageName:"postcss-selector-not",id:"not-pseudo-class",importName:"postcssSelectorNot"},{packageName:"@csstools/postcss-stepped-value-functions",id:"stepped-value-functions",importName:"postcssSteppedValueFunctions"},{packageName:"postcss-system-ui-font-family",importedPackage:"../patch/postcss-system-ui-font-family.mjs",id:"system-ui-font-family",importName:"postcssFontFamilySystemUI"},{packageName:"@csstools/postcss-unset-value",id:"unset-value",importName:"postcssUnsetValue"},{packageName:"@csstools/postcss-cascade-layers",id:"cascade-layers",importName:"postcssCascadeLayers"},{packageName:"@csstools/postcss-trigonometric-functions",id:"trigonometric-functions",importName:"postcssTrigonometricFunctions"},{packageName:"@csstools/postcss-nested-calc",id:"nested-calc",importName:"postcssNestedCalc"},{packageName:"@csstools/postcss-text-decoration-shorthand",id:"text-decoration-shorthand",importName:"postcssTextDecorationShorthand"},{packageName:"@csstools/postcss-progressive-custom-properties",id:"progressive-custom-properties",importName:"postcssProgressiveCustomProperties",omitTypedOptions:!0,omitDocs:!0}];function getPackageNamesToIds(){const s={};return Fs.forEach((e=>{s[e.packageName]=e.id})),s}function pluginIdHelp(s,e,o){const t=Fs.map((s=>s.id)),i=Fs.map((s=>s.packageName)),r=getPackageNamesToIds();s.forEach((s=>{if(t.includes(s))return;const a=[...t.map((e=>[e,levenshteinDistance(s,e)])),...i.map((e=>[r[e],levenshteinDistance(s,e)]))].sort(((s,e)=>s[1]-e[1])).filter((s=>s[1]<10)),c=new Set;for(let s=0;s=3));s++);if(!c.size)return void e.warn(o,`Unknown feature: "${s}", see the list of features https://github.com/csstools/postcss-plugins/blob/main/plugin-packs/postcss-preset-env/FEATURES.md`);let n='"';n+=Array.from(c).join('", "'),n+='"',e.warn(o,`Unknown feature: "${s}", did you mean one of: ${n}`)}))}function levenshteinDistance(s,e){if(!s.length)return e.length;if(!e.length)return s.length;const o=[];for(let t=0;t<=e.length;t++){o[t]=[t];for(let i=1;i<=s.length;i++)o[t][i]=0===t?i:Math.min(o[t-1][i]+1,o[t][i-1]+1,o[t-1][i-1]+(s[i-1]===e[t-1]?0:1))}return o[e.length][s.length]}const creator=o=>{const t=new Logger,i=Object(o),r=Object.keys(Object(i.features)),a=i.browsers?void 0:i.env,c=i.browsers,n=initializeSharedOptions(i),p=listFeatures(e,i,n,t),l=p.map((s=>s.plugin));!1!==i.autoprefixer&&l.push(s(Object.assign({env:a,overrideBrowserslist:c},i.autoprefixer))),logFeaturesList(p,i,t);const internalPlugin=()=>({postcssPlugin:"postcss-preset-env",OnceExit(s,{result:e}){pluginIdHelp(r,s,e),i.debug&&t.emitLogs(e),t.resetLogger()}});return internalPlugin.postcss=!0,{postcssPlugin:"postcss-preset-env",plugins:[...l,internalPlugin()]}};creator.postcss=!0,module.exports=creator; diff --git a/plugin-packs/postcss-preset-env/dist/index.mjs b/plugin-packs/postcss-preset-env/dist/index.mjs index 93078b0e9..d70b95a8f 100644 --- a/plugin-packs/postcss-preset-env/dist/index.mjs +++ b/plugin-packs/postcss-preset-env/dist/index.mjs @@ -1 +1 @@ -import s from"autoprefixer";import o from"cssdb";import e from"browserslist";import t from"@csstools/postcss-initial";import i from"postcss-pseudo-class-any-link";import r from"css-blank-pseudo";import a from"postcss-page-break";import p from"@csstools/postcss-cascade-layers";import c from"postcss-attribute-case-insensitive";import n from"postcss-clamp";import l from"@csstools/postcss-color-function";import m from"postcss-color-functional-notation";import u from"@csstools/postcss-color-mix-function";import d from"postcss-custom-media";import f from"postcss-custom-properties";import g from"postcss-custom-selectors";import b from"postcss-dir-pseudo-class";import h from"@csstools/postcss-normalize-display-values";import v from"postcss-double-position-gradients";import N from"@csstools/postcss-exponential-functions";import y from"@csstools/postcss-logical-float-and-clear";import k from"postcss-focus-visible";import w from"postcss-focus-within";import x from"@csstools/postcss-font-format-keywords";import F from"postcss-font-variant";import O from"@csstools/postcss-gamut-mapping";import $ from"postcss-gap-properties";import S from"@csstools/postcss-gradients-interpolation-method";import P from"css-has-pseudo";import C from"postcss-color-hex-alpha";import I from"@csstools/postcss-hwb-function";import B from"@csstools/postcss-ic-unit";import E from"postcss-image-set-function";import A from"@csstools/postcss-is-pseudo-class";import L from"postcss-lab-function";import U from"@csstools/postcss-light-dark-function";import _ from"@csstools/postcss-logical-overflow";import q from"@csstools/postcss-logical-overscroll-behavior";import j from"postcss-logical";import D from"@csstools/postcss-logical-resize";import M from"@csstools/postcss-logical-viewport-units";import z from"@csstools/postcss-media-queries-aspect-ratio-number-values";import R from"@csstools/postcss-media-minmax";import V from"@csstools/postcss-nested-calc";import T from"postcss-nesting";import H from"postcss-selector-not";import W from"@csstools/postcss-oklab-function";import G from"postcss-opacity-percentage";import K from"postcss-overflow-shorthand";import Z from"postcss-replace-overflow-wrap";import Q from"postcss-place";import J from"css-prefers-color-scheme";import X from"@csstools/postcss-progressive-custom-properties";import Y from"postcss-color-rebeccapurple";import ss from"@csstools/postcss-relative-color-syntax";import os from"@csstools/postcss-scope-pseudo-class";import es from"@csstools/postcss-stepped-value-functions";import ts from"@csstools/postcss-text-decoration-shorthand";import is from"@csstools/postcss-trigonometric-functions";import rs from"@csstools/postcss-unset-value";const as={"blank-pseudo-class":"https://github.com/csstools/postcss-plugins/blob/main/plugins/css-blank-pseudo/README.md#browser","focus-visible-pseudo-class":"https://github.com/WICG/focus-visible","focus-within-pseudo-class":"https://github.com/csstools/postcss-plugins/blob/main/plugins/postcss-focus-within/README.md#browser","has-pseudo-class":"https://github.com/csstools/postcss-plugins/blob/main/plugins/css-has-pseudo/README.md#browser","prefers-color-scheme-query":"https://github.com/csstools/postcss-plugins/blob/main/plugins/css-prefers-color-scheme/README.md#browser"},ps=["blank-pseudo-class","focus-visible-pseudo-class","focus-within-pseudo-class","has-pseudo-class","prefers-color-scheme-query"];function logFeaturesList(s,o,e){if(o.debug){e.log("Enabling the following feature(s):");const t=[],i=[];!1!==o.autoprefixer&&i.push(" autoprefixer"),s.forEach((s=>{s.id.startsWith("before")||s.id.startsWith("after")?i.push(` ${s.id} (injected via options)`):i.push(` ${s.id}`),void 0!==as[s.id]&&t.push(s.id)})),i.sort(((s,o)=>s.localeCompare(o))),t.sort(((s,o)=>s.localeCompare(o))),i.forEach((s=>e.log(s))),t.length&&(e.log("These feature(s) need a browser library to work:"),t.forEach((s=>e.log(` ${s}: ${as[s]}`))))}}function initializeSharedOptions(s){if("preserve"in s){const o={};return o.preserve=s.preserve,o}return!1}function clamp(s,o,e){return Math.max(s,Math.min(o,e))}const cs=2,ns=5;function stageFromOptions(s,o){let e=cs;if(void 0===s.stage)return o.log(`Using features from Stage ${e} (default)`),e;if(!1===s.stage)e=ns;else{let o=parseInt(s.stage,10);Number.isNaN(o)&&(o=0),e=clamp(0,o,ns)}return e===ns?o.log('Stage has been disabled, features will be handled via the "features" option.'):o.log(`Using features from Stage ${e}`),e}const ls=Symbol("insertBefore"),ms=Symbol("insertAfter"),us=Symbol("insertOrder"),ds=Symbol("plugin");function getTransformedInsertions(s,o,e){if("insertBefore"!==e&&"insertAfter"!==e)return[];const t="insertBefore"===e?ls:ms,i=[];for(const e in o){if(!Object.hasOwnProperty.call(o,e))continue;if(!s.find((s=>s.id===e)))continue;let r=o[e];Array.isArray(r)||(r=[r]);for(let s=0;sfeatureIsInsertedOrHasAPlugin(s))).sort(((s,o)=>featureIsLess(s,o)))}const ws=["and_chr","and_ff","android","chrome","edge","firefox","ie","ios_saf","op_mini","op_mob","opera","safari","samsung"];function getUnsupportedBrowsersByFeature(s){if(!s)return[];if(!("browser_support"in s))return["> 0%"];const o=[];return ws.forEach((e=>{if("op_mini"===e&&void 0===s.browser_support[e])return void o.push("op_mini all");const t=s.browser_support[e];"string"==typeof t&&xs.test(t)?o.push(`${e} < ${s.browser_support[e]}`):o.push(`${e} >= 1`)})),o}const xs=/^[0-9|.]+$/;function getOptionsForBrowsersByFeature(s,o,e,t,i){switch(o.id){case"is-pseudo-class":return{onComplexSelector:"warning"};case"nesting-rules":if(needsOptionFor(e.find((s=>"is-pseudo-class"===s.id)),s))return i.log('Disabling :is on "nesting-rules" due to lack of browser support.'),{noIsPseudoSelector:!0};return{};case"any-link-pseudo-class":if(s.find((s=>s.startsWith("ie ")||s.startsWith("edge "))))return i.log('Adding area[href] fallbacks for ":any-link" support in Edge and IE.'),{subFeatures:{areaHrefNeedsFixing:!0}};return{};case"logical-properties-and-values":case"float-clear-logical-values":case"logical-resize":case"logical-viewport-units":case"logical-overflow":case"logical-overscroll-behavior":return"logical"in t?t.logical:{};default:return{}}}function needsOptionFor(s,o){const t=getUnsupportedBrowsersByFeature(s),i=e(t,{ignoreUnknownVersions:!0});return!!o.some((s=>i.some((o=>o===s))))}function formatPolyfillableFeature(s){const o=getUnsupportedBrowsersByFeature(s);if(s[ls]||s[ms]){let e=s.id;return e=s.insertBefore?`before-${e}`:`after-${e}`,{browsers:o,vendors_implementations:s.vendors_implementations,plugin:s[ds],id:e,stage:ns+1}}return{browsers:o,vendors_implementations:s.vendors_implementations,plugin:ks.get(s.id),id:s.id,stage:s.stage}}function formatStagedFeature(s,o,e,t,i,r,a){let p,c;return p=getOptionsForBrowsersByFeature(o,t,s,r,a),p=i?Object.assign({},p,i,featureOptions(e,t.id)):Object.assign({},p,featureOptions(e,t.id)),"progressive-custom-properties"!==t.id&&(p.enableProgressiveCustomProperties=!1),"overflow-wrap-property"===t.id&&"preserve"in p&&(p.method=p.preserve?"copy":"replace"),c=t.plugin.postcss&&"function"==typeof t.plugin?t.plugin(p):t.plugin&&t.plugin.default&&"function"==typeof t.plugin.default&&t.plugin.default.postcss?t.plugin.default(p):t.plugin,{browsers:t.browsers,vendors_implementations:t.vendors_implementations,plugin:c,pluginOptions:p,id:t.id}}function featureOptions(s,o){if(!(o in s))return;const e=s[o];return Array.isArray(e)?e[1]:e}function intOrZero(s){const o=parseInt(s,10);return Number.isNaN(o)?0:o}const Fs=new Set(["progressive-custom-properties"]);function listFeatures(s,o,t,i){const r=Object(o.features),a="enableClientSidePolyfills"in o&&o.enableClientSidePolyfills,p=Object(o.insertBefore),c=Object(o.insertAfter),n=o.browsers?void 0:o.env,l=o.browsers,m=clamp(0,intOrZero(o.minimumVendorImplementations),3);m>0&&i.log(`Using features with ${m} or more vendor implementations`);const u=stageFromOptions(o,i),d=prepareFeaturesList([...s,{id:"progressive-custom-properties"}],p,c).map((s=>formatPolyfillableFeature(s))).filter((s=>!!Fs.has(s.id)||(0===m||(!(!s[ls]&&!s[ms])||(m<=s.vendors_implementations||(!0===featureEnabledByOptions(r,s.id)?(i.log(` ${s.id} does not meet the required vendor implementations but has been enabled by options`),!0):(i.log(` ${s.id} with ${s.vendors_implementations} vendor implementations has been disabled`),!1))))))),f=e(l,{env:n,ignoreUnknownVersions:!0}).filter((s=>ws.includes(s.split(" ")[0])));return d.filter((s=>{if(Fs.has(s.id))return!0;const o=s.stage>=u,e=a||!ps.includes(s.id),t=featureEnabledByOptions(r,s.id),p=!1===t,c=!0===t||o&&e;return p?i.log(` ${s.id} has been disabled by options`):o?e||i.log(` ${s.id} has been disabled by "enableClientSidePolyfills: false".`):c?i.log(` ${s.id} does not meet the required stage but has been enabled by options`):i.log(` ${s.id} with stage ${s.stage} has been disabled`),!p&&c})).map((e=>formatStagedFeature(s,f,r,e,t,o,i))).filter((s=>{if(Fs.has(s.id))return!0;const o=featureEnabledByOptions(r,s.id);if(!0===o||!1===o)return o;const t=e(s.browsers,{ignoreUnknownVersions:!0}),a=f.some((s=>t.some((o=>o===s))));return a||i.log(`${s.id} disabled due to browser support`),a}))}function featureEnabledByOptions(s,o){if(!(o in s))return"auto";const e=s[o];return Array.isArray(e)?!0===e[0]||!1!==e[0]&&"auto":Boolean(e)}class Logger{constructor(){this.logs=[]}log(s){this.logs.push(s)}resetLogger(){this.logs.length=0}dumpLogs(s){s&&s.warn(this.logs.join("\n")),this.resetLogger()}}var Os=[{packageName:"css-blank-pseudo",id:"blank-pseudo-class",importName:"postcssBlankPseudo"},{packageName:"css-has-pseudo",id:"has-pseudo-class",importName:"postcssHasPseudo"},{packageName:"css-prefers-color-scheme",id:"prefers-color-scheme-query",importName:"postcssPrefersColorScheme"},{packageName:"postcss-attribute-case-insensitive",id:"case-insensitive-attributes",importName:"postcssAttributeCaseInsensitive"},{packageName:"postcss-clamp",id:"clamp",importName:"postcssClamp"},{packageName:"@csstools/postcss-color-mix-function",id:"color-mix",importName:"postcssColorMixFunction"},{packageName:"@csstools/postcss-color-function",id:"color-function",importName:"postcssColorFunction"},{packageName:"postcss-color-functional-notation",id:"color-functional-notation",importName:"postcssColorFunctionalNotation"},{packageName:"postcss-color-hex-alpha",id:"hexadecimal-alpha-notation",importName:"postcssColorHexAlpha"},{packageName:"postcss-color-rebeccapurple",id:"rebeccapurple-color",importName:"postcssColorRebeccapurple"},{packageName:"postcss-custom-media",id:"custom-media-queries",importName:"postcssCustomMedia"},{packageName:"postcss-custom-properties",id:"custom-properties",importName:"postcssCustomProperties"},{packageName:"postcss-custom-selectors",id:"custom-selectors",importName:"postcssCustomSelectors"},{packageName:"postcss-dir-pseudo-class",id:"dir-pseudo-class",importName:"postcssDirPseudoClass"},{packageName:"postcss-double-position-gradients",id:"double-position-gradients",importName:"postcssDoublePositionGradients"},{packageName:"@csstools/postcss-exponential-functions",id:"exponential-functions",importName:"postcssExponentialFunctions"},{packageName:"postcss-focus-visible",id:"focus-visible-pseudo-class",importName:"postcssFocusVisible"},{packageName:"postcss-focus-within",id:"focus-within-pseudo-class",importName:"postcssFocusWithin"},{packageName:"@csstools/postcss-font-format-keywords",id:"font-format-keywords",importName:"postcssFontFormatKeywords"},{packageName:"postcss-font-variant",id:"font-variant-property",importName:"postcssFontVariant"},{packageName:"@csstools/postcss-gamut-mapping",id:"gamut-mapping",importName:"postcssGamutMapping"},{packageName:"postcss-gap-properties",id:"gap-properties",importName:"postcssGapProperties"},{packageName:"@csstools/postcss-gradients-interpolation-method",id:"gradients-interpolation-method",importName:"postcssGradientsInterpolationMethod"},{packageName:"@csstools/postcss-hwb-function",id:"hwb-function",importName:"postcssHWBFunction"},{packageName:"@csstools/postcss-ic-unit",id:"ic-unit",importName:"postcssICUnit"},{packageName:"postcss-image-set-function",id:"image-set-function",importName:"postcssImageSetFunction"},{packageName:"@csstools/postcss-initial",id:"all-property",importName:"postcssInitial"},{packageName:"@csstools/postcss-is-pseudo-class",id:"is-pseudo-class",importName:"postcssIsPseudoClass"},{packageName:"@csstools/postcss-scope-pseudo-class",id:"scope-pseudo-class",importName:"postcssScopePseudoClass"},{packageName:"postcss-lab-function",id:"lab-function",importName:"postcssLabFunction"},{packageName:"@csstools/postcss-light-dark-function",id:"light-dark-function",importName:"postcssLightDarkFunction"},{packageName:"postcss-logical",id:"logical-properties-and-values",importName:"postcssLogical"},{packageName:"@csstools/postcss-logical-float-and-clear",id:"float-clear-logical-values",importName:"postcssLogicalFloatAndClear"},{packageName:"@csstools/postcss-logical-overflow",id:"logical-overflow",importName:"postcssLogicalOverflow"},{packageName:"@csstools/postcss-logical-overscroll-behavior",id:"logical-overscroll-behavior",importName:"postcssLogicalOverscrollBehavor"},{packageName:"@csstools/postcss-logical-resize",id:"logical-resize",importName:"postcssLogicalResize"},{packageName:"@csstools/postcss-logical-viewport-units",id:"logical-viewport-units",importName:"postcssLogicalViewportUnits"},{packageName:"@csstools/postcss-media-minmax",id:"media-query-ranges",importName:"postcssMediaMinmax"},{packageName:"@csstools/postcss-media-queries-aspect-ratio-number-values",id:"media-queries-aspect-ratio-number-values",importName:"postcssMediaQueriesAspectRatioNumberValues"},{packageName:"postcss-nesting",id:"nesting-rules",importName:"postcssNesting"},{packageName:"@csstools/postcss-normalize-display-values",id:"display-two-values",importName:"postcssNormalizeDisplayValues"},{packageName:"@csstools/postcss-oklab-function",id:"oklab-function",importName:"postcssOKLabFunction"},{packageName:"@csstools/postcss-relative-color-syntax",id:"relative-color-syntax",importName:"postcssRelativeColorSyntax"},{packageName:"postcss-opacity-percentage",id:"opacity-percentage",importName:"postcssOpacityPercentage"},{packageName:"postcss-overflow-shorthand",id:"overflow-property",importName:"postcssOverflowShorthand"},{packageName:"postcss-page-break",id:"break-properties",importName:"postcssPageBreak"},{packageName:"postcss-place",id:"place-properties",importName:"postcssPlace"},{packageName:"postcss-pseudo-class-any-link",id:"any-link-pseudo-class",importName:"postcssPseudoClassAnyLink"},{packageName:"postcss-replace-overflow-wrap",id:"overflow-wrap-property",importName:"postcssReplaceOverflowWrap"},{packageName:"postcss-selector-not",id:"not-pseudo-class",importName:"postcssSelectorNot"},{packageName:"@csstools/postcss-stepped-value-functions",id:"stepped-value-functions",importName:"postcssSteppedValueFunctions"},{packageName:"postcss-system-ui-font-family",importedPackage:"../patch/postcss-system-ui-font-family.mjs",id:"system-ui-font-family",importName:"postcssFontFamilySystemUI"},{packageName:"@csstools/postcss-unset-value",id:"unset-value",importName:"postcssUnsetValue"},{packageName:"@csstools/postcss-cascade-layers",id:"cascade-layers",importName:"postcssCascadeLayers"},{packageName:"@csstools/postcss-trigonometric-functions",id:"trigonometric-functions",importName:"postcssTrigonometricFunctions"},{packageName:"@csstools/postcss-nested-calc",id:"nested-calc",importName:"postcssNestedCalc"},{packageName:"@csstools/postcss-text-decoration-shorthand",id:"text-decoration-shorthand",importName:"postcssTextDecorationShorthand"},{packageName:"@csstools/postcss-progressive-custom-properties",id:"progressive-custom-properties",importName:"postcssProgressiveCustomProperties",omitTypedOptions:!0,omitDocs:!0}];function getPackageNamesToIds(){const s={};return Os.forEach((o=>{s[o.packageName]=o.id})),s}function pluginIdHelp(s,o,e){const t=Os.map((s=>s.id)),i=Os.map((s=>s.packageName)),r=getPackageNamesToIds();s.forEach((s=>{if(t.includes(s))return;const a=[...t.map((o=>[o,levenshteinDistance(s,o)])),...i.map((o=>[r[o],levenshteinDistance(s,o)]))].sort(((s,o)=>s[1]-o[1])).filter((s=>s[1]<10)),p=new Set;for(let s=0;s=3));s++);if(!p.size)return void o.warn(e,`Unknown feature: "${s}", see the list of features https://github.com/csstools/postcss-plugins/blob/main/plugin-packs/postcss-preset-env/FEATURES.md`);let c='"';c+=Array.from(p).join('", "'),c+='"',o.warn(e,`Unknown feature: "${s}", did you mean one of: ${c}`)}))}function levenshteinDistance(s,o){if(!s.length)return o.length;if(!o.length)return s.length;const e=[];for(let t=0;t<=o.length;t++){e[t]=[t];for(let i=1;i<=s.length;i++)e[t][i]=0===t?i:Math.min(e[t-1][i]+1,e[t][i-1]+1,e[t-1][i-1]+(s[i-1]===o[t-1]?0:1))}return e[o.length][s.length]}const creator=e=>{const t=new Logger,i=Object(e),r=Object.keys(Object(i.features)),a=i.browsers?void 0:i.env,p=i.browsers,c=initializeSharedOptions(i),n=listFeatures(o,i,c,t),l=n.map((s=>s.plugin));!1!==i.autoprefixer&&l.push(s(Object.assign({env:a,overrideBrowserslist:p},i.autoprefixer))),logFeaturesList(n,i,t);const internalPlugin=()=>({postcssPlugin:"postcss-preset-env",OnceExit(s,{result:o}){pluginIdHelp(r,s,o),i.debug&&t.dumpLogs(o),t.resetLogger()}});return internalPlugin.postcss=!0,{postcssPlugin:"postcss-preset-env",plugins:[...l,internalPlugin()]}};creator.postcss=!0;export{creator as default}; +import s from"autoprefixer";import o from"cssdb";import e from"browserslist";import t from"@csstools/postcss-initial";import i from"postcss-pseudo-class-any-link";import r from"css-blank-pseudo";import a from"postcss-page-break";import c from"@csstools/postcss-cascade-layers";import p from"postcss-attribute-case-insensitive";import n from"postcss-clamp";import l from"@csstools/postcss-color-function";import m from"postcss-color-functional-notation";import u from"@csstools/postcss-color-mix-function";import d from"postcss-custom-media";import f from"postcss-custom-properties";import g from"postcss-custom-selectors";import b from"postcss-dir-pseudo-class";import h from"@csstools/postcss-normalize-display-values";import v from"postcss-double-position-gradients";import N from"@csstools/postcss-exponential-functions";import y from"@csstools/postcss-logical-float-and-clear";import k from"postcss-focus-visible";import w from"postcss-focus-within";import x from"@csstools/postcss-font-format-keywords";import F from"postcss-font-variant";import O from"@csstools/postcss-gamut-mapping";import $ from"postcss-gap-properties";import S from"@csstools/postcss-gradients-interpolation-method";import P from"css-has-pseudo";import C from"postcss-color-hex-alpha";import I from"@csstools/postcss-hwb-function";import B from"@csstools/postcss-ic-unit";import E from"postcss-image-set-function";import A from"@csstools/postcss-is-pseudo-class";import L from"postcss-lab-function";import U from"@csstools/postcss-light-dark-function";import _ from"@csstools/postcss-logical-overflow";import q from"@csstools/postcss-logical-overscroll-behavior";import j from"postcss-logical";import D from"@csstools/postcss-logical-resize";import M from"@csstools/postcss-logical-viewport-units";import z from"@csstools/postcss-media-queries-aspect-ratio-number-values";import R from"@csstools/postcss-media-minmax";import V from"@csstools/postcss-nested-calc";import T from"postcss-nesting";import H from"postcss-selector-not";import W from"@csstools/postcss-oklab-function";import G from"postcss-opacity-percentage";import K from"postcss-overflow-shorthand";import Z from"postcss-replace-overflow-wrap";import Q from"postcss-place";import J from"css-prefers-color-scheme";import X from"@csstools/postcss-progressive-custom-properties";import Y from"postcss-color-rebeccapurple";import ss from"@csstools/postcss-relative-color-syntax";import os from"@csstools/postcss-scope-pseudo-class";import es from"@csstools/postcss-stepped-value-functions";import ts from"@csstools/postcss-text-decoration-shorthand";import is from"@csstools/postcss-trigonometric-functions";import rs from"@csstools/postcss-unset-value";const as={"blank-pseudo-class":"https://github.com/csstools/postcss-plugins/blob/main/plugins/css-blank-pseudo/README.md#browser","focus-visible-pseudo-class":"https://github.com/WICG/focus-visible","focus-within-pseudo-class":"https://github.com/csstools/postcss-plugins/blob/main/plugins/postcss-focus-within/README.md#browser","has-pseudo-class":"https://github.com/csstools/postcss-plugins/blob/main/plugins/css-has-pseudo/README.md#browser","prefers-color-scheme-query":"https://github.com/csstools/postcss-plugins/blob/main/plugins/css-prefers-color-scheme/README.md#browser"},cs=["blank-pseudo-class","focus-visible-pseudo-class","focus-within-pseudo-class","has-pseudo-class","prefers-color-scheme-query"];function logFeaturesList(s,o,e){if(o.debug){e.log("Enabling the following feature(s):");const t=[],i=[];!1!==o.autoprefixer&&i.push(" autoprefixer"),s.forEach((s=>{s.id.startsWith("before")||s.id.startsWith("after")?i.push(` ${s.id} (injected via options)`):i.push(` ${s.id}`),void 0!==as[s.id]&&t.push(s.id)})),i.sort(((s,o)=>s.localeCompare(o))),t.sort(((s,o)=>s.localeCompare(o))),i.forEach((s=>e.log(s))),t.length&&(e.log("These feature(s) need a browser library to work:"),t.forEach((s=>e.log(` ${s}: ${as[s]}`))))}}function initializeSharedOptions(s){if("preserve"in s){const o={};return o.preserve=s.preserve,o}return!1}function clamp(s,o,e){return Math.max(s,Math.min(o,e))}const ps=2,ns=5;function stageFromOptions(s,o){let e=ps;if(void 0===s.stage)return o.log(`Using features from Stage ${e} (default)`),e;if(!1===s.stage)e=ns;else{let o=parseInt(s.stage,10);Number.isNaN(o)&&(o=0),e=clamp(0,o,ns)}return e===ns?o.log('Stage has been disabled, features will be handled via the "features" option.'):o.log(`Using features from Stage ${e}`),e}const ls=Symbol("insertBefore"),ms=Symbol("insertAfter"),us=Symbol("insertOrder"),ds=Symbol("plugin");function getTransformedInsertions(s,o,e){if("insertBefore"!==e&&"insertAfter"!==e)return[];const t="insertBefore"===e?ls:ms,i=[];for(const e in o){if(!Object.hasOwnProperty.call(o,e))continue;if(!s.find((s=>s.id===e)))continue;let r=o[e];Array.isArray(r)||(r=[r]);for(let s=0;sfeatureIsInsertedOrHasAPlugin(s))).sort(((s,o)=>featureIsLess(s,o)))}const ws=["and_chr","and_ff","android","chrome","edge","firefox","ie","ios_saf","op_mini","op_mob","opera","safari","samsung"];function getUnsupportedBrowsersByFeature(s){if(!s)return[];if(!("browser_support"in s))return["> 0%"];const o=[];return ws.forEach((e=>{if("op_mini"===e&&void 0===s.browser_support[e])return void o.push("op_mini all");const t=s.browser_support[e];"string"==typeof t&&xs.test(t)?o.push(`${e} < ${s.browser_support[e]}`):o.push(`${e} >= 1`)})),o}const xs=/^[0-9|.]+$/;function getOptionsForBrowsersByFeature(s,o,e,t,i){switch(o.id){case"is-pseudo-class":return{onComplexSelector:"warning"};case"nesting-rules":if(needsOptionFor(e.find((s=>"is-pseudo-class"===s.id)),s))return i.log('Disabling :is on "nesting-rules" due to lack of browser support.'),{noIsPseudoSelector:!0};return{};case"any-link-pseudo-class":if(s.find((s=>s.startsWith("ie ")||s.startsWith("edge "))))return i.log('Adding area[href] fallbacks for ":any-link" support in Edge and IE.'),{subFeatures:{areaHrefNeedsFixing:!0}};return{};case"logical-properties-and-values":case"float-clear-logical-values":case"logical-resize":case"logical-viewport-units":case"logical-overflow":case"logical-overscroll-behavior":return"logical"in t?t.logical:{};default:return{}}}function needsOptionFor(s,o){const t=getUnsupportedBrowsersByFeature(s),i=e(t,{ignoreUnknownVersions:!0});return!!o.some((s=>i.some((o=>o===s))))}function formatPolyfillableFeature(s){const o=getUnsupportedBrowsersByFeature(s);if(s[ls]||s[ms]){let e=s.id;return e=s.insertBefore?`before-${e}`:`after-${e}`,{browsers:o,vendors_implementations:s.vendors_implementations,plugin:s[ds],id:e,stage:ns+1}}return{browsers:o,vendors_implementations:s.vendors_implementations,plugin:ks.get(s.id),id:s.id,stage:s.stage}}function formatStagedFeature(s,o,e,t,i,r,a){let c,p;return c=getOptionsForBrowsersByFeature(o,t,s,r,a),c=i?Object.assign({},c,i,featureOptions(e,t.id)):Object.assign({},c,featureOptions(e,t.id)),"progressive-custom-properties"!==t.id&&(c.enableProgressiveCustomProperties=!1),"overflow-wrap-property"===t.id&&"preserve"in c&&(c.method=c.preserve?"copy":"replace"),p=t.plugin.postcss&&"function"==typeof t.plugin?t.plugin(c):t.plugin&&t.plugin.default&&"function"==typeof t.plugin.default&&t.plugin.default.postcss?t.plugin.default(c):t.plugin,{browsers:t.browsers,vendors_implementations:t.vendors_implementations,plugin:p,pluginOptions:c,id:t.id}}function featureOptions(s,o){if(!(o in s))return;const e=s[o];return Array.isArray(e)?e[1]:e}function intOrZero(s){const o=parseInt(s,10);return Number.isNaN(o)?0:o}const Fs=new Set(["progressive-custom-properties"]);function listFeatures(s,o,t,i){const r=Object(o.features),a="enableClientSidePolyfills"in o&&o.enableClientSidePolyfills,c=Object(o.insertBefore),p=Object(o.insertAfter),n=o.browsers?void 0:o.env,l=o.browsers,m=clamp(0,intOrZero(o.minimumVendorImplementations),3);m>0&&i.log(`Using features with ${m} or more vendor implementations`);const u=stageFromOptions(o,i),d=prepareFeaturesList([...s,{id:"progressive-custom-properties"}],c,p).map((s=>formatPolyfillableFeature(s))).filter((s=>!!Fs.has(s.id)||(0===m||(!(!s[ls]&&!s[ms])||(m<=s.vendors_implementations||(!0===featureEnabledByOptions(r,s.id)?(i.log(` ${s.id} does not meet the required vendor implementations but has been enabled by options`),!0):(i.log(` ${s.id} with ${s.vendors_implementations} vendor implementations has been disabled`),!1))))))),f=e(l,{env:n,ignoreUnknownVersions:!0}).filter((s=>ws.includes(s.split(" ")[0])));return d.filter((s=>{if(Fs.has(s.id))return!0;const o=s.stage>=u,e=a||!cs.includes(s.id),t=featureEnabledByOptions(r,s.id),c=!1===t,p=!0===t||o&&e;return c?i.log(` ${s.id} has been disabled by options`):o?e||i.log(` ${s.id} has been disabled by "enableClientSidePolyfills: false".`):p?i.log(` ${s.id} does not meet the required stage but has been enabled by options`):i.log(` ${s.id} with stage ${s.stage} has been disabled`),!c&&p})).map((e=>formatStagedFeature(s,f,r,e,t,o,i))).filter((s=>{if(Fs.has(s.id))return!0;const o=featureEnabledByOptions(r,s.id);if(!0===o||!1===o)return o;const t=e(s.browsers,{ignoreUnknownVersions:!0}),a=f.some((s=>t.some((o=>o===s))));return a||i.log(`${s.id} disabled due to browser support`),a}))}function featureEnabledByOptions(s,o){if(!(o in s))return"auto";const e=s[o];return Array.isArray(e)?!0===e[0]||!1!==e[0]&&"auto":Boolean(e)}class Logger{constructor(){this.logs=[]}log(s){this.logs.push(s)}resetLogger(){this.logs.length=0}emitLogs(s){s&&s.warn(this.logs.join("\n")),this.resetLogger()}}var Os=[{packageName:"css-blank-pseudo",id:"blank-pseudo-class",importName:"postcssBlankPseudo"},{packageName:"css-has-pseudo",id:"has-pseudo-class",importName:"postcssHasPseudo"},{packageName:"css-prefers-color-scheme",id:"prefers-color-scheme-query",importName:"postcssPrefersColorScheme"},{packageName:"postcss-attribute-case-insensitive",id:"case-insensitive-attributes",importName:"postcssAttributeCaseInsensitive"},{packageName:"postcss-clamp",id:"clamp",importName:"postcssClamp"},{packageName:"@csstools/postcss-color-mix-function",id:"color-mix",importName:"postcssColorMixFunction"},{packageName:"@csstools/postcss-color-function",id:"color-function",importName:"postcssColorFunction"},{packageName:"postcss-color-functional-notation",id:"color-functional-notation",importName:"postcssColorFunctionalNotation"},{packageName:"postcss-color-hex-alpha",id:"hexadecimal-alpha-notation",importName:"postcssColorHexAlpha"},{packageName:"postcss-color-rebeccapurple",id:"rebeccapurple-color",importName:"postcssColorRebeccapurple"},{packageName:"postcss-custom-media",id:"custom-media-queries",importName:"postcssCustomMedia"},{packageName:"postcss-custom-properties",id:"custom-properties",importName:"postcssCustomProperties"},{packageName:"postcss-custom-selectors",id:"custom-selectors",importName:"postcssCustomSelectors"},{packageName:"postcss-dir-pseudo-class",id:"dir-pseudo-class",importName:"postcssDirPseudoClass"},{packageName:"postcss-double-position-gradients",id:"double-position-gradients",importName:"postcssDoublePositionGradients"},{packageName:"@csstools/postcss-exponential-functions",id:"exponential-functions",importName:"postcssExponentialFunctions"},{packageName:"postcss-focus-visible",id:"focus-visible-pseudo-class",importName:"postcssFocusVisible"},{packageName:"postcss-focus-within",id:"focus-within-pseudo-class",importName:"postcssFocusWithin"},{packageName:"@csstools/postcss-font-format-keywords",id:"font-format-keywords",importName:"postcssFontFormatKeywords"},{packageName:"postcss-font-variant",id:"font-variant-property",importName:"postcssFontVariant"},{packageName:"@csstools/postcss-gamut-mapping",id:"gamut-mapping",importName:"postcssGamutMapping"},{packageName:"postcss-gap-properties",id:"gap-properties",importName:"postcssGapProperties"},{packageName:"@csstools/postcss-gradients-interpolation-method",id:"gradients-interpolation-method",importName:"postcssGradientsInterpolationMethod"},{packageName:"@csstools/postcss-hwb-function",id:"hwb-function",importName:"postcssHWBFunction"},{packageName:"@csstools/postcss-ic-unit",id:"ic-unit",importName:"postcssICUnit"},{packageName:"postcss-image-set-function",id:"image-set-function",importName:"postcssImageSetFunction"},{packageName:"@csstools/postcss-initial",id:"all-property",importName:"postcssInitial"},{packageName:"@csstools/postcss-is-pseudo-class",id:"is-pseudo-class",importName:"postcssIsPseudoClass"},{packageName:"@csstools/postcss-scope-pseudo-class",id:"scope-pseudo-class",importName:"postcssScopePseudoClass"},{packageName:"postcss-lab-function",id:"lab-function",importName:"postcssLabFunction"},{packageName:"@csstools/postcss-light-dark-function",id:"light-dark-function",importName:"postcssLightDarkFunction"},{packageName:"postcss-logical",id:"logical-properties-and-values",importName:"postcssLogical"},{packageName:"@csstools/postcss-logical-float-and-clear",id:"float-clear-logical-values",importName:"postcssLogicalFloatAndClear"},{packageName:"@csstools/postcss-logical-overflow",id:"logical-overflow",importName:"postcssLogicalOverflow"},{packageName:"@csstools/postcss-logical-overscroll-behavior",id:"logical-overscroll-behavior",importName:"postcssLogicalOverscrollBehavor"},{packageName:"@csstools/postcss-logical-resize",id:"logical-resize",importName:"postcssLogicalResize"},{packageName:"@csstools/postcss-logical-viewport-units",id:"logical-viewport-units",importName:"postcssLogicalViewportUnits"},{packageName:"@csstools/postcss-media-minmax",id:"media-query-ranges",importName:"postcssMediaMinmax"},{packageName:"@csstools/postcss-media-queries-aspect-ratio-number-values",id:"media-queries-aspect-ratio-number-values",importName:"postcssMediaQueriesAspectRatioNumberValues"},{packageName:"postcss-nesting",id:"nesting-rules",importName:"postcssNesting"},{packageName:"@csstools/postcss-normalize-display-values",id:"display-two-values",importName:"postcssNormalizeDisplayValues"},{packageName:"@csstools/postcss-oklab-function",id:"oklab-function",importName:"postcssOKLabFunction"},{packageName:"@csstools/postcss-relative-color-syntax",id:"relative-color-syntax",importName:"postcssRelativeColorSyntax"},{packageName:"postcss-opacity-percentage",id:"opacity-percentage",importName:"postcssOpacityPercentage"},{packageName:"postcss-overflow-shorthand",id:"overflow-property",importName:"postcssOverflowShorthand"},{packageName:"postcss-page-break",id:"break-properties",importName:"postcssPageBreak"},{packageName:"postcss-place",id:"place-properties",importName:"postcssPlace"},{packageName:"postcss-pseudo-class-any-link",id:"any-link-pseudo-class",importName:"postcssPseudoClassAnyLink"},{packageName:"postcss-replace-overflow-wrap",id:"overflow-wrap-property",importName:"postcssReplaceOverflowWrap"},{packageName:"postcss-selector-not",id:"not-pseudo-class",importName:"postcssSelectorNot"},{packageName:"@csstools/postcss-stepped-value-functions",id:"stepped-value-functions",importName:"postcssSteppedValueFunctions"},{packageName:"postcss-system-ui-font-family",importedPackage:"../patch/postcss-system-ui-font-family.mjs",id:"system-ui-font-family",importName:"postcssFontFamilySystemUI"},{packageName:"@csstools/postcss-unset-value",id:"unset-value",importName:"postcssUnsetValue"},{packageName:"@csstools/postcss-cascade-layers",id:"cascade-layers",importName:"postcssCascadeLayers"},{packageName:"@csstools/postcss-trigonometric-functions",id:"trigonometric-functions",importName:"postcssTrigonometricFunctions"},{packageName:"@csstools/postcss-nested-calc",id:"nested-calc",importName:"postcssNestedCalc"},{packageName:"@csstools/postcss-text-decoration-shorthand",id:"text-decoration-shorthand",importName:"postcssTextDecorationShorthand"},{packageName:"@csstools/postcss-progressive-custom-properties",id:"progressive-custom-properties",importName:"postcssProgressiveCustomProperties",omitTypedOptions:!0,omitDocs:!0}];function getPackageNamesToIds(){const s={};return Os.forEach((o=>{s[o.packageName]=o.id})),s}function pluginIdHelp(s,o,e){const t=Os.map((s=>s.id)),i=Os.map((s=>s.packageName)),r=getPackageNamesToIds();s.forEach((s=>{if(t.includes(s))return;const a=[...t.map((o=>[o,levenshteinDistance(s,o)])),...i.map((o=>[r[o],levenshteinDistance(s,o)]))].sort(((s,o)=>s[1]-o[1])).filter((s=>s[1]<10)),c=new Set;for(let s=0;s=3));s++);if(!c.size)return void o.warn(e,`Unknown feature: "${s}", see the list of features https://github.com/csstools/postcss-plugins/blob/main/plugin-packs/postcss-preset-env/FEATURES.md`);let p='"';p+=Array.from(c).join('", "'),p+='"',o.warn(e,`Unknown feature: "${s}", did you mean one of: ${p}`)}))}function levenshteinDistance(s,o){if(!s.length)return o.length;if(!o.length)return s.length;const e=[];for(let t=0;t<=o.length;t++){e[t]=[t];for(let i=1;i<=s.length;i++)e[t][i]=0===t?i:Math.min(e[t-1][i]+1,e[t][i-1]+1,e[t-1][i-1]+(s[i-1]===o[t-1]?0:1))}return e[o.length][s.length]}const creator=e=>{const t=new Logger,i=Object(e),r=Object.keys(Object(i.features)),a=i.browsers?void 0:i.env,c=i.browsers,p=initializeSharedOptions(i),n=listFeatures(o,i,p,t),l=n.map((s=>s.plugin));!1!==i.autoprefixer&&l.push(s(Object.assign({env:a,overrideBrowserslist:c},i.autoprefixer))),logFeaturesList(n,i,t);const internalPlugin=()=>({postcssPlugin:"postcss-preset-env",OnceExit(s,{result:o}){pluginIdHelp(r,s,o),i.debug&&t.emitLogs(o),t.resetLogger()}});return internalPlugin.postcss=!0,{postcssPlugin:"postcss-preset-env",plugins:[...l,internalPlugin()]}};creator.postcss=!0;export{creator as default}; diff --git a/plugin-packs/postcss-preset-env/src/index.ts b/plugin-packs/postcss-preset-env/src/index.ts index 4e03a270f..931ef2a28 100644 --- a/plugin-packs/postcss-preset-env/src/index.ts +++ b/plugin-packs/postcss-preset-env/src/index.ts @@ -1,3 +1,9 @@ +/* eslint-disable @typescript-eslint/no-unsafe-return */ +/* eslint-disable @typescript-eslint/no-unsafe-member-access */ +/* eslint-disable @typescript-eslint/no-unsafe-argument */ +/* eslint-disable @typescript-eslint/no-unsafe-call */ +/* eslint-disable @typescript-eslint/no-unsafe-assignment */ + import autoprefixer from 'autoprefixer'; import cssdb from 'cssdb'; import logFeaturesList from './log/features-list.mjs'; @@ -44,10 +50,10 @@ const creator: PluginCreator = (opts?: pluginOptions) => { pluginIdHelp(featureNamesInOptions, root, result); if (options.debug) { - logger.dumpLogs(result); + logger.emitLogs(result); } - // Always reset the logger, if when debug is false + // Always reset the logger, even when debug is false logger.resetLogger(); }, }; diff --git a/plugin-packs/postcss-preset-env/src/log/helper.mjs b/plugin-packs/postcss-preset-env/src/log/helper.mjs index 62f0ee85e..2e0a76b0a 100644 --- a/plugin-packs/postcss-preset-env/src/log/helper.mjs +++ b/plugin-packs/postcss-preset-env/src/log/helper.mjs @@ -11,7 +11,7 @@ class Logger { this.logs.length = 0; } - dumpLogs(result) { + emitLogs(result) { if (result) { result.warn(this.logs.join('\n')); } diff --git a/plugin-packs/postcss-preset-env/src/test/lib/list-features/array-options.mjs b/plugin-packs/postcss-preset-env/src/test/lib/list-features/array-options.mjs index d7b4ab963..f586c2f23 100644 --- a/plugin-packs/postcss-preset-env/src/test/lib/list-features/array-options.mjs +++ b/plugin-packs/postcss-preset-env/src/test/lib/list-features/array-options.mjs @@ -24,7 +24,7 @@ test('array options [false, ...] - A', () => { ], ); - testLogger.logger.dumpLogs(testLogger); + testLogger.logger.emitLogs(testLogger); assert.deepStrictEqual( testLogger.getLogs(), [ @@ -55,7 +55,7 @@ test('array options [false, ...] - B', () => { ], ); - testLogger.logger.dumpLogs(testLogger); + testLogger.logger.emitLogs(testLogger); assert.deepStrictEqual( testLogger.getLogs(), [ @@ -105,7 +105,7 @@ test('array options [true, ...] - A', () => { ], ); - testLogger.logger.dumpLogs(testLogger); + testLogger.logger.emitLogs(testLogger); assert.deepStrictEqual( testLogger.getLogs(), ['Using features from Stage 2 (default)\n blank-pseudo-class with stage 1 has been disabled\nAdding area[href] fallbacks for ":any-link" support in Edge and IE.'], @@ -151,7 +151,7 @@ test('array options [true, ...] - B', () => { ], ); - testLogger.logger.dumpLogs(testLogger); + testLogger.logger.emitLogs(testLogger); assert.deepStrictEqual( testLogger.getLogs(), ['Using features from Stage 2 (default)\n blank-pseudo-class with stage 1 has been disabled\nAdding area[href] fallbacks for ":any-link" support in Edge and IE.'], @@ -197,7 +197,7 @@ test('array options [true, ...] - C', () => { ], ); - testLogger.logger.dumpLogs(testLogger); + testLogger.logger.emitLogs(testLogger); assert.deepStrictEqual( testLogger.getLogs(), ['Using features from Stage 2 (default)\n blank-pseudo-class with stage 1 has been disabled\nAdding area[href] fallbacks for ":any-link" support in Edge and IE.'], @@ -286,7 +286,7 @@ test('array options - enabled', () => { ], ); - testLogger.logger.dumpLogs(testLogger); + testLogger.logger.emitLogs(testLogger); assert.deepStrictEqual( testLogger.getLogs(), ['Using features from Stage 2 (default)\n blank-pseudo-class with stage 1 has been disabled\nAdding area[href] fallbacks for ":any-link" support in Edge and IE.'], @@ -339,7 +339,7 @@ test('array options - disabled', () => { ], ); - testLogger.logger.dumpLogs(testLogger); + testLogger.logger.emitLogs(testLogger); assert.deepStrictEqual( testLogger.getLogs(), ['Using features from Stage 2 (default)\n any-link-pseudo-class has been disabled by options\n blank-pseudo-class with stage 1 has been disabled'], @@ -368,7 +368,7 @@ test('array options - disabled - B', () => { ], ); - testLogger.logger.dumpLogs(testLogger); + testLogger.logger.emitLogs(testLogger); assert.deepStrictEqual( testLogger.getLogs(), ['Using features from Stage 2 (default)\n blank-pseudo-class with stage 1 has been disabled\nAdding area[href] fallbacks for ":any-link" support in Edge and IE.\nany-link-pseudo-class disabled due to browser support'], diff --git a/plugin-packs/postcss-preset-env/src/test/lib/list-features/client-side.mjs b/plugin-packs/postcss-preset-env/src/test/lib/list-features/client-side.mjs index 721b9c473..dcd869ce5 100644 --- a/plugin-packs/postcss-preset-env/src/test/lib/list-features/client-side.mjs +++ b/plugin-packs/postcss-preset-env/src/test/lib/list-features/client-side.mjs @@ -37,7 +37,7 @@ assert.deepStrictEqual( ], ); -testLogger.logger.dumpLogs(testLogger); +testLogger.logger.emitLogs(testLogger); assert.deepStrictEqual( testLogger.getLogs(), [ @@ -91,7 +91,7 @@ assert.deepStrictEqual( ], ); -testLogger.logger.dumpLogs(testLogger); +testLogger.logger.emitLogs(testLogger); assert.deepStrictEqual( testLogger.getLogs(), [ diff --git a/plugin-packs/postcss-preset-env/src/test/lib/list-features/no-options.mjs b/plugin-packs/postcss-preset-env/src/test/lib/list-features/no-options.mjs index fb68f8362..aaeab2c2d 100644 --- a/plugin-packs/postcss-preset-env/src/test/lib/list-features/no-options.mjs +++ b/plugin-packs/postcss-preset-env/src/test/lib/list-features/no-options.mjs @@ -37,7 +37,7 @@ assert.deepStrictEqual( ], ); -testLogger.logger.dumpLogs(testLogger); +testLogger.logger.emitLogs(testLogger); assert.deepStrictEqual( testLogger.getLogs(), [ diff --git a/plugin-packs/postcss-preset-env/src/test/lib/list-features/preserve.mjs b/plugin-packs/postcss-preset-env/src/test/lib/list-features/preserve.mjs index 0304d71d2..49481c38e 100644 --- a/plugin-packs/postcss-preset-env/src/test/lib/list-features/preserve.mjs +++ b/plugin-packs/postcss-preset-env/src/test/lib/list-features/preserve.mjs @@ -36,7 +36,7 @@ assert.deepStrictEqual( ], ); -testLogger.logger.dumpLogs(testLogger); +testLogger.logger.emitLogs(testLogger); assert.deepStrictEqual( testLogger.getLogs(), [ @@ -78,7 +78,7 @@ assert.deepStrictEqual( ], ); -testLogger.logger.dumpLogs(testLogger); +testLogger.logger.emitLogs(testLogger); assert.deepStrictEqual( testLogger.getLogs(), [ diff --git a/plugin-packs/postcss-preset-env/src/test/lib/list-features/stage-0.mjs b/plugin-packs/postcss-preset-env/src/test/lib/list-features/stage-0.mjs index 15dcd616f..5cbd7479e 100644 --- a/plugin-packs/postcss-preset-env/src/test/lib/list-features/stage-0.mjs +++ b/plugin-packs/postcss-preset-env/src/test/lib/list-features/stage-0.mjs @@ -35,7 +35,7 @@ assert.deepStrictEqual( ], ); -testLogger.logger.dumpLogs(testLogger); +testLogger.logger.emitLogs(testLogger); assert.deepStrictEqual( testLogger.getLogs(), [ diff --git a/plugin-packs/postcss-preset-env/src/test/lib/list-features/vendor-implementations.mjs b/plugin-packs/postcss-preset-env/src/test/lib/list-features/vendor-implementations.mjs index 4bf628586..389fc2c21 100644 --- a/plugin-packs/postcss-preset-env/src/test/lib/list-features/vendor-implementations.mjs +++ b/plugin-packs/postcss-preset-env/src/test/lib/list-features/vendor-implementations.mjs @@ -35,7 +35,7 @@ assert.deepStrictEqual( ], ); -testLogger.logger.dumpLogs(testLogger); +testLogger.logger.emitLogs(testLogger); assert.deepStrictEqual( testLogger.getLogs(), [ @@ -89,7 +89,7 @@ assert.deepStrictEqual( ], ); -testLogger.logger.dumpLogs(testLogger); +testLogger.logger.emitLogs(testLogger); assert.deepStrictEqual( testLogger.getLogs(), [ @@ -157,7 +157,7 @@ assert.deepStrictEqual( ], ); -testLogger.logger.dumpLogs(testLogger); +testLogger.logger.emitLogs(testLogger); assert.deepStrictEqual( testLogger.getLogs(), [ diff --git a/plugin-packs/postcss-preset-env/src/test/lib/stage.mjs b/plugin-packs/postcss-preset-env/src/test/lib/stage.mjs index a0f819ea7..75be9ee68 100644 --- a/plugin-packs/postcss-preset-env/src/test/lib/stage.mjs +++ b/plugin-packs/postcss-preset-env/src/test/lib/stage.mjs @@ -10,7 +10,7 @@ assert.deepStrictEqual( 4, ); -testLogger.logger.dumpLogs(testLogger); +testLogger.logger.emitLogs(testLogger); assert.deepStrictEqual( testLogger.getLogs(), ['Using features from Stage 4'], @@ -22,7 +22,7 @@ assert.deepStrictEqual( 4, ); -testLogger.logger.dumpLogs(testLogger); +testLogger.logger.emitLogs(testLogger); assert.deepStrictEqual( testLogger.getLogs(), ['Using features from Stage 4'], @@ -34,7 +34,7 @@ assert.deepStrictEqual( 0, ); -testLogger.logger.dumpLogs(testLogger); +testLogger.logger.emitLogs(testLogger); assert.deepStrictEqual( testLogger.getLogs(), ['Using features from Stage 0'], @@ -46,7 +46,7 @@ assert.deepStrictEqual( OUT_OF_RANGE_STAGE, ); -testLogger.logger.dumpLogs(testLogger); +testLogger.logger.emitLogs(testLogger); assert.deepStrictEqual( testLogger.getLogs(), ['Stage has been disabled, features will be handled via the "features" option.'], @@ -58,7 +58,7 @@ assert.deepStrictEqual( 0, ); -testLogger.logger.dumpLogs(testLogger); +testLogger.logger.emitLogs(testLogger); assert.deepStrictEqual( testLogger.getLogs(), ['Using features from Stage 0'], @@ -70,7 +70,7 @@ assert.deepStrictEqual( 2, ); -testLogger.logger.dumpLogs(testLogger); +testLogger.logger.emitLogs(testLogger); assert.deepStrictEqual( testLogger.getLogs(), ['Using features from Stage 2 (default)'], @@ -82,7 +82,7 @@ assert.deepStrictEqual( OUT_OF_RANGE_STAGE, ); -testLogger.logger.dumpLogs(testLogger); +testLogger.logger.emitLogs(testLogger); assert.deepStrictEqual( testLogger.getLogs(), ['Stage has been disabled, features will be handled via the "features" option.'], diff --git a/plugin-packs/postcss-preset-env/tsconfig.json b/plugin-packs/postcss-preset-env/tsconfig.json index e0d06239c..ef293b55b 100644 --- a/plugin-packs/postcss-preset-env/tsconfig.json +++ b/plugin-packs/postcss-preset-env/tsconfig.json @@ -2,7 +2,8 @@ "extends": "../../tsconfig.json", "compilerOptions": { "outDir": "dist", - "declarationDir": "." + "declarationDir": ".", + "allowJs": true, }, "include": ["./src/**/*"], "exclude": ["dist"], diff --git a/plugins/css-blank-pseudo/dist/browser-global.js.map b/plugins/css-blank-pseudo/dist/browser-global.js.map index 61fdb22f1..56996b0a1 100644 --- a/plugins/css-blank-pseudo/dist/browser-global.js.map +++ b/plugins/css-blank-pseudo/dist/browser-global.js.map @@ -1 +1 @@ -{"version":3,"file":"browser-global.js","sources":["../src/is-valid-replacement.mjs","../src/browser.js","../src/browser-global.js"],"sourcesContent":["const INVALID_SELECTOR_CHAR = [\n\t' ', // Can't use child selector\n\t'>', // Can't use direct child selector\n\t'~', // Can't use sibling selector\n\t':', // Can't use pseudo selector\n\t'+', // Can't use adjacent selector\n\t'@', // Can't use at\n\t'#', // Can't use id selector\n\t'(', // Can't use parenthesis\n\t')', // Can't use parenthesis\n];\n\nexport default function isValidReplacement(selector) {\n\tlet isValid = true;\n\n\t// Purposely archaic so it's interoperable in old browsers\n\tfor (let i = 0, length = INVALID_SELECTOR_CHAR.length; i < length && isValid; i++) {\n\t\tif (selector.indexOf(INVALID_SELECTOR_CHAR[i]) > -1) {\n\t\t\tisValid = false;\n\t\t}\n\t}\n\n\treturn isValid;\n}\n","/* global document,window,self,MutationObserver */\nimport isValidReplacement from './is-valid-replacement.mjs';\n\nconst CSS_CLASS_LOADED = 'js-blank-pseudo';\n\n// form control elements selector\nfunction isFormControlElement(element) {\n\tif (element.nodeName === 'INPUT' || element.nodeName === 'SELECT' || element.nodeName === 'TEXTAREA') {\n\t\treturn true;\n\t}\n\n\treturn false;\n}\n\nfunction createNewEvent(eventName) {\n\tlet event;\n\n\tif (typeof(Event) === 'function') {\n\t\tevent = new Event(eventName, { bubbles: true });\n\t} else {\n\t\tevent = document.createEvent('Event');\n\t\tevent.initEvent(eventName, true, false);\n\t}\n\n\treturn event;\n}\n\nfunction generateHandler(replaceWith) {\n\tlet selector;\n\tlet remove;\n\tlet add;\n\n\tif (replaceWith[0] === '.') {\n\t\tselector = replaceWith.slice(1);\n\t\tremove = (el) => el.classList.remove(selector);\n\t\tadd = (el) => el.classList.add(selector);\n\t} else {\n\t\t// A bit naive\n\t\tselector = replaceWith.slice(1, -1);\n\t\tremove = (el) => el.removeAttribute(selector, '');\n\t\tadd = (el) => el.setAttribute(selector, '');\n\t}\n\n\treturn function handleInputOrChangeEvent(event) {\n\t\tconst element = event.target;\n\t\tif (!isFormControlElement(element)) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst isSelect = element.nodeName === 'SELECT';\n\t\tconst hasValue = isSelect\n\t\t\t? !!element.options[element.selectedIndex]?.value\n\t\t\t: !!element.value;\n\n\t\tif (hasValue) {\n\t\t\tremove(element);\n\t\t} else {\n\t\t\tadd(element);\n\t\t}\n\t};\n}\n\n// observe changes to the \"selected\" property on an HTML Element\nfunction observeSelectedOfHTMLElement(HTMLElement) {\n\tconst descriptor = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'selected');\n\tconst nativeSet = descriptor.set;\n\n\tdescriptor.set = function set(value) { // eslint-disable-line no-unused-vars\n\t\tnativeSet.apply(this, arguments);\n\n\t\tconst event = createNewEvent('change');\n\t\tthis.parentElement.dispatchEvent(event);\n\t};\n\n\tObject.defineProperty(HTMLElement.prototype, 'selected', descriptor);\n}\n\n// observe changes to the \"value\" property on an HTML Element\nfunction observeValueOfHTMLElement(HTMLElement, handler) {\n\tconst descriptor = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'value');\n\tconst nativeSet = descriptor.set;\n\n\tdescriptor.set = function set() {\n\t\tnativeSet.apply(this, arguments);\n\t\thandler({ target: this });\n\t};\n\n\tObject.defineProperty(HTMLElement.prototype, 'value', descriptor);\n}\n\nexport default function cssBlankPseudoInit(opts) {\n\t// configuration\n\tconst options = {\n\t\tforce: false,\n\t\treplaceWith: '[blank]',\n\t};\n\n\tif (typeof opts !== 'undefined' && 'force' in opts) {\n\t\toptions.force = opts.force;\n\t}\n\n\tif (typeof opts !== 'undefined' && 'replaceWith' in opts) {\n\t\toptions.replaceWith = opts.replaceWith;\n\t}\n\n\tif (!isValidReplacement(options.replaceWith)) {\n\t\tthrow new Error(`${options.replaceWith} is not a valid replacement since it can't be applied to single elements.`);\n\t}\n\n\ttry {\n\t\tdocument.querySelector(':blank');\n\n\t\tif (!options.force) {\n\t\t\treturn;\n\t\t}\n\t} catch (ignoredError) { /* do nothing and continue */ }\n\n\tconst handler = generateHandler(options.replaceWith);\n\tconst bindEvents = () => {\n\t\tif (document.body) {\n\t\t\tdocument.body.addEventListener('change', handler);\n\t\t\tdocument.body.addEventListener('input', handler);\n\t\t}\n\t};\n\tconst updateAllCandidates = () => {\n\t\tArray.prototype.forEach.call(\n\t\t\tdocument.querySelectorAll('input, select, textarea'),\n\t\t\tnode => {\n\t\t\t\thandler({ target: node });\n\t\t\t},\n\t\t);\n\t};\n\n\tif (document.body) {\n\t\tbindEvents();\n\t} else {\n\t\twindow.addEventListener('load', bindEvents);\n\t}\n\n\tif (document.documentElement.className.indexOf(CSS_CLASS_LOADED) === -1) {\n\t\tdocument.documentElement.className += ` ${CSS_CLASS_LOADED}`;\n\t}\n\n\tobserveValueOfHTMLElement(self.HTMLInputElement, handler);\n\tobserveValueOfHTMLElement(self.HTMLSelectElement, handler);\n\tobserveValueOfHTMLElement(self.HTMLTextAreaElement, handler);\n\tobserveSelectedOfHTMLElement(self.HTMLOptionElement);\n\n\t// conditionally update all form control elements\n\tupdateAllCandidates();\n\n\tif (typeof self.MutationObserver !== 'undefined') {\n\t\t// conditionally observe added or unobserve removed form control elements\n\t\tnew MutationObserver(mutationsList => {\n\t\t\tmutationsList.forEach(mutation => {\n\t\t\t\tArray.prototype.forEach.call(\n\t\t\t\t\tmutation.addedNodes || [],\n\t\t\t\t\tnode => {\n\t\t\t\t\t\tif (node.nodeType === 1 && isFormControlElement(node)) {\n\t\t\t\t\t\t\thandler({ target: node });\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t);\n\t\t\t});\n\t\t}).observe(document, { childList: true, subtree: true });\n\t} else {\n\t\tconst handleOnLoad = () => updateAllCandidates();\n\n\t\twindow.addEventListener('load', handleOnLoad);\n\t\twindow.addEventListener('DOMContentLoaded', handleOnLoad);\n\t}\n}\n","/* global self,window */\nimport { default as cssBlankPseudoInit } from './browser';\n\n(function (global) {\n\tglobal.cssBlankPseudoInit = cssBlankPseudoInit;\n}('object' === typeof window && window || 'object' === typeof self && self || {}));\n"],"names":["INVALID_SELECTOR_CHAR","isValidReplacement","selector","isValid","i","length","indexOf","CSS_CLASS_LOADED","isFormControlElement","element","nodeName","createNewEvent","eventName","event","Event","bubbles","document","createEvent","initEvent","observeValueOfHTMLElement","HTMLElement","handler","descriptor","Object","getOwnPropertyDescriptor","prototype","nativeSet","set","apply","this","arguments","target","defineProperty","cssBlankPseudoInit","opts","options","force","replaceWith","Error","querySelector","ignoredError","remove","add","slice","el","classList","removeAttribute","setAttribute","handleInputOrChangeEvent","_element$options$elem","selectedIndex","value","bindEvents","body","addEventListener","updateAllCandidates","Array","forEach","call","querySelectorAll","node","window","documentElement","className","self","HTMLInputElement","HTMLSelectElement","HTMLTextAreaElement","HTMLOptionElement","parentElement","dispatchEvent","MutationObserver","mutationsList","mutation","addedNodes","nodeType","observe","childList","subtree","handleOnLoad"],"mappings":"YAAA,IAAMA,EAAwB,CAC7B,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,KAGc,SAASC,mBAAmBC,GAI1C,IAHA,IAAIC,GAAU,EAGLC,EAAI,EAAGC,EAASL,EAAsBK,OAAQD,EAAIC,GAAUF,EAASC,IACzEF,EAASI,QAAQN,EAAsBI,KAAO,IACjDD,GAAU,GAIZ,OAAOA,CACR,CCpBA,IAAMI,EAAmB,kBAGzB,SAASC,qBAAqBC,GAC7B,MAAyB,UAArBA,EAAQC,UAA6C,WAArBD,EAAQC,UAA8C,aAArBD,EAAQC,QAK9E,CAEA,SAASC,eAAeC,GACvB,IAAIC,EASJ,MAPsB,mBAAXC,MACVD,EAAQ,IAA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Y,OAASxB,GAAqB,EAEhDM,OAAOP,iBAAiB,OAAQyB,GAChClB,OAAOP,iBAAiB,mBAAoByB,EAC7C,CACD,ECtKE,iBAAoBlB,QAAUA,QAAU,iBAAoBG,MAAQA,MAAQ,IADtE/B,mBAAqBA"} \ No newline at end of file +{"version":3,"file":"browser-global.js","sources":["../src/is-valid-replacement.mjs","../src/browser.js","../src/browser-global.js"],"sourcesContent":["const INVALID_SELECTOR_CHAR = [\n\t' ', // Can't use child selector\n\t'>', // Can't use direct child selector\n\t'~', // Can't use sibling selector\n\t':', // Can't use pseudo selector\n\t'+', // Can't use adjacent selector\n\t'@', // Can't use at\n\t'#', // Can't use id selector\n\t'(', // Can't use parenthesis\n\t')', // Can't use parenthesis\n];\n\nexport default function isValidReplacement(selector) {\n\tlet isValid = true;\n\n\t// Purposely archaic so it's interoperable in old browsers\n\tfor (let i = 0, length = INVALID_SELECTOR_CHAR.length; i < length && isValid; i++) {\n\t\tif (selector.indexOf(INVALID_SELECTOR_CHAR[i]) > -1) {\n\t\t\tisValid = false;\n\t\t}\n\t}\n\n\treturn isValid;\n}\n","import isValidReplacement from './is-valid-replacement.mjs';\n\nconst CSS_CLASS_LOADED = 'js-blank-pseudo';\n\n// form control elements selector\nfunction isFormControlElement(element) {\n\tif (element.nodeName === 'INPUT' || element.nodeName === 'SELECT' || element.nodeName === 'TEXTAREA') {\n\t\treturn true;\n\t}\n\n\treturn false;\n}\n\nfunction createNewEvent(eventName) {\n\tlet event;\n\n\tif (typeof(Event) === 'function') {\n\t\tevent = new Event(eventName, { bubbles: true });\n\t} else {\n\t\tevent = document.createEvent('Event');\n\t\tevent.initEvent(eventName, true, false);\n\t}\n\n\treturn event;\n}\n\nfunction generateHandler(replaceWith) {\n\tlet selector;\n\tlet remove;\n\tlet add;\n\n\tif (replaceWith[0] === '.') {\n\t\tselector = replaceWith.slice(1);\n\t\tremove = (el) => el.classList.remove(selector);\n\t\tadd = (el) => el.classList.add(selector);\n\t} else {\n\t\t// A bit naive\n\t\tselector = replaceWith.slice(1, -1);\n\t\tremove = (el) => el.removeAttribute(selector, '');\n\t\tadd = (el) => el.setAttribute(selector, '');\n\t}\n\n\treturn function handleInputOrChangeEvent(event) {\n\t\tconst element = event.target;\n\t\tif (!isFormControlElement(element)) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst isSelect = element.nodeName === 'SELECT';\n\t\tconst hasValue = isSelect\n\t\t\t? !!element.options[element.selectedIndex]?.value\n\t\t\t: !!element.value;\n\n\t\tif (hasValue) {\n\t\t\tremove(element);\n\t\t} else {\n\t\t\tadd(element);\n\t\t}\n\t};\n}\n\n// observe changes to the \"selected\" property on an HTML Element\nfunction observeSelectedOfHTMLElement(HTMLElement) {\n\tconst descriptor = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'selected');\n\tconst nativeSet = descriptor.set;\n\n\tdescriptor.set = function set(value) { // eslint-disable-line no-unused-vars\n\t\tnativeSet.apply(this, arguments);\n\n\t\tconst event = createNewEvent('change');\n\t\tthis.parentElement.dispatchEvent(event);\n\t};\n\n\tObject.defineProperty(HTMLElement.prototype, 'selected', descriptor);\n}\n\n// observe changes to the \"value\" property on an HTML Element\nfunction observeValueOfHTMLElement(HTMLElement, handler) {\n\tconst descriptor = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'value');\n\tconst nativeSet = descriptor.set;\n\n\tdescriptor.set = function set() {\n\t\tnativeSet.apply(this, arguments);\n\t\thandler({ target: this });\n\t};\n\n\tObject.defineProperty(HTMLElement.prototype, 'value', descriptor);\n}\n\nexport default function cssBlankPseudoInit(opts) {\n\t// configuration\n\tconst options = {\n\t\tforce: false,\n\t\treplaceWith: '[blank]',\n\t};\n\n\tif (typeof opts !== 'undefined' && 'force' in opts) {\n\t\toptions.force = opts.force;\n\t}\n\n\tif (typeof opts !== 'undefined' && 'replaceWith' in opts) {\n\t\toptions.replaceWith = opts.replaceWith;\n\t}\n\n\tif (!isValidReplacement(options.replaceWith)) {\n\t\tthrow new Error(`${options.replaceWith} is not a valid replacement since it can't be applied to single elements.`);\n\t}\n\n\ttry {\n\t\tdocument.querySelector(':blank');\n\n\t\tif (!options.force) {\n\t\t\treturn;\n\t\t}\n\t} catch (_) {}\n\n\tconst handler = generateHandler(options.replaceWith);\n\tconst bindEvents = () => {\n\t\tif (document.body) {\n\t\t\tdocument.body.addEventListener('change', handler);\n\t\t\tdocument.body.addEventListener('input', handler);\n\t\t}\n\t};\n\tconst updateAllCandidates = () => {\n\t\tArray.prototype.forEach.call(\n\t\t\tdocument.querySelectorAll('input, select, textarea'),\n\t\t\tnode => {\n\t\t\t\thandler({ target: node });\n\t\t\t},\n\t\t);\n\t};\n\n\tif (document.body) {\n\t\tbindEvents();\n\t} else {\n\t\twindow.addEventListener('load', bindEvents);\n\t}\n\n\tif (document.documentElement.className.indexOf(CSS_CLASS_LOADED) === -1) {\n\t\tdocument.documentElement.className += ` ${CSS_CLASS_LOADED}`;\n\t}\n\n\tobserveValueOfHTMLElement(self.HTMLInputElement, handler);\n\tobserveValueOfHTMLElement(self.HTMLSelectElement, handler);\n\tobserveValueOfHTMLElement(self.HTMLTextAreaElement, handler);\n\tobserveSelectedOfHTMLElement(self.HTMLOptionElement);\n\n\t// conditionally update all form control elements\n\tupdateAllCandidates();\n\n\tif (typeof self.MutationObserver !== 'undefined') {\n\t\t// conditionally observe added or unobserve removed form control elements\n\t\tnew MutationObserver(mutationsList => {\n\t\t\tmutationsList.forEach(mutation => {\n\t\t\t\tArray.prototype.forEach.call(\n\t\t\t\t\tmutation.addedNodes || [],\n\t\t\t\t\tnode => {\n\t\t\t\t\t\tif (node.nodeType === 1 && isFormControlElement(node)) {\n\t\t\t\t\t\t\thandler({ target: node });\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t);\n\t\t\t});\n\t\t}).observe(document, { childList: true, subtree: true });\n\t} else {\n\t\tconst handleOnLoad = () => updateAllCandidates();\n\n\t\twindow.addEventListener('load', handleOnLoad);\n\t\twindow.addEventListener('DOMContentLoaded', handleOnLoad);\n\t}\n}\n","import { default as cssBlankPseudoInit } from './browser';\n\n(function (global) {\n\tglobal.cssBlankPseudoInit = cssBlankPseudoInit;\n}('object' === typeof window && window || 'object' === typeof self && self || {}));\n"],"names":["INVALID_SELECTOR_CHAR","isValidReplacement","selector","isValid","i","length","indexOf","CSS_CLASS_LOADED","isFormControlElement","element","nodeName","createNewEvent","eventName","event","Event","bubbles","document","createEvent","initEvent","observeValueOfHTMLElement","HTMLElement","handler","descriptor","Object","getOwnPropertyDescriptor","prototype","nativeSet","set","apply","this","arguments","target","defineProperty","cssBlankPseudoInit","opts","options","force","replaceWith","Error","querySelector","_","remove","add","slice","el","classList","removeAttribute","setAttribute","handleInputOrChangeEvent","_element$options$elem","selectedIndex","value","bindEvents","body","addEventListener","updateAllCandidates","Array","forEach","call","querySelectorAll","node","window","documentElement","className","self","HTMLInputElement","HTMLSelectElement","HTMLTextAreaElement","HTMLOptionElement","parentElement","dispatchEvent","MutationObserver","mutationsList","mutation","addedNodes","nodeType","observe","childList","subtree","handleOnLoad"],"mappings":"YAAA,IAAMA,EAAwB,CAC7B,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,KAGc,SAASC,mBAAmBC,GAI1C,IAHA,IAAIC,GAAU,EAGLC,EAAI,EAAGC,EAASL,EAAsBK,OAAQD,EAAIC,GAAUF,EAASC,IACzEF,EAASI,QAAQN,EAAsBI,KAAO,IACjDD,GAAU,GAIZ,OAAOA,CACR,CCrBA,IAAMI,EAAmB,kBAGzB,SAASC,qBAAqBC,GAC7B,MAAyB,UAArBA,EAAQC,UAA6C,WAArBD,EAAQC,UAA8C,aAArBD,EAAQC,QAK9E,CAEA,SAASC,eAAeC,GACvB,IAAIC,EASJ,MAPsB,mBAAXC,MACVD,EAAQ,IAAIC,MAAMF,EAAW,CAAEG,SAAS,KAExCF,EAAQG,SAASC,YAAY,UACvBC,UAAUN,GAAW,GAAM,GAG3BC,CACR,CAqDA,SAASM,0BAA0BC,EAAaC,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AoBG,MAAQA,MAAQ,IADtE/B,mBAAqBA"} \ No newline at end of file diff --git a/plugins/css-blank-pseudo/dist/browser.cjs.map b/plugins/css-blank-pseudo/dist/browser.cjs.map index fb855fe34..507dbbb7e 100644 --- a/plugins/css-blank-pseudo/dist/browser.cjs.map +++ b/plugins/css-blank-pseudo/dist/browser.cjs.map @@ -1 +1 @@ -{"version":3,"file":"browser.cjs","sources":["../src/is-valid-replacement.mjs","../src/browser.js"],"sourcesContent":["const INVALID_SELECTOR_CHAR = [\n\t' ', // Can't use child selector\n\t'>', // Can't use direct child selector\n\t'~', // Can't use sibling selector\n\t':', // Can't use pseudo selector\n\t'+', // Can't use adjacent selector\n\t'@', // Can't use at\n\t'#', // Can't use id selector\n\t'(', // Can't use parenthesis\n\t')', // Can't use parenthesis\n];\n\nexport default function isValidReplacement(selector) {\n\tlet isValid = true;\n\n\t// Purposely archaic so it's interoperable in old browsers\n\tfor (let i = 0, length = INVALID_SELECTOR_CHAR.length; i < length && isValid; i++) {\n\t\tif (selector.indexOf(INVALID_SELECTOR_CHAR[i]) > -1) {\n\t\t\tisValid = false;\n\t\t}\n\t}\n\n\treturn isValid;\n}\n","/* global document,window,self,MutationObserver */\nimport isValidReplacement from './is-valid-replacement.mjs';\n\nconst CSS_CLASS_LOADED = 'js-blank-pseudo';\n\n// form control elements selector\nfunction isFormControlElement(element) {\n\tif (element.nodeName === 'INPUT' || element.nodeName === 'SELECT' || element.nodeName === 'TEXTAREA') {\n\t\treturn true;\n\t}\n\n\treturn false;\n}\n\nfunction createNewEvent(eventName) {\n\tlet event;\n\n\tif (typeof(Event) === 'function') {\n\t\tevent = new Event(eventName, { bubbles: true });\n\t} else {\n\t\tevent = document.createEvent('Event');\n\t\tevent.initEvent(eventName, true, false);\n\t}\n\n\treturn event;\n}\n\nfunction generateHandler(replaceWith) {\n\tlet selector;\n\tlet remove;\n\tlet add;\n\n\tif (replaceWith[0] === '.') {\n\t\tselector = replaceWith.slice(1);\n\t\tremove = (el) => el.classList.remove(selector);\n\t\tadd = (el) => el.classList.add(selector);\n\t} else {\n\t\t// A bit naive\n\t\tselector = replaceWith.slice(1, -1);\n\t\tremove = (el) => el.removeAttribute(selector, '');\n\t\tadd = (el) => el.setAttribute(selector, '');\n\t}\n\n\treturn function handleInputOrChangeEvent(event) {\n\t\tconst element = event.target;\n\t\tif (!isFormControlElement(element)) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst isSelect = element.nodeName === 'SELECT';\n\t\tconst hasValue = isSelect\n\t\t\t? !!element.options[element.selectedIndex]?.value\n\t\t\t: !!element.value;\n\n\t\tif (hasValue) {\n\t\t\tremove(element);\n\t\t} else {\n\t\t\tadd(element);\n\t\t}\n\t};\n}\n\n// observe changes to the \"selected\" property on an HTML Element\nfunction observeSelectedOfHTMLElement(HTMLElement) {\n\tconst descriptor = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'selected');\n\tconst nativeSet = descriptor.set;\n\n\tdescriptor.set = function set(value) { // eslint-disable-line no-unused-vars\n\t\tnativeSet.apply(this, arguments);\n\n\t\tconst event = createNewEvent('change');\n\t\tthis.parentElement.dispatchEvent(event);\n\t};\n\n\tObject.defineProperty(HTMLElement.prototype, 'selected', descriptor);\n}\n\n// observe changes to the \"value\" property on an HTML Element\nfunction observeValueOfHTMLElement(HTMLElement, handler) {\n\tconst descriptor = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'value');\n\tconst nativeSet = descriptor.set;\n\n\tdescriptor.set = function set() {\n\t\tnativeSet.apply(this, arguments);\n\t\thandler({ target: this });\n\t};\n\n\tObject.defineProperty(HTMLElement.prototype, 'value', descriptor);\n}\n\nexport default function cssBlankPseudoInit(opts) {\n\t// configuration\n\tconst options = {\n\t\tforce: false,\n\t\treplaceWith: '[blank]',\n\t};\n\n\tif (typeof opts !== 'undefined' && 'force' in opts) {\n\t\toptions.force = opts.force;\n\t}\n\n\tif (typeof opts !== 'undefined' && 'replaceWith' in opts) {\n\t\toptions.replaceWith = opts.replaceWith;\n\t}\n\n\tif (!isValidReplacement(options.replaceWith)) {\n\t\tthrow new Error(`${options.replaceWith} is not a valid replacement since it can't be applied to single elements.`);\n\t}\n\n\ttry {\n\t\tdocument.querySelector(':blank');\n\n\t\tif (!options.force) {\n\t\t\treturn;\n\t\t}\n\t} catch (ignoredError) { /* do nothing and continue */ }\n\n\tconst handler = generateHandler(options.replaceWith);\n\tconst bindEvents = () => {\n\t\tif (document.body) {\n\t\t\tdocument.body.addEventListener('change', handler);\n\t\t\tdocument.body.addEventListener('input', handler);\n\t\t}\n\t};\n\tconst updateAllCandidates = () => {\n\t\tArray.prototype.forEach.call(\n\t\t\tdocument.querySelectorAll('input, select, textarea'),\n\t\t\tnode => {\n\t\t\t\thandler({ target: node });\n\t\t\t},\n\t\t);\n\t};\n\n\tif (document.body) {\n\t\tbindEvents();\n\t} else {\n\t\twindow.addEventListener('load', bindEvents);\n\t}\n\n\tif (document.documentElement.className.indexOf(CSS_CLASS_LOADED) === -1) {\n\t\tdocument.documentElement.className += ` ${CSS_CLASS_LOADED}`;\n\t}\n\n\tobserveValueOfHTMLElement(self.HTMLInputElement, handler);\n\tobserveValueOfHTMLElement(self.HTMLSelectElement, handler);\n\tobserveValueOfHTMLElement(self.HTMLTextAreaElement, handler);\n\tobserveSelectedOfHTMLElement(self.HTMLOptionElement);\n\n\t// conditionally update all form control elements\n\tupdateAllCandidates();\n\n\tif (typeof self.MutationObserver !== 'undefined') {\n\t\t// conditionally observe added or unobserve removed form control elements\n\t\tnew MutationObserver(mutationsList => {\n\t\t\tmutationsList.forEach(mutation => {\n\t\t\t\tArray.prototype.forEach.call(\n\t\t\t\t\tmutation.addedNodes || [],\n\t\t\t\t\tnode => {\n\t\t\t\t\t\tif (node.nodeType === 1 && isFormControlElement(node)) {\n\t\t\t\t\t\t\thandler({ target: node });\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t);\n\t\t\t});\n\t\t}).observe(document, { childList: true, subtree: true });\n\t} else {\n\t\tconst handleOnLoad = () => updateAllCandidates();\n\n\t\twindow.addEventListener('load', handleOnLoad);\n\t\twindow.addEventListener('DOMContentLoaded', handleOnLoad);\n\t}\n}\n"],"names":["INVALID_SELECTOR_CHAR","isValidReplacement","selector","isValid","i","length","indexOf","CSS_CLASS_LOADED","isFormControlElement","element","nodeName","createNewEvent","eventName","event","Event","bubbles","document","createEvent","initEvent","observeValueOfHTMLElement","HTMLElement","handler","descriptor","Object","getOwnPropertyDescriptor","prototype","nativeSet","set","apply","this","arguments","target","defineProperty","cssBlankPseudoInit","opts","options","force","replaceWith","Error","querySelector","ignoredError","remove","add","slice","el","classList","removeAttribute","setAttribute","handleInputOrChangeEvent","_element$options$elem","selectedIndex","value","bindEvents","body","addEventListener","updateAllCandidates","Array","forEach","call","querySelectorAll","node","window","documentElement","className","self","HTMLInputElement","HTMLSelectElement","HTMLTextAreaElement","HTMLOptionElement","parentElement","dispatchEvent","MutationObserver","mutationsList","mutation","addedNodes","nodeType","observe","childList","subtree","handleOnLoad"],"mappings":"AAAA,IAAMA,EAAwB,CAC7B,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,KAGc,SAASC,mBAAmBC,GAI1C,IAHA,IAAIC,GAAU,EAGLC,EAAI,EAAGC,EAASL,EAAsBK,OAAQD,EAAIC,GAAUF,EAASC,IACzEF,EAASI,QAAQN,EAAsBI,KAAO,IACjDD,GAAU,GAIZ,OAAOA,CACR,CCpBA,IAAMI,EAAmB,kBAGzB,SAASC,qBAAqBC,GAC7B,MAAyB,UAArBA,EAAQC,UAA6C,WAArBD,EAAQC,UAA8C,aAArBD,EAAQC,QAK9E,CAEA,SAASC,eAAeC,GACvB,IAAIC,EASJ,MAPsB,mBAAXC,MACVD,EAAQ,IAAIC,MAAMF,EAAW,CAAEG,SAAS,KAExCF,EAAQG,SAASC,YAAY,UACvBC,UAAUN,GAAW,GAAM,GAG3BC,CACR,CAqDA,SAASM,0BAA0BC,EAAaC,GAC/C,IAAMC,EAAaC,OAAOC,yB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ser.js"],"sourcesContent":["const INVALID_SELECTOR_CHAR = [\n\t' ', // Can't use child selector\n\t'>', // Can't use direct child selector\n\t'~', // Can't use sibling selector\n\t':', // Can't use pseudo selector\n\t'+', // Can't use adjacent selector\n\t'@', // Can't use at\n\t'#', // Can't use id selector\n\t'(', // Can't use parenthesis\n\t')', // Can't use parenthesis\n];\n\nexport default function isValidReplacement(selector) {\n\tlet isValid = true;\n\n\t// Purposely archaic so it's interoperable in old browsers\n\tfor (let i = 0, length = INVALID_SELECTOR_CHAR.length; i < length && isValid; i++) {\n\t\tif (selector.indexOf(INVALID_SELECTOR_CHAR[i]) > -1) {\n\t\t\tisValid = false;\n\t\t}\n\t}\n\n\treturn isValid;\n}\n","import isValidReplacement from './is-valid-replacement.mjs';\n\nconst CSS_CLASS_LOADED = 'js-blank-pseudo';\n\n// form control elements selector\nfunction isFormControlElement(element) {\n\tif (element.nodeName === 'INPUT' || element.nodeName === 'SELECT' || element.nodeName === 'TEXTAREA') {\n\t\treturn true;\n\t}\n\n\treturn false;\n}\n\nfunction createNewEvent(eventName) {\n\tlet event;\n\n\tif (typeof(Event) === 'function') {\n\t\tevent = new Event(eventName, { bubbles: true });\n\t} else {\n\t\tevent = document.createEvent('Event');\n\t\tevent.initEvent(eventName, true, false);\n\t}\n\n\treturn event;\n}\n\nfunction generateHandler(replaceWith) {\n\tlet selector;\n\tlet remove;\n\tlet add;\n\n\tif (replaceWith[0] === '.') {\n\t\tselector = replaceWith.slice(1);\n\t\tremove = (el) => el.classList.remove(selector);\n\t\tadd = (el) => el.classList.add(selector);\n\t} else {\n\t\t// A bit naive\n\t\tselector = replaceWith.slice(1, -1);\n\t\tremove = (el) => el.removeAttribute(selector, '');\n\t\tadd = (el) => el.setAttribute(selector, '');\n\t}\n\n\treturn function handleInputOrChangeEvent(event) {\n\t\tconst element = event.target;\n\t\tif (!isFormControlElement(element)) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst isSelect = element.nodeName === 'SELECT';\n\t\tconst hasValue = isSelect\n\t\t\t? !!element.options[element.selectedIndex]?.value\n\t\t\t: !!element.value;\n\n\t\tif (hasValue) {\n\t\t\tremove(element);\n\t\t} else {\n\t\t\tadd(element);\n\t\t}\n\t};\n}\n\n// observe changes to the \"selected\" property on an HTML Element\nfunction observeSelectedOfHTMLElement(HTMLElement) {\n\tconst descriptor = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'selected');\n\tconst nativeSet = descriptor.set;\n\n\tdescriptor.set = function set(value) { // eslint-disable-line no-unused-vars\n\t\tnativeSet.apply(this, arguments);\n\n\t\tconst event = createNewEvent('change');\n\t\tthis.parentElement.dispatchEvent(event);\n\t};\n\n\tObject.defineProperty(HTMLElement.prototype, 'selected', descriptor);\n}\n\n// observe changes to the \"value\" property on an HTML Element\nfunction observeValueOfHTMLElement(HTMLElement, handler) {\n\tconst descriptor = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'value');\n\tconst nativeSet = descriptor.set;\n\n\tdescriptor.set = function set() {\n\t\tnativeSet.apply(this, arguments);\n\t\thandler({ target: this });\n\t};\n\n\tObject.defineProperty(HTMLElement.prototype, 'value', descriptor);\n}\n\nexport default function cssBlankPseudoInit(opts) {\n\t// configuration\n\tconst options = {\n\t\tforce: false,\n\t\treplaceWith: '[blank]',\n\t};\n\n\tif (typeof opts !== 'undefined' && 'force' in opts) {\n\t\toptions.force = opts.force;\n\t}\n\n\tif (typeof opts !== 'undefined' && 'replaceWith' in opts) {\n\t\toptions.replaceWith = opts.replaceWith;\n\t}\n\n\tif (!isValidReplacement(options.replaceWith)) {\n\t\tthrow new Error(`${options.replaceWith} is not a valid replacement since it can't be applied to single elements.`);\n\t}\n\n\ttry {\n\t\tdocument.querySelector(':blank');\n\n\t\tif (!options.force) {\n\t\t\treturn;\n\t\t}\n\t} catch (_) {}\n\n\tconst handler = generateHandler(options.replaceWith);\n\tconst bindEvents = () => {\n\t\tif (document.body) {\n\t\t\tdocument.body.addEventListener('change', handler);\n\t\t\tdocument.body.addEventListener('input', handler);\n\t\t}\n\t};\n\tconst updateAllCandidates = () => {\n\t\tArray.prototype.forEach.call(\n\t\t\tdocument.querySelectorAll('input, select, textarea'),\n\t\t\tnode => {\n\t\t\t\thandler({ target: node });\n\t\t\t},\n\t\t);\n\t};\n\n\tif (document.body) {\n\t\tbindEvents();\n\t} else {\n\t\twindow.addEventListener('load', bindEvents);\n\t}\n\n\tif (document.documentElement.className.indexOf(CSS_CLASS_LOADED) === -1) {\n\t\tdocument.documentElement.className += ` ${CSS_CLASS_LOADED}`;\n\t}\n\n\tobserveValueOfHTMLElement(self.HTMLInputElement, handler);\n\tobserveValueOfHTMLElement(self.HTMLSelectElement, handler);\n\tobserveValueOfHTMLElement(self.HTMLTextAreaElement, handler);\n\tobserveSelectedOfHTMLElement(self.HTMLOptionElement);\n\n\t// conditionally update all form control elements\n\tupdateAllCandidates();\n\n\tif (typeof self.MutationObserver !== 'undefined') {\n\t\t// conditionally observe added or unobserve removed form control elements\n\t\tnew MutationObserver(mutationsList => {\n\t\t\tmutationsList.forEach(mutation => {\n\t\t\t\tArray.prototype.forEach.call(\n\t\t\t\t\tmutation.addedNodes || [],\n\t\t\t\t\tnode => {\n\t\t\t\t\t\tif (node.nodeType === 1 && isFormControlElement(node)) {\n\t\t\t\t\t\t\thandler({ target: node });\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t);\n\t\t\t});\n\t\t}).observe(document, { childList: true, subtree: true });\n\t} else {\n\t\tconst handleOnLoad = () => updateAllCandidates();\n\n\t\twindow.addEventListener('load', handleOnLoad);\n\t\twindow.addEventListener('DOMContentLoaded', handleOnLoad);\n\t}\n}\n"],"names":["INVALID_SELECTOR_CHAR","isValidReplacement","selector","isValid","i","length","indexOf","CSS_CLASS_LOADED","isFormControlElement","element","nodeName","createNewEvent","eventName","event","Event","bubbles","document","createEvent","initEvent","observeValueOfHTMLElement","HTMLElement","handler","descriptor","Object","getOwnPropertyDescriptor","prototype","nativeSet","set","apply","this","arguments","target","defineProperty","cssBlankPseudoInit","opts","options","force","replaceWith","Error","querySelector","_","remove","add","slice","el","classList","removeAttribute","setAttribute","handleInputOrChangeEvent","_element$options$elem","selectedIndex","value","bindEvents","body","addEventListener","updateAllCandidates","Array","forEach","call","querySelectorAll","node","window","documentElement","className","self","HTMLInputElement","HTMLSelectElement","HTMLTextAreaElement","HTMLOptionElement","parentElement","dispatchEvent","MutationObserver","mutationsList","mutation","addedNodes","nodeType","observe","childList","subtree","handleOnLoad"],"mappings":"AAAA,IAAMA,EAAwB,CAC7B,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,KAGc,SAASC,mBAAmBC,GAI1C,IAHA,IAAIC,GAAU,EAGLC,EAAI,EAAGC,EAASL,EAAsBK,OAAQD,EAAIC,GAAUF,EAASC,IACzEF,EAASI,QAAQN,EAAsBI,KAAO,IACjDD,GAAU,GAIZ,OAAOA,CACR,CCrBA,IAAMI,EAAmB,kBAGzB,SAASC,qBAAqBC,GAC7B,MAAyB,UAArBA,EAAQC,UAA6C,WAArBD,EAAQC,UAA8C,aAArBD,EAAQC,QAK9E,CAEA,SAASC,eAAeC,GACvB,IAAIC,EASJ,MAPsB,mBAAXC,MACVD,EAAQ,IAAIC,MAAMF,EAAW,CAAEG,SAAS,KAExCF,EAAQG,SAASC,YAAY,UACvBC,UAAUN,GAAW,GAAM,GAG3BC,CACR,CAqDA,SAASM,0BAA0BC,EAAaC,GAC/C,IAAMC,EAAaC,OAAOC,yBAAyBJ,EAAYK,UAAW,SACpEC,EAAYJ,EAAWK,IAE7BL,EAAWK,IAAM,SAASA,MACzBD,EAAUE,MAAMC,KAAMC,WACtBT,EAAQ,CAAEU,OAAQF,QAGnBN,OAAOS,eAAeZ,EAAYK,UAAW,QAASH,EACvD,gBAEe,SAASW,mBAAmBC,GAE1C,IAAMC,EAAU,CACfC,OAAO,EACPC,YAAa,WAWd,QARoB,IAATH,GAAwB,UAAWA,IAC7CC,EAAQC,MAAQF,EAAKE,YAGF,IAATF,GAA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AS8C,gBAAgBC,eAAiBxD,GAG3CY,0BAA0B6C,KAAKC,iBAAkB5C,GACjDF,0BAA0B6C,KAAKE,kBAAmB7C,GAClDF,0BAA0B6C,KAAKG,oBAAqB9C,GAlFfD,EAmFR4C,KAAKI,kBAlF5B9C,EAAaC,OAAOC,yBAAyBJ,EAAYK,UAAW,YACpEC,EAAYJ,EAAWK,IAE7BL,EAAWK,IAAM,SAASA,IAAIwB,GAC7BzB,EAAUE,MAAMC,KAAMC,WAEtB,IAAMjB,EAAQF,eAAe,UAC7BkB,KAAKwC,cAAcC,cAAczD,IAGlCU,OAAOS,eAAeZ,EAAYK,UAAW,WAAYH,GA2EzDiC,IAEqC,oBAA1BS,KAAKO,iBAEf,IAAIA,kBAAiB,SAAAC,GACpBA,EAAcf,SAAQ,SAAAgB,GACrBjB,MAAM/B,UAAUgC,QAAQC,KACvBe,EAASC,YAAc,IACvB,SAAAd,GACuB,IAAlBA,EAAKe,UAAkBnE,qBAAqBoD,IAC/CvC,EAAQ,CAAEU,OAAQ6B,GAEpB,GAEF,GACD,IAAGgB,QAAQ5D,SAAU,CAAE6D,WAAW,EAAMC,SAAS,QAC3C,CACN,IAAMC,EAAe,SAAfA,eAAY,OAASxB,GAAqB,EAEhDM,OAAOP,iBAAiB,OAAQyB,GAChClB,OAAOP,iBAAiB,mBAAoByB,EAC7C,CACD"} \ No newline at end of file diff --git a/plugins/css-blank-pseudo/dist/browser.mjs.map b/plugins/css-blank-pseudo/dist/browser.mjs.map index de6d70467..9069f823e 100644 --- a/plugins/css-blank-pseudo/dist/browser.mjs.map +++ b/plugins/css-blank-pseudo/dist/browser.mjs.map @@ -1 +1 @@ -{"version":3,"file":"browser.mjs","sources":["../src/is-valid-replacement.mjs","../src/browser.js"],"sourcesContent":["const INVALID_SELECTOR_CHAR = [\n\t' ', // Can't use child selector\n\t'>', // Can't use direct child selector\n\t'~', // Can't use sibling selector\n\t':', // Can't use pseudo selector\n\t'+', // Can't use adjacent selector\n\t'@', // Can't use at\n\t'#', // Can't use id selector\n\t'(', // Can't use parenthesis\n\t')', // Can't use parenthesis\n];\n\nexport default function isValidReplacement(selector) {\n\tlet isValid = true;\n\n\t// Purposely archaic so it's interoperable in old browsers\n\tfor (let i = 0, length = INVALID_SELECTOR_CHAR.length; i < length && isValid; i++) {\n\t\tif (selector.indexOf(INVALID_SELECTOR_CHAR[i]) > -1) {\n\t\t\tisValid = false;\n\t\t}\n\t}\n\n\treturn isValid;\n}\n","/* global document,window,self,MutationObserver */\nimport isValidReplacement from './is-valid-replacement.mjs';\n\nconst CSS_CLASS_LOADED = 'js-blank-pseudo';\n\n// form control elements selector\nfunction isFormControlElement(element) {\n\tif (element.nodeName === 'INPUT' || element.nodeName === 'SELECT' || element.nodeName === 'TEXTAREA') {\n\t\treturn true;\n\t}\n\n\treturn false;\n}\n\nfunction createNewEvent(eventName) {\n\tlet event;\n\n\tif (typeof(Event) === 'function') {\n\t\tevent = new Event(eventName, { bubbles: true });\n\t} else {\n\t\tevent = document.createEvent('Event');\n\t\tevent.initEvent(eventName, true, false);\n\t}\n\n\treturn event;\n}\n\nfunction generateHandler(replaceWith) {\n\tlet selector;\n\tlet remove;\n\tlet add;\n\n\tif (replaceWith[0] === '.') {\n\t\tselector = replaceWith.slice(1);\n\t\tremove = (el) => el.classList.remove(selector);\n\t\tadd = (el) => el.classList.add(selector);\n\t} else {\n\t\t// A bit naive\n\t\tselector = replaceWith.slice(1, -1);\n\t\tremove = (el) => el.removeAttribute(selector, '');\n\t\tadd = (el) => el.setAttribute(selector, '');\n\t}\n\n\treturn function handleInputOrChangeEvent(event) {\n\t\tconst element = event.target;\n\t\tif (!isFormControlElement(element)) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst isSelect = element.nodeName === 'SELECT';\n\t\tconst hasValue = isSelect\n\t\t\t? !!element.options[element.selectedIndex]?.value\n\t\t\t: !!element.value;\n\n\t\tif (hasValue) {\n\t\t\tremove(element);\n\t\t} else {\n\t\t\tadd(element);\n\t\t}\n\t};\n}\n\n// observe changes to the \"selected\" property on an HTML Element\nfunction observeSelectedOfHTMLElement(HTMLElement) {\n\tconst descriptor = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'selected');\n\tconst nativeSet = descriptor.set;\n\n\tdescriptor.set = function set(value) { // eslint-disable-line no-unused-vars\n\t\tnativeSet.apply(this, arguments);\n\n\t\tconst event = createNewEvent('change');\n\t\tthis.parentElement.dispatchEvent(event);\n\t};\n\n\tObject.defineProperty(HTMLElement.prototype, 'selected', descriptor);\n}\n\n// observe changes to the \"value\" property on an HTML Element\nfunction observeValueOfHTMLElement(HTMLElement, handler) {\n\tconst descriptor = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'value');\n\tconst nativeSet = descriptor.set;\n\n\tdescriptor.set = function set() {\n\t\tnativeSet.apply(this, arguments);\n\t\thandler({ target: this });\n\t};\n\n\tObject.defineProperty(HTMLElement.prototype, 'value', descriptor);\n}\n\nexport default function cssBlankPseudoInit(opts) {\n\t// configuration\n\tconst options = {\n\t\tforce: false,\n\t\treplaceWith: '[blank]',\n\t};\n\n\tif (typeof opts !== 'undefined' && 'force' in opts) {\n\t\toptions.force = opts.force;\n\t}\n\n\tif (typeof opts !== 'undefined' && 'replaceWith' in opts) {\n\t\toptions.replaceWith = opts.replaceWith;\n\t}\n\n\tif (!isValidReplacement(options.replaceWith)) {\n\t\tthrow new Error(`${options.replaceWith} is not a valid replacement since it can't be applied to single elements.`);\n\t}\n\n\ttry {\n\t\tdocument.querySelector(':blank');\n\n\t\tif (!options.force) {\n\t\t\treturn;\n\t\t}\n\t} catch (ignoredError) { /* do nothing and continue */ }\n\n\tconst handler = generateHandler(options.replaceWith);\n\tconst bindEvents = () => {\n\t\tif (document.body) {\n\t\t\tdocument.body.addEventListener('change', handler);\n\t\t\tdocument.body.addEventListener('input', handler);\n\t\t}\n\t};\n\tconst updateAllCandidates = () => {\n\t\tArray.prototype.forEach.call(\n\t\t\tdocument.querySelectorAll('input, select, textarea'),\n\t\t\tnode => {\n\t\t\t\thandler({ target: node });\n\t\t\t},\n\t\t);\n\t};\n\n\tif (document.body) {\n\t\tbindEvents();\n\t} else {\n\t\twindow.addEventListener('load', bindEvents);\n\t}\n\n\tif (document.documentElement.className.indexOf(CSS_CLASS_LOADED) === -1) {\n\t\tdocument.documentElement.className += ` ${CSS_CLASS_LOADED}`;\n\t}\n\n\tobserveValueOfHTMLElement(self.HTMLInputElement, handler);\n\tobserveValueOfHTMLElement(self.HTMLSelectElement, handler);\n\tobserveValueOfHTMLElement(self.HTMLTextAreaElement, handler);\n\tobserveSelectedOfHTMLElement(self.HTMLOptionElement);\n\n\t// conditionally update all form control elements\n\tupdateAllCandidates();\n\n\tif (typeof self.MutationObserver !== 'undefined') {\n\t\t// conditionally observe added or unobserve removed form control elements\n\t\tnew MutationObserver(mutationsList => {\n\t\t\tmutationsList.forEach(mutation => {\n\t\t\t\tArray.prototype.forEach.call(\n\t\t\t\t\tmutation.addedNodes || [],\n\t\t\t\t\tnode => {\n\t\t\t\t\t\tif (node.nodeType === 1 && isFormControlElement(node)) {\n\t\t\t\t\t\t\thandler({ target: node });\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t);\n\t\t\t});\n\t\t}).observe(document, { childList: true, subtree: true });\n\t} else {\n\t\tconst handleOnLoad = () => updateAllCandidates();\n\n\t\twindow.addEventListener('load', handleOnLoad);\n\t\twindow.addEventListener('DOMContentLoaded', handleOnLoad);\n\t}\n}\n"],"names":["INVALID_SELECTOR_CHAR","isValidReplacement","selector","isValid","i","length","indexOf","CSS_CLASS_LOADED","isFormControlElement","element","nodeName","createNewEvent","eventName","event","Event","bubbles","document","createEvent","initEvent","observeValueOfHTMLElement","HTMLElement","handler","descriptor","Object","getOwnPropertyDescriptor","prototype","nativeSet","set","apply","this","arguments","target","defineProperty","cssBlankPseudoInit","opts","options","force","replaceWith","Error","querySelector","ignoredError","remove","add","slice","el","classList","removeAttribute","setAttribute","handleInputOrChangeEvent","_element$options$elem","selectedIndex","value","bindEvents","body","addEventListener","updateAllCandidates","Array","forEach","call","querySelectorAll","node","window","documentElement","className","self","HTMLInputElement","HTMLSelectElement","HTMLTextAreaElement","HTMLOptionElement","parentElement","dispatchEvent","MutationObserver","mutationsList","mutation","addedNodes","nodeType","observe","childList","subtree","handleOnLoad"],"mappings":"AAAA,IAAMA,EAAwB,CAC7B,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,KAGc,SAASC,mBAAmBC,GAI1C,IAHA,IAAIC,GAAU,EAGLC,EAAI,EAAGC,EAASL,EAAsBK,OAAQD,EAAIC,GAAUF,EAASC,IACzEF,EAASI,QAAQN,EAAsBI,KAAO,IACjDD,GAAU,GAIZ,OAAOA,CACR,CCpBA,IAAMI,EAAmB,kBAGzB,SAASC,qBAAqBC,GAC7B,MAAyB,UAArBA,EAAQC,UAA6C,WAArBD,EAAQC,UAA8C,aAArBD,EAAQC,QAK9E,CAEA,SAASC,eAAeC,GACvB,IAAIC,EASJ,MAPsB,mBAAXC,MACVD,EAAQ,IAAIC,MAAMF,EAAW,CAAEG,SAAS,KAExCF,EAAQG,SAASC,YAAY,UACvBC,UAAUN,GAAW,GAAM,GAG3BC,CACR,CAqDA,SAASM,0BAA0BC,EAAaC,GAC/C,IAAMC,EAAaC,OAAOC,yBAAyBJ,EAAYK,UAAW,SACpEC,EAAYJ,EAAWK,IAE7BL,EAAWK,IAAM,SAASA,MACzBD,EAAUE,MAAMC,KAAMC,WACtBT,EAAQ,CAAEU,OAAQF,QAGnBN,OAAOS,eAAeZ,EAAYK,UAAW,QAASH,EACvD,CAEe,SAASW,mBAAmBC,GAE1C,IAAMC,EAAU,CACfC,OAAO,EACPC,YAAa,WAWd,QARoB,IAATH,GAAwB,UAAWA,IAC7CC,EAAQC,MAAQF,EAAKE,YAGF,IAATF,GAAwB,gBAAiBA,IACnDC,EAAQE,YAAcH,EAAKG,cAGvBpC,mBAAmBkC,EAAQE,aAC/B,MAAM,IAAIC,MAASH,EAAQE,yFAG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0BAA0B6C,KAAKG,oBAAqB9C,GAlFfD,EAmFR4C,KAAKI,kBAlF5B9C,EAAaC,OAAOC,yBAAyBJ,EAAYK,UAAW,YACpEC,EAAYJ,EAAWK,IAE7BL,EAAWK,IAAM,SAASA,IAAIwB,GAC7BzB,EAAUE,MAAMC,KAAMC,WAEtB,IAAMjB,EAAQF,eAAe,UAC7BkB,KAAKwC,cAAcC,cAAczD,IAGlCU,OAAOS,eAAeZ,EAAYK,UAAW,WAAYH,GA2EzDiC,IAEqC,oBAA1BS,KAAKO,iBAEf,IAAIA,kBAAiB,SAAAC,GACpBA,EAAcf,SAAQ,SAAAgB,GACrBjB,MAAM/B,UAAUgC,QAAQC,KACvBe,EAASC,YAAc,IACvB,SAAAd,GACuB,IAAlBA,EAAKe,UAAkBnE,qBAAqBoD,IAC/CvC,EAAQ,CAAEU,OAAQ6B,GAEpB,GAEF,GACD,IAAGgB,QAAQ5D,SAAU,CAAE6D,WAAW,EAAMC,SAAS,QAC3C,CACN,IAAMC,EAAe,SAAfA,eAAY,OAASxB,GAAqB,EAEhDM,OAAOP,iBAAiB,OAAQyB,GAChClB,OAAOP,iBAAiB,mBAAoByB,EAC7C,CACD"} \ No newline at end of file +{"version":3,"file":"browser.mjs","sources":["../src/is-valid-replacement.mjs","../src/browser.js"],"sourcesContent":["const INVALID_SELECTOR_CHAR = [\n\t' ', // Can't use child selector\n\t'>', // Can't use direct child selector\n\t'~', // Can't use sibling selector\n\t':', // Can't use pseudo selector\n\t'+', // Can't use adjacent selector\n\t'@', // Can't use at\n\t'#', // Can't use id selector\n\t'(', // Can't use parenthesis\n\t')', // Can't use parenthesis\n];\n\nexport default function isValidReplacement(selector) {\n\tlet isValid = true;\n\n\t// Purposely archaic so it's interoperable in old browsers\n\tfor (let i = 0, length = INVALID_SELECTOR_CHAR.length; i < length && isValid; i++) {\n\t\tif (selector.indexOf(INVALID_SELECTOR_CHAR[i]) > -1) {\n\t\t\tisValid = false;\n\t\t}\n\t}\n\n\treturn isValid;\n}\n","import isValidReplacement from './is-valid-replacement.mjs';\n\nconst CSS_CLASS_LOADED = 'js-blank-pseudo';\n\n// form control elements selector\nfunction isFormControlElement(element) {\n\tif (element.nodeName === 'INPUT' || element.nodeName === 'SELECT' || element.nodeName === 'TEXTAREA') {\n\t\treturn true;\n\t}\n\n\treturn false;\n}\n\nfunction createNewEvent(eventName) {\n\tlet event;\n\n\tif (typeof(Event) === 'function') {\n\t\tevent = new Event(eventName, { bubbles: true });\n\t} else {\n\t\tevent = document.createEvent('Event');\n\t\tevent.initEvent(eventName, true, false);\n\t}\n\n\treturn event;\n}\n\nfunction generateHandler(replaceWith) {\n\tlet selector;\n\tlet remove;\n\tlet add;\n\n\tif (replaceWith[0] === '.') {\n\t\tselector = replaceWith.slice(1);\n\t\tremove = (el) => el.classList.remove(selector);\n\t\tadd = (el) => el.classList.add(selector);\n\t} else {\n\t\t// A bit naive\n\t\tselector = replaceWith.slice(1, -1);\n\t\tremove = (el) => el.removeAttribute(selector, '');\n\t\tadd = (el) => el.setAttribute(selector, '');\n\t}\n\n\treturn function handleInputOrChangeEvent(event) {\n\t\tconst element = event.target;\n\t\tif (!isFormControlElement(element)) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst isSelect = element.nodeName === 'SELECT';\n\t\tconst hasValue = isSelect\n\t\t\t? !!element.options[element.selectedIndex]?.value\n\t\t\t: !!element.value;\n\n\t\tif (hasValue) {\n\t\t\tremove(element);\n\t\t} else {\n\t\t\tadd(element);\n\t\t}\n\t};\n}\n\n// observe changes to the \"selected\" property on an HTML Element\nfunction observeSelectedOfHTMLElement(HTMLElement) {\n\tconst descriptor = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'selected');\n\tconst nativeSet = descriptor.set;\n\n\tdescriptor.set = function set(value) { // eslint-disable-line no-unused-vars\n\t\tnativeSet.apply(this, arguments);\n\n\t\tconst event = createNewEvent('change');\n\t\tthis.parentElement.dispatchEvent(event);\n\t};\n\n\tObject.defineProperty(HTMLElement.prototype, 'selected', descriptor);\n}\n\n// observe changes to the \"value\" property on an HTML Element\nfunction observeValueOfHTMLElement(HTMLElement, handler) {\n\tconst descriptor = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'value');\n\tconst nativeSet = descriptor.set;\n\n\tdescriptor.set = function set() {\n\t\tnativeSet.apply(this, arguments);\n\t\thandler({ target: this });\n\t};\n\n\tObject.defineProperty(HTMLElement.prototype, 'value', descriptor);\n}\n\nexport default function cssBlankPseudoInit(opts) {\n\t// configuration\n\tconst options = {\n\t\tforce: false,\n\t\treplaceWith: '[blank]',\n\t};\n\n\tif (typeof opts !== 'undefined' && 'force' in opts) {\n\t\toptions.force = opts.force;\n\t}\n\n\tif (typeof opts !== 'undefined' && 'replaceWith' in opts) {\n\t\toptions.replaceWith = opts.replaceWith;\n\t}\n\n\tif (!isValidReplacement(options.replaceWith)) {\n\t\tthrow new Error(`${options.replaceWith} is not a valid replacement since it can't be applied to single elements.`);\n\t}\n\n\ttry {\n\t\tdocument.querySelector(':blank');\n\n\t\tif (!options.force) {\n\t\t\treturn;\n\t\t}\n\t} catch (_) {}\n\n\tconst handler = generateHandler(options.replaceWith);\n\tconst bindEvents = () => {\n\t\tif (document.body) {\n\t\t\tdocument.body.addEventListener('change', handler);\n\t\t\tdocument.body.addEventListener('input', handler);\n\t\t}\n\t};\n\tconst updateAllCandidates = () => {\n\t\tArray.prototype.forEach.call(\n\t\t\tdocument.querySelectorAll('input, select, textarea'),\n\t\t\tnode => {\n\t\t\t\thandler({ target: node });\n\t\t\t},\n\t\t);\n\t};\n\n\tif (document.body) {\n\t\tbindEvents();\n\t} else {\n\t\twindow.addEventListener('load', bindEvents);\n\t}\n\n\tif (document.documentElement.className.indexOf(CSS_CLASS_LOADED) === -1) {\n\t\tdocument.documentElement.className += ` ${CSS_CLASS_LOADED}`;\n\t}\n\n\tobserveValueOfHTMLElement(self.HTMLInputElement, handler);\n\tobserveValueOfHTMLElement(self.HTMLSelectElement, handler);\n\tobserveValueOfHTMLElement(self.HTMLTextAreaElement, handler);\n\tobserveSelectedOfHTMLElement(self.HTMLOptionElement);\n\n\t// conditionally update all form control elements\n\tupdateAllCandidates();\n\n\tif (typeof self.MutationObserver !== 'undefined') {\n\t\t// conditionally observe added or unobserve removed form control elements\n\t\tnew MutationObserver(mutationsList => {\n\t\t\tmutationsList.forEach(mutation => {\n\t\t\t\tArray.prototype.forEach.call(\n\t\t\t\t\tmutation.addedNodes || [],\n\t\t\t\t\tnode => {\n\t\t\t\t\t\tif (node.nodeType === 1 && isFormControlElement(node)) {\n\t\t\t\t\t\t\thandler({ target: node });\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t);\n\t\t\t});\n\t\t}).observe(document, { childList: true, subtree: true });\n\t} else {\n\t\tconst handleOnLoad = () => updateAllCandidates();\n\n\t\twindow.addEventListener('load', handleOnLoad);\n\t\twindow.addEventListener('DOMContentLoaded', handleOnLoad);\n\t}\n}\n"],"names":["INVALID_SELECTOR_CHAR","isValidReplacement","selector","isValid","i","length","indexOf","CSS_CLASS_LOADED","isFormControlElement","element","nodeName","createNewEvent","eventName","event","Event","bubbles","document","createEvent","initEvent","observeValueOfHTMLElement","HTMLElement","handler","descriptor","Object","getOwnPropertyDescriptor","prototype","nativeSet","set","apply","this","arguments","target","defineProperty","cssBlankPseudoInit","opts","options","force","replaceWith","Error","querySelector","_","remove","add","slice","el","classList","removeAttribute","setAttribute","handleInputOrChangeEvent","_element$options$elem","selectedIndex","value","bindEvents","body","addEventListener","updateAllCandidates","Array","forEach","call","querySelectorAll","node","window","documentElement","className","self","HTMLInputElement","HTMLSelectElement","HTMLTextAreaElement","HTMLOptionElement","parentElement","dispatchEvent","MutationObserver","mutationsList","mutation","addedNodes","nodeType","observe","childList","subtree","handleOnLoad"],"mappings":"AAAA,IAAMA,EAAwB,CAC7B,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,KAGc,SAASC,mBAAmBC,GAI1C,IAHA,IAAIC,GAAU,EAGLC,EA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KAAKO,iBAEf,IAAIA,kBAAiB,SAAAC,GACpBA,EAAcf,SAAQ,SAAAgB,GACrBjB,MAAM/B,UAAUgC,QAAQC,KACvBe,EAASC,YAAc,IACvB,SAAAd,GACuB,IAAlBA,EAAKe,UAAkBnE,qBAAqBoD,IAC/CvC,EAAQ,CAAEU,OAAQ6B,GAEpB,GAEF,GACD,IAAGgB,QAAQ5D,SAAU,CAAE6D,WAAW,EAAMC,SAAS,QAC3C,CACN,IAAMC,EAAe,SAAfA,eAAY,OAASxB,GAAqB,EAEhDM,OAAOP,iBAAiB,OAAQyB,GAChClB,OAAOP,iBAAiB,mBAAoByB,EAC7C,CACD"} \ No newline at end of file diff --git a/plugins/css-blank-pseudo/src/browser-global.js b/plugins/css-blank-pseudo/src/browser-global.js index 5e307d8c7..951e4d3e9 100644 --- a/plugins/css-blank-pseudo/src/browser-global.js +++ b/plugins/css-blank-pseudo/src/browser-global.js @@ -1,4 +1,3 @@ -/* global self,window */ import { default as cssBlankPseudoInit } from './browser'; (function (global) { diff --git a/plugins/css-blank-pseudo/src/browser.js b/plugins/css-blank-pseudo/src/browser.js index 99db41a7a..9e976bfce 100644 --- a/plugins/css-blank-pseudo/src/browser.js +++ b/plugins/css-blank-pseudo/src/browser.js @@ -1,4 +1,3 @@ -/* global document,window,self,MutationObserver */ import isValidReplacement from './is-valid-replacement.mjs'; const CSS_CLASS_LOADED = 'js-blank-pseudo'; @@ -113,7 +112,7 @@ export default function cssBlankPseudoInit(opts) { if (!options.force) { return; } - } catch (ignoredError) { /* do nothing and continue */ } + } catch (_) {} const handler = generateHandler(options.replaceWith); const bindEvents = () => { diff --git a/plugins/css-blank-pseudo/test/_browser.mjs b/plugins/css-blank-pseudo/test/_browser.mjs index e9f084b74..41e83dbe2 100644 --- a/plugins/css-blank-pseudo/test/_browser.mjs +++ b/plugins/css-blank-pseudo/test/_browser.mjs @@ -77,7 +77,6 @@ if (!process.env.DEBUG) { { await page.goto('http://localhost:8080'); const result = await page.evaluate(async () => { - // eslint-disable-next-line no-undef return await window.runTest(); }); @@ -204,7 +203,7 @@ if (!process.env.DEBUG) { { await page.goto('http://localhost:8080'); await page.evaluate(async () => { - // eslint-disable-next-line no-undef + return await window.runTest(); }); @@ -229,7 +228,7 @@ if (!process.env.DEBUG) { { await page.goto('http://localhost:8080/replace-with'); const result = await page.evaluate(async () => { - // eslint-disable-next-line no-undef + return await window.runTest(); }); diff --git a/plugins/css-has-pseudo/dist/browser-global.js.map b/plugins/css-has-pseudo/dist/browser-global.js.map index 5937dba2c..163332f7b 100644 --- a/plugins/css-has-pseudo/dist/browser-global.js.map +++ b/plugins/css-has-pseudo/dist/browser-global.js.map @@ -1 +1 @@ -{"version":3,"file":"browser-global.js","sources":["../src/encode/decode.mjs","../src/encode/extract.mjs","../src/encode/encode.mjs","../src/browser.js","../../../node_modules/@mrhenry/core-web/modules/~element-qsa-has.js","../src/browser-global.js"],"sourcesContent":["\n/** Decodes an identifier back into a CSS selector */\nexport default function decodeCSS(value) {\n\tif (value.slice(0, 13) !== 'csstools-has-') {\n\t\treturn '';\n\t}\n\n\tvalue = value.slice(13);\n\tlet values = value.split('-');\n\n\tlet result = '';\n\tfor (let i = 0; i < values.length; i++) {\n\t\tresult += String.fromCharCode(parseInt(values[i], 36));\n\t}\n\n\treturn result;\n}\n","import decodeCSS from './decode.mjs';\n\n/** Extract encoded selectors out of attribute selectors */\nexport default function extractEncodedSelectors(value) {\n\tlet out = [];\n\n\tlet depth = 0;\n\tlet candidate;\n\n\tlet quoted = false;\n\tlet quotedMark;\n\n\tlet containsUnescapedUnquotedHasAtDepth1 = false;\n\n\t// Stryker disable next-line EqualityOperator\n\tfor (let i = 0; i < value.length; i++) {\n\t\tconst char = value[i];\n\n\t\tswitch (char) {\n\t\t\tcase '[':\n\t\t\t\tif (quoted) {\n\t\t\t\t\tcandidate += char;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tif (depth === 0) {\n\t\t\t\t\tcandidate = '';\n\t\t\t\t} else {\n\t\t\t\t\tcandidate += char;\n\t\t\t\t}\n\n\t\t\t\tdepth++;\n\t\t\t\tcontinue;\n\t\t\tcase ']':\n\t\t\t\tif (quoted) {\n\t\t\t\t\tcandidate += char;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\t{\n\t\t\t\t\tdepth--;\n\t\t\t\t\tif (depth === 0) {\n\t\t\t\t\t\tconst decoded = decodeCSS(candidate);\n\t\t\t\t\t\tif (containsUnescapedUnquotedHasAtDepth1) {\n\t\t\t\t\t\t\tout.push(decoded);\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tcandidate += char;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tcontinue;\n\t\t\tcase '\\\\':\n\t\t\t\tcandidate += value[i];\n\t\t\t\tcandidate += value[i+1];\n\t\t\t\ti++;\n\t\t\t\tcontinue;\n\n\t\t\tcase '\"':\n\t\t\tcase '\\'':\n\t\t\t\tif (quoted && char === quotedMark) {\n\t\t\t\t\tquoted = false;\n\t\t\t\t\tcontinue;\n\t\t\t\t} else if (quoted) {\n\t\t\t\t\tcandidate += char;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tquoted = true;\n\t\t\t\tquotedMark = char;\n\t\t\t\tcontinue;\n\n\t\t\tdefault:\n\t\t\t\tif (candidate === '' && depth === 1 && (value.slice(i, i + 13) === 'csstools-has-')) {\n\t\t\t\t\tcontainsUnescapedUnquotedHasAtDepth1 = true;\n\t\t\t\t}\n\n\t\t\t\tcandidate += char;\n\t\t\t\tcontinue;\n\t\t}\n\t}\n\n\tconst unique = [];\n\tfor (let i = 0; i < out.length; i++) {\n\t\tif (unique.indexOf(out[i]) === -1) {\n\t\t\tunique.push(out[i]);\n\t\t}\n\t}\n\n\treturn unique;\n}\n","\n/** Returns the string as an encoded CSS identifier. */\nexport default function encodeCSS(value) {\n\tif (value === '') {\n\t\treturn '';\n\t}\n\n\tlet hex;\n\tlet result = '';\n\tfor (let i = 0; i < value.length; i++) {\n\t\thex = value.charCodeAt(i).toString(36);\n\t\tif (i === 0) {\n\t\t\tresult += hex;\n\t\t} else {\n\t\t\tresult += '-' + hex;\n\t\t}\n\t}\n\n\treturn 'csstools-has-' + result;\n}\n","/* global MutationObserver,requestAnimationFrame,cancelAnimationFrame,self,HTMLElement */\n\nimport '@mrhenry/core-web/modules/~element-qsa-has.js';\nimport extractEncodedSelectors from './encode/extract.mjs';\nimport encodeCSS from './encode/encode.mjs';\n\nfunction hasNativeSupport() {\n\ttry {\n\t\tif (!('CSS' in self) || !('supports' in self.CSS) || !self.CSS.supports('selector(:has(div))')) {\n\t\t\treturn false;\n\t\t}\n\n\t} catch (_) {\n\t\treturn false;\n\t}\n\n\treturn true;\n}\n\nexport default function cssHasPseudo(document, options) {\n\t// OPTIONS\n\t{\n\t\tif (!options) {\n\t\t\toptions = {};\n\t\t}\n\n\t\toptions = {\n\t\t\thover: (!!options.hover) || false,\n\t\t\tdebug: (!!options.debug) || false,\n\t\t\tobservedAttributes: options.observedAttributes || [],\n\t\t\tforcePolyfill: (!!options.forcePolyfill) || false,\n\t\t};\n\n\t\toptions.mustPolyfill = options.forcePolyfill || !hasNativeSupport();\n\n\t\tif (!Array.isArray(options.observedAttributes)) {\n\t\t\toptions.observedAttributes = [];\n\t\t}\n\n\t\toptions.observedAttributes = options.observedAttributes.filter((x) => {\n\t\t\treturn (typeof x === 'string');\n\t\t});\n\n\t\t// https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes\n\t\t// `data-*` and `style` were omitted\n\t\toptions.observedAttributes = options.observedAttributes.concat(['accept', 'accept-charset', 'accesskey', 'action', 'align', 'allow', 'alt', 'async', 'autocapitalize', 'autocomplete', 'autofocus', 'autoplay', 'buffered', 'capture', 'challenge', 'charset', 'checked', 'cite', 'class', 'code', 'codebase', 'cols', 'colspan', 'content', 'contenteditable', 'contextmenu', 'controls', 'coords', 'crossorigin', 'csp', 'data', 'datetime', 'decoding', 'default', 'defer', 'dir', 'dirname', 'disabled', 'download', 'draggable', 'enctype', 'enterkeyhint', 'for', 'form', 'formaction', 'formenctype', 'formmethod', 'formnovalidate', 'formtarget', 'headers', 'hidden', 'high', 'href', 'hreflang', 'http-equiv', 'icon', 'id', 'importance', 'integrity', 'intrinsicsize', 'inputmode', 'ismap', 'itemprop', 'keytype', 'kind', 'label', 'lang', 'language', 'list', 'loop', 'low', 'manifest', 'max', 'maxlength', 'minlength', 'media', 'method', 'min', 'multiple', 'muted', 'name', 'novalidate', 'open', 'optimum', 'pattern', 'ping', 'placeholder', 'poster', 'preload', 'radiogroup', 'readonly', 'referrerpolicy', 'rel', 'required', 'reversed', 'rows', 'rowspan', 'sandbox', 'scope', 'scoped', 'selected', 'shape', 'size', 'sizes', 'slot', 'span', 'spellcheck', 'src', 'srcdoc', 'srclang', 'srcset', 'start', 'step', 'summary', 'tabindex', 'target', 'title', 'translate', 'type', 'usemap', 'value', 'width', 'wrap']);\n\t}\n\n\tconst observedItems = [];\n\n\t// document.createAttribute() doesn't support `:` in the name. innerHTML does\n\tconst attributeElement = document.createElement('x');\n\n\t// walk all stylesheets to collect observed css rules\n\t[].forEach.call(document.styleSheets, walkStyleSheet);\n\tif (!options.mustPolyfill) {\n\t\t// Cleanup of rules will have happened in `walkStyleSheet`\n\t\t// Native support will take over from here\n\t\treturn;\n\t}\n\n\ttransformObservedItemsThrottled();\n\n\t// observe DOM modifications that affect selectors\n\tif ('MutationObserver' in self) {\n\t\tconst mutationObserver = new MutationObserver((mutationsList) => {\n\t\t\tmutationsList.forEach(mutation => {\n\t\t\t\t[].forEach.call(mutation.addedNodes || [], node => {\n\t\t\t\t\t// walk stylesheets to collect observed css rules\n\t\t\t\t\tif (node.nodeType === 1 && node.sheet) {\n\t\t\t\t\t\twalkStyleSheet(node.sheet);\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\t// transform observed css rules\n\t\t\t\tcleanupObservedCssRules();\n\t\t\t\ttransformObservedItemsThrottled();\n\t\t\t});\n\t\t});\n\n\t\tmutationObserver.observe(document, { childList: true, subtree: true, attributes: true, attributeFilter: options.observedAttributes });\n\t}\n\n\t// observe DOM events that affect pseudo-selectors\n\tdocument.addEventListener('focus', transformObservedItemsThrottled, true);\n\tdocument.addEventListener('blur', transformObservedItemsThrottled, true);\n\tdocument.addEventListener('input', transformObservedItemsThrottled);\n\tdocument.addEventListener('change', transformObservedItemsThrottled, true);\n\n\tif (options.hover) {\n\t\tif ('onpointerenter' in document) {\n\t\t\tdocument.addEventListener('pointerenter', transformObservedItemsThrottled, true);\n\t\t\tdocument.addEventListener('pointerleave', transformObservedItemsThrottled, true);\n\t\t} else {\n\t\t\tdocument.addEventListener('mouseover', transformObservedItemsThrottled, true);\n\t\t\tdocument.addEventListener('mouseout', transformObservedItemsThrottled, true);\n\t\t}\n\t}\n\n\t// observe Javascript setters that effect pseudo-selectors\n\tif ('defineProperty' in Object && 'getOwnPropertyDescriptor' in Object && 'hasOwnProperty' in Object) {\n\t\ttry {\n\t\t\t// eslint-disable-next-line no-inner-declarations\n\t\t\tfunction observeProperty(proto, property) {\n\t\t\t\t// eslint-disable-next-line no-prototype-builtins\n\t\t\t\tif (proto.hasOwnProperty(property)) {\n\t\t\t\t\tconst descriptor = Object.getOwnPropertyDescriptor(proto, property);\n\t\t\t\t\tif (descriptor && descriptor.configurable && 'set' in descriptor) {\n\t\t\t\t\t\tObject.defineProperty(proto, property, {\n\t\t\t\t\t\t\tconfigurable: descriptor.configurable,\n\t\t\t\t\t\t\tenumerable: descriptor.enumerable,\n\t\t\t\t\t\t\tget: function () {\n\t\t\t\t\t\t\t\treturn descriptor.get.apply(this, arguments);\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tset: function () {\n\t\t\t\t\t\t\t\tdescriptor.set.apply(this, arguments);\n\n\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\ttransformObservedItemsThrottled();\n\t\t\t\t\t\t\t\t} catch (_) {\n\t\t\t\t\t\t\t\t\t// should never happen as there is an inner try/catch\n\t\t\t\t\t\t\t\t\t// but just in case\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif ('HTMLElement' in self && HTMLElement.prototype) {\n\t\t\t\tobserveProperty(HTMLElement.prototype, 'disabled');\n\t\t\t}\n\n\t\t\t// Not all of these elements have all of these properties.\n\t\t\t// But the code above checks if they exist first.\n\t\t\t['checked', 'selected', 'readOnly', 'required'].forEach((property) => {\n\t\t\t\t[\n\t\t\t\t\t'HTMLButtonElement',\n\t\t\t\t\t'HTMLFieldSetElement',\n\t\t\t\t\t'HTMLInputElement',\n\t\t\t\t\t'HTMLMeterElement',\n\t\t\t\t\t'HTMLOptGroupElement',\n\t\t\t\t\t'HTMLOptionElement',\n\t\t\t\t\t'HTMLOutputElement',\n\t\t\t\t\t'HTMLProgressElement',\n\t\t\t\t\t'HTMLSelectElement',\n\t\t\t\t\t'HTMLTextAreaElement',\n\t\t\t\t].forEach((elementName) => {\n\t\t\t\t\tif (elementName in self && self[elementName].prototype) {\n\t\t\t\t\t\tobserveProperty(self[elementName].prototype, property);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t});\n\t\t} catch (e) {\n\t\t\tif (options.debug) {\n\t\t\t\tconsole.error(e);\n\t\t\t}\n\t\t}\n\t}\n\n\tlet transformObservedItemsThrottledBusy = false;\n\tfunction transformObservedItemsThrottled() {\n\t\tif (transformObservedItemsThrottledBusy) {\n\t\t\tcancelAnimationFrame(transformObservedItemsThrottledBusy);\n\t\t}\n\n\t\ttransformObservedItemsThrottledBusy = requestAnimationFrame(() => {\n\t\t\ttransformObservedItems();\n\t\t});\n\t}\n\n\t// transform observed css rules\n\tfunction transformObservedItems() {\n\t\tobservedItems.forEach((item) => {\n\t\t\tconst nodes = [];\n\n\t\t\tlet matches = [];\n\t\t\ttry {\n\t\t\t\tmatches = document.querySelectorAll(item.selector);\n\t\t\t} catch (e) {\n\t\t\t\tif (options.debug) {\n\t\t\t\t\tconsole.error(e);\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t[].forEach.call(matches, (element) => {\n\t\t\t\t// memorize the node\n\t\t\t\tnodes.push(element);\n\n\t\t\t\t// set an attribute with an irregular attribute name\n\t\t\t\t// document.createAttribute() doesn't support special characters\n\t\t\t\tattributeElement.innerHTML = '';\n\n\t\t\t\telement.setAttributeNode(attributeElement.children[0].attributes[0].cloneNode());\n\n\t\t\t\t// trigger a style refresh in IE and Edge\n\t\t\t\tdocument.documentElement.style.zoom = 1; document.documentElement.style.zoom = null;\n\t\t\t});\n\n\t\t\t// remove the encoded attribute from all nodes that no longer match them\n\t\t\titem.nodes.forEach(node => {\n\t\t\t\tif (nodes.indexOf(node) === -1) {\n\t\t\t\t\tnode.removeAttribute(item.attributeName);\n\n\t\t\t\t\t// trigger a style refresh in IE and Edge\n\t\t\t\t\tdocument.documentElement.style.zoom = 1; document.documentElement.style.zoom = null;\n\t\t\t\t}\n\t\t\t});\n\n\t\t\t// update the\n\t\t\titem.nodes = nodes;\n\t\t});\n\t}\n\n\t// remove any observed cssrules that no longer apply\n\tfunction cleanupObservedCssRules() {\n\t\t[].push.apply(\n\t\t\tobservedItems,\n\t\t\tobservedItems.splice(0).filter((item) => {\n\t\t\t\treturn item.rule.parentStyleSheet &&\n\t\t\t\t\titem.rule.parentStyleSheet.ownerNode &&\n\t\t\t\t\tdocument.documentElement.contains(item.rule.parentStyleSheet.ownerNode);\n\t\t\t}),\n\t\t);\n\t}\n\n\t// walk a stylesheet to collect observed css rules\n\tfunction walkStyleSheet(styleSheet) {\n\t\ttry {\n\t\t\t// walk a css rule to collect observed css rules\n\t\t\t[].forEach.call(styleSheet.cssRules || [], (rule, index) => {\n\t\t\t\tif (rule.selectorText) {\n\t\t\t\t\trule.selectorText = rule.selectorText.replace(/\\.js-has-pseudo\\s/g, '');\n\n\t\t\t\t\ttry {\n\t\t\t\t\t\t// decode the selector text in all browsers to:\n\t\t\t\t\t\tconst hasSelectors = extractEncodedSelectors(rule.selectorText.toString());\n\t\t\t\t\t\tif (hasSelectors.length === 0) {\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (!options.mustPolyfill) {\n\t\t\t\t\t\t\tstyleSheet.deleteRule(index);\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tfor (let i = 0; i < hasSelectors.length; i++) {\n\t\t\t\t\t\t\tconst hasSelector = hasSelectors[i];\n\t\t\t\t\t\t\tobservedItems.push({\n\t\t\t\t\t\t\t\trule: rule,\n\t\t\t\t\t\t\t\tselector: hasSelector,\n\t\t\t\t\t\t\t\tattributeName: encodeCSS(hasSelector),\n\t\t\t\t\t\t\t\tnodes: [],\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\tif (options.debug) {\n\t\t\t\t\t\t\tconsole.error(e);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\twalkStyleSheet(rule);\n\t\t\t\t}\n\t\t\t});\n\t\t} catch (e) {\n\t\t\tif (options.debug) {\n\t\t\t\tconsole.error(e);\n\t\t\t}\n\t\t}\n\t}\n}\n","/* eslint-disable */\n(function (global) {\n\ttry {\n\t\t// test for has support\n\t\tglobal.document.querySelector(':has(*, :does-not-exist, > *)');\n\n\t\tif (\n\t\t\t!global.document.querySelector(':has(:scope *)') &&\n\t\t\tCSS.supports('selector(:has(div))')\n\t\t) {\n\t\t\treturn;\n\t\t}\n\t} catch (_) { }\n\n\t// ELEMENT\n\t// polyfill Element#querySelector\n\tvar querySelectorWithHasElement = polyfill(global.Element.prototype.querySelector);\n\n\tglobal.Element.prototype.querySelector = function querySelector(selectors) {\n\t\treturn querySelectorWithHasElement.apply(this, arguments);\n\t};\n\n\t// polyfill Element#querySelectorAll\n\tvar querySelectorAllWithHasElement = polyfill(global.Element.prototype.querySelectorAll);\n\n\tglobal.Element.prototype.querySelectorAll = function querySelectorAll(selectors) {\n\t\treturn querySelectorAllWithHasElement.apply(this, arguments);\n\t};\n\n\t// polyfill Element#matches\n\tif (global.Element.prototype.matches) {\n\t\tvar matchesWithHasElement = polyfill(global.Element.prototype.matches);\n\n\t\tglobal.Element.prototype.matches = function matches(selectors) {\n\t\t\treturn matchesWithHasElement.apply(this, arguments);\n\t\t};\n\t}\n\n\t// polyfill Element#closest\n\tif (global.Element.prototype.closest) {\n\t\tvar closestWithHasElement = polyfill(global.Element.prototype.closest);\n\n\t\tglobal.Element.prototype.closest = function closest(selectors) {\n\t\t\treturn closestWithHasElement.apply(this, arguments);\n\t\t};\n\t}\n\n\t// DOCUMENT\n\tif ('Document' in global && 'prototype' in global.Document) {\n\t\t// polyfill Document#querySelector\n\t\tvar querySelectorWithHasDocument = polyfill(global.Document.prototype.querySelector);\n\n\t\tglobal.Document.prototype.querySelector = function querySelector(selectors) {\n\t\t\treturn querySelectorWithHasDocument.apply(this, arguments);\n\t\t};\n\n\t\t// polyfill Document#querySelectorAll\n\t\tvar querySelectorAllWithHasDocument = polyfill(global.Document.prototype.querySelectorAll);\n\n\t\tglobal.Document.prototype.querySelectorAll = function querySelectorAll(selectors) {\n\t\t\treturn querySelectorAllWithHasDocument.apply(this, arguments);\n\t\t};\n\n\t\t// polyfill Document#matches\n\t\tif (global.Document.prototype.matches) {\n\t\t\tvar matchesWithHasDocument = polyfill(global.Document.prototype.matches);\n\n\t\t\tglobal.Document.prototype.matches = function matches(selectors) {\n\t\t\t\treturn matchesWithHasDocument.apply(this, arguments);\n\t\t\t};\n\t\t}\n\n\t\t// polyfill Document#closest\n\t\tif (global.Document.prototype.closest) {\n\t\t\tvar closestWithHasDocument = polyfill(global.Document.prototype.closest);\n\n\t\t\tglobal.Document.prototype.closest = function closest(selectors) {\n\t\t\t\treturn closestWithHasDocument.apply(this, arguments);\n\t\t\t};\n\t\t}\n\t}\n\n\tfunction pseudoClassHasInnerQuery(query) {\n\t\tvar current = '';\n\t\tvar start = 0;\n\t\tvar depth = 0;\n\n\t\tvar escaped = false;\n\n\t\tvar quoted = false;\n\t\tvar quotedMark = false;\n\n\t\tvar inHas = false;\n\n\t\tvar bracketed = 0;\n\n\t\tfor (var i = 0; i < query.length; i++) {\n\t\t\tvar char = query[i];\n\n\t\t\tif (escaped) {\n\t\t\t\tcurrent += char;\n\t\t\t\tescaped = false;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (quoted) {\n\t\t\t\tif (char === quotedMark) {\n\t\t\t\t\tquoted = false;\n\t\t\t\t}\n\n\t\t\t\tcurrent += char;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (current.toLowerCase() === ':has(' && !inHas) {\n\t\t\t\tinHas = true;\n\t\t\t\tstart = i;\n\t\t\t\tcurrent = '';\n\t\t\t}\n\n\t\t\tswitch (char) {\n\t\t\t\tcase ':':\n\t\t\t\t\tif (!inHas) {\n\t\t\t\t\t\tcurrent = '';\n\t\t\t\t\t}\n\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tcontinue;\n\n\t\t\t\tcase '(':\n\t\t\t\t\tif (inHas) {\n\t\t\t\t\t\tdepth++;\n\t\t\t\t\t}\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tcontinue;\n\n\t\t\t\tcase ')':\n\t\t\t\t\tif (inHas) {\n\t\t\t\t\t\tif (depth === 0) {\n\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\tinnerQuery: current,\n\t\t\t\t\t\t\t\tstart: start,\n\t\t\t\t\t\t\t\tend: i-1\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tdepth--;\n\t\t\t\t\t}\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tcontinue;\n\n\t\t\t\tcase '\\\\':\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tescaped = true;\n\t\t\t\t\tcontinue;\n\n\t\t\t\tcase '\"':\n\t\t\t\tcase \"'\":\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tquoted = true;\n\t\t\t\t\tquotedMark = char;\n\t\t\t\t\tcontinue;\n\n\t\t\t\tcase '[':\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tbracketed++;\n\t\t\t\t\tcontinue;\n\n\t\t\t\tcase \"]\":\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tif (bracketed > 0) {\n\t\t\t\t\t\tbracketed--\n\t\t\t\t\t}\n\n\t\t\t\t\tcontinue;\n\t\t\t\n\t\t\t\tdefault:\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\n\t\treturn false;\n\t}\n\n\tfunction replaceScopeWithAttr(query, attr) {\n\t\tvar parts = [];\n\t\tvar current = '';\n\n\t\tvar escaped = false;\n\n\t\tvar quoted = false;\n\t\tvar quotedMark = false;\n\n\t\tvar bracketed = 0;\n\n\t\tfor (var i = 0; i < query.length; i++) {\n\t\t\tvar char = query[i];\n\n\t\t\tif (escaped) {\n\t\t\t\tcurrent += char;\n\t\t\t\tescaped = false;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (quoted) {\n\t\t\t\tif (char === quotedMark) {\n\t\t\t\t\tquoted = false;\n\t\t\t\t}\n\n\t\t\t\tcurrent += char;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (current.toLowerCase() === ':scope' && !bracketed && (/^[\\[\\.\\:\\\\\"\\s|+>~#&,)]/.test(char || ''))) {\n\t\t\t\tparts.push(current.slice(0, current.length - 6));\n\t\t\t\tparts.push('[' + attr + ']');\n\t\t\t\tcurrent = '';\n\t\t\t}\n\n\t\t\tswitch (char) {\n\t\t\t\tcase ':':\n\t\t\t\t\tparts.push(current);\n\t\t\t\t\tcurrent = '';\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tcontinue;\n\n\t\t\t\tcase '\\\\':\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tescaped = true;\n\t\t\t\t\tcontinue;\n\n\t\t\t\tcase '\"':\n\t\t\t\tcase \"'\":\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tquoted = true;\n\t\t\t\t\tquotedMark = char;\n\t\t\t\t\tcontinue;\n\n\t\t\t\tcase '[':\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tbracketed++;\n\t\t\t\t\tcontinue;\n\n\t\t\t\tcase \"]\":\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tif (bracketed > 0) {\n\t\t\t\t\t\tbracketed--\n\t\t\t\t\t}\n\n\t\t\t\t\tcontinue;\n\n\t\t\t\tdefault:\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\n\t\tif (current.toLowerCase() === ':scope') {\n\t\t\tparts.push(current.slice(0, current.length - 6));\n\t\t\tparts.push('[' + attr + ']');\n\t\t\tcurrent = '';\n\t\t}\n\n\t\tif (parts.length === 0) {\n\t\t\treturn query;\n\t\t}\n\n\t\treturn parts.join('') + current;\n\t}\n\n\tfunction charIsNestedMarkMirror(char, mark) {\n\t\tif (mark === '(' && char === ')') {\n\t\t\treturn true;\n\t\t}\n\n\t\tif (mark === '[' && char === ']') {\n\t\t\treturn true;\n\t\t}\n\n\t\treturn false;\n\t}\n\n\tfunction splitSelector(query) {\n\t\tvar selectors = [];\n\t\tvar current = '';\n\n\t\tvar escaped = false;\n\n\t\tvar quoted = false;\n\t\tvar quotedMark = false;\n\n\t\tvar nestedMark = false;\n\t\tvar nestedDepth = 0;\n\n\t\tfor (var i = 0; i < query.length; i++) {\n\t\t\tvar char = query[i];\n\n\t\t\tif (escaped) {\n\t\t\t\tcurrent += char;\n\t\t\t\tescaped = false;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tswitch (char) {\n\t\t\t\tcase ',':\n\t\t\t\t\tif (quoted) {\n\t\t\t\t\t\tcurrent += char;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (nestedDepth > 0) {\n\t\t\t\t\t\tcurrent += char;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tselectors.push(current);\n\t\t\t\t\tcurrent = '';\n\t\t\t\t\tcontinue;\n\n\t\t\t\tcase '\\\\':\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tescaped = true;\n\t\t\t\t\tcontinue;\n\n\t\t\t\tcase '\"':\n\t\t\t\tcase \"'\":\n\t\t\t\t\tif (quoted && char === quotedMark) {\n\t\t\t\t\t\tcurrent += char;\n\t\t\t\t\t\tquoted = false;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tquoted = true;\n\t\t\t\t\tquotedMark = char;\n\t\t\t\t\tcontinue;\n\n\t\t\t\tcase '(':\n\t\t\t\tcase ')':\n\t\t\t\tcase '[':\n\t\t\t\tcase ']':\n\t\t\t\t\tif (quoted) {\n\t\t\t\t\t\tcurrent += char;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (charIsNestedMarkMirror(char, nestedMark)) {\n\t\t\t\t\t\tcurrent += char;\n\t\t\t\t\t\tnestedDepth--;\n\n\t\t\t\t\t\tif (nestedDepth === 0) {\n\t\t\t\t\t\t\tnestedMark = false;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (char === nestedMark) {\n\t\t\t\t\t\tcurrent += char;\n\t\t\t\t\t\tnestedDepth++;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tnestedDepth++;\n\t\t\t\t\tnestedMark = char;\n\t\t\t\t\tcontinue;\n\n\t\t\t\tdefault:\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tcontinue;\n\n\t\t\t}\n\t\t}\n\n\t\tselectors.push(current);\n\n\t\treturn selectors;\n\t}\n\n\tfunction replaceAllWithTempAttr(query, nested, callback) {\n\t\tvar inner = pseudoClassHasInnerQuery(query);\n\t\tif (!inner) {\n\t\t\treturn query;\n\t\t}\n\n\t\tif (nested) {\n\t\t\treturn false;\n\t\t}\n\n\t\tvar innerQuery = inner.innerQuery;\n\t\tvar attr = 'q-has' + (Math.floor(Math.random() * 9000000) + 1000000);\n\t\tvar innerReplacement = '[' + attr + ']';\n\n\t\tvar x = query;\n\n\t\tif (inner.innerQuery.toLowerCase().indexOf(':has(') > -1) {\n\t\t\tvar innerParts = splitSelector(inner.innerQuery);\n\t\t\tvar newInnerParts = [];\n\t\t\tfor (var i = 0; i < innerParts.length; i++) {\n\t\t\t\tvar innerPart = innerParts[i];\n\n\t\t\t\t// Nested has is not supported.\n\t\t\t\t// If a recursive/nested call returns \"false\" we throw\n\t\t\t\tvar innerPartReplaced = replaceAllWithTempAttr(innerPart, true, function () { });\n\t\t\t\tif (!innerPartReplaced) {\n\t\t\t\t\tthrow new Error(\"Nested :has() is not supported\")\n\t\t\t\t} else {\n\t\t\t\t\tnewInnerParts.push(innerPart);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tvar _prefix = x.substring(0, inner.start - 5); // ':has('.length === 5\n\t\t\tvar _suffix = x.substring(inner.end + 2); // ')'.length === 1\n\n\t\t\treturn _prefix + newInnerParts.join(', ') + _suffix;\n\t\t}\n\n\t\tvar _prefix = x.substring(0, inner.start - 5); // ':has('.length === 5\n\t\tvar _suffix = x.substring(inner.end + 2); // ')'.length === 1\n\n\t\tx = _prefix + innerReplacement + _suffix;\n\n\t\tcallback(innerQuery, attr);\n\t\tif (x.toLowerCase().indexOf(':has(') > -1) {\n\t\t\tvar y = replaceAllWithTempAttr(x, false, callback);\n\t\t\tif (y) {\n\t\t\t\treturn y;\n\t\t\t}\n\t\t}\n\n\t\treturn x;\n\t}\n\n\tfunction walkNode(rootNode, callback) {\n\t\tif (('setAttribute' in (rootNode)) && ('querySelector' in (rootNode))) {\n\t\t\tcallback(rootNode);\n\t\t}\n\n\t\tif (rootNode.hasChildNodes()) {\n\t\t\tvar nodes = rootNode.childNodes;\n\t\t\tfor (var i = 0; i < nodes.length; ++i) {\n\t\t\t\twalkNode(nodes[i], callback);\n\t\t\t}\n\t\t}\n\t}\n\n\tfunction polyfill(qsa) {\n\t\treturn function (selectors) {\n\t\t\tif (!selectors) {\n\t\t\t\treturn qsa.apply(this, arguments);\n\t\t\t}\n\n\t\t\tvar selectorsString = String(selectors);\n\t\t\tif (!selectorsString || (selectorsString.toLowerCase().indexOf(':has(') === -1) || !pseudoClassHasInnerQuery(selectorsString)) {\n\t\t\t\treturn qsa.apply(this, arguments);\n\t\t\t}\n\n\t\t\tvar rootNode;\n\t\t\tif ('getRootNode' in this) {\n\t\t\t\trootNode = this.getRootNode();\n\t\t\t} else {\n\t\t\t\tvar r = this;\n\t\t\t\twhile (r) {\n\t\t\t\t\trootNode = r;\n\t\t\t\t\tr = r.parentNode;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tvar _focus = this;\n\t\t\tif (_focus === global.document) {\n\t\t\t\t_focus = global.document.documentElement;\n\t\t\t}\n\n\t\t\tvar scopeAttr = 'q-has-scope' + (Math.floor(Math.random() * 9000000) + 1000000);\n\t\t\t_focus.setAttribute(scopeAttr, '');\n\n\t\t\ttry {\n\t\t\t\tselectorsString = replaceScopeWithAttr(selectorsString, scopeAttr);\n\n\t\t\t\tvar attrs = [scopeAttr];\n\t\t\t\tvar newQuery = replaceAllWithTempAttr(selectorsString, false, function (inner, attr) {\n\t\t\t\t\tattrs.push(attr);\n\n\t\t\t\t\tvar selectorParts = splitSelector(inner);\n\t\t\t\t\tfor (var x = 0; x < selectorParts.length; x++) {\n\t\t\t\t\t\tvar selectorPart = selectorParts[x].trim();\n\t\t\t\t\t\tvar absoluteSelectorPart = selectorPart;\n\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\tselectorPart[0] === '>' ||\n\t\t\t\t\t\t\tselectorPart[0] === '+' ||\n\t\t\t\t\t\t\tselectorPart[0] === '~'\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\tabsoluteSelectorPart = selectorPart.slice(1).trim();\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tabsoluteSelectorPart = ':scope ' + selectorPart;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\twalkNode(rootNode, function (node) {\n\t\t\t\t\t\t\tif (!(node.querySelector(absoluteSelectorPart))) {\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tswitch (selectorPart[0]) {\n\t\t\t\t\t\t\t\tcase '~':\n\t\t\t\t\t\t\t\tcase '+':\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tvar siblings = node.childNodes;\n\t\t\t\t\t\t\t\t\t\tfor (var i = 0; i < siblings.length; i++) {\n\t\t\t\t\t\t\t\t\t\t\tvar sibling = siblings[i];\n\t\t\t\t\t\t\t\t\t\t\tif (!('setAttribute' in sibling)) {\n\t\t\t\t\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\tvar idAttr = 'q-has-id' + (Math.floor(Math.random() * 9000000) + 1000000);\n\t\t\t\t\t\t\t\t\t\t\tsibling.setAttribute(idAttr, '');\n\n\t\t\t\t\t\t\t\t\t\t\tif (node.querySelector(':scope [' + idAttr + ']' + ' ' + selectorPart)) {\n\t\t\t\t\t\t\t\t\t\t\t\tsibling.setAttribute(attr, '');\n\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\tsibling.removeAttribute(idAttr);\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\t\t\tcase '>':\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tvar idAttr = 'q-has-id' + (Math.floor(Math.random() * 9000000) + 1000000);\n\t\t\t\t\t\t\t\t\t\tnode.setAttribute(idAttr, '');\n\n\t\t\t\t\t\t\t\t\t\tif (node.querySelector(':scope[' + idAttr + ']' + ' ' + selectorPart)) {\n\t\t\t\t\t\t\t\t\t\t\tnode.setAttribute(attr, '');\n\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\tnode.removeAttribute(idAttr);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\t\t\tnode.setAttribute(attr, '');\n\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\targuments[0] = newQuery;\n\n\t\t\t\t// results of the qsa\n\t\t\t\tvar elementOrNodeList = qsa.apply(this, arguments);\n\n\t\t\t\t_focus.removeAttribute(scopeAttr);\n\n\t\t\t\tif (attrs.length > 0) {\n\t\t\t\t\t// remove the fallback attribute\n\t\t\t\t\tvar attrsForQuery = [];\n\t\t\t\t\tfor (var j = 0; j < attrs.length; j++) {\n\t\t\t\t\t\tattrsForQuery.push('[' + attrs[j] + ']');\n\t\t\t\t\t}\n\n\t\t\t\t\tvar elements = global.document.querySelectorAll(attrsForQuery.join(','));\n\t\t\t\t\tfor (var k = 0; k < elements.length; k++) {\n\t\t\t\t\t\tvar element = elements[k];\n\t\t\t\t\t\tfor (var l = 0; l < attrs.length; l++) {\n\t\t\t\t\t\t\telement.removeAttribute(attrs[l]);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// return the results of the qsa\n\t\t\t\treturn elementOrNodeList;\n\t\t\t} catch (err) {\n\t\t\t\t_focus.removeAttribute(scopeAttr);\n\n\t\t\t\tif (attrs.length > 0) {\n\t\t\t\t\t// remove the fallback attribute\n\t\t\t\t\tvar attrsForQuery = [];\n\t\t\t\t\tfor (var j = 0; j < attrs.length; j++) {\n\t\t\t\t\t\tattrsForQuery.push('[' + attrs[j] + ']');\n\t\t\t\t\t}\n\n\t\t\t\t\tvar elements = global.document.querySelectorAll(attrsForQuery.join(','));\n\t\t\t\t\tfor (var k = 0; k < elements.length; k++) {\n\t\t\t\t\t\tvar element = elements[k];\n\t\t\t\t\t\tfor (var l = 0; l < attrs.length; l++) {\n\t\t\t\t\t\t\telement.removeAttribute(attrs[l]);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tvar errorMessage = '';\n\t\t\t\ttry {\n\t\t\t\t\tqsa.apply(this, [':core-web-does-not-exist']);\n\t\t\t\t} catch (dummyError) {\n\t\t\t\t\terrorMessage = dummyError.message;\n\t\t\t\t\tif (errorMessage) {\n\t\t\t\t\t\terrorMessage = errorMessage.replace(':core-web-does-not-exist', selectorsString);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (!errorMessage) {\n\t\t\t\t\terrorMessage = \"Failed to execute 'querySelector' on 'Document': '\" + selectorsString + \"' is not a valid selector.\";\n\t\t\t\t}\n\n\t\t\t\ttry {\n\t\t\t\t\tthrow new DOMException(errorMessage);\n\t\t\t\t} catch (_) {\n\t\t\t\t\tthrow new Error(errorMessage);\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\t}\n})(self);\n","/* global self,window */\nimport { default as cssHasPseudo } from './browser';\n\n(function (global) {\n\tglobal.cssHasPseudo = cssHasPseudo;\n}('object' === typeof window && window || 'object' === typeof self && self || {}));\n"],"names":["decodeCSS","value","slice","values","split","result","i","length","String","fromCharCode","parseInt","extractEncodedSelectors","candidate","quotedMark","out","depth","quoted","containsUnescapedUnquotedHasAtDepth1","char","decoded","push","unique","indexOf","encodeCSS","hex","charCodeAt","toString","hasNativeSupport","self","CSS","supports","_","cssHasPseudo","document","options","hover","debug","observedAttributes","forcePolyfill","mustPolyfill","Array","isArray","filter","x","concat","observedItems","attributeElement","createElement","forEach","call","styleSheets","walkStyleSheet","transformObservedItemsThrottled","MutationObserver","mutationsList","mutation","addedNodes","node","nodeType","sheet","apply","splice","item","rule","parentStyleSheet","ownerNode","documentElement","contains","observe","childList","subtree","attributes","attributeFilter","addEventListener","Object","observeProperty","proto","property","hasOwnProperty","descriptor","getOwnPropertyDescriptor","configurable","defineProperty","enumerable","get","this","arguments","set","HTMLElement","prototype","elementName","e","console","error","transformObservedItemsThrottledBusy","cancelAnimationFrame","requestAnimationFrame","nodes","matches","querySelectorAll","selector","element","innerHTML","attributeName","setAttributeNode","children","cloneNode","style","zoom","removeAttribute","styleSheet","cssRules","index","selectorText","replace","hasSelectors","deleteRule","hasSelector","global","querySelector","querySelectorWithHasElement","polyfill","Element","selectors","querySelectorAllWithHasElement","matchesWithHasElement","closest","closestWithHasElement","Document","querySelectorWithHasDocument","querySelectorAllWithHasDocument","matchesWithHasDocument","closestWithHasDocument","pseudoClassHasInnerQuery","query","current","start","escaped","inHas","toLowerCase","innerQuery","end","replaceScopeWithAttr","attr","parts","bracketed","test","join","splitSelector","mark","nestedMark","nestedDepth","replaceAllWithTempAttr","nested","callback","inner","Math","floor","random","innerReplacement","innerParts","newInnerParts","innerPart","Error","_prefix","substring","_suffix","y","walkNode","rootNode","hasChildNodes","childNodes","qsa","selectorsString","getRootNode","r","parentNode","_focus","scopeAttr","setAttribute","attrs","newQuery","selectorParts","selectorPart","trim","absoluteSelectorPart","siblings","sibling","idAttr","elementOrNodeList","attrsForQuery","j","elements","k","l","err","errorMessage","dummyError","message","DOMException","window"],"mappings":"YAEe,SAASA,UAAUC,GACjC,GAA2B,kBAAvBA,EAAMC,MAAM,EAAG,IAClB,MAAO,GAOR,IAHA,IAAIC,GADJF,EAAQA,EAAMC,MAAM,KACDE,MAAM,KAErBC,EAAS,GACJC,EAAI,EAAGA,EAAIH,EAAOI,OAAQD,IAClCD,GAAUG,OAAOC,aAAaC,SAASP,EAAOG,GAAI,KAGnD,OAAOD,CACR,CCbe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,EAAQQ,gBAAgBuE,EAAMc,GAGjC,CAGA,OAAOL,CACP,CAAC,MAAOM,GAGR,GAFAlB,EAAOpE,gBAAgBqE,GAEnBE,EAAM7K,OAAS,EAAG,CAGrB,IADIuL,EAAgB,GACXC,EAAI,EAAGA,EAAIX,EAAM7K,OAAQwL,IACjCD,EAAc1K,KAAK,IAAMgK,EAAMW,GAAK,KAIrC,IADIC,EAAW1E,EAAOrF,SAASkE,iBAAiB2F,EAAc3C,KAAK,MAC1D8C,EAAI,EAAGA,EAAID,EAASzL,OAAQ0L,IAEpC,IADI5F,EAAU2F,EAASC,GACdC,EAAI,EAAGA,EAAId,EAAM7K,OAAQ2L,IACjC7F,EAAQQ,gBAAgBuE,EAAMc,GAGjC,CAEA,IAAIE,EAAe,GACnB,IACCxB,EAAIhH,MAAMyB,KAAM,CAAC,4BACjB,CAAC,MAAOgH,GACRD,EAAeC,EAAWC,QACtBF,IACHA,EAAeA,EAAalF,QAAQ,2BAA4B2D,GAElE,CAEKuB,IACJA,EAAe,qDAAuDvB,EAAkB,8BAGzF,IACC,MAAM,IAAI0B,aAAaH,EACvB,CAAC,MAAOrK,GACR,MAAM,IAAIoI,MAAMiC,EACjB,CACD,EAEF,CACA,CAvmBD,CAumBGxK,OCnmBD,iBAAoB4K,QAAUA,QAAU,iBAAoB5K,MAAQA,MAAQ,IADtEI,aAAeA","x_google_ignoreList":[4]} \ No newline at end of file +{"version":3,"file":"browser-global.js","sources":["../src/encode/decode.mjs","../src/encode/extract.mjs","../src/encode/encode.mjs","../src/browser.js","../../../node_modules/@mrhenry/core-web/modules/~element-qsa-has.js","../src/browser-global.js"],"sourcesContent":["\n/** Decodes an identifier back into a CSS selector */\nexport default function decodeCSS(value) {\n\tif (value.slice(0, 13) !== 'csstools-has-') {\n\t\treturn '';\n\t}\n\n\tvalue = value.slice(13);\n\tlet values = value.split('-');\n\n\tlet result = '';\n\tfor (let i = 0; i < values.length; i++) {\n\t\tresult += String.fromCharCode(parseInt(values[i], 36));\n\t}\n\n\treturn result;\n}\n","import decodeCSS from './decode.mjs';\n\n/** Extract encoded selectors out of attribute selectors */\nexport default function extractEncodedSelectors(value) {\n\tlet out = [];\n\n\tlet depth = 0;\n\tlet candidate;\n\n\tlet quoted = false;\n\tlet quotedMark;\n\n\tlet containsUnescapedUnquotedHasAtDepth1 = false;\n\n\t// Stryker disable next-line EqualityOperator\n\tfor (let i = 0; i < value.length; i++) {\n\t\tconst char = value[i];\n\n\t\tswitch (char) {\n\t\t\tcase '[':\n\t\t\t\tif (quoted) {\n\t\t\t\t\tcandidate += char;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tif (depth === 0) {\n\t\t\t\t\tcandidate = '';\n\t\t\t\t} else {\n\t\t\t\t\tcandidate += char;\n\t\t\t\t}\n\n\t\t\t\tdepth++;\n\t\t\t\tcontinue;\n\t\t\tcase ']':\n\t\t\t\tif (quoted) {\n\t\t\t\t\tcandidate += char;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\t{\n\t\t\t\t\tdepth--;\n\t\t\t\t\tif (depth === 0) {\n\t\t\t\t\t\tconst decoded = decodeCSS(candidate);\n\t\t\t\t\t\tif (containsUnescapedUnquotedHasAtDepth1) {\n\t\t\t\t\t\t\tout.push(decoded);\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tcandidate += char;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tcontinue;\n\t\t\tcase '\\\\':\n\t\t\t\tcandidate += value[i];\n\t\t\t\tcandidate += value[i+1];\n\t\t\t\ti++;\n\t\t\t\tcontinue;\n\n\t\t\tcase '\"':\n\t\t\tcase '\\'':\n\t\t\t\tif (quoted && char === quotedMark) {\n\t\t\t\t\tquoted = false;\n\t\t\t\t\tcontinue;\n\t\t\t\t} else if (quoted) {\n\t\t\t\t\tcandidate += char;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tquoted = true;\n\t\t\t\tquotedMark = char;\n\t\t\t\tcontinue;\n\n\t\t\tdefault:\n\t\t\t\tif (candidate === '' && depth === 1 && (value.slice(i, i + 13) === 'csstools-has-')) {\n\t\t\t\t\tcontainsUnescapedUnquotedHasAtDepth1 = true;\n\t\t\t\t}\n\n\t\t\t\tcandidate += char;\n\t\t\t\tcontinue;\n\t\t}\n\t}\n\n\tconst unique = [];\n\tfor (let i = 0; i < out.length; i++) {\n\t\tif (unique.indexOf(out[i]) === -1) {\n\t\t\tunique.push(out[i]);\n\t\t}\n\t}\n\n\treturn unique;\n}\n","\n/** Returns the string as an encoded CSS identifier. */\nexport default function encodeCSS(value) {\n\tif (value === '') {\n\t\treturn '';\n\t}\n\n\tlet hex;\n\tlet result = '';\n\tfor (let i = 0; i < value.length; i++) {\n\t\thex = value.charCodeAt(i).toString(36);\n\t\tif (i === 0) {\n\t\t\tresult += hex;\n\t\t} else {\n\t\t\tresult += '-' + hex;\n\t\t}\n\t}\n\n\treturn 'csstools-has-' + result;\n}\n","import '@mrhenry/core-web/modules/~element-qsa-has.js';\nimport extractEncodedSelectors from './encode/extract.mjs';\nimport encodeCSS from './encode/encode.mjs';\n\nfunction hasNativeSupport() {\n\ttry {\n\t\tif (!('CSS' in self) || !('supports' in self.CSS) || !self.CSS.supports('selector(:has(div))')) {\n\t\t\treturn false;\n\t\t}\n\n\t} catch (_) {\n\t\treturn false;\n\t}\n\n\treturn true;\n}\n\nexport default function cssHasPseudo(document, options) {\n\t// OPTIONS\n\t{\n\t\tif (!options) {\n\t\t\toptions = {};\n\t\t}\n\n\t\toptions = {\n\t\t\thover: (!!options.hover) || false,\n\t\t\tdebug: (!!options.debug) || false,\n\t\t\tobservedAttributes: options.observedAttributes || [],\n\t\t\tforcePolyfill: (!!options.forcePolyfill) || false,\n\t\t};\n\n\t\toptions.mustPolyfill = options.forcePolyfill || !hasNativeSupport();\n\n\t\tif (!Array.isArray(options.observedAttributes)) {\n\t\t\toptions.observedAttributes = [];\n\t\t}\n\n\t\toptions.observedAttributes = options.observedAttributes.filter((x) => {\n\t\t\treturn (typeof x === 'string');\n\t\t});\n\n\t\t// https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes\n\t\t// `data-*` and `style` were omitted\n\t\toptions.observedAttributes = options.observedAttributes.concat(['accept', 'accept-charset', 'accesskey', 'action', 'align', 'allow', 'alt', 'async', 'autocapitalize', 'autocomplete', 'autofocus', 'autoplay', 'buffered', 'capture', 'challenge', 'charset', 'checked', 'cite', 'class', 'code', 'codebase', 'cols', 'colspan', 'content', 'contenteditable', 'contextmenu', 'controls', 'coords', 'crossorigin', 'csp', 'data', 'datetime', 'decoding', 'default', 'defer', 'dir', 'dirname', 'disabled', 'download', 'draggable', 'enctype', 'enterkeyhint', 'for', 'form', 'formaction', 'formenctype', 'formmethod', 'formnovalidate', 'formtarget', 'headers', 'hidden', 'high', 'href', 'hreflang', 'http-equiv', 'icon', 'id', 'importance', 'integrity', 'intrinsicsize', 'inputmode', 'ismap', 'itemprop', 'keytype', 'kind', 'label', 'lang', 'language', 'list', 'loop', 'low', 'manifest', 'max', 'maxlength', 'minlength', 'media', 'method', 'min', 'multiple', 'muted', 'name', 'novalidate', 'open', 'optimum', 'pattern', 'ping', 'placeholder', 'poster', 'preload', 'radiogroup', 'readonly', 'referrerpolicy', 'rel', 'required', 'reversed', 'rows', 'rowspan', 'sandbox', 'scope', 'scoped', 'selected', 'shape', 'size', 'sizes', 'slot', 'span', 'spellcheck', 'src', 'srcdoc', 'srclang', 'srcset', 'start', 'step', 'summary', 'tabindex', 'target', 'title', 'translate', 'type', 'usemap', 'value', 'width', 'wrap']);\n\t}\n\n\tconst observedItems = [];\n\n\t// document.createAttribute() doesn't support `:` in the name. innerHTML does\n\tconst attributeElement = document.createElement('x');\n\n\t// walk all stylesheets to collect observed css rules\n\t[].forEach.call(document.styleSheets, walkStyleSheet);\n\tif (!options.mustPolyfill) {\n\t\t// Cleanup of rules will have happened in `walkStyleSheet`\n\t\t// Native support will take over from here\n\t\treturn;\n\t}\n\n\ttransformObservedItemsThrottled();\n\n\t// observe DOM modifications that affect selectors\n\tif ('MutationObserver' in self) {\n\t\tconst mutationObserver = new MutationObserver((mutationsList) => {\n\t\t\tmutationsList.forEach(mutation => {\n\t\t\t\t[].forEach.call(mutation.addedNodes || [], node => {\n\t\t\t\t\t// walk stylesheets to collect observed css rules\n\t\t\t\t\tif (node.nodeType === 1 && node.sheet) {\n\t\t\t\t\t\twalkStyleSheet(node.sheet);\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\t// transform observed css rules\n\t\t\t\tcleanupObservedCssRules();\n\t\t\t\ttransformObservedItemsThrottled();\n\t\t\t});\n\t\t});\n\n\t\tmutationObserver.observe(document, { childList: true, subtree: true, attributes: true, attributeFilter: options.observedAttributes });\n\t}\n\n\t// observe DOM events that affect pseudo-selectors\n\tdocument.addEventListener('focus', transformObservedItemsThrottled, true);\n\tdocument.addEventListener('blur', transformObservedItemsThrottled, true);\n\tdocument.addEventListener('input', transformObservedItemsThrottled);\n\tdocument.addEventListener('change', transformObservedItemsThrottled, true);\n\n\tif (options.hover) {\n\t\tif ('onpointerenter' in document) {\n\t\t\tdocument.addEventListener('pointerenter', transformObservedItemsThrottled, true);\n\t\t\tdocument.addEventListener('pointerleave', transformObservedItemsThrottled, true);\n\t\t} else {\n\t\t\tdocument.addEventListener('mouseover', transformObservedItemsThrottled, true);\n\t\t\tdocument.addEventListener('mouseout', transformObservedItemsThrottled, true);\n\t\t}\n\t}\n\n\t// observe Javascript setters that effect pseudo-selectors\n\tif ('defineProperty' in Object && 'getOwnPropertyDescriptor' in Object && 'hasOwnProperty' in Object) {\n\t\ttry {\n\t\t\tfunction observeProperty(proto, property) {\n\t\t\t\t// eslint-disable-next-line no-prototype-builtins\n\t\t\t\tif (proto.hasOwnProperty(property)) {\n\t\t\t\t\tconst descriptor = Object.getOwnPropertyDescriptor(proto, property);\n\t\t\t\t\tif (descriptor && descriptor.configurable && 'set' in descriptor) {\n\t\t\t\t\t\tObject.defineProperty(proto, property, {\n\t\t\t\t\t\t\tconfigurable: descriptor.configurable,\n\t\t\t\t\t\t\tenumerable: descriptor.enumerable,\n\t\t\t\t\t\t\tget: function () {\n\t\t\t\t\t\t\t\treturn descriptor.get.apply(this, arguments);\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tset: function () {\n\t\t\t\t\t\t\t\tdescriptor.set.apply(this, arguments);\n\n\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\ttransformObservedItemsThrottled();\n\t\t\t\t\t\t\t\t} catch (_) {\n\t\t\t\t\t\t\t\t\t// should never happen as there is an inner try/catch\n\t\t\t\t\t\t\t\t\t// but just in case\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif ('HTMLElement' in self && HTMLElement.prototype) {\n\t\t\t\tobserveProperty(HTMLElement.prototype, 'disabled');\n\t\t\t}\n\n\t\t\t// Not all of these elements have all of these properties.\n\t\t\t// But the code above checks if they exist first.\n\t\t\t['checked', 'selected', 'readOnly', 'required'].forEach((property) => {\n\t\t\t\t[\n\t\t\t\t\t'HTMLButtonElement',\n\t\t\t\t\t'HTMLFieldSetElement',\n\t\t\t\t\t'HTMLInputElement',\n\t\t\t\t\t'HTMLMeterElement',\n\t\t\t\t\t'HTMLOptGroupElement',\n\t\t\t\t\t'HTMLOptionElement',\n\t\t\t\t\t'HTMLOutputElement',\n\t\t\t\t\t'HTMLProgressElement',\n\t\t\t\t\t'HTMLSelectElement',\n\t\t\t\t\t'HTMLTextAreaElement',\n\t\t\t\t].forEach((elementName) => {\n\t\t\t\t\tif (elementName in self && self[elementName].prototype) {\n\t\t\t\t\t\tobserveProperty(self[elementName].prototype, property);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t});\n\t\t} catch (e) {\n\t\t\tif (options.debug) {\n\t\t\t\tconsole.error(e);\n\t\t\t}\n\t\t}\n\t}\n\n\tlet transformObservedItemsThrottledBusy = false;\n\tfunction transformObservedItemsThrottled() {\n\t\tif (transformObservedItemsThrottledBusy) {\n\t\t\tcancelAnimationFrame(transformObservedItemsThrottledBusy);\n\t\t}\n\n\t\ttransformObservedItemsThrottledBusy = requestAnimationFrame(() => {\n\t\t\ttransformObservedItems();\n\t\t});\n\t}\n\n\t// transform observed css rules\n\tfunction transformObservedItems() {\n\t\tobservedItems.forEach((item) => {\n\t\t\tconst nodes = [];\n\n\t\t\tlet matches = [];\n\t\t\ttry {\n\t\t\t\tmatches = document.querySelectorAll(item.selector);\n\t\t\t} catch (e) {\n\t\t\t\tif (options.debug) {\n\t\t\t\t\tconsole.error(e);\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t[].forEach.call(matches, (element) => {\n\t\t\t\t// memorize the node\n\t\t\t\tnodes.push(element);\n\n\t\t\t\t// set an attribute with an irregular attribute name\n\t\t\t\t// document.createAttribute() doesn't support special characters\n\t\t\t\tattributeElement.innerHTML = '';\n\n\t\t\t\telement.setAttributeNode(attributeElement.children[0].attributes[0].cloneNode());\n\n\t\t\t\t// trigger a style refresh in IE and Edge\n\t\t\t\tdocument.documentElement.style.zoom = 1; document.documentElement.style.zoom = null;\n\t\t\t});\n\n\t\t\t// remove the encoded attribute from all nodes that no longer match them\n\t\t\titem.nodes.forEach(node => {\n\t\t\t\tif (nodes.indexOf(node) === -1) {\n\t\t\t\t\tnode.removeAttribute(item.attributeName);\n\n\t\t\t\t\t// trigger a style refresh in IE and Edge\n\t\t\t\t\tdocument.documentElement.style.zoom = 1; document.documentElement.style.zoom = null;\n\t\t\t\t}\n\t\t\t});\n\n\t\t\t// update the\n\t\t\titem.nodes = nodes;\n\t\t});\n\t}\n\n\t// remove any observed cssrules that no longer apply\n\tfunction cleanupObservedCssRules() {\n\t\t[].push.apply(\n\t\t\tobservedItems,\n\t\t\tobservedItems.splice(0).filter((item) => {\n\t\t\t\treturn item.rule.parentStyleSheet &&\n\t\t\t\t\titem.rule.parentStyleSheet.ownerNode &&\n\t\t\t\t\tdocument.documentElement.contains(item.rule.parentStyleSheet.ownerNode);\n\t\t\t}),\n\t\t);\n\t}\n\n\t// walk a stylesheet to collect observed css rules\n\tfunction walkStyleSheet(styleSheet) {\n\t\ttry {\n\t\t\t// walk a css rule to collect observed css rules\n\t\t\t[].forEach.call(styleSheet.cssRules || [], (rule, index) => {\n\t\t\t\tif (rule.selectorText) {\n\t\t\t\t\trule.selectorText = rule.selectorText.replace(/\\.js-has-pseudo\\s/g, '');\n\n\t\t\t\t\ttry {\n\t\t\t\t\t\t// decode the selector text in all browsers to:\n\t\t\t\t\t\tconst hasSelectors = extractEncodedSelectors(rule.selectorText.toString());\n\t\t\t\t\t\tif (hasSelectors.length === 0) {\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (!options.mustPolyfill) {\n\t\t\t\t\t\t\tstyleSheet.deleteRule(index);\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tfor (let i = 0; i < hasSelectors.length; i++) {\n\t\t\t\t\t\t\tconst hasSelector = hasSelectors[i];\n\t\t\t\t\t\t\tobservedItems.push({\n\t\t\t\t\t\t\t\trule: rule,\n\t\t\t\t\t\t\t\tselector: hasSelector,\n\t\t\t\t\t\t\t\tattributeName: encodeCSS(hasSelector),\n\t\t\t\t\t\t\t\tnodes: [],\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\tif (options.debug) {\n\t\t\t\t\t\t\tconsole.error(e);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\twalkStyleSheet(rule);\n\t\t\t\t}\n\t\t\t});\n\t\t} catch (e) {\n\t\t\tif (options.debug) {\n\t\t\t\tconsole.error(e);\n\t\t\t}\n\t\t}\n\t}\n}\n","/* eslint-disable */\n(function (global) {\n\ttry {\n\t\t// test for has support\n\t\tglobal.document.querySelector(':has(*, :does-not-exist, > *)');\n\n\t\tif (\n\t\t\t!global.document.querySelector(':has(:scope *)') &&\n\t\t\tCSS.supports('selector(:has(div))')\n\t\t) {\n\t\t\treturn;\n\t\t}\n\t} catch (_) { }\n\n\t// ELEMENT\n\t// polyfill Element#querySelector\n\tvar querySelectorWithHasElement = polyfill(global.Element.prototype.querySelector);\n\n\tglobal.Element.prototype.querySelector = function querySelector(selectors) {\n\t\treturn querySelectorWithHasElement.apply(this, arguments);\n\t};\n\n\t// polyfill Element#querySelectorAll\n\tvar querySelectorAllWithHasElement = polyfill(global.Element.prototype.querySelectorAll);\n\n\tglobal.Element.prototype.querySelectorAll = function querySelectorAll(selectors) {\n\t\treturn querySelectorAllWithHasElement.apply(this, arguments);\n\t};\n\n\t// polyfill Element#matches\n\tif (global.Element.prototype.matches) {\n\t\tvar matchesWithHasElement = polyfill(global.Element.prototype.matches);\n\n\t\tglobal.Element.prototype.matches = function matches(selectors) {\n\t\t\treturn matchesWithHasElement.apply(this, arguments);\n\t\t};\n\t}\n\n\t// polyfill Element#closest\n\tif (global.Element.prototype.closest) {\n\t\tvar closestWithHasElement = polyfill(global.Element.prototype.closest);\n\n\t\tglobal.Element.prototype.closest = function closest(selectors) {\n\t\t\treturn closestWithHasElement.apply(this, arguments);\n\t\t};\n\t}\n\n\t// DOCUMENT\n\tif ('Document' in global && 'prototype' in global.Document) {\n\t\t// polyfill Document#querySelector\n\t\tvar querySelectorWithHasDocument = polyfill(global.Document.prototype.querySelector);\n\n\t\tglobal.Document.prototype.querySelector = function querySelector(selectors) {\n\t\t\treturn querySelectorWithHasDocument.apply(this, arguments);\n\t\t};\n\n\t\t// polyfill Document#querySelectorAll\n\t\tvar querySelectorAllWithHasDocument = polyfill(global.Document.prototype.querySelectorAll);\n\n\t\tglobal.Document.prototype.querySelectorAll = function querySelectorAll(selectors) {\n\t\t\treturn querySelectorAllWithHasDocument.apply(this, arguments);\n\t\t};\n\n\t\t// polyfill Document#matches\n\t\tif (global.Document.prototype.matches) {\n\t\t\tvar matchesWithHasDocument = polyfill(global.Document.prototype.matches);\n\n\t\t\tglobal.Document.prototype.matches = function matches(selectors) {\n\t\t\t\treturn matchesWithHasDocument.apply(this, arguments);\n\t\t\t};\n\t\t}\n\n\t\t// polyfill Document#closest\n\t\tif (global.Document.prototype.closest) {\n\t\t\tvar closestWithHasDocument = polyfill(global.Document.prototype.closest);\n\n\t\t\tglobal.Document.prototype.closest = function closest(selectors) {\n\t\t\t\treturn closestWithHasDocument.apply(this, arguments);\n\t\t\t};\n\t\t}\n\t}\n\n\tfunction pseudoClassHasInnerQuery(query) {\n\t\tvar current = '';\n\t\tvar start = 0;\n\t\tvar depth = 0;\n\n\t\tvar escaped = false;\n\n\t\tvar quoted = false;\n\t\tvar quotedMark = false;\n\n\t\tvar inHas = false;\n\n\t\tvar bracketed = 0;\n\n\t\tfor (var i = 0; i < query.length; i++) {\n\t\t\tvar char = query[i];\n\n\t\t\tif (escaped) {\n\t\t\t\tcurrent += char;\n\t\t\t\tescaped = false;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (quoted) {\n\t\t\t\tif (char === quotedMark) {\n\t\t\t\t\tquoted = false;\n\t\t\t\t}\n\n\t\t\t\tcurrent += char;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (current.toLowerCase() === ':has(' && !inHas) {\n\t\t\t\tinHas = true;\n\t\t\t\tstart = i;\n\t\t\t\tcurrent = '';\n\t\t\t}\n\n\t\t\tswitch (char) {\n\t\t\t\tcase ':':\n\t\t\t\t\tif (!inHas) {\n\t\t\t\t\t\tcurrent = '';\n\t\t\t\t\t}\n\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tcontinue;\n\n\t\t\t\tcase '(':\n\t\t\t\t\tif (inHas) {\n\t\t\t\t\t\tdepth++;\n\t\t\t\t\t}\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tcontinue;\n\n\t\t\t\tcase ')':\n\t\t\t\t\tif (inHas) {\n\t\t\t\t\t\tif (depth === 0) {\n\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\tinnerQuery: current,\n\t\t\t\t\t\t\t\tstart: start,\n\t\t\t\t\t\t\t\tend: i-1\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tdepth--;\n\t\t\t\t\t}\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tcontinue;\n\n\t\t\t\tcase '\\\\':\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tescaped = true;\n\t\t\t\t\tcontinue;\n\n\t\t\t\tcase '\"':\n\t\t\t\tcase \"'\":\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tquoted = true;\n\t\t\t\t\tquotedMark = char;\n\t\t\t\t\tcontinue;\n\n\t\t\t\tcase '[':\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tbracketed++;\n\t\t\t\t\tcontinue;\n\n\t\t\t\tcase \"]\":\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tif (bracketed > 0) {\n\t\t\t\t\t\tbracketed--\n\t\t\t\t\t}\n\n\t\t\t\t\tcontinue;\n\t\t\t\n\t\t\t\tdefault:\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\n\t\treturn false;\n\t}\n\n\tfunction replaceScopeWithAttr(query, attr) {\n\t\tvar parts = [];\n\t\tvar current = '';\n\n\t\tvar escaped = false;\n\n\t\tvar quoted = false;\n\t\tvar quotedMark = false;\n\n\t\tvar bracketed = 0;\n\n\t\tfor (var i = 0; i < query.length; i++) {\n\t\t\tvar char = query[i];\n\n\t\t\tif (escaped) {\n\t\t\t\tcurrent += char;\n\t\t\t\tescaped = false;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (quoted) {\n\t\t\t\tif (char === quotedMark) {\n\t\t\t\t\tquoted = false;\n\t\t\t\t}\n\n\t\t\t\tcurrent += char;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (current.toLowerCase() === ':scope' && !bracketed && (/^[\\[\\.\\:\\\\\"\\s|+>~#&,)]/.test(char || ''))) {\n\t\t\t\tparts.push(current.slice(0, current.length - 6));\n\t\t\t\tparts.push('[' + attr + ']');\n\t\t\t\tcurrent = '';\n\t\t\t}\n\n\t\t\tswitch (char) {\n\t\t\t\tcase ':':\n\t\t\t\t\tparts.push(current);\n\t\t\t\t\tcurrent = '';\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tcontinue;\n\n\t\t\t\tcase '\\\\':\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tescaped = true;\n\t\t\t\t\tcontinue;\n\n\t\t\t\tcase '\"':\n\t\t\t\tcase \"'\":\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tquoted = true;\n\t\t\t\t\tquotedMark = char;\n\t\t\t\t\tcontinue;\n\n\t\t\t\tcase '[':\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tbracketed++;\n\t\t\t\t\tcontinue;\n\n\t\t\t\tcase \"]\":\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tif (bracketed > 0) {\n\t\t\t\t\t\tbracketed--\n\t\t\t\t\t}\n\n\t\t\t\t\tcontinue;\n\n\t\t\t\tdefault:\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\n\t\tif (current.toLowerCase() === ':scope') {\n\t\t\tparts.push(current.slice(0, current.length - 6));\n\t\t\tparts.push('[' + attr + ']');\n\t\t\tcurrent = '';\n\t\t}\n\n\t\tif (parts.length === 0) {\n\t\t\treturn query;\n\t\t}\n\n\t\treturn parts.join('') + current;\n\t}\n\n\tfunction charIsNestedMarkMirror(char, mark) {\n\t\tif (mark === '(' && char === ')') {\n\t\t\treturn true;\n\t\t}\n\n\t\tif (mark === '[' && char === ']') {\n\t\t\treturn true;\n\t\t}\n\n\t\treturn false;\n\t}\n\n\tfunction splitSelector(query) {\n\t\tvar selectors = [];\n\t\tvar current = '';\n\n\t\tvar escaped = false;\n\n\t\tvar quoted = false;\n\t\tvar quotedMark = false;\n\n\t\tvar nestedMark = false;\n\t\tvar nestedDepth = 0;\n\n\t\tfor (var i = 0; i < query.length; i++) {\n\t\t\tvar char = query[i];\n\n\t\t\tif (escaped) {\n\t\t\t\tcurrent += char;\n\t\t\t\tescaped = false;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tswitch (char) {\n\t\t\t\tcase ',':\n\t\t\t\t\tif (quoted) {\n\t\t\t\t\t\tcurrent += char;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (nestedDepth > 0) {\n\t\t\t\t\t\tcurrent += char;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tselectors.push(current);\n\t\t\t\t\tcurrent = '';\n\t\t\t\t\tcontinue;\n\n\t\t\t\tcase '\\\\':\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tescaped = true;\n\t\t\t\t\tcontinue;\n\n\t\t\t\tcase '\"':\n\t\t\t\tcase \"'\":\n\t\t\t\t\tif (quoted && char === quotedMark) {\n\t\t\t\t\t\tcurrent += char;\n\t\t\t\t\t\tquoted = false;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tquoted = true;\n\t\t\t\t\tquotedMark = char;\n\t\t\t\t\tcontinue;\n\n\t\t\t\tcase '(':\n\t\t\t\tcase ')':\n\t\t\t\tcase '[':\n\t\t\t\tcase ']':\n\t\t\t\t\tif (quoted) {\n\t\t\t\t\t\tcurrent += char;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (charIsNestedMarkMirror(char, nestedMark)) {\n\t\t\t\t\t\tcurrent += char;\n\t\t\t\t\t\tnestedDepth--;\n\n\t\t\t\t\t\tif (nestedDepth === 0) {\n\t\t\t\t\t\t\tnestedMark = false;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (char === nestedMark) {\n\t\t\t\t\t\tcurrent += char;\n\t\t\t\t\t\tnestedDepth++;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tnestedDepth++;\n\t\t\t\t\tnestedMark = char;\n\t\t\t\t\tcontinue;\n\n\t\t\t\tdefault:\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tcontinue;\n\n\t\t\t}\n\t\t}\n\n\t\tselectors.push(current);\n\n\t\treturn selectors;\n\t}\n\n\tfunction replaceAllWithTempAttr(query, nested, callback) {\n\t\tvar inner = pseudoClassHasInnerQuery(query);\n\t\tif (!inner) {\n\t\t\treturn query;\n\t\t}\n\n\t\tif (nested) {\n\t\t\treturn false;\n\t\t}\n\n\t\tvar innerQuery = inner.innerQuery;\n\t\tvar attr = 'q-has' + (Math.floor(Math.random() * 9000000) + 1000000);\n\t\tvar innerReplacement = '[' + attr + ']';\n\n\t\tvar x = query;\n\n\t\tif (inner.innerQuery.toLowerCase().indexOf(':has(') > -1) {\n\t\t\tvar innerParts = splitSelector(inner.innerQuery);\n\t\t\tvar newInnerParts = [];\n\t\t\tfor (var i = 0; i < innerParts.length; i++) {\n\t\t\t\tvar innerPart = innerParts[i];\n\n\t\t\t\t// Nested has is not supported.\n\t\t\t\t// If a recursive/nested call returns \"false\" we throw\n\t\t\t\tvar innerPartReplaced = replaceAllWithTempAttr(innerPart, true, function () { });\n\t\t\t\tif (!innerPartReplaced) {\n\t\t\t\t\tthrow new Error(\"Nested :has() is not supported\")\n\t\t\t\t} else {\n\t\t\t\t\tnewInnerParts.push(innerPart);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tvar _prefix = x.substring(0, inner.start - 5); // ':has('.length === 5\n\t\t\tvar _suffix = x.substring(inner.end + 2); // ')'.length === 1\n\n\t\t\treturn _prefix + newInnerParts.join(', ') + _suffix;\n\t\t}\n\n\t\tvar _prefix = x.substring(0, inner.start - 5); // ':has('.length === 5\n\t\tvar _suffix = x.substring(inner.end + 2); // ')'.length === 1\n\n\t\tx = _prefix + innerReplacement + _suffix;\n\n\t\tcallback(innerQuery, attr);\n\t\tif (x.toLowerCase().indexOf(':has(') > -1) {\n\t\t\tvar y = replaceAllWithTempAttr(x, false, callback);\n\t\t\tif (y) {\n\t\t\t\treturn y;\n\t\t\t}\n\t\t}\n\n\t\treturn x;\n\t}\n\n\tfunction walkNode(rootNode, callback) {\n\t\tif (('setAttribute' in (rootNode)) && ('querySelector' in (rootNode))) {\n\t\t\tcallback(rootNode);\n\t\t}\n\n\t\tif (rootNode.hasChildNodes()) {\n\t\t\tvar nodes = rootNode.childNodes;\n\t\t\tfor (var i = 0; i < nodes.length; ++i) {\n\t\t\t\twalkNode(nodes[i], callback);\n\t\t\t}\n\t\t}\n\t}\n\n\tfunction polyfill(qsa) {\n\t\treturn function (selectors) {\n\t\t\tif (!selectors) {\n\t\t\t\treturn qsa.apply(this, arguments);\n\t\t\t}\n\n\t\t\tvar selectorsString = String(selectors);\n\t\t\tif (!selectorsString || (selectorsString.toLowerCase().indexOf(':has(') === -1) || !pseudoClassHasInnerQuery(selectorsString)) {\n\t\t\t\treturn qsa.apply(this, arguments);\n\t\t\t}\n\n\t\t\tvar rootNode;\n\t\t\tif ('getRootNode' in this) {\n\t\t\t\trootNode = this.getRootNode();\n\t\t\t} else {\n\t\t\t\tvar r = this;\n\t\t\t\twhile (r) {\n\t\t\t\t\trootNode = r;\n\t\t\t\t\tr = r.parentNode;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tvar _focus = this;\n\t\t\tif (_focus === global.document) {\n\t\t\t\t_focus = global.document.documentElement;\n\t\t\t}\n\n\t\t\tvar scopeAttr = 'q-has-scope' + (Math.floor(Math.random() * 9000000) + 1000000);\n\t\t\t_focus.setAttribute(scopeAttr, '');\n\n\t\t\ttry {\n\t\t\t\tselectorsString = replaceScopeWithAttr(selectorsString, scopeAttr);\n\n\t\t\t\tvar attrs = [scopeAttr];\n\t\t\t\tvar newQuery = replaceAllWithTempAttr(selectorsString, false, function (inner, attr) {\n\t\t\t\t\tattrs.push(attr);\n\n\t\t\t\t\tvar selectorParts = splitSelector(inner);\n\t\t\t\t\tfor (var x = 0; x < selectorParts.length; x++) {\n\t\t\t\t\t\tvar selectorPart = selectorParts[x].trim();\n\t\t\t\t\t\tvar absoluteSelectorPart = selectorPart;\n\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\tselectorPart[0] === '>' ||\n\t\t\t\t\t\t\tselectorPart[0] === '+' ||\n\t\t\t\t\t\t\tselectorPart[0] === '~'\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\tabsoluteSelectorPart = selectorPart.slice(1).trim();\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tabsoluteSelectorPart = ':scope ' + selectorPart;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\twalkNode(rootNode, function (node) {\n\t\t\t\t\t\t\tif (!(node.querySelector(absoluteSelectorPart))) {\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tswitch (selectorPart[0]) {\n\t\t\t\t\t\t\t\tcase '~':\n\t\t\t\t\t\t\t\tcase '+':\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tvar siblings = node.childNodes;\n\t\t\t\t\t\t\t\t\t\tfor (var i = 0; i < siblings.length; i++) {\n\t\t\t\t\t\t\t\t\t\t\tvar sibling = siblings[i];\n\t\t\t\t\t\t\t\t\t\t\tif (!('setAttribute' in sibling)) {\n\t\t\t\t\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\tvar idAttr = 'q-has-id' + (Math.floor(Math.random() * 9000000) + 1000000);\n\t\t\t\t\t\t\t\t\t\t\tsibling.setAttribute(idAttr, '');\n\n\t\t\t\t\t\t\t\t\t\t\tif (node.querySelector(':scope [' + idAttr + ']' + ' ' + selectorPart)) {\n\t\t\t\t\t\t\t\t\t\t\t\tsibling.setAttribute(attr, '');\n\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\tsibling.removeAttribute(idAttr);\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\t\t\tcase '>':\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tvar idAttr = 'q-has-id' + (Math.floor(Math.random() * 9000000) + 1000000);\n\t\t\t\t\t\t\t\t\t\tnode.setAttribute(idAttr, '');\n\n\t\t\t\t\t\t\t\t\t\tif (node.querySelector(':scope[' + idAttr + ']' + ' ' + selectorPart)) {\n\t\t\t\t\t\t\t\t\t\t\tnode.setAttribute(attr, '');\n\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\tnode.removeAttribute(idAttr);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\t\t\tnode.setAttribute(attr, '');\n\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\targuments[0] = newQuery;\n\n\t\t\t\t// results of the qsa\n\t\t\t\tvar elementOrNodeList = qsa.apply(this, arguments);\n\n\t\t\t\t_focus.removeAttribute(scopeAttr);\n\n\t\t\t\tif (attrs.length > 0) {\n\t\t\t\t\t// remove the fallback attribute\n\t\t\t\t\tvar attrsForQuery = [];\n\t\t\t\t\tfor (var j = 0; j < attrs.length; j++) {\n\t\t\t\t\t\tattrsForQuery.push('[' + attrs[j] + ']');\n\t\t\t\t\t}\n\n\t\t\t\t\tvar elements = global.document.querySelectorAll(attrsForQuery.join(','));\n\t\t\t\t\tfor (var k = 0; k < elements.length; k++) {\n\t\t\t\t\t\tvar element = elements[k];\n\t\t\t\t\t\tfor (var l = 0; l < attrs.length; l++) {\n\t\t\t\t\t\t\telement.removeAttribute(attrs[l]);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// return the results of the qsa\n\t\t\t\treturn elementOrNodeList;\n\t\t\t} catch (err) {\n\t\t\t\t_focus.removeAttribute(scopeAttr);\n\n\t\t\t\tif (attrs.length > 0) {\n\t\t\t\t\t// remove the fallback attribute\n\t\t\t\t\tvar attrsForQuery = [];\n\t\t\t\t\tfor (var j = 0; j < attrs.length; j++) {\n\t\t\t\t\t\tattrsForQuery.push('[' + attrs[j] + ']');\n\t\t\t\t\t}\n\n\t\t\t\t\tvar elements = global.document.querySelectorAll(attrsForQuery.join(','));\n\t\t\t\t\tfor (var k = 0; k < elements.length; k++) {\n\t\t\t\t\t\tvar element = elements[k];\n\t\t\t\t\t\tfor (var l = 0; l < attrs.length; l++) {\n\t\t\t\t\t\t\telement.removeAttribute(attrs[l]);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tvar errorMessage = '';\n\t\t\t\ttry {\n\t\t\t\t\tqsa.apply(this, [':core-web-does-not-exist']);\n\t\t\t\t} catch (dummyError) {\n\t\t\t\t\terrorMessage = dummyError.message;\n\t\t\t\t\tif (errorMessage) {\n\t\t\t\t\t\terrorMessage = errorMessage.replace(':core-web-does-not-exist', selectorsString);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (!errorMessage) {\n\t\t\t\t\terrorMessage = \"Failed to execute 'querySelector' on 'Document': '\" + selectorsString + \"' is not a valid selector.\";\n\t\t\t\t}\n\n\t\t\t\ttry {\n\t\t\t\t\tthrow new DOMException(errorMessage);\n\t\t\t\t} catch (_) {\n\t\t\t\t\tthrow new Error(errorMessage);\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\t}\n})(self);\n","import { default as cssHasPseudo } from './browser';\n\n(function (global) {\n\tglobal.cssHasPseudo = cssHasPseudo;\n}('object' === typeof window && window || 'object' === typeof self && self || {}));\n"],"names":["decodeCSS","value","slice","values","split","result","i","length","String","fromCharCode","parseInt","extractEncodedSelectors","candidate","quotedMark","out","depth","quoted","containsUnescapedUnquotedHasAtDepth1","char","decoded","push","unique","indexOf","encodeCSS","hex","charCodeAt","toString","hasNativeSupport","self","CSS","supports","_","cssHasPseudo","document","options","hover","debug","observedAttributes","forcePolyfill","mustPolyfill","Array","isArray","filter","x","concat","observedItems","attributeElement","createElement","forEach","call","styleSheets","walkStyleSheet","transformObservedItemsThrottled","MutationObserver","mutationsList","mutation","addedNodes","node","nodeType","sheet","apply","splice","item","rule","parentStyleSheet","ownerNode","documentElement","contains","observe","childList","subtree","attributes","attributeFilter","addEventListener","Object","observeProperty","proto","property","hasOwnProperty","descriptor","getOwnPropertyDescriptor","configurable","defineProperty","enumerable","get","this","arguments","set","HTMLElement","prototype","elementName","e","console","error","transformObservedItemsThrottledBusy","cancelAnimationFrame","requestAnimationFrame","nodes","matches","querySelectorAll","selector","element","innerHTML","attributeName","setAttributeNode","children","cloneNode","style","zoom","removeAttribute","styleSheet","cssRules","index","selectorText","replace","hasSelectors","deleteRule","hasSelector","global","querySelector","querySelectorWithHasElement","polyfill","Element","selectors","querySelectorAllWithHasElement","matchesWithHasElement","closest","closestWithHasElement","Document","querySelectorWithHasDocument","querySelectorAllWithHasDocument","matchesWithHasDocument","closestWithHasDocument","pseudoClassHasInnerQuery","query","current","start","escaped","inHas","toLowerCase","innerQuery","end","replaceScopeWithAttr","attr","parts","bracketed","test","join","splitSelector","mark","nestedMark","nestedDepth","replaceAllWithTempAttr","nested","callback","inner","Math","floor","random","innerReplacement","innerParts","newInnerParts","innerPart","Error","_prefix","substring","_suffix","y","walkNode","rootNode","hasChildNodes","childNodes","qsa","selectorsString","getRootNode","r","parentNode","_focus","scopeAttr","setAttribute","attrs","newQuery","selectorParts","selectorPart","trim","absoluteSelectorPart","siblings","sibling","idAttr","elementOrNodeList","attrsForQuery","j","elements","k","l","err","errorMessage","dummyError","message","DOMException","window"],"mappings":"YAEe,SAASA,UAAUC,GACjC,GAA2B,kBAAvBA,EAAMC,MAAM,EAAG,IAClB,MAAO,GAOR,IAHA,IAAIC,GADJF,EAAQA,EAAMC,MAAM,KACDE,MAAM,KAErBC,EAAS,GACJC,EAAI,EAAGA,EAAIH,EAAOI,OAAQD,IAClCD,GAAUG,OAAOC,aAAaC,SAASP,EAAOG,GAAI,KAGnD,OAAOD,CACR,CCbe,SAASM,wBAAwBV,GAY/C,IAXA,IAGIW,EAGAC,EANAC,EAAM,GAENC,EAAQ,EAGRC,GAAS,EAGTC,GAAuC,EAGlCX,EAAI,EAAGA,EAAIL,EAAMM,OAAQD,IAAK,CACtC,IAAMY,EAAOjB,EAAMK,GAEnB,OAAQY,GACP,IAAK,IACJ,GAAIF,EAAQ,CACXJ,GAAaM,EACb,QACD,CAEc,IAAVH,EACHH,EAAY,GAEZA,GAAaM,EAGdH,IACA,SACD,IAAK,IACJ,GAAIC,EAAQ,CACXJ,GAAaM,EACb,QACD,CAIC,GAAc,MADdH,EACiB,CAChB,IAAMI,EAAUnB,UAAUY,GACtBK,GACHH,EAAIM,KAAKD,EAEX,MACCP,GAAaM,EAIf,SACD,IAAK,KACJN,GAAaX,EAAMK,GACnBM,GAAaX,EAAMK,EAAE,GACrBA,IACA,SAED,IAAK,IACL,IAAK,IACJ,GAAIU,GAAUE,IAASL,EAAY,CAClCG,GAAS,EACT,QACA,CAAM,GAAIA,EAAQ,CAClBJ,GAAaM,EACb,QACD,CAEAF,GAAS,EACTH,EAAaK,EACb,SAED,QACmB,KAAdN,GAA8B,IAAVG,GAA2C,kBAA3Bd,EAAMC,MAAMI,EAAGA,EAAI,MAC1DW,GAAuC,GAGxCL,GAAaM,EACb,SAEH,CAGA,IADA,IAAMG,EAAS,GACNf,EAAI,EAAGA,EAAIQ,EAAIP,OAAQD,KACC,IAA5Be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a/plugins/css-has-pseudo/dist/browser.cjs.map b/plugins/css-has-pseudo/dist/browser.cjs.map index c295ea4b9..5c727321f 100644 --- a/plugins/css-has-pseudo/dist/browser.cjs.map +++ b/plugins/css-has-pseudo/dist/browser.cjs.map @@ -1 +1 @@ -{"version":3,"file":"browser.cjs","sources":["../src/encode/decode.mjs","../src/encode/extract.mjs","../src/encode/encode.mjs","../src/browser.js","../../../node_modules/@mrhenry/core-web/modules/~element-qsa-has.js"],"sourcesContent":["\n/** Decodes an identifier back into a CSS selector */\nexport default function decodeCSS(value) {\n\tif (value.slice(0, 13) !== 'csstools-has-') {\n\t\treturn '';\n\t}\n\n\tvalue = value.slice(13);\n\tlet values = value.split('-');\n\n\tlet result = '';\n\tfor (let i = 0; i < values.length; i++) {\n\t\tresult += String.fromCharCode(parseInt(values[i], 36));\n\t}\n\n\treturn result;\n}\n","import decodeCSS from './decode.mjs';\n\n/** Extract encoded selectors out of attribute selectors */\nexport default function extractEncodedSelectors(value) {\n\tlet out = [];\n\n\tlet depth = 0;\n\tlet candidate;\n\n\tlet quoted = false;\n\tlet quotedMark;\n\n\tlet containsUnescapedUnquotedHasAtDepth1 = false;\n\n\t// Stryker disable next-line EqualityOperator\n\tfor (let i = 0; i < value.length; i++) {\n\t\tconst char = value[i];\n\n\t\tswitch (char) {\n\t\t\tcase '[':\n\t\t\t\tif (quoted) {\n\t\t\t\t\tcandidate += char;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tif (depth === 0) {\n\t\t\t\t\tcandidate = '';\n\t\t\t\t} else {\n\t\t\t\t\tcandidate += char;\n\t\t\t\t}\n\n\t\t\t\tdepth++;\n\t\t\t\tcontinue;\n\t\t\tcase ']':\n\t\t\t\tif (quoted) {\n\t\t\t\t\tcandidate += char;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\t{\n\t\t\t\t\tdepth--;\n\t\t\t\t\tif (depth === 0) {\n\t\t\t\t\t\tconst decoded = decodeCSS(candidate);\n\t\t\t\t\t\tif (containsUnescapedUnquotedHasAtDepth1) {\n\t\t\t\t\t\t\tout.push(decoded);\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tcandidate += char;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tcontinue;\n\t\t\tcase '\\\\':\n\t\t\t\tcandidate += value[i];\n\t\t\t\tcandidate += value[i+1];\n\t\t\t\ti++;\n\t\t\t\tcontinue;\n\n\t\t\tcase '\"':\n\t\t\tcase '\\'':\n\t\t\t\tif (quoted && char === quotedMark) {\n\t\t\t\t\tquoted = false;\n\t\t\t\t\tcontinue;\n\t\t\t\t} else if (quoted) {\n\t\t\t\t\tcandidate += char;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tquoted = true;\n\t\t\t\tquotedMark = char;\n\t\t\t\tcontinue;\n\n\t\t\tdefault:\n\t\t\t\tif (candidate === '' && depth === 1 && (value.slice(i, i + 13) === 'csstools-has-')) {\n\t\t\t\t\tcontainsUnescapedUnquotedHasAtDepth1 = true;\n\t\t\t\t}\n\n\t\t\t\tcandidate += char;\n\t\t\t\tcontinue;\n\t\t}\n\t}\n\n\tconst unique = [];\n\tfor (let i = 0; i < out.length; i++) {\n\t\tif (unique.indexOf(out[i]) === -1) {\n\t\t\tunique.push(out[i]);\n\t\t}\n\t}\n\n\treturn unique;\n}\n","\n/** Returns the string as an encoded CSS identifier. */\nexport default function encodeCSS(value) {\n\tif (value === '') {\n\t\treturn '';\n\t}\n\n\tlet hex;\n\tlet result = '';\n\tfor (let i = 0; i < value.length; i++) {\n\t\thex = value.charCodeAt(i).toString(36);\n\t\tif (i === 0) {\n\t\t\tresult += hex;\n\t\t} else {\n\t\t\tresult += '-' + hex;\n\t\t}\n\t}\n\n\treturn 'csstools-has-' + result;\n}\n","/* global MutationObserver,requestAnimationFrame,cancelAnimationFrame,self,HTMLElement */\n\nimport '@mrhenry/core-web/modules/~element-qsa-has.js';\nimport extractEncodedSelectors from './encode/extract.mjs';\nimport encodeCSS from './encode/encode.mjs';\n\nfunction hasNativeSupport() {\n\ttry {\n\t\tif (!('CSS' in self) || !('supports' in self.CSS) || !self.CSS.supports('selector(:has(div))')) {\n\t\t\treturn false;\n\t\t}\n\n\t} catch (_) {\n\t\treturn false;\n\t}\n\n\treturn true;\n}\n\nexport default function cssHasPseudo(document, options) {\n\t// OPTIONS\n\t{\n\t\tif (!options) {\n\t\t\toptions = {};\n\t\t}\n\n\t\toptions = {\n\t\t\thover: (!!options.hover) || false,\n\t\t\tdebug: (!!options.debug) || false,\n\t\t\tobservedAttributes: options.observedAttributes || [],\n\t\t\tforcePolyfill: (!!options.forcePolyfill) || false,\n\t\t};\n\n\t\toptions.mustPolyfill = options.forcePolyfill || !hasNativeSupport();\n\n\t\tif (!Array.isArray(options.observedAttributes)) {\n\t\t\toptions.observedAttributes = [];\n\t\t}\n\n\t\toptions.observedAttributes = options.observedAttributes.filter((x) => {\n\t\t\treturn (typeof x === 'string');\n\t\t});\n\n\t\t// https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes\n\t\t// `data-*` and `style` were omitted\n\t\toptions.observedAttributes = options.observedAttributes.concat(['accept', 'accept-charset', 'accesskey', 'action', 'align', 'allow', 'alt', 'async', 'autocapitalize', 'autocomplete', 'autofocus', 'autoplay', 'buffered', 'capture', 'challenge', 'charset', 'checked', 'cite', 'class', 'code', 'codebase', 'cols', 'colspan', 'content', 'contenteditable', 'contextmenu', 'controls', 'coords', 'crossorigin', 'csp', 'data', 'datetime', 'decoding', 'default', 'defer', 'dir', 'dirname', 'disabled', 'download', 'draggable', 'enctype', 'enterkeyhint', 'for', 'form', 'formaction', 'formenctype', 'formmethod', 'formnovalidate', 'formtarget', 'headers', 'hidden', 'high', 'href', 'hreflang', 'http-equiv', 'icon', 'id', 'importance', 'integrity', 'intrinsicsize', 'inputmode', 'ismap', 'itemprop', 'keytype', 'kind', 'label', 'lang', 'language', 'list', 'loop', 'low', 'manifest', 'max', 'maxlength', 'minlength', 'media', 'method', 'min', 'multiple', 'muted', 'name', 'novalidate', 'open', 'optimum', 'pattern', 'ping', 'placeholder', 'poster', 'preload', 'radiogroup', 'readonly', 'referrerpolicy', 'rel', 'required', 'reversed', 'rows', 'rowspan', 'sandbox', 'scope', 'scoped', 'selected', 'shape', 'size', 'sizes', 'slot', 'span', 'spellcheck', 'src', 'srcdoc', 'srclang', 'srcset', 'start', 'step', 'summary', 'tabindex', 'target', 'title', 'translate', 'type', 'usemap', 'value', 'width', 'wrap']);\n\t}\n\n\tconst observedItems = [];\n\n\t// document.createAttribute() doesn't support `:` in the name. innerHTML does\n\tconst attributeElement = document.createElement('x');\n\n\t// walk all stylesheets to collect observed css rules\n\t[].forEach.call(document.styleSheets, walkStyleSheet);\n\tif (!options.mustPolyfill) {\n\t\t// Cleanup of rules will have happened in `walkStyleSheet`\n\t\t// Native support will take over from here\n\t\treturn;\n\t}\n\n\ttransformObservedItemsThrottled();\n\n\t// observe DOM modifications that affect selectors\n\tif ('MutationObserver' in self) {\n\t\tconst mutationObserver = new MutationObserver((mutationsList) => {\n\t\t\tmutationsList.forEach(mutation => {\n\t\t\t\t[].forEach.call(mutation.addedNodes || [], node => {\n\t\t\t\t\t// walk stylesheets to collect observed css rules\n\t\t\t\t\tif (node.nodeType === 1 && node.sheet) {\n\t\t\t\t\t\twalkStyleSheet(node.sheet);\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\t// transform observed css rules\n\t\t\t\tcleanupObservedCssRules();\n\t\t\t\ttransformObservedItemsThrottled();\n\t\t\t});\n\t\t});\n\n\t\tmutationObserver.observe(document, { childList: true, subtree: true, attributes: true, attributeFilter: options.observedAttributes });\n\t}\n\n\t// observe DOM events that affect pseudo-selectors\n\tdocument.addEventListener('focus', transformObservedItemsThrottled, true);\n\tdocument.addEventListener('blur', transformObservedItemsThrottled, true);\n\tdocument.addEventListener('input', transformObservedItemsThrottled);\n\tdocument.addEventListener('change', transformObservedItemsThrottled, true);\n\n\tif (options.hover) {\n\t\tif ('onpointerenter' in document) {\n\t\t\tdocument.addEventListener('pointerenter', transformObservedItemsThrottled, true);\n\t\t\tdocument.addEventListener('pointerleave', transformObservedItemsThrottled, true);\n\t\t} else {\n\t\t\tdocument.addEventListener('mouseover', transformObservedItemsThrottled, true);\n\t\t\tdocument.addEventListener('mouseout', transformObservedItemsThrottled, true);\n\t\t}\n\t}\n\n\t// observe Javascript setters that effect pseudo-selectors\n\tif ('defineProperty' in Object && 'getOwnPropertyDescriptor' in Object && 'hasOwnProperty' in Object) {\n\t\ttry {\n\t\t\t// eslint-disable-next-line no-inner-declarations\n\t\t\tfunction observeProperty(proto, property) {\n\t\t\t\t// eslint-disable-next-line no-prototype-builtins\n\t\t\t\tif (proto.hasOwnProperty(property)) {\n\t\t\t\t\tconst descriptor = Object.getOwnPropertyDescriptor(proto, property);\n\t\t\t\t\tif (descriptor && descriptor.configurable && 'set' in descriptor) {\n\t\t\t\t\t\tObject.defineProperty(proto, property, {\n\t\t\t\t\t\t\tconfigurable: descriptor.configurable,\n\t\t\t\t\t\t\tenumerable: descriptor.enumerable,\n\t\t\t\t\t\t\tget: function () {\n\t\t\t\t\t\t\t\treturn descriptor.get.apply(this, arguments);\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tset: function () {\n\t\t\t\t\t\t\t\tdescriptor.set.apply(this, arguments);\n\n\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\ttransformObservedItemsThrottled();\n\t\t\t\t\t\t\t\t} catch (_) {\n\t\t\t\t\t\t\t\t\t// should never happen as there is an inner try/catch\n\t\t\t\t\t\t\t\t\t// but just in case\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif ('HTMLElement' in self && HTMLElement.prototype) {\n\t\t\t\tobserveProperty(HTMLElement.prototype, 'disabled');\n\t\t\t}\n\n\t\t\t// Not all of these elements have all of these properties.\n\t\t\t// But the code above checks if they exist first.\n\t\t\t['checked', 'selected', 'readOnly', 'required'].forEach((property) => {\n\t\t\t\t[\n\t\t\t\t\t'HTMLButtonElement',\n\t\t\t\t\t'HTMLFieldSetElement',\n\t\t\t\t\t'HTMLInputElement',\n\t\t\t\t\t'HTMLMeterElement',\n\t\t\t\t\t'HTMLOptGroupElement',\n\t\t\t\t\t'HTMLOptionElement',\n\t\t\t\t\t'HTMLOutputElement',\n\t\t\t\t\t'HTMLProgressElement',\n\t\t\t\t\t'HTMLSelectElement',\n\t\t\t\t\t'HTMLTextAreaElement',\n\t\t\t\t].forEach((elementName) => {\n\t\t\t\t\tif (elementName in self && self[elementName].prototype) {\n\t\t\t\t\t\tobserveProperty(self[elementName].prototype, property);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t});\n\t\t} catch (e) {\n\t\t\tif (options.debug) {\n\t\t\t\tconsole.error(e);\n\t\t\t}\n\t\t}\n\t}\n\n\tlet transformObservedItemsThrottledBusy = false;\n\tfunction transformObservedItemsThrottled() {\n\t\tif (transformObservedItemsThrottledBusy) {\n\t\t\tcancelAnimationFrame(transformObservedItemsThrottledBusy);\n\t\t}\n\n\t\ttransformObservedItemsThrottledBusy = requestAnimationFrame(() => {\n\t\t\ttransformObservedItems();\n\t\t});\n\t}\n\n\t// transform observed css rules\n\tfunction transformObservedItems() {\n\t\tobservedItems.forEach((item) => {\n\t\t\tconst nodes = [];\n\n\t\t\tlet matches = [];\n\t\t\ttry {\n\t\t\t\tmatches = document.querySelectorAll(item.selector);\n\t\t\t} catch (e) {\n\t\t\t\tif (options.debug) {\n\t\t\t\t\tconsole.error(e);\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t[].forEach.call(matches, (element) => {\n\t\t\t\t// memorize the node\n\t\t\t\tnodes.push(element);\n\n\t\t\t\t// set an attribute with an irregular attribute name\n\t\t\t\t// document.createAttribute() doesn't support special characters\n\t\t\t\tattributeElement.innerHTML = '';\n\n\t\t\t\telement.setAttributeNode(attributeElement.children[0].attributes[0].cloneNode());\n\n\t\t\t\t// trigger a style refresh in IE and Edge\n\t\t\t\tdocument.documentElement.style.zoom = 1; document.documentElement.style.zoom = null;\n\t\t\t});\n\n\t\t\t// remove the encoded attribute from all nodes that no longer match them\n\t\t\titem.nodes.forEach(node => {\n\t\t\t\tif (nodes.indexOf(node) === -1) {\n\t\t\t\t\tnode.removeAttribute(item.attributeName);\n\n\t\t\t\t\t// trigger a style refresh in IE and Edge\n\t\t\t\t\tdocument.documentElement.style.zoom = 1; document.documentElement.style.zoom = null;\n\t\t\t\t}\n\t\t\t});\n\n\t\t\t// update the\n\t\t\titem.nodes = nodes;\n\t\t});\n\t}\n\n\t// remove any observed cssrules that no longer apply\n\tfunction cleanupObservedCssRules() {\n\t\t[].push.apply(\n\t\t\tobservedItems,\n\t\t\tobservedItems.splice(0).filter((item) => {\n\t\t\t\treturn item.rule.parentStyleSheet &&\n\t\t\t\t\titem.rule.parentStyleSheet.ownerNode &&\n\t\t\t\t\tdocument.documentElement.contains(item.rule.parentStyleSheet.ownerNode);\n\t\t\t}),\n\t\t);\n\t}\n\n\t// walk a stylesheet to collect observed css rules\n\tfunction walkStyleSheet(styleSheet) {\n\t\ttry {\n\t\t\t// walk a css rule to collect observed css rules\n\t\t\t[].forEach.call(styleSheet.cssRules || [], (rule, index) => {\n\t\t\t\tif (rule.selectorText) {\n\t\t\t\t\trule.selectorText = rule.selectorText.replace(/\\.js-has-pseudo\\s/g, '');\n\n\t\t\t\t\ttry {\n\t\t\t\t\t\t// decode the selector text in all browsers to:\n\t\t\t\t\t\tconst hasSelectors = extractEncodedSelectors(rule.selectorText.toString());\n\t\t\t\t\t\tif (hasSelectors.length === 0) {\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (!options.mustPolyfill) {\n\t\t\t\t\t\t\tstyleSheet.deleteRule(index);\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tfor (let i = 0; i < hasSelectors.length; i++) {\n\t\t\t\t\t\t\tconst hasSelector = hasSelectors[i];\n\t\t\t\t\t\t\tobservedItems.push({\n\t\t\t\t\t\t\t\trule: rule,\n\t\t\t\t\t\t\t\tselector: hasSelector,\n\t\t\t\t\t\t\t\tattributeName: encodeCSS(hasSelector),\n\t\t\t\t\t\t\t\tnodes: [],\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\tif (options.debug) {\n\t\t\t\t\t\t\tconsole.error(e);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\twalkStyleSheet(rule);\n\t\t\t\t}\n\t\t\t});\n\t\t} catch (e) {\n\t\t\tif (options.debug) {\n\t\t\t\tconsole.error(e);\n\t\t\t}\n\t\t}\n\t}\n}\n","/* eslint-disable */\n(function (global) {\n\ttry {\n\t\t// test for has support\n\t\tglobal.document.querySelector(':has(*, :does-not-exist, > *)');\n\n\t\tif (\n\t\t\t!global.document.querySelector(':has(:scope *)') &&\n\t\t\tCSS.supports('selector(:has(div))')\n\t\t) {\n\t\t\treturn;\n\t\t}\n\t} catch (_) { }\n\n\t// ELEMENT\n\t// polyfill Element#querySelector\n\tvar querySelectorWithHasElement = polyfill(global.Element.prototype.querySelector);\n\n\tglobal.Element.prototype.querySelector = function querySelector(selectors) {\n\t\treturn querySelectorWithHasElement.apply(this, arguments);\n\t};\n\n\t// polyfill Element#querySelectorAll\n\tvar querySelectorAllWithHasElement = polyfill(global.Element.prototype.querySelectorAll);\n\n\tglobal.Element.prototype.querySelectorAll = function querySelectorAll(selectors) {\n\t\treturn querySelectorAllWithHasElement.apply(this, arguments);\n\t};\n\n\t// polyfill Element#matches\n\tif (global.Element.prototype.matches) {\n\t\tvar matchesWithHasElement = polyfill(global.Element.prototype.matches);\n\n\t\tglobal.Element.prototype.matches = function matches(selectors) {\n\t\t\treturn matchesWithHasElement.apply(this, arguments);\n\t\t};\n\t}\n\n\t// polyfill Element#closest\n\tif (global.Element.prototype.closest) {\n\t\tvar closestWithHasElement = polyfill(global.Element.prototype.closest);\n\n\t\tglobal.Element.prototype.closest = function closest(selectors) {\n\t\t\treturn closestWithHasElement.apply(this, arguments);\n\t\t};\n\t}\n\n\t// DOCUMENT\n\tif ('Document' in global && 'prototype' in global.Document) {\n\t\t// polyfill Document#querySelector\n\t\tvar querySelectorWithHasDocument = polyfill(global.Document.prototype.querySelector);\n\n\t\tglobal.Document.prototype.querySelector = function querySelector(selectors) {\n\t\t\treturn querySelectorWithHasDocument.apply(this, arguments);\n\t\t};\n\n\t\t// polyfill Document#querySelectorAll\n\t\tvar querySelectorAllWithHasDocument = polyfill(global.Document.prototype.querySelectorAll);\n\n\t\tglobal.Document.prototype.querySelectorAll = function querySelectorAll(selectors) {\n\t\t\treturn querySelectorAllWithHasDocument.apply(this, arguments);\n\t\t};\n\n\t\t// polyfill Document#matches\n\t\tif (global.Document.prototype.matches) {\n\t\t\tvar matchesWithHasDocument = polyfill(global.Document.prototype.matches);\n\n\t\t\tglobal.Document.prototype.matches = function matches(selectors) {\n\t\t\t\treturn matchesWithHasDocument.apply(this, arguments);\n\t\t\t};\n\t\t}\n\n\t\t// polyfill Document#closest\n\t\tif (global.Document.prototype.closest) {\n\t\t\tvar closestWithHasDocument = polyfill(global.Document.prototype.closest);\n\n\t\t\tglobal.Document.prototype.closest = function closest(selectors) {\n\t\t\t\treturn closestWithHasDocument.apply(this, arguments);\n\t\t\t};\n\t\t}\n\t}\n\n\tfunction pseudoClassHasInnerQuery(query) {\n\t\tvar current = '';\n\t\tvar start = 0;\n\t\tvar depth = 0;\n\n\t\tvar escaped = false;\n\n\t\tvar quoted = false;\n\t\tvar quotedMark = false;\n\n\t\tvar inHas = false;\n\n\t\tvar bracketed = 0;\n\n\t\tfor (var i = 0; i < query.length; i++) {\n\t\t\tvar char = query[i];\n\n\t\t\tif (escaped) {\n\t\t\t\tcurrent += char;\n\t\t\t\tescaped = false;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (quoted) {\n\t\t\t\tif (char === quotedMark) {\n\t\t\t\t\tquoted = false;\n\t\t\t\t}\n\n\t\t\t\tcurrent += char;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (current.toLowerCase() === ':has(' && !inHas) {\n\t\t\t\tinHas = true;\n\t\t\t\tstart = i;\n\t\t\t\tcurrent = '';\n\t\t\t}\n\n\t\t\tswitch (char) {\n\t\t\t\tcase ':':\n\t\t\t\t\tif (!inHas) {\n\t\t\t\t\t\tcurrent = '';\n\t\t\t\t\t}\n\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tcontinue;\n\n\t\t\t\tcase '(':\n\t\t\t\t\tif (inHas) {\n\t\t\t\t\t\tdepth++;\n\t\t\t\t\t}\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tcontinue;\n\n\t\t\t\tcase ')':\n\t\t\t\t\tif (inHas) {\n\t\t\t\t\t\tif (depth === 0) {\n\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\tinnerQuery: current,\n\t\t\t\t\t\t\t\tstart: start,\n\t\t\t\t\t\t\t\tend: i-1\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tdepth--;\n\t\t\t\t\t}\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tcontinue;\n\n\t\t\t\tcase '\\\\':\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tescaped = true;\n\t\t\t\t\tcontinue;\n\n\t\t\t\tcase '\"':\n\t\t\t\tcase \"'\":\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tquoted = true;\n\t\t\t\t\tquotedMark = char;\n\t\t\t\t\tcontinue;\n\n\t\t\t\tcase '[':\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tbracketed++;\n\t\t\t\t\tcontinue;\n\n\t\t\t\tcase \"]\":\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tif (bracketed > 0) {\n\t\t\t\t\t\tbracketed--\n\t\t\t\t\t}\n\n\t\t\t\t\tcontinue;\n\t\t\t\n\t\t\t\tdefault:\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\n\t\treturn false;\n\t}\n\n\tfunction replaceScopeWithAttr(query, attr) {\n\t\tvar parts = [];\n\t\tvar current = '';\n\n\t\tvar escaped = false;\n\n\t\tvar quoted = false;\n\t\tvar quotedMark = false;\n\n\t\tvar bracketed = 0;\n\n\t\tfor (var i = 0; i < query.length; i++) {\n\t\t\tvar char = query[i];\n\n\t\t\tif (escaped) {\n\t\t\t\tcurrent += char;\n\t\t\t\tescaped = false;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (quoted) {\n\t\t\t\tif (char === quotedMark) {\n\t\t\t\t\tquoted = false;\n\t\t\t\t}\n\n\t\t\t\tcurrent += char;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (current.toLowerCase() === ':scope' && !bracketed && (/^[\\[\\.\\:\\\\\"\\s|+>~#&,)]/.test(char || ''))) {\n\t\t\t\tparts.push(current.slice(0, current.length - 6));\n\t\t\t\tparts.push('[' + attr + ']');\n\t\t\t\tcurrent = '';\n\t\t\t}\n\n\t\t\tswitch (char) {\n\t\t\t\tcase ':':\n\t\t\t\t\tparts.push(current);\n\t\t\t\t\tcurrent = '';\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tcontinue;\n\n\t\t\t\tcase '\\\\':\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tescaped = true;\n\t\t\t\t\tcontinue;\n\n\t\t\t\tcase '\"':\n\t\t\t\tcase \"'\":\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tquoted = true;\n\t\t\t\t\tquotedMark = char;\n\t\t\t\t\tcontinue;\n\n\t\t\t\tcase '[':\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tbracketed++;\n\t\t\t\t\tcontinue;\n\n\t\t\t\tcase \"]\":\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tif (bracketed > 0) {\n\t\t\t\t\t\tbracketed--\n\t\t\t\t\t}\n\n\t\t\t\t\tcontinue;\n\n\t\t\t\tdefault:\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\n\t\tif (current.toLowerCase() === ':scope') {\n\t\t\tparts.push(current.slice(0, current.length - 6));\n\t\t\tparts.push('[' + attr + ']');\n\t\t\tcurrent = '';\n\t\t}\n\n\t\tif (parts.length === 0) {\n\t\t\treturn query;\n\t\t}\n\n\t\treturn parts.join('') + current;\n\t}\n\n\tfunction charIsNestedMarkMirror(char, mark) {\n\t\tif (mark === '(' && char === ')') {\n\t\t\treturn true;\n\t\t}\n\n\t\tif (mark === '[' && char === ']') {\n\t\t\treturn true;\n\t\t}\n\n\t\treturn false;\n\t}\n\n\tfunction splitSelector(query) {\n\t\tvar selectors = [];\n\t\tvar current = '';\n\n\t\tvar escaped = false;\n\n\t\tvar quoted = false;\n\t\tvar quotedMark = false;\n\n\t\tvar nestedMark = false;\n\t\tvar nestedDepth = 0;\n\n\t\tfor (var i = 0; i < query.length; i++) {\n\t\t\tvar char = query[i];\n\n\t\t\tif (escaped) {\n\t\t\t\tcurrent += char;\n\t\t\t\tescaped = false;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tswitch (char) {\n\t\t\t\tcase ',':\n\t\t\t\t\tif (quoted) {\n\t\t\t\t\t\tcurrent += char;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (nestedDepth > 0) {\n\t\t\t\t\t\tcurrent += char;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tselectors.push(current);\n\t\t\t\t\tcurrent = '';\n\t\t\t\t\tcontinue;\n\n\t\t\t\tcase '\\\\':\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tescaped = true;\n\t\t\t\t\tcontinue;\n\n\t\t\t\tcase '\"':\n\t\t\t\tcase \"'\":\n\t\t\t\t\tif (quoted && char === quotedMark) {\n\t\t\t\t\t\tcurrent += char;\n\t\t\t\t\t\tquoted = false;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tquoted = true;\n\t\t\t\t\tquotedMark = char;\n\t\t\t\t\tcontinue;\n\n\t\t\t\tcase '(':\n\t\t\t\tcase ')':\n\t\t\t\tcase '[':\n\t\t\t\tcase ']':\n\t\t\t\t\tif (quoted) {\n\t\t\t\t\t\tcurrent += char;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (charIsNestedMarkMirror(char, nestedMark)) {\n\t\t\t\t\t\tcurrent += char;\n\t\t\t\t\t\tnestedDepth--;\n\n\t\t\t\t\t\tif (nestedDepth === 0) {\n\t\t\t\t\t\t\tnestedMark = false;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (char === nestedMark) {\n\t\t\t\t\t\tcurrent += char;\n\t\t\t\t\t\tnestedDepth++;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tnestedDepth++;\n\t\t\t\t\tnestedMark = char;\n\t\t\t\t\tcontinue;\n\n\t\t\t\tdefault:\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tcontinue;\n\n\t\t\t}\n\t\t}\n\n\t\tselectors.push(current);\n\n\t\treturn selectors;\n\t}\n\n\tfunction replaceAllWithTempAttr(query, nested, callback) {\n\t\tvar inner = pseudoClassHasInnerQuery(query);\n\t\tif (!inner) {\n\t\t\treturn query;\n\t\t}\n\n\t\tif (nested) {\n\t\t\treturn false;\n\t\t}\n\n\t\tvar innerQuery = inner.innerQuery;\n\t\tvar attr = 'q-has' + (Math.floor(Math.random() * 9000000) + 1000000);\n\t\tvar innerReplacement = '[' + attr + ']';\n\n\t\tvar x = query;\n\n\t\tif (inner.innerQuery.toLowerCase().indexOf(':has(') > -1) {\n\t\t\tvar innerParts = splitSelector(inner.innerQuery);\n\t\t\tvar newInnerParts = [];\n\t\t\tfor (var i = 0; i < innerParts.length; i++) {\n\t\t\t\tvar innerPart = innerParts[i];\n\n\t\t\t\t// Nested has is not supported.\n\t\t\t\t// If a recursive/nested call returns \"false\" we throw\n\t\t\t\tvar innerPartReplaced = replaceAllWithTempAttr(innerPart, true, function () { });\n\t\t\t\tif (!innerPartReplaced) {\n\t\t\t\t\tthrow new Error(\"Nested :has() is not supported\")\n\t\t\t\t} else {\n\t\t\t\t\tnewInnerParts.push(innerPart);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tvar _prefix = x.substring(0, inner.start - 5); // ':has('.length === 5\n\t\t\tvar _suffix = x.substring(inner.end + 2); // ')'.length === 1\n\n\t\t\treturn _prefix + newInnerParts.join(', ') + _suffix;\n\t\t}\n\n\t\tvar _prefix = x.substring(0, inner.start - 5); // ':has('.length === 5\n\t\tvar _suffix = x.substring(inner.end + 2); // ')'.length === 1\n\n\t\tx = _prefix + innerReplacement + _suffix;\n\n\t\tcallback(innerQuery, attr);\n\t\tif (x.toLowerCase().indexOf(':has(') > -1) {\n\t\t\tvar y = replaceAllWithTempAttr(x, false, callback);\n\t\t\tif (y) {\n\t\t\t\treturn y;\n\t\t\t}\n\t\t}\n\n\t\treturn x;\n\t}\n\n\tfunction walkNode(rootNode, callback) {\n\t\tif (('setAttribute' in (rootNode)) && ('querySelector' in (rootNode))) {\n\t\t\tcallback(rootNode);\n\t\t}\n\n\t\tif (rootNode.hasChildNodes()) {\n\t\t\tvar nodes = rootNode.childNodes;\n\t\t\tfor (var i = 0; i < nodes.length; ++i) {\n\t\t\t\twalkNode(nodes[i], callback);\n\t\t\t}\n\t\t}\n\t}\n\n\tfunction polyfill(qsa) {\n\t\treturn function (selectors) {\n\t\t\tif (!selectors) {\n\t\t\t\treturn qsa.apply(this, arguments);\n\t\t\t}\n\n\t\t\tvar selectorsString = String(selectors);\n\t\t\tif (!selectorsString || (selectorsString.toLowerCase().indexOf(':has(') === -1) || !pseudoClassHasInnerQuery(selectorsString)) {\n\t\t\t\treturn qsa.apply(this, arguments);\n\t\t\t}\n\n\t\t\tvar rootNode;\n\t\t\tif ('getRootNode' in this) {\n\t\t\t\trootNode = this.getRootNode();\n\t\t\t} else {\n\t\t\t\tvar r = this;\n\t\t\t\twhile (r) {\n\t\t\t\t\trootNode = r;\n\t\t\t\t\tr = r.parentNode;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tvar _focus = this;\n\t\t\tif (_focus === global.document) {\n\t\t\t\t_focus = global.document.documentElement;\n\t\t\t}\n\n\t\t\tvar scopeAttr = 'q-has-scope' + (Math.floor(Math.random() * 9000000) + 1000000);\n\t\t\t_focus.setAttribute(scopeAttr, '');\n\n\t\t\ttry {\n\t\t\t\tselectorsString = replaceScopeWithAttr(selectorsString, scopeAttr);\n\n\t\t\t\tvar attrs = [scopeAttr];\n\t\t\t\tvar newQuery = replaceAllWithTempAttr(selectorsString, false, function (inner, attr) {\n\t\t\t\t\tattrs.push(attr);\n\n\t\t\t\t\tvar selectorParts = splitSelector(inner);\n\t\t\t\t\tfor (var x = 0; x < selectorParts.length; x++) {\n\t\t\t\t\t\tvar selectorPart = selectorParts[x].trim();\n\t\t\t\t\t\tvar absoluteSelectorPart = selectorPart;\n\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\tselectorPart[0] === '>' ||\n\t\t\t\t\t\t\tselectorPart[0] === '+' ||\n\t\t\t\t\t\t\tselectorPart[0] === '~'\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\tabsoluteSelectorPart = selectorPart.slice(1).trim();\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tabsoluteSelectorPart = ':scope ' + selectorPart;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\twalkNode(rootNode, function (node) {\n\t\t\t\t\t\t\tif (!(node.querySelector(absoluteSelectorPart))) {\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tswitch (selectorPart[0]) {\n\t\t\t\t\t\t\t\tcase '~':\n\t\t\t\t\t\t\t\tcase '+':\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tvar siblings = node.childNodes;\n\t\t\t\t\t\t\t\t\t\tfor (var i = 0; i < siblings.length; i++) {\n\t\t\t\t\t\t\t\t\t\t\tvar sibling = siblings[i];\n\t\t\t\t\t\t\t\t\t\t\tif (!('setAttribute' in sibling)) {\n\t\t\t\t\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\tvar idAttr = 'q-has-id' + (Math.floor(Math.random() * 9000000) + 1000000);\n\t\t\t\t\t\t\t\t\t\t\tsibling.setAttribute(idAttr, '');\n\n\t\t\t\t\t\t\t\t\t\t\tif (node.querySelector(':scope [' + idAttr + ']' + ' ' + selectorPart)) {\n\t\t\t\t\t\t\t\t\t\t\t\tsibling.setAttribute(attr, '');\n\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\tsibling.removeAttribute(idAttr);\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\t\t\tcase '>':\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tvar idAttr = 'q-has-id' + (Math.floor(Math.random() * 9000000) + 1000000);\n\t\t\t\t\t\t\t\t\t\tnode.setAttribute(idAttr, '');\n\n\t\t\t\t\t\t\t\t\t\tif (node.querySelector(':scope[' + idAttr + ']' + ' ' + selectorPart)) {\n\t\t\t\t\t\t\t\t\t\t\tnode.setAttribute(attr, '');\n\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\tnode.removeAttribute(idAttr);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\t\t\tnode.setAttribute(attr, '');\n\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\targuments[0] = newQuery;\n\n\t\t\t\t// results of the qsa\n\t\t\t\tvar elementOrNodeList = qsa.apply(this, arguments);\n\n\t\t\t\t_focus.removeAttribute(scopeAttr);\n\n\t\t\t\tif (attrs.length > 0) {\n\t\t\t\t\t// remove the fallback attribute\n\t\t\t\t\tvar attrsForQuery = [];\n\t\t\t\t\tfor (var j = 0; j < attrs.length; j++) {\n\t\t\t\t\t\tattrsForQuery.push('[' + attrs[j] + ']');\n\t\t\t\t\t}\n\n\t\t\t\t\tvar elements = global.document.querySelectorAll(attrsForQuery.join(','));\n\t\t\t\t\tfor (var k = 0; k < elements.length; k++) {\n\t\t\t\t\t\tvar element = elements[k];\n\t\t\t\t\t\tfor (var l = 0; l < attrs.length; l++) {\n\t\t\t\t\t\t\telement.removeAttribute(attrs[l]);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// return the results of the qsa\n\t\t\t\treturn elementOrNodeList;\n\t\t\t} catch (err) {\n\t\t\t\t_focus.removeAttribute(scopeAttr);\n\n\t\t\t\tif (attrs.length > 0) {\n\t\t\t\t\t// remove the fallback attribute\n\t\t\t\t\tvar attrsForQuery = [];\n\t\t\t\t\tfor (var j = 0; j < attrs.length; j++) {\n\t\t\t\t\t\tattrsForQuery.push('[' + attrs[j] + ']');\n\t\t\t\t\t}\n\n\t\t\t\t\tvar elements = global.document.querySelectorAll(attrsForQuery.join(','));\n\t\t\t\t\tfor (var k = 0; k < elements.length; k++) {\n\t\t\t\t\t\tvar element = elements[k];\n\t\t\t\t\t\tfor (var l = 0; l < attrs.length; l++) {\n\t\t\t\t\t\t\telement.removeAttribute(attrs[l]);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tvar errorMessage = '';\n\t\t\t\ttry {\n\t\t\t\t\tqsa.apply(this, [':core-web-does-not-exist']);\n\t\t\t\t} catch (dummyError) {\n\t\t\t\t\terrorMessage = dummyError.message;\n\t\t\t\t\tif (errorMessage) {\n\t\t\t\t\t\terrorMessage = errorMessage.replace(':core-web-does-not-exist', selectorsString);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (!errorMessage) {\n\t\t\t\t\terrorMessage = \"Failed to execute 'querySelector' on 'Document': '\" + selectorsString + \"' is not a valid selector.\";\n\t\t\t\t}\n\n\t\t\t\ttry {\n\t\t\t\t\tthrow new DOMException(errorMessage);\n\t\t\t\t} catch (_) {\n\t\t\t\t\tthrow new Error(errorMessage);\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\t}\n})(self);\n"],"names":["decodeCSS","value","slice","values","split","result","i","length","String","fromCharCode","parseInt","extractEncodedSelectors","candidate","quotedMark","out","depth","quoted","containsUnescapedUnquotedHasAtDepth1","char","decoded","push","unique","indexOf","encodeCSS","hex","charCodeAt","toString","hasNativeSupport","self","CSS","supports","_","global","document","querySelector","querySelectorWithHasElement","polyfill","Element","prototype","selectors","apply","this","arguments","querySelectorAllWithHasElement","querySelectorAll","matches","matchesWithHasElement","closest","closestWithHasElement","Document","querySelectorWithHasDocument","querySelectorAllWithHasDocument","matchesWithHasDocument","closestWithHasDocument","pseudoClassHasInnerQuery","query","current","start","escaped","inHas","toLowerCase","innerQuery","end","replaceScopeWithAttr","attr","parts","bracketed","test","join","splitSelector","mark","nestedMark","nestedDepth","replaceAllWithTempAttr","nested","callback","inner","Math","floor","random","innerReplacement","x","innerParts","newInnerParts","innerPart","Error","_prefix","substring","_suffix","y","walkNode","rootNode","hasChildNodes","nodes","childNodes","qsa","selectorsString","getRootNode","r","parentNode","_focus","documentElement","scopeAttr","setAttribute","attrs","newQuery","selectorParts","selectorPart","trim","absoluteSelectorPart","node","siblings","sibling","idAttr","removeAttribute","elementOrNodeList","attrsForQuery","j","elements","k","element","l","err","errorMessage","dummyError","message","replace","DOMException","cssHasPseudo","options","hover","debug","observedAttributes","forcePolyfill","mustPolyfill","Array","isArray","filter","concat","observedItems","attributeElement","createElement","forEach","call","styleSheets","walkStyleSheet","transformObservedItemsThrottled","MutationObserver","mutationsList","mutation","addedNodes","nodeType","sheet","splice","item","rule","parentStyleSheet","ownerNode","contains","observe","childList","subtree","attributes","attributeFilter","addEventListener","Object","observeProperty","proto","property","hasOwnProperty","descriptor","getOwnPropertyDescriptor","configurable","defineProperty","enumerable","get","set","HTMLElement","elementName","e","console","error","transformObservedItemsThrottledBusy","cancelAnimationFrame","requestAnimationFrame","selector","innerHTML","attributeName","setAttributeNode","children","cloneNode","style","zoom","styleSheet","cssRules","index","selectorText","hasSelectors","deleteRule","hasSelector"],"mappings":"AAEe,SAASA,UAAUC,GACjC,GAA2B,kBAAvBA,EAAMC,MAAM,EAAG,IAClB,MAAO,GAOR,IAHA,IAAIC,GADJF,EAAQA,EAAMC,MAAM,KACDE,MAAM,KAErBC,EAAS,GACJC,EAAI,EAAGA,EAAIH,EAAOI,OAAQD,IAClCD,GAAUG,OAAOC,aAAaC,SAASP,EAAOG,GAAI,KAGnD,OAAOD,CACR,CCbe,SAASM,wBAAwBV,GAY/C,IAXA,IAGIW,EAGAC,EANAC,EAAM,GAENC,EAAQ,EAGRC,GAAS,EAGTC,GAAuC,EAGlCX,EAAI,EAAGA,EAAIL,EAAMM,OAAQD,IAAK,CACtC,IAAMY,EAAOjB,EAAMK,GAEnB,OAAQY,GACP,IAAK,IACJ,GAAIF,EAAQ,CACXJ,GAAaM,EACb,QACD,CAEc,IAAVH,EACHH,EAAY,GAEZA,GAAaM,EAGdH,IACA,SACD,IAAK,IACJ,GAAIC,EAAQ,CACXJ,GAAaM,EACb,QACD,CAIC,GAAc,MADdH,EACiB,CAChB,IAAMI,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L,EAAa9L,OAAQD,IAAK,CAC7C,IAAMiM,EAAcF,EAAa/L,GACjCqI,EAAcvH,KAAK,CAClBuI,KAAMA,EACN8B,SAAUc,EACVZ,cAAepK,UAAUgL,GACzB1G,MAAO,IAET,CACA,CAAC,MAAOsF,GACJlD,EAAQE,OACXiD,QAAQC,MAAMF,EAEhB,CACD,MACClC,eAAeU,EAEjB,GACA,CAAC,MAAOwB,GACJlD,EAAQE,OACXiD,QAAQC,MAAMF,EAEhB,CACD,CACD","x_google_ignoreList":[4]} \ No newline at end of file +{"version":3,"file":"browser.cjs","sources":["../src/encode/decode.mjs","../src/encode/extract.mjs","../src/encode/encode.mjs","../src/browser.js","../../../node_modules/@mrhenry/core-web/modules/~element-qsa-has.js"],"sourcesContent":["\n/** Decodes an identifier back into a CSS selector */\nexport default function decodeCSS(value) {\n\tif (value.slice(0, 13) !== 'csstools-has-') {\n\t\treturn '';\n\t}\n\n\tvalue = value.slice(13);\n\tlet values = value.split('-');\n\n\tlet result = '';\n\tfor (let i = 0; i < values.length; i++) {\n\t\tresult += String.fromCharCode(parseInt(values[i], 36));\n\t}\n\n\treturn result;\n}\n","import decodeCSS from './decode.mjs';\n\n/** Extract encoded selectors out of attribute selectors */\nexport default function extractEncodedSelectors(value) {\n\tlet out = [];\n\n\tlet depth = 0;\n\tlet candidate;\n\n\tlet quoted = false;\n\tlet quotedMark;\n\n\tlet containsUnescapedUnquotedHasAtDepth1 = false;\n\n\t// Stryker disable next-line EqualityOperator\n\tfor (let i = 0; i < value.length; i++) {\n\t\tconst char = value[i];\n\n\t\tswitch (char) {\n\t\t\tcase '[':\n\t\t\t\tif (quoted) {\n\t\t\t\t\tcandidate += char;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tif (depth === 0) {\n\t\t\t\t\tcandidate = '';\n\t\t\t\t} else {\n\t\t\t\t\tcandidate += char;\n\t\t\t\t}\n\n\t\t\t\tdepth++;\n\t\t\t\tcontinue;\n\t\t\tcase ']':\n\t\t\t\tif (quoted) {\n\t\t\t\t\tcandidate += char;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\t{\n\t\t\t\t\tdepth--;\n\t\t\t\t\tif (depth === 0) {\n\t\t\t\t\t\tconst decoded = decodeCSS(candidate);\n\t\t\t\t\t\tif (containsUnescapedUnquotedHasAtDepth1) {\n\t\t\t\t\t\t\tout.push(decoded);\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tcandidate += char;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tcontinue;\n\t\t\tcase '\\\\':\n\t\t\t\tcandidate += value[i];\n\t\t\t\tcandidate += value[i+1];\n\t\t\t\ti++;\n\t\t\t\tcontinue;\n\n\t\t\tcase '\"':\n\t\t\tcase '\\'':\n\t\t\t\tif (quoted && char === quotedMark) {\n\t\t\t\t\tquoted = false;\n\t\t\t\t\tcontinue;\n\t\t\t\t} else if (quoted) {\n\t\t\t\t\tcandidate += char;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tquoted = true;\n\t\t\t\tquotedMark = char;\n\t\t\t\tcontinue;\n\n\t\t\tdefault:\n\t\t\t\tif (candidate === '' && depth === 1 && (value.slice(i, i + 13) === 'csstools-has-')) {\n\t\t\t\t\tcontainsUnescapedUnquotedHasAtDepth1 = true;\n\t\t\t\t}\n\n\t\t\t\tcandidate += char;\n\t\t\t\tcontinue;\n\t\t}\n\t}\n\n\tconst unique = [];\n\tfor (let i = 0; i < out.length; i++) {\n\t\tif (unique.indexOf(out[i]) === -1) {\n\t\t\tunique.push(out[i]);\n\t\t}\n\t}\n\n\treturn unique;\n}\n","\n/** Returns the string as an encoded CSS identifier. */\nexport default function encodeCSS(value) {\n\tif (value === '') {\n\t\treturn '';\n\t}\n\n\tlet hex;\n\tlet result = '';\n\tfor (let i = 0; i < value.length; i++) {\n\t\thex = value.charCodeAt(i).toString(36);\n\t\tif (i === 0) {\n\t\t\tresult += hex;\n\t\t} else {\n\t\t\tresult += '-' + hex;\n\t\t}\n\t}\n\n\treturn 'csstools-has-' + result;\n}\n","import '@mrhenry/core-web/modules/~element-qsa-has.js';\nimport extractEncodedSelectors from './encode/extract.mjs';\nimport encodeCSS from './encode/encode.mjs';\n\nfunction hasNativeSupport() {\n\ttry {\n\t\tif (!('CSS' in self) || !('supports' in self.CSS) || !self.CSS.supports('selector(:has(div))')) {\n\t\t\treturn false;\n\t\t}\n\n\t} catch (_) {\n\t\treturn false;\n\t}\n\n\treturn true;\n}\n\nexport default function cssHasPseudo(document, options) {\n\t// OPTIONS\n\t{\n\t\tif (!options) {\n\t\t\toptions = {};\n\t\t}\n\n\t\toptions = {\n\t\t\thover: (!!options.hover) || false,\n\t\t\tdebug: (!!options.debug) || false,\n\t\t\tobservedAttributes: options.observedAttributes || [],\n\t\t\tforcePolyfill: (!!options.forcePolyfill) || false,\n\t\t};\n\n\t\toptions.mustPolyfill = options.forcePolyfill || !hasNativeSupport();\n\n\t\tif (!Array.isArray(options.observedAttributes)) {\n\t\t\toptions.observedAttributes = [];\n\t\t}\n\n\t\toptions.observedAttributes = options.observedAttributes.filter((x) => {\n\t\t\treturn (typeof x === 'string');\n\t\t});\n\n\t\t// https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes\n\t\t// `data-*` and `style` were omitted\n\t\toptions.observedAttributes = options.observedAttributes.concat(['accept', 'accept-charset', 'accesskey', 'action', 'align', 'allow', 'alt', 'async', 'autocapitalize', 'autocomplete', 'autofocus', 'autoplay', 'buffered', 'capture', 'challenge', 'charset', 'checked', 'cite', 'class', 'code', 'codebase', 'cols', 'colspan', 'content', 'contenteditable', 'contextmenu', 'controls', 'coords', 'crossorigin', 'csp', 'data', 'datetime', 'decoding', 'default', 'defer', 'dir', 'dirname', 'disabled', 'download', 'draggable', 'enctype', 'enterkeyhint', 'for', 'form', 'formaction', 'formenctype', 'formmethod', 'formnovalidate', 'formtarget', 'headers', 'hidden', 'high', 'href', 'hreflang', 'http-equiv', 'icon', 'id', 'importance', 'integrity', 'intrinsicsize', 'inputmode', 'ismap', 'itemprop', 'keytype', 'kind', 'label', 'lang', 'language', 'list', 'loop', 'low', 'manifest', 'max', 'maxlength', 'minlength', 'media', 'method', 'min', 'multiple', 'muted', 'name', 'novalidate', 'open', 'optimum', 'pattern', 'ping', 'placeholder', 'poster', 'preload', 'radiogroup', 'readonly', 'referrerpolicy', 'rel', 'required', 'reversed', 'rows', 'rowspan', 'sandbox', 'scope', 'scoped', 'selected', 'shape', 'size', 'sizes', 'slot', 'span', 'spellcheck', 'src', 'srcdoc', 'srclang', 'srcset', 'start', 'step', 'summary', 'tabindex', 'target', 'title', 'translate', 'type', 'usemap', 'value', 'width', 'wrap']);\n\t}\n\n\tconst observedItems = [];\n\n\t// document.createAttribute() doesn't support `:` in the name. innerHTML does\n\tconst attributeElement = document.createElement('x');\n\n\t// walk all stylesheets to collect observed css rules\n\t[].forEach.call(document.styleSheets, walkStyleSheet);\n\tif (!options.mustPolyfill) {\n\t\t// Cleanup of rules will have happened in `walkStyleSheet`\n\t\t// Native support will take over from here\n\t\treturn;\n\t}\n\n\ttransformObservedItemsThrottled();\n\n\t// observe DOM modifications that affect selectors\n\tif ('MutationObserver' in self) {\n\t\tconst mutationObserver = new MutationObserver((mutationsList) => {\n\t\t\tmutationsList.forEach(mutation => {\n\t\t\t\t[].forEach.call(mutation.addedNodes || [], node => {\n\t\t\t\t\t// walk stylesheets to collect observed css rules\n\t\t\t\t\tif (node.nodeType === 1 && node.sheet) {\n\t\t\t\t\t\twalkStyleSheet(node.sheet);\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\t// transform observed css rules\n\t\t\t\tcleanupObservedCssRules();\n\t\t\t\ttransformObservedItemsThrottled();\n\t\t\t});\n\t\t});\n\n\t\tmutationObserver.observe(document, { childList: true, subtree: true, attributes: true, attributeFilter: options.observedAttributes });\n\t}\n\n\t// observe DOM events that affect pseudo-selectors\n\tdocument.addEventListener('focus', transformObservedItemsThrottled, true);\n\tdocument.addEventListener('blur', transformObservedItemsThrottled, true);\n\tdocument.addEventListener('input', transformObservedItemsThrottled);\n\tdocument.addEventListener('change', transformObservedItemsThrottled, true);\n\n\tif (options.hover) {\n\t\tif ('onpointerenter' in document) {\n\t\t\tdocument.addEventListener('pointerenter', transformObservedItemsThrottled, true);\n\t\t\tdocument.addEventListener('pointerleave', transformObservedItemsThrottled, true);\n\t\t} else {\n\t\t\tdocument.addEventListener('mouseover', transformObservedItemsThrottled, true);\n\t\t\tdocument.addEventListener('mouseout', transformObservedItemsThrottled, true);\n\t\t}\n\t}\n\n\t// observe Javascript setters that effect pseudo-selectors\n\tif ('defineProperty' in Object && 'getOwnPropertyDescriptor' in Object && 'hasOwnProperty' in Object) {\n\t\ttry {\n\t\t\tfunction observeProperty(proto, property) {\n\t\t\t\t// eslint-disable-next-line no-prototype-builtins\n\t\t\t\tif (proto.hasOwnProperty(property)) {\n\t\t\t\t\tconst descriptor = Object.getOwnPropertyDescriptor(proto, property);\n\t\t\t\t\tif (descriptor && descriptor.configurable && 'set' in descriptor) {\n\t\t\t\t\t\tObject.defineProperty(proto, property, {\n\t\t\t\t\t\t\tconfigurable: descriptor.configurable,\n\t\t\t\t\t\t\tenumerable: descriptor.enumerable,\n\t\t\t\t\t\t\tget: function () {\n\t\t\t\t\t\t\t\treturn descriptor.get.apply(this, arguments);\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tset: function () {\n\t\t\t\t\t\t\t\tdescriptor.set.apply(this, arguments);\n\n\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\ttransformObservedItemsThrottled();\n\t\t\t\t\t\t\t\t} catch (_) {\n\t\t\t\t\t\t\t\t\t// should never happen as there is an inner try/catch\n\t\t\t\t\t\t\t\t\t// but just in case\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif ('HTMLElement' in self && HTMLElement.prototype) {\n\t\t\t\tobserveProperty(HTMLElement.prototype, 'disabled');\n\t\t\t}\n\n\t\t\t// Not all of these elements have all of these properties.\n\t\t\t// But the code above checks if they exist first.\n\t\t\t['checked', 'selected', 'readOnly', 'required'].forEach((property) => {\n\t\t\t\t[\n\t\t\t\t\t'HTMLButtonElement',\n\t\t\t\t\t'HTMLFieldSetElement',\n\t\t\t\t\t'HTMLInputElement',\n\t\t\t\t\t'HTMLMeterElement',\n\t\t\t\t\t'HTMLOptGroupElement',\n\t\t\t\t\t'HTMLOptionElement',\n\t\t\t\t\t'HTMLOutputElement',\n\t\t\t\t\t'HTMLProgressElement',\n\t\t\t\t\t'HTMLSelectElement',\n\t\t\t\t\t'HTMLTextAreaElement',\n\t\t\t\t].forEach((elementName) => {\n\t\t\t\t\tif (elementName in self && self[elementName].prototype) {\n\t\t\t\t\t\tobserveProperty(self[elementName].prototype, property);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t});\n\t\t} catch (e) {\n\t\t\tif (options.debug) {\n\t\t\t\tconsole.error(e);\n\t\t\t}\n\t\t}\n\t}\n\n\tlet transformObservedItemsThrottledBusy = false;\n\tfunction transformObservedItemsThrottled() {\n\t\tif (transformObservedItemsThrottledBusy) {\n\t\t\tcancelAnimationFrame(transformObservedItemsThrottledBusy);\n\t\t}\n\n\t\ttransformObservedItemsThrottledBusy = requestAnimationFrame(() => {\n\t\t\ttransformObservedItems();\n\t\t});\n\t}\n\n\t// transform observed css rules\n\tfunction transformObservedItems() {\n\t\tobservedItems.forEach((item) => {\n\t\t\tconst nodes = [];\n\n\t\t\tlet matches = [];\n\t\t\ttry {\n\t\t\t\tmatches = document.querySelectorAll(item.selector);\n\t\t\t} catch (e) {\n\t\t\t\tif (options.debug) {\n\t\t\t\t\tconsole.error(e);\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t[].forEach.call(matches, (element) => {\n\t\t\t\t// memorize the node\n\t\t\t\tnodes.push(element);\n\n\t\t\t\t// set an attribute with an irregular attribute name\n\t\t\t\t// document.createAttribute() doesn't support special characters\n\t\t\t\tattributeElement.innerHTML = '';\n\n\t\t\t\telement.setAttributeNode(attributeElement.children[0].attributes[0].cloneNode());\n\n\t\t\t\t// trigger a style refresh in IE and Edge\n\t\t\t\tdocument.documentElement.style.zoom = 1; document.documentElement.style.zoom = null;\n\t\t\t});\n\n\t\t\t// remove the encoded attribute from all nodes that no longer match them\n\t\t\titem.nodes.forEach(node => {\n\t\t\t\tif (nodes.indexOf(node) === -1) {\n\t\t\t\t\tnode.removeAttribute(item.attributeName);\n\n\t\t\t\t\t// trigger a style refresh in IE and Edge\n\t\t\t\t\tdocument.documentElement.style.zoom = 1; document.documentElement.style.zoom = null;\n\t\t\t\t}\n\t\t\t});\n\n\t\t\t// update the\n\t\t\titem.nodes = nodes;\n\t\t});\n\t}\n\n\t// remove any observed cssrules that no longer apply\n\tfunction cleanupObservedCssRules() {\n\t\t[].push.apply(\n\t\t\tobservedItems,\n\t\t\tobservedItems.splice(0).filter((item) => {\n\t\t\t\treturn item.rule.parentStyleSheet &&\n\t\t\t\t\titem.rule.parentStyleSheet.ownerNode &&\n\t\t\t\t\tdocument.documentElement.contains(item.rule.parentStyleSheet.ownerNode);\n\t\t\t}),\n\t\t);\n\t}\n\n\t// walk a stylesheet to collect observed css rules\n\tfunction walkStyleSheet(styleSheet) {\n\t\ttry {\n\t\t\t// walk a css rule to collect observed css rules\n\t\t\t[].forEach.call(styleSheet.cssRules || [], (rule, index) => {\n\t\t\t\tif (rule.selectorText) {\n\t\t\t\t\trule.selectorText = rule.selectorText.replace(/\\.js-has-pseudo\\s/g, '');\n\n\t\t\t\t\ttry {\n\t\t\t\t\t\t// decode the selector text in all browsers to:\n\t\t\t\t\t\tconst hasSelectors = extractEncodedSelectors(rule.selectorText.toString());\n\t\t\t\t\t\tif (hasSelectors.length === 0) {\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (!options.mustPolyfill) {\n\t\t\t\t\t\t\tstyleSheet.deleteRule(index);\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tfor (let i = 0; i < hasSelectors.length; i++) {\n\t\t\t\t\t\t\tconst hasSelector = hasSelectors[i];\n\t\t\t\t\t\t\tobservedItems.push({\n\t\t\t\t\t\t\t\trule: rule,\n\t\t\t\t\t\t\t\tselector: hasSelector,\n\t\t\t\t\t\t\t\tattributeName: encodeCSS(hasSelector),\n\t\t\t\t\t\t\t\tnodes: [],\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\tif (options.debug) {\n\t\t\t\t\t\t\tconsole.error(e);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\twalkStyleSheet(rule);\n\t\t\t\t}\n\t\t\t});\n\t\t} catch (e) {\n\t\t\tif (options.debug) {\n\t\t\t\tconsole.error(e);\n\t\t\t}\n\t\t}\n\t}\n}\n","/* eslint-disable */\n(function (global) {\n\ttry {\n\t\t// test for has support\n\t\tglobal.document.querySelector(':has(*, :does-not-exist, > *)');\n\n\t\tif (\n\t\t\t!global.document.querySelector(':has(:scope *)') &&\n\t\t\tCSS.supports('selector(:has(div))')\n\t\t) {\n\t\t\treturn;\n\t\t}\n\t} catch (_) { }\n\n\t// ELEMENT\n\t// polyfill Element#querySelector\n\tvar querySelectorWithHasElement = polyfill(global.Element.prototype.querySelector);\n\n\tglobal.Element.prototype.querySelector = function querySelector(selectors) {\n\t\treturn querySelectorWithHasElement.apply(this, arguments);\n\t};\n\n\t// polyfill Element#querySelectorAll\n\tvar querySelectorAllWithHasElement = polyfill(global.Element.prototype.querySelectorAll);\n\n\tglobal.Element.prototype.querySelectorAll = function querySelectorAll(selectors) {\n\t\treturn querySelectorAllWithHasElement.apply(this, arguments);\n\t};\n\n\t// polyfill Element#matches\n\tif (global.Element.prototype.matches) {\n\t\tvar matchesWithHasElement = polyfill(global.Element.prototype.matches);\n\n\t\tglobal.Element.prototype.matches = function matches(selectors) {\n\t\t\treturn matchesWithHasElement.apply(this, arguments);\n\t\t};\n\t}\n\n\t// polyfill Element#closest\n\tif (global.Element.prototype.closest) {\n\t\tvar closestWithHasElement = polyfill(global.Element.prototype.closest);\n\n\t\tglobal.Element.prototype.closest = function closest(selectors) {\n\t\t\treturn closestWithHasElement.apply(this, arguments);\n\t\t};\n\t}\n\n\t// DOCUMENT\n\tif ('Document' in global && 'prototype' in global.Document) {\n\t\t// polyfill Document#querySelector\n\t\tvar querySelectorWithHasDocument = polyfill(global.Document.prototype.querySelector);\n\n\t\tglobal.Document.prototype.querySelector = function querySelector(selectors) {\n\t\t\treturn querySelectorWithHasDocument.apply(this, arguments);\n\t\t};\n\n\t\t// polyfill Document#querySelectorAll\n\t\tvar querySelectorAllWithHasDocument = polyfill(global.Document.prototype.querySelectorAll);\n\n\t\tglobal.Document.prototype.querySelectorAll = function querySelectorAll(selectors) {\n\t\t\treturn querySelectorAllWithHasDocument.apply(this, arguments);\n\t\t};\n\n\t\t// polyfill Document#matches\n\t\tif (global.Document.prototype.matches) {\n\t\t\tvar matchesWithHasDocument = polyfill(global.Document.prototype.matches);\n\n\t\t\tglobal.Document.prototype.matches = function matches(selectors) {\n\t\t\t\treturn matchesWithHasDocument.apply(this, arguments);\n\t\t\t};\n\t\t}\n\n\t\t// polyfill Document#closest\n\t\tif (global.Document.prototype.closest) {\n\t\t\tvar closestWithHasDocument = polyfill(global.Document.prototype.closest);\n\n\t\t\tglobal.Document.prototype.closest = function closest(selectors) {\n\t\t\t\treturn closestWithHasDocument.apply(this, arguments);\n\t\t\t};\n\t\t}\n\t}\n\n\tfunction pseudoClassHasInnerQuery(query) {\n\t\tvar current = '';\n\t\tvar start = 0;\n\t\tvar depth = 0;\n\n\t\tvar escaped = false;\n\n\t\tvar quoted = false;\n\t\tvar quotedMark = false;\n\n\t\tvar inHas = false;\n\n\t\tvar bracketed = 0;\n\n\t\tfor (var i = 0; i < query.length; i++) {\n\t\t\tvar char = query[i];\n\n\t\t\tif (escaped) {\n\t\t\t\tcurrent += char;\n\t\t\t\tescaped = false;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (quoted) {\n\t\t\t\tif (char === quotedMark) {\n\t\t\t\t\tquoted = false;\n\t\t\t\t}\n\n\t\t\t\tcurrent += char;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (current.toLowerCase() === ':has(' && !inHas) {\n\t\t\t\tinHas = true;\n\t\t\t\tstart = i;\n\t\t\t\tcurrent = '';\n\t\t\t}\n\n\t\t\tswitch (char) {\n\t\t\t\tcase ':':\n\t\t\t\t\tif (!inHas) {\n\t\t\t\t\t\tcurrent = '';\n\t\t\t\t\t}\n\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tcontinue;\n\n\t\t\t\tcase '(':\n\t\t\t\t\tif (inHas) {\n\t\t\t\t\t\tdepth++;\n\t\t\t\t\t}\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tcontinue;\n\n\t\t\t\tcase ')':\n\t\t\t\t\tif (inHas) {\n\t\t\t\t\t\tif (depth === 0) {\n\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\tinnerQuery: current,\n\t\t\t\t\t\t\t\tstart: start,\n\t\t\t\t\t\t\t\tend: i-1\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tdepth--;\n\t\t\t\t\t}\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tcontinue;\n\n\t\t\t\tcase '\\\\':\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tescaped = true;\n\t\t\t\t\tcontinue;\n\n\t\t\t\tcase '\"':\n\t\t\t\tcase \"'\":\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tquoted = true;\n\t\t\t\t\tquotedMark = char;\n\t\t\t\t\tcontinue;\n\n\t\t\t\tcase '[':\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tbracketed++;\n\t\t\t\t\tcontinue;\n\n\t\t\t\tcase \"]\":\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tif (bracketed > 0) {\n\t\t\t\t\t\tbracketed--\n\t\t\t\t\t}\n\n\t\t\t\t\tcontinue;\n\t\t\t\n\t\t\t\tdefault:\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\n\t\treturn false;\n\t}\n\n\tfunction replaceScopeWithAttr(query, attr) {\n\t\tvar parts = [];\n\t\tvar current = '';\n\n\t\tvar escaped = false;\n\n\t\tvar quoted = false;\n\t\tvar quotedMark = false;\n\n\t\tvar bracketed = 0;\n\n\t\tfor (var i = 0; i < query.length; i++) {\n\t\t\tvar char = query[i];\n\n\t\t\tif (escaped) {\n\t\t\t\tcurrent += char;\n\t\t\t\tescaped = false;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (quoted) {\n\t\t\t\tif (char === quotedMark) {\n\t\t\t\t\tquoted = false;\n\t\t\t\t}\n\n\t\t\t\tcurrent += char;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (current.toLowerCase() === ':scope' && !bracketed && (/^[\\[\\.\\:\\\\\"\\s|+>~#&,)]/.test(char || ''))) {\n\t\t\t\tparts.push(current.slice(0, current.length - 6));\n\t\t\t\tparts.push('[' + attr + ']');\n\t\t\t\tcurrent = '';\n\t\t\t}\n\n\t\t\tswitch (char) {\n\t\t\t\tcase ':':\n\t\t\t\t\tparts.push(current);\n\t\t\t\t\tcurrent = '';\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tcontinue;\n\n\t\t\t\tcase '\\\\':\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tescaped = true;\n\t\t\t\t\tcontinue;\n\n\t\t\t\tcase '\"':\n\t\t\t\tcase \"'\":\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tquoted = true;\n\t\t\t\t\tquotedMark = char;\n\t\t\t\t\tcontinue;\n\n\t\t\t\tcase '[':\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tbracketed++;\n\t\t\t\t\tcontinue;\n\n\t\t\t\tcase \"]\":\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tif (bracketed > 0) {\n\t\t\t\t\t\tbracketed--\n\t\t\t\t\t}\n\n\t\t\t\t\tcontinue;\n\n\t\t\t\tdefault:\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\n\t\tif (current.toLowerCase() === ':scope') {\n\t\t\tparts.push(current.slice(0, current.length - 6));\n\t\t\tparts.push('[' + attr + ']');\n\t\t\tcurrent = '';\n\t\t}\n\n\t\tif (parts.length === 0) {\n\t\t\treturn query;\n\t\t}\n\n\t\treturn parts.join('') + current;\n\t}\n\n\tfunction charIsNestedMarkMirror(char, mark) {\n\t\tif (mark === '(' && char === ')') {\n\t\t\treturn true;\n\t\t}\n\n\t\tif (mark === '[' && char === ']') {\n\t\t\treturn true;\n\t\t}\n\n\t\treturn false;\n\t}\n\n\tfunction splitSelector(query) {\n\t\tvar selectors = [];\n\t\tvar current = '';\n\n\t\tvar escaped = false;\n\n\t\tvar quoted = false;\n\t\tvar quotedMark = false;\n\n\t\tvar nestedMark = false;\n\t\tvar nestedDepth = 0;\n\n\t\tfor (var i = 0; i < query.length; i++) {\n\t\t\tvar char = query[i];\n\n\t\t\tif (escaped) {\n\t\t\t\tcurrent += char;\n\t\t\t\tescaped = false;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tswitch (char) {\n\t\t\t\tcase ',':\n\t\t\t\t\tif (quoted) {\n\t\t\t\t\t\tcurrent += char;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (nestedDepth > 0) {\n\t\t\t\t\t\tcurrent += char;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tselectors.push(current);\n\t\t\t\t\tcurrent = '';\n\t\t\t\t\tcontinue;\n\n\t\t\t\tcase '\\\\':\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tescaped = true;\n\t\t\t\t\tcontinue;\n\n\t\t\t\tcase '\"':\n\t\t\t\tcase \"'\":\n\t\t\t\t\tif (quoted && char === quotedMark) {\n\t\t\t\t\t\tcurrent += char;\n\t\t\t\t\t\tquoted = false;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tquoted = true;\n\t\t\t\t\tquotedMark = char;\n\t\t\t\t\tcontinue;\n\n\t\t\t\tcase '(':\n\t\t\t\tcase ')':\n\t\t\t\tcase '[':\n\t\t\t\tcase ']':\n\t\t\t\t\tif (quoted) {\n\t\t\t\t\t\tcurrent += char;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (charIsNestedMarkMirror(char, nestedMark)) {\n\t\t\t\t\t\tcurrent += char;\n\t\t\t\t\t\tnestedDepth--;\n\n\t\t\t\t\t\tif (nestedDepth === 0) {\n\t\t\t\t\t\t\tnestedMark = false;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (char === nestedMark) {\n\t\t\t\t\t\tcurrent += char;\n\t\t\t\t\t\tnestedDepth++;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tnestedDepth++;\n\t\t\t\t\tnestedMark = char;\n\t\t\t\t\tcontinue;\n\n\t\t\t\tdefault:\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tcontinue;\n\n\t\t\t}\n\t\t}\n\n\t\tselectors.push(current);\n\n\t\treturn selectors;\n\t}\n\n\tfunction replaceAllWithTempAttr(query, nested, callback) {\n\t\tvar inner = pseudoClassHasInnerQuery(query);\n\t\tif (!inner) {\n\t\t\treturn query;\n\t\t}\n\n\t\tif (nested) {\n\t\t\treturn false;\n\t\t}\n\n\t\tvar innerQuery = inner.innerQuery;\n\t\tvar attr = 'q-has' + (Math.floor(Math.random() * 9000000) + 1000000);\n\t\tvar innerReplacement = '[' + attr + ']';\n\n\t\tvar x = query;\n\n\t\tif (inner.innerQuery.toLowerCase().indexOf(':has(') > -1) {\n\t\t\tvar innerParts = splitSelector(inner.innerQuery);\n\t\t\tvar newInnerParts = [];\n\t\t\tfor (var i = 0; i < innerParts.length; i++) {\n\t\t\t\tvar innerPart = innerParts[i];\n\n\t\t\t\t// Nested has is not supported.\n\t\t\t\t// If a recursive/nested call returns \"false\" we throw\n\t\t\t\tvar innerPartReplaced = replaceAllWithTempAttr(innerPart, true, function () { });\n\t\t\t\tif (!innerPartReplaced) {\n\t\t\t\t\tthrow new Error(\"Nested :has() is not supported\")\n\t\t\t\t} else {\n\t\t\t\t\tnewInnerParts.push(innerPart);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tvar _prefix = x.substring(0, inner.start - 5); // ':has('.length === 5\n\t\t\tvar _suffix = x.substring(inner.end + 2); // ')'.length === 1\n\n\t\t\treturn _prefix + newInnerParts.join(', ') + _suffix;\n\t\t}\n\n\t\tvar _prefix = x.substring(0, inner.start - 5); // ':has('.length === 5\n\t\tvar _suffix = x.substring(inner.end + 2); // ')'.length === 1\n\n\t\tx = _prefix + innerReplacement + _suffix;\n\n\t\tcallback(innerQuery, attr);\n\t\tif (x.toLowerCase().indexOf(':has(') > -1) {\n\t\t\tvar y = replaceAllWithTempAttr(x, false, callback);\n\t\t\tif (y) {\n\t\t\t\treturn y;\n\t\t\t}\n\t\t}\n\n\t\treturn x;\n\t}\n\n\tfunction walkNode(rootNode, callback) {\n\t\tif (('setAttribute' in (rootNode)) && ('querySelector' in (rootNode))) {\n\t\t\tcallback(rootNode);\n\t\t}\n\n\t\tif (rootNode.hasChildNodes()) {\n\t\t\tvar nodes = rootNode.childNodes;\n\t\t\tfor (var i = 0; i < nodes.length; ++i) {\n\t\t\t\twalkNode(nodes[i], callback);\n\t\t\t}\n\t\t}\n\t}\n\n\tfunction polyfill(qsa) {\n\t\treturn function (selectors) {\n\t\t\tif (!selectors) {\n\t\t\t\treturn qsa.apply(this, arguments);\n\t\t\t}\n\n\t\t\tvar selectorsString = String(selectors);\n\t\t\tif (!selectorsString || (selectorsString.toLowerCase().indexOf(':has(') === -1) || !pseudoClassHasInnerQuery(selectorsString)) {\n\t\t\t\treturn qsa.apply(this, arguments);\n\t\t\t}\n\n\t\t\tvar rootNode;\n\t\t\tif ('getRootNode' in this) {\n\t\t\t\trootNode = this.getRootNode();\n\t\t\t} else {\n\t\t\t\tvar r = this;\n\t\t\t\twhile (r) {\n\t\t\t\t\trootNode = r;\n\t\t\t\t\tr = r.parentNode;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tvar _focus = this;\n\t\t\tif (_focus === global.document) {\n\t\t\t\t_focus = global.document.documentElement;\n\t\t\t}\n\n\t\t\tvar scopeAttr = 'q-has-scope' + (Math.floor(Math.random() * 9000000) + 1000000);\n\t\t\t_focus.setAttribute(scopeAttr, '');\n\n\t\t\ttry {\n\t\t\t\tselectorsString = replaceScopeWithAttr(selectorsString, scopeAttr);\n\n\t\t\t\tvar attrs = [scopeAttr];\n\t\t\t\tvar newQuery = replaceAllWithTempAttr(selectorsString, false, function (inner, attr) {\n\t\t\t\t\tattrs.push(attr);\n\n\t\t\t\t\tvar selectorParts = splitSelector(inner);\n\t\t\t\t\tfor (var x = 0; x < selectorParts.length; x++) {\n\t\t\t\t\t\tvar selectorPart = selectorParts[x].trim();\n\t\t\t\t\t\tvar absoluteSelectorPart = selectorPart;\n\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\tselectorPart[0] === '>' ||\n\t\t\t\t\t\t\tselectorPart[0] === '+' ||\n\t\t\t\t\t\t\tselectorPart[0] === '~'\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\tabsoluteSelectorPart = selectorPart.slice(1).trim();\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tabsoluteSelectorPart = ':scope ' + selectorPart;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\twalkNode(rootNode, function (node) {\n\t\t\t\t\t\t\tif (!(node.querySelector(absoluteSelectorPart))) {\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tswitch (selectorPart[0]) {\n\t\t\t\t\t\t\t\tcase '~':\n\t\t\t\t\t\t\t\tcase '+':\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tvar siblings = node.childNodes;\n\t\t\t\t\t\t\t\t\t\tfor (var i = 0; i < siblings.length; i++) {\n\t\t\t\t\t\t\t\t\t\t\tvar sibling = siblings[i];\n\t\t\t\t\t\t\t\t\t\t\tif (!('setAttribute' in sibling)) {\n\t\t\t\t\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\tvar idAttr = 'q-has-id' + (Math.floor(Math.random() * 9000000) + 1000000);\n\t\t\t\t\t\t\t\t\t\t\tsibling.setAttribute(idAttr, '');\n\n\t\t\t\t\t\t\t\t\t\t\tif (node.querySelector(':scope [' + idAttr + ']' + ' ' + selectorPart)) {\n\t\t\t\t\t\t\t\t\t\t\t\tsibling.setAttribute(attr, '');\n\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\tsibling.removeAttribute(idAttr);\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\t\t\tcase '>':\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tvar idAttr = 'q-has-id' + (Math.floor(Math.random() * 9000000) + 1000000);\n\t\t\t\t\t\t\t\t\t\tnode.setAttribute(idAttr, '');\n\n\t\t\t\t\t\t\t\t\t\tif (node.querySelector(':scope[' + idAttr + ']' + ' ' + selectorPart)) {\n\t\t\t\t\t\t\t\t\t\t\tnode.setAttribute(attr, '');\n\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\tnode.removeAttribute(idAttr);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\t\t\tnode.setAttribute(attr, '');\n\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\targuments[0] = newQuery;\n\n\t\t\t\t// results of the qsa\n\t\t\t\tvar elementOrNodeList = qsa.apply(this, arguments);\n\n\t\t\t\t_focus.removeAttribute(scopeAttr);\n\n\t\t\t\tif (attrs.length > 0) {\n\t\t\t\t\t// remove the fallback attribute\n\t\t\t\t\tvar attrsForQuery = [];\n\t\t\t\t\tfor (var j = 0; j < attrs.length; j++) {\n\t\t\t\t\t\tattrsForQuery.push('[' + attrs[j] + ']');\n\t\t\t\t\t}\n\n\t\t\t\t\tvar elements = global.document.querySelectorAll(attrsForQuery.join(','));\n\t\t\t\t\tfor (var k = 0; k < elements.length; k++) {\n\t\t\t\t\t\tvar element = elements[k];\n\t\t\t\t\t\tfor (var l = 0; l < attrs.length; l++) {\n\t\t\t\t\t\t\telement.removeAttribute(attrs[l]);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// return the results of the qsa\n\t\t\t\treturn elementOrNodeList;\n\t\t\t} catch (err) {\n\t\t\t\t_focus.removeAttribute(scopeAttr);\n\n\t\t\t\tif (attrs.length > 0) {\n\t\t\t\t\t// remove the fallback attribute\n\t\t\t\t\tvar attrsForQuery = [];\n\t\t\t\t\tfor (var j = 0; j < attrs.length; j++) {\n\t\t\t\t\t\tattrsForQuery.push('[' + attrs[j] + ']');\n\t\t\t\t\t}\n\n\t\t\t\t\tvar elements = global.document.querySelectorAll(attrsForQuery.join(','));\n\t\t\t\t\tfor (var k = 0; k < elements.length; k++) {\n\t\t\t\t\t\tvar element = elements[k];\n\t\t\t\t\t\tfor (var l = 0; l < attrs.length; l++) {\n\t\t\t\t\t\t\telement.removeAttribute(attrs[l]);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tvar errorMessage = '';\n\t\t\t\ttry {\n\t\t\t\t\tqsa.apply(this, [':core-web-does-not-exist']);\n\t\t\t\t} catch (dummyError) {\n\t\t\t\t\terrorMessage = dummyError.message;\n\t\t\t\t\tif (errorMessage) {\n\t\t\t\t\t\terrorMessage = errorMessage.replace(':core-web-does-not-exist', selectorsString);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (!errorMessage) {\n\t\t\t\t\terrorMessage = \"Failed to execute 'querySelector' on 'Document': '\" + selectorsString + \"' is not a valid selector.\";\n\t\t\t\t}\n\n\t\t\t\ttry {\n\t\t\t\t\tthrow new DOMException(errorMessage);\n\t\t\t\t} catch (_) {\n\t\t\t\t\tthrow new Error(errorMessage);\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\t}\n})(self);\n"],"names":["decodeCSS","value","slice","values","split","result","i","length","String","fromCharCode","parseInt","extractEncodedSelectors","candidate","quotedMark","out","depth","quoted","containsUnescapedUnquotedHasAtDepth1","char","decoded","push","unique","indexOf","encodeCSS","hex","charCodeAt","toString","hasNativeSupport","self","CSS","supports","_","global","document","querySelector","querySelectorWithHasElement","polyfill","Element","prototype","selectors","apply","this","arguments","querySelectorAllWithHasElement","querySelectorAll","matches","matchesWithHasElement","closest","closestWithHasElement","Document","querySelectorWithHasDocument","querySelectorAllWithHasDocument","matchesWithHasDocument","closestWithHasDocument","pseudoClassHasInnerQuery","query","current","start","escaped","inHas","toLowerCase","innerQuery","end","replaceScopeWithAttr","attr","parts","bracketed","test","join","splitSelector","mark","nestedMark","nestedDepth","replaceAllWithTempAttr","nested","callback","inner","Math","floor","random","innerReplacement","x","innerParts","newInnerParts","innerPart","Error","_prefix","substring","_suffix","y","walkNode","rootNode","hasChildNodes","nodes","childNodes","qsa","selectorsString","getRootNode","r","parentNode","_focus","documentElement","scopeAttr","setAttribute","attrs","newQuery","selectorParts","selectorPart","trim","absoluteSelectorPart","node","siblings","sibling","idAttr","removeAttribute","elementOrNodeList","attrsForQuery","j","elements","k","element","l","err","errorMessage","dummyError","message","replace","DOMException","cssHasPseudo","options","hover","debug","observedAttributes","forcePolyfill","mustPolyfill","Array","isArray","filter","concat","observedItems","attributeElement","createElement","forEach","call","styleSheets","walkStyleSheet","transformObservedItemsThrottled","MutationObserver","mutationsList","mutation","addedNodes","nodeType","sheet","splice","item","rule","parentStyleSheet","ownerNode","contains","observe","childList","subtree","attributes","attributeFilter","addEventListener","Object","observeProperty","proto","property","hasOwnProperty","descriptor","getOwnPropertyDescriptor","configurable","defineProperty","enumerable","get","set","HTMLElement","elementName","e","console","error","transformObservedItemsThrottledBusy","cancelAnimationFrame","requestAnimationFrame","selector","innerHTML","attributeName","setAttributeNode","children","cloneNode","style","zoom","styleSheet","cssRules","index","selectorText","hasSelectors","deleteRule","hasSelector"],"mappings":"AAEe,SAASA,UAAUC,GACjC,GAA2B,kBAAvBA,EAAMC,MAAM,EAAG,IAClB,MAAO,GAOR,IAHA,IAAIC,GADJF,EAAQA,EAAMC,MAAM,KACDE,MAAM,KAErBC,EAAS,GACJC,EAAI,EAAGA,EAAIH,EAAOI,OAAQD,IAClCD,GAAUG,OAAOC,aAAaC,SAASP,EAAOG,GAAI,KAGnD,OAAOD,CACR,CCbe,SAASM,wBAAwBV,GAY/C,IAXA,IAGIW,EAGAC,EANAC,EAAM,GAENC,EAAQ,EAGRC,GAAS,EAGTC,GAAuC,EAGlCX,EAAI,EAAGA,EAAIL,EAAMM,OAAQD,IAAK,CACtC,IAAMY,EAAOjB,EAAMK,GAEnB,OAAQY,GACP,IAAK,IACJ,GAAIF,EAAQ,CACXJ,GAAaM,EACb,QACD,CAEc,IAAVH,EACHH,EAAY,GAEZA,GAAaM,EAGdH,IACA,SACD,IAA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IAAK0H,EAAQK,aAEZ,YADA2D,EAAWK,WAAWH,GAIvB,IAAK,IAAI7L,EAAI,EAAGA,EAAI+L,EAAa9L,OAAQD,IAAK,CAC7C,IAAMiM,EAAcF,EAAa/L,GACjCqI,EAAcvH,KAAK,CAClBuI,KAAMA,EACN8B,SAAUc,EACVZ,cAAepK,UAAUgL,GACzB1G,MAAO,IAET,CACA,CAAC,MAAOsF,GACJlD,EAAQE,OACXiD,QAAQC,MAAMF,EAEhB,CACD,MACClC,eAAeU,EAEjB,GACA,CAAC,MAAOwB,GACJlD,EAAQE,OACXiD,QAAQC,MAAMF,EAEhB,CACD,CACD","x_google_ignoreList":[4]} \ No newline at end of file diff --git a/plugins/css-has-pseudo/dist/browser.mjs.map b/plugins/css-has-pseudo/dist/browser.mjs.map index 0d427e8e6..c28d43553 100644 --- a/plugins/css-has-pseudo/dist/browser.mjs.map +++ b/plugins/css-has-pseudo/dist/browser.mjs.map @@ -1 +1 @@ -{"version":3,"file":"browser.mjs","sources":["../src/encode/decode.mjs","../src/encode/extract.mjs","../src/encode/encode.mjs","../src/browser.js","../../../node_modules/@mrhenry/core-web/modules/~element-qsa-has.js"],"sourcesContent":["\n/** Decodes an identifier back into a CSS selector */\nexport default function decodeCSS(value) {\n\tif (value.slice(0, 13) !== 'csstools-has-') {\n\t\treturn '';\n\t}\n\n\tvalue = value.slice(13);\n\tlet values = value.split('-');\n\n\tlet result = '';\n\tfor (let i = 0; i < values.length; i++) {\n\t\tresult += String.fromCharCode(parseInt(values[i], 36));\n\t}\n\n\treturn result;\n}\n","import decodeCSS from './decode.mjs';\n\n/** Extract encoded selectors out of attribute selectors */\nexport default function extractEncodedSelectors(value) {\n\tlet out = [];\n\n\tlet depth = 0;\n\tlet candidate;\n\n\tlet quoted = false;\n\tlet quotedMark;\n\n\tlet containsUnescapedUnquotedHasAtDepth1 = false;\n\n\t// Stryker disable next-line EqualityOperator\n\tfor (let i = 0; i < value.length; i++) {\n\t\tconst char = value[i];\n\n\t\tswitch (char) {\n\t\t\tcase '[':\n\t\t\t\tif (quoted) {\n\t\t\t\t\tcandidate += char;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tif (depth === 0) {\n\t\t\t\t\tcandidate = '';\n\t\t\t\t} else {\n\t\t\t\t\tcandidate += char;\n\t\t\t\t}\n\n\t\t\t\tdepth++;\n\t\t\t\tcontinue;\n\t\t\tcase ']':\n\t\t\t\tif (quoted) {\n\t\t\t\t\tcandidate += char;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\t{\n\t\t\t\t\tdepth--;\n\t\t\t\t\tif (depth === 0) {\n\t\t\t\t\t\tconst decoded = decodeCSS(candidate);\n\t\t\t\t\t\tif (containsUnescapedUnquotedHasAtDepth1) {\n\t\t\t\t\t\t\tout.push(decoded);\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tcandidate += char;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tcontinue;\n\t\t\tcase '\\\\':\n\t\t\t\tcandidate += value[i];\n\t\t\t\tcandidate += value[i+1];\n\t\t\t\ti++;\n\t\t\t\tcontinue;\n\n\t\t\tcase '\"':\n\t\t\tcase '\\'':\n\t\t\t\tif (quoted && char === quotedMark) {\n\t\t\t\t\tquoted = false;\n\t\t\t\t\tcontinue;\n\t\t\t\t} else if (quoted) {\n\t\t\t\t\tcandidate += char;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tquoted = true;\n\t\t\t\tquotedMark = char;\n\t\t\t\tcontinue;\n\n\t\t\tdefault:\n\t\t\t\tif (candidate === '' && depth === 1 && (value.slice(i, i + 13) === 'csstools-has-')) {\n\t\t\t\t\tcontainsUnescapedUnquotedHasAtDepth1 = true;\n\t\t\t\t}\n\n\t\t\t\tcandidate += char;\n\t\t\t\tcontinue;\n\t\t}\n\t}\n\n\tconst unique = [];\n\tfor (let i = 0; i < out.length; i++) {\n\t\tif (unique.indexOf(out[i]) === -1) {\n\t\t\tunique.push(out[i]);\n\t\t}\n\t}\n\n\treturn unique;\n}\n","\n/** Returns the string as an encoded CSS identifier. */\nexport default function encodeCSS(value) {\n\tif (value === '') {\n\t\treturn '';\n\t}\n\n\tlet hex;\n\tlet result = '';\n\tfor (let i = 0; i < value.length; i++) {\n\t\thex = value.charCodeAt(i).toString(36);\n\t\tif (i === 0) {\n\t\t\tresult += hex;\n\t\t} else {\n\t\t\tresult += '-' + hex;\n\t\t}\n\t}\n\n\treturn 'csstools-has-' + result;\n}\n","/* global MutationObserver,requestAnimationFrame,cancelAnimationFrame,self,HTMLElement */\n\nimport '@mrhenry/core-web/modules/~element-qsa-has.js';\nimport extractEncodedSelectors from './encode/extract.mjs';\nimport encodeCSS from './encode/encode.mjs';\n\nfunction hasNativeSupport() {\n\ttry {\n\t\tif (!('CSS' in self) || !('supports' in self.CSS) || !self.CSS.supports('selector(:has(div))')) {\n\t\t\treturn false;\n\t\t}\n\n\t} catch (_) {\n\t\treturn false;\n\t}\n\n\treturn true;\n}\n\nexport default function cssHasPseudo(document, options) {\n\t// OPTIONS\n\t{\n\t\tif (!options) {\n\t\t\toptions = {};\n\t\t}\n\n\t\toptions = {\n\t\t\thover: (!!options.hover) || false,\n\t\t\tdebug: (!!options.debug) || false,\n\t\t\tobservedAttributes: options.observedAttributes || [],\n\t\t\tforcePolyfill: (!!options.forcePolyfill) || false,\n\t\t};\n\n\t\toptions.mustPolyfill = options.forcePolyfill || !hasNativeSupport();\n\n\t\tif (!Array.isArray(options.observedAttributes)) {\n\t\t\toptions.observedAttributes = [];\n\t\t}\n\n\t\toptions.observedAttributes = options.observedAttributes.filter((x) => {\n\t\t\treturn (typeof x === 'string');\n\t\t});\n\n\t\t// https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes\n\t\t// `data-*` and `style` were omitted\n\t\toptions.observedAttributes = options.observedAttributes.concat(['accept', 'accept-charset', 'accesskey', 'action', 'align', 'allow', 'alt', 'async', 'autocapitalize', 'autocomplete', 'autofocus', 'autoplay', 'buffered', 'capture', 'challenge', 'charset', 'checked', 'cite', 'class', 'code', 'codebase', 'cols', 'colspan', 'content', 'contenteditable', 'contextmenu', 'controls', 'coords', 'crossorigin', 'csp', 'data', 'datetime', 'decoding', 'default', 'defer', 'dir', 'dirname', 'disabled', 'download', 'draggable', 'enctype', 'enterkeyhint', 'for', 'form', 'formaction', 'formenctype', 'formmethod', 'formnovalidate', 'formtarget', 'headers', 'hidden', 'high', 'href', 'hreflang', 'http-equiv', 'icon', 'id', 'importance', 'integrity', 'intrinsicsize', 'inputmode', 'ismap', 'itemprop', 'keytype', 'kind', 'label', 'lang', 'language', 'list', 'loop', 'low', 'manifest', 'max', 'maxlength', 'minlength', 'media', 'method', 'min', 'multiple', 'muted', 'name', 'novalidate', 'open', 'optimum', 'pattern', 'ping', 'placeholder', 'poster', 'preload', 'radiogroup', 'readonly', 'referrerpolicy', 'rel', 'required', 'reversed', 'rows', 'rowspan', 'sandbox', 'scope', 'scoped', 'selected', 'shape', 'size', 'sizes', 'slot', 'span', 'spellcheck', 'src', 'srcdoc', 'srclang', 'srcset', 'start', 'step', 'summary', 'tabindex', 'target', 'title', 'translate', 'type', 'usemap', 'value', 'width', 'wrap']);\n\t}\n\n\tconst observedItems = [];\n\n\t// document.createAttribute() doesn't support `:` in the name. innerHTML does\n\tconst attributeElement = document.createElement('x');\n\n\t// walk all stylesheets to collect observed css rules\n\t[].forEach.call(document.styleSheets, walkStyleSheet);\n\tif (!options.mustPolyfill) {\n\t\t// Cleanup of rules will have happened in `walkStyleSheet`\n\t\t// Native support will take over from here\n\t\treturn;\n\t}\n\n\ttransformObservedItemsThrottled();\n\n\t// observe DOM modifications that affect selectors\n\tif ('MutationObserver' in self) {\n\t\tconst mutationObserver = new MutationObserver((mutationsList) => {\n\t\t\tmutationsList.forEach(mutation => {\n\t\t\t\t[].forEach.call(mutation.addedNodes || [], node => {\n\t\t\t\t\t// walk stylesheets to collect observed css rules\n\t\t\t\t\tif (node.nodeType === 1 && node.sheet) {\n\t\t\t\t\t\twalkStyleSheet(node.sheet);\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\t// transform observed css rules\n\t\t\t\tcleanupObservedCssRules();\n\t\t\t\ttransformObservedItemsThrottled();\n\t\t\t});\n\t\t});\n\n\t\tmutationObserver.observe(document, { childList: true, subtree: true, attributes: true, attributeFilter: options.observedAttributes });\n\t}\n\n\t// observe DOM events that affect pseudo-selectors\n\tdocument.addEventListener('focus', transformObservedItemsThrottled, true);\n\tdocument.addEventListener('blur', transformObservedItemsThrottled, true);\n\tdocument.addEventListener('input', transformObservedItemsThrottled);\n\tdocument.addEventListener('change', transformObservedItemsThrottled, true);\n\n\tif (options.hover) {\n\t\tif ('onpointerenter' in document) {\n\t\t\tdocument.addEventListener('pointerenter', transformObservedItemsThrottled, true);\n\t\t\tdocument.addEventListener('pointerleave', transformObservedItemsThrottled, true);\n\t\t} else {\n\t\t\tdocument.addEventListener('mouseover', transformObservedItemsThrottled, true);\n\t\t\tdocument.addEventListener('mouseout', transformObservedItemsThrottled, true);\n\t\t}\n\t}\n\n\t// observe Javascript setters that effect pseudo-selectors\n\tif ('defineProperty' in Object && 'getOwnPropertyDescriptor' in Object && 'hasOwnProperty' in Object) {\n\t\ttry {\n\t\t\t// eslint-disable-next-line no-inner-declarations\n\t\t\tfunction observeProperty(proto, property) {\n\t\t\t\t// eslint-disable-next-line no-prototype-builtins\n\t\t\t\tif (proto.hasOwnProperty(property)) {\n\t\t\t\t\tconst descriptor = Object.getOwnPropertyDescriptor(proto, property);\n\t\t\t\t\tif (descriptor && descriptor.configurable && 'set' in descriptor) {\n\t\t\t\t\t\tObject.defineProperty(proto, property, {\n\t\t\t\t\t\t\tconfigurable: descriptor.configurable,\n\t\t\t\t\t\t\tenumerable: descriptor.enumerable,\n\t\t\t\t\t\t\tget: function () {\n\t\t\t\t\t\t\t\treturn descriptor.get.apply(this, arguments);\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tset: function () {\n\t\t\t\t\t\t\t\tdescriptor.set.apply(this, arguments);\n\n\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\ttransformObservedItemsThrottled();\n\t\t\t\t\t\t\t\t} catch (_) {\n\t\t\t\t\t\t\t\t\t// should never happen as there is an inner try/catch\n\t\t\t\t\t\t\t\t\t// but just in case\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif ('HTMLElement' in self && HTMLElement.prototype) {\n\t\t\t\tobserveProperty(HTMLElement.prototype, 'disabled');\n\t\t\t}\n\n\t\t\t// Not all of these elements have all of these properties.\n\t\t\t// But the code above checks if they exist first.\n\t\t\t['checked', 'selected', 'readOnly', 'required'].forEach((property) => {\n\t\t\t\t[\n\t\t\t\t\t'HTMLButtonElement',\n\t\t\t\t\t'HTMLFieldSetElement',\n\t\t\t\t\t'HTMLInputElement',\n\t\t\t\t\t'HTMLMeterElement',\n\t\t\t\t\t'HTMLOptGroupElement',\n\t\t\t\t\t'HTMLOptionElement',\n\t\t\t\t\t'HTMLOutputElement',\n\t\t\t\t\t'HTMLProgressElement',\n\t\t\t\t\t'HTMLSelectElement',\n\t\t\t\t\t'HTMLTextAreaElement',\n\t\t\t\t].forEach((elementName) => {\n\t\t\t\t\tif (elementName in self && self[elementName].prototype) {\n\t\t\t\t\t\tobserveProperty(self[elementName].prototype, property);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t});\n\t\t} catch (e) {\n\t\t\tif (options.debug) {\n\t\t\t\tconsole.error(e);\n\t\t\t}\n\t\t}\n\t}\n\n\tlet transformObservedItemsThrottledBusy = false;\n\tfunction transformObservedItemsThrottled() {\n\t\tif (transformObservedItemsThrottledBusy) {\n\t\t\tcancelAnimationFrame(transformObservedItemsThrottledBusy);\n\t\t}\n\n\t\ttransformObservedItemsThrottledBusy = requestAnimationFrame(() => {\n\t\t\ttransformObservedItems();\n\t\t});\n\t}\n\n\t// transform observed css rules\n\tfunction transformObservedItems() {\n\t\tobservedItems.forEach((item) => {\n\t\t\tconst nodes = [];\n\n\t\t\tlet matches = [];\n\t\t\ttry {\n\t\t\t\tmatches = document.querySelectorAll(item.selector);\n\t\t\t} catch (e) {\n\t\t\t\tif (options.debug) {\n\t\t\t\t\tconsole.error(e);\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t[].forEach.call(matches, (element) => {\n\t\t\t\t// memorize the node\n\t\t\t\tnodes.push(element);\n\n\t\t\t\t// set an attribute with an irregular attribute name\n\t\t\t\t// document.createAttribute() doesn't support special characters\n\t\t\t\tattributeElement.innerHTML = '';\n\n\t\t\t\telement.setAttributeNode(attributeElement.children[0].attributes[0].cloneNode());\n\n\t\t\t\t// trigger a style refresh in IE and Edge\n\t\t\t\tdocument.documentElement.style.zoom = 1; document.documentElement.style.zoom = null;\n\t\t\t});\n\n\t\t\t// remove the encoded attribute from all nodes that no longer match them\n\t\t\titem.nodes.forEach(node => {\n\t\t\t\tif (nodes.indexOf(node) === -1) {\n\t\t\t\t\tnode.removeAttribute(item.attributeName);\n\n\t\t\t\t\t// trigger a style refresh in IE and Edge\n\t\t\t\t\tdocument.documentElement.style.zoom = 1; document.documentElement.style.zoom = null;\n\t\t\t\t}\n\t\t\t});\n\n\t\t\t// update the\n\t\t\titem.nodes = nodes;\n\t\t});\n\t}\n\n\t// remove any observed cssrules that no longer apply\n\tfunction cleanupObservedCssRules() {\n\t\t[].push.apply(\n\t\t\tobservedItems,\n\t\t\tobservedItems.splice(0).filter((item) => {\n\t\t\t\treturn item.rule.parentStyleSheet &&\n\t\t\t\t\titem.rule.parentStyleSheet.ownerNode &&\n\t\t\t\t\tdocument.documentElement.contains(item.rule.parentStyleSheet.ownerNode);\n\t\t\t}),\n\t\t);\n\t}\n\n\t// walk a stylesheet to collect observed css rules\n\tfunction walkStyleSheet(styleSheet) {\n\t\ttry {\n\t\t\t// walk a css rule to collect observed css rules\n\t\t\t[].forEach.call(styleSheet.cssRules || [], (rule, index) => {\n\t\t\t\tif (rule.selectorText) {\n\t\t\t\t\trule.selectorText = rule.selectorText.replace(/\\.js-has-pseudo\\s/g, '');\n\n\t\t\t\t\ttry {\n\t\t\t\t\t\t// decode the selector text in all browsers to:\n\t\t\t\t\t\tconst hasSelectors = extractEncodedSelectors(rule.selectorText.toString());\n\t\t\t\t\t\tif (hasSelectors.length === 0) {\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (!options.mustPolyfill) {\n\t\t\t\t\t\t\tstyleSheet.deleteRule(index);\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tfor (let i = 0; i < hasSelectors.length; i++) {\n\t\t\t\t\t\t\tconst hasSelector = hasSelectors[i];\n\t\t\t\t\t\t\tobservedItems.push({\n\t\t\t\t\t\t\t\trule: rule,\n\t\t\t\t\t\t\t\tselector: hasSelector,\n\t\t\t\t\t\t\t\tattributeName: encodeCSS(hasSelector),\n\t\t\t\t\t\t\t\tnodes: [],\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\tif (options.debug) {\n\t\t\t\t\t\t\tconsole.error(e);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\twalkStyleSheet(rule);\n\t\t\t\t}\n\t\t\t});\n\t\t} catch (e) {\n\t\t\tif (options.debug) {\n\t\t\t\tconsole.error(e);\n\t\t\t}\n\t\t}\n\t}\n}\n","/* eslint-disable */\n(function (global) {\n\ttry {\n\t\t// test for has support\n\t\tglobal.document.querySelector(':has(*, :does-not-exist, > *)');\n\n\t\tif (\n\t\t\t!global.document.querySelector(':has(:scope *)') &&\n\t\t\tCSS.supports('selector(:has(div))')\n\t\t) {\n\t\t\treturn;\n\t\t}\n\t} catch (_) { }\n\n\t// ELEMENT\n\t// polyfill Element#querySelector\n\tvar querySelectorWithHasElement = polyfill(global.Element.prototype.querySelector);\n\n\tglobal.Element.prototype.querySelector = function querySelector(selectors) {\n\t\treturn querySelectorWithHasElement.apply(this, arguments);\n\t};\n\n\t// polyfill Element#querySelectorAll\n\tvar querySelectorAllWithHasElement = polyfill(global.Element.prototype.querySelectorAll);\n\n\tglobal.Element.prototype.querySelectorAll = function querySelectorAll(selectors) {\n\t\treturn querySelectorAllWithHasElement.apply(this, arguments);\n\t};\n\n\t// polyfill Element#matches\n\tif (global.Element.prototype.matches) {\n\t\tvar matchesWithHasElement = polyfill(global.Element.prototype.matches);\n\n\t\tglobal.Element.prototype.matches = function matches(selectors) {\n\t\t\treturn matchesWithHasElement.apply(this, arguments);\n\t\t};\n\t}\n\n\t// polyfill Element#closest\n\tif (global.Element.prototype.closest) {\n\t\tvar closestWithHasElement = polyfill(global.Element.prototype.closest);\n\n\t\tglobal.Element.prototype.closest = function closest(selectors) {\n\t\t\treturn closestWithHasElement.apply(this, arguments);\n\t\t};\n\t}\n\n\t// DOCUMENT\n\tif ('Document' in global && 'prototype' in global.Document) {\n\t\t// polyfill Document#querySelector\n\t\tvar querySelectorWithHasDocument = polyfill(global.Document.prototype.querySelector);\n\n\t\tglobal.Document.prototype.querySelector = function querySelector(selectors) {\n\t\t\treturn querySelectorWithHasDocument.apply(this, arguments);\n\t\t};\n\n\t\t// polyfill Document#querySelectorAll\n\t\tvar querySelectorAllWithHasDocument = polyfill(global.Document.prototype.querySelectorAll);\n\n\t\tglobal.Document.prototype.querySelectorAll = function querySelectorAll(selectors) {\n\t\t\treturn querySelectorAllWithHasDocument.apply(this, arguments);\n\t\t};\n\n\t\t// polyfill Document#matches\n\t\tif (global.Document.prototype.matches) {\n\t\t\tvar matchesWithHasDocument = polyfill(global.Document.prototype.matches);\n\n\t\t\tglobal.Document.prototype.matches = function matches(selectors) {\n\t\t\t\treturn matchesWithHasDocument.apply(this, arguments);\n\t\t\t};\n\t\t}\n\n\t\t// polyfill Document#closest\n\t\tif (global.Document.prototype.closest) {\n\t\t\tvar closestWithHasDocument = polyfill(global.Document.prototype.closest);\n\n\t\t\tglobal.Document.prototype.closest = function closest(selectors) {\n\t\t\t\treturn closestWithHasDocument.apply(this, arguments);\n\t\t\t};\n\t\t}\n\t}\n\n\tfunction pseudoClassHasInnerQuery(query) {\n\t\tvar current = '';\n\t\tvar start = 0;\n\t\tvar depth = 0;\n\n\t\tvar escaped = false;\n\n\t\tvar quoted = false;\n\t\tvar quotedMark = false;\n\n\t\tvar inHas = false;\n\n\t\tvar bracketed = 0;\n\n\t\tfor (var i = 0; i < query.length; i++) {\n\t\t\tvar char = query[i];\n\n\t\t\tif (escaped) {\n\t\t\t\tcurrent += char;\n\t\t\t\tescaped = false;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (quoted) {\n\t\t\t\tif (char === quotedMark) {\n\t\t\t\t\tquoted = false;\n\t\t\t\t}\n\n\t\t\t\tcurrent += char;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (current.toLowerCase() === ':has(' && !inHas) {\n\t\t\t\tinHas = true;\n\t\t\t\tstart = i;\n\t\t\t\tcurrent = '';\n\t\t\t}\n\n\t\t\tswitch (char) {\n\t\t\t\tcase ':':\n\t\t\t\t\tif (!inHas) {\n\t\t\t\t\t\tcurrent = '';\n\t\t\t\t\t}\n\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tcontinue;\n\n\t\t\t\tcase '(':\n\t\t\t\t\tif (inHas) {\n\t\t\t\t\t\tdepth++;\n\t\t\t\t\t}\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tcontinue;\n\n\t\t\t\tcase ')':\n\t\t\t\t\tif (inHas) {\n\t\t\t\t\t\tif (depth === 0) {\n\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\tinnerQuery: current,\n\t\t\t\t\t\t\t\tstart: start,\n\t\t\t\t\t\t\t\tend: i-1\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tdepth--;\n\t\t\t\t\t}\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tcontinue;\n\n\t\t\t\tcase '\\\\':\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tescaped = true;\n\t\t\t\t\tcontinue;\n\n\t\t\t\tcase '\"':\n\t\t\t\tcase \"'\":\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tquoted = true;\n\t\t\t\t\tquotedMark = char;\n\t\t\t\t\tcontinue;\n\n\t\t\t\tcase '[':\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tbracketed++;\n\t\t\t\t\tcontinue;\n\n\t\t\t\tcase \"]\":\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tif (bracketed > 0) {\n\t\t\t\t\t\tbracketed--\n\t\t\t\t\t}\n\n\t\t\t\t\tcontinue;\n\t\t\t\n\t\t\t\tdefault:\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\n\t\treturn false;\n\t}\n\n\tfunction replaceScopeWithAttr(query, attr) {\n\t\tvar parts = [];\n\t\tvar current = '';\n\n\t\tvar escaped = false;\n\n\t\tvar quoted = false;\n\t\tvar quotedMark = false;\n\n\t\tvar bracketed = 0;\n\n\t\tfor (var i = 0; i < query.length; i++) {\n\t\t\tvar char = query[i];\n\n\t\t\tif (escaped) {\n\t\t\t\tcurrent += char;\n\t\t\t\tescaped = false;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (quoted) {\n\t\t\t\tif (char === quotedMark) {\n\t\t\t\t\tquoted = false;\n\t\t\t\t}\n\n\t\t\t\tcurrent += char;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (current.toLowerCase() === ':scope' && !bracketed && (/^[\\[\\.\\:\\\\\"\\s|+>~#&,)]/.test(char || ''))) {\n\t\t\t\tparts.push(current.slice(0, current.length - 6));\n\t\t\t\tparts.push('[' + attr + ']');\n\t\t\t\tcurrent = '';\n\t\t\t}\n\n\t\t\tswitch (char) {\n\t\t\t\tcase ':':\n\t\t\t\t\tparts.push(current);\n\t\t\t\t\tcurrent = '';\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tcontinue;\n\n\t\t\t\tcase '\\\\':\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tescaped = true;\n\t\t\t\t\tcontinue;\n\n\t\t\t\tcase '\"':\n\t\t\t\tcase \"'\":\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tquoted = true;\n\t\t\t\t\tquotedMark = char;\n\t\t\t\t\tcontinue;\n\n\t\t\t\tcase '[':\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tbracketed++;\n\t\t\t\t\tcontinue;\n\n\t\t\t\tcase \"]\":\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tif (bracketed > 0) {\n\t\t\t\t\t\tbracketed--\n\t\t\t\t\t}\n\n\t\t\t\t\tcontinue;\n\n\t\t\t\tdefault:\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\n\t\tif (current.toLowerCase() === ':scope') {\n\t\t\tparts.push(current.slice(0, current.length - 6));\n\t\t\tparts.push('[' + attr + ']');\n\t\t\tcurrent = '';\n\t\t}\n\n\t\tif (parts.length === 0) {\n\t\t\treturn query;\n\t\t}\n\n\t\treturn parts.join('') + current;\n\t}\n\n\tfunction charIsNestedMarkMirror(char, mark) {\n\t\tif (mark === '(' && char === ')') {\n\t\t\treturn true;\n\t\t}\n\n\t\tif (mark === '[' && char === ']') {\n\t\t\treturn true;\n\t\t}\n\n\t\treturn false;\n\t}\n\n\tfunction splitSelector(query) {\n\t\tvar selectors = [];\n\t\tvar current = '';\n\n\t\tvar escaped = false;\n\n\t\tvar quoted = false;\n\t\tvar quotedMark = false;\n\n\t\tvar nestedMark = false;\n\t\tvar nestedDepth = 0;\n\n\t\tfor (var i = 0; i < query.length; i++) {\n\t\t\tvar char = query[i];\n\n\t\t\tif (escaped) {\n\t\t\t\tcurrent += char;\n\t\t\t\tescaped = false;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tswitch (char) {\n\t\t\t\tcase ',':\n\t\t\t\t\tif (quoted) {\n\t\t\t\t\t\tcurrent += char;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (nestedDepth > 0) {\n\t\t\t\t\t\tcurrent += char;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tselectors.push(current);\n\t\t\t\t\tcurrent = '';\n\t\t\t\t\tcontinue;\n\n\t\t\t\tcase '\\\\':\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tescaped = true;\n\t\t\t\t\tcontinue;\n\n\t\t\t\tcase '\"':\n\t\t\t\tcase \"'\":\n\t\t\t\t\tif (quoted && char === quotedMark) {\n\t\t\t\t\t\tcurrent += char;\n\t\t\t\t\t\tquoted = false;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tquoted = true;\n\t\t\t\t\tquotedMark = char;\n\t\t\t\t\tcontinue;\n\n\t\t\t\tcase '(':\n\t\t\t\tcase ')':\n\t\t\t\tcase '[':\n\t\t\t\tcase ']':\n\t\t\t\t\tif (quoted) {\n\t\t\t\t\t\tcurrent += char;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (charIsNestedMarkMirror(char, nestedMark)) {\n\t\t\t\t\t\tcurrent += char;\n\t\t\t\t\t\tnestedDepth--;\n\n\t\t\t\t\t\tif (nestedDepth === 0) {\n\t\t\t\t\t\t\tnestedMark = false;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (char === nestedMark) {\n\t\t\t\t\t\tcurrent += char;\n\t\t\t\t\t\tnestedDepth++;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tnestedDepth++;\n\t\t\t\t\tnestedMark = char;\n\t\t\t\t\tcontinue;\n\n\t\t\t\tdefault:\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tcontinue;\n\n\t\t\t}\n\t\t}\n\n\t\tselectors.push(current);\n\n\t\treturn selectors;\n\t}\n\n\tfunction replaceAllWithTempAttr(query, nested, callback) {\n\t\tvar inner = pseudoClassHasInnerQuery(query);\n\t\tif (!inner) {\n\t\t\treturn query;\n\t\t}\n\n\t\tif (nested) {\n\t\t\treturn false;\n\t\t}\n\n\t\tvar innerQuery = inner.innerQuery;\n\t\tvar attr = 'q-has' + (Math.floor(Math.random() * 9000000) + 1000000);\n\t\tvar innerReplacement = '[' + attr + ']';\n\n\t\tvar x = query;\n\n\t\tif (inner.innerQuery.toLowerCase().indexOf(':has(') > -1) {\n\t\t\tvar innerParts = splitSelector(inner.innerQuery);\n\t\t\tvar newInnerParts = [];\n\t\t\tfor (var i = 0; i < innerParts.length; i++) {\n\t\t\t\tvar innerPart = innerParts[i];\n\n\t\t\t\t// Nested has is not supported.\n\t\t\t\t// If a recursive/nested call returns \"false\" we throw\n\t\t\t\tvar innerPartReplaced = replaceAllWithTempAttr(innerPart, true, function () { });\n\t\t\t\tif (!innerPartReplaced) {\n\t\t\t\t\tthrow new Error(\"Nested :has() is not supported\")\n\t\t\t\t} else {\n\t\t\t\t\tnewInnerParts.push(innerPart);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tvar _prefix = x.substring(0, inner.start - 5); // ':has('.length === 5\n\t\t\tvar _suffix = x.substring(inner.end + 2); // ')'.length === 1\n\n\t\t\treturn _prefix + newInnerParts.join(', ') + _suffix;\n\t\t}\n\n\t\tvar _prefix = x.substring(0, inner.start - 5); // ':has('.length === 5\n\t\tvar _suffix = x.substring(inner.end + 2); // ')'.length === 1\n\n\t\tx = _prefix + innerReplacement + _suffix;\n\n\t\tcallback(innerQuery, attr);\n\t\tif (x.toLowerCase().indexOf(':has(') > -1) {\n\t\t\tvar y = replaceAllWithTempAttr(x, false, callback);\n\t\t\tif (y) {\n\t\t\t\treturn y;\n\t\t\t}\n\t\t}\n\n\t\treturn x;\n\t}\n\n\tfunction walkNode(rootNode, callback) {\n\t\tif (('setAttribute' in (rootNode)) && ('querySelector' in (rootNode))) {\n\t\t\tcallback(rootNode);\n\t\t}\n\n\t\tif (rootNode.hasChildNodes()) {\n\t\t\tvar nodes = rootNode.childNodes;\n\t\t\tfor (var i = 0; i < nodes.length; ++i) {\n\t\t\t\twalkNode(nodes[i], callback);\n\t\t\t}\n\t\t}\n\t}\n\n\tfunction polyfill(qsa) {\n\t\treturn function (selectors) {\n\t\t\tif (!selectors) {\n\t\t\t\treturn qsa.apply(this, arguments);\n\t\t\t}\n\n\t\t\tvar selectorsString = String(selectors);\n\t\t\tif (!selectorsString || (selectorsString.toLowerCase().indexOf(':has(') === -1) || !pseudoClassHasInnerQuery(selectorsString)) {\n\t\t\t\treturn qsa.apply(this, arguments);\n\t\t\t}\n\n\t\t\tvar rootNode;\n\t\t\tif ('getRootNode' in this) {\n\t\t\t\trootNode = this.getRootNode();\n\t\t\t} else {\n\t\t\t\tvar r = this;\n\t\t\t\twhile (r) {\n\t\t\t\t\trootNode = r;\n\t\t\t\t\tr = r.parentNode;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tvar _focus = this;\n\t\t\tif (_focus === global.document) {\n\t\t\t\t_focus = global.document.documentElement;\n\t\t\t}\n\n\t\t\tvar scopeAttr = 'q-has-scope' + (Math.floor(Math.random() * 9000000) + 1000000);\n\t\t\t_focus.setAttribute(scopeAttr, '');\n\n\t\t\ttry {\n\t\t\t\tselectorsString = replaceScopeWithAttr(selectorsString, scopeAttr);\n\n\t\t\t\tvar attrs = [scopeAttr];\n\t\t\t\tvar newQuery = replaceAllWithTempAttr(selectorsString, false, function (inner, attr) {\n\t\t\t\t\tattrs.push(attr);\n\n\t\t\t\t\tvar selectorParts = splitSelector(inner);\n\t\t\t\t\tfor (var x = 0; x < selectorParts.length; x++) {\n\t\t\t\t\t\tvar selectorPart = selectorParts[x].trim();\n\t\t\t\t\t\tvar absoluteSelectorPart = selectorPart;\n\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\tselectorPart[0] === '>' ||\n\t\t\t\t\t\t\tselectorPart[0] === '+' ||\n\t\t\t\t\t\t\tselectorPart[0] === '~'\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\tabsoluteSelectorPart = selectorPart.slice(1).trim();\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tabsoluteSelectorPart = ':scope ' + selectorPart;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\twalkNode(rootNode, function (node) {\n\t\t\t\t\t\t\tif (!(node.querySelector(absoluteSelectorPart))) {\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tswitch (selectorPart[0]) {\n\t\t\t\t\t\t\t\tcase '~':\n\t\t\t\t\t\t\t\tcase '+':\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tvar siblings = node.childNodes;\n\t\t\t\t\t\t\t\t\t\tfor (var i = 0; i < siblings.length; i++) {\n\t\t\t\t\t\t\t\t\t\t\tvar sibling = siblings[i];\n\t\t\t\t\t\t\t\t\t\t\tif (!('setAttribute' in sibling)) {\n\t\t\t\t\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\tvar idAttr = 'q-has-id' + (Math.floor(Math.random() * 9000000) + 1000000);\n\t\t\t\t\t\t\t\t\t\t\tsibling.setAttribute(idAttr, '');\n\n\t\t\t\t\t\t\t\t\t\t\tif (node.querySelector(':scope [' + idAttr + ']' + ' ' + selectorPart)) {\n\t\t\t\t\t\t\t\t\t\t\t\tsibling.setAttribute(attr, '');\n\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\tsibling.removeAttribute(idAttr);\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\t\t\tcase '>':\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tvar idAttr = 'q-has-id' + (Math.floor(Math.random() * 9000000) + 1000000);\n\t\t\t\t\t\t\t\t\t\tnode.setAttribute(idAttr, '');\n\n\t\t\t\t\t\t\t\t\t\tif (node.querySelector(':scope[' + idAttr + ']' + ' ' + selectorPart)) {\n\t\t\t\t\t\t\t\t\t\t\tnode.setAttribute(attr, '');\n\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\tnode.removeAttribute(idAttr);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\t\t\tnode.setAttribute(attr, '');\n\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\targuments[0] = newQuery;\n\n\t\t\t\t// results of the qsa\n\t\t\t\tvar elementOrNodeList = qsa.apply(this, arguments);\n\n\t\t\t\t_focus.removeAttribute(scopeAttr);\n\n\t\t\t\tif (attrs.length > 0) {\n\t\t\t\t\t// remove the fallback attribute\n\t\t\t\t\tvar attrsForQuery = [];\n\t\t\t\t\tfor (var j = 0; j < attrs.length; j++) {\n\t\t\t\t\t\tattrsForQuery.push('[' + attrs[j] + ']');\n\t\t\t\t\t}\n\n\t\t\t\t\tvar elements = global.document.querySelectorAll(attrsForQuery.join(','));\n\t\t\t\t\tfor (var k = 0; k < elements.length; k++) {\n\t\t\t\t\t\tvar element = elements[k];\n\t\t\t\t\t\tfor (var l = 0; l < attrs.length; l++) {\n\t\t\t\t\t\t\telement.removeAttribute(attrs[l]);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// return the results of the qsa\n\t\t\t\treturn elementOrNodeList;\n\t\t\t} catch (err) {\n\t\t\t\t_focus.removeAttribute(scopeAttr);\n\n\t\t\t\tif (attrs.length > 0) {\n\t\t\t\t\t// remove the fallback attribute\n\t\t\t\t\tvar attrsForQuery = [];\n\t\t\t\t\tfor (var j = 0; j < attrs.length; j++) {\n\t\t\t\t\t\tattrsForQuery.push('[' + attrs[j] + ']');\n\t\t\t\t\t}\n\n\t\t\t\t\tvar elements = global.document.querySelectorAll(attrsForQuery.join(','));\n\t\t\t\t\tfor (var k = 0; k < elements.length; k++) {\n\t\t\t\t\t\tvar element = elements[k];\n\t\t\t\t\t\tfor (var l = 0; l < attrs.length; l++) {\n\t\t\t\t\t\t\telement.removeAttribute(attrs[l]);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tvar errorMessage = '';\n\t\t\t\ttry {\n\t\t\t\t\tqsa.apply(this, [':core-web-does-not-exist']);\n\t\t\t\t} catch (dummyError) {\n\t\t\t\t\terrorMessage = dummyError.message;\n\t\t\t\t\tif (errorMessage) {\n\t\t\t\t\t\terrorMessage = errorMessage.replace(':core-web-does-not-exist', selectorsString);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (!errorMessage) {\n\t\t\t\t\terrorMessage = \"Failed to execute 'querySelector' on 'Document': '\" + selectorsString + \"' is not a valid selector.\";\n\t\t\t\t}\n\n\t\t\t\ttry {\n\t\t\t\t\tthrow new DOMException(errorMessage);\n\t\t\t\t} catch (_) {\n\t\t\t\t\tthrow new Error(errorMessage);\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\t}\n})(self);\n"],"names":["decodeCSS","value","slice","values","split","result","i","length","String","fromCharCode","parseInt","extractEncodedSelectors","candidate","quotedMark","out","depth","quoted","containsUnescapedUnquotedHasAtDepth1","char","decoded","push","unique","indexOf","encodeCSS","hex","charCodeAt","toString","hasNativeSupport","self","CSS","supports","_","cssHasPseudo","document","options","hover","debug","observedAttributes","forcePolyfill","mustPolyfill","Array","isArray","filter","x","concat","observedItems","attributeElement","createElement","forEach","call","styleSheets","walkStyleSheet","transformObservedItemsThrottled","MutationObserver","mutationsList","mutation","addedNodes","node","nodeType","sheet","apply","splice","item","rule","parentStyleSheet","ownerNode","documentElement","contains","observe","childList","subtree","attributes","attributeFilter","addEventListener","Object","observeProperty","proto","property","hasOwnProperty","descriptor","getOwnPropertyDescriptor","configurable","defineProperty","enumerable","get","this","arguments","set","HTMLElement","prototype","elementName","e","console","error","transformObservedItemsThrottledBusy","cancelAnimationFrame","requestAnimationFrame","nodes","matches","querySelectorAll","selector","element","innerHTML","attributeName","setAttributeNode","children","cloneNode","style","zoom","removeAttribute","styleSheet","cssRules","index","selectorText","replace","hasSelectors","deleteRule","hasSelector","global","querySelector","querySelectorWithHasElement","polyfill","Element","selectors","querySelectorAllWithHasElement","matchesWithHasElement","closest","closestWithHasElement","Document","querySelectorWithHasDocument","querySelectorAllWithHasDocument","matchesWithHasDocument","closestWithHasDocument","pseudoClassHasInnerQuery","query","current","start","escaped","inHas","toLowerCase","innerQuery","end","replaceScopeWithAttr","attr","parts","bracketed","test","join","splitSelector","mark","nestedMark","nestedDepth","replaceAllWithTempAttr","nested","callback","inner","Math","floor","random","innerReplacement","innerParts","newInnerParts","innerPart","Error","_prefix","substring","_suffix","y","walkNode","rootNode","hasChildNodes","childNodes","qsa","selectorsString","getRootNode","r","parentNode","_focus","scopeAttr","setAttribute","attrs","newQuery","selectorParts","selectorPart","trim","absoluteSelectorPart","siblings","sibling","idAttr","elementOrNodeList","attrsForQuery","j","elements","k","l","err","errorMessage","dummyError","message","DOMException"],"mappings":"AAEe,SAASA,UAAUC,GACjC,GAA2B,kBAAvBA,EAAMC,MAAM,EAAG,IAClB,MAAO,GAOR,IAHA,IAAIC,GADJF,EAAQA,EAAMC,MAAM,KACDE,MAAM,KAErBC,EAAS,GACJC,EAAI,EAAGA,EAAIH,EAAOI,OAAQD,IAClCD,GAAUG,OAAOC,aAAaC,SAAS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,EAAGA,EAAId,EAAM7K,OAAQ2L,IACjC7F,EAAQQ,gBAAgBuE,EAAMc,GAGjC,CAGA,OAAOL,CACP,CAAC,MAAOM,GAGR,GAFAlB,EAAOpE,gBAAgBqE,GAEnBE,EAAM7K,OAAS,EAAG,CAGrB,IADIuL,EAAgB,GACXC,EAAI,EAAGA,EAAIX,EAAM7K,OAAQwL,IACjCD,EAAc1K,KAAK,IAAMgK,EAAMW,GAAK,KAIrC,IADIC,EAAW1E,EAAOrF,SAASkE,iBAAiB2F,EAAc3C,KAAK,MAC1D8C,EAAI,EAAGA,EAAID,EAASzL,OAAQ0L,IAEpC,IADI5F,EAAU2F,EAASC,GACdC,EAAI,EAAGA,EAAId,EAAM7K,OAAQ2L,IACjC7F,EAAQQ,gBAAgBuE,EAAMc,GAGjC,CAEA,IAAIE,EAAe,GACnB,IACCxB,EAAIhH,MAAMyB,KAAM,CAAC,4BACjB,CAAC,MAAOgH,GACRD,EAAeC,EAAWC,QACtBF,IACHA,EAAeA,EAAalF,QAAQ,2BAA4B2D,GAElE,CAEKuB,IACJA,EAAe,qDAAuDvB,EAAkB,8BAGzF,IACC,MAAM,IAAI0B,aAAaH,EACvB,CAAC,MAAOrK,GACR,MAAM,IAAIoI,MAAMiC,EACjB,CACD,EAEF,CACA,CAvmBD,CAumBGxK","x_google_ignoreList":[4]} \ No newline at end of file +{"version":3,"file":"browser.mjs","sources":["../src/encode/decode.mjs","../src/encode/extract.mjs","../src/encode/encode.mjs","../src/browser.js","../../../node_modules/@mrhenry/core-web/modules/~element-qsa-has.js"],"sourcesContent":["\n/** Decodes an identifier back into a CSS selector */\nexport default function decodeCSS(value) {\n\tif (value.slice(0, 13) !== 'csstools-has-') {\n\t\treturn '';\n\t}\n\n\tvalue = value.slice(13);\n\tlet values = value.split('-');\n\n\tlet result = '';\n\tfor (let i = 0; i < values.length; i++) {\n\t\tresult += String.fromCharCode(parseInt(values[i], 36));\n\t}\n\n\treturn result;\n}\n","import decodeCSS from './decode.mjs';\n\n/** Extract encoded selectors out of attribute selectors */\nexport default function extractEncodedSelectors(value) {\n\tlet out = [];\n\n\tlet depth = 0;\n\tlet candidate;\n\n\tlet quoted = false;\n\tlet quotedMark;\n\n\tlet containsUnescapedUnquotedHasAtDepth1 = false;\n\n\t// Stryker disable next-line EqualityOperator\n\tfor (let i = 0; i < value.length; i++) {\n\t\tconst char = value[i];\n\n\t\tswitch (char) {\n\t\t\tcase '[':\n\t\t\t\tif (quoted) {\n\t\t\t\t\tcandidate += char;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tif (depth === 0) {\n\t\t\t\t\tcandidate = '';\n\t\t\t\t} else {\n\t\t\t\t\tcandidate += char;\n\t\t\t\t}\n\n\t\t\t\tdepth++;\n\t\t\t\tcontinue;\n\t\t\tcase ']':\n\t\t\t\tif (quoted) {\n\t\t\t\t\tcandidate += char;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\t{\n\t\t\t\t\tdepth--;\n\t\t\t\t\tif (depth === 0) {\n\t\t\t\t\t\tconst decoded = decodeCSS(candidate);\n\t\t\t\t\t\tif (containsUnescapedUnquotedHasAtDepth1) {\n\t\t\t\t\t\t\tout.push(decoded);\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tcandidate += char;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tcontinue;\n\t\t\tcase '\\\\':\n\t\t\t\tcandidate += value[i];\n\t\t\t\tcandidate += value[i+1];\n\t\t\t\ti++;\n\t\t\t\tcontinue;\n\n\t\t\tcase '\"':\n\t\t\tcase '\\'':\n\t\t\t\tif (quoted && char === quotedMark) {\n\t\t\t\t\tquoted = false;\n\t\t\t\t\tcontinue;\n\t\t\t\t} else if (quoted) {\n\t\t\t\t\tcandidate += char;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tquoted = true;\n\t\t\t\tquotedMark = char;\n\t\t\t\tcontinue;\n\n\t\t\tdefault:\n\t\t\t\tif (candidate === '' && depth === 1 && (value.slice(i, i + 13) === 'csstools-has-')) {\n\t\t\t\t\tcontainsUnescapedUnquotedHasAtDepth1 = true;\n\t\t\t\t}\n\n\t\t\t\tcandidate += char;\n\t\t\t\tcontinue;\n\t\t}\n\t}\n\n\tconst unique = [];\n\tfor (let i = 0; i < out.length; i++) {\n\t\tif (unique.indexOf(out[i]) === -1) {\n\t\t\tunique.push(out[i]);\n\t\t}\n\t}\n\n\treturn unique;\n}\n","\n/** Returns the string as an encoded CSS identifier. */\nexport default function encodeCSS(value) {\n\tif (value === '') {\n\t\treturn '';\n\t}\n\n\tlet hex;\n\tlet result = '';\n\tfor (let i = 0; i < value.length; i++) {\n\t\thex = value.charCodeAt(i).toString(36);\n\t\tif (i === 0) {\n\t\t\tresult += hex;\n\t\t} else {\n\t\t\tresult += '-' + hex;\n\t\t}\n\t}\n\n\treturn 'csstools-has-' + result;\n}\n","import '@mrhenry/core-web/modules/~element-qsa-has.js';\nimport extractEncodedSelectors from './encode/extract.mjs';\nimport encodeCSS from './encode/encode.mjs';\n\nfunction hasNativeSupport() {\n\ttry {\n\t\tif (!('CSS' in self) || !('supports' in self.CSS) || !self.CSS.supports('selector(:has(div))')) {\n\t\t\treturn false;\n\t\t}\n\n\t} catch (_) {\n\t\treturn false;\n\t}\n\n\treturn true;\n}\n\nexport default function cssHasPseudo(document, options) {\n\t// OPTIONS\n\t{\n\t\tif (!options) {\n\t\t\toptions = {};\n\t\t}\n\n\t\toptions = {\n\t\t\thover: (!!options.hover) || false,\n\t\t\tdebug: (!!options.debug) || false,\n\t\t\tobservedAttributes: options.observedAttributes || [],\n\t\t\tforcePolyfill: (!!options.forcePolyfill) || false,\n\t\t};\n\n\t\toptions.mustPolyfill = options.forcePolyfill || !hasNativeSupport();\n\n\t\tif (!Array.isArray(options.observedAttributes)) {\n\t\t\toptions.observedAttributes = [];\n\t\t}\n\n\t\toptions.observedAttributes = options.observedAttributes.filter((x) => {\n\t\t\treturn (typeof x === 'string');\n\t\t});\n\n\t\t// https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes\n\t\t// `data-*` and `style` were omitted\n\t\toptions.observedAttributes = options.observedAttributes.concat(['accept', 'accept-charset', 'accesskey', 'action', 'align', 'allow', 'alt', 'async', 'autocapitalize', 'autocomplete', 'autofocus', 'autoplay', 'buffered', 'capture', 'challenge', 'charset', 'checked', 'cite', 'class', 'code', 'codebase', 'cols', 'colspan', 'content', 'contenteditable', 'contextmenu', 'controls', 'coords', 'crossorigin', 'csp', 'data', 'datetime', 'decoding', 'default', 'defer', 'dir', 'dirname', 'disabled', 'download', 'draggable', 'enctype', 'enterkeyhint', 'for', 'form', 'formaction', 'formenctype', 'formmethod', 'formnovalidate', 'formtarget', 'headers', 'hidden', 'high', 'href', 'hreflang', 'http-equiv', 'icon', 'id', 'importance', 'integrity', 'intrinsicsize', 'inputmode', 'ismap', 'itemprop', 'keytype', 'kind', 'label', 'lang', 'language', 'list', 'loop', 'low', 'manifest', 'max', 'maxlength', 'minlength', 'media', 'method', 'min', 'multiple', 'muted', 'name', 'novalidate', 'open', 'optimum', 'pattern', 'ping', 'placeholder', 'poster', 'preload', 'radiogroup', 'readonly', 'referrerpolicy', 'rel', 'required', 'reversed', 'rows', 'rowspan', 'sandbox', 'scope', 'scoped', 'selected', 'shape', 'size', 'sizes', 'slot', 'span', 'spellcheck', 'src', 'srcdoc', 'srclang', 'srcset', 'start', 'step', 'summary', 'tabindex', 'target', 'title', 'translate', 'type', 'usemap', 'value', 'width', 'wrap']);\n\t}\n\n\tconst observedItems = [];\n\n\t// document.createAttribute() doesn't support `:` in the name. innerHTML does\n\tconst attributeElement = document.createElement('x');\n\n\t// walk all stylesheets to collect observed css rules\n\t[].forEach.call(document.styleSheets, walkStyleSheet);\n\tif (!options.mustPolyfill) {\n\t\t// Cleanup of rules will have happened in `walkStyleSheet`\n\t\t// Native support will take over from here\n\t\treturn;\n\t}\n\n\ttransformObservedItemsThrottled();\n\n\t// observe DOM modifications that affect selectors\n\tif ('MutationObserver' in self) {\n\t\tconst mutationObserver = new MutationObserver((mutationsList) => {\n\t\t\tmutationsList.forEach(mutation => {\n\t\t\t\t[].forEach.call(mutation.addedNodes || [], node => {\n\t\t\t\t\t// walk stylesheets to collect observed css rules\n\t\t\t\t\tif (node.nodeType === 1 && node.sheet) {\n\t\t\t\t\t\twalkStyleSheet(node.sheet);\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\t// transform observed css rules\n\t\t\t\tcleanupObservedCssRules();\n\t\t\t\ttransformObservedItemsThrottled();\n\t\t\t});\n\t\t});\n\n\t\tmutationObserver.observe(document, { childList: true, subtree: true, attributes: true, attributeFilter: options.observedAttributes });\n\t}\n\n\t// observe DOM events that affect pseudo-selectors\n\tdocument.addEventListener('focus', transformObservedItemsThrottled, true);\n\tdocument.addEventListener('blur', transformObservedItemsThrottled, true);\n\tdocument.addEventListener('input', transformObservedItemsThrottled);\n\tdocument.addEventListener('change', transformObservedItemsThrottled, true);\n\n\tif (options.hover) {\n\t\tif ('onpointerenter' in document) {\n\t\t\tdocument.addEventListener('pointerenter', transformObservedItemsThrottled, true);\n\t\t\tdocument.addEventListener('pointerleave', transformObservedItemsThrottled, true);\n\t\t} else {\n\t\t\tdocument.addEventListener('mouseover', transformObservedItemsThrottled, true);\n\t\t\tdocument.addEventListener('mouseout', transformObservedItemsThrottled, true);\n\t\t}\n\t}\n\n\t// observe Javascript setters that effect pseudo-selectors\n\tif ('defineProperty' in Object && 'getOwnPropertyDescriptor' in Object && 'hasOwnProperty' in Object) {\n\t\ttry {\n\t\t\tfunction observeProperty(proto, property) {\n\t\t\t\t// eslint-disable-next-line no-prototype-builtins\n\t\t\t\tif (proto.hasOwnProperty(property)) {\n\t\t\t\t\tconst descriptor = Object.getOwnPropertyDescriptor(proto, property);\n\t\t\t\t\tif (descriptor && descriptor.configurable && 'set' in descriptor) {\n\t\t\t\t\t\tObject.defineProperty(proto, property, {\n\t\t\t\t\t\t\tconfigurable: descriptor.configurable,\n\t\t\t\t\t\t\tenumerable: descriptor.enumerable,\n\t\t\t\t\t\t\tget: function () {\n\t\t\t\t\t\t\t\treturn descriptor.get.apply(this, arguments);\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tset: function () {\n\t\t\t\t\t\t\t\tdescriptor.set.apply(this, arguments);\n\n\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\ttransformObservedItemsThrottled();\n\t\t\t\t\t\t\t\t} catch (_) {\n\t\t\t\t\t\t\t\t\t// should never happen as there is an inner try/catch\n\t\t\t\t\t\t\t\t\t// but just in case\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif ('HTMLElement' in self && HTMLElement.prototype) {\n\t\t\t\tobserveProperty(HTMLElement.prototype, 'disabled');\n\t\t\t}\n\n\t\t\t// Not all of these elements have all of these properties.\n\t\t\t// But the code above checks if they exist first.\n\t\t\t['checked', 'selected', 'readOnly', 'required'].forEach((property) => {\n\t\t\t\t[\n\t\t\t\t\t'HTMLButtonElement',\n\t\t\t\t\t'HTMLFieldSetElement',\n\t\t\t\t\t'HTMLInputElement',\n\t\t\t\t\t'HTMLMeterElement',\n\t\t\t\t\t'HTMLOptGroupElement',\n\t\t\t\t\t'HTMLOptionElement',\n\t\t\t\t\t'HTMLOutputElement',\n\t\t\t\t\t'HTMLProgressElement',\n\t\t\t\t\t'HTMLSelectElement',\n\t\t\t\t\t'HTMLTextAreaElement',\n\t\t\t\t].forEach((elementName) => {\n\t\t\t\t\tif (elementName in self && self[elementName].prototype) {\n\t\t\t\t\t\tobserveProperty(self[elementName].prototype, property);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t});\n\t\t} catch (e) {\n\t\t\tif (options.debug) {\n\t\t\t\tconsole.error(e);\n\t\t\t}\n\t\t}\n\t}\n\n\tlet transformObservedItemsThrottledBusy = false;\n\tfunction transformObservedItemsThrottled() {\n\t\tif (transformObservedItemsThrottledBusy) {\n\t\t\tcancelAnimationFrame(transformObservedItemsThrottledBusy);\n\t\t}\n\n\t\ttransformObservedItemsThrottledBusy = requestAnimationFrame(() => {\n\t\t\ttransformObservedItems();\n\t\t});\n\t}\n\n\t// transform observed css rules\n\tfunction transformObservedItems() {\n\t\tobservedItems.forEach((item) => {\n\t\t\tconst nodes = [];\n\n\t\t\tlet matches = [];\n\t\t\ttry {\n\t\t\t\tmatches = document.querySelectorAll(item.selector);\n\t\t\t} catch (e) {\n\t\t\t\tif (options.debug) {\n\t\t\t\t\tconsole.error(e);\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t[].forEach.call(matches, (element) => {\n\t\t\t\t// memorize the node\n\t\t\t\tnodes.push(element);\n\n\t\t\t\t// set an attribute with an irregular attribute name\n\t\t\t\t// document.createAttribute() doesn't support special characters\n\t\t\t\tattributeElement.innerHTML = '';\n\n\t\t\t\telement.setAttributeNode(attributeElement.children[0].attributes[0].cloneNode());\n\n\t\t\t\t// trigger a style refresh in IE and Edge\n\t\t\t\tdocument.documentElement.style.zoom = 1; document.documentElement.style.zoom = null;\n\t\t\t});\n\n\t\t\t// remove the encoded attribute from all nodes that no longer match them\n\t\t\titem.nodes.forEach(node => {\n\t\t\t\tif (nodes.indexOf(node) === -1) {\n\t\t\t\t\tnode.removeAttribute(item.attributeName);\n\n\t\t\t\t\t// trigger a style refresh in IE and Edge\n\t\t\t\t\tdocument.documentElement.style.zoom = 1; document.documentElement.style.zoom = null;\n\t\t\t\t}\n\t\t\t});\n\n\t\t\t// update the\n\t\t\titem.nodes = nodes;\n\t\t});\n\t}\n\n\t// remove any observed cssrules that no longer apply\n\tfunction cleanupObservedCssRules() {\n\t\t[].push.apply(\n\t\t\tobservedItems,\n\t\t\tobservedItems.splice(0).filter((item) => {\n\t\t\t\treturn item.rule.parentStyleSheet &&\n\t\t\t\t\titem.rule.parentStyleSheet.ownerNode &&\n\t\t\t\t\tdocument.documentElement.contains(item.rule.parentStyleSheet.ownerNode);\n\t\t\t}),\n\t\t);\n\t}\n\n\t// walk a stylesheet to collect observed css rules\n\tfunction walkStyleSheet(styleSheet) {\n\t\ttry {\n\t\t\t// walk a css rule to collect observed css rules\n\t\t\t[].forEach.call(styleSheet.cssRules || [], (rule, index) => {\n\t\t\t\tif (rule.selectorText) {\n\t\t\t\t\trule.selectorText = rule.selectorText.replace(/\\.js-has-pseudo\\s/g, '');\n\n\t\t\t\t\ttry {\n\t\t\t\t\t\t// decode the selector text in all browsers to:\n\t\t\t\t\t\tconst hasSelectors = extractEncodedSelectors(rule.selectorText.toString());\n\t\t\t\t\t\tif (hasSelectors.length === 0) {\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (!options.mustPolyfill) {\n\t\t\t\t\t\t\tstyleSheet.deleteRule(index);\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tfor (let i = 0; i < hasSelectors.length; i++) {\n\t\t\t\t\t\t\tconst hasSelector = hasSelectors[i];\n\t\t\t\t\t\t\tobservedItems.push({\n\t\t\t\t\t\t\t\trule: rule,\n\t\t\t\t\t\t\t\tselector: hasSelector,\n\t\t\t\t\t\t\t\tattributeName: encodeCSS(hasSelector),\n\t\t\t\t\t\t\t\tnodes: [],\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\tif (options.debug) {\n\t\t\t\t\t\t\tconsole.error(e);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\twalkStyleSheet(rule);\n\t\t\t\t}\n\t\t\t});\n\t\t} catch (e) {\n\t\t\tif (options.debug) {\n\t\t\t\tconsole.error(e);\n\t\t\t}\n\t\t}\n\t}\n}\n","/* eslint-disable */\n(function (global) {\n\ttry {\n\t\t// test for has support\n\t\tglobal.document.querySelector(':has(*, :does-not-exist, > *)');\n\n\t\tif (\n\t\t\t!global.document.querySelector(':has(:scope *)') &&\n\t\t\tCSS.supports('selector(:has(div))')\n\t\t) {\n\t\t\treturn;\n\t\t}\n\t} catch (_) { }\n\n\t// ELEMENT\n\t// polyfill Element#querySelector\n\tvar querySelectorWithHasElement = polyfill(global.Element.prototype.querySelector);\n\n\tglobal.Element.prototype.querySelector = function querySelector(selectors) {\n\t\treturn querySelectorWithHasElement.apply(this, arguments);\n\t};\n\n\t// polyfill Element#querySelectorAll\n\tvar querySelectorAllWithHasElement = polyfill(global.Element.prototype.querySelectorAll);\n\n\tglobal.Element.prototype.querySelectorAll = function querySelectorAll(selectors) {\n\t\treturn querySelectorAllWithHasElement.apply(this, arguments);\n\t};\n\n\t// polyfill Element#matches\n\tif (global.Element.prototype.matches) {\n\t\tvar matchesWithHasElement = polyfill(global.Element.prototype.matches);\n\n\t\tglobal.Element.prototype.matches = function matches(selectors) {\n\t\t\treturn matchesWithHasElement.apply(this, arguments);\n\t\t};\n\t}\n\n\t// polyfill Element#closest\n\tif (global.Element.prototype.closest) {\n\t\tvar closestWithHasElement = polyfill(global.Element.prototype.closest);\n\n\t\tglobal.Element.prototype.closest = function closest(selectors) {\n\t\t\treturn closestWithHasElement.apply(this, arguments);\n\t\t};\n\t}\n\n\t// DOCUMENT\n\tif ('Document' in global && 'prototype' in global.Document) {\n\t\t// polyfill Document#querySelector\n\t\tvar querySelectorWithHasDocument = polyfill(global.Document.prototype.querySelector);\n\n\t\tglobal.Document.prototype.querySelector = function querySelector(selectors) {\n\t\t\treturn querySelectorWithHasDocument.apply(this, arguments);\n\t\t};\n\n\t\t// polyfill Document#querySelectorAll\n\t\tvar querySelectorAllWithHasDocument = polyfill(global.Document.prototype.querySelectorAll);\n\n\t\tglobal.Document.prototype.querySelectorAll = function querySelectorAll(selectors) {\n\t\t\treturn querySelectorAllWithHasDocument.apply(this, arguments);\n\t\t};\n\n\t\t// polyfill Document#matches\n\t\tif (global.Document.prototype.matches) {\n\t\t\tvar matchesWithHasDocument = polyfill(global.Document.prototype.matches);\n\n\t\t\tglobal.Document.prototype.matches = function matches(selectors) {\n\t\t\t\treturn matchesWithHasDocument.apply(this, arguments);\n\t\t\t};\n\t\t}\n\n\t\t// polyfill Document#closest\n\t\tif (global.Document.prototype.closest) {\n\t\t\tvar closestWithHasDocument = polyfill(global.Document.prototype.closest);\n\n\t\t\tglobal.Document.prototype.closest = function closest(selectors) {\n\t\t\t\treturn closestWithHasDocument.apply(this, arguments);\n\t\t\t};\n\t\t}\n\t}\n\n\tfunction pseudoClassHasInnerQuery(query) {\n\t\tvar current = '';\n\t\tvar start = 0;\n\t\tvar depth = 0;\n\n\t\tvar escaped = false;\n\n\t\tvar quoted = false;\n\t\tvar quotedMark = false;\n\n\t\tvar inHas = false;\n\n\t\tvar bracketed = 0;\n\n\t\tfor (var i = 0; i < query.length; i++) {\n\t\t\tvar char = query[i];\n\n\t\t\tif (escaped) {\n\t\t\t\tcurrent += char;\n\t\t\t\tescaped = false;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (quoted) {\n\t\t\t\tif (char === quotedMark) {\n\t\t\t\t\tquoted = false;\n\t\t\t\t}\n\n\t\t\t\tcurrent += char;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (current.toLowerCase() === ':has(' && !inHas) {\n\t\t\t\tinHas = true;\n\t\t\t\tstart = i;\n\t\t\t\tcurrent = '';\n\t\t\t}\n\n\t\t\tswitch (char) {\n\t\t\t\tcase ':':\n\t\t\t\t\tif (!inHas) {\n\t\t\t\t\t\tcurrent = '';\n\t\t\t\t\t}\n\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tcontinue;\n\n\t\t\t\tcase '(':\n\t\t\t\t\tif (inHas) {\n\t\t\t\t\t\tdepth++;\n\t\t\t\t\t}\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tcontinue;\n\n\t\t\t\tcase ')':\n\t\t\t\t\tif (inHas) {\n\t\t\t\t\t\tif (depth === 0) {\n\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\tinnerQuery: current,\n\t\t\t\t\t\t\t\tstart: start,\n\t\t\t\t\t\t\t\tend: i-1\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tdepth--;\n\t\t\t\t\t}\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tcontinue;\n\n\t\t\t\tcase '\\\\':\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tescaped = true;\n\t\t\t\t\tcontinue;\n\n\t\t\t\tcase '\"':\n\t\t\t\tcase \"'\":\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tquoted = true;\n\t\t\t\t\tquotedMark = char;\n\t\t\t\t\tcontinue;\n\n\t\t\t\tcase '[':\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tbracketed++;\n\t\t\t\t\tcontinue;\n\n\t\t\t\tcase \"]\":\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tif (bracketed > 0) {\n\t\t\t\t\t\tbracketed--\n\t\t\t\t\t}\n\n\t\t\t\t\tcontinue;\n\t\t\t\n\t\t\t\tdefault:\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\n\t\treturn false;\n\t}\n\n\tfunction replaceScopeWithAttr(query, attr) {\n\t\tvar parts = [];\n\t\tvar current = '';\n\n\t\tvar escaped = false;\n\n\t\tvar quoted = false;\n\t\tvar quotedMark = false;\n\n\t\tvar bracketed = 0;\n\n\t\tfor (var i = 0; i < query.length; i++) {\n\t\t\tvar char = query[i];\n\n\t\t\tif (escaped) {\n\t\t\t\tcurrent += char;\n\t\t\t\tescaped = false;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (quoted) {\n\t\t\t\tif (char === quotedMark) {\n\t\t\t\t\tquoted = false;\n\t\t\t\t}\n\n\t\t\t\tcurrent += char;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (current.toLowerCase() === ':scope' && !bracketed && (/^[\\[\\.\\:\\\\\"\\s|+>~#&,)]/.test(char || ''))) {\n\t\t\t\tparts.push(current.slice(0, current.length - 6));\n\t\t\t\tparts.push('[' + attr + ']');\n\t\t\t\tcurrent = '';\n\t\t\t}\n\n\t\t\tswitch (char) {\n\t\t\t\tcase ':':\n\t\t\t\t\tparts.push(current);\n\t\t\t\t\tcurrent = '';\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tcontinue;\n\n\t\t\t\tcase '\\\\':\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tescaped = true;\n\t\t\t\t\tcontinue;\n\n\t\t\t\tcase '\"':\n\t\t\t\tcase \"'\":\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tquoted = true;\n\t\t\t\t\tquotedMark = char;\n\t\t\t\t\tcontinue;\n\n\t\t\t\tcase '[':\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tbracketed++;\n\t\t\t\t\tcontinue;\n\n\t\t\t\tcase \"]\":\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tif (bracketed > 0) {\n\t\t\t\t\t\tbracketed--\n\t\t\t\t\t}\n\n\t\t\t\t\tcontinue;\n\n\t\t\t\tdefault:\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\n\t\tif (current.toLowerCase() === ':scope') {\n\t\t\tparts.push(current.slice(0, current.length - 6));\n\t\t\tparts.push('[' + attr + ']');\n\t\t\tcurrent = '';\n\t\t}\n\n\t\tif (parts.length === 0) {\n\t\t\treturn query;\n\t\t}\n\n\t\treturn parts.join('') + current;\n\t}\n\n\tfunction charIsNestedMarkMirror(char, mark) {\n\t\tif (mark === '(' && char === ')') {\n\t\t\treturn true;\n\t\t}\n\n\t\tif (mark === '[' && char === ']') {\n\t\t\treturn true;\n\t\t}\n\n\t\treturn false;\n\t}\n\n\tfunction splitSelector(query) {\n\t\tvar selectors = [];\n\t\tvar current = '';\n\n\t\tvar escaped = false;\n\n\t\tvar quoted = false;\n\t\tvar quotedMark = false;\n\n\t\tvar nestedMark = false;\n\t\tvar nestedDepth = 0;\n\n\t\tfor (var i = 0; i < query.length; i++) {\n\t\t\tvar char = query[i];\n\n\t\t\tif (escaped) {\n\t\t\t\tcurrent += char;\n\t\t\t\tescaped = false;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tswitch (char) {\n\t\t\t\tcase ',':\n\t\t\t\t\tif (quoted) {\n\t\t\t\t\t\tcurrent += char;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (nestedDepth > 0) {\n\t\t\t\t\t\tcurrent += char;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tselectors.push(current);\n\t\t\t\t\tcurrent = '';\n\t\t\t\t\tcontinue;\n\n\t\t\t\tcase '\\\\':\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tescaped = true;\n\t\t\t\t\tcontinue;\n\n\t\t\t\tcase '\"':\n\t\t\t\tcase \"'\":\n\t\t\t\t\tif (quoted && char === quotedMark) {\n\t\t\t\t\t\tcurrent += char;\n\t\t\t\t\t\tquoted = false;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tquoted = true;\n\t\t\t\t\tquotedMark = char;\n\t\t\t\t\tcontinue;\n\n\t\t\t\tcase '(':\n\t\t\t\tcase ')':\n\t\t\t\tcase '[':\n\t\t\t\tcase ']':\n\t\t\t\t\tif (quoted) {\n\t\t\t\t\t\tcurrent += char;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (charIsNestedMarkMirror(char, nestedMark)) {\n\t\t\t\t\t\tcurrent += char;\n\t\t\t\t\t\tnestedDepth--;\n\n\t\t\t\t\t\tif (nestedDepth === 0) {\n\t\t\t\t\t\t\tnestedMark = false;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (char === nestedMark) {\n\t\t\t\t\t\tcurrent += char;\n\t\t\t\t\t\tnestedDepth++;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tnestedDepth++;\n\t\t\t\t\tnestedMark = char;\n\t\t\t\t\tcontinue;\n\n\t\t\t\tdefault:\n\t\t\t\t\tcurrent += char;\n\t\t\t\t\tcontinue;\n\n\t\t\t}\n\t\t}\n\n\t\tselectors.push(current);\n\n\t\treturn selectors;\n\t}\n\n\tfunction replaceAllWithTempAttr(query, nested, callback) {\n\t\tvar inner = pseudoClassHasInnerQuery(query);\n\t\tif (!inner) {\n\t\t\treturn query;\n\t\t}\n\n\t\tif (nested) {\n\t\t\treturn false;\n\t\t}\n\n\t\tvar innerQuery = inner.innerQuery;\n\t\tvar attr = 'q-has' + (Math.floor(Math.random() * 9000000) + 1000000);\n\t\tvar innerReplacement = '[' + attr + ']';\n\n\t\tvar x = query;\n\n\t\tif (inner.innerQuery.toLowerCase().indexOf(':has(') > -1) {\n\t\t\tvar innerParts = splitSelector(inner.innerQuery);\n\t\t\tvar newInnerParts = [];\n\t\t\tfor (var i = 0; i < innerParts.length; i++) {\n\t\t\t\tvar innerPart = innerParts[i];\n\n\t\t\t\t// Nested has is not supported.\n\t\t\t\t// If a recursive/nested call returns \"false\" we throw\n\t\t\t\tvar innerPartReplaced = replaceAllWithTempAttr(innerPart, true, function () { });\n\t\t\t\tif (!innerPartReplaced) {\n\t\t\t\t\tthrow new Error(\"Nested :has() is not supported\")\n\t\t\t\t} else {\n\t\t\t\t\tnewInnerParts.push(innerPart);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tvar _prefix = x.substring(0, inner.start - 5); // ':has('.length === 5\n\t\t\tvar _suffix = x.substring(inner.end + 2); // ')'.length === 1\n\n\t\t\treturn _prefix + newInnerParts.join(', ') + _suffix;\n\t\t}\n\n\t\tvar _prefix = x.substring(0, inner.start - 5); // ':has('.length === 5\n\t\tvar _suffix = x.substring(inner.end + 2); // ')'.length === 1\n\n\t\tx = _prefix + innerReplacement + _suffix;\n\n\t\tcallback(innerQuery, attr);\n\t\tif (x.toLowerCase().indexOf(':has(') > -1) {\n\t\t\tvar y = replaceAllWithTempAttr(x, false, callback);\n\t\t\tif (y) {\n\t\t\t\treturn y;\n\t\t\t}\n\t\t}\n\n\t\treturn x;\n\t}\n\n\tfunction walkNode(rootNode, callback) {\n\t\tif (('setAttribute' in (rootNode)) && ('querySelector' in (rootNode))) {\n\t\t\tcallback(rootNode);\n\t\t}\n\n\t\tif (rootNode.hasChildNodes()) {\n\t\t\tvar nodes = rootNode.childNodes;\n\t\t\tfor (var i = 0; i < nodes.length; ++i) {\n\t\t\t\twalkNode(nodes[i], callback);\n\t\t\t}\n\t\t}\n\t}\n\n\tfunction polyfill(qsa) {\n\t\treturn function (selectors) {\n\t\t\tif (!selectors) {\n\t\t\t\treturn qsa.apply(this, arguments);\n\t\t\t}\n\n\t\t\tvar selectorsString = String(selectors);\n\t\t\tif (!selectorsString || (selectorsString.toLowerCase().indexOf(':has(') === -1) || !pseudoClassHasInnerQuery(selectorsString)) {\n\t\t\t\treturn qsa.apply(this, arguments);\n\t\t\t}\n\n\t\t\tvar rootNode;\n\t\t\tif ('getRootNode' in this) {\n\t\t\t\trootNode = this.getRootNode();\n\t\t\t} else {\n\t\t\t\tvar r = this;\n\t\t\t\twhile (r) {\n\t\t\t\t\trootNode = r;\n\t\t\t\t\tr = r.parentNode;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tvar _focus = this;\n\t\t\tif (_focus === global.document) {\n\t\t\t\t_focus = global.document.documentElement;\n\t\t\t}\n\n\t\t\tvar scopeAttr = 'q-has-scope' + (Math.floor(Math.random() * 9000000) + 1000000);\n\t\t\t_focus.setAttribute(scopeAttr, '');\n\n\t\t\ttry {\n\t\t\t\tselectorsString = replaceScopeWithAttr(selectorsString, scopeAttr);\n\n\t\t\t\tvar attrs = [scopeAttr];\n\t\t\t\tvar newQuery = replaceAllWithTempAttr(selectorsString, false, function (inner, attr) {\n\t\t\t\t\tattrs.push(attr);\n\n\t\t\t\t\tvar selectorParts = splitSelector(inner);\n\t\t\t\t\tfor (var x = 0; x < selectorParts.length; x++) {\n\t\t\t\t\t\tvar selectorPart = selectorParts[x].trim();\n\t\t\t\t\t\tvar absoluteSelectorPart = selectorPart;\n\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\tselectorPart[0] === '>' ||\n\t\t\t\t\t\t\tselectorPart[0] === '+' ||\n\t\t\t\t\t\t\tselectorPart[0] === '~'\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\tabsoluteSelectorPart = selectorPart.slice(1).trim();\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tabsoluteSelectorPart = ':scope ' + selectorPart;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\twalkNode(rootNode, function (node) {\n\t\t\t\t\t\t\tif (!(node.querySelector(absoluteSelectorPart))) {\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tswitch (selectorPart[0]) {\n\t\t\t\t\t\t\t\tcase '~':\n\t\t\t\t\t\t\t\tcase '+':\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tvar siblings = node.childNodes;\n\t\t\t\t\t\t\t\t\t\tfor (var i = 0; i < siblings.length; i++) {\n\t\t\t\t\t\t\t\t\t\t\tvar sibling = siblings[i];\n\t\t\t\t\t\t\t\t\t\t\tif (!('setAttribute' in sibling)) {\n\t\t\t\t\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\tvar idAttr = 'q-has-id' + (Math.floor(Math.random() * 9000000) + 1000000);\n\t\t\t\t\t\t\t\t\t\t\tsibling.setAttribute(idAttr, '');\n\n\t\t\t\t\t\t\t\t\t\t\tif (node.querySelector(':scope [' + idAttr + ']' + ' ' + selectorPart)) {\n\t\t\t\t\t\t\t\t\t\t\t\tsibling.setAttribute(attr, '');\n\t\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\t\tsibling.removeAttribute(idAttr);\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\t\t\tcase '>':\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tvar idAttr = 'q-has-id' + (Math.floor(Math.random() * 9000000) + 1000000);\n\t\t\t\t\t\t\t\t\t\tnode.setAttribute(idAttr, '');\n\n\t\t\t\t\t\t\t\t\t\tif (node.querySelector(':scope[' + idAttr + ']' + ' ' + selectorPart)) {\n\t\t\t\t\t\t\t\t\t\t\tnode.setAttribute(attr, '');\n\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\tnode.removeAttribute(idAttr);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\t\t\tnode.setAttribute(attr, '');\n\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\targuments[0] = newQuery;\n\n\t\t\t\t// results of the qsa\n\t\t\t\tvar elementOrNodeList = qsa.apply(this, arguments);\n\n\t\t\t\t_focus.removeAttribute(scopeAttr);\n\n\t\t\t\tif (attrs.length > 0) {\n\t\t\t\t\t// remove the fallback attribute\n\t\t\t\t\tvar attrsForQuery = [];\n\t\t\t\t\tfor (var j = 0; j < attrs.length; j++) {\n\t\t\t\t\t\tattrsForQuery.push('[' + attrs[j] + ']');\n\t\t\t\t\t}\n\n\t\t\t\t\tvar elements = global.document.querySelectorAll(attrsForQuery.join(','));\n\t\t\t\t\tfor (var k = 0; k < elements.length; k++) {\n\t\t\t\t\t\tvar element = elements[k];\n\t\t\t\t\t\tfor (var l = 0; l < attrs.length; l++) {\n\t\t\t\t\t\t\telement.removeAttribute(attrs[l]);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// return the results of the qsa\n\t\t\t\treturn elementOrNodeList;\n\t\t\t} catch (err) {\n\t\t\t\t_focus.removeAttribute(scopeAttr);\n\n\t\t\t\tif (attrs.length > 0) {\n\t\t\t\t\t// remove the fallback attribute\n\t\t\t\t\tvar attrsForQuery = [];\n\t\t\t\t\tfor (var j = 0; j < attrs.length; j++) {\n\t\t\t\t\t\tattrsForQuery.push('[' + attrs[j] + ']');\n\t\t\t\t\t}\n\n\t\t\t\t\tvar elements = global.document.querySelectorAll(attrsForQuery.join(','));\n\t\t\t\t\tfor (var k = 0; k < elements.length; k++) {\n\t\t\t\t\t\tvar element = elements[k];\n\t\t\t\t\t\tfor (var l = 0; l < attrs.length; l++) {\n\t\t\t\t\t\t\telement.removeAttribute(attrs[l]);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tvar errorMessage = '';\n\t\t\t\ttry {\n\t\t\t\t\tqsa.apply(this, [':core-web-does-not-exist']);\n\t\t\t\t} catch (dummyError) {\n\t\t\t\t\terrorMessage = dummyError.message;\n\t\t\t\t\tif (errorMessage) {\n\t\t\t\t\t\terrorMessage = errorMessage.replace(':core-web-does-not-exist', selectorsString);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (!errorMessage) {\n\t\t\t\t\terrorMessage = \"Failed to execute 'querySelector' on 'Document': '\" + selectorsString + \"' is not a valid selector.\";\n\t\t\t\t}\n\n\t\t\t\ttry {\n\t\t\t\t\tthrow new DOMException(errorMessage);\n\t\t\t\t} catch (_) {\n\t\t\t\t\tthrow new Error(errorMessage);\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\t}\n})(self);\n"],"names":["decodeCSS","value","slice","values","split","result","i","length","String","fromCharCode","parseInt","extractEncodedSelectors","candidate","quotedMark","out","depth","quoted","containsUnescapedUnquotedHasAtDepth1","char","decoded","push","unique","indexOf","encodeCSS","hex","charCodeAt","toString","hasNativeSupport","self","CSS","supports","_","cssHasPseudo","document","options","hover","debug","observedAttributes","forcePolyfill","mustPolyfill","Array","isArray","filter","x","concat","observedItems","attributeElement","createElement","forEach","call","styleSheets","walkStyleSheet","transformObservedItemsThrottled","MutationObserver","mutationsList","mutation","addedNodes","node","nodeType","sheet","apply","splice","item","rule","parentStyleSheet","ownerNode","documentElement","contains","observe","childList","subtree","attributes","attributeFilter","addEventListener","Object","observeProperty","proto","property","hasOwnProperty","descriptor","getOwnPropertyDescriptor","configurable","defineProperty","enumerable","get","this","arguments","set","HTMLElement","prototype","elementName","e","console","error","transformObservedItemsThrottledBusy","cancelAnimationFrame","requestAnimationFrame","nodes","matches","querySelectorAll","selector","element","innerHTML","attributeName","setAttributeNode","children","cloneNode","style","zoom","removeAttribute","styleSheet","cssRules","index","selectorText","replace","hasSelectors","deleteRule","hasSelector","global","querySelector","querySelectorWithHasElement","polyfill","Element","selectors","querySelectorAllWithHasElement","matchesWithHasElement","closest","closestWithHasElement","Document","querySelectorWithHasDocument","querySelectorAllWithHasDocument","matchesWithHasDocument","closestWithHasDocument","pseudoClassHasInnerQuery","query","current","start","escaped","inHas","toLowerCase","innerQuery","end","replaceScopeWithAttr","attr","parts","bracketed","test","join","splitSelector","mark","nestedMark","nestedDepth","replaceAllWithTempAttr","nested","callback","inner","Math","floor","random","innerReplacement","innerParts","newInnerParts","innerPart","Error","_prefix","substring","_suffix","y","walkNode","rootNode","hasChildNodes","childNodes","qsa","selectorsString","getRootNode","r","parentNode","_focus","scopeAttr","setAttribute","attrs","newQuery","selectorParts","selectorPart","trim","absoluteSelectorPart","siblings","sibling","idAttr","elementOrNodeList","attrsForQuery","j","elements","k","l","err","errorMessage","dummyError","message","DOMException"],"mappings":"AAEe,SAASA,UAAUC,GACjC,GAA2B,kBAAvBA,EAAMC,MAAM,EA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,KAIrC,IADA,IAAIC,EAAW1E,EAAOrF,SAASkE,iBAAiB2F,EAAc3C,KAAK,MAC1D8C,EAAI,EAAGA,EAAID,EAASzL,OAAQ0L,IAEpC,IADA,IAAI5F,EAAU2F,EAASC,GACdC,EAAI,EAAGA,EAAId,EAAM7K,OAAQ2L,IACjC7F,EAAQQ,gBAAgBuE,EAAMc,GAGjC,CAGA,OAAOL,CACP,CAAC,MAAOM,GAGR,GAFAlB,EAAOpE,gBAAgBqE,GAEnBE,EAAM7K,OAAS,EAAG,CAGrB,IADIuL,EAAgB,GACXC,EAAI,EAAGA,EAAIX,EAAM7K,OAAQwL,IACjCD,EAAc1K,KAAK,IAAMgK,EAAMW,GAAK,KAIrC,IADIC,EAAW1E,EAAOrF,SAASkE,iBAAiB2F,EAAc3C,KAAK,MAC1D8C,EAAI,EAAGA,EAAID,EAASzL,OAAQ0L,IAEpC,IADI5F,EAAU2F,EAASC,GACdC,EAAI,EAAGA,EAAId,EAAM7K,OAAQ2L,IACjC7F,EAAQQ,gBAAgBuE,EAAMc,GAGjC,CAEA,IAAIE,EAAe,GACnB,IACCxB,EAAIhH,MAAMyB,KAAM,CAAC,4BACjB,CAAC,MAAOgH,GACRD,EAAeC,EAAWC,QACtBF,IACHA,EAAeA,EAAalF,QAAQ,2BAA4B2D,GAElE,CAEKuB,IACJA,EAAe,qDAAuDvB,EAAkB,8BAGzF,IACC,MAAM,IAAI0B,aAAaH,EACvB,CAAC,MAAOrK,GACR,MAAM,IAAIoI,MAAMiC,EACjB,CACD,EAEF,CACA,CAvmBD,CAumBGxK","x_google_ignoreList":[4]} \ No newline at end of file diff --git a/plugins/css-has-pseudo/dist/index.cjs b/plugins/css-has-pseudo/dist/index.cjs index 33b81a423..f3117e383 100644 --- a/plugins/css-has-pseudo/dist/index.cjs +++ b/plugins/css-has-pseudo/dist/index.cjs @@ -1 +1 @@ -"use strict";var e=require("postcss-selector-parser"),t=require("postcss-value-parser"),s=require("@csstools/selector-specificity");function encodeCSS(e){if(""===e)return"";let t,s="";for(let r=0;r{if("function"===e.type&&"selector"===e.value.toLowerCase())return r.add(t.stringify(e.nodes)),!1})),r.forEach((e=>{selectorContainsHasPseudo(e)&&(s=!0)}))}catch(e){}return s}function selectorContainsHasPseudo(t){if(!t.toLowerCase().includes(":has("))return!1;let s=!1;try{e().astSync(t).walk((e=>{if("pseudo"===e.type&&":has"===e.value.toLowerCase()&&e.nodes&&e.nodes.length>0)return s=!0,!1}))}catch(e){}return s}const creator=t=>{const r={preserve:!0,specificityMatchingName:"does-not-exist",...t||{}},o=":not(#"+r.specificityMatchingName+")",n=":not(."+r.specificityMatchingName+")",a=":not("+r.specificityMatchingName+")";return{postcssPlugin:"css-has-pseudo",prepare(){const t=new WeakSet;return{postcssPlugin:"css-has-pseudo",RuleExit(c,{result:i}){if(t.has(c))return;if(!c.selector.toLowerCase().includes(":has(")||isWithinSupportCheck(c))return;const l=c.selectors.map((t=>{if(!t.toLowerCase().includes(":has("))return t;let l;try{l=e().astSync(t)}catch(e){return c.warn(i,`Failed to parse selector : "${t}" with message: "${e instanceof Error?e.message:e}"`),t}if(void 0===l)return t;l.walkPseudos((t=>{let s=t.parent,o=!1;for(;s;)e.isPseudoClass(s)&&":has"===s.value.toLowerCase()&&(o=!0),s=s.parent;o&&(":visited"===t.value.toLowerCase()&&t.replaceWith(e.className({value:r.specificityMatchingName})),":any-link"===t.value.toLowerCase()&&(t.value=":link"))})),l.walkPseudos((t=>{if(":has"!==t.value.toLowerCase()||!t.nodes)return;const r=t.parent;if(!r)return;const c=e.selector({value:"",nodes:[]});{let t=r.nodes.length;e:for(let s=0;s=0;e--)if("combinator"!==r.nodes[s].type&&"comment"!==r.nodes[s].type){t=e+1;break e}}r.nodes.slice(0,t).forEach((e=>{e.remove(),"selector"===e.type?e.nodes.forEach((e=>{delete e.parent,c.append(e)})):(delete e.parent,c.append(e))}))}const i="["+encodeCSS(c.toString())+"]",l=s.selectorSpecificity(c);let u=i;for(let e=0;e=0;e--)r.prepend(d[e])}));const u=l.toString();return u!==t?".js-has-pseudo "+u:t}));l.join(",")!==c.selectors.join(",")&&(t.add(c),c.cloneBefore({selectors:l}),r.preserve||c.remove())}}}}};function isWithinSupportCheck(e){let t=e.parent;for(;t;){if("atrule"===t.type&&isGuardedByAtSupportsFromAtRuleParams(t.params))return!0;t=t.parent}return!1}creator.postcss=!0,module.exports=creator; +"use strict";var e=require("postcss-selector-parser"),t=require("postcss-value-parser"),s=require("@csstools/selector-specificity");function encodeCSS(e){if(""===e)return"";let t,s="";for(let r=0;r{if("function"===e.type&&"selector"===e.value.toLowerCase())return r.add(t.stringify(e.nodes)),!1})),r.forEach((e=>{selectorContainsHasPseudo(e)&&(s=!0)}))}catch{}return s}function selectorContainsHasPseudo(t){if(!t.toLowerCase().includes(":has("))return!1;let s=!1;try{e().astSync(t).walk((e=>{if("pseudo"===e.type&&":has"===e.value.toLowerCase()&&e.nodes&&e.nodes.length>0)return s=!0,!1}))}catch{}return s}const creator=t=>{const r={preserve:!0,specificityMatchingName:"does-not-exist",...t||{}},o=":not(#"+r.specificityMatchingName+")",n=":not(."+r.specificityMatchingName+")",a=":not("+r.specificityMatchingName+")";return{postcssPlugin:"css-has-pseudo",prepare(){const t=new WeakSet;return{postcssPlugin:"css-has-pseudo",RuleExit(c,{result:i}){if(t.has(c))return;if(!c.selector.toLowerCase().includes(":has(")||isWithinSupportCheck(c))return;const l=c.selectors.map((t=>{if(!t.toLowerCase().includes(":has("))return t;let l;try{l=e().astSync(t)}catch(e){return c.warn(i,`Failed to parse selector : "${t}" with message: "${e instanceof Error?e.message:e}"`),t}if(void 0===l)return t;l.walkPseudos((t=>{let s=t.parent,o=!1;for(;s;)e.isPseudoClass(s)&&":has"===s.value.toLowerCase()&&(o=!0),s=s.parent;o&&(":visited"===t.value.toLowerCase()&&t.replaceWith(e.className({value:r.specificityMatchingName})),":any-link"===t.value.toLowerCase()&&(t.value=":link"))})),l.walkPseudos((t=>{if(":has"!==t.value.toLowerCase()||!t.nodes)return;const r=t.parent;if(!r)return;const c=e.selector({value:"",nodes:[]});{let t=r.nodes.length;e:for(let s=0;s=0;e--)if("combinator"!==r.nodes[s].type&&"comment"!==r.nodes[s].type){t=e+1;break e}}r.nodes.slice(0,t).forEach((e=>{e.remove(),"selector"===e.type?e.nodes.forEach((e=>{delete e.parent,c.append(e)})):(delete e.parent,c.append(e))}))}const i="["+encodeCSS(c.toString())+"]",l=s.selectorSpecificity(c);let u=i;for(let e=0;e=0;e--)r.prepend(d[e])}));const u=l.toString();return u!==t?".js-has-pseudo "+u:t}));l.join(",")!==c.selectors.join(",")&&(t.add(c),c.cloneBefore({selectors:l}),r.preserve||c.remove())}}}}};function isWithinSupportCheck(e){let t=e.parent;for(;t;){if("atrule"===t.type&&isGuardedByAtSupportsFromAtRuleParams(t.params))return!0;t=t.parent}return!1}creator.postcss=!0,module.exports=creator; diff --git a/plugins/css-has-pseudo/dist/index.mjs b/plugins/css-has-pseudo/dist/index.mjs index 66b4a8538..fb2dfe009 100644 --- a/plugins/css-has-pseudo/dist/index.mjs +++ b/plugins/css-has-pseudo/dist/index.mjs @@ -1 +1 @@ -import e from"postcss-selector-parser";import t from"postcss-value-parser";import{selectorSpecificity as s}from"@csstools/selector-specificity";function encodeCSS(e){if(""===e)return"";let t,s="";for(let o=0;o{if("function"===e.type&&"selector"===e.value.toLowerCase())return o.add(t.stringify(e.nodes)),!1})),o.forEach((e=>{selectorContainsHasPseudo(e)&&(s=!0)}))}catch(e){}return s}function selectorContainsHasPseudo(t){if(!t.toLowerCase().includes(":has("))return!1;let s=!1;try{e().astSync(t).walk((e=>{if("pseudo"===e.type&&":has"===e.value.toLowerCase()&&e.nodes&&e.nodes.length>0)return s=!0,!1}))}catch(e){}return s}const creator=t=>{const o={preserve:!0,specificityMatchingName:"does-not-exist",...t||{}},r=":not(#"+o.specificityMatchingName+")",n=":not(."+o.specificityMatchingName+")",a=":not("+o.specificityMatchingName+")";return{postcssPlugin:"css-has-pseudo",prepare(){const t=new WeakSet;return{postcssPlugin:"css-has-pseudo",RuleExit(c,{result:i}){if(t.has(c))return;if(!c.selector.toLowerCase().includes(":has(")||isWithinSupportCheck(c))return;const l=c.selectors.map((t=>{if(!t.toLowerCase().includes(":has("))return t;let l;try{l=e().astSync(t)}catch(e){return c.warn(i,`Failed to parse selector : "${t}" with message: "${e instanceof Error?e.message:e}"`),t}if(void 0===l)return t;l.walkPseudos((t=>{let s=t.parent,r=!1;for(;s;)e.isPseudoClass(s)&&":has"===s.value.toLowerCase()&&(r=!0),s=s.parent;r&&(":visited"===t.value.toLowerCase()&&t.replaceWith(e.className({value:o.specificityMatchingName})),":any-link"===t.value.toLowerCase()&&(t.value=":link"))})),l.walkPseudos((t=>{if(":has"!==t.value.toLowerCase()||!t.nodes)return;const o=t.parent;if(!o)return;const c=e.selector({value:"",nodes:[]});{let t=o.nodes.length;e:for(let s=0;s=0;e--)if("combinator"!==o.nodes[s].type&&"comment"!==o.nodes[s].type){t=e+1;break e}}o.nodes.slice(0,t).forEach((e=>{e.remove(),"selector"===e.type?e.nodes.forEach((e=>{delete e.parent,c.append(e)})):(delete e.parent,c.append(e))}))}const i="["+encodeCSS(c.toString())+"]",l=s(c);let u=i;for(let e=0;e=0;e--)o.prepend(d[e])}));const u=l.toString();return u!==t?".js-has-pseudo "+u:t}));l.join(",")!==c.selectors.join(",")&&(t.add(c),c.cloneBefore({selectors:l}),o.preserve||c.remove())}}}}};function isWithinSupportCheck(e){let t=e.parent;for(;t;){if("atrule"===t.type&&isGuardedByAtSupportsFromAtRuleParams(t.params))return!0;t=t.parent}return!1}creator.postcss=!0;export{creator as default}; +import e from"postcss-selector-parser";import t from"postcss-value-parser";import{selectorSpecificity as s}from"@csstools/selector-specificity";function encodeCSS(e){if(""===e)return"";let t,s="";for(let o=0;o{if("function"===e.type&&"selector"===e.value.toLowerCase())return o.add(t.stringify(e.nodes)),!1})),o.forEach((e=>{selectorContainsHasPseudo(e)&&(s=!0)}))}catch{}return s}function selectorContainsHasPseudo(t){if(!t.toLowerCase().includes(":has("))return!1;let s=!1;try{e().astSync(t).walk((e=>{if("pseudo"===e.type&&":has"===e.value.toLowerCase()&&e.nodes&&e.nodes.length>0)return s=!0,!1}))}catch{}return s}const creator=t=>{const o={preserve:!0,specificityMatchingName:"does-not-exist",...t||{}},r=":not(#"+o.specificityMatchingName+")",n=":not(."+o.specificityMatchingName+")",a=":not("+o.specificityMatchingName+")";return{postcssPlugin:"css-has-pseudo",prepare(){const t=new WeakSet;return{postcssPlugin:"css-has-pseudo",RuleExit(c,{result:i}){if(t.has(c))return;if(!c.selector.toLowerCase().includes(":has(")||isWithinSupportCheck(c))return;const l=c.selectors.map((t=>{if(!t.toLowerCase().includes(":has("))return t;let l;try{l=e().astSync(t)}catch(e){return c.warn(i,`Failed to parse selector : "${t}" with message: "${e instanceof Error?e.message:e}"`),t}if(void 0===l)return t;l.walkPseudos((t=>{let s=t.parent,r=!1;for(;s;)e.isPseudoClass(s)&&":has"===s.value.toLowerCase()&&(r=!0),s=s.parent;r&&(":visited"===t.value.toLowerCase()&&t.replaceWith(e.className({value:o.specificityMatchingName})),":any-link"===t.value.toLowerCase()&&(t.value=":link"))})),l.walkPseudos((t=>{if(":has"!==t.value.toLowerCase()||!t.nodes)return;const o=t.parent;if(!o)return;const c=e.selector({value:"",nodes:[]});{let t=o.nodes.length;e:for(let s=0;s=0;e--)if("combinator"!==o.nodes[s].type&&"comment"!==o.nodes[s].type){t=e+1;break e}}o.nodes.slice(0,t).forEach((e=>{e.remove(),"selector"===e.type?e.nodes.forEach((e=>{delete e.parent,c.append(e)})):(delete e.parent,c.append(e))}))}const i="["+encodeCSS(c.toString())+"]",l=s(c);let u=i;for(let e=0;e=0;e--)o.prepend(d[e])}));const u=l.toString();return u!==t?".js-has-pseudo "+u:t}));l.join(",")!==c.selectors.join(",")&&(t.add(c),c.cloneBefore({selectors:l}),o.preserve||c.remove())}}}}};function isWithinSupportCheck(e){let t=e.parent;for(;t;){if("atrule"===t.type&&isGuardedByAtSupportsFromAtRuleParams(t.params))return!0;t=t.parent}return!1}creator.postcss=!0;export{creator as default}; diff --git a/plugins/css-has-pseudo/src/browser-global.js b/plugins/css-has-pseudo/src/browser-global.js index 3cba9e690..082a25376 100644 --- a/plugins/css-has-pseudo/src/browser-global.js +++ b/plugins/css-has-pseudo/src/browser-global.js @@ -1,4 +1,3 @@ -/* global self,window */ import { default as cssHasPseudo } from './browser'; (function (global) { diff --git a/plugins/css-has-pseudo/src/browser.js b/plugins/css-has-pseudo/src/browser.js index 996456f13..fcfe1619a 100644 --- a/plugins/css-has-pseudo/src/browser.js +++ b/plugins/css-has-pseudo/src/browser.js @@ -1,5 +1,3 @@ -/* global MutationObserver,requestAnimationFrame,cancelAnimationFrame,self,HTMLElement */ - import '@mrhenry/core-web/modules/~element-qsa-has.js'; import extractEncodedSelectors from './encode/extract.mjs'; import encodeCSS from './encode/encode.mjs'; @@ -100,7 +98,6 @@ export default function cssHasPseudo(document, options) { // observe Javascript setters that effect pseudo-selectors if ('defineProperty' in Object && 'getOwnPropertyDescriptor' in Object && 'hasOwnProperty' in Object) { try { - // eslint-disable-next-line no-inner-declarations function observeProperty(proto, property) { // eslint-disable-next-line no-prototype-builtins if (proto.hasOwnProperty(property)) { diff --git a/plugins/css-has-pseudo/src/is-guarded-by-at-supports.ts b/plugins/css-has-pseudo/src/is-guarded-by-at-supports.ts index a67193018..68cf6986c 100644 --- a/plugins/css-has-pseudo/src/is-guarded-by-at-supports.ts +++ b/plugins/css-has-pseudo/src/is-guarded-by-at-supports.ts @@ -25,7 +25,7 @@ export function isGuardedByAtSupportsFromAtRuleParams(atSupportsParams: string): } }); - } catch (_) { + } catch { /* ignore */ } @@ -48,7 +48,7 @@ function selectorContainsHasPseudo(selector: string): boolean { } }); - } catch (_) { + } catch { /* ignore */ } diff --git a/plugins/css-prefers-color-scheme/dist/browser-global.js.map b/plugins/css-prefers-color-scheme/dist/browser-global.js.map index 9144ca628..97d2ad775 100644 --- a/plugins/css-prefers-color-scheme/dist/browser-global.js.map +++ b/plugins/css-prefers-color-scheme/dist/browser-global.js.map @@ -1 +1 @@ -{"version":3,"file":"browser-global.js","sources":["../src/browser.js","../src/browser-global.js"],"sourcesContent":["/* global document,window */\nconst PREFERS_COLOR_SCHEME_REGEX = /prefers-color-scheme:/i;\n\nconst prefersColorSchemeInit = (initialColorScheme, options) => {\n\t// OPTIONS\n\t{\n\t\tif (!options) {\n\t\t\toptions = {};\n\t\t}\n\n\t\toptions = {\n\t\t\tdebug: (!!options.debug) || false,\n\t\t};\n\t}\n\n\tconst mediaQueryString = '(prefers-color-scheme: dark)';\n\tconst mediaQueryList = ('matchMedia' in window) && window.matchMedia(mediaQueryString);\n\tconst hasNativeSupport = mediaQueryList && mediaQueryList.media === mediaQueryString;\n\tconst mediaQueryListener = () => {\n\t\tset((mediaQueryList && mediaQueryList.matches) ? 'dark' : 'light');\n\t};\n\tconst removeListener = () => {\n\t\tif (mediaQueryList) {\n\t\t\tmediaQueryList.removeListener(mediaQueryListener);\n\t\t}\n\t};\n\tconst set = (colorScheme) => {\n\t\tif (colorScheme !== 'dark' && colorScheme !== 'light') {\n\t\t\tif (hasNativeSupport) {\n\t\t\t\tcolorScheme = mediaQueryList.matches ? 'dark' : 'light';\n\t\t\t} else {\n\t\t\t\tcolorScheme = 'light';\n\t\t\t}\n\t\t}\n\n\t\tif (colorScheme !== currentColorScheme) {\n\t\t\tcurrentColorScheme = colorScheme;\n\n\t\t\tif (typeof result.onChange === 'function') {\n\t\t\t\tresult.onChange();\n\t\t\t}\n\t\t}\n\n\t\t[].forEach.call(document.styleSheets || [], styleSheet => {\n\t\t\ttry {\n\t\t\t\t// cssRules is a live list. Converting to an Array first.\n\t\t\t\tconst rules = [];\n\t\t\t\t[].forEach.call(styleSheet.cssRules || [], cssRule => {\n\t\t\t\t\trules.push(cssRule);\n\t\t\t\t});\n\n\t\t\t\trules.forEach(cssRule => {\n\t\t\t\t\tconst colorSchemeMatch = PREFERS_COLOR_SCHEME_REGEX.test(Object(cssRule.media).mediaText);\n\n\t\t\t\t\tif (colorSchemeMatch) {\n\t\t\t\t\t\tconst index = [].indexOf.call(cssRule.parentStyleSheet.cssRules, cssRule);\n\t\t\t\t\t\tcssRule.parentStyleSheet.deleteRule(index);\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// New style which supports complex media queries.\n\t\t\t\t\t\tconst colorDepthMatch = (Object(cssRule.media).mediaText || '').match(/\\( *(?:color|max-color): *(48842621|70318723) *\\)/i);\n\t\t\t\t\t\tif (colorDepthMatch && colorDepthMatch.length > 1) {\n\t\t\t\t\t\t\tif (colorScheme === 'dark' && (colorDepthMatch[1] === '48842621')) {\n\t\t\t\t\t\t\t\t// preferred is dark and rule is dark.\n\t\t\t\t\t\t\t\tcssRule.media.mediaText = cssRule.media.mediaText.replace(/\\( *color: *(?:48842621) *\\)/i, `(max-color: ${colorDepthMatch[1]})`);\n\t\t\t\t\t\t\t} else if (colorScheme === 'light' && (colorDepthMatch[1] === '70318723')) {\n\t\t\t\t\t\t\t\t// preferred is light and rule is light.\n\t\t\t\t\t\t\t\tcssRule.media.mediaText = cssRule.media.mediaText.replace(/\\( *color: *(?:70318723) *\\)/i, `(max-color: ${colorDepthMatch[1]})`);\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tcssRule.media.mediaText = cssRule.media.mediaText.replace(/\\( *max-color: *(?:48842621|70318723) *\\)/i, `(color: ${colorDepthMatch[1]})`);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t} catch (e) {\n\t\t\t\tif (options.debug) {\n\t\t\t\t\tconsole.error(e);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t};\n\tconst result = Object.defineProperty(\n\t\t{ hasNativeSupport, removeListener },\n\t\t'scheme',\n\t\t{ get: () => currentColorScheme, set },\n\t);\n\n\t// initialize the color scheme using the provided value, the system value, or light\n\tlet currentColorScheme = initialColorScheme || (mediaQueryList && mediaQueryList.matches ? 'dark' : 'light');\n\n\tset(currentColorScheme);\n\n\t// listen for system changes\n\tif (mediaQueryList) {\n\t\tif ('addEventListener' in mediaQueryList) {\n\t\t\tmediaQueryList.addEventListener('change', mediaQueryListener);\n\t\t} else {\n\t\t\tmediaQueryList.addListener(mediaQueryListener);\n\t\t}\n\t}\n\n\treturn result;\n};\n\nexport default prefersColorSchemeInit;\n","/* global self,window */\nimport { default as prefersColorSchemeInit } from './browser';\n\n(function (global) {\n\tglobal.prefersColorSchemeInit = prefersColorSchemeInit;\n}('object' === typeof window && window || 'object' === typeof self && self || {}));\n"],"names":["PREFERS_COLOR_SCHEME_REGEX","prefersColorSchemeInit","initialColorScheme","options","debug","mediaQueryString","mediaQueryList","window","matchMedia","hasNativeSupport","media","mediaQueryListener","set","matches","colorScheme","currentColorScheme","result","onChange","forEach","call","document","styleSheets","styleSheet","rules","cssRules","cssRule","push","test","Object","mediaText","index","indexOf","parentStyleSheet","deleteRule","colorDepthMatch","match","length","replace","e","console","error","defineProperty","removeListener","get","addEventListener","addListener","self"],"mappings":"YACA,IAAMA,EAA6B,yBAE7BC,EAAyB,SAAzBA,uBAA0BC,EAAoBC,GAG7CA,IACJA,EAAU,CAAA,GAGXA,EAAU,CACTC,QAAUD,EAAQC,QAAU,GAI9B,IAAMC,EAAmB,+BACnBC,EAAkB,eAAgBC,QAAWA,OAAOC,WAAWH,GAC/DI,EAAmBH,GAAkBA,EAAeI,QAAUL,EAC9DM,EAAqB,SAArBA,qBACLC,EAAKN,GAAkBA,EAAeO,QAAW,OAAS,UAOrDD,EAAM,SAANA,IAAOE,GACQ,SAAhBA,GAA0C,UAAhBA,IAE5BA,EADGL,GACWH,EAAeO,QAAU,OAEzB,SAIZC,IAAgBC,IACnBA,EAAqBD,EAEU,mBAApBE,EAAOC,UACjBD,EAAOC,YAIT,GAAGC,QAAQC,KAAKC,SAASC,aAAe,IAAI,SAAAC,GAC3C,IAEC,IAAMC,EAAQ,GACd,GAAGL,QA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src/browser.js","../src/browser-global.js"],"sourcesContent":["const PREFERS_COLOR_SCHEME_REGEX = /prefers-color-scheme:/i;\n\nconst prefersColorSchemeInit = (initialColorScheme, options) => {\n\t// OPTIONS\n\t{\n\t\tif (!options) {\n\t\t\toptions = {};\n\t\t}\n\n\t\toptions = {\n\t\t\tdebug: (!!options.debug) || false,\n\t\t};\n\t}\n\n\tconst mediaQueryString = '(prefers-color-scheme: dark)';\n\tconst mediaQueryList = ('matchMedia' in window) && window.matchMedia(mediaQueryString);\n\tconst hasNativeSupport = mediaQueryList && mediaQueryList.media === mediaQueryString;\n\tconst mediaQueryListener = () => {\n\t\tset((mediaQueryList && mediaQueryList.matches) ? 'dark' : 'light');\n\t};\n\tconst removeListener = () => {\n\t\tif (mediaQueryList) {\n\t\t\tmediaQueryList.removeListener(mediaQueryListener);\n\t\t}\n\t};\n\tconst set = (colorScheme) => {\n\t\tif (colorScheme !== 'dark' && colorScheme !== 'light') {\n\t\t\tif (hasNativeSupport) {\n\t\t\t\tcolorScheme = mediaQueryList.matches ? 'dark' : 'light';\n\t\t\t} else {\n\t\t\t\tcolorScheme = 'light';\n\t\t\t}\n\t\t}\n\n\t\tif (colorScheme !== currentColorScheme) {\n\t\t\tcurrentColorScheme = colorScheme;\n\n\t\t\tif (typeof result.onChange === 'function') {\n\t\t\t\tresult.onChange();\n\t\t\t}\n\t\t}\n\n\t\t[].forEach.call(document.styleSheets || [], styleSheet => {\n\t\t\ttry {\n\t\t\t\t// cssRules is a live list. Converting to an Array first.\n\t\t\t\tconst rules = [];\n\t\t\t\t[].forEach.call(styleSheet.cssRules || [], cssRule => {\n\t\t\t\t\trules.push(cssRule);\n\t\t\t\t});\n\n\t\t\t\trules.forEach(cssRule => {\n\t\t\t\t\tconst colorSchemeMatch = PREFERS_COLOR_SCHEME_REGEX.test(Object(cssRule.media).mediaText);\n\n\t\t\t\t\tif (colorSchemeMatch) {\n\t\t\t\t\t\tconst index = [].indexOf.call(cssRule.parentStyleSheet.cssRules, cssRule);\n\t\t\t\t\t\tcssRule.parentStyleSheet.deleteRule(index);\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// New style which supports complex media queries.\n\t\t\t\t\t\tconst colorDepthMatch = (Object(cssRule.media).mediaText || '').match(/\\( *(?:color|max-color): *(48842621|70318723) *\\)/i);\n\t\t\t\t\t\tif (colorDepthMatch && colorDepthMatch.length > 1) {\n\t\t\t\t\t\t\tif (colorScheme === 'dark' && (colorDepthMatch[1] === '48842621')) {\n\t\t\t\t\t\t\t\t// preferred is dark and rule is dark.\n\t\t\t\t\t\t\t\tcssRule.media.mediaText = cssRule.media.mediaText.replace(/\\( *color: *(?:48842621) *\\)/i, `(max-color: ${colorDepthMatch[1]})`);\n\t\t\t\t\t\t\t} else if (colorScheme === 'light' && (colorDepthMatch[1] === '70318723')) {\n\t\t\t\t\t\t\t\t// preferred is light and rule is light.\n\t\t\t\t\t\t\t\tcssRule.media.mediaText = cssRule.media.mediaText.replace(/\\( *color: *(?:70318723) *\\)/i, `(max-color: ${colorDepthMatch[1]})`);\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tcssRule.media.mediaText = cssRule.media.mediaText.replace(/\\( *max-color: *(?:48842621|70318723) *\\)/i, `(color: ${colorDepthMatch[1]})`);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t} catch (e) {\n\t\t\t\tif (options.debug) {\n\t\t\t\t\tconsole.error(e);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t};\n\tconst result = Object.defineProperty(\n\t\t{ hasNativeSupport, removeListener },\n\t\t'scheme',\n\t\t{ get: () => currentColorScheme, set },\n\t);\n\n\t// initialize the color scheme using the provided value, the system value, or light\n\tlet currentColorScheme = initialColorScheme || (mediaQueryList && mediaQueryList.matches ? 'dark' : 'light');\n\n\tset(currentColorScheme);\n\n\t// listen for system changes\n\tif (mediaQueryList) {\n\t\tif ('addEventListener' in mediaQueryList) {\n\t\t\tmediaQueryList.addEventListener('change', mediaQueryListener);\n\t\t} else {\n\t\t\tmediaQueryList.addListener(mediaQueryListener);\n\t\t}\n\t}\n\n\treturn result;\n};\n\nexport default prefersColorSchemeInit;\n","import { default as prefersColorSchemeInit } from './browser';\n\n(function (global) {\n\tglobal.prefersColorSchemeInit = prefersColorSchemeInit;\n}('object' === typeof window && window || 'object' === typeof self && self || {}));\n"],"names":["PREFERS_COLOR_SCHEME_REGEX","prefersColorSchemeInit","initialColorScheme","options","debug","mediaQueryString","mediaQueryList","window","matchMedia","hasNativeSupport","media","mediaQueryListener","set","matches","colorScheme","currentColorScheme","result","onChange","forEach","call","document","styleSheets","styleSheet","rules","cssRules","cssRule","push","test","Object","mediaText","index","indexOf","parentStyleSheet","deleteRule","colorDepthMatch","match","length","replace","e","console","error","defineProperty","removeListener","get","addEventListener","addListener","self"],"mappings":"YAAA,IAAMA,EAA6B,yBAE7BC,EAAyB,SAAzBA,uBAA0BC,EAAoBC,GAG7CA,IACJA,EAAU,CAAA,GAGXA,EAAU,CACTC,QAAUD,EAAQC,QAAU,GAI9B,IAAMC,EAAmB,+BACnBC,EAAkB,eAAgBC,QAAWA,OAAOC,WAAWH,GAC/DI,EAAmBH,GAAkBA,EAAeI,QAAUL,EAC9DM,EAAqB,SAArBA,qBACLC,EAAKN,GAAkBA,EAAeO,QAAW,OAAS,UAOrDD,EAAM,SAANA,IAAOE,GACQ,SAAhBA,GAA0C,UAAhBA,IAE5BA,EADGL,GACWH,EAAeO,QAAU,OAEzB,SAIZC,IAAgBC,IACnBA,EAAqBD,EAEU,mBAApBE,EAAOC,UACjBD,EAAOC,YAIT,GAAGC,QAAQC,KAAKC,SAASC,aAAe,IAAI,SAAAC,GAC3C,IAEC,IAAMC,EAAQ,GACd,GAAGL,QAAQC,KAAKG,EAAWE,UAAY,IAAI,SAAAC,GAC1CF,EAAMG,KAAKD,EACZ,IAEAF,EAAML,SAAQ,SAAAO,GAGb,GAFyBzB,EAA2B2B,KAAKC,OAAOH,EAAQf,OAAOmB,WAEzD,CACrB,IAAMC,EAAQ,GAAGC,QAAQZ,KAAKM,EAAQO,iBAAiBR,SAAUC,GACjEA,EAAQO,iBAAiBC,WAAWH,EACrC,KAAO,CAEN,IAAMI,GAAmBN,OAAOH,EAAQf,OAAOmB,WAAa,IAAIM,MAAM,sDAClED,GAAmBA,EAAgBE,OAAS,IAC3B,SAAhBtB,GAAkD,aAAvBoB,EAAgB,GAE9CT,EAAQf,MAAMmB,UAAYJ,EAAQf,MAAMmB,UAAUQ,QAAQ,gCAAgDH,eAAAA,EAAgB,QAChG,UAAhBpB,GAAmD,aAAvBoB,EAAgB,GAEtDT,EAAQf,MAAMmB,UAAYJ,EAAQf,MAAMmB,UAAUQ,QAAQ,gCAAgDH,eAAAA,EAAgB,QAE1HT,EAAQf,MAAMmB,UAAYJ,EAAQf,MAAMmB,UAAUQ,QAAQ,6CAAyDH,WAAAA,EAAgB,QAGtI,CACD,GACA,CAAC,MAAOI,GACJnC,EAAQC,OACXmC,QAAQC,MAAMF,EAEhB,CACD,KAEKtB,EAASY,OAAOa,eACrB,CAAEhC,iBAAAA,EAAkBiC,eA5DE,SAAjBA,iBACDpC,GACHA,EAAeoC,eAAe/B,KA2D/B,SACA,CAAEgC,IAAK,SAAAA,MAAA,OAAM5B,CAAkB,EAAEH,IAAAA,IAI9BG,EAAqBb,IAAuBI,GAAkBA,EAAeO,QAAU,OAAS,SAapG,OAXAD,EAAIG,GAGAT,IACC,qBAAsBA,EACzBA,EAAesC,iBAAiB,SAAUjC,GAE1CL,EAAeuC,YAAYlC,IAItBK,CACR,GChGE,iBAAoBT,QAAUA,QAAU,iBAAoBuC,MAAQA,MAAQ,IADtE7C,uBAAyBA"} \ No newline at end of file diff --git a/plugins/css-prefers-color-scheme/dist/browser.cjs.map b/plugins/css-prefers-color-scheme/dist/browser.cjs.map index 10621d40a..5473be581 100644 --- a/plugins/css-prefers-color-scheme/dist/browser.cjs.map +++ b/plugins/css-prefers-color-scheme/dist/browser.cjs.map @@ -1 +1 @@ -{"version":3,"file":"browser.cjs","sources":["../src/browser.js"],"sourcesContent":["/* global document,window */\nconst PREFERS_COLOR_SCHEME_REGEX = /prefers-color-scheme:/i;\n\nconst prefersColorSchemeInit = (initialColorScheme, options) => {\n\t// OPTIONS\n\t{\n\t\tif (!options) {\n\t\t\toptions = {};\n\t\t}\n\n\t\toptions = {\n\t\t\tdebug: (!!options.debug) || false,\n\t\t};\n\t}\n\n\tconst mediaQueryString = '(prefers-color-scheme: dark)';\n\tconst mediaQueryList = ('matchMedia' in window) && window.matchMedia(mediaQueryString);\n\tconst hasNativeSupport = mediaQueryList && mediaQueryList.media === mediaQueryString;\n\tconst mediaQueryListener = () => {\n\t\tset((mediaQueryList && mediaQueryList.matches) ? 'dark' : 'light');\n\t};\n\tconst removeListener = () => {\n\t\tif (mediaQueryList) {\n\t\t\tmediaQueryList.removeListener(mediaQueryListener);\n\t\t}\n\t};\n\tconst set = (colorScheme) => {\n\t\tif (colorScheme !== 'dark' && colorScheme !== 'light') {\n\t\t\tif (hasNativeSupport) {\n\t\t\t\tcolorScheme = mediaQueryList.matches ? 'dark' : 'light';\n\t\t\t} else {\n\t\t\t\tcolorScheme = 'light';\n\t\t\t}\n\t\t}\n\n\t\tif (colorScheme !== currentColorScheme) {\n\t\t\tcurrentColorScheme = colorScheme;\n\n\t\t\tif (typeof result.onChange === 'function') {\n\t\t\t\tresult.onChange();\n\t\t\t}\n\t\t}\n\n\t\t[].forEach.call(document.styleSheets || [], styleSheet => {\n\t\t\ttry {\n\t\t\t\t// cssRules is a live list. Converting to an Array first.\n\t\t\t\tconst rules = [];\n\t\t\t\t[].forEach.call(styleSheet.cssRules || [], cssRule => {\n\t\t\t\t\trules.push(cssRule);\n\t\t\t\t});\n\n\t\t\t\trules.forEach(cssRule => {\n\t\t\t\t\tconst colorSchemeMatch = PREFERS_COLOR_SCHEME_REGEX.test(Object(cssRule.media).mediaText);\n\n\t\t\t\t\tif (colorSchemeMatch) {\n\t\t\t\t\t\tconst index = [].indexOf.call(cssRule.parentStyleSheet.cssRules, cssRule);\n\t\t\t\t\t\tcssRule.parentStyleSheet.deleteRule(index);\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// New style which supports complex media queries.\n\t\t\t\t\t\tconst colorDepthMatch = (Object(cssRule.media).mediaText || '').match(/\\( *(?:color|max-color): *(48842621|70318723) *\\)/i);\n\t\t\t\t\t\tif (colorDepthMatch && colorDepthMatch.length > 1) {\n\t\t\t\t\t\t\tif (colorScheme === 'dark' && (colorDepthMatch[1] === '48842621')) {\n\t\t\t\t\t\t\t\t// preferred is dark and rule is dark.\n\t\t\t\t\t\t\t\tcssRule.media.mediaText = cssRule.media.mediaText.replace(/\\( *color: *(?:48842621) *\\)/i, `(max-color: ${colorDepthMatch[1]})`);\n\t\t\t\t\t\t\t} else if (colorScheme === 'light' && (colorDepthMatch[1] === '70318723')) {\n\t\t\t\t\t\t\t\t// preferred is light and rule is light.\n\t\t\t\t\t\t\t\tcssRule.media.mediaText = cssRule.media.mediaText.replace(/\\( *color: *(?:70318723) *\\)/i, `(max-color: ${colorDepthMatch[1]})`);\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tcssRule.media.mediaText = cssRule.media.mediaText.replace(/\\( *max-color: *(?:48842621|70318723) *\\)/i, `(color: ${colorDepthMatch[1]})`);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t} catch (e) {\n\t\t\t\tif (options.debug) {\n\t\t\t\t\tconsole.error(e);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t};\n\tconst result = Object.defineProperty(\n\t\t{ hasNativeSupport, removeListener },\n\t\t'scheme',\n\t\t{ get: () => currentColorScheme, set },\n\t);\n\n\t// initialize the color scheme using the provided value, the system value, or light\n\tlet currentColorScheme = initialColorScheme || (mediaQueryList && mediaQueryList.matches ? 'dark' : 'light');\n\n\tset(currentColorScheme);\n\n\t// listen for system changes\n\tif (mediaQueryList) {\n\t\tif ('addEventListener' in mediaQueryList) {\n\t\t\tmediaQueryList.addEventListener('change', mediaQueryListener);\n\t\t} else {\n\t\t\tmediaQueryList.addListener(mediaQueryListener);\n\t\t}\n\t}\n\n\treturn result;\n};\n\nexport default prefersColorSchemeInit;\n"],"names":["PREFERS_COLOR_SCHEME_REGEX","prefersColorSchemeInit","initialColorScheme","options","debug","mediaQueryString","mediaQueryList","window","matchMedia","hasNativeSupport","media","mediaQueryListener","set","matches","colorScheme","currentColorScheme","result","onChange","forEach","call","document","styleSheets","styleSheet","rules","cssRules","cssRule","push","test","Object","mediaText","index","indexOf","parentStyleSheet","deleteRule","colorDepthMatch","match","length","replace","e","console","error","defineProperty","removeListener","get","addEventListener","addListener"],"mappings":"AACA,IAAMA,EAA6B,wCAEJ,SAAzBC,uBAA0BC,EAAoBC,GAG7CA,IACJA,EAAU,CAAA,GAGXA,EAAU,CACTC,QAAUD,EAAQC,QAAU,GAI9B,IAAMC,EAAmB,+BACnBC,EAAkB,eAAgBC,QAAWA,OAAOC,WAAWH,GAC/DI,EAAmBH,GAAkBA,EAAeI,QAAUL,EAC9DM,EAAqB,SAArBA,qBACLC,EAAKN,GAAkBA,EAAeO,QAAW,OAAS,UAOrDD,EAAM,SAANA,IAAOE,GACQ,SAAhBA,GAA0C,UAAhBA,IAE5BA,EADGL,GACWH,EAAeO,QAAU,OAEzB,SAIZC,IAAgBC,IACnBA,EAAqBD,EAEU,mBAApBE,EAAOC,UACjBD,EAAOC,YAIT,GAAGC,QAAQC,KAAKC,SAASC,aAAe,IAAI,SAAAC,GAC3C,IAEC,IAAMC,EAAQ,GACd,GAAGL,QAAQC,KAAKG,EAAWE,UAAY,IAAI,SAAAC,GAC1CF,EAAMG,KAAKD,EACZ,IAEAF,EAAML,SAAQ,SAAAO,GAGb,GAFyBzB,EAA2B2B,KAAKC,OAAOH,EAAQf,OAAOmB,WAEzD,CACrB,IAAMC,EAAQ,GAAGC,QAAQZ,KAAKM,EAAQO,iBAAiBR,SAAUC,GACjEA,EAAQO,iBAAiBC,WAAWH,EACrC,KAAO,CAEN,IAAMI,GAAmBN,OAAOH,EAAQf,OAAOmB,WAAa,IAAIM,MAAM,sDAClED,GAAmBA,EAAgBE,OAAS,IAC3B,SAAhBtB,GAAkD,aAAvBoB,EAAgB,GAE9CT,EAAQf,MAAMmB,UAAYJ,EAAQf,MAAMmB,UAAUQ,QAAQ,gCAAgDH,eAAAA,EAAgB,QAChG,UAAhBpB,GAAmD,aAAvBoB,EAAgB,GAEtDT,EAAQf,MAAMmB,UAAYJ,EAAQf,MAAMmB,UAAUQ,QAAQ,gCAAgDH,eAAAA,EAAgB,QAE1HT,EAAQf,MAAMmB,UAAYJ,EAAQf,MAAMmB,UAAUQ,QAAQ,6CAAyDH,WAAAA,EAAgB,QAGtI,CACD,GACA,CAAC,MAAOI,GACJnC,EAAQC,OACXmC,QAAQC,MAAMF,EAEhB,CACD,KAEKtB,EAASY,OAAOa,eACrB,CAAEhC,iBAAAA,EAAkBiC,eA5DE,SAAjBA,iBACDpC,GACHA,EAAeoC,eAAe/B,KA2D/B,SACA,CAAEgC,IAAK,SAAAA,MAAA,OAAM5B,CAAkB,EAAEH,IAAAA,IAI9BG,EAAqBb,IAAuBI,GAAkBA,EAAeO,QAAU,OAAS,SAapG,OAXAD,EAAIG,GAGAT,IACC,qBAAsBA,EACzBA,EAAesC,iBAAiB,SAAUjC,GAE1CL,EAAeuC,YAAYlC,IAItBK,CACR"} \ No newline at end of file +{"version":3,"file":"browser.cjs","sources":["../src/browser.js"],"sourcesContent":["const PREFERS_COLOR_SCHEME_REGEX = /prefers-color-scheme:/i;\n\nconst prefersColorSchemeInit = (initialColorScheme, options) => {\n\t// OPTIONS\n\t{\n\t\tif (!options) {\n\t\t\toptions = {};\n\t\t}\n\n\t\toptions = {\n\t\t\tdebug: (!!options.debug) || false,\n\t\t};\n\t}\n\n\tconst mediaQueryString = '(prefers-color-scheme: dark)';\n\tconst mediaQueryList = ('matchMedia' in window) && window.matchMedia(mediaQueryString);\n\tconst hasNativeSupport = mediaQueryList && mediaQueryList.media === mediaQueryString;\n\tconst mediaQueryListener = () => {\n\t\tset((mediaQueryList && mediaQueryList.matches) ? 'dark' : 'light');\n\t};\n\tconst removeListener = () => {\n\t\tif (mediaQueryList) {\n\t\t\tmediaQueryList.removeListener(mediaQueryListener);\n\t\t}\n\t};\n\tconst set = (colorScheme) => {\n\t\tif (colorScheme !== 'dark' && colorScheme !== 'light') {\n\t\t\tif (hasNativeSupport) {\n\t\t\t\tcolorScheme = mediaQueryList.matches ? 'dark' : 'light';\n\t\t\t} else {\n\t\t\t\tcolorScheme = 'light';\n\t\t\t}\n\t\t}\n\n\t\tif (colorScheme !== currentColorScheme) {\n\t\t\tcurrentColorScheme = colorScheme;\n\n\t\t\tif (typeof result.onChange === 'function') {\n\t\t\t\tresult.onChange();\n\t\t\t}\n\t\t}\n\n\t\t[].forEach.call(document.styleSheets || [], styleSheet => {\n\t\t\ttry {\n\t\t\t\t// cssRules is a live list. Converting to an Array first.\n\t\t\t\tconst rules = [];\n\t\t\t\t[].forEach.call(styleSheet.cssRules || [], cssRule => {\n\t\t\t\t\trules.push(cssRule);\n\t\t\t\t});\n\n\t\t\t\trules.forEach(cssRule => {\n\t\t\t\t\tconst colorSchemeMatch = PREFERS_COLOR_SCHEME_REGEX.test(Object(cssRule.media).mediaText);\n\n\t\t\t\t\tif (colorSchemeMatch) {\n\t\t\t\t\t\tconst index = [].indexOf.call(cssRule.parentStyleSheet.cssRules, cssRule);\n\t\t\t\t\t\tcssRule.parentStyleSheet.deleteRule(index);\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// New style which supports complex media queries.\n\t\t\t\t\t\tconst colorDepthMatch = (Object(cssRule.media).mediaText || '').match(/\\( *(?:color|max-color): *(48842621|70318723) *\\)/i);\n\t\t\t\t\t\tif (colorDepthMatch && colorDepthMatch.length > 1) {\n\t\t\t\t\t\t\tif (colorScheme === 'dark' && (colorDepthMatch[1] === '48842621')) {\n\t\t\t\t\t\t\t\t// preferred is dark and rule is dark.\n\t\t\t\t\t\t\t\tcssRule.media.mediaText = cssRule.media.mediaText.replace(/\\( *color: *(?:48842621) *\\)/i, `(max-color: ${colorDepthMatch[1]})`);\n\t\t\t\t\t\t\t} else if (colorScheme === 'light' && (colorDepthMatch[1] === '70318723')) {\n\t\t\t\t\t\t\t\t// preferred is light and rule is light.\n\t\t\t\t\t\t\t\tcssRule.media.mediaText = cssRule.media.mediaText.replace(/\\( *color: *(?:70318723) *\\)/i, `(max-color: ${colorDepthMatch[1]})`);\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tcssRule.media.mediaText = cssRule.media.mediaText.replace(/\\( *max-color: *(?:48842621|70318723) *\\)/i, `(color: ${colorDepthMatch[1]})`);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t} catch (e) {\n\t\t\t\tif (options.debug) {\n\t\t\t\t\tconsole.error(e);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t};\n\tconst result = Object.defineProperty(\n\t\t{ hasNativeSupport, removeListener },\n\t\t'scheme',\n\t\t{ get: () => currentColorScheme, set },\n\t);\n\n\t// initialize the color scheme using the provided value, the system value, or light\n\tlet currentColorScheme = initialColorScheme || (mediaQueryList && mediaQueryList.matches ? 'dark' : 'light');\n\n\tset(currentColorScheme);\n\n\t// listen for system changes\n\tif (mediaQueryList) {\n\t\tif ('addEventListener' in mediaQueryList) {\n\t\t\tmediaQueryList.addEventListener('change', mediaQueryListener);\n\t\t} else {\n\t\t\tmediaQueryList.addListener(mediaQueryListener);\n\t\t}\n\t}\n\n\treturn result;\n};\n\nexport default prefersColorSchemeInit;\n"],"names":["PREFERS_COLOR_SCHEME_REGEX","prefersColorSchemeInit","initialColorScheme","options","debug","mediaQueryString","mediaQueryList","window","matchMedia","hasNativeSupport","media","mediaQueryListener","set","matches","colorScheme","currentColorScheme","result","onChange","forEach","call","document","styleSheets","styleSheet","rules","cssRules","cssRule","push","test","Object","mediaText","index","indexOf","parentStyleSheet","deleteRule","colorDepthMatch","match","length","replace","e","console","error","defineProperty","removeListener","get","addEventListener","addListener"],"mappings":"AAAA,IAAMA,EAA6B,wCAEJ,SAAzBC,uBAA0BC,EAAoBC,GAG7CA,IACJA,EAAU,CAAA,GAGXA,EAAU,CACTC,QAAUD,EAAQC,QAAU,GAI9B,IAAMC,EAAmB,+BACnBC,EAAkB,eAAgBC,QAAWA,OAAOC,WAAWH,GAC/DI,EAAmBH,GAAkBA,EAAeI,QAAUL,EAC9DM,EAAqB,SAArBA,qBACLC,EAAKN,GAAkBA,EAAeO,QAAW,OAAS,UAOrDD,EAAM,SAANA,IAAOE,GACQ,SAAhBA,GAA0C,UAAhBA,IAE5BA,EADGL,GACWH,EAAeO,QAAU,OAEzB,SAIZC,IAAgBC,IACnBA,EAAqBD,EAEU,mBAApBE,EAAOC,UACjBD,EAAOC,YAIT,GAAGC,QAAQC,KAAKC,SAASC,aAAe,IAAI,SAAAC,GAC3C,IAEC,IAAMC,EAAQ,GACd,GAAGL,QAAQC,KAAKG,EAAWE,UAAY,IAAI,SAAAC,GAC1CF,EAAMG,KAAKD,EACZ,IAEAF,EAAML,SAAQ,SAAAO,GAGb,GAFyBzB,EAA2B2B,KAAKC,OAAOH,EAAQf,OAAOmB,WAEzD,CACrB,IAAMC,EAAQ,GAAGC,QAAQZ,KAAKM,EAAQO,iBAAiBR,SAAUC,GACjEA,EAAQO,iBAAiBC,WAAWH,EACrC,KAAO,CAEN,IAAMI,GAAmBN,OAAOH,EAAQf,OAAOmB,WAAa,IAAIM,MAAM,sDAClED,GAAmBA,EAAgBE,OAAS,IAC3B,SAAhBtB,GAAkD,aAAvBoB,EAAgB,GAE9CT,EAAQf,MAAMmB,UAAYJ,EAAQf,MAAMmB,UAAUQ,QAAQ,gCAAgDH,eAAAA,EAAgB,QAChG,UAAhBpB,GAAmD,aAAvBoB,EAAgB,GAEtDT,EAAQf,MAAMmB,UAAYJ,EAAQf,MAAMmB,UAAUQ,QAAQ,gCAAgDH,eAAAA,EAAgB,QAE1HT,EAAQf,MAAMmB,UAAYJ,EAAQf,MAAMmB,UAAUQ,QAAQ,6CAAyDH,WAAAA,EAAgB,QAGtI,CACD,GACA,CAAC,MAAOI,GACJnC,EAAQC,OACXmC,QAAQC,MAAMF,EAEhB,CACD,KAEKtB,EAASY,OAAOa,eACrB,CAAEhC,iBAAAA,EAAkBiC,eA5DE,SAAjBA,iBACDpC,GACHA,EAAeoC,eAAe/B,KA2D/B,SACA,CAAEgC,IAAK,SAAAA,MAAA,OAAM5B,CAAkB,EAAEH,IAAAA,IAI9BG,EAAqBb,IAAuBI,GAAkBA,EAAeO,QAAU,OAAS,SAapG,OAXAD,EAAIG,GAGAT,IACC,qBAAsBA,EACzBA,EAAesC,iBAAiB,SAAUjC,GAE1CL,EAAeuC,YAAYlC,IAItBK,CACR"} \ No newline at end of file diff --git a/plugins/css-prefers-color-scheme/dist/browser.mjs.map b/plugins/css-prefers-color-scheme/dist/browser.mjs.map index f6448d377..e8206c159 100644 --- a/plugins/css-prefers-color-scheme/dist/browser.mjs.map +++ b/plugins/css-prefers-color-scheme/dist/browser.mjs.map @@ -1 +1 @@ -{"version":3,"file":"browser.mjs","sources":["../src/browser.js"],"sourcesContent":["/* global document,window */\nconst PREFERS_COLOR_SCHEME_REGEX = /prefers-color-scheme:/i;\n\nconst prefersColorSchemeInit = (initialColorScheme, options) => {\n\t// OPTIONS\n\t{\n\t\tif (!options) {\n\t\t\toptions = {};\n\t\t}\n\n\t\toptions = {\n\t\t\tdebug: (!!options.debug) || false,\n\t\t};\n\t}\n\n\tconst mediaQueryString = '(prefers-color-scheme: dark)';\n\tconst mediaQueryList = ('matchMedia' in window) && window.matchMedia(mediaQueryString);\n\tconst hasNativeSupport = mediaQueryList && mediaQueryList.media === mediaQueryString;\n\tconst mediaQueryListener = () => {\n\t\tset((mediaQueryList && mediaQueryList.matches) ? 'dark' : 'light');\n\t};\n\tconst removeListener = () => {\n\t\tif (mediaQueryList) {\n\t\t\tmediaQueryList.removeListener(mediaQueryListener);\n\t\t}\n\t};\n\tconst set = (colorScheme) => {\n\t\tif (colorScheme !== 'dark' && colorScheme !== 'light') {\n\t\t\tif (hasNativeSupport) {\n\t\t\t\tcolorScheme = mediaQueryList.matches ? 'dark' : 'light';\n\t\t\t} else {\n\t\t\t\tcolorScheme = 'light';\n\t\t\t}\n\t\t}\n\n\t\tif (colorScheme !== currentColorScheme) {\n\t\t\tcurrentColorScheme = colorScheme;\n\n\t\t\tif (typeof result.onChange === 'function') {\n\t\t\t\tresult.onChange();\n\t\t\t}\n\t\t}\n\n\t\t[].forEach.call(document.styleSheets || [], styleSheet => {\n\t\t\ttry {\n\t\t\t\t// cssRules is a live list. Converting to an Array first.\n\t\t\t\tconst rules = [];\n\t\t\t\t[].forEach.call(styleSheet.cssRules || [], cssRule => {\n\t\t\t\t\trules.push(cssRule);\n\t\t\t\t});\n\n\t\t\t\trules.forEach(cssRule => {\n\t\t\t\t\tconst colorSchemeMatch = PREFERS_COLOR_SCHEME_REGEX.test(Object(cssRule.media).mediaText);\n\n\t\t\t\t\tif (colorSchemeMatch) {\n\t\t\t\t\t\tconst index = [].indexOf.call(cssRule.parentStyleSheet.cssRules, cssRule);\n\t\t\t\t\t\tcssRule.parentStyleSheet.deleteRule(index);\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// New style which supports complex media queries.\n\t\t\t\t\t\tconst colorDepthMatch = (Object(cssRule.media).mediaText || '').match(/\\( *(?:color|max-color): *(48842621|70318723) *\\)/i);\n\t\t\t\t\t\tif (colorDepthMatch && colorDepthMatch.length > 1) {\n\t\t\t\t\t\t\tif (colorScheme === 'dark' && (colorDepthMatch[1] === '48842621')) {\n\t\t\t\t\t\t\t\t// preferred is dark and rule is dark.\n\t\t\t\t\t\t\t\tcssRule.media.mediaText = cssRule.media.mediaText.replace(/\\( *color: *(?:48842621) *\\)/i, `(max-color: ${colorDepthMatch[1]})`);\n\t\t\t\t\t\t\t} else if (colorScheme === 'light' && (colorDepthMatch[1] === '70318723')) {\n\t\t\t\t\t\t\t\t// preferred is light and rule is light.\n\t\t\t\t\t\t\t\tcssRule.media.mediaText = cssRule.media.mediaText.replace(/\\( *color: *(?:70318723) *\\)/i, `(max-color: ${colorDepthMatch[1]})`);\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tcssRule.media.mediaText = cssRule.media.mediaText.replace(/\\( *max-color: *(?:48842621|70318723) *\\)/i, `(color: ${colorDepthMatch[1]})`);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t} catch (e) {\n\t\t\t\tif (options.debug) {\n\t\t\t\t\tconsole.error(e);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t};\n\tconst result = Object.defineProperty(\n\t\t{ hasNativeSupport, removeListener },\n\t\t'scheme',\n\t\t{ get: () => currentColorScheme, set },\n\t);\n\n\t// initialize the color scheme using the provided value, the system value, or light\n\tlet currentColorScheme = initialColorScheme || (mediaQueryList && mediaQueryList.matches ? 'dark' : 'light');\n\n\tset(currentColorScheme);\n\n\t// listen for system changes\n\tif (mediaQueryList) {\n\t\tif ('addEventListener' in mediaQueryList) {\n\t\t\tmediaQueryList.addEventListener('change', mediaQueryListener);\n\t\t} else {\n\t\t\tmediaQueryList.addListener(mediaQueryListener);\n\t\t}\n\t}\n\n\treturn result;\n};\n\nexport default prefersColorSchemeInit;\n"],"names":["PREFERS_COLOR_SCHEME_REGEX","prefersColorSchemeInit","initialColorScheme","options","debug","mediaQueryString","mediaQueryList","window","matchMedia","hasNativeSupport","media","mediaQueryListener","set","matches","colorScheme","currentColorScheme","result","onChange","forEach","call","document","styleSheets","styleSheet","rules","cssRules","cssRule","push","test","Object","mediaText","index","indexOf","parentStyleSheet","deleteRule","colorDepthMatch","match","length","replace","e","console","error","defineProperty","removeListener","get","addEventListener","addListener"],"mappings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AAUQ,QAAQ,6CAAyDH,WAAAA,EAAgB,QAGtI,CACD,GACA,CAAC,MAAOI,GACJnC,EAAQC,OACXmC,QAAQC,MAAMF,EAEhB,CACD,KAEKtB,EAASY,OAAOa,eACrB,CAAEhC,iBAAAA,EAAkBiC,eA5DE,SAAjBA,iBACDpC,GACHA,EAAeoC,eAAe/B,KA2D/B,SACA,CAAEgC,IAAK,SAAAA,MAAA,OAAM5B,CAAkB,EAAEH,IAAAA,IAI9BG,EAAqBb,IAAuBI,GAAkBA,EAAeO,QAAU,OAAS,SAapG,OAXAD,EAAIG,GAGAT,IACC,qBAAsBA,EACzBA,EAAesC,iBAAiB,SAAUjC,GAE1CL,EAAeuC,YAAYlC,IAItBK,CACR"} \ No newline at end of file +{"version":3,"file":"browser.mjs","sources":["../src/browser.js"],"sourcesContent":["const PREFERS_COLOR_SCHEME_REGEX = /prefers-color-scheme:/i;\n\nconst prefersColorSchemeInit = (initialColorScheme, options) => {\n\t// OPTIONS\n\t{\n\t\tif (!options) {\n\t\t\toptions = {};\n\t\t}\n\n\t\toptions = {\n\t\t\tdebug: (!!options.debug) || false,\n\t\t};\n\t}\n\n\tconst mediaQueryString = '(prefers-color-scheme: dark)';\n\tconst mediaQueryList = ('matchMedia' in window) && window.matchMedia(mediaQueryString);\n\tconst hasNativeSupport = mediaQueryList && mediaQueryList.media === mediaQueryString;\n\tconst mediaQueryListener = () => {\n\t\tset((mediaQueryList && mediaQueryList.matches) ? 'dark' : 'light');\n\t};\n\tconst removeListener = () => {\n\t\tif (mediaQueryList) {\n\t\t\tmediaQueryList.removeListener(mediaQueryListener);\n\t\t}\n\t};\n\tconst set = (colorScheme) => {\n\t\tif (colorScheme !== 'dark' && colorScheme !== 'light') {\n\t\t\tif (hasNativeSupport) {\n\t\t\t\tcolorScheme = mediaQueryList.matches ? 'dark' : 'light';\n\t\t\t} else {\n\t\t\t\tcolorScheme = 'light';\n\t\t\t}\n\t\t}\n\n\t\tif (colorScheme !== currentColorScheme) {\n\t\t\tcurrentColorScheme = colorScheme;\n\n\t\t\tif (typeof result.onChange === 'function') {\n\t\t\t\tresult.onChange();\n\t\t\t}\n\t\t}\n\n\t\t[].forEach.call(document.styleSheets || [], styleSheet => {\n\t\t\ttry {\n\t\t\t\t// cssRules is a live list. Converting to an Array first.\n\t\t\t\tconst rules = [];\n\t\t\t\t[].forEach.call(styleSheet.cssRules || [], cssRule => {\n\t\t\t\t\trules.push(cssRule);\n\t\t\t\t});\n\n\t\t\t\trules.forEach(cssRule => {\n\t\t\t\t\tconst colorSchemeMatch = PREFERS_COLOR_SCHEME_REGEX.test(Object(cssRule.media).mediaText);\n\n\t\t\t\t\tif (colorSchemeMatch) {\n\t\t\t\t\t\tconst index = [].indexOf.call(cssRule.parentStyleSheet.cssRules, cssRule);\n\t\t\t\t\t\tcssRule.parentStyleSheet.deleteRule(index);\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// New style which supports complex media queries.\n\t\t\t\t\t\tconst colorDepthMatch = (Object(cssRule.media).mediaText || '').match(/\\( *(?:color|max-color): *(48842621|70318723) *\\)/i);\n\t\t\t\t\t\tif (colorDepthMatch && colorDepthMatch.length > 1) {\n\t\t\t\t\t\t\tif (colorScheme === 'dark' && (colorDepthMatch[1] === '48842621')) {\n\t\t\t\t\t\t\t\t// preferred is dark and rule is dark.\n\t\t\t\t\t\t\t\tcssRule.media.mediaText = cssRule.media.mediaText.replace(/\\( *color: *(?:48842621) *\\)/i, `(max-color: ${colorDepthMatch[1]})`);\n\t\t\t\t\t\t\t} else if (colorScheme === 'light' && (colorDepthMatch[1] === '70318723')) {\n\t\t\t\t\t\t\t\t// preferred is light and rule is light.\n\t\t\t\t\t\t\t\tcssRule.media.mediaText = cssRule.media.mediaText.replace(/\\( *color: *(?:70318723) *\\)/i, `(max-color: ${colorDepthMatch[1]})`);\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tcssRule.media.mediaText = cssRule.media.mediaText.replace(/\\( *max-color: *(?:48842621|70318723) *\\)/i, `(color: ${colorDepthMatch[1]})`);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t} catch (e) {\n\t\t\t\tif (options.debug) {\n\t\t\t\t\tconsole.error(e);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t};\n\tconst result = Object.defineProperty(\n\t\t{ hasNativeSupport, removeListener },\n\t\t'scheme',\n\t\t{ get: () => currentColorScheme, set },\n\t);\n\n\t// initialize the color scheme using the provided value, the system value, or light\n\tlet currentColorScheme = initialColorScheme || (mediaQueryList && mediaQueryList.matches ? 'dark' : 'light');\n\n\tset(currentColorScheme);\n\n\t// listen for system changes\n\tif (mediaQueryList) {\n\t\tif ('addEventListener' in mediaQueryList) {\n\t\t\tmediaQueryList.addEventListener('change', mediaQueryListener);\n\t\t} else {\n\t\t\tmediaQueryList.addListener(mediaQueryListener);\n\t\t}\n\t}\n\n\treturn result;\n};\n\nexport default prefersColorSchemeInit;\n"],"names":["PREFERS_COLOR_SCHEME_REGEX","prefersColorSchemeInit","initialColorScheme","options","debug","mediaQueryString","mediaQueryList","window","matchMedia","hasNativeSupport","media","mediaQueryListener","set","matches","colorScheme","currentColorScheme","result","onChange","forEach","call","document","styleSheets","styleSheet","rules","cssRules","cssRule","push","test","Object","mediaText","index","indexOf","parentStyleSheet","deleteRule","colorDepthMatch","match","length","replace","e","console","error","defineProperty","removeListener","get","addEventListener","addListener"],"mappings":"AAAA,IAAMA,EAA6B,yBAE7BC,EAAyB,SAAzBA,uBAA0BC,EAAoBC,GAG7CA,IACJA,EAAU,CAAA,GAGXA,EAAU,CACTC,QAAUD,EAAQC,QAAU,GAI9B,IAAMC,EAAmB,+BACnBC,EAAkB,eAAgBC,QAAWA,OAAOC,WAAWH,GAC/DI,EAAmBH,GAAkBA,EAAeI,QAAUL,EAC9DM,EAAqB,SAArBA,qBACLC,EAAKN,GAAkBA,EAAeO,QAAW,OAAS,UAOrDD,EAAM,SAANA,IAAO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,QAAU,OAAS,SAapG,OAXAD,EAAIG,GAGAT,IACC,qBAAsBA,EACzBA,EAAesC,iBAAiB,SAAUjC,GAE1CL,EAAeuC,YAAYlC,IAItBK,CACR"} \ No newline at end of file diff --git a/plugins/css-prefers-color-scheme/src/browser-global.js b/plugins/css-prefers-color-scheme/src/browser-global.js index 947c5f36a..576dea2c3 100644 --- a/plugins/css-prefers-color-scheme/src/browser-global.js +++ b/plugins/css-prefers-color-scheme/src/browser-global.js @@ -1,4 +1,3 @@ -/* global self,window */ import { default as prefersColorSchemeInit } from './browser'; (function (global) { diff --git a/plugins/css-prefers-color-scheme/src/browser.js b/plugins/css-prefers-color-scheme/src/browser.js index de2202c66..3adbb6151 100644 --- a/plugins/css-prefers-color-scheme/src/browser.js +++ b/plugins/css-prefers-color-scheme/src/browser.js @@ -1,4 +1,3 @@ -/* global document,window */ const PREFERS_COLOR_SCHEME_REGEX = /prefers-color-scheme:/i; const prefersColorSchemeInit = (initialColorScheme, options) => { diff --git a/plugins/css-prefers-color-scheme/src/index.ts b/plugins/css-prefers-color-scheme/src/index.ts index a5924c052..bc6c254d1 100644 --- a/plugins/css-prefers-color-scheme/src/index.ts +++ b/plugins/css-prefers-color-scheme/src/index.ts @@ -37,7 +37,7 @@ const creator: PluginCreator = (opts?: pluginOptions) => { } const { params } = atRule; - const altParamsColorDepth = params.replace(prefersInterfaceRegExp, ($0, style) => { + const altParamsColorDepth = params.replace(prefersInterfaceRegExp, ($0, style: string) => { if (style.toLowerCase() === 'dark') { return colorDepthByStyle.dark; } diff --git a/plugins/postcss-browser-comments/dist/index.cjs b/plugins/postcss-browser-comments/dist/index.cjs index f85da74e9..738c80df1 100644 --- a/plugins/postcss-browser-comments/dist/index.cjs +++ b/plugins/postcss-browser-comments/dist/index.cjs @@ -1 +1 @@ -"use strict";var e=require("browserslist");const creator=s=>({postcssPlugin:"postcss-browser-comments",prepare(t){console.log("result",t.root?.source?.input.file);const r=new Set(e(Object(s).browsers||null,{path:t.root?.source?.input.file}));return{postcssPlugin:"postcss-browser-comments",Once(s){const t=s.nodes.slice(0);for(const s of t){if(!isBrowserCommentNode(s))continue;const t=s.next();if(!t||"rule"!==t.type)continue;const o=getBrowserData(s.text);o.isNumbered?(t.nodes.filter(isBrowserReferenceCommentNode).map((s=>{const t=parseFloat(s.text)-1,n=e(o.browserslist[t]);browserslistsOverlap(r,n)||(s.prev()?.remove(),s.remove())})),t.nodes.length||(t.remove(),s.remove())):browserslistsOverlap(r,e(o.browserslist))||(t.remove(),s.remove())}}}}});function isBrowserCommentNode(e){return"comment"===e.type&&(!!s.test(e.text)&&"rule"===e.next()?.type)}creator.postcss=!0;const s=/^\*\n +/;function isBrowserReferenceCommentNode(e){return"comment"===e.type&&t.test(e.text)}const t=/^\d+$/;function getBrowserData(e){const s=e.match(r);return s?{browserslist:s.map((e=>getBrowsersList(e.replace(n,"$1")))),isNumbered:!0}:{browserslist:getBrowsersList(e.replace(o,"")),isNumbered:!1}}const r=/(\n \* \d+\. (?:[^\n]|\n \* {4,})+)/g,o=/^\*\n \* ?|\n \*/g,n=/\n \* (?:( )\s*)?/g;function getBrowsersList(e){return e.split(c).slice(1).map((e=>e.split(i).filter((e=>e)))).reduce(((e,s)=>e.concat(s)),[]).map((e=>e.replace(l,((e,s,t)=>"all"===s?"> 0%":`${s}${t?/^((?:\d*\.)?\d+)-$/.test(t)?` <= ${t.slice(0,-1)}`:` ${t}`:" > 0"}`)).toLowerCase()))}const c=/\s+in\s+/,i=/ and|, and|,/,l=/^\s*(\w+)(?: ((?:(?:\d*\.)?\d+-)?(?:\d*\.)?\d+[+-]?))?.*$/;function browserslistsOverlap(e,s){return s.some((s=>e.has(s)))}module.exports=creator; +"use strict";var e=require("browserslist");const creator=s=>({postcssPlugin:"postcss-browser-comments",prepare(t){console.log("result",t.root?.source?.input.file);const r=new Set(e(s?.browsers??null,{path:t.root?.source?.input.file}));return{postcssPlugin:"postcss-browser-comments",Once(s){const t=s.nodes.slice(0);for(const s of t){if(!isBrowserCommentNode(s))continue;const t=s.next();if(!t||"rule"!==t.type)continue;const o=getBrowserData(s.text);o.isNumbered?(t.nodes.filter(isBrowserReferenceCommentNode).map((s=>{const t=parseFloat(s.text)-1,n=e(o.browserslist[t]);browserslistsOverlap(r,n)||(s.prev()?.remove(),s.remove())})),t.nodes.length||(t.remove(),s.remove())):browserslistsOverlap(r,e(o.browserslist))||(t.remove(),s.remove())}}}}});function isBrowserCommentNode(e){return"comment"===e.type&&(!!s.test(e.text)&&"rule"===e.next()?.type)}creator.postcss=!0;const s=/^\*\n +/;function isBrowserReferenceCommentNode(e){return"comment"===e.type&&t.test(e.text)}const t=/^\d+$/;function getBrowserData(e){const s=e.match(r);return s?{browserslist:s.map((e=>getBrowsersList(e.replace(n,"$1")))),isNumbered:!0}:{browserslist:getBrowsersList(e.replace(o,"")),isNumbered:!1}}const r=/(\n \* \d+\. (?:[^\n]|\n \* {4,})+)/g,o=/^\*\n \* ?|\n \*/g,n=/\n \* (?:( )\s*)?/g;function getBrowsersList(e){return e.split(c).slice(1).map((e=>e.split(i).filter((e=>e)))).reduce(((e,s)=>e.concat(s)),[]).map((e=>e.replace(l,((e,s,t)=>"all"===s?"> 0%":`${s}${t?/^((?:\d*\.)?\d+)-$/.test(t)?` <= ${t.slice(0,-1)}`:` ${t}`:" > 0"}`)).toLowerCase()))}const c=/\s+in\s+/,i=/ and|, and|,/,l=/^\s*(\w+)(?: ((?:(?:\d*\.)?\d+-)?(?:\d*\.)?\d+[+-]?))?.*$/;function browserslistsOverlap(e,s){return s.some((s=>e.has(s)))}module.exports=creator; diff --git a/plugins/postcss-browser-comments/dist/index.mjs b/plugins/postcss-browser-comments/dist/index.mjs index 776cd1ca2..4c4bc0362 100644 --- a/plugins/postcss-browser-comments/dist/index.mjs +++ b/plugins/postcss-browser-comments/dist/index.mjs @@ -1 +1 @@ -import e from"browserslist";const creator=s=>({postcssPlugin:"postcss-browser-comments",prepare(t){console.log("result",t.root?.source?.input.file);const r=new Set(e(Object(s).browsers||null,{path:t.root?.source?.input.file}));return{postcssPlugin:"postcss-browser-comments",Once(s){const t=s.nodes.slice(0);for(const s of t){if(!isBrowserCommentNode(s))continue;const t=s.next();if(!t||"rule"!==t.type)continue;const o=getBrowserData(s.text);o.isNumbered?(t.nodes.filter(isBrowserReferenceCommentNode).map((s=>{const t=parseFloat(s.text)-1,n=e(o.browserslist[t]);browserslistsOverlap(r,n)||(s.prev()?.remove(),s.remove())})),t.nodes.length||(t.remove(),s.remove())):browserslistsOverlap(r,e(o.browserslist))||(t.remove(),s.remove())}}}}});function isBrowserCommentNode(e){return"comment"===e.type&&(!!s.test(e.text)&&"rule"===e.next()?.type)}creator.postcss=!0;const s=/^\*\n +/;function isBrowserReferenceCommentNode(e){return"comment"===e.type&&t.test(e.text)}const t=/^\d+$/;function getBrowserData(e){const s=e.match(r);return s?{browserslist:s.map((e=>getBrowsersList(e.replace(n,"$1")))),isNumbered:!0}:{browserslist:getBrowsersList(e.replace(o,"")),isNumbered:!1}}const r=/(\n \* \d+\. (?:[^\n]|\n \* {4,})+)/g,o=/^\*\n \* ?|\n \*/g,n=/\n \* (?:( )\s*)?/g;function getBrowsersList(e){return e.split(c).slice(1).map((e=>e.split(i).filter((e=>e)))).reduce(((e,s)=>e.concat(s)),[]).map((e=>e.replace(l,((e,s,t)=>"all"===s?"> 0%":`${s}${t?/^((?:\d*\.)?\d+)-$/.test(t)?` <= ${t.slice(0,-1)}`:` ${t}`:" > 0"}`)).toLowerCase()))}const c=/\s+in\s+/,i=/ and|, and|,/,l=/^\s*(\w+)(?: ((?:(?:\d*\.)?\d+-)?(?:\d*\.)?\d+[+-]?))?.*$/;function browserslistsOverlap(e,s){return s.some((s=>e.has(s)))}export{creator as default}; +import e from"browserslist";const creator=s=>({postcssPlugin:"postcss-browser-comments",prepare(t){console.log("result",t.root?.source?.input.file);const r=new Set(e(s?.browsers??null,{path:t.root?.source?.input.file}));return{postcssPlugin:"postcss-browser-comments",Once(s){const t=s.nodes.slice(0);for(const s of t){if(!isBrowserCommentNode(s))continue;const t=s.next();if(!t||"rule"!==t.type)continue;const o=getBrowserData(s.text);o.isNumbered?(t.nodes.filter(isBrowserReferenceCommentNode).map((s=>{const t=parseFloat(s.text)-1,n=e(o.browserslist[t]);browserslistsOverlap(r,n)||(s.prev()?.remove(),s.remove())})),t.nodes.length||(t.remove(),s.remove())):browserslistsOverlap(r,e(o.browserslist))||(t.remove(),s.remove())}}}}});function isBrowserCommentNode(e){return"comment"===e.type&&(!!s.test(e.text)&&"rule"===e.next()?.type)}creator.postcss=!0;const s=/^\*\n +/;function isBrowserReferenceCommentNode(e){return"comment"===e.type&&t.test(e.text)}const t=/^\d+$/;function getBrowserData(e){const s=e.match(r);return s?{browserslist:s.map((e=>getBrowsersList(e.replace(n,"$1")))),isNumbered:!0}:{browserslist:getBrowsersList(e.replace(o,"")),isNumbered:!1}}const r=/(\n \* \d+\. (?:[^\n]|\n \* {4,})+)/g,o=/^\*\n \* ?|\n \*/g,n=/\n \* (?:( )\s*)?/g;function getBrowsersList(e){return e.split(c).slice(1).map((e=>e.split(i).filter((e=>e)))).reduce(((e,s)=>e.concat(s)),[]).map((e=>e.replace(l,((e,s,t)=>"all"===s?"> 0%":`${s}${t?/^((?:\d*\.)?\d+)-$/.test(t)?` <= ${t.slice(0,-1)}`:` ${t}`:" > 0"}`)).toLowerCase()))}const c=/\s+in\s+/,i=/ and|, and|,/,l=/^\s*(\w+)(?: ((?:(?:\d*\.)?\d+-)?(?:\d*\.)?\d+[+-]?))?.*$/;function browserslistsOverlap(e,s){return s.some((s=>e.has(s)))}export{creator as default}; diff --git a/plugins/postcss-browser-comments/src/index.ts b/plugins/postcss-browser-comments/src/index.ts index 786cf7fdc..bfde82b83 100644 --- a/plugins/postcss-browser-comments/src/index.ts +++ b/plugins/postcss-browser-comments/src/index.ts @@ -14,7 +14,7 @@ const creator: PluginCreator = (opts?: pluginOptions) => { console.log('result', result.root?.source?.input.file); const clientBrowserList = new Set(browserslist( - Object(opts).browsers || null, + opts?.browsers ?? null, { path: result.root?.source?.input.file, }, @@ -138,7 +138,9 @@ function getBrowsersList(text: string): Array { ($0, browser, query) => browser === 'all' ? '> 0%' : `${browser}${query + // eslint-disable-next-line @typescript-eslint/no-unsafe-argument ? /^((?:\d*\.)?\d+)-$/.test(query) + // eslint-disable-next-line @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-member-access ? ` <= ${query.slice(0, -1)}` : ` ${query}` : ' > 0' diff --git a/plugins/postcss-color-functional-notation/dist/index.cjs b/plugins/postcss-color-functional-notation/dist/index.cjs index f83a389ad..08ba436e4 100644 --- a/plugins/postcss-color-functional-notation/dist/index.cjs +++ b/plugins/postcss-color-functional-notation/dist/index.cjs @@ -1 +1 @@ -"use strict";var s=require("@csstools/postcss-progressive-custom-properties"),e=require("@csstools/css-color-parser"),t=require("@csstools/utilities"),o=require("@csstools/css-parser-algorithms"),a=require("@csstools/css-tokenizer");const r=/^(?:rgb|hsl)a?$/i,n=/\b(?:rgb|hsl)a?\(/i,basePlugin=s=>({postcssPlugin:"postcss-color-functional-notation",Declaration(l){const i=l.value;if(!n.test(i))return;if(t.hasFallback(l))return;if(t.hasSupportsAtRuleAncestor(l,n))return;const c=o.replaceComponentValues(o.parseCommaSeparatedListOfComponentValues(a.tokenize({css:i})),(s=>{if(!o.isFunctionNode(s)||!r.test(s.getName()))return;const t=e.color(s);return!t||t.syntaxFlags.has(e.SyntaxFlag.Experimental)||t.syntaxFlags.has(e.SyntaxFlag.HasNoneKeywords)||t.syntaxFlags.has(e.SyntaxFlag.RelativeColorSyntax)||(t.syntaxFlags.has(e.SyntaxFlag.LegacyRGB)||t.syntaxFlags.has(e.SyntaxFlag.LegacyHSL))&&!t.syntaxFlags.has(e.SyntaxFlag.HasPercentageAlpha)?void 0:"hsl"===t.colorNotation?e.serializeHSL(t):e.serializeRGB(t)})),u=o.stringify(c);u!==i&&(l.cloneBefore({value:u}),s?.preserve||l.remove())}});basePlugin.postcss=!0;const postcssPlugin=e=>{const t=Object.assign({preserve:!1,enableProgressiveCustomProperties:!0},e);return t.enableProgressiveCustomProperties&&t.preserve?{postcssPlugin:"postcss-color-functional-notation",plugins:[s(),basePlugin(t)]}:basePlugin(t)};postcssPlugin.postcss=!0,module.exports=postcssPlugin; +"use strict";var s=require("@csstools/postcss-progressive-custom-properties"),e=require("@csstools/css-color-parser"),t=require("@csstools/utilities"),o=require("@csstools/css-parser-algorithms"),a=require("@csstools/css-tokenizer");const r=/^(?:rgb|hsl)a?$/i,n=/\b(?:rgb|hsl)a?\(/i,basePlugin=s=>({postcssPlugin:"postcss-color-functional-notation",Declaration(l){const i=l.value;if(!n.test(i))return;if(t.hasFallback(l))return;if(t.hasSupportsAtRuleAncestor(l,n))return;const c=o.replaceComponentValues(o.parseCommaSeparatedListOfComponentValues(a.tokenize({css:i})),(s=>{if(!o.isFunctionNode(s)||!r.test(s.getName()))return;const t=e.color(s);return!t||t.syntaxFlags.has(e.SyntaxFlag.Experimental)||t.syntaxFlags.has(e.SyntaxFlag.HasNoneKeywords)||t.syntaxFlags.has(e.SyntaxFlag.RelativeColorSyntax)||(t.syntaxFlags.has(e.SyntaxFlag.LegacyRGB)||t.syntaxFlags.has(e.SyntaxFlag.LegacyHSL))&&!t.syntaxFlags.has(e.SyntaxFlag.HasPercentageAlpha)?void 0:t.colorNotation===e.ColorNotation.HSL?e.serializeHSL(t):e.serializeRGB(t)})),u=o.stringify(c);u!==i&&(l.cloneBefore({value:u}),s?.preserve||l.remove())}});basePlugin.postcss=!0;const postcssPlugin=e=>{const t=Object.assign({preserve:!1,enableProgressiveCustomProperties:!0},e);return t.enableProgressiveCustomProperties&&t.preserve?{postcssPlugin:"postcss-color-functional-notation",plugins:[s(),basePlugin(t)]}:basePlugin(t)};postcssPlugin.postcss=!0,module.exports=postcssPlugin; diff --git a/plugins/postcss-color-functional-notation/dist/index.mjs b/plugins/postcss-color-functional-notation/dist/index.mjs index 045cea099..59f8809aa 100644 --- a/plugins/postcss-color-functional-notation/dist/index.mjs +++ b/plugins/postcss-color-functional-notation/dist/index.mjs @@ -1 +1 @@ -import s from"@csstools/postcss-progressive-custom-properties";import{color as o,SyntaxFlag as t,serializeHSL as e,serializeRGB as r}from"@csstools/css-color-parser";import{hasFallback as a,hasSupportsAtRuleAncestor as n}from"@csstools/utilities";import{replaceComponentValues as l,parseCommaSeparatedListOfComponentValues as c,isFunctionNode as i,stringify as p}from"@csstools/css-parser-algorithms";import{tokenize as g}from"@csstools/css-tokenizer";const u=/^(?:rgb|hsl)a?$/i,m=/\b(?:rgb|hsl)a?\(/i,basePlugin=s=>({postcssPlugin:"postcss-color-functional-notation",Declaration(f){const h=f.value;if(!m.test(h))return;if(a(f))return;if(n(f,m))return;const v=l(c(g({css:h})),(s=>{if(!i(s)||!u.test(s.getName()))return;const a=o(s);return!a||a.syntaxFlags.has(t.Experimental)||a.syntaxFlags.has(t.HasNoneKeywords)||a.syntaxFlags.has(t.RelativeColorSyntax)||(a.syntaxFlags.has(t.LegacyRGB)||a.syntaxFlags.has(t.LegacyHSL))&&!a.syntaxFlags.has(t.HasPercentageAlpha)?void 0:"hsl"===a.colorNotation?e(a):r(a)})),y=p(v);y!==h&&(f.cloneBefore({value:y}),s?.preserve||f.remove())}});basePlugin.postcss=!0;const postcssPlugin=o=>{const t=Object.assign({preserve:!1,enableProgressiveCustomProperties:!0},o);return t.enableProgressiveCustomProperties&&t.preserve?{postcssPlugin:"postcss-color-functional-notation",plugins:[s(),basePlugin(t)]}:basePlugin(t)};postcssPlugin.postcss=!0;export{postcssPlugin as default}; +import s from"@csstools/postcss-progressive-custom-properties";import{color as o,SyntaxFlag as t,ColorNotation as e,serializeHSL as r,serializeRGB as a}from"@csstools/css-color-parser";import{hasFallback as n,hasSupportsAtRuleAncestor as c}from"@csstools/utilities";import{replaceComponentValues as i,parseCommaSeparatedListOfComponentValues as l,isFunctionNode as p,stringify as g}from"@csstools/css-parser-algorithms";import{tokenize as u}from"@csstools/css-tokenizer";const m=/^(?:rgb|hsl)a?$/i,f=/\b(?:rgb|hsl)a?\(/i,basePlugin=s=>({postcssPlugin:"postcss-color-functional-notation",Declaration(v){const h=v.value;if(!f.test(h))return;if(n(v))return;if(c(v,f))return;const y=i(l(u({css:h})),(s=>{if(!p(s)||!m.test(s.getName()))return;const n=o(s);return!n||n.syntaxFlags.has(t.Experimental)||n.syntaxFlags.has(t.HasNoneKeywords)||n.syntaxFlags.has(t.RelativeColorSyntax)||(n.syntaxFlags.has(t.LegacyRGB)||n.syntaxFlags.has(t.LegacyHSL))&&!n.syntaxFlags.has(t.HasPercentageAlpha)?void 0:n.colorNotation===e.HSL?r(n):a(n)})),x=g(y);x!==h&&(v.cloneBefore({value:x}),s?.preserve||v.remove())}});basePlugin.postcss=!0;const postcssPlugin=o=>{const t=Object.assign({preserve:!1,enableProgressiveCustomProperties:!0},o);return t.enableProgressiveCustomProperties&&t.preserve?{postcssPlugin:"postcss-color-functional-notation",plugins:[s(),basePlugin(t)]}:basePlugin(t)};postcssPlugin.postcss=!0;export{postcssPlugin as default}; diff --git a/plugins/postcss-color-functional-notation/src/index.ts b/plugins/postcss-color-functional-notation/src/index.ts index 278aa78c0..08bac826c 100644 --- a/plugins/postcss-color-functional-notation/src/index.ts +++ b/plugins/postcss-color-functional-notation/src/index.ts @@ -1,6 +1,6 @@ import postcssProgressiveCustomProperties from '@csstools/postcss-progressive-custom-properties'; import type { Declaration, PluginCreator } from 'postcss'; -import { color, serializeRGB, serializeHSL, SyntaxFlag } from '@csstools/css-color-parser'; +import { color, serializeRGB, serializeHSL, SyntaxFlag, ColorNotation } from '@csstools/css-color-parser'; import { hasFallback, hasSupportsAtRuleAncestor } from '@csstools/utilities'; import { isFunctionNode, parseCommaSeparatedListOfComponentValues, replaceComponentValues, stringify } from '@csstools/css-parser-algorithms'; import { tokenize } from '@csstools/css-tokenizer'; @@ -62,7 +62,7 @@ const basePlugin: PluginCreator = (opts?: basePluginOptions) return; } - if (colorData.colorNotation === 'hsl') { + if (colorData.colorNotation === ColorNotation.HSL) { return serializeHSL(colorData); } diff --git a/plugins/postcss-custom-media/dist/index.cjs b/plugins/postcss-custom-media/dist/index.cjs index eba771278..49927c985 100644 --- a/plugins/postcss-custom-media/dist/index.cjs +++ b/plugins/postcss-custom-media/dist/index.cjs @@ -1 +1 @@ -"use strict";var e=require("@csstools/cascade-layer-name-parser"),r=require("@csstools/css-tokenizer"),t=require("@csstools/media-query-list-parser");const n=e.parse("csstools-implicit-layer")[0];function collectCascadeLayerOrder(r){const t=new Map,o=new Map,a=[];r.walkAtRules((r=>{if("layer"!==r.name.toLowerCase())return;{let e=r.parent;for(;e;){if("atrule"!==e.type||"layer"!==e.name.toLowerCase()){if(e===r.root())break;return}e=e.parent}}let s;if(r.nodes)s=normalizeLayerName(r.params,1);else{if(!r.params.trim())return;s=r.params}let i=e.parse(s);if(i?.length){{let e=r.parent;for(;e&&"atrule"===e.type&&"layer"===e.name.toLowerCase();){const r=o.get(e);r?(i=i.map((e=>r.concat(e))),e=e.parent):e=e.parent}}if(e.addLayerToModel(a,i),r.nodes){const e=i[0].concat(n);t.set(r,e),o.set(r,i[0])}}}));for(const r of t.values())e.addLayerToModel(a,[r]);const s=new WeakMap;for(const[e,r]of t)s.set(e,a.findIndex((e=>r.equal(e))));return s}function normalizeLayerName(e,r){return e.trim()?e:"csstools-anon-layer--"+r++}const o=new Set(["scope","container","layer"]);function isProcessableCustomMediaRule(e){if("custom-media"!==e.name.toLowerCase())return!1;if(!e.params||!e.params.includes("--"))return!1;if(e.nodes&&e.nodes.length>0)return!1;let r=e.parent;for(;r;){if("atrule"===r.type&&!o.has(r.name.toLowerCase()))return!1;r=r.parent}return!0}function removeCyclicReferences(e,r){const t=new Set;for(;e.size>0;){const n=findCyclicNode(Array.from(e.keys()),r);if(!n)return t;e.delete(n),t.add(n),r=r.filter((e=>-1===e.indexOf(n)))}return t}function findCyclicNode(e,r){let t=e.length;const n=new Array(t),o={};let a=t;const s=makeOutgoingEdges(r),i=makeNodesHash(e);for(;a--;)if(!o[a]){const r=visit(e[a],a,new Set);if(!r)continue;return r}function visit(e,r,a){if(a.has(e))return e;if(!i.has(e))return;if(o[r])return;o[r]=!0;const l=Array.from(s.get(e)||new Set);if(r=l.length){a.add(e);do{const e=l[--r],t=visit(e,i.get(e),a);if(t)return t}while(r);a.delete(e)}n[--t]=e}}function makeOutgoingEdges(e){const r=new Map;for(let t=0,n=e.length;t{throw new Error(`Unable to parse media query "${e}"`)}}),n=[];for(;!t.endOfFile();)n.push(t.nextToken());return n}const a=[[r.TokenType.Ident,"max-color",0,0,{value:"max-color"}],[r.TokenType.Colon,":",0,0,void 0],[r.TokenType.Number,"2147477350",0,0,{value:2147477350,type:r.NumberType.Integer}]],s=[[r.TokenType.Ident,"color",0,0,{value:"color"}],[r.TokenType.Colon,":",0,0,void 0],[r.TokenType.Number,"2147477350",0,0,{value:2147477350,type:r.NumberType.Integer}]];function replaceTrueAndFalseTokens(e){let t,n=[];for(let o=0;o{throw new Error(`Unable to parse media query "${r.stringify(...s)}"`)}}),l=t.parseFromTokens(r.cloneTokens(s),{preserveInvalidMediaQueries:!0,onParseError:()=>{throw new Error(`Unable to parse media query "${r.stringify(...s)}"`)}});for(let e=0;e[a,e]))}}function getCustomMedia(e,r,t){const n=new Map,o=new Map,a=[],s=collectCascadeLayerOrder(e);e.walkAtRules((e=>{if(!isProcessableCustomMediaRule(e))return;const r=parseCustomMedia(e.params);if(!r)return;if(0===r.truthy.length)return;const i=(u=s,(l=e).parent&&"atrule"===l.parent.type&&"layer"===l.parent.name.toLowerCase()?u.has(l.parent)?u.get(l.parent)+1:0:1e7);var l,u;const c=o.get(r.name)??-1;if(i&&i>=c&&(o.set(r.name,i),n.set(r.name,{truthy:r.truthy,falsy:r.falsy}),a.push(...r.dependencies)),!t.preserve){const r=e.parent;e.remove(),removeEmptyAncestorBlocks(r)}}));const i=removeCyclicReferences(n,a);for(const t of i.values())e.warn(r,`@custom-media rules have cyclic dependencies for "${t}"`);return n}function removeEmptyAncestorBlocks(e){if(!e)return;let r=e;for(;r;){if(r.nodes&&r.nodes.length>0)return;const e=r.parent;r.remove(),r=e}}function transformAtMediaListTokens(e,r){const n=t.parse(e,{preserveInvalidMediaQueries:!0,onParseError:()=>{throw new Error(`Unable to parse media query "${e}"`)}}),o=n.map((e=>e.toString()));for(let e=0;et===e?n:{replaceWith:r}))}const s=transformComplexMediaQuery(t,r);if(s&&0!==s.length&&s[0].replaceWith!==a)return o.flatMap(((r,t)=>t===e?s:[{replaceWith:r}]))}return[]}function transformSimpleMediaQuery(e,r){if(!mediaQueryIsSimple(e))return null;let n=null;return e.walk((e=>{const o=e.node;if(!t.isMediaFeatureBoolean(o))return;const a=o.getName();if(!a.startsWith("--"))return!1;const s=r.get(a);return s?(n={replaceWith:s.truthy.map((e=>e.toString().trim())).join(",")},!1):void 0})),n}function transformComplexMediaQuery(e,r){let n=[];return e.walk((o=>{const i=o.node;if(!t.isMediaFeatureBoolean(i))return;const l=o.parent;if(!t.isMediaFeature(l))return;const u=i.getName();if(!u.startsWith("--"))return!1;const c=r.get(u);if(c){if(1===c.truthy.length&&mediaQueryIsSimple(c.truthy[0])){let r=null;if(c.truthy[0].walk((e=>{if(t.isMediaFeature(e.node))return r=e.node,!1})),r&&r.feature)return l.feature=r.feature,n=[{replaceWith:e.toString()}],!1}const r=t.newMediaFeaturePlain(a[0][4].value,a[2]);l.feature=r.feature;const o=e.toString(),i=t.newMediaFeaturePlain(s[0][4].value,s[2]);l.feature=i.feature;const u=e.toString();return n=[{replaceWith:o,encapsulateWith:c.truthy.map((e=>e.toString().trim())).join(",")},{replaceWith:u,encapsulateWith:c.falsy.map((e=>e.toString().trim())).join(",")}],!1}})),n}function mediaQueryIsSimple(e){if(t.isMediaQueryInvalid(e))return!1;if(t.isMediaQueryWithType(e))return!1;let r=!0;return e.walk((e=>{if(t.isMediaAnd(e.node)||t.isMediaOr(e.node)||t.isMediaNot(e.node)||t.isMediaConditionList(e.node)||t.isGeneralEnclosed(e.node))return r=!1,!1})),r}const creator=e=>{const r=Boolean(Object(e).preserve);if("importFrom"in Object(e))throw new Error('[postcss-custom-media] "importFrom" is no longer supported');if("exportTo"in Object(e))throw new Error('[postcss-custom-media] "exportTo" is no longer supported');return{postcssPlugin:"postcss-custom-media",prepare(){const e=new WeakSet;let t=new Map;return{postcssPlugin:"postcss-custom-media",Once(e,{result:n}){t=getCustomMedia(e,n,{preserve:r})},AtRule(n,{result:o}){if(e.has(n))return;if("media"!==n.name.toLowerCase())return;if(!n.params)return;if(!n.params.includes("--"))return;let a=[];try{a=transformAtMediaListTokens(n.params,t)}catch(e){return void n.warn(o,`Failed to parse @custom-media params with error message: "${e instanceof Error?e.message:e}"`)}if(!a||0===a.length)return;if(1===a.length){if(n.params.trim()===a[0].replaceWith.trim())return;return e.add(n),n.cloneBefore({params:a[0].replaceWith.trim()}),r?void 0:void n.remove()}if(!!!a.find((e=>!!e.encapsulateWith)))return e.add(n),n.cloneBefore({params:a.map((e=>e.replaceWith)).join(",").trim()}),void(r||n.remove());a.forEach((r=>{if(!r.encapsulateWith)return void n.cloneBefore({params:r.replaceWith.trim()});const t=n.clone({params:r.replaceWith}),o=n.clone({params:r.encapsulateWith.trim(),nodes:[]});t.parent=void 0,o.parent=void 0,e.add(n),o.append(t),n.before(o)})),r||n.remove()}}}}};creator.postcss=!0,module.exports=creator; +"use strict";var e=require("@csstools/cascade-layer-name-parser"),r=require("@csstools/css-tokenizer"),t=require("@csstools/media-query-list-parser");const n=e.parse("csstools-implicit-layer")[0];function collectCascadeLayerOrder(r){const t=new Map,o=new Map,a=[];r.walkAtRules((r=>{if("layer"!==r.name.toLowerCase())return;{let e=r.parent;for(;e;){if("atrule"!==e.type||"layer"!==e.name.toLowerCase()){if(e===r.root())break;return}e=e.parent}}let s;if(r.nodes)s=normalizeLayerName(r.params,1);else{if(!r.params.trim())return;s=r.params}let i=e.parse(s);if(i?.length){{let e=r.parent;for(;e&&"atrule"===e.type&&"layer"===e.name.toLowerCase();){const r=o.get(e);r?(i=i.map((e=>r.concat(e))),e=e.parent):e=e.parent}}if(e.addLayerToModel(a,i),r.nodes){const e=i[0].concat(n);t.set(r,e),o.set(r,i[0])}}}));for(const r of t.values())e.addLayerToModel(a,[r]);const s=new WeakMap;for(const[e,r]of t)s.set(e,a.findIndex((e=>r.equal(e))));return s}function normalizeLayerName(e,r){return e.trim()?e:"csstools-anon-layer--"+r++}const o=new Set(["scope","container","layer"]);function isProcessableCustomMediaRule(e){if("custom-media"!==e.name.toLowerCase())return!1;if(!e.params||!e.params.includes("--"))return!1;if(e.nodes&&e.nodes.length>0)return!1;let r=e.parent;for(;r;){if("atrule"===r.type&&!o.has(r.name.toLowerCase()))return!1;r=r.parent}return!0}function removeCyclicReferences(e,r){const t=new Set;for(;e.size>0;){const n=findCyclicNode(Array.from(e.keys()),r);if(!n)return t;e.delete(n),t.add(n),r=r.filter((e=>-1===e.indexOf(n)))}return t}function findCyclicNode(e,r){let t=e.length;const n=new Array(t),o={};let a=t;const s=makeOutgoingEdges(r),i=makeNodesHash(e);for(;a--;)if(!o[a]){const r=visit(e[a],a,new Set);if(!r)continue;return r}function visit(e,r,a){if(a.has(e))return e;if(!i.has(e))return;if(o[r])return;o[r]=!0;const l=Array.from(s.get(e)||new Set);if(r=l.length){a.add(e);do{const e=l[--r],t=visit(e,i.get(e),a);if(t)return t}while(r);a.delete(e)}n[--t]=e}}function makeOutgoingEdges(e){const r=new Map;for(let t=0,n=e.length;t{throw new Error(`Unable to parse media query "${e}"`)}}),n=[];for(;!t.endOfFile();)n.push(t.nextToken());return n}const a=[[r.TokenType.Ident,"max-color",0,0,{value:"max-color"}],[r.TokenType.Colon,":",0,0,void 0],[r.TokenType.Number,"2147477350",0,0,{value:2147477350,type:r.NumberType.Integer}]],s=[[r.TokenType.Ident,"color",0,0,{value:"color"}],[r.TokenType.Colon,":",0,0,void 0],[r.TokenType.Number,"2147477350",0,0,{value:2147477350,type:r.NumberType.Integer}]];function replaceTrueAndFalseTokens(e){let t,n=[];for(let o=0;o{throw new Error(`Unable to parse media query "${r.stringify(...s)}"`)}}),l=t.parseFromTokens(r.cloneTokens(s),{preserveInvalidMediaQueries:!0,onParseError:()=>{throw new Error(`Unable to parse media query "${r.stringify(...s)}"`)}});for(let e=0;e[a,e]))}}function getCustomMedia(e,r,t){const n=new Map,o=new Map,a=[],s=collectCascadeLayerOrder(e);e.walkAtRules((e=>{if(!isProcessableCustomMediaRule(e))return;const r=parseCustomMedia(e.params);if(!r)return;if(0===r.truthy.length)return;const i=(u=s,(l=e).parent&&"atrule"===l.parent.type&&"layer"===l.parent.name.toLowerCase()?u.has(l.parent)?u.get(l.parent)+1:0:1e7);var l,u;const c=o.get(r.name)??-1;if(i&&i>=c&&(o.set(r.name,i),n.set(r.name,{truthy:r.truthy,falsy:r.falsy}),a.push(...r.dependencies)),!t.preserve){const r=e.parent;e.remove(),removeEmptyAncestorBlocks(r)}}));const i=removeCyclicReferences(n,a);for(const t of i.values())e.warn(r,`@custom-media rules have cyclic dependencies for "${t}"`);return n}function removeEmptyAncestorBlocks(e){if(!e)return;let r=e;for(;r;){if(r.nodes&&r.nodes.length>0)return;const e=r.parent;r.remove(),r=e}}function transformAtMediaListTokens(e,r){const n=t.parse(e,{preserveInvalidMediaQueries:!0,onParseError:()=>{throw new Error(`Unable to parse media query "${e}"`)}}),o=n.map((e=>e.toString()));for(let e=0;et===e?n:{replaceWith:r}))}const s=transformComplexMediaQuery(t,r);if(s&&0!==s.length&&s[0].replaceWith!==a)return o.flatMap(((r,t)=>t===e?s:[{replaceWith:r}]))}return[]}function transformSimpleMediaQuery(e,r){if(!mediaQueryIsSimple(e))return null;let n=null;return e.walk((e=>{const o=e.node;if(!t.isMediaFeatureBoolean(o))return;const a=o.getName();if(!a.startsWith("--"))return!1;const s=r.get(a);return s?(n={replaceWith:s.truthy.map((e=>e.toString().trim())).join(",")},!1):void 0})),n}function transformComplexMediaQuery(e,r){let n=[];return e.walk((o=>{const i=o.node;if(!t.isMediaFeatureBoolean(i))return;const l=o.parent;if(!t.isMediaFeature(l))return;const u=i.getName();if(!u.startsWith("--"))return!1;const c=r.get(u);if(c){if(1===c.truthy.length&&mediaQueryIsSimple(c.truthy[0])){let r=null;if(c.truthy[0].walk((e=>{if(t.isMediaFeature(e.node))return r=e.node,!1})),r&&r.feature)return l.feature=r.feature,n=[{replaceWith:e.toString()}],!1}const r=t.newMediaFeaturePlain(a[0][4].value,a[2]);l.feature=r.feature;const o=e.toString(),i=t.newMediaFeaturePlain(s[0][4].value,s[2]);l.feature=i.feature;const u=e.toString();return n=[{replaceWith:o,encapsulateWith:c.truthy.map((e=>e.toString().trim())).join(",")},{replaceWith:u,encapsulateWith:c.falsy.map((e=>e.toString().trim())).join(",")}],!1}})),n}function mediaQueryIsSimple(e){if(t.isMediaQueryInvalid(e))return!1;if(t.isMediaQueryWithType(e))return!1;let r=!0;return e.walk((e=>{if(t.isMediaAnd(e.node)||t.isMediaOr(e.node)||t.isMediaNot(e.node)||t.isMediaConditionList(e.node)||t.isGeneralEnclosed(e.node))return r=!1,!1})),r}const creator=e=>{const r=e?.preserve??!1;if("importFrom"in Object(e))throw new Error('[postcss-custom-media] "importFrom" is no longer supported');if("exportTo"in Object(e))throw new Error('[postcss-custom-media] "exportTo" is no longer supported');return{postcssPlugin:"postcss-custom-media",prepare(){const e=new WeakSet;let t=new Map;return{postcssPlugin:"postcss-custom-media",Once(e,{result:n}){t=getCustomMedia(e,n,{preserve:r})},AtRule(n,{result:o}){if(e.has(n))return;if("media"!==n.name.toLowerCase())return;if(!n.params)return;if(!n.params.includes("--"))return;let a=[];try{a=transformAtMediaListTokens(n.params,t)}catch(e){return void n.warn(o,`Failed to parse @custom-media params with error message: "${e instanceof Error?e.message:e}"`)}if(!a||0===a.length)return;if(1===a.length){if(n.params.trim()===a[0].replaceWith.trim())return;return e.add(n),n.cloneBefore({params:a[0].replaceWith.trim()}),r?void 0:void n.remove()}if(!!!a.find((e=>!!e.encapsulateWith)))return e.add(n),n.cloneBefore({params:a.map((e=>e.replaceWith)).join(",").trim()}),void(r||n.remove());a.forEach((r=>{if(!r.encapsulateWith)return void n.cloneBefore({params:r.replaceWith.trim()});const t=n.clone({params:r.replaceWith}),o=n.clone({params:r.encapsulateWith.trim(),nodes:[]});t.parent=void 0,o.parent=void 0,e.add(n),o.append(t),n.before(o)})),r||n.remove()}}}}};creator.postcss=!0,module.exports=creator; diff --git a/plugins/postcss-custom-media/dist/index.mjs b/plugins/postcss-custom-media/dist/index.mjs index 5e3492256..46fe6ca7f 100644 --- a/plugins/postcss-custom-media/dist/index.mjs +++ b/plugins/postcss-custom-media/dist/index.mjs @@ -1 +1 @@ -import{parse as e,addLayerToModel as r}from"@csstools/cascade-layer-name-parser";import{tokenizer as t,TokenType as n,NumberType as o,isTokenWhiteSpaceOrComment as a,isTokenIdent as s,cloneTokens as i,stringify as l}from"@csstools/css-tokenizer";import{parseFromTokens as u,parse as c,isMediaFeatureBoolean as f,isMediaFeature as p,newMediaFeaturePlain as m,isMediaQueryInvalid as d,isMediaQueryWithType as h,isMediaAnd as y,isMediaOr as v,isMediaNot as g,isMediaConditionList as w,isGeneralEnclosed as k}from"@csstools/media-query-list-parser";const C=e("csstools-implicit-layer")[0];function collectCascadeLayerOrder(t){const n=new Map,o=new Map,a=[];t.walkAtRules((t=>{if("layer"!==t.name.toLowerCase())return;{let e=t.parent;for(;e;){if("atrule"!==e.type||"layer"!==e.name.toLowerCase()){if(e===t.root())break;return}e=e.parent}}let s;if(t.nodes)s=normalizeLayerName(t.params,1);else{if(!t.params.trim())return;s=t.params}let i=e(s);if(i?.length){{let e=t.parent;for(;e&&"atrule"===e.type&&"layer"===e.name.toLowerCase();){const r=o.get(e);r?(i=i.map((e=>r.concat(e))),e=e.parent):e=e.parent}}if(r(a,i),t.nodes){const e=i[0].concat(C);n.set(t,e),o.set(t,i[0])}}}));for(const e of n.values())r(a,[e]);const s=new WeakMap;for(const[e,r]of n)s.set(e,a.findIndex((e=>r.equal(e))));return s}function normalizeLayerName(e,r){return e.trim()?e:"csstools-anon-layer--"+r++}const M=new Set(["scope","container","layer"]);function isProcessableCustomMediaRule(e){if("custom-media"!==e.name.toLowerCase())return!1;if(!e.params||!e.params.includes("--"))return!1;if(e.nodes&&e.nodes.length>0)return!1;let r=e.parent;for(;r;){if("atrule"===r.type&&!M.has(r.name.toLowerCase()))return!1;r=r.parent}return!0}function removeCyclicReferences(e,r){const t=new Set;for(;e.size>0;){const n=findCyclicNode(Array.from(e.keys()),r);if(!n)return t;e.delete(n),t.add(n),r=r.filter((e=>-1===e.indexOf(n)))}return t}function findCyclicNode(e,r){let t=e.length;const n=new Array(t),o={};let a=t;const s=makeOutgoingEdges(r),i=makeNodesHash(e);for(;a--;)if(!o[a]){const r=visit(e[a],a,new Set);if(!r)continue;return r}function visit(e,r,a){if(a.has(e))return e;if(!i.has(e))return;if(o[r])return;o[r]=!0;const l=Array.from(s.get(e)||new Set);if(r=l.length){a.add(e);do{const e=l[--r],t=visit(e,i.get(e),a);if(t)return t}while(r);a.delete(e)}n[--t]=e}}function makeOutgoingEdges(e){const r=new Map;for(let t=0,n=e.length;t{throw new Error(`Unable to parse media query "${e}"`)}}),n=[];for(;!r.endOfFile();)n.push(r.nextToken());return n}const W=[[n.Ident,"max-color",0,0,{value:"max-color"}],[n.Colon,":",0,0,void 0],[n.Number,"2147477350",0,0,{value:2147477350,type:o.Integer}]],S=[[n.Ident,"color",0,0,{value:"color"}],[n.Colon,":",0,0,void 0],[n.Number,"2147477350",0,0,{value:2147477350,type:o.Integer}]];function replaceTrueAndFalseTokens(e){let r,t=[];for(let n=0;n{throw new Error(`Unable to parse media query "${l(...o)}"`)}}),f=u(i(o),{preserveInvalidMediaQueries:!0,onParseError:()=>{throw new Error(`Unable to parse media query "${l(...o)}"`)}});for(let e=0;e[n,e]))}}function getCustomMedia(e,r,t){const n=new Map,o=new Map,a=[],s=collectCascadeLayerOrder(e);e.walkAtRules((e=>{if(!isProcessableCustomMediaRule(e))return;const r=parseCustomMedia(e.params);if(!r)return;if(0===r.truthy.length)return;const i=(u=s,(l=e).parent&&"atrule"===l.parent.type&&"layer"===l.parent.name.toLowerCase()?u.has(l.parent)?u.get(l.parent)+1:0:1e7);var l,u;const c=o.get(r.name)??-1;if(i&&i>=c&&(o.set(r.name,i),n.set(r.name,{truthy:r.truthy,falsy:r.falsy}),a.push(...r.dependencies)),!t.preserve){const r=e.parent;e.remove(),removeEmptyAncestorBlocks(r)}}));const i=removeCyclicReferences(n,a);for(const t of i.values())e.warn(r,`@custom-media rules have cyclic dependencies for "${t}"`);return n}function removeEmptyAncestorBlocks(e){if(!e)return;let r=e;for(;r;){if(r.nodes&&r.nodes.length>0)return;const e=r.parent;r.remove(),r=e}}function transformAtMediaListTokens(e,r){const t=c(e,{preserveInvalidMediaQueries:!0,onParseError:()=>{throw new Error(`Unable to parse media query "${e}"`)}}),n=t.map((e=>e.toString()));for(let e=0;en===e?t:{replaceWith:r}))}const s=transformComplexMediaQuery(o,r);if(s&&0!==s.length&&s[0].replaceWith!==a)return n.flatMap(((r,t)=>t===e?s:[{replaceWith:r}]))}return[]}function transformSimpleMediaQuery(e,r){if(!mediaQueryIsSimple(e))return null;let t=null;return e.walk((e=>{const n=e.node;if(!f(n))return;const o=n.getName();if(!o.startsWith("--"))return!1;const a=r.get(o);return a?(t={replaceWith:a.truthy.map((e=>e.toString().trim())).join(",")},!1):void 0})),t}function transformComplexMediaQuery(e,r){let t=[];return e.walk((n=>{const o=n.node;if(!f(o))return;const a=n.parent;if(!p(a))return;const s=o.getName();if(!s.startsWith("--"))return!1;const i=r.get(s);if(i){if(1===i.truthy.length&&mediaQueryIsSimple(i.truthy[0])){let r=null;if(i.truthy[0].walk((e=>{if(p(e.node))return r=e.node,!1})),r&&r.feature)return a.feature=r.feature,t=[{replaceWith:e.toString()}],!1}const r=m(W[0][4].value,W[2]);a.feature=r.feature;const n=e.toString(),o=m(S[0][4].value,S[2]);a.feature=o.feature;const s=e.toString();return t=[{replaceWith:n,encapsulateWith:i.truthy.map((e=>e.toString().trim())).join(",")},{replaceWith:s,encapsulateWith:i.falsy.map((e=>e.toString().trim())).join(",")}],!1}})),t}function mediaQueryIsSimple(e){if(d(e))return!1;if(h(e))return!1;let r=!0;return e.walk((e=>{if(y(e.node)||v(e.node)||g(e.node)||w(e.node)||k(e.node))return r=!1,!1})),r}const creator=e=>{const r=Boolean(Object(e).preserve);if("importFrom"in Object(e))throw new Error('[postcss-custom-media] "importFrom" is no longer supported');if("exportTo"in Object(e))throw new Error('[postcss-custom-media] "exportTo" is no longer supported');return{postcssPlugin:"postcss-custom-media",prepare(){const e=new WeakSet;let t=new Map;return{postcssPlugin:"postcss-custom-media",Once(e,{result:n}){t=getCustomMedia(e,n,{preserve:r})},AtRule(n,{result:o}){if(e.has(n))return;if("media"!==n.name.toLowerCase())return;if(!n.params)return;if(!n.params.includes("--"))return;let a=[];try{a=transformAtMediaListTokens(n.params,t)}catch(e){return void n.warn(o,`Failed to parse @custom-media params with error message: "${e instanceof Error?e.message:e}"`)}if(!a||0===a.length)return;if(1===a.length){if(n.params.trim()===a[0].replaceWith.trim())return;return e.add(n),n.cloneBefore({params:a[0].replaceWith.trim()}),r?void 0:void n.remove()}if(!!!a.find((e=>!!e.encapsulateWith)))return e.add(n),n.cloneBefore({params:a.map((e=>e.replaceWith)).join(",").trim()}),void(r||n.remove());a.forEach((r=>{if(!r.encapsulateWith)return void n.cloneBefore({params:r.replaceWith.trim()});const t=n.clone({params:r.replaceWith}),o=n.clone({params:r.encapsulateWith.trim(),nodes:[]});t.parent=void 0,o.parent=void 0,e.add(n),o.append(t),n.before(o)})),r||n.remove()}}}}};creator.postcss=!0;export{creator as default}; +import{parse as e,addLayerToModel as r}from"@csstools/cascade-layer-name-parser";import{tokenizer as t,TokenType as n,NumberType as a,isTokenWhiteSpaceOrComment as o,isTokenIdent as s,cloneTokens as i,stringify as l}from"@csstools/css-tokenizer";import{parseFromTokens as u,parse as c,isMediaFeatureBoolean as f,isMediaFeature as p,newMediaFeaturePlain as m,isMediaQueryInvalid as d,isMediaQueryWithType as h,isMediaAnd as y,isMediaOr as v,isMediaNot as g,isMediaConditionList as w,isGeneralEnclosed as k}from"@csstools/media-query-list-parser";const C=e("csstools-implicit-layer")[0];function collectCascadeLayerOrder(t){const n=new Map,a=new Map,o=[];t.walkAtRules((t=>{if("layer"!==t.name.toLowerCase())return;{let e=t.parent;for(;e;){if("atrule"!==e.type||"layer"!==e.name.toLowerCase()){if(e===t.root())break;return}e=e.parent}}let s;if(t.nodes)s=normalizeLayerName(t.params,1);else{if(!t.params.trim())return;s=t.params}let i=e(s);if(i?.length){{let e=t.parent;for(;e&&"atrule"===e.type&&"layer"===e.name.toLowerCase();){const r=a.get(e);r?(i=i.map((e=>r.concat(e))),e=e.parent):e=e.parent}}if(r(o,i),t.nodes){const e=i[0].concat(C);n.set(t,e),a.set(t,i[0])}}}));for(const e of n.values())r(o,[e]);const s=new WeakMap;for(const[e,r]of n)s.set(e,o.findIndex((e=>r.equal(e))));return s}function normalizeLayerName(e,r){return e.trim()?e:"csstools-anon-layer--"+r++}const M=new Set(["scope","container","layer"]);function isProcessableCustomMediaRule(e){if("custom-media"!==e.name.toLowerCase())return!1;if(!e.params||!e.params.includes("--"))return!1;if(e.nodes&&e.nodes.length>0)return!1;let r=e.parent;for(;r;){if("atrule"===r.type&&!M.has(r.name.toLowerCase()))return!1;r=r.parent}return!0}function removeCyclicReferences(e,r){const t=new Set;for(;e.size>0;){const n=findCyclicNode(Array.from(e.keys()),r);if(!n)return t;e.delete(n),t.add(n),r=r.filter((e=>-1===e.indexOf(n)))}return t}function findCyclicNode(e,r){let t=e.length;const n=new Array(t),a={};let o=t;const s=makeOutgoingEdges(r),i=makeNodesHash(e);for(;o--;)if(!a[o]){const r=visit(e[o],o,new Set);if(!r)continue;return r}function visit(e,r,o){if(o.has(e))return e;if(!i.has(e))return;if(a[r])return;a[r]=!0;const l=Array.from(s.get(e)||new Set);if(r=l.length){o.add(e);do{const e=l[--r],t=visit(e,i.get(e),o);if(t)return t}while(r);o.delete(e)}n[--t]=e}}function makeOutgoingEdges(e){const r=new Map;for(let t=0,n=e.length;t{throw new Error(`Unable to parse media query "${e}"`)}}),n=[];for(;!r.endOfFile();)n.push(r.nextToken());return n}const W=[[n.Ident,"max-color",0,0,{value:"max-color"}],[n.Colon,":",0,0,void 0],[n.Number,"2147477350",0,0,{value:2147477350,type:a.Integer}]],S=[[n.Ident,"color",0,0,{value:"color"}],[n.Colon,":",0,0,void 0],[n.Number,"2147477350",0,0,{value:2147477350,type:a.Integer}]];function replaceTrueAndFalseTokens(e){let r,t=[];for(let n=0;n{throw new Error(`Unable to parse media query "${l(...a)}"`)}}),f=u(i(a),{preserveInvalidMediaQueries:!0,onParseError:()=>{throw new Error(`Unable to parse media query "${l(...a)}"`)}});for(let e=0;e[n,e]))}}function getCustomMedia(e,r,t){const n=new Map,a=new Map,o=[],s=collectCascadeLayerOrder(e);e.walkAtRules((e=>{if(!isProcessableCustomMediaRule(e))return;const r=parseCustomMedia(e.params);if(!r)return;if(0===r.truthy.length)return;const i=(u=s,(l=e).parent&&"atrule"===l.parent.type&&"layer"===l.parent.name.toLowerCase()?u.has(l.parent)?u.get(l.parent)+1:0:1e7);var l,u;const c=a.get(r.name)??-1;if(i&&i>=c&&(a.set(r.name,i),n.set(r.name,{truthy:r.truthy,falsy:r.falsy}),o.push(...r.dependencies)),!t.preserve){const r=e.parent;e.remove(),removeEmptyAncestorBlocks(r)}}));const i=removeCyclicReferences(n,o);for(const t of i.values())e.warn(r,`@custom-media rules have cyclic dependencies for "${t}"`);return n}function removeEmptyAncestorBlocks(e){if(!e)return;let r=e;for(;r;){if(r.nodes&&r.nodes.length>0)return;const e=r.parent;r.remove(),r=e}}function transformAtMediaListTokens(e,r){const t=c(e,{preserveInvalidMediaQueries:!0,onParseError:()=>{throw new Error(`Unable to parse media query "${e}"`)}}),n=t.map((e=>e.toString()));for(let e=0;en===e?t:{replaceWith:r}))}const s=transformComplexMediaQuery(a,r);if(s&&0!==s.length&&s[0].replaceWith!==o)return n.flatMap(((r,t)=>t===e?s:[{replaceWith:r}]))}return[]}function transformSimpleMediaQuery(e,r){if(!mediaQueryIsSimple(e))return null;let t=null;return e.walk((e=>{const n=e.node;if(!f(n))return;const a=n.getName();if(!a.startsWith("--"))return!1;const o=r.get(a);return o?(t={replaceWith:o.truthy.map((e=>e.toString().trim())).join(",")},!1):void 0})),t}function transformComplexMediaQuery(e,r){let t=[];return e.walk((n=>{const a=n.node;if(!f(a))return;const o=n.parent;if(!p(o))return;const s=a.getName();if(!s.startsWith("--"))return!1;const i=r.get(s);if(i){if(1===i.truthy.length&&mediaQueryIsSimple(i.truthy[0])){let r=null;if(i.truthy[0].walk((e=>{if(p(e.node))return r=e.node,!1})),r&&r.feature)return o.feature=r.feature,t=[{replaceWith:e.toString()}],!1}const r=m(W[0][4].value,W[2]);o.feature=r.feature;const n=e.toString(),a=m(S[0][4].value,S[2]);o.feature=a.feature;const s=e.toString();return t=[{replaceWith:n,encapsulateWith:i.truthy.map((e=>e.toString().trim())).join(",")},{replaceWith:s,encapsulateWith:i.falsy.map((e=>e.toString().trim())).join(",")}],!1}})),t}function mediaQueryIsSimple(e){if(d(e))return!1;if(h(e))return!1;let r=!0;return e.walk((e=>{if(y(e.node)||v(e.node)||g(e.node)||w(e.node)||k(e.node))return r=!1,!1})),r}const creator=e=>{const r=e?.preserve??!1;if("importFrom"in Object(e))throw new Error('[postcss-custom-media] "importFrom" is no longer supported');if("exportTo"in Object(e))throw new Error('[postcss-custom-media] "exportTo" is no longer supported');return{postcssPlugin:"postcss-custom-media",prepare(){const e=new WeakSet;let t=new Map;return{postcssPlugin:"postcss-custom-media",Once(e,{result:n}){t=getCustomMedia(e,n,{preserve:r})},AtRule(n,{result:a}){if(e.has(n))return;if("media"!==n.name.toLowerCase())return;if(!n.params)return;if(!n.params.includes("--"))return;let o=[];try{o=transformAtMediaListTokens(n.params,t)}catch(e){return void n.warn(a,`Failed to parse @custom-media params with error message: "${e instanceof Error?e.message:e}"`)}if(!o||0===o.length)return;if(1===o.length){if(n.params.trim()===o[0].replaceWith.trim())return;return e.add(n),n.cloneBefore({params:o[0].replaceWith.trim()}),r?void 0:void n.remove()}if(!!!o.find((e=>!!e.encapsulateWith)))return e.add(n),n.cloneBefore({params:o.map((e=>e.replaceWith)).join(",").trim()}),void(r||n.remove());o.forEach((r=>{if(!r.encapsulateWith)return void n.cloneBefore({params:r.replaceWith.trim()});const t=n.clone({params:r.replaceWith}),a=n.clone({params:r.encapsulateWith.trim(),nodes:[]});t.parent=void 0,a.parent=void 0,e.add(n),a.append(t),n.before(a)})),r||n.remove()}}}}};creator.postcss=!0;export{creator as default}; diff --git a/plugins/postcss-custom-media/src/cascade-layers.ts b/plugins/postcss-custom-media/src/cascade-layers.ts index 79751908e..cdf95a694 100644 --- a/plugins/postcss-custom-media/src/cascade-layers.ts +++ b/plugins/postcss-custom-media/src/cascade-layers.ts @@ -112,6 +112,7 @@ export function cascadeLayerNumberForNode(node: Node, layers: WeakMap = (opts?: pluginOptions) => { // whether to preserve custom media and rules using them - const preserve = Boolean(Object(opts).preserve); + const preserve = opts?.preserve ?? false; if ('importFrom' in Object(opts)) { throw new Error('[postcss-custom-media] "importFrom" is no longer supported'); diff --git a/plugins/postcss-custom-media/src/toposort.ts b/plugins/postcss-custom-media/src/toposort.ts index fff20af35..4aed45536 100644 --- a/plugins/postcss-custom-media/src/toposort.ts +++ b/plugins/postcss-custom-media/src/toposort.ts @@ -46,7 +46,7 @@ export function removeCyclicReferences(nodes: Map, edges: Array function findCyclicNode(nodes: Array, edges: Array>): string | undefined { let cursor = nodes.length; - const sorted: Array = new Array(cursor); + const sorted: Array = new Array(cursor) as Array; const visited: Record = {}; let i = cursor; // Better data structures make algorithm much faster. @@ -86,6 +86,7 @@ function findCyclicNode(nodes: Array, edges: Array>): stri predecessors.add(node); do { const child = outgoing[--j]; + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const cyclicNode = visit(child, nodesHash.get(child)!, predecessors); if (!cyclicNode) { continue; @@ -110,13 +111,14 @@ function makeOutgoingEdges(arr: Array>): Map> if (!edges.has(edge[1])) { edges.set(edge[1], new Set()); } + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion edges.get(edge[0])!.add(edge[1]); } return edges; } function makeNodesHash(arr: Array): Map { - const res = new Map(); + const res: Map = new Map(); for (let i = 0, len = arr.length; i < len; i++) { res.set(arr[i], i); } diff --git a/plugins/postcss-custom-properties/dist/index.cjs b/plugins/postcss-custom-properties/dist/index.cjs index 325ad83df..55a9f5540 100644 --- a/plugins/postcss-custom-properties/dist/index.cjs +++ b/plugins/postcss-custom-properties/dist/index.cjs @@ -1 +1 @@ -"use strict";var e=require("@csstools/cascade-layer-name-parser"),t=require("postcss-value-parser"),r=require("@csstools/utilities");const n=e.parse("csstools-implicit-layer")[0];function collectCascadeLayerOrder(t){const r=new Map,o=new Map,s=[];t.walkAtRules((t=>{if("layer"!==t.name.toLowerCase())return;{let e=t.parent;for(;e;){if("atrule"!==e.type||"layer"!==e.name.toLowerCase()){if(e===t.root())break;return}e=e.parent}}let a;if(t.nodes)a=normalizeLayerName(t.params,1);else{if(!t.params.trim())return;a=t.params}let i=e.parse(a);if(i?.length){{let e=t.parent;for(;e&&"atrule"===e.type&&"layer"===e.name.toLowerCase();){const t=o.get(e);t?(i=i.map((e=>t.concat(e))),e=e.parent):e=e.parent}}if(e.addLayerToModel(s,i),t.nodes){const e=i[0].concat(n);r.set(t,e),o.set(t,i[0])}}}));for(const t of r.values())e.addLayerToModel(s,[t]);const a=new WeakMap;for(const[e,t]of r)a.set(e,s.findIndex((e=>t.equal(e))));return a}function normalizeLayerName(e,t){return e.trim()?e:"csstools-anon-layer--"+t++}const o=/(?:!\s*)?postcss-custom-properties:\s*off\b/i,s=new WeakMap;function isBlockIgnored(e){if(!e||!e.nodes)return!1;if(s.has(e))return s.get(e);const t=e.some((e=>isIgnoreComment(e,o)));return s.set(e,t),t}const a=/(?:!\s*)?postcss-custom-properties:\s*ignore\s+next\b/i;function isDeclarationIgnored(e){return!!e&&(!!isBlockIgnored(e.parent)||isIgnoreComment(e.prev(),a))}function isIgnoreComment(e,t){return!!e&&"comment"===e.type&&t.test(e.text)}const i=new Set(["layer"]);function isProcessableRule(e){let t=e.parent;for(;t;){if("atrule"===t.type&&!i.has(t.name.toLowerCase()))return!1;t=t.parent}return!0}const l=/^html$/i,c=/^:where\(html\)$/i,u=/^:root$/i,p=/^:where\(:root\)$/i,f=/(html|:root)/i,d=/^var$/i;function isVarFunction(e){return"function"===e.type&&d.test(e.value)&&Object(e.nodes).length>0}const m=/\bvar\(/i;function parseOrCached(e,r){let n=r.get(e);return n||(n=t(e),r.set(e,n),n)}function toposort(e,t){let r=e.length;const n=new Array(r),o={};let s=r;const a=makeOutgoingEdges(t),i=makeNodesHash(e);for(;s--;)o[s]||visit(e[s],s,new Set);return n;function visit(e,t,s){if(s.has(e)){let t;try{t=", node was:"+JSON.stringify(e)}catch(e){t=""}throw new Error("Cyclic dependency"+t)}if(!i.has(e))throw new Error("Found unknown node. Make sure to provided all involved nodes. Unknown node: "+JSON.stringify(e));if(o[t])return;o[t]=!0;const l=Array.from(a.get(e)||new Set);if(t=l.length){s.add(e);do{const e=l[--t];visit(e,i.get(e),s)}while(t);s.delete(e)}n[--r]=e}}function removeCyclicReferences(e,t){const r=new Set;for(;e.size>0;){const n=findCyclicNode(Array.from(e.keys()),t);if(!n)return r;e.delete(n),r.add(n),t=t.filter((e=>-1===e.indexOf(n)))}return r}function findCyclicNode(e,t){let r=e.length;const n=new Array(r),o={};let s=r;const a=makeOutgoingEdges(t),i=makeNodesHash(e);for(;s--;)if(!o[s]){const t=visit(e[s],s,new Set);if(!t)continue;return t}function visit(e,t,s){if(s.has(e))return e;if(!i.has(e))return;if(o[t])return;o[t]=!0;const l=Array.from(a.get(e)||new Set);if(t=l.length){s.add(e);do{const e=l[--t],r=visit(e,i.get(e),s);if(r)return r}while(t);s.delete(e)}n[--r]=e}}function makeOutgoingEdges(e){const t=new Map;for(let r=0,n=e.length;r{if(!isVarFunction(e))return;const s=parseVarFunction(e);if(!s)return;let a=!1;s.fallback&&t.walk(s.fallback,(e=>{if(!isVarFunction(e))return;const t=parseVarFunction(e);return t?t.fallback||r.has(t.name.value)?void 0:(a=!0,!1):void 0}));let i=r.get(s.name.value)?.nodes;i||!s.fallback||a||(i=s.fallback),void 0!==i&&(i.length?o.splice(n,1,...i):o.splice(n,1,{type:"div",value:" ",before:"",after:"",sourceIndex:e.sourceIndex,sourceEndIndex:e.sourceEndIndex}))})),t.stringify(e.nodes)):""}function walk(e,t){let r,n,o;for(r=0,n=e.length;r"comment"!==e.type&&"space"!==e.type));return 1===t.length&&("word"===t[0].type&&v.test(t[0].value))}function buildCustomPropertiesMap(e,r,n){if(!e.size)return r;const o=new Map(r);{const s=[];for(const[a,i]of e.entries()){const l=parseOrCached(i,n);let c=!1;t.walk(l.nodes,(t=>{if(!isVarFunction(t))return;const n=parseVarFunction(t);n&&(n.fallback||e.has(n.name.value)||r.has(n.name.value)?s.push([n.name.value,a]):c=!0)})),c||o.set(a,l)}removeCyclicReferences(o,s)}{const e=[];for(const[r,n]of o.entries())t.walk(n.nodes,(t=>{if(!isVarFunction(t))return;const n=parseVarFunction(t);n&&(n.fallback||o.has(n.name.value)?e.push([n.name.value,r]):o.delete(r))}));for(let t=0;t{f.test(e.selector)&&e.nodes?.length&&isProcessableRule(e)&&(isBlockIgnored(e)||e.selectors.forEach((t=>{let s=-1;if(c.test(t)||p.test(t))s=0;else if(l.test(t))s=1;else{if(!u.test(t))return;s=2}const a=(f=o,((i=e).parent&&"atrule"===i.parent.type&&"layer"===i.parent.name.toLowerCase()?f.has(i.parent)?f.get(i.parent)+1:0:1e7)+10+s);var i,f;e.each((e=>{if("decl"!==e.type)return;if(!e.variable||isDeclarationIgnored(e))return;if("initial"===e.value.toLowerCase().trim())return;const t=n.get(e.prop)??-1;a>=t&&(n.set(e.prop,a),r.set(e.prop,e.value))}))})))})),buildCustomPropertiesMap(r,new Map,t)}function getCustomPropertiesFromSiblings(e,t,r){if(!e.parent)return t;const n=new Map;return e.parent.each((t=>{"decl"===t.type&&t.variable&&e!==t&&(isDeclarationIgnored(t)||n.set(t.prop,t.value))})),n.size?buildCustomPropertiesMap(n,t,r):t}function transformProperties(e,r,n){if(isTransformableDecl(e)&&!isDeclarationIgnored(e)){const o=e.value,s=transformValueAST(t(o),r);if(s===o)return;if(parentHasExactFallback(e,s))return void(n.preserve||e.remove());if(n.preserve){const t=e.cloneBefore({value:s});hasTrailingComment(t)&&t.raws?.value&&(t.raws.value.value=t.value.replace(w,"$1"),t.raws.value.raw=t.raws.value.value+t.raws.value.raw.replace(w,"$2"))}else e.value=s,hasTrailingComment(e)&&e.raws?.value&&(e.raws.value.value=e.value.replace(w,"$1"),e.raws.value.raw=e.raws.value.value+e.raws.value.raw.replace(w,"$2"))}}const isTransformableDecl=e=>!e.variable&&e.value.includes("--")&&e.value.toLowerCase().includes("var("),hasTrailingComment=e=>"value"in Object(Object(e.raws).value)&&"raw"in(e.raws?.value??{})&&w.test(e.raws.value?.raw??""),w=/^([\W\w]+)(\s*\/\*[\W\w]+?\*\/)$/;function parentHasExactFallback(e,t){if(!e||!e.parent)return!1;let r=!1;const n=e.parent.index(e);return e.parent.each(((o,s)=>o!==e&&(!(s>=n)&&void("decl"===o.type&&o.prop.toLowerCase()===e.prop.toLowerCase()&&o.value===t&&(r=!0))))),r}const g=/\bvar\(|\(top: var\(--f\)/i,creator=e=>{const t=!("preserve"in Object(e))||Boolean(e?.preserve);if("importFrom"in Object(e))throw new Error('[postcss-custom-properties] "importFrom" is no longer supported');if("exportTo"in Object(e))throw new Error('[postcss-custom-properties] "exportTo" is no longer supported');return{postcssPlugin:"postcss-custom-properties",prepare(){let e=new Map;const n=new WeakMap,o=new Map;return{postcssPlugin:"postcss-custom-properties",Once(t){e=getCustomPropertiesFromRoot(t,o)},Declaration(s){if(!m.test(s.value))return;if(r.hasSupportsAtRuleAncestor(s,g))return;let a=e;t&&s.parent&&(a=n.get(s.parent)??getCustomPropertiesFromSiblings(s,e,o),n.set(s.parent,a)),transformProperties(s,a,{preserve:t})}}}}};creator.postcss=!0,module.exports=creator; +"use strict";var e=require("@csstools/cascade-layer-name-parser"),t=require("postcss-value-parser"),r=require("@csstools/utilities");const n=e.parse("csstools-implicit-layer")[0];function collectCascadeLayerOrder(t){const r=new Map,o=new Map,s=[];t.walkAtRules((t=>{if("layer"!==t.name.toLowerCase())return;{let e=t.parent;for(;e;){if("atrule"!==e.type||"layer"!==e.name.toLowerCase()){if(e===t.root())break;return}e=e.parent}}let a;if(t.nodes)a=normalizeLayerName(t.params,1);else{if(!t.params.trim())return;a=t.params}let i=e.parse(a);if(i?.length){{let e=t.parent;for(;e&&"atrule"===e.type&&"layer"===e.name.toLowerCase();){const t=o.get(e);t?(i=i.map((e=>t.concat(e))),e=e.parent):e=e.parent}}if(e.addLayerToModel(s,i),t.nodes){const e=i[0].concat(n);r.set(t,e),o.set(t,i[0])}}}));for(const t of r.values())e.addLayerToModel(s,[t]);const a=new WeakMap;for(const[e,t]of r)a.set(e,s.findIndex((e=>t.equal(e))));return a}function normalizeLayerName(e,t){return e.trim()?e:"csstools-anon-layer--"+t++}const o=/(?:!\s*)?postcss-custom-properties:\s*off\b/i,s=new WeakMap;function isBlockIgnored(e){if(!e||!e.nodes)return!1;if(s.has(e))return s.get(e);const t=e.some((e=>isIgnoreComment(e,o)));return s.set(e,t),t}const a=/(?:!\s*)?postcss-custom-properties:\s*ignore\s+next\b/i;function isDeclarationIgnored(e){return!!e&&(!!isBlockIgnored(e.parent)||isIgnoreComment(e.prev(),a))}function isIgnoreComment(e,t){return!!e&&"comment"===e.type&&t.test(e.text)}const i=new Set(["layer"]);function isProcessableRule(e){let t=e.parent;for(;t;){if("atrule"===t.type&&!i.has(t.name.toLowerCase()))return!1;t=t.parent}return!0}const l=/^html$/i,c=/^:where\(html\)$/i,u=/^:root$/i,p=/^:where\(:root\)$/i,f=/(html|:root)/i,d=/^var$/i;function isVarFunction(e){return"function"===e.type&&d.test(e.value)&&e.nodes?.length>0}const m=/\bvar\(/i;function parseOrCached(e,r){let n=r.get(e);return n||(n=t(e),r.set(e,n),n)}function toposort(e,t){let r=e.length;const n=new Array(r),o={};let s=r;const a=makeOutgoingEdges(t),i=makeNodesHash(e);for(;s--;)o[s]||visit(e[s],s,new Set);return n;function visit(e,t,s){if(s.has(e)){let t;try{t=", node was:"+JSON.stringify(e)}catch{t=""}throw new Error("Cyclic dependency"+t)}if(!i.has(e))throw new Error("Found unknown node. Make sure to provided all involved nodes. Unknown node: "+JSON.stringify(e));if(o[t])return;o[t]=!0;const l=Array.from(a.get(e)||new Set);if(t=l.length){s.add(e);do{const e=l[--t];visit(e,i.get(e),s)}while(t);s.delete(e)}n[--r]=e}}function removeCyclicReferences(e,t){const r=new Set;for(;e.size>0;){const n=findCyclicNode(Array.from(e.keys()),t);if(!n)return r;e.delete(n),r.add(n),t=t.filter((e=>-1===e.indexOf(n)))}return r}function findCyclicNode(e,t){let r=e.length;const n=new Array(r),o={};let s=r;const a=makeOutgoingEdges(t),i=makeNodesHash(e);for(;s--;)if(!o[s]){const t=visit(e[s],s,new Set);if(!t)continue;return t}function visit(e,t,s){if(s.has(e))return e;if(!i.has(e))return;if(o[t])return;o[t]=!0;const l=Array.from(a.get(e)||new Set);if(t=l.length){s.add(e);do{const e=l[--t],r=visit(e,i.get(e),s);if(r)return r}while(t);s.delete(e)}n[--r]=e}}function makeOutgoingEdges(e){const t=new Map;for(let r=0,n=e.length;r{if(!isVarFunction(e))return;const s=parseVarFunction(e);if(!s)return;let a=!1;s.fallback&&t.walk(s.fallback,(e=>{if(!isVarFunction(e))return;const t=parseVarFunction(e);return t?t.fallback||r.has(t.name.value)?void 0:(a=!0,!1):void 0}));let i=r.get(s.name.value)?.nodes;i||!s.fallback||a||(i=s.fallback),void 0!==i&&(i.length?o.splice(n,1,...i):o.splice(n,1,{type:"div",value:" ",before:"",after:"",sourceIndex:e.sourceIndex,sourceEndIndex:e.sourceEndIndex}))})),t.stringify(e.nodes)):""}function walk(e,t){let r,n,o;for(r=0,n=e.length;r"comment"!==e.type&&"space"!==e.type));return 1===t.length&&("word"===t[0].type&&v.test(t[0].value))}function buildCustomPropertiesMap(e,r,n){if(!e.size)return r;const o=new Map(r);{const s=[];for(const[a,i]of e.entries()){const l=parseOrCached(i,n);let c=!1;t.walk(l.nodes,(t=>{if(!isVarFunction(t))return;const n=parseVarFunction(t);n&&(n.fallback||e.has(n.name.value)||r.has(n.name.value)?s.push([n.name.value,a]):c=!0)})),c||o.set(a,l)}removeCyclicReferences(o,s)}{const e=[];for(const[r,n]of o.entries())t.walk(n.nodes,(t=>{if(!isVarFunction(t))return;const n=parseVarFunction(t);n&&(n.fallback||o.has(n.name.value)?e.push([n.name.value,r]):o.delete(r))}));for(let t=0;t{f.test(e.selector)&&e.nodes?.length&&isProcessableRule(e)&&(isBlockIgnored(e)||e.selectors.forEach((t=>{let s=-1;if(c.test(t)||p.test(t))s=0;else if(l.test(t))s=1;else{if(!u.test(t))return;s=2}const a=(f=o,((i=e).parent&&"atrule"===i.parent.type&&"layer"===i.parent.name.toLowerCase()?f.has(i.parent)?f.get(i.parent)+1:0:1e7)+10+s);var i,f;e.each((e=>{if("decl"!==e.type)return;if(!e.variable||isDeclarationIgnored(e))return;if("initial"===e.value.toLowerCase().trim())return;const t=n.get(e.prop)??-1;a>=t&&(n.set(e.prop,a),r.set(e.prop,e.value))}))})))})),buildCustomPropertiesMap(r,new Map,t)}function getCustomPropertiesFromSiblings(e,t,r){if(!e.parent)return t;const n=new Map;return e.parent.each((t=>{"decl"===t.type&&t.variable&&e!==t&&(isDeclarationIgnored(t)||n.set(t.prop,t.value))})),n.size?buildCustomPropertiesMap(n,t,r):t}function transformProperties(e,r,n){if(isTransformableDecl(e)&&!isDeclarationIgnored(e)){const o=e.value,s=transformValueAST(t(o),r);if(s===o)return;if(parentHasExactFallback(e,s))return void(n.preserve||e.remove());if(n.preserve){const t=e.cloneBefore({value:s});hasTrailingComment(t)&&t.raws?.value&&(t.raws.value.value=t.value.replace(w,"$1"),t.raws.value.raw=t.raws.value.value+t.raws.value.raw.replace(w,"$2"))}else e.value=s,hasTrailingComment(e)&&e.raws?.value&&(e.raws.value.value=e.value.replace(w,"$1"),e.raws.value.raw=e.raws.value.value+e.raws.value.raw.replace(w,"$2"))}}const isTransformableDecl=e=>!e.variable&&e.value.includes("--")&&e.value.toLowerCase().includes("var("),hasTrailingComment=e=>"value"in Object(Object(e.raws).value)&&"raw"in(e.raws?.value??{})&&w.test(e.raws.value?.raw??""),w=/^([\W\w]+)(\s*\/\*[\W\w]+?\*\/)$/;function parentHasExactFallback(e,t){if(!e||!e.parent)return!1;let r=!1;const n=e.parent.index(e);return e.parent.each(((o,s)=>o!==e&&(!(s>=n)&&void("decl"===o.type&&o.prop.toLowerCase()===e.prop.toLowerCase()&&o.value===t&&(r=!0))))),r}const g=/\bvar\(|\(top: var\(--f\)/i,creator=e=>{const t=!("preserve"in Object(e))||Boolean(e?.preserve);if("importFrom"in Object(e))throw new Error('[postcss-custom-properties] "importFrom" is no longer supported');if("exportTo"in Object(e))throw new Error('[postcss-custom-properties] "exportTo" is no longer supported');return{postcssPlugin:"postcss-custom-properties",prepare(){let e=new Map;const n=new WeakMap,o=new Map;return{postcssPlugin:"postcss-custom-properties",Once(t){e=getCustomPropertiesFromRoot(t,o)},Declaration(s){if(!m.test(s.value))return;if(r.hasSupportsAtRuleAncestor(s,g))return;let a=e;t&&s.parent&&(a=n.get(s.parent)??getCustomPropertiesFromSiblings(s,e,o),n.set(s.parent,a)),transformProperties(s,a,{preserve:t})}}}}};creator.postcss=!0,module.exports=creator; diff --git a/plugins/postcss-custom-properties/dist/index.mjs b/plugins/postcss-custom-properties/dist/index.mjs index 1ccb53dfe..83c0c47e9 100644 --- a/plugins/postcss-custom-properties/dist/index.mjs +++ b/plugins/postcss-custom-properties/dist/index.mjs @@ -1 +1 @@ -import{parse as e,addLayerToModel as t}from"@csstools/cascade-layer-name-parser";import r from"postcss-value-parser";import{hasSupportsAtRuleAncestor as n}from"@csstools/utilities";const o=e("csstools-implicit-layer")[0];function collectCascadeLayerOrder(r){const n=new Map,s=new Map,a=[];r.walkAtRules((r=>{if("layer"!==r.name.toLowerCase())return;{let e=r.parent;for(;e;){if("atrule"!==e.type||"layer"!==e.name.toLowerCase()){if(e===r.root())break;return}e=e.parent}}let i;if(r.nodes)i=normalizeLayerName(r.params,1);else{if(!r.params.trim())return;i=r.params}let l=e(i);if(l?.length){{let e=r.parent;for(;e&&"atrule"===e.type&&"layer"===e.name.toLowerCase();){const t=s.get(e);t?(l=l.map((e=>t.concat(e))),e=e.parent):e=e.parent}}if(t(a,l),r.nodes){const e=l[0].concat(o);n.set(r,e),s.set(r,l[0])}}}));for(const e of n.values())t(a,[e]);const i=new WeakMap;for(const[e,t]of n)i.set(e,a.findIndex((e=>t.equal(e))));return i}function normalizeLayerName(e,t){return e.trim()?e:"csstools-anon-layer--"+t++}const s=/(?:!\s*)?postcss-custom-properties:\s*off\b/i,a=new WeakMap;function isBlockIgnored(e){if(!e||!e.nodes)return!1;if(a.has(e))return a.get(e);const t=e.some((e=>isIgnoreComment(e,s)));return a.set(e,t),t}const i=/(?:!\s*)?postcss-custom-properties:\s*ignore\s+next\b/i;function isDeclarationIgnored(e){return!!e&&(!!isBlockIgnored(e.parent)||isIgnoreComment(e.prev(),i))}function isIgnoreComment(e,t){return!!e&&"comment"===e.type&&t.test(e.text)}const l=new Set(["layer"]);function isProcessableRule(e){let t=e.parent;for(;t;){if("atrule"===t.type&&!l.has(t.name.toLowerCase()))return!1;t=t.parent}return!0}const c=/^html$/i,u=/^:where\(html\)$/i,p=/^:root$/i,f=/^:where\(:root\)$/i,d=/(html|:root)/i,m=/^var$/i;function isVarFunction(e){return"function"===e.type&&m.test(e.value)&&Object(e.nodes).length>0}const v=/\bvar\(/i;function parseOrCached(e,t){let n=t.get(e);return n||(n=r(e),t.set(e,n),n)}function toposort(e,t){let r=e.length;const n=new Array(r),o={};let s=r;const a=makeOutgoingEdges(t),i=makeNodesHash(e);for(;s--;)o[s]||visit(e[s],s,new Set);return n;function visit(e,t,s){if(s.has(e)){let t;try{t=", node was:"+JSON.stringify(e)}catch(e){t=""}throw new Error("Cyclic dependency"+t)}if(!i.has(e))throw new Error("Found unknown node. Make sure to provided all involved nodes. Unknown node: "+JSON.stringify(e));if(o[t])return;o[t]=!0;const l=Array.from(a.get(e)||new Set);if(t=l.length){s.add(e);do{const e=l[--t];visit(e,i.get(e),s)}while(t);s.delete(e)}n[--r]=e}}function removeCyclicReferences(e,t){const r=new Set;for(;e.size>0;){const n=findCyclicNode(Array.from(e.keys()),t);if(!n)return r;e.delete(n),r.add(n),t=t.filter((e=>-1===e.indexOf(n)))}return r}function findCyclicNode(e,t){let r=e.length;const n=new Array(r),o={};let s=r;const a=makeOutgoingEdges(t),i=makeNodesHash(e);for(;s--;)if(!o[s]){const t=visit(e[s],s,new Set);if(!t)continue;return t}function visit(e,t,s){if(s.has(e))return e;if(!i.has(e))return;if(o[t])return;o[t]=!0;const l=Array.from(a.get(e)||new Set);if(t=l.length){s.add(e);do{const e=l[--t],r=visit(e,i.get(e),s);if(r)return r}while(t);s.delete(e)}n[--r]=e}}function makeOutgoingEdges(e){const t=new Map;for(let r=0,n=e.length;r{if(!isVarFunction(e))return;const s=parseVarFunction(e);if(!s)return;let a=!1;s.fallback&&r.walk(s.fallback,(e=>{if(!isVarFunction(e))return;const r=parseVarFunction(e);return r?r.fallback||t.has(r.name.value)?void 0:(a=!0,!1):void 0}));let i=t.get(s.name.value)?.nodes;i||!s.fallback||a||(i=s.fallback),void 0!==i&&(i.length?o.splice(n,1,...i):o.splice(n,1,{type:"div",value:" ",before:"",after:"",sourceIndex:e.sourceIndex,sourceEndIndex:e.sourceEndIndex}))})),r.stringify(e.nodes)):""}function walk(e,t){let r,n,o;for(r=0,n=e.length;r"comment"!==e.type&&"space"!==e.type));return 1===t.length&&("word"===t[0].type&&w.test(t[0].value))}function buildCustomPropertiesMap(e,t,n){if(!e.size)return t;const o=new Map(t);{const s=[];for(const[a,i]of e.entries()){const l=parseOrCached(i,n);let c=!1;r.walk(l.nodes,(r=>{if(!isVarFunction(r))return;const n=parseVarFunction(r);n&&(n.fallback||e.has(n.name.value)||t.has(n.name.value)?s.push([n.name.value,a]):c=!0)})),c||o.set(a,l)}removeCyclicReferences(o,s)}{const e=[];for(const[t,n]of o.entries())r.walk(n.nodes,(r=>{if(!isVarFunction(r))return;const n=parseVarFunction(r);n&&(n.fallback||o.has(n.name.value)?e.push([n.name.value,t]):o.delete(t))}));for(let t=0;t{d.test(e.selector)&&e.nodes?.length&&isProcessableRule(e)&&(isBlockIgnored(e)||e.selectors.forEach((t=>{let s=-1;if(u.test(t)||f.test(t))s=0;else if(c.test(t))s=1;else{if(!p.test(t))return;s=2}const a=(l=o,((i=e).parent&&"atrule"===i.parent.type&&"layer"===i.parent.name.toLowerCase()?l.has(i.parent)?l.get(i.parent)+1:0:1e7)+10+s);var i,l;e.each((e=>{if("decl"!==e.type)return;if(!e.variable||isDeclarationIgnored(e))return;if("initial"===e.value.toLowerCase().trim())return;const t=n.get(e.prop)??-1;a>=t&&(n.set(e.prop,a),r.set(e.prop,e.value))}))})))})),buildCustomPropertiesMap(r,new Map,t)}function getCustomPropertiesFromSiblings(e,t,r){if(!e.parent)return t;const n=new Map;return e.parent.each((t=>{"decl"===t.type&&t.variable&&e!==t&&(isDeclarationIgnored(t)||n.set(t.prop,t.value))})),n.size?buildCustomPropertiesMap(n,t,r):t}function transformProperties(e,t,n){if(isTransformableDecl(e)&&!isDeclarationIgnored(e)){const o=e.value,s=transformValueAST(r(o),t);if(s===o)return;if(parentHasExactFallback(e,s))return void(n.preserve||e.remove());if(n.preserve){const t=e.cloneBefore({value:s});hasTrailingComment(t)&&t.raws?.value&&(t.raws.value.value=t.value.replace(g,"$1"),t.raws.value.raw=t.raws.value.value+t.raws.value.raw.replace(g,"$2"))}else e.value=s,hasTrailingComment(e)&&e.raws?.value&&(e.raws.value.value=e.value.replace(g,"$1"),e.raws.value.raw=e.raws.value.value+e.raws.value.raw.replace(g,"$2"))}}const isTransformableDecl=e=>!e.variable&&e.value.includes("--")&&e.value.toLowerCase().includes("var("),hasTrailingComment=e=>"value"in Object(Object(e.raws).value)&&"raw"in(e.raws?.value??{})&&g.test(e.raws.value?.raw??""),g=/^([\W\w]+)(\s*\/\*[\W\w]+?\*\/)$/;function parentHasExactFallback(e,t){if(!e||!e.parent)return!1;let r=!1;const n=e.parent.index(e);return e.parent.each(((o,s)=>o!==e&&(!(s>=n)&&void("decl"===o.type&&o.prop.toLowerCase()===e.prop.toLowerCase()&&o.value===t&&(r=!0))))),r}const h=/\bvar\(|\(top: var\(--f\)/i,creator=e=>{const t=!("preserve"in Object(e))||Boolean(e?.preserve);if("importFrom"in Object(e))throw new Error('[postcss-custom-properties] "importFrom" is no longer supported');if("exportTo"in Object(e))throw new Error('[postcss-custom-properties] "exportTo" is no longer supported');return{postcssPlugin:"postcss-custom-properties",prepare(){let e=new Map;const r=new WeakMap,o=new Map;return{postcssPlugin:"postcss-custom-properties",Once(t){e=getCustomPropertiesFromRoot(t,o)},Declaration(s){if(!v.test(s.value))return;if(n(s,h))return;let a=e;t&&s.parent&&(a=r.get(s.parent)??getCustomPropertiesFromSiblings(s,e,o),r.set(s.parent,a)),transformProperties(s,a,{preserve:t})}}}}};creator.postcss=!0;export{creator as default}; +import{parse as e,addLayerToModel as t}from"@csstools/cascade-layer-name-parser";import r from"postcss-value-parser";import{hasSupportsAtRuleAncestor as n}from"@csstools/utilities";const o=e("csstools-implicit-layer")[0];function collectCascadeLayerOrder(r){const n=new Map,s=new Map,a=[];r.walkAtRules((r=>{if("layer"!==r.name.toLowerCase())return;{let e=r.parent;for(;e;){if("atrule"!==e.type||"layer"!==e.name.toLowerCase()){if(e===r.root())break;return}e=e.parent}}let i;if(r.nodes)i=normalizeLayerName(r.params,1);else{if(!r.params.trim())return;i=r.params}let l=e(i);if(l?.length){{let e=r.parent;for(;e&&"atrule"===e.type&&"layer"===e.name.toLowerCase();){const t=s.get(e);t?(l=l.map((e=>t.concat(e))),e=e.parent):e=e.parent}}if(t(a,l),r.nodes){const e=l[0].concat(o);n.set(r,e),s.set(r,l[0])}}}));for(const e of n.values())t(a,[e]);const i=new WeakMap;for(const[e,t]of n)i.set(e,a.findIndex((e=>t.equal(e))));return i}function normalizeLayerName(e,t){return e.trim()?e:"csstools-anon-layer--"+t++}const s=/(?:!\s*)?postcss-custom-properties:\s*off\b/i,a=new WeakMap;function isBlockIgnored(e){if(!e||!e.nodes)return!1;if(a.has(e))return a.get(e);const t=e.some((e=>isIgnoreComment(e,s)));return a.set(e,t),t}const i=/(?:!\s*)?postcss-custom-properties:\s*ignore\s+next\b/i;function isDeclarationIgnored(e){return!!e&&(!!isBlockIgnored(e.parent)||isIgnoreComment(e.prev(),i))}function isIgnoreComment(e,t){return!!e&&"comment"===e.type&&t.test(e.text)}const l=new Set(["layer"]);function isProcessableRule(e){let t=e.parent;for(;t;){if("atrule"===t.type&&!l.has(t.name.toLowerCase()))return!1;t=t.parent}return!0}const c=/^html$/i,u=/^:where\(html\)$/i,p=/^:root$/i,f=/^:where\(:root\)$/i,d=/(html|:root)/i,m=/^var$/i;function isVarFunction(e){return"function"===e.type&&m.test(e.value)&&e.nodes?.length>0}const v=/\bvar\(/i;function parseOrCached(e,t){let n=t.get(e);return n||(n=r(e),t.set(e,n),n)}function toposort(e,t){let r=e.length;const n=new Array(r),o={};let s=r;const a=makeOutgoingEdges(t),i=makeNodesHash(e);for(;s--;)o[s]||visit(e[s],s,new Set);return n;function visit(e,t,s){if(s.has(e)){let t;try{t=", node was:"+JSON.stringify(e)}catch{t=""}throw new Error("Cyclic dependency"+t)}if(!i.has(e))throw new Error("Found unknown node. Make sure to provided all involved nodes. Unknown node: "+JSON.stringify(e));if(o[t])return;o[t]=!0;const l=Array.from(a.get(e)||new Set);if(t=l.length){s.add(e);do{const e=l[--t];visit(e,i.get(e),s)}while(t);s.delete(e)}n[--r]=e}}function removeCyclicReferences(e,t){const r=new Set;for(;e.size>0;){const n=findCyclicNode(Array.from(e.keys()),t);if(!n)return r;e.delete(n),r.add(n),t=t.filter((e=>-1===e.indexOf(n)))}return r}function findCyclicNode(e,t){let r=e.length;const n=new Array(r),o={};let s=r;const a=makeOutgoingEdges(t),i=makeNodesHash(e);for(;s--;)if(!o[s]){const t=visit(e[s],s,new Set);if(!t)continue;return t}function visit(e,t,s){if(s.has(e))return e;if(!i.has(e))return;if(o[t])return;o[t]=!0;const l=Array.from(a.get(e)||new Set);if(t=l.length){s.add(e);do{const e=l[--t],r=visit(e,i.get(e),s);if(r)return r}while(t);s.delete(e)}n[--r]=e}}function makeOutgoingEdges(e){const t=new Map;for(let r=0,n=e.length;r{if(!isVarFunction(e))return;const s=parseVarFunction(e);if(!s)return;let a=!1;s.fallback&&r.walk(s.fallback,(e=>{if(!isVarFunction(e))return;const r=parseVarFunction(e);return r?r.fallback||t.has(r.name.value)?void 0:(a=!0,!1):void 0}));let i=t.get(s.name.value)?.nodes;i||!s.fallback||a||(i=s.fallback),void 0!==i&&(i.length?o.splice(n,1,...i):o.splice(n,1,{type:"div",value:" ",before:"",after:"",sourceIndex:e.sourceIndex,sourceEndIndex:e.sourceEndIndex}))})),r.stringify(e.nodes)):""}function walk(e,t){let r,n,o;for(r=0,n=e.length;r"comment"!==e.type&&"space"!==e.type));return 1===t.length&&("word"===t[0].type&&w.test(t[0].value))}function buildCustomPropertiesMap(e,t,n){if(!e.size)return t;const o=new Map(t);{const s=[];for(const[a,i]of e.entries()){const l=parseOrCached(i,n);let c=!1;r.walk(l.nodes,(r=>{if(!isVarFunction(r))return;const n=parseVarFunction(r);n&&(n.fallback||e.has(n.name.value)||t.has(n.name.value)?s.push([n.name.value,a]):c=!0)})),c||o.set(a,l)}removeCyclicReferences(o,s)}{const e=[];for(const[t,n]of o.entries())r.walk(n.nodes,(r=>{if(!isVarFunction(r))return;const n=parseVarFunction(r);n&&(n.fallback||o.has(n.name.value)?e.push([n.name.value,t]):o.delete(t))}));for(let t=0;t{d.test(e.selector)&&e.nodes?.length&&isProcessableRule(e)&&(isBlockIgnored(e)||e.selectors.forEach((t=>{let s=-1;if(u.test(t)||f.test(t))s=0;else if(c.test(t))s=1;else{if(!p.test(t))return;s=2}const a=(l=o,((i=e).parent&&"atrule"===i.parent.type&&"layer"===i.parent.name.toLowerCase()?l.has(i.parent)?l.get(i.parent)+1:0:1e7)+10+s);var i,l;e.each((e=>{if("decl"!==e.type)return;if(!e.variable||isDeclarationIgnored(e))return;if("initial"===e.value.toLowerCase().trim())return;const t=n.get(e.prop)??-1;a>=t&&(n.set(e.prop,a),r.set(e.prop,e.value))}))})))})),buildCustomPropertiesMap(r,new Map,t)}function getCustomPropertiesFromSiblings(e,t,r){if(!e.parent)return t;const n=new Map;return e.parent.each((t=>{"decl"===t.type&&t.variable&&e!==t&&(isDeclarationIgnored(t)||n.set(t.prop,t.value))})),n.size?buildCustomPropertiesMap(n,t,r):t}function transformProperties(e,t,n){if(isTransformableDecl(e)&&!isDeclarationIgnored(e)){const o=e.value,s=transformValueAST(r(o),t);if(s===o)return;if(parentHasExactFallback(e,s))return void(n.preserve||e.remove());if(n.preserve){const t=e.cloneBefore({value:s});hasTrailingComment(t)&&t.raws?.value&&(t.raws.value.value=t.value.replace(g,"$1"),t.raws.value.raw=t.raws.value.value+t.raws.value.raw.replace(g,"$2"))}else e.value=s,hasTrailingComment(e)&&e.raws?.value&&(e.raws.value.value=e.value.replace(g,"$1"),e.raws.value.raw=e.raws.value.value+e.raws.value.raw.replace(g,"$2"))}}const isTransformableDecl=e=>!e.variable&&e.value.includes("--")&&e.value.toLowerCase().includes("var("),hasTrailingComment=e=>"value"in Object(Object(e.raws).value)&&"raw"in(e.raws?.value??{})&&g.test(e.raws.value?.raw??""),g=/^([\W\w]+)(\s*\/\*[\W\w]+?\*\/)$/;function parentHasExactFallback(e,t){if(!e||!e.parent)return!1;let r=!1;const n=e.parent.index(e);return e.parent.each(((o,s)=>o!==e&&(!(s>=n)&&void("decl"===o.type&&o.prop.toLowerCase()===e.prop.toLowerCase()&&o.value===t&&(r=!0))))),r}const h=/\bvar\(|\(top: var\(--f\)/i,creator=e=>{const t=!("preserve"in Object(e))||Boolean(e?.preserve);if("importFrom"in Object(e))throw new Error('[postcss-custom-properties] "importFrom" is no longer supported');if("exportTo"in Object(e))throw new Error('[postcss-custom-properties] "exportTo" is no longer supported');return{postcssPlugin:"postcss-custom-properties",prepare(){let e=new Map;const r=new WeakMap,o=new Map;return{postcssPlugin:"postcss-custom-properties",Once(t){e=getCustomPropertiesFromRoot(t,o)},Declaration(s){if(!v.test(s.value))return;if(n(s,h))return;let a=e;t&&s.parent&&(a=r.get(s.parent)??getCustomPropertiesFromSiblings(s,e,o),r.set(s.parent,a)),transformProperties(s,a,{preserve:t})}}}}};creator.postcss=!0;export{creator as default}; diff --git a/plugins/postcss-custom-properties/src/cascade-layers.ts b/plugins/postcss-custom-properties/src/cascade-layers.ts index 79751908e..cdf95a694 100644 --- a/plugins/postcss-custom-properties/src/cascade-layers.ts +++ b/plugins/postcss-custom-properties/src/cascade-layers.ts @@ -112,6 +112,7 @@ export function cascadeLayerNumberForNode(node: Node, layers: WeakMap = new WeakMap(); export function isBlockIgnored(container: Container | undefined): boolean { if (!container || !container.nodes) { @@ -10,7 +10,8 @@ export function isBlockIgnored(container: Container | undefined): boolean { } if (blockIgnoredCache.has(container)) { - return blockIgnoredCache.get(container); + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + return blockIgnoredCache.get(container)!; } const result = container.some((child) => isIgnoreComment(child, blockRegExp)); diff --git a/plugins/postcss-custom-properties/src/is-var-function.ts b/plugins/postcss-custom-properties/src/is-var-function.ts index efbfe5fe1..fa080d34a 100644 --- a/plugins/postcss-custom-properties/src/is-var-function.ts +++ b/plugins/postcss-custom-properties/src/is-var-function.ts @@ -5,7 +5,7 @@ const IS_VAR_FUNCTION_REGEX = /^var$/i; // whether the node is a var() function export function isVarFunction(node: Node): node is FunctionNode { - return node.type === 'function' && IS_VAR_FUNCTION_REGEX.test(node.value) && Object(node.nodes).length > 0; + return node.type === 'function' && IS_VAR_FUNCTION_REGEX.test(node.value) && node.nodes?.length > 0; } export const HAS_VAR_FUNCTION_REGEX = /\bvar\(/i; diff --git a/plugins/postcss-custom-properties/src/toposort.ts b/plugins/postcss-custom-properties/src/toposort.ts index 00d613d32..de7390ea8 100644 --- a/plugins/postcss-custom-properties/src/toposort.ts +++ b/plugins/postcss-custom-properties/src/toposort.ts @@ -21,7 +21,7 @@ export function toposort(nodes: Array, edges: Array>): Array { let cursor = nodes.length; - const sorted: Array = new Array(cursor); + const sorted: Array = new Array(cursor) as Array; const visited: Record = {}; let i = cursor; // Better data structures make algorithm much faster. @@ -41,7 +41,7 @@ export function toposort(nodes: Array, edges: Array>): Arr let nodeRep; try { nodeRep = ', node was:' + JSON.stringify(node); - } catch (e) { + } catch { nodeRep = ''; } throw new Error('Cyclic dependency' + nodeRep); @@ -63,6 +63,7 @@ export function toposort(nodes: Array, edges: Array>): Arr predecessors.add(node); do { const child = outgoing[--j]; + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion visit(child, nodesHash.get(child)!, predecessors); } while (j); predecessors.delete(node); @@ -99,7 +100,7 @@ export function removeCyclicReferences(nodes: Map, edges: Array function findCyclicNode(nodes: Array, edges: Array>): string | undefined { let cursor = nodes.length; - const sorted: Array = new Array(cursor); + const sorted: Array = new Array(cursor) as Array; const visited: Record = {}; let i = cursor; // Better data structures make algorithm much faster. @@ -139,6 +140,7 @@ function findCyclicNode(nodes: Array, edges: Array>): stri predecessors.add(node); do { const child = outgoing[--j]; + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const cyclicNode = visit(child, nodesHash.get(child)!, predecessors); if (!cyclicNode) { continue; @@ -163,13 +165,14 @@ function makeOutgoingEdges(arr: Array>): Map> if (!edges.has(edge[1])) { edges.set(edge[1], new Set()); } + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion edges.get(edge[0])!.add(edge[1]); } return edges; } function makeNodesHash(arr: Array): Map { - const res = new Map(); + const res: Map = new Map(); for (let i = 0, len = arr.length; i < len; i++) { res.set(arr[i], i); } diff --git a/plugins/postcss-custom-properties/src/transform-properties.ts b/plugins/postcss-custom-properties/src/transform-properties.ts index 053e75bc7..ba521e77f 100644 --- a/plugins/postcss-custom-properties/src/transform-properties.ts +++ b/plugins/postcss-custom-properties/src/transform-properties.ts @@ -47,6 +47,7 @@ export function transformProperties(decl: Declaration, customProperties: Map !decl.variable && decl.value.includes('--') && decl.value.toLowerCase().includes('var('); // whether the declaration has a trailing comment +// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access const hasTrailingComment = (decl: Declaration): boolean => 'value' in Object(Object(decl.raws).value) && ('raw' in (decl.raws?.value ?? {})) && TRAILING_COMMENT_REGEX.test(decl.raws.value?.raw ?? ''); const TRAILING_COMMENT_REGEX = /^([\W\w]+)(\s*\/\*[\W\w]+?\*\/)$/; diff --git a/plugins/postcss-custom-selectors/dist/index.cjs b/plugins/postcss-custom-selectors/dist/index.cjs index 693730659..a088dd20e 100644 --- a/plugins/postcss-custom-selectors/dist/index.cjs +++ b/plugins/postcss-custom-selectors/dist/index.cjs @@ -1 +1 @@ -"use strict";var e=require("postcss-selector-parser"),r=require("@csstools/cascade-layer-name-parser");const t=r.parse("csstools-implicit-layer")[0];function collectCascadeLayerOrder(e){const s=new Map,o=new Map,n=[];e.walkAtRules((e=>{if("layer"!==e.name.toLowerCase())return;{let r=e.parent;for(;r;){if("atrule"!==r.type||"layer"!==r.name.toLowerCase()){if(r===e.root())break;return}r=r.parent}}let a;if(e.nodes)a=normalizeLayerName(e.params,1);else{if(!e.params.trim())return;a=e.params}let c=r.parse(a);if(c?.length){{let r=e.parent;for(;r&&"atrule"===r.type&&"layer"===r.name.toLowerCase();){const e=o.get(r);e?(c=c.map((r=>e.concat(r))),r=r.parent):r=r.parent}}if(r.addLayerToModel(n,c),e.nodes){const r=c[0].concat(t);s.set(e,r),o.set(e,c[0])}}}));for(const e of s.values())r.addLayerToModel(n,[e]);const a=new WeakMap;for(const[e,r]of s)a.set(e,n.findIndex((e=>r.equal(e))));return a}function normalizeLayerName(e,r){return e.trim()?e:"csstools-anon-layer--"+r++}const s=new Set(["scope","container","layer"]);function isProcessableCustomSelectorRule(e){if("atrule"!==e.type)return!1;if("custom-selector"!==e.name.toLowerCase())return!1;if(!e.params||!e.params.includes(":--"))return!1;if(e.nodes&&e.nodes.length>0)return!1;let r=e.parent;for(;r;){if("rule"===r.type)return!1;if("atrule"===r.type&&!s.has(r.name.toLowerCase()))return!1;r=r.parent}return!0}function getCustomSelectors(r,t,s){const o=new Map,n=new Map,a=collectCascadeLayerOrder(r);return r.walkAtRules((r=>{var c,l;if(isProcessableCustomSelectorRule(r))try{const t=r.params.trim(),p=e().astSync(t),u=p?.nodes?.[0]?.nodes?.[0];if(!u||"pseudo"!==u.type||!u.value.startsWith(":--"))return;const i=u.toString(),m=(l=a,(c=r).parent&&"atrule"===c.parent.type&&"layer"===c.parent.name.toLowerCase()?l.has(c.parent)?l.get(c.parent)+1:0:1e7),f=n.get(i)??-1;if(m&&m>=f&&(n.set(i,m),o.set(i,e().astSync(t.slice(i.length).trim()))),!s.preserve){const e=r.parent;r.remove(),removeEmptyAncestorBlocks(e)}}catch(e){r.warn(t,`Failed to parse selector : "${r.params}" with message: "${e instanceof Error?e.message:e}"`)}})),o}function removeEmptyAncestorBlocks(e){if(!e)return;let r=e;for(;r;){if(r.nodes&&r.nodes.length>0)return;const e=r.parent;r.remove(),r=e}}function transformRule(r,t,s){let o=r.selector;try{o=e((r=>{r.walkPseudos((r=>{if(!s.has(r.value))return;const t=e.pseudo({value:":is",nodes:[]}),o=s.get(r.value);o&&(o.each((e=>{t.append(e.clone({}))})),r.replaceWith(t))}))})).processSync(r.selector)}catch(e){return r.warn(t,`Failed to parse selector : "${o}" with message: "${e instanceof Error?e.message:e}"`),r.selector}return o}const creator=e=>{const r=Boolean(Object(e).preserve);if("importFrom"in Object(e))throw new Error('[postcss-custom-selectors] "importFrom" is no longer supported');if("exportTo"in Object(e))throw new Error('[postcss-custom-selectors] "exportTo" is no longer supported');return{postcssPlugin:"postcss-custom-selectors",prepare(){const e=new WeakSet;let t=new Map;return{postcssPlugin:"postcss-custom-selectors",Once(e,{result:s}){t=getCustomSelectors(e,s,{preserve:r})},Rule(s,{result:o}){if(e.has(s))return;if(!s.selector?.includes(":--"))return;const n=transformRule(s,o,t);n!==s.selector&&(e.add(s),s.cloneBefore({selector:n}),r||s.remove())}}}}};creator.postcss=!0,module.exports=creator; +"use strict";var e=require("postcss-selector-parser"),r=require("@csstools/cascade-layer-name-parser");const t=r.parse("csstools-implicit-layer")[0];function collectCascadeLayerOrder(e){const s=new Map,o=new Map,n=[];e.walkAtRules((e=>{if("layer"!==e.name.toLowerCase())return;{let r=e.parent;for(;r;){if("atrule"!==r.type||"layer"!==r.name.toLowerCase()){if(r===e.root())break;return}r=r.parent}}let a;if(e.nodes)a=normalizeLayerName(e.params,1);else{if(!e.params.trim())return;a=e.params}let c=r.parse(a);if(c?.length){{let r=e.parent;for(;r&&"atrule"===r.type&&"layer"===r.name.toLowerCase();){const e=o.get(r);e?(c=c.map((r=>e.concat(r))),r=r.parent):r=r.parent}}if(r.addLayerToModel(n,c),e.nodes){const r=c[0].concat(t);s.set(e,r),o.set(e,c[0])}}}));for(const e of s.values())r.addLayerToModel(n,[e]);const a=new WeakMap;for(const[e,r]of s)a.set(e,n.findIndex((e=>r.equal(e))));return a}function normalizeLayerName(e,r){return e.trim()?e:"csstools-anon-layer--"+r++}const s=new Set(["scope","container","layer"]);function isProcessableCustomSelectorRule(e){if("atrule"!==e.type)return!1;if("custom-selector"!==e.name.toLowerCase())return!1;if(!e.params||!e.params.includes(":--"))return!1;if(e.nodes&&e.nodes.length>0)return!1;let r=e.parent;for(;r;){if("rule"===r.type)return!1;if("atrule"===r.type&&!s.has(r.name.toLowerCase()))return!1;r=r.parent}return!0}function getCustomSelectors(r,t,s){const o=new Map,n=new Map,a=collectCascadeLayerOrder(r);return r.walkAtRules((r=>{var c,l;if(isProcessableCustomSelectorRule(r))try{const t=r.params.trim(),p=e().astSync(t),u=p?.nodes?.[0]?.nodes?.[0];if(!u||"pseudo"!==u.type||!u.value.startsWith(":--"))return;const i=u.toString(),m=(l=a,(c=r).parent&&"atrule"===c.parent.type&&"layer"===c.parent.name.toLowerCase()?l.has(c.parent)?l.get(c.parent)+1:0:1e7),f=n.get(i)??-1;if(m&&m>=f&&(n.set(i,m),o.set(i,e().astSync(t.slice(i.length).trim()))),!s.preserve){const e=r.parent;r.remove(),removeEmptyAncestorBlocks(e)}}catch(e){r.warn(t,`Failed to parse selector : "${r.params}" with message: "${e instanceof Error?e.message:e}"`)}})),o}function removeEmptyAncestorBlocks(e){if(!e)return;let r=e;for(;r;){if(r.nodes&&r.nodes.length>0)return;const e=r.parent;r.remove(),r=e}}function transformRule(r,t,s){let o=r.selector;try{o=e((r=>{r.walkPseudos((r=>{if(!s.has(r.value))return;const t=e.pseudo({value:":is",nodes:[]}),o=s.get(r.value);o&&(o.each((e=>{t.append(e.clone())})),r.replaceWith(t))}))})).processSync(r.selector)}catch(e){return r.warn(t,`Failed to parse selector : "${o}" with message: "${e instanceof Error?e.message:e}"`),r.selector}return o}const creator=e=>{const r=e?.preserve??!1;if("importFrom"in Object(e))throw new Error('[postcss-custom-selectors] "importFrom" is no longer supported');if("exportTo"in Object(e))throw new Error('[postcss-custom-selectors] "exportTo" is no longer supported');return{postcssPlugin:"postcss-custom-selectors",prepare(){const e=new WeakSet;let t=new Map;return{postcssPlugin:"postcss-custom-selectors",Once(e,{result:s}){t=getCustomSelectors(e,s,{preserve:r})},Rule(s,{result:o}){if(e.has(s))return;if(!s.selector?.includes(":--"))return;const n=transformRule(s,o,t);n!==s.selector&&(e.add(s),s.cloneBefore({selector:n}),r||s.remove())}}}}};creator.postcss=!0,module.exports=creator; diff --git a/plugins/postcss-custom-selectors/dist/index.mjs b/plugins/postcss-custom-selectors/dist/index.mjs index 8d1b0cb64..0e09b1d60 100644 --- a/plugins/postcss-custom-selectors/dist/index.mjs +++ b/plugins/postcss-custom-selectors/dist/index.mjs @@ -1 +1 @@ -import e from"postcss-selector-parser";import{parse as r,addLayerToModel as t}from"@csstools/cascade-layer-name-parser";const s=r("csstools-implicit-layer")[0];function collectCascadeLayerOrder(e){const o=new Map,n=new Map,a=[];e.walkAtRules((e=>{if("layer"!==e.name.toLowerCase())return;{let r=e.parent;for(;r;){if("atrule"!==r.type||"layer"!==r.name.toLowerCase()){if(r===e.root())break;return}r=r.parent}}let c;if(e.nodes)c=normalizeLayerName(e.params,1);else{if(!e.params.trim())return;c=e.params}let l=r(c);if(l?.length){{let r=e.parent;for(;r&&"atrule"===r.type&&"layer"===r.name.toLowerCase();){const e=n.get(r);e?(l=l.map((r=>e.concat(r))),r=r.parent):r=r.parent}}if(t(a,l),e.nodes){const r=l[0].concat(s);o.set(e,r),n.set(e,l[0])}}}));for(const e of o.values())t(a,[e]);const c=new WeakMap;for(const[e,r]of o)c.set(e,a.findIndex((e=>r.equal(e))));return c}function normalizeLayerName(e,r){return e.trim()?e:"csstools-anon-layer--"+r++}const o=new Set(["scope","container","layer"]);function isProcessableCustomSelectorRule(e){if("atrule"!==e.type)return!1;if("custom-selector"!==e.name.toLowerCase())return!1;if(!e.params||!e.params.includes(":--"))return!1;if(e.nodes&&e.nodes.length>0)return!1;let r=e.parent;for(;r;){if("rule"===r.type)return!1;if("atrule"===r.type&&!o.has(r.name.toLowerCase()))return!1;r=r.parent}return!0}function getCustomSelectors(r,t,s){const o=new Map,n=new Map,a=collectCascadeLayerOrder(r);return r.walkAtRules((r=>{var c,l;if(isProcessableCustomSelectorRule(r))try{const t=r.params.trim(),p=e().astSync(t),u=p?.nodes?.[0]?.nodes?.[0];if(!u||"pseudo"!==u.type||!u.value.startsWith(":--"))return;const i=u.toString(),m=(l=a,(c=r).parent&&"atrule"===c.parent.type&&"layer"===c.parent.name.toLowerCase()?l.has(c.parent)?l.get(c.parent)+1:0:1e7),f=n.get(i)??-1;if(m&&m>=f&&(n.set(i,m),o.set(i,e().astSync(t.slice(i.length).trim()))),!s.preserve){const e=r.parent;r.remove(),removeEmptyAncestorBlocks(e)}}catch(e){r.warn(t,`Failed to parse selector : "${r.params}" with message: "${e instanceof Error?e.message:e}"`)}})),o}function removeEmptyAncestorBlocks(e){if(!e)return;let r=e;for(;r;){if(r.nodes&&r.nodes.length>0)return;const e=r.parent;r.remove(),r=e}}function transformRule(r,t,s){let o=r.selector;try{o=e((r=>{r.walkPseudos((r=>{if(!s.has(r.value))return;const t=e.pseudo({value:":is",nodes:[]}),o=s.get(r.value);o&&(o.each((e=>{t.append(e.clone({}))})),r.replaceWith(t))}))})).processSync(r.selector)}catch(e){return r.warn(t,`Failed to parse selector : "${o}" with message: "${e instanceof Error?e.message:e}"`),r.selector}return o}const creator=e=>{const r=Boolean(Object(e).preserve);if("importFrom"in Object(e))throw new Error('[postcss-custom-selectors] "importFrom" is no longer supported');if("exportTo"in Object(e))throw new Error('[postcss-custom-selectors] "exportTo" is no longer supported');return{postcssPlugin:"postcss-custom-selectors",prepare(){const e=new WeakSet;let t=new Map;return{postcssPlugin:"postcss-custom-selectors",Once(e,{result:s}){t=getCustomSelectors(e,s,{preserve:r})},Rule(s,{result:o}){if(e.has(s))return;if(!s.selector?.includes(":--"))return;const n=transformRule(s,o,t);n!==s.selector&&(e.add(s),s.cloneBefore({selector:n}),r||s.remove())}}}}};creator.postcss=!0;export{creator as default}; +import e from"postcss-selector-parser";import{parse as r,addLayerToModel as t}from"@csstools/cascade-layer-name-parser";const s=r("csstools-implicit-layer")[0];function collectCascadeLayerOrder(e){const o=new Map,n=new Map,a=[];e.walkAtRules((e=>{if("layer"!==e.name.toLowerCase())return;{let r=e.parent;for(;r;){if("atrule"!==r.type||"layer"!==r.name.toLowerCase()){if(r===e.root())break;return}r=r.parent}}let c;if(e.nodes)c=normalizeLayerName(e.params,1);else{if(!e.params.trim())return;c=e.params}let l=r(c);if(l?.length){{let r=e.parent;for(;r&&"atrule"===r.type&&"layer"===r.name.toLowerCase();){const e=n.get(r);e?(l=l.map((r=>e.concat(r))),r=r.parent):r=r.parent}}if(t(a,l),e.nodes){const r=l[0].concat(s);o.set(e,r),n.set(e,l[0])}}}));for(const e of o.values())t(a,[e]);const c=new WeakMap;for(const[e,r]of o)c.set(e,a.findIndex((e=>r.equal(e))));return c}function normalizeLayerName(e,r){return e.trim()?e:"csstools-anon-layer--"+r++}const o=new Set(["scope","container","layer"]);function isProcessableCustomSelectorRule(e){if("atrule"!==e.type)return!1;if("custom-selector"!==e.name.toLowerCase())return!1;if(!e.params||!e.params.includes(":--"))return!1;if(e.nodes&&e.nodes.length>0)return!1;let r=e.parent;for(;r;){if("rule"===r.type)return!1;if("atrule"===r.type&&!o.has(r.name.toLowerCase()))return!1;r=r.parent}return!0}function getCustomSelectors(r,t,s){const o=new Map,n=new Map,a=collectCascadeLayerOrder(r);return r.walkAtRules((r=>{var c,l;if(isProcessableCustomSelectorRule(r))try{const t=r.params.trim(),p=e().astSync(t),u=p?.nodes?.[0]?.nodes?.[0];if(!u||"pseudo"!==u.type||!u.value.startsWith(":--"))return;const i=u.toString(),m=(l=a,(c=r).parent&&"atrule"===c.parent.type&&"layer"===c.parent.name.toLowerCase()?l.has(c.parent)?l.get(c.parent)+1:0:1e7),f=n.get(i)??-1;if(m&&m>=f&&(n.set(i,m),o.set(i,e().astSync(t.slice(i.length).trim()))),!s.preserve){const e=r.parent;r.remove(),removeEmptyAncestorBlocks(e)}}catch(e){r.warn(t,`Failed to parse selector : "${r.params}" with message: "${e instanceof Error?e.message:e}"`)}})),o}function removeEmptyAncestorBlocks(e){if(!e)return;let r=e;for(;r;){if(r.nodes&&r.nodes.length>0)return;const e=r.parent;r.remove(),r=e}}function transformRule(r,t,s){let o=r.selector;try{o=e((r=>{r.walkPseudos((r=>{if(!s.has(r.value))return;const t=e.pseudo({value:":is",nodes:[]}),o=s.get(r.value);o&&(o.each((e=>{t.append(e.clone())})),r.replaceWith(t))}))})).processSync(r.selector)}catch(e){return r.warn(t,`Failed to parse selector : "${o}" with message: "${e instanceof Error?e.message:e}"`),r.selector}return o}const creator=e=>{const r=e?.preserve??!1;if("importFrom"in Object(e))throw new Error('[postcss-custom-selectors] "importFrom" is no longer supported');if("exportTo"in Object(e))throw new Error('[postcss-custom-selectors] "exportTo" is no longer supported');return{postcssPlugin:"postcss-custom-selectors",prepare(){const e=new WeakSet;let t=new Map;return{postcssPlugin:"postcss-custom-selectors",Once(e,{result:s}){t=getCustomSelectors(e,s,{preserve:r})},Rule(s,{result:o}){if(e.has(s))return;if(!s.selector?.includes(":--"))return;const n=transformRule(s,o,t);n!==s.selector&&(e.add(s),s.cloneBefore({selector:n}),r||s.remove())}}}}};creator.postcss=!0;export{creator as default}; diff --git a/plugins/postcss-custom-selectors/src/cascade-layers.ts b/plugins/postcss-custom-selectors/src/cascade-layers.ts index 79751908e..cdf95a694 100644 --- a/plugins/postcss-custom-selectors/src/cascade-layers.ts +++ b/plugins/postcss-custom-selectors/src/cascade-layers.ts @@ -112,6 +112,7 @@ export function cascadeLayerNumberForNode(node: Node, layers: WeakMap = (opts?: pluginOptions) => { // whether to preserve custom selectors and rules using them - const preserve = Boolean(Object(opts).preserve); + const preserve = opts?.preserve ?? false; if ('importFrom' in Object(opts)) { throw new Error('[postcss-custom-selectors] "importFrom" is no longer supported'); @@ -24,7 +25,7 @@ const creator: PluginCreator = (opts?: pluginOptions) => { postcssPlugin: 'postcss-custom-selectors', prepare(): Plugin { const transformedNodes = new WeakSet(); - let customSelectors = new Map(); + let customSelectors: Map = new Map(); return { postcssPlugin: 'postcss-custom-selectors', diff --git a/plugins/postcss-custom-selectors/src/transform-rule.ts b/plugins/postcss-custom-selectors/src/transform-rule.ts index 01333e71f..e7ff0b932 100644 --- a/plugins/postcss-custom-selectors/src/transform-rule.ts +++ b/plugins/postcss-custom-selectors/src/transform-rule.ts @@ -1,6 +1,6 @@ import parser from 'postcss-selector-parser'; import type { Result, Rule } from 'postcss'; -import type { Root, Selector } from 'postcss-selector-parser'; +import type { Root } from 'postcss-selector-parser'; // transform custom pseudo selectors with custom selectors export function transformRule(rule: Rule, result: Result, customSelectors: Map): string { @@ -25,7 +25,7 @@ export function transformRule(rule: Rule, result: Result, customSelectors: Map { - isWrapper.append(node.clone({}) as Selector); + isWrapper.append(node.clone()); }); pseudo.replaceWith(isWrapper); diff --git a/plugins/postcss-design-tokens/dist/index.cjs b/plugins/postcss-design-tokens/dist/index.cjs index 6453439a7..3c9768994 100644 --- a/plugins/postcss-design-tokens/dist/index.cjs +++ b/plugins/postcss-design-tokens/dist/index.cjs @@ -1 +1 @@ -"use strict";var e=require("postcss-value-parser"),t=require("path"),n=require("fs"),r=require("module"),o=require("@csstools/css-parser-algorithms"),s=require("@csstools/css-tokenizer");function toposort(e,t){let n=e.length;const r=new Array(n),o={};let s=n;const a=makeOutgoingEdges(t),i=makeNodesHash(e);for(t.forEach((function(e){if(!i.has(e[0])||!i.has(e[1]))throw new Error("Unknown token. Make sure to provide all tokens used in aliases.")}));s--;)o[s]||visit(e[s],s,new Set);return r;function visit(e,t,s){if(s.has(e)){let t;try{t=", token was: "+JSON.stringify(e)}catch(e){t=""}throw new Error("Cyclic dependency"+t)}if(!i.has(e))throw new Error("Found unknown token. Make sure to provided all involved tokens. Unknown token: "+JSON.stringify(e));if(o[t])return;o[t]=!0;const u=Array.from(a.get(e)||new Set);if(t=u.length){s.add(e);do{const e=u[--t];visit(e,i.get(e),s)}while(t);s.delete(e)}r[--n]=e}}function makeOutgoingEdges(e){const t=new Map;for(let n=0,r=e.length;napplyTransformsToValue(o,e),name:String(e.name??"")||t,comment:String(e.comment??"")||void 0,metadata:{name:String(e.name??"")?t:void 0,path:[...n,t],filePath:r,isSource:!0}}}const a=new Map;function applyTransformsToValue(t,n){if(!t)return"";if(!n)return t;if(!n.toUnit)return t;const r=e.unit(t);if(!r||r.unit===n.toUnit)return t;if(!r.unit){if(a.has(n.toUnit)){if(a.get(n.toUnit))return`${t}${n.toUnit}`;throw new Error(`Invalid unit "${n.toUnit}" for "${t}"`)}try{const r=e.unit(`${t}${n.toUnit}`);if(r&&r.unit===n.toUnit)return a.set(n.toUnit,!0),`${t}${n.toUnit}`;a.set(n.toUnit,!1)}catch(e){a.set(n.toUnit,!1)}throw new Error(`Invalid unit "${n.toUnit}" for "${t}"`)}return"rem"===r.unit&&"px"===n.toUnit?remToPx(parseFloat(r.number),n.pluginOptions?.rootFontSize??16):"px"===r.unit&&"rem"===n.toUnit?pxToRem(parseFloat(r.number),n.pluginOptions?.rootFontSize??16):t}function remToPx(e,t){return`${formatFloat(e*t)}px`}function pxToRem(e,t){return`${formatFloat(e/t)}rem`}function formatFloat(e){if(Number.isInteger(e))return e.toString();let t=e.toFixed(5);for(let e=t.length-1;e>=0&&"."!==t[e]&&"0"===t[e];e--)t=t.slice(0,e);return t}function dereferenceTokenValues(e){const t=new Set,n=new Map;for(const[r,o]of e.entries()){const e=parseReferences(o.value);e.length&&(t.add(r),n.set(r,e))}for(const[r,o]of n.entries()){for(let n=0;n"value-reference"===e.type)))continue;const s=o.map((e=>e.value)).join(""),a=e.get(r);a.value=s,a.cssValue=e=>applyTransformsToValue(s,e),e.set(r,a),t.delete(r),n.delete(r)}if(0===t.size)return e;{const r=Array.from(e.keys()),o=[];for(const[e,t]of n.entries())for(let n=0;n"value-reference"===e.type)))throw new Error('Token "'+r+'" can not be fully resolved');const s=o.map((e=>e.value)).join(""),a=e.get(r);a.value=s,a.cssValue=e=>applyTransformsToValue(s,e),e.set(r,a),t.delete(r),n.delete(r)}if(0===t.size)return e}return e}function parseReferences(e){if("string"!=typeof e)return[];if(-1===e.indexOf("{"))return[];const t=[];let n=!1,r=!1,o="";for(let s=0;s0&&(t.push({type:"value-non-reference",value:o}),o=""),r=!0;break;case"}":if(!r)throw new Error('Unexpected "}" in "'+e+'" at '+s);if(0===o.length)throw new Error('Empty alias "{}" in "'+e+'" at '+s);{let e=o.trim();".value"===e.slice(-6)&&(e=e.slice(0,-6)),t.push({type:"value-reference",raw:e}),o=""}n=!0,r=!1;break;default:o+=a}}if(r)throw new Error('Unexpected end of alias in "'+e+'"');return o.length>0&&t.push({type:"value-non-reference",value:o}),n?t:[]}function extractTokens(e,t,n){const r=new Map;for(const o in e)if(Object.hasOwnProperty.call(e,o)){if(null===e[o]||"object"!=typeof e[o]||Array.isArray(e[o]))throw new Error(`Parsing error at "${[...t,o].join(".")}"`);const s=Object(e[o]);if(!s)throw new Error(`Parsing error at "${[...t,o].join(".")}"`);if(void 0!==s.value){const e=extractStyleDictionaryV3Token(s,o,t,n);r.set(e.metadata.path.join("."),e);continue}for(const[e,a]of extractTokens(s,[...t,o],n).entries())r.set(e,a)}return r}function extractStyleDictionaryV3Tokens(e,t){return dereferenceTokenValues(extractTokens(e,[],t))}function extractStyleDictionaryTokens(e,t,n){return extractStyleDictionaryV3Tokens(t,n)}const i="6b4e71e7-4787-42f7-a092-8684961895db";function parseImport(t){const n=e(t),r={filePath:"",format:"standard",conditions:[i]};return n.walk((e=>{"function"===e.type&&"url"===e.value&&(r.filePath=e.nodes[0].value),"function"===e.type&&"format"===e.value&&(r.format=e.nodes[0].value),"function"===e.type&&"when"===e.value&&(r.conditions=e.nodes.filter((e=>"string"===e.type)).map((e=>e.value)))})),r.conditions.length||(r.conditions=[i]),r}async function tokensFromImport(e,o,s,a,i,u){const{filePath:l,format:c,conditions:f}=parseImport(i);if(!f.every((e=>s.includes(e))))return!1;let p="";try{if(l.startsWith("node_modules://")){p=r.createRequire(t.dirname(a)).resolve(l.slice(15))}else if(l.startsWith("node_modules:")){p=r.createRequire(t.dirname(a)).resolve(l.slice(13))}else p=t.resolve(t.dirname(a),l)}catch(e){throw new Error(`Failed to read ${l} with error ${e instanceof Error?e.message:e}`)}if(u.has(p))return!1;o.result.messages.push({type:"dependency",plugin:"postcss-design-tokens",file:p,parent:e.source?.input?.file}),u.add(p);const d=await n.promises.readFile(p,"utf8"),m=JSON.parse(d);if("style-dictionary3"===c)return{filePath:t.resolve(l),tokens:extractStyleDictionaryTokens(0,m,p)};throw new Error("Unsupported format: "+c)}function mergeTokens(e,t){const n=new Map(e);for(const[e,r]of t)n.set(e,r);return n}function parsePluginOptions(e){const t={importAtRuleName:"design-tokens",is:[i],unitsAndValues:{rootFontSize:16},valueFunctionName:"design-token"};return e?("object"!=typeof e||(Array.isArray(e.is)&&(t.is=e.is.filter((e=>"string"==typeof e))),0===t.is.length&&(t.is=[i]),"object"==typeof e.unitsAndValues&&"number"==typeof e.unitsAndValues.rootFontSize&&((n=e.unitsAndValues.rootFontSize)>0&&n!==1/0)&&(t.unitsAndValues.rootFontSize=e.unitsAndValues.rootFontSize),"string"==typeof e.valueFunctionName&&(t.valueFunctionName=e.valueFunctionName),"string"==typeof e.importAtRuleName&&(t.importAtRuleName=e.importAtRuleName)),t):t;var n}function parseComponentValuesFromTokens(e){return o.parseListOfComponentValues(e,{onParseError:e=>{throw e}})}function parseComponentValues(e){const t=s.tokenizer({css:e},{onParseError:e=>{throw e}}),n=[];for(;!t.endOfFile();)n.push(t.nextToken());return n.push(t.nextToken()),parseComponentValuesFromTokens(n)}function transform(e,t,n,r,o){const s=parseComponentValues(r);let a=!1;return s.forEach(((r,i)=>{if("walk"in r){{const u=transformComponentValue(r,e,t,n,o);if(u)return s.splice(i,1,...u),a=!0,!1}r.walk(((r,s)=>{if("string"==typeof s)return;const i=transformComponentValue(r.node,e,t,n,o);return i?(r.parent.value.splice(s,1,...i),a=!0,!1):void 0}))}})),a?s.map((e=>e.toString())).join(""):r}function transformComponentValue(e,t,n,r,a){if(!o.isFunctionNode(e))return;if(e.getName().toLowerCase()!==a.valueFunctionName)return;let i="",u="",l="";for(let t=0;t{const t=parsePluginOptions(e);return{postcssPlugin:"postcss-design-tokens",prepare(){let e=new Map,n=new Set;return{postcssPlugin:"postcss-design-tokens",OnceExit(){e=new Map,n=new Set},async Once(r,o){const s=[];r.walkAtRules((e=>{if(e.name.toLowerCase()!==t.importAtRuleName)return;if(!e?.source?.input?.file)return;const n=e.source.input.file,r=e.params;e.remove(),s.push({filePath:n,params:r,node:e})}));for(const a of s.values()){let s;try{if(s=await tokensFromImport(r,o,t.is,a.filePath,a.params,n),!s)continue}catch(e){a.node.warn(o.result,`Failed to import design tokens from "${a.params}" with error:\n\t`+(e instanceof Error?e.message:e));continue}o.result.messages.push({type:"dependency",plugin:"postcss-design-tokens",file:s.filePath,parent:a.filePath}),e=mergeTokens(e,s.tokens)}},Declaration(n,{result:r}){if(n.value.toLowerCase().includes(t.valueFunctionName))try{const o=transform(e,r,n,n.value,t);if(o===n.value)return;n.value=o}catch(e){n.warn(r,`Failed to parse and transform "${n.value}"`)}},AtRule(n,{result:r}){if(n.params.toLowerCase().includes(t.valueFunctionName))try{const o=transform(e,r,n,n.params,t);if(o===n.params)return;n.params=o}catch(e){n.warn(r,`Failed to parse and transform "${n.params}"`)}}}}}};creator.postcss=!0,module.exports=creator; +"use strict";var e=require("postcss-value-parser"),t=require("path"),n=require("fs"),r=require("module"),o=require("@csstools/css-parser-algorithms"),s=require("@csstools/css-tokenizer");function toposort(e,t){let n=e.length;const r=new Array(n),o={};let s=n;const a=makeOutgoingEdges(t),i=makeNodesHash(e);for(t.forEach((function(e){if(!i.has(e[0])||!i.has(e[1]))throw new Error("Unknown token. Make sure to provide all tokens used in aliases.")}));s--;)o[s]||visit(e[s],s,new Set);return r;function visit(e,t,s){if(s.has(e)){let t;try{t=", token was: "+JSON.stringify(e)}catch{t=""}throw new Error("Cyclic dependency"+t)}if(!i.has(e))throw new Error("Found unknown token. Make sure to provided all involved tokens. Unknown token: "+JSON.stringify(e));if(o[t])return;o[t]=!0;const u=Array.from(a.get(e)||new Set);if(t=u.length){s.add(e);do{const e=u[--t];visit(e,i.get(e),s)}while(t);s.delete(e)}r[--n]=e}}function makeOutgoingEdges(e){const t=new Map;for(let n=0,r=e.length;napplyTransformsToValue(o,e),name:String(e.name??"")||t,comment:String(e.comment??"")||void 0,metadata:{name:String(e.name??"")?t:void 0,path:[...n,t],filePath:r,isSource:!0}}}const a=new Map;function applyTransformsToValue(t,n){if(!t)return"";if(!n)return t;if(!n.toUnit)return t;const r=e.unit(t);if(!r||r.unit===n.toUnit)return t;if(!r.unit){if(a.has(n.toUnit)){if(a.get(n.toUnit))return`${t}${n.toUnit}`;throw new Error(`Invalid unit "${n.toUnit}" for "${t}"`)}try{const r=e.unit(`${t}${n.toUnit}`);if(r&&r.unit===n.toUnit)return a.set(n.toUnit,!0),`${t}${n.toUnit}`;a.set(n.toUnit,!1)}catch{a.set(n.toUnit,!1)}throw new Error(`Invalid unit "${n.toUnit}" for "${t}"`)}return"rem"===r.unit&&"px"===n.toUnit?remToPx(parseFloat(r.number),n.pluginOptions?.rootFontSize??16):"px"===r.unit&&"rem"===n.toUnit?pxToRem(parseFloat(r.number),n.pluginOptions?.rootFontSize??16):t}function remToPx(e,t){return`${formatFloat(e*t)}px`}function pxToRem(e,t){return`${formatFloat(e/t)}rem`}function formatFloat(e){if(Number.isInteger(e))return e.toString();let t=e.toFixed(5);for(let e=t.length-1;e>=0&&"."!==t[e]&&"0"===t[e];e--)t=t.slice(0,e);return t}function dereferenceTokenValues(e){const t=new Set,n=new Map;for(const[r,o]of e.entries()){const e=parseReferences(o.value);e.length&&(t.add(r),n.set(r,e))}for(const[r,o]of n.entries()){for(let n=0;n"value-reference"===e.type)))continue;const s=o.map((e=>e.value)).join(""),a=e.get(r);a.value=s,a.cssValue=e=>applyTransformsToValue(s,e),e.set(r,a),t.delete(r),n.delete(r)}if(0===t.size)return e;{const r=Array.from(e.keys()),o=[];for(const[e,t]of n.entries())for(let n=0;n"value-reference"===e.type)))throw new Error('Token "'+r+'" can not be fully resolved');const s=o.map((e=>e.value)).join(""),a=e.get(r);a.value=s,a.cssValue=e=>applyTransformsToValue(s,e),e.set(r,a),t.delete(r),n.delete(r)}if(0===t.size)return e}return e}function parseReferences(e){if("string"!=typeof e)return[];if(-1===e.indexOf("{"))return[];const t=[];let n=!1,r=!1,o="";for(let s=0;s0&&(t.push({type:"value-non-reference",value:o}),o=""),r=!0;break;case"}":if(!r)throw new Error('Unexpected "}" in "'+e+'" at '+s);if(0===o.length)throw new Error('Empty alias "{}" in "'+e+'" at '+s);{let e=o.trim();".value"===e.slice(-6)&&(e=e.slice(0,-6)),t.push({type:"value-reference",raw:e}),o=""}n=!0,r=!1;break;default:o+=a}}if(r)throw new Error('Unexpected end of alias in "'+e+'"');return o.length>0&&t.push({type:"value-non-reference",value:o}),n?t:[]}function isTokenGroup(e){return"object"==typeof e&&null!==e&&void 0===e.value}function extractTokens(e,t,n){const r=new Map;for(const o in e)if(Object.hasOwnProperty.call(e,o)){if(null===e[o]||"object"!=typeof e[o]||Array.isArray(e[o]))throw new Error(`Parsing error at "${[...t,o].join(".")}"`);const s=e[o];if(!s)throw new Error(`Parsing error at "${[...t,o].join(".")}"`);if(!isTokenGroup(s)){const e=extractStyleDictionaryV3Token(s,o,t,n);r.set(e.metadata.path.join("."),e);continue}for(const[e,a]of extractTokens(s,[...t,o],n).entries())r.set(e,a)}return r}function extractStyleDictionaryV3Tokens(e,t){return dereferenceTokenValues(extractTokens(e,[],t))}function extractStyleDictionaryTokens(e,t,n){return extractStyleDictionaryV3Tokens(t,n)}const i="6b4e71e7-4787-42f7-a092-8684961895db";function parseImport(t){const n=e(t),r={filePath:"",format:"standard",conditions:[i]};return n.walk((e=>{"function"===e.type&&"url"===e.value&&(r.filePath=e.nodes[0].value),"function"===e.type&&"format"===e.value&&(r.format=e.nodes[0].value),"function"===e.type&&"when"===e.value&&(r.conditions=e.nodes.filter((e=>"string"===e.type)).map((e=>e.value)))})),r.conditions.length||(r.conditions=[i]),r}async function tokensFromImport(e,o,s,a,i,u){const{filePath:l,format:c,conditions:f}=parseImport(i);if(!f.every((e=>s.includes(e))))return!1;let p="";try{if(l.startsWith("node_modules://")){p=r.createRequire(t.dirname(a)).resolve(l.slice(15))}else if(l.startsWith("node_modules:")){p=r.createRequire(t.dirname(a)).resolve(l.slice(13))}else p=t.resolve(t.dirname(a),l)}catch(e){throw new Error(`Failed to read ${l} with error ${e instanceof Error?e.message:e}`)}if(u.has(p))return!1;o.result.messages.push({type:"dependency",plugin:"postcss-design-tokens",file:p,parent:e.source?.input?.file}),u.add(p);const d=await n.promises.readFile(p,"utf8"),m=JSON.parse(d);if("style-dictionary3"===c)return{filePath:t.resolve(l),tokens:extractStyleDictionaryTokens(0,m,p)};throw new Error("Unsupported format: "+c)}function mergeTokens(e,t){const n=new Map(e);for(const[e,r]of t)n.set(e,r);return n}function parsePluginOptions(e){const t={importAtRuleName:"design-tokens",is:[i],unitsAndValues:{rootFontSize:16},valueFunctionName:"design-token"};return e?("object"!=typeof e||(Array.isArray(e.is)&&(t.is=e.is.filter((e=>"string"==typeof e))),0===t.is.length&&(t.is=[i]),"object"==typeof e.unitsAndValues&&"number"==typeof e.unitsAndValues.rootFontSize&&((n=e.unitsAndValues.rootFontSize)>0&&n!==1/0)&&(t.unitsAndValues.rootFontSize=e.unitsAndValues.rootFontSize),"string"==typeof e.valueFunctionName&&(t.valueFunctionName=e.valueFunctionName),"string"==typeof e.importAtRuleName&&(t.importAtRuleName=e.importAtRuleName)),t):t;var n}function parseComponentValuesFromTokens(e){return o.parseListOfComponentValues(e,{onParseError:e=>{throw e}})}function parseComponentValues(e){const t=s.tokenizer({css:e},{onParseError:e=>{throw e}}),n=[];for(;!t.endOfFile();)n.push(t.nextToken());return n.push(t.nextToken()),parseComponentValuesFromTokens(n)}function transform(e,t,n,r,o){const s=parseComponentValues(r);let a=!1;return s.forEach(((r,i)=>{if("walk"in r){{const u=transformComponentValue(r,e,t,n,o);if(u)return s.splice(i,1,...u),a=!0,!1}r.walk(((r,s)=>{if("string"==typeof s)return;const i=transformComponentValue(r.node,e,t,n,o);return i?(r.parent.value.splice(s,1,...i),a=!0,!1):void 0}))}})),a?s.map((e=>e.toString())).join(""):r}function transformComponentValue(e,t,n,r,a){if(!o.isFunctionNode(e))return;if(e.getName().toLowerCase()!==a.valueFunctionName)return;let i="",u="",l="";for(let t=0;t{const t=parsePluginOptions(e);return{postcssPlugin:"postcss-design-tokens",prepare(){let e=new Map,n=new Set;return{postcssPlugin:"postcss-design-tokens",OnceExit(){e=new Map,n=new Set},async Once(r,o){const s=[];r.walkAtRules((e=>{if(e.name.toLowerCase()!==t.importAtRuleName)return;if(!e?.source?.input?.file)return;const n=e.source.input.file,r=e.params;e.remove(),s.push({filePath:n,params:r,node:e})}));for(const a of s.values()){let s;try{if(s=await tokensFromImport(r,o,t.is,a.filePath,a.params,n),!s)continue}catch(e){a.node.warn(o.result,`Failed to import design tokens from "${a.params}" with error:\n\t`+(e instanceof Error?e.message:e));continue}o.result.messages.push({type:"dependency",plugin:"postcss-design-tokens",file:s.filePath,parent:a.filePath}),e=mergeTokens(e,s.tokens)}},Declaration(n,{result:r}){if(n.value.toLowerCase().includes(t.valueFunctionName))try{const o=transform(e,r,n,n.value,t);if(o===n.value)return;n.value=o}catch{n.warn(r,`Failed to parse and transform "${n.value}"`)}},AtRule(n,{result:r}){if(n.params.toLowerCase().includes(t.valueFunctionName))try{const o=transform(e,r,n,n.params,t);if(o===n.params)return;n.params=o}catch{n.warn(r,`Failed to parse and transform "${n.params}"`)}}}}}};creator.postcss=!0,module.exports=creator; diff --git a/plugins/postcss-design-tokens/dist/index.mjs b/plugins/postcss-design-tokens/dist/index.mjs index 9439cd469..170c01cf4 100644 --- a/plugins/postcss-design-tokens/dist/index.mjs +++ b/plugins/postcss-design-tokens/dist/index.mjs @@ -1 +1 @@ -import e from"postcss-value-parser";import t from"path";import{promises as n}from"fs";import r from"module";import{parseListOfComponentValues as o,isFunctionNode as s,isWhitespaceNode as a,isCommentNode as i,isTokenNode as u}from"@csstools/css-parser-algorithms";import{tokenizer as l,isTokenString as c,isTokenIdent as f}from"@csstools/css-tokenizer";function toposort(e,t){let n=e.length;const r=new Array(n),o={};let s=n;const a=makeOutgoingEdges(t),i=makeNodesHash(e);for(t.forEach((function(e){if(!i.has(e[0])||!i.has(e[1]))throw new Error("Unknown token. Make sure to provide all tokens used in aliases.")}));s--;)o[s]||visit(e[s],s,new Set);return r;function visit(e,t,s){if(s.has(e)){let t;try{t=", token was: "+JSON.stringify(e)}catch(e){t=""}throw new Error("Cyclic dependency"+t)}if(!i.has(e))throw new Error("Found unknown token. Make sure to provided all involved tokens. Unknown token: "+JSON.stringify(e));if(o[t])return;o[t]=!0;const u=Array.from(a.get(e)||new Set);if(t=u.length){s.add(e);do{const e=u[--t];visit(e,i.get(e),s)}while(t);s.delete(e)}r[--n]=e}}function makeOutgoingEdges(e){const t=new Map;for(let n=0,r=e.length;napplyTransformsToValue(o,e),name:String(e.name??"")||t,comment:String(e.comment??"")||void 0,metadata:{name:String(e.name??"")?t:void 0,path:[...n,t],filePath:r,isSource:!0}}}const p=new Map;function applyTransformsToValue(t,n){if(!t)return"";if(!n)return t;if(!n.toUnit)return t;const r=e.unit(t);if(!r||r.unit===n.toUnit)return t;if(!r.unit){if(p.has(n.toUnit)){if(p.get(n.toUnit))return`${t}${n.toUnit}`;throw new Error(`Invalid unit "${n.toUnit}" for "${t}"`)}try{const r=e.unit(`${t}${n.toUnit}`);if(r&&r.unit===n.toUnit)return p.set(n.toUnit,!0),`${t}${n.toUnit}`;p.set(n.toUnit,!1)}catch(e){p.set(n.toUnit,!1)}throw new Error(`Invalid unit "${n.toUnit}" for "${t}"`)}return"rem"===r.unit&&"px"===n.toUnit?remToPx(parseFloat(r.number),n.pluginOptions?.rootFontSize??16):"px"===r.unit&&"rem"===n.toUnit?pxToRem(parseFloat(r.number),n.pluginOptions?.rootFontSize??16):t}function remToPx(e,t){return`${formatFloat(e*t)}px`}function pxToRem(e,t){return`${formatFloat(e/t)}rem`}function formatFloat(e){if(Number.isInteger(e))return e.toString();let t=e.toFixed(5);for(let e=t.length-1;e>=0&&"."!==t[e]&&"0"===t[e];e--)t=t.slice(0,e);return t}function dereferenceTokenValues(e){const t=new Set,n=new Map;for(const[r,o]of e.entries()){const e=parseReferences(o.value);e.length&&(t.add(r),n.set(r,e))}for(const[r,o]of n.entries()){for(let n=0;n"value-reference"===e.type)))continue;const s=o.map((e=>e.value)).join(""),a=e.get(r);a.value=s,a.cssValue=e=>applyTransformsToValue(s,e),e.set(r,a),t.delete(r),n.delete(r)}if(0===t.size)return e;{const r=Array.from(e.keys()),o=[];for(const[e,t]of n.entries())for(let n=0;n"value-reference"===e.type)))throw new Error('Token "'+r+'" can not be fully resolved');const s=o.map((e=>e.value)).join(""),a=e.get(r);a.value=s,a.cssValue=e=>applyTransformsToValue(s,e),e.set(r,a),t.delete(r),n.delete(r)}if(0===t.size)return e}return e}function parseReferences(e){if("string"!=typeof e)return[];if(-1===e.indexOf("{"))return[];const t=[];let n=!1,r=!1,o="";for(let s=0;s0&&(t.push({type:"value-non-reference",value:o}),o=""),r=!0;break;case"}":if(!r)throw new Error('Unexpected "}" in "'+e+'" at '+s);if(0===o.length)throw new Error('Empty alias "{}" in "'+e+'" at '+s);{let e=o.trim();".value"===e.slice(-6)&&(e=e.slice(0,-6)),t.push({type:"value-reference",raw:e}),o=""}n=!0,r=!1;break;default:o+=a}}if(r)throw new Error('Unexpected end of alias in "'+e+'"');return o.length>0&&t.push({type:"value-non-reference",value:o}),n?t:[]}function extractTokens(e,t,n){const r=new Map;for(const o in e)if(Object.hasOwnProperty.call(e,o)){if(null===e[o]||"object"!=typeof e[o]||Array.isArray(e[o]))throw new Error(`Parsing error at "${[...t,o].join(".")}"`);const s=Object(e[o]);if(!s)throw new Error(`Parsing error at "${[...t,o].join(".")}"`);if(void 0!==s.value){const e=extractStyleDictionaryV3Token(s,o,t,n);r.set(e.metadata.path.join("."),e);continue}for(const[e,a]of extractTokens(s,[...t,o],n).entries())r.set(e,a)}return r}function extractStyleDictionaryV3Tokens(e,t){return dereferenceTokenValues(extractTokens(e,[],t))}function extractStyleDictionaryTokens(e,t,n){return extractStyleDictionaryV3Tokens(t,n)}const m="6b4e71e7-4787-42f7-a092-8684961895db";function parseImport(t){const n=e(t),r={filePath:"",format:"standard",conditions:[m]};return n.walk((e=>{"function"===e.type&&"url"===e.value&&(r.filePath=e.nodes[0].value),"function"===e.type&&"format"===e.value&&(r.format=e.nodes[0].value),"function"===e.type&&"when"===e.value&&(r.conditions=e.nodes.filter((e=>"string"===e.type)).map((e=>e.value)))})),r.conditions.length||(r.conditions=[m]),r}async function tokensFromImport(e,o,s,a,i,u){const{filePath:l,format:c,conditions:f}=parseImport(i);if(!f.every((e=>s.includes(e))))return!1;let p="";try{if(l.startsWith("node_modules://")){p=r.createRequire(t.dirname(a)).resolve(l.slice(15))}else if(l.startsWith("node_modules:")){p=r.createRequire(t.dirname(a)).resolve(l.slice(13))}else p=t.resolve(t.dirname(a),l)}catch(e){throw new Error(`Failed to read ${l} with error ${e instanceof Error?e.message:e}`)}if(u.has(p))return!1;o.result.messages.push({type:"dependency",plugin:"postcss-design-tokens",file:p,parent:e.source?.input?.file}),u.add(p);const m=await n.readFile(p,"utf8"),d=JSON.parse(m);if("style-dictionary3"===c)return{filePath:t.resolve(l),tokens:extractStyleDictionaryTokens(0,d,p)};throw new Error("Unsupported format: "+c)}function mergeTokens(e,t){const n=new Map(e);for(const[e,r]of t)n.set(e,r);return n}function parsePluginOptions(e){const t={importAtRuleName:"design-tokens",is:[m],unitsAndValues:{rootFontSize:16},valueFunctionName:"design-token"};return e?("object"!=typeof e||(Array.isArray(e.is)&&(t.is=e.is.filter((e=>"string"==typeof e))),0===t.is.length&&(t.is=[m]),"object"==typeof e.unitsAndValues&&"number"==typeof e.unitsAndValues.rootFontSize&&((n=e.unitsAndValues.rootFontSize)>0&&n!==1/0)&&(t.unitsAndValues.rootFontSize=e.unitsAndValues.rootFontSize),"string"==typeof e.valueFunctionName&&(t.valueFunctionName=e.valueFunctionName),"string"==typeof e.importAtRuleName&&(t.importAtRuleName=e.importAtRuleName)),t):t;var n}function parseComponentValuesFromTokens(e){return o(e,{onParseError:e=>{throw e}})}function parseComponentValues(e){const t=l({css:e},{onParseError:e=>{throw e}}),n=[];for(;!t.endOfFile();)n.push(t.nextToken());return n.push(t.nextToken()),parseComponentValuesFromTokens(n)}function transform(e,t,n,r,o){const s=parseComponentValues(r);let a=!1;return s.forEach(((r,i)=>{if("walk"in r){{const u=transformComponentValue(r,e,t,n,o);if(u)return s.splice(i,1,...u),a=!0,!1}r.walk(((r,s)=>{if("string"==typeof s)return;const i=transformComponentValue(r.node,e,t,n,o);return i?(r.parent.value.splice(s,1,...i),a=!0,!1):void 0}))}})),a?s.map((e=>e.toString())).join(""):r}function transformComponentValue(e,t,n,r,o){if(!s(e))return;if(e.getName().toLowerCase()!==o.valueFunctionName)return;let l="",p="",m="";for(let t=0;t{const t=parsePluginOptions(e);return{postcssPlugin:"postcss-design-tokens",prepare(){let e=new Map,n=new Set;return{postcssPlugin:"postcss-design-tokens",OnceExit(){e=new Map,n=new Set},async Once(r,o){const s=[];r.walkAtRules((e=>{if(e.name.toLowerCase()!==t.importAtRuleName)return;if(!e?.source?.input?.file)return;const n=e.source.input.file,r=e.params;e.remove(),s.push({filePath:n,params:r,node:e})}));for(const a of s.values()){let s;try{if(s=await tokensFromImport(r,o,t.is,a.filePath,a.params,n),!s)continue}catch(e){a.node.warn(o.result,`Failed to import design tokens from "${a.params}" with error:\n\t`+(e instanceof Error?e.message:e));continue}o.result.messages.push({type:"dependency",plugin:"postcss-design-tokens",file:s.filePath,parent:a.filePath}),e=mergeTokens(e,s.tokens)}},Declaration(n,{result:r}){if(n.value.toLowerCase().includes(t.valueFunctionName))try{const o=transform(e,r,n,n.value,t);if(o===n.value)return;n.value=o}catch(e){n.warn(r,`Failed to parse and transform "${n.value}"`)}},AtRule(n,{result:r}){if(n.params.toLowerCase().includes(t.valueFunctionName))try{const o=transform(e,r,n,n.params,t);if(o===n.params)return;n.params=o}catch(e){n.warn(r,`Failed to parse and transform "${n.params}"`)}}}}}};creator.postcss=!0;export{creator as default}; +import e from"postcss-value-parser";import t from"path";import{promises as n}from"fs";import r from"module";import{parseListOfComponentValues as o,isFunctionNode as s,isWhitespaceNode as a,isCommentNode as i,isTokenNode as u}from"@csstools/css-parser-algorithms";import{tokenizer as l,isTokenString as c,isTokenIdent as f}from"@csstools/css-tokenizer";function toposort(e,t){let n=e.length;const r=new Array(n),o={};let s=n;const a=makeOutgoingEdges(t),i=makeNodesHash(e);for(t.forEach((function(e){if(!i.has(e[0])||!i.has(e[1]))throw new Error("Unknown token. Make sure to provide all tokens used in aliases.")}));s--;)o[s]||visit(e[s],s,new Set);return r;function visit(e,t,s){if(s.has(e)){let t;try{t=", token was: "+JSON.stringify(e)}catch{t=""}throw new Error("Cyclic dependency"+t)}if(!i.has(e))throw new Error("Found unknown token. Make sure to provided all involved tokens. Unknown token: "+JSON.stringify(e));if(o[t])return;o[t]=!0;const u=Array.from(a.get(e)||new Set);if(t=u.length){s.add(e);do{const e=u[--t];visit(e,i.get(e),s)}while(t);s.delete(e)}r[--n]=e}}function makeOutgoingEdges(e){const t=new Map;for(let n=0,r=e.length;napplyTransformsToValue(o,e),name:String(e.name??"")||t,comment:String(e.comment??"")||void 0,metadata:{name:String(e.name??"")?t:void 0,path:[...n,t],filePath:r,isSource:!0}}}const p=new Map;function applyTransformsToValue(t,n){if(!t)return"";if(!n)return t;if(!n.toUnit)return t;const r=e.unit(t);if(!r||r.unit===n.toUnit)return t;if(!r.unit){if(p.has(n.toUnit)){if(p.get(n.toUnit))return`${t}${n.toUnit}`;throw new Error(`Invalid unit "${n.toUnit}" for "${t}"`)}try{const r=e.unit(`${t}${n.toUnit}`);if(r&&r.unit===n.toUnit)return p.set(n.toUnit,!0),`${t}${n.toUnit}`;p.set(n.toUnit,!1)}catch{p.set(n.toUnit,!1)}throw new Error(`Invalid unit "${n.toUnit}" for "${t}"`)}return"rem"===r.unit&&"px"===n.toUnit?remToPx(parseFloat(r.number),n.pluginOptions?.rootFontSize??16):"px"===r.unit&&"rem"===n.toUnit?pxToRem(parseFloat(r.number),n.pluginOptions?.rootFontSize??16):t}function remToPx(e,t){return`${formatFloat(e*t)}px`}function pxToRem(e,t){return`${formatFloat(e/t)}rem`}function formatFloat(e){if(Number.isInteger(e))return e.toString();let t=e.toFixed(5);for(let e=t.length-1;e>=0&&"."!==t[e]&&"0"===t[e];e--)t=t.slice(0,e);return t}function dereferenceTokenValues(e){const t=new Set,n=new Map;for(const[r,o]of e.entries()){const e=parseReferences(o.value);e.length&&(t.add(r),n.set(r,e))}for(const[r,o]of n.entries()){for(let n=0;n"value-reference"===e.type)))continue;const s=o.map((e=>e.value)).join(""),a=e.get(r);a.value=s,a.cssValue=e=>applyTransformsToValue(s,e),e.set(r,a),t.delete(r),n.delete(r)}if(0===t.size)return e;{const r=Array.from(e.keys()),o=[];for(const[e,t]of n.entries())for(let n=0;n"value-reference"===e.type)))throw new Error('Token "'+r+'" can not be fully resolved');const s=o.map((e=>e.value)).join(""),a=e.get(r);a.value=s,a.cssValue=e=>applyTransformsToValue(s,e),e.set(r,a),t.delete(r),n.delete(r)}if(0===t.size)return e}return e}function parseReferences(e){if("string"!=typeof e)return[];if(-1===e.indexOf("{"))return[];const t=[];let n=!1,r=!1,o="";for(let s=0;s0&&(t.push({type:"value-non-reference",value:o}),o=""),r=!0;break;case"}":if(!r)throw new Error('Unexpected "}" in "'+e+'" at '+s);if(0===o.length)throw new Error('Empty alias "{}" in "'+e+'" at '+s);{let e=o.trim();".value"===e.slice(-6)&&(e=e.slice(0,-6)),t.push({type:"value-reference",raw:e}),o=""}n=!0,r=!1;break;default:o+=a}}if(r)throw new Error('Unexpected end of alias in "'+e+'"');return o.length>0&&t.push({type:"value-non-reference",value:o}),n?t:[]}function isTokenGroup(e){return"object"==typeof e&&null!==e&&void 0===e.value}function extractTokens(e,t,n){const r=new Map;for(const o in e)if(Object.hasOwnProperty.call(e,o)){if(null===e[o]||"object"!=typeof e[o]||Array.isArray(e[o]))throw new Error(`Parsing error at "${[...t,o].join(".")}"`);const s=e[o];if(!s)throw new Error(`Parsing error at "${[...t,o].join(".")}"`);if(!isTokenGroup(s)){const e=extractStyleDictionaryV3Token(s,o,t,n);r.set(e.metadata.path.join("."),e);continue}for(const[e,a]of extractTokens(s,[...t,o],n).entries())r.set(e,a)}return r}function extractStyleDictionaryV3Tokens(e,t){return dereferenceTokenValues(extractTokens(e,[],t))}function extractStyleDictionaryTokens(e,t,n){return extractStyleDictionaryV3Tokens(t,n)}const m="6b4e71e7-4787-42f7-a092-8684961895db";function parseImport(t){const n=e(t),r={filePath:"",format:"standard",conditions:[m]};return n.walk((e=>{"function"===e.type&&"url"===e.value&&(r.filePath=e.nodes[0].value),"function"===e.type&&"format"===e.value&&(r.format=e.nodes[0].value),"function"===e.type&&"when"===e.value&&(r.conditions=e.nodes.filter((e=>"string"===e.type)).map((e=>e.value)))})),r.conditions.length||(r.conditions=[m]),r}async function tokensFromImport(e,o,s,a,i,u){const{filePath:l,format:c,conditions:f}=parseImport(i);if(!f.every((e=>s.includes(e))))return!1;let p="";try{if(l.startsWith("node_modules://")){p=r.createRequire(t.dirname(a)).resolve(l.slice(15))}else if(l.startsWith("node_modules:")){p=r.createRequire(t.dirname(a)).resolve(l.slice(13))}else p=t.resolve(t.dirname(a),l)}catch(e){throw new Error(`Failed to read ${l} with error ${e instanceof Error?e.message:e}`)}if(u.has(p))return!1;o.result.messages.push({type:"dependency",plugin:"postcss-design-tokens",file:p,parent:e.source?.input?.file}),u.add(p);const m=await n.readFile(p,"utf8"),d=JSON.parse(m);if("style-dictionary3"===c)return{filePath:t.resolve(l),tokens:extractStyleDictionaryTokens(0,d,p)};throw new Error("Unsupported format: "+c)}function mergeTokens(e,t){const n=new Map(e);for(const[e,r]of t)n.set(e,r);return n}function parsePluginOptions(e){const t={importAtRuleName:"design-tokens",is:[m],unitsAndValues:{rootFontSize:16},valueFunctionName:"design-token"};return e?("object"!=typeof e||(Array.isArray(e.is)&&(t.is=e.is.filter((e=>"string"==typeof e))),0===t.is.length&&(t.is=[m]),"object"==typeof e.unitsAndValues&&"number"==typeof e.unitsAndValues.rootFontSize&&((n=e.unitsAndValues.rootFontSize)>0&&n!==1/0)&&(t.unitsAndValues.rootFontSize=e.unitsAndValues.rootFontSize),"string"==typeof e.valueFunctionName&&(t.valueFunctionName=e.valueFunctionName),"string"==typeof e.importAtRuleName&&(t.importAtRuleName=e.importAtRuleName)),t):t;var n}function parseComponentValuesFromTokens(e){return o(e,{onParseError:e=>{throw e}})}function parseComponentValues(e){const t=l({css:e},{onParseError:e=>{throw e}}),n=[];for(;!t.endOfFile();)n.push(t.nextToken());return n.push(t.nextToken()),parseComponentValuesFromTokens(n)}function transform(e,t,n,r,o){const s=parseComponentValues(r);let a=!1;return s.forEach(((r,i)=>{if("walk"in r){{const u=transformComponentValue(r,e,t,n,o);if(u)return s.splice(i,1,...u),a=!0,!1}r.walk(((r,s)=>{if("string"==typeof s)return;const i=transformComponentValue(r.node,e,t,n,o);return i?(r.parent.value.splice(s,1,...i),a=!0,!1):void 0}))}})),a?s.map((e=>e.toString())).join(""):r}function transformComponentValue(e,t,n,r,o){if(!s(e))return;if(e.getName().toLowerCase()!==o.valueFunctionName)return;let l="",p="",m="";for(let t=0;t{const t=parsePluginOptions(e);return{postcssPlugin:"postcss-design-tokens",prepare(){let e=new Map,n=new Set;return{postcssPlugin:"postcss-design-tokens",OnceExit(){e=new Map,n=new Set},async Once(r,o){const s=[];r.walkAtRules((e=>{if(e.name.toLowerCase()!==t.importAtRuleName)return;if(!e?.source?.input?.file)return;const n=e.source.input.file,r=e.params;e.remove(),s.push({filePath:n,params:r,node:e})}));for(const a of s.values()){let s;try{if(s=await tokensFromImport(r,o,t.is,a.filePath,a.params,n),!s)continue}catch(e){a.node.warn(o.result,`Failed to import design tokens from "${a.params}" with error:\n\t`+(e instanceof Error?e.message:e));continue}o.result.messages.push({type:"dependency",plugin:"postcss-design-tokens",file:s.filePath,parent:a.filePath}),e=mergeTokens(e,s.tokens)}},Declaration(n,{result:r}){if(n.value.toLowerCase().includes(t.valueFunctionName))try{const o=transform(e,r,n,n.value,t);if(o===n.value)return;n.value=o}catch{n.warn(r,`Failed to parse and transform "${n.value}"`)}},AtRule(n,{result:r}){if(n.params.toLowerCase().includes(t.valueFunctionName))try{const o=transform(e,r,n,n.params,t);if(o===n.params)return;n.params=o}catch{n.warn(r,`Failed to parse and transform "${n.params}"`)}}}}}};creator.postcss=!0;export{creator as default}; diff --git a/plugins/postcss-design-tokens/src/data-formats/parse-import.ts b/plugins/postcss-design-tokens/src/data-formats/parse-import.ts index 822835ca6..9c27ac1d0 100644 --- a/plugins/postcss-design-tokens/src/data-formats/parse-import.ts +++ b/plugins/postcss-design-tokens/src/data-formats/parse-import.ts @@ -77,7 +77,7 @@ export async function tokensFromImport(root: Root, postcssHelpers: Helpers, buil alreadyImported.add(resolvedPath); const fileContents = await fsp.readFile(resolvedPath, 'utf8'); - const tokenContents = JSON.parse(fileContents); + const tokenContents: unknown = JSON.parse(fileContents); switch (format) { case 'style-dictionary3': diff --git a/plugins/postcss-design-tokens/src/data-formats/style-dictionary/v3/group.ts b/plugins/postcss-design-tokens/src/data-formats/style-dictionary/v3/group.ts index 7e96d77f8..dcf287861 100644 --- a/plugins/postcss-design-tokens/src/data-formats/style-dictionary/v3/group.ts +++ b/plugins/postcss-design-tokens/src/data-formats/style-dictionary/v3/group.ts @@ -6,6 +6,10 @@ export type StyleDictionaryV3TokenGroup = { [key: string]: StyleDictionaryV3TokenGroup | StyleDictionaryV3TokenValue; } +function isTokenGroup(node: unknown): node is StyleDictionaryV3TokenGroup { + return typeof node === 'object' && node !== null && typeof (node as Record)['value'] === 'undefined'; +} + function extractTokens(node: StyleDictionaryV3TokenGroup, path: Array, filePath: string): Map { const result: Map = new Map(); for (const key in node) { @@ -18,12 +22,12 @@ function extractTokens(node: StyleDictionaryV3TokenGroup, path: Array, f throw new Error(`Parsing error at "${[...path, key].join('.')}"`); } - const child = Object(node[key]); + const child = node[key]; if (!child) { throw new Error(`Parsing error at "${[...path, key].join('.')}"`); } - if (typeof child['value'] !== 'undefined') { + if (!isTokenGroup(child)) { const token = extractStyleDictionaryV3Token(child, key, path, filePath); // eslint-disable-next-line @typescript-eslint/no-non-null-assertion result.set(token.metadata!.path.join('.'), token); @@ -31,7 +35,6 @@ function extractTokens(node: StyleDictionaryV3TokenGroup, path: Array, f } for (const [tokenPath, token] of extractTokens(child, [...path, key], filePath).entries()) { - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion result.set(tokenPath, token); continue; } diff --git a/plugins/postcss-design-tokens/src/data-formats/style-dictionary/v3/value.ts b/plugins/postcss-design-tokens/src/data-formats/style-dictionary/v3/value.ts index 4a3b86ace..51a2c2c7a 100644 --- a/plugins/postcss-design-tokens/src/data-formats/style-dictionary/v3/value.ts +++ b/plugins/postcss-design-tokens/src/data-formats/style-dictionary/v3/value.ts @@ -99,7 +99,7 @@ export function applyTransformsToValue(value: string|undefined|null, transformOp } unitValidity.set(transformOptions.toUnit, false); - } catch (_) { + } catch { unitValidity.set(transformOptions.toUnit, false); } diff --git a/plugins/postcss-design-tokens/src/data-formats/toposort/toposort.ts b/plugins/postcss-design-tokens/src/data-formats/toposort/toposort.ts index 515a5e0bc..0082ba319 100644 --- a/plugins/postcss-design-tokens/src/data-formats/toposort/toposort.ts +++ b/plugins/postcss-design-tokens/src/data-formats/toposort/toposort.ts @@ -21,7 +21,7 @@ export function toposort(nodes: Array, edges: Array>): Array { let cursor = nodes.length; - const sorted: Array = new Array(cursor); + const sorted: Array = new Array(cursor) as Array; const visited: Record = {}; let i = cursor; // Better data structures make algorithm much faster. @@ -48,7 +48,7 @@ export function toposort(nodes: Array, edges: Array>): Arr let nodeRep; try { nodeRep = ', token was: ' + JSON.stringify(node); - } catch (_) { + } catch { nodeRep = ''; } throw new Error('Cyclic dependency' + nodeRep); @@ -70,6 +70,7 @@ export function toposort(nodes: Array, edges: Array>): Arr predecessors.add(node); do { const child = outgoing[--j]; + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion visit(child, nodesHash.get(child)!, predecessors); } while (j); predecessors.delete(node); @@ -80,7 +81,7 @@ export function toposort(nodes: Array, edges: Array>): Arr } function makeOutgoingEdges(arr: Array>): Map> { - const edges = new Map(); + const edges: Map> = new Map(); for (let i = 0, len = arr.length; i < len; i++) { const edge = arr[i]; if (!edges.has(edge[0])) { @@ -89,13 +90,14 @@ function makeOutgoingEdges(arr: Array>): Map> if (!edges.has(edge[1])) { edges.set(edge[1], new Set()); } - edges.get(edge[0]).add(edge[1]); + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + edges.get(edge[0])!.add(edge[1]); } return edges; } function makeNodesHash(arr: Array): Map { - const res = new Map(); + const res: Map = new Map(); for (let i = 0, len = arr.length; i < len; i++) { res.set(arr[i], i); } diff --git a/plugins/postcss-design-tokens/src/index.ts b/plugins/postcss-design-tokens/src/index.ts index 1c66dbf77..96cb17454 100644 --- a/plugins/postcss-design-tokens/src/index.ts +++ b/plugins/postcss-design-tokens/src/index.ts @@ -77,7 +77,7 @@ const creator: PluginCreator = (opts?: pluginOptions) => { } decl.value = modifiedValue; - } catch (_) { + } catch { decl.warn(result, `Failed to parse and transform "${decl.value}"`); } }, @@ -93,7 +93,7 @@ const creator: PluginCreator = (opts?: pluginOptions) => { } atRule.params = modifiedValue; - } catch(err) { + } catch { atRule.warn(result, `Failed to parse and transform "${atRule.params}"`); } }, diff --git a/plugins/postcss-dir-pseudo-class/dist/index.cjs b/plugins/postcss-dir-pseudo-class/dist/index.cjs index 5a8dce696..af592cca6 100644 --- a/plugins/postcss-dir-pseudo-class/dist/index.cjs +++ b/plugins/postcss-dir-pseudo-class/dist/index.cjs @@ -1 +1 @@ -"use strict";var e=require("postcss-selector-parser");const creator=t=>{const r=Object.assign({dir:null,preserve:!1,shadow:!1},t);return{postcssPlugin:"postcss-dir-pseudo-class",prepare(){const t=new WeakSet;return{postcssPlugin:"postcss-dir-pseudo-class",Rule(o,{result:s}){if(t.has(o))return;let a,n=!1;if(o.selector.toLowerCase().includes(":dir(")){try{a=e((t=>{t.nodes.forEach((t=>{t.walk((t=>{if("pseudo"!==t.type)return;if(":dir"!==t.value.toLowerCase())return;if(!t.nodes||!t.nodes.length)return;const a=t.nodes.toString().toLowerCase();if("rtl"!==a&&"ltr"!==a)return;const l=t.parent;if(!l)return;l.nodes.filter((e=>"pseudo"===e.type&&":dir"===e.value.toLowerCase())).length>1&&!n&&(n=!0,o.warn(s,`Hierarchical :dir pseudo class usage can't be transformed correctly to [dir] attributes. This will lead to incorrect selectors for "${o.selector}"`));const c=t.prev(),p=t.next(),i=c&&c.type&&"combinator"!==c.type,u=p&&p.type&&"combinator"!==p.type,d=p&&p.type&&("combinator"!==p.type||"combinator"===p.type&&" "===p.value);i||u||0===l.nodes.indexOf(t)&&d||1===l.nodes.length?t.remove():t.replaceWith(e.universal());const v=l.nodes[0],f=v&&"combinator"===v.type&&" "===v.value,w=v&&"tag"===v.type&&"html"===v.value.toLowerCase(),y=v&&"pseudo"===v.type&&":root"===v.value.toLowerCase();!v||w||y||f||l.prepend(e.combinator({value:" "}));const h=r.dir===a,b=e.attribute({attribute:"dir",operator:"=",quoteMark:'"',value:`"${a}"`,raws:{}}),m=e.pseudo({value:":host-context"});m.append(e.selector({value:"",nodes:[b]}));const g=e.pseudo({value:(w||y?"":"html")+":not"});g.append(e.selector({value:"",nodes:[e.attribute({attribute:"dir",operator:"=",quoteMark:'"',value:`"${"ltr"===a?"rtl":"ltr"}"`,raws:{}})]})),h?w?l.insertAfter(v,g):l.prepend(g):w?l.insertAfter(v,b):r.shadow&&!y?l.prepend(m):l.prepend(b)}))}))})).processSync(o.selector)}catch(e){return void o.warn(s,`Failed to parse selector : ${o.selector}`)}void 0!==a&&a!==o.selector&&(t.add(o),o.cloneBefore({selector:a}),r.preserve||o.remove())}}}}}};creator.postcss=!0,module.exports=creator; +"use strict";var e=require("postcss-selector-parser");const creator=t=>{const r=Object.assign({dir:null,preserve:!1,shadow:!1},t);return{postcssPlugin:"postcss-dir-pseudo-class",prepare(){const t=new WeakSet;return{postcssPlugin:"postcss-dir-pseudo-class",Rule(o,{result:s}){if(t.has(o))return;let a,n=!1;if(o.selector.toLowerCase().includes(":dir(")){try{a=e((t=>{t.nodes.forEach((t=>{t.walk((t=>{if("pseudo"!==t.type)return;if(":dir"!==t.value.toLowerCase())return;if(!t.nodes||!t.nodes.length)return;const a=t.nodes.toString().toLowerCase();if("rtl"!==a&&"ltr"!==a)return;const l=t.parent;if(!l)return;l.nodes.filter((e=>"pseudo"===e.type&&":dir"===e.value.toLowerCase())).length>1&&!n&&(n=!0,o.warn(s,`Hierarchical :dir pseudo class usage can't be transformed correctly to [dir] attributes. This will lead to incorrect selectors for "${o.selector}"`));const c=t.prev(),p=t.next(),i=c&&c.type&&"combinator"!==c.type,u=p&&p.type&&"combinator"!==p.type,d=p&&p.type&&("combinator"!==p.type||"combinator"===p.type&&" "===p.value);i||u||0===l.nodes.indexOf(t)&&d||1===l.nodes.length?t.remove():t.replaceWith(e.universal());const v=l.nodes[0],f=v&&"combinator"===v.type&&" "===v.value,w=v&&"tag"===v.type&&"html"===v.value.toLowerCase(),y=v&&"pseudo"===v.type&&":root"===v.value.toLowerCase();!v||w||y||f||l.prepend(e.combinator({value:" "}));const h=r.dir===a,b=e.attribute({attribute:"dir",operator:"=",quoteMark:'"',value:`"${a}"`,raws:{}}),m=e.pseudo({value:":host-context"});m.append(e.selector({value:"",nodes:[b]}));const g=e.pseudo({value:(w||y?"":"html")+":not"});g.append(e.selector({value:"",nodes:[e.attribute({attribute:"dir",operator:"=",quoteMark:'"',value:`"${"ltr"===a?"rtl":"ltr"}"`,raws:{}})]})),h?w?l.insertAfter(v,g):l.prepend(g):w?l.insertAfter(v,b):r.shadow&&!y?l.prepend(m):l.prepend(b)}))}))})).processSync(o.selector)}catch{return void o.warn(s,`Failed to parse selector : ${o.selector}`)}void 0!==a&&a!==o.selector&&(t.add(o),o.cloneBefore({selector:a}),r.preserve||o.remove())}}}}}};creator.postcss=!0,module.exports=creator; diff --git a/plugins/postcss-dir-pseudo-class/dist/index.mjs b/plugins/postcss-dir-pseudo-class/dist/index.mjs index 9321d9b86..dd4d5f9d4 100644 --- a/plugins/postcss-dir-pseudo-class/dist/index.mjs +++ b/plugins/postcss-dir-pseudo-class/dist/index.mjs @@ -1 +1 @@ -import e from"postcss-selector-parser";const creator=t=>{const r=Object.assign({dir:null,preserve:!1,shadow:!1},t);return{postcssPlugin:"postcss-dir-pseudo-class",prepare(){const t=new WeakSet;return{postcssPlugin:"postcss-dir-pseudo-class",Rule(o,{result:s}){if(t.has(o))return;let a,n=!1;if(o.selector.toLowerCase().includes(":dir(")){try{a=e((t=>{t.nodes.forEach((t=>{t.walk((t=>{if("pseudo"!==t.type)return;if(":dir"!==t.value.toLowerCase())return;if(!t.nodes||!t.nodes.length)return;const a=t.nodes.toString().toLowerCase();if("rtl"!==a&&"ltr"!==a)return;const l=t.parent;if(!l)return;l.nodes.filter((e=>"pseudo"===e.type&&":dir"===e.value.toLowerCase())).length>1&&!n&&(n=!0,o.warn(s,`Hierarchical :dir pseudo class usage can't be transformed correctly to [dir] attributes. This will lead to incorrect selectors for "${o.selector}"`));const c=t.prev(),p=t.next(),i=c&&c.type&&"combinator"!==c.type,d=p&&p.type&&"combinator"!==p.type,u=p&&p.type&&("combinator"!==p.type||"combinator"===p.type&&" "===p.value);i||d||0===l.nodes.indexOf(t)&&u||1===l.nodes.length?t.remove():t.replaceWith(e.universal());const v=l.nodes[0],f=v&&"combinator"===v.type&&" "===v.value,w=v&&"tag"===v.type&&"html"===v.value.toLowerCase(),y=v&&"pseudo"===v.type&&":root"===v.value.toLowerCase();!v||w||y||f||l.prepend(e.combinator({value:" "}));const h=r.dir===a,b=e.attribute({attribute:"dir",operator:"=",quoteMark:'"',value:`"${a}"`,raws:{}}),m=e.pseudo({value:":host-context"});m.append(e.selector({value:"",nodes:[b]}));const g=e.pseudo({value:(w||y?"":"html")+":not"});g.append(e.selector({value:"",nodes:[e.attribute({attribute:"dir",operator:"=",quoteMark:'"',value:`"${"ltr"===a?"rtl":"ltr"}"`,raws:{}})]})),h?w?l.insertAfter(v,g):l.prepend(g):w?l.insertAfter(v,b):r.shadow&&!y?l.prepend(m):l.prepend(b)}))}))})).processSync(o.selector)}catch(e){return void o.warn(s,`Failed to parse selector : ${o.selector}`)}void 0!==a&&a!==o.selector&&(t.add(o),o.cloneBefore({selector:a}),r.preserve||o.remove())}}}}}};creator.postcss=!0;export{creator as default}; +import e from"postcss-selector-parser";const creator=t=>{const r=Object.assign({dir:null,preserve:!1,shadow:!1},t);return{postcssPlugin:"postcss-dir-pseudo-class",prepare(){const t=new WeakSet;return{postcssPlugin:"postcss-dir-pseudo-class",Rule(o,{result:s}){if(t.has(o))return;let a,n=!1;if(o.selector.toLowerCase().includes(":dir(")){try{a=e((t=>{t.nodes.forEach((t=>{t.walk((t=>{if("pseudo"!==t.type)return;if(":dir"!==t.value.toLowerCase())return;if(!t.nodes||!t.nodes.length)return;const a=t.nodes.toString().toLowerCase();if("rtl"!==a&&"ltr"!==a)return;const l=t.parent;if(!l)return;l.nodes.filter((e=>"pseudo"===e.type&&":dir"===e.value.toLowerCase())).length>1&&!n&&(n=!0,o.warn(s,`Hierarchical :dir pseudo class usage can't be transformed correctly to [dir] attributes. This will lead to incorrect selectors for "${o.selector}"`));const c=t.prev(),p=t.next(),i=c&&c.type&&"combinator"!==c.type,d=p&&p.type&&"combinator"!==p.type,u=p&&p.type&&("combinator"!==p.type||"combinator"===p.type&&" "===p.value);i||d||0===l.nodes.indexOf(t)&&u||1===l.nodes.length?t.remove():t.replaceWith(e.universal());const v=l.nodes[0],f=v&&"combinator"===v.type&&" "===v.value,w=v&&"tag"===v.type&&"html"===v.value.toLowerCase(),y=v&&"pseudo"===v.type&&":root"===v.value.toLowerCase();!v||w||y||f||l.prepend(e.combinator({value:" "}));const h=r.dir===a,b=e.attribute({attribute:"dir",operator:"=",quoteMark:'"',value:`"${a}"`,raws:{}}),m=e.pseudo({value:":host-context"});m.append(e.selector({value:"",nodes:[b]}));const g=e.pseudo({value:(w||y?"":"html")+":not"});g.append(e.selector({value:"",nodes:[e.attribute({attribute:"dir",operator:"=",quoteMark:'"',value:`"${"ltr"===a?"rtl":"ltr"}"`,raws:{}})]})),h?w?l.insertAfter(v,g):l.prepend(g):w?l.insertAfter(v,b):r.shadow&&!y?l.prepend(m):l.prepend(b)}))}))})).processSync(o.selector)}catch{return void o.warn(s,`Failed to parse selector : ${o.selector}`)}void 0!==a&&a!==o.selector&&(t.add(o),o.cloneBefore({selector:a}),r.preserve||o.remove())}}}}}};creator.postcss=!0;export{creator as default}; diff --git a/plugins/postcss-dir-pseudo-class/src/index.ts b/plugins/postcss-dir-pseudo-class/src/index.ts index 6af9405cd..f055540e7 100644 --- a/plugins/postcss-dir-pseudo-class/src/index.ts +++ b/plugins/postcss-dir-pseudo-class/src/index.ts @@ -103,6 +103,7 @@ const creator: PluginCreator = (opts?: pluginOptions) => { node.remove(); } else { node.replaceWith( + // eslint-disable-next-line @typescript-eslint/no-unsafe-argument selectorParser.universal(), ); } @@ -186,7 +187,7 @@ const creator: PluginCreator = (opts?: pluginOptions) => { }); }); }).processSync(rule.selector); - } catch (_) { + } catch { rule.warn(result, `Failed to parse selector : ${rule.selector}`); return; } diff --git a/plugins/postcss-double-position-gradients/dist/index.cjs b/plugins/postcss-double-position-gradients/dist/index.cjs index c77f67604..219c4ce24 100644 --- a/plugins/postcss-double-position-gradients/dist/index.cjs +++ b/plugins/postcss-double-position-gradients/dist/index.cjs @@ -1 +1 @@ -"use strict";var e=require("@csstools/postcss-progressive-custom-properties"),t=require("postcss-value-parser"),s=require("@csstools/utilities");const r=/(?:repeating-)?(?:conic|linear|radial)-gradient\(/i,o=/^(?:repeating-)?(?:conic|linear|radial)-gradient$/i,i=["at","bottom","center","circle","closest-corner","closest-side","ellipse","farthest-corner","farthest-side","from","in","left","right","to","top"],isPunctuationCommaNode=e=>"div"===e.type&&","===e.value;function isNumericNode(e){try{return!1!==t.unit(e?.value)}catch(e){return!1}}const basePlugin=e=>({postcssPlugin:"postcss-double-position-gradients",Declaration(n,{result:a}){if(!r.test(n.value))return;if(s.hasFallback(n))return;if(s.hasSupportsAtRuleAncestor(n,r))return;let c;try{c=t(n.value)}catch(e){n.warn(a,`Failed to parse value '${n.value}' as a CSS gradient. Leaving the original value intact.`)}if(void 0===c)return;c.walk((e=>{if("function"!==e.type||!o.test(e.value))return;const t=e.nodes.filter((e=>"comment"!==e.type&&"space"!==e.type));let s=!1;t.forEach(((t,r,o)=>{if("word"===t.type&&i.includes(t.value.toLowerCase())&&(s=!0),"div"===t.type&&","===t.value&&(s=!1),s)return;const n=Object(o[r-1]),a=Object(o[r-2]),c=Object(o[r+1]);if(a.type&&isNumericNode(n)&&isNumericNode(t)){const s=a,r={type:"div",value:",",before:isPunctuationCommaNode(c)?c.before:"",after:isPunctuationCommaNode(c)?"":" ",sourceIndex:0,sourceEndIndex:0};e.nodes.splice(e.nodes.indexOf(t)-1,0,r,s)}}))}));const l=c.toString();l!==n.value&&(n.cloneBefore({value:l}),e?.preserve||n.remove())}});basePlugin.postcss=!0;const postcssPlugin=t=>{const s=Object.assign({enableProgressiveCustomProperties:!0,preserve:!0},t);return s.enableProgressiveCustomProperties&&s.preserve?{postcssPlugin:"postcss-double-position-gradients",plugins:[e(),basePlugin(s)]}:basePlugin(s)};postcssPlugin.postcss=!0,module.exports=postcssPlugin; +"use strict";var e=require("@csstools/postcss-progressive-custom-properties"),t=require("postcss-value-parser"),s=require("@csstools/utilities");const r=/(?:repeating-)?(?:conic|linear|radial)-gradient\(/i,o=/^(?:repeating-)?(?:conic|linear|radial)-gradient$/i,i=["at","bottom","center","circle","closest-corner","closest-side","ellipse","farthest-corner","farthest-side","from","in","left","right","to","top"];function isPunctuationCommaNode(e){return!!e&&"div"===e.type&&","===e.value}function isNumericNode(e){if(!e)return!1;try{return!1!==t.unit(e.value)}catch{return!1}}const basePlugin=e=>({postcssPlugin:"postcss-double-position-gradients",Declaration(n,{result:a}){if(!r.test(n.value))return;if(s.hasFallback(n))return;if(s.hasSupportsAtRuleAncestor(n,r))return;let u;try{u=t(n.value)}catch{n.warn(a,`Failed to parse value '${n.value}' as a CSS gradient. Leaving the original value intact.`)}if(void 0===u)return;u.walk((e=>{if("function"!==e.type||!o.test(e.value))return;const t=e.nodes.filter((e=>"comment"!==e.type&&"space"!==e.type));let s=!1;t.forEach(((t,r,o)=>{if("word"===t.type&&i.includes(t.value.toLowerCase())&&(s=!0),"div"===t.type&&","===t.value&&(s=!1),s)return;const n=o[r-1],a=o[r-2],u=o[r+1];if(a&&a.type&&isNumericNode(n)&&isNumericNode(t)){const s=a,r={type:"div",value:",",before:isPunctuationCommaNode(u)?u.before:"",after:isPunctuationCommaNode(u)?"":" ",sourceIndex:0,sourceEndIndex:0};e.nodes.splice(e.nodes.indexOf(t)-1,0,r,s)}}))}));const c=u.toString();c!==n.value&&(n.cloneBefore({value:c}),e?.preserve||n.remove())}});basePlugin.postcss=!0;const postcssPlugin=t=>{const s=Object.assign({enableProgressiveCustomProperties:!0,preserve:!0},t);return s.enableProgressiveCustomProperties&&s.preserve?{postcssPlugin:"postcss-double-position-gradients",plugins:[e(),basePlugin(s)]}:basePlugin(s)};postcssPlugin.postcss=!0,module.exports=postcssPlugin; diff --git a/plugins/postcss-double-position-gradients/dist/index.mjs b/plugins/postcss-double-position-gradients/dist/index.mjs index 24bc84670..331830240 100644 --- a/plugins/postcss-double-position-gradients/dist/index.mjs +++ b/plugins/postcss-double-position-gradients/dist/index.mjs @@ -1 +1 @@ -import e from"@csstools/postcss-progressive-custom-properties";import t from"postcss-value-parser";import{hasFallback as s,hasSupportsAtRuleAncestor as r}from"@csstools/utilities";const o=/(?:repeating-)?(?:conic|linear|radial)-gradient\(/i,i=/^(?:repeating-)?(?:conic|linear|radial)-gradient$/i,n=["at","bottom","center","circle","closest-corner","closest-side","ellipse","farthest-corner","farthest-side","from","in","left","right","to","top"],isPunctuationCommaNode=e=>"div"===e.type&&","===e.value;function isNumericNode(e){try{return!1!==t.unit(e?.value)}catch(e){return!1}}const basePlugin=e=>({postcssPlugin:"postcss-double-position-gradients",Declaration(a,{result:c}){if(!o.test(a.value))return;if(s(a))return;if(r(a,o))return;let l;try{l=t(a.value)}catch(e){a.warn(c,`Failed to parse value '${a.value}' as a CSS gradient. Leaving the original value intact.`)}if(void 0===l)return;l.walk((e=>{if("function"!==e.type||!i.test(e.value))return;const t=e.nodes.filter((e=>"comment"!==e.type&&"space"!==e.type));let s=!1;t.forEach(((t,r,o)=>{if("word"===t.type&&n.includes(t.value.toLowerCase())&&(s=!0),"div"===t.type&&","===t.value&&(s=!1),s)return;const i=Object(o[r-1]),a=Object(o[r-2]),c=Object(o[r+1]);if(a.type&&isNumericNode(i)&&isNumericNode(t)){const s=a,r={type:"div",value:",",before:isPunctuationCommaNode(c)?c.before:"",after:isPunctuationCommaNode(c)?"":" ",sourceIndex:0,sourceEndIndex:0};e.nodes.splice(e.nodes.indexOf(t)-1,0,r,s)}}))}));const u=l.toString();u!==a.value&&(a.cloneBefore({value:u}),e?.preserve||a.remove())}});basePlugin.postcss=!0;const postcssPlugin=t=>{const s=Object.assign({enableProgressiveCustomProperties:!0,preserve:!0},t);return s.enableProgressiveCustomProperties&&s.preserve?{postcssPlugin:"postcss-double-position-gradients",plugins:[e(),basePlugin(s)]}:basePlugin(s)};postcssPlugin.postcss=!0;export{postcssPlugin as default}; +import e from"@csstools/postcss-progressive-custom-properties";import t from"postcss-value-parser";import{hasFallback as r,hasSupportsAtRuleAncestor as s}from"@csstools/utilities";const o=/(?:repeating-)?(?:conic|linear|radial)-gradient\(/i,i=/^(?:repeating-)?(?:conic|linear|radial)-gradient$/i,n=["at","bottom","center","circle","closest-corner","closest-side","ellipse","farthest-corner","farthest-side","from","in","left","right","to","top"];function isPunctuationCommaNode(e){return!!e&&"div"===e.type&&","===e.value}function isNumericNode(e){if(!e)return!1;try{return!1!==t.unit(e.value)}catch{return!1}}const basePlugin=e=>({postcssPlugin:"postcss-double-position-gradients",Declaration(a,{result:c}){if(!o.test(a.value))return;if(r(a))return;if(s(a,o))return;let u;try{u=t(a.value)}catch{a.warn(c,`Failed to parse value '${a.value}' as a CSS gradient. Leaving the original value intact.`)}if(void 0===u)return;u.walk((e=>{if("function"!==e.type||!i.test(e.value))return;const t=e.nodes.filter((e=>"comment"!==e.type&&"space"!==e.type));let r=!1;t.forEach(((t,s,o)=>{if("word"===t.type&&n.includes(t.value.toLowerCase())&&(r=!0),"div"===t.type&&","===t.value&&(r=!1),r)return;const i=o[s-1],a=o[s-2],c=o[s+1];if(a&&a.type&&isNumericNode(i)&&isNumericNode(t)){const r=a,s={type:"div",value:",",before:isPunctuationCommaNode(c)?c.before:"",after:isPunctuationCommaNode(c)?"":" ",sourceIndex:0,sourceEndIndex:0};e.nodes.splice(e.nodes.indexOf(t)-1,0,s,r)}}))}));const l=u.toString();l!==a.value&&(a.cloneBefore({value:l}),e?.preserve||a.remove())}});basePlugin.postcss=!0;const postcssPlugin=t=>{const r=Object.assign({enableProgressiveCustomProperties:!0,preserve:!0},t);return r.enableProgressiveCustomProperties&&r.preserve?{postcssPlugin:"postcss-double-position-gradients",plugins:[e(),basePlugin(r)]}:basePlugin(r)};postcssPlugin.postcss=!0;export{postcssPlugin as default}; diff --git a/plugins/postcss-double-position-gradients/src/index.ts b/plugins/postcss-double-position-gradients/src/index.ts index 30a17c76c..df4e48fd1 100644 --- a/plugins/postcss-double-position-gradients/src/index.ts +++ b/plugins/postcss-double-position-gradients/src/index.ts @@ -22,12 +22,18 @@ const keywords = [ 'top', ]; -const isPunctuationCommaNode = (node: valueParser.Node): boolean => node.type === 'div' && node.value === ','; +function isPunctuationCommaNode(node?: valueParser.Node): node is valueParser.DivNode { + return !!node && node.type === 'div' && node.value === ','; +} + +function isNumericNode(node?: valueParser.Node): boolean { + if (!node) { + return false; + } -function isNumericNode(node: valueParser.Node): boolean { try { - return valueParser.unit(node?.value) !== false; - } catch (_) { + return valueParser.unit(node.value) !== false; + } catch { return false; } } @@ -57,7 +63,7 @@ const basePlugin: PluginCreator<{ preserve?: boolean }> = (opts?: { preserve?: b try { valueAST = valueParser(decl.value); - } catch (_) { + } catch { decl.warn( result, `Failed to parse value '${decl.value}' as a CSS gradient. Leaving the original value intact.`, @@ -94,10 +100,10 @@ const basePlugin: PluginCreator<{ preserve?: boolean }> = (opts?: { preserve?: b return; } - const oneValueBack = Object(currentNodes[index - 1]); - const twoValuesBack = Object(currentNodes[index - 2]); - const nextNode = Object(currentNodes[index + 1]); - const isDoublePositionLength = twoValuesBack.type && isNumericNode(oneValueBack) && isNumericNode(node); + const oneValueBack = currentNodes[index - 1]; + const twoValuesBack = currentNodes[index - 2]; + const nextNode = currentNodes[index + 1]; + const isDoublePositionLength = twoValuesBack && twoValuesBack.type && isNumericNode(oneValueBack) && isNumericNode(node); // if the argument concludes a double-position gradient if (isDoublePositionLength) { diff --git a/plugins/postcss-env-function/dist/index.cjs b/plugins/postcss-env-function/dist/index.cjs index 4577a7f33..aaf8f5142 100644 --- a/plugins/postcss-env-function/dist/index.cjs +++ b/plugins/postcss-env-function/dist/index.cjs @@ -1 +1 @@ -"use strict";var e=require("postcss-value-parser"),t=require("fs"),n=require("path"),r=require("url"),isEnvFunc=e=>e&&"function"===e.type&&"env"===e.value,getReplacedValue=(t,n)=>{const r=e(t);return r.walk((e=>{if(isEnvFunc(e)){const[t]=e.nodes;"word"===t.type&&void 0!==n[t.value]&&(e.nodes=[],e.type="word",e.value=n[t.value])}})),r.toString()};function importEnvironmentVariablesFromObject(e){return Object.assign({},Object(e).environmentVariables||Object(e)["environment-variables"])}async function importEnvironmentVariablesFromJSONFile(e){return importEnvironmentVariablesFromObject(await readJSON(n.resolve(e)))}async function importEnvironmentVariablesFromJSFile(e){const t=await import(r.pathToFileURL(n.resolve(e)));return importEnvironmentVariablesFromObject("default"in t?t.default:t)}const readFile=e=>new Promise(((n,r)=>{t.readFile(e,"utf8",((e,t)=>{e?r(e):n(t)}))})),readJSON=async e=>JSON.parse(await readFile(e));function creator(e){const t=[].concat(Object(e).importFrom||[]),r=t.map((e=>{if(e instanceof Promise)return e;if(e instanceof Function)return e();const t=e===Object(e)?e:{from:String(e)};if(t.environmentVariables||t["environment-variables"])return t;const r=String(t.from||"");return{type:(t.type||n.extname(r).slice(1)).toLowerCase(),from:r}})).reduce((async(e,t)=>{const{type:n,from:r}=await t;return"js"===n||"cjs"===n?Object.assign(e,await importEnvironmentVariablesFromJSFile(r)):"json"===n?Object.assign(e,await importEnvironmentVariablesFromJSONFile(r)):Object.assign(e,importEnvironmentVariablesFromObject(await t))}),{});const a="disableDeprecationNotice"in Object(e)&&Boolean(e.disableDeprecationNotice);let i=!1;return{postcssPlugin:"postcss-env-fn",async AtRule(e,{result:t}){let n;try{n=getReplacedValue(e.params,await r)}catch(n){e.warn(t,`Failed to parse params '${e.params}' as an environment value. Leaving the original value intact.`)}void 0!==n&&n!==e.params&&(e.params=n,a||i||(i=!0,e.warn(t,"postcss-env-function is deprecated and will be removed.\nCheck the discussion on github for more details. https://github.com/csstools/postcss-plugins/discussions/192")))},async Declaration(e,{result:t}){let n;try{n=getReplacedValue(e.value,await r)}catch(n){e.warn(t,`Failed to parse value '${e.value}' as an environment value. Leaving the original value intact.`)}void 0!==n&&n!==e.value&&(e.value=n,a||i||(i=!0,e.warn(t,"postcss-env-function is deprecated and will be removed.\nWe are looking for insights and anecdotes on how these features are used so that we can design the best alternative.\nPlease let us know if our proposal will work for you.\nVisit the discussion on github for more details. https://github.com/csstools/postcss-plugins/discussions/192")))}}}creator.postcss=!0,module.exports=creator; +"use strict";var e=require("postcss-value-parser"),t=require("fs"),n=require("path"),r=require("url"),isEnvFunc=e=>e&&"function"===e.type&&"env"===e.value,getReplacedValue=(t,n)=>{const r=e(t);return r.walk((e=>{if(isEnvFunc(e)){const[t]=e.nodes;"word"===t.type&&void 0!==n[t.value]&&(e.nodes=[],e.type="word",e.value=n[t.value])}})),r.toString()};function importEnvironmentVariablesFromObject(e){return Object.assign({},Object(e).environmentVariables||Object(e)["environment-variables"])}async function importEnvironmentVariablesFromJSONFile(e){return importEnvironmentVariablesFromObject(await readJSON(n.resolve(e)))}async function importEnvironmentVariablesFromJSFile(e){const t=await import(r.pathToFileURL(n.resolve(e)));return importEnvironmentVariablesFromObject("default"in t?t.default:t)}const readFile=e=>new Promise(((n,r)=>{t.readFile(e,"utf8",((e,t)=>{e?r(e):n(t)}))})),readJSON=async e=>JSON.parse(await readFile(e));function creator(e){const t=[].concat(Object(e).importFrom||[]),r=t.map((e=>{if(e instanceof Promise)return e;if(e instanceof Function)return e();const t=e===Object(e)?e:{from:String(e)};if(t.environmentVariables||t["environment-variables"])return t;const r=String(t.from||"");return{type:(t.type||n.extname(r).slice(1)).toLowerCase(),from:r}})).reduce((async(e,t)=>{const{type:n,from:r}=await t;return"js"===n||"cjs"===n?Object.assign(e,await importEnvironmentVariablesFromJSFile(r)):"json"===n?Object.assign(e,await importEnvironmentVariablesFromJSONFile(r)):Object.assign(e,importEnvironmentVariablesFromObject(await t))}),{});const a="disableDeprecationNotice"in Object(e)&&Boolean(e.disableDeprecationNotice);let i=!1;return{postcssPlugin:"postcss-env-fn",async AtRule(e,{result:t}){let n;try{n=getReplacedValue(e.params,await r)}catch{e.warn(t,`Failed to parse params '${e.params}' as an environment value. Leaving the original value intact.`)}void 0!==n&&n!==e.params&&(e.params=n,a||i||(i=!0,e.warn(t,"postcss-env-function is deprecated and will be removed.\nCheck the discussion on github for more details. https://github.com/csstools/postcss-plugins/discussions/192")))},async Declaration(e,{result:t}){let n;try{n=getReplacedValue(e.value,await r)}catch{e.warn(t,`Failed to parse value '${e.value}' as an environment value. Leaving the original value intact.`)}void 0!==n&&n!==e.value&&(e.value=n,a||i||(i=!0,e.warn(t,"postcss-env-function is deprecated and will be removed.\nWe are looking for insights and anecdotes on how these features are used so that we can design the best alternative.\nPlease let us know if our proposal will work for you.\nVisit the discussion on github for more details. https://github.com/csstools/postcss-plugins/discussions/192")))}}}creator.postcss=!0,module.exports=creator; diff --git a/plugins/postcss-env-function/dist/index.mjs b/plugins/postcss-env-function/dist/index.mjs index 82ce43a8c..7bd407386 100644 --- a/plugins/postcss-env-function/dist/index.mjs +++ b/plugins/postcss-env-function/dist/index.mjs @@ -1 +1 @@ -import e from"postcss-value-parser";import t from"fs";import n from"path";import a from"url";var isEnvFunc=e=>e&&"function"===e.type&&"env"===e.value,getReplacedValue=(t,n)=>{const a=e(t);return a.walk((e=>{if(isEnvFunc(e)){const[t]=e.nodes;"word"===t.type&&void 0!==n[t.value]&&(e.nodes=[],e.type="word",e.value=n[t.value])}})),a.toString()};function importEnvironmentVariablesFromObject(e){return Object.assign({},Object(e).environmentVariables||Object(e)["environment-variables"])}async function importEnvironmentVariablesFromJSONFile(e){return importEnvironmentVariablesFromObject(await readJSON(n.resolve(e)))}async function importEnvironmentVariablesFromJSFile(e){const t=await import(a.pathToFileURL(n.resolve(e)));return importEnvironmentVariablesFromObject("default"in t?t.default:t)}const readFile=e=>new Promise(((n,a)=>{t.readFile(e,"utf8",((e,t)=>{e?a(e):n(t)}))})),readJSON=async e=>JSON.parse(await readFile(e));function creator(e){const t=[].concat(Object(e).importFrom||[]),a=t.map((e=>{if(e instanceof Promise)return e;if(e instanceof Function)return e();const t=e===Object(e)?e:{from:String(e)};if(t.environmentVariables||t["environment-variables"])return t;const a=String(t.from||"");return{type:(t.type||n.extname(a).slice(1)).toLowerCase(),from:a}})).reduce((async(e,t)=>{const{type:n,from:a}=await t;return"js"===n||"cjs"===n?Object.assign(e,await importEnvironmentVariablesFromJSFile(a)):"json"===n?Object.assign(e,await importEnvironmentVariablesFromJSONFile(a)):Object.assign(e,importEnvironmentVariablesFromObject(await t))}),{});const r="disableDeprecationNotice"in Object(e)&&Boolean(e.disableDeprecationNotice);let o=!1;return{postcssPlugin:"postcss-env-fn",async AtRule(e,{result:t}){let n;try{n=getReplacedValue(e.params,await a)}catch(n){e.warn(t,`Failed to parse params '${e.params}' as an environment value. Leaving the original value intact.`)}void 0!==n&&n!==e.params&&(e.params=n,r||o||(o=!0,e.warn(t,"postcss-env-function is deprecated and will be removed.\nCheck the discussion on github for more details. https://github.com/csstools/postcss-plugins/discussions/192")))},async Declaration(e,{result:t}){let n;try{n=getReplacedValue(e.value,await a)}catch(n){e.warn(t,`Failed to parse value '${e.value}' as an environment value. Leaving the original value intact.`)}void 0!==n&&n!==e.value&&(e.value=n,r||o||(o=!0,e.warn(t,"postcss-env-function is deprecated and will be removed.\nWe are looking for insights and anecdotes on how these features are used so that we can design the best alternative.\nPlease let us know if our proposal will work for you.\nVisit the discussion on github for more details. https://github.com/csstools/postcss-plugins/discussions/192")))}}}creator.postcss=!0;export{creator as default}; +import e from"postcss-value-parser";import t from"fs";import n from"path";import a from"url";var isEnvFunc=e=>e&&"function"===e.type&&"env"===e.value,getReplacedValue=(t,n)=>{const a=e(t);return a.walk((e=>{if(isEnvFunc(e)){const[t]=e.nodes;"word"===t.type&&void 0!==n[t.value]&&(e.nodes=[],e.type="word",e.value=n[t.value])}})),a.toString()};function importEnvironmentVariablesFromObject(e){return Object.assign({},Object(e).environmentVariables||Object(e)["environment-variables"])}async function importEnvironmentVariablesFromJSONFile(e){return importEnvironmentVariablesFromObject(await readJSON(n.resolve(e)))}async function importEnvironmentVariablesFromJSFile(e){const t=await import(a.pathToFileURL(n.resolve(e)));return importEnvironmentVariablesFromObject("default"in t?t.default:t)}const readFile=e=>new Promise(((n,a)=>{t.readFile(e,"utf8",((e,t)=>{e?a(e):n(t)}))})),readJSON=async e=>JSON.parse(await readFile(e));function creator(e){const t=[].concat(Object(e).importFrom||[]),a=t.map((e=>{if(e instanceof Promise)return e;if(e instanceof Function)return e();const t=e===Object(e)?e:{from:String(e)};if(t.environmentVariables||t["environment-variables"])return t;const a=String(t.from||"");return{type:(t.type||n.extname(a).slice(1)).toLowerCase(),from:a}})).reduce((async(e,t)=>{const{type:n,from:a}=await t;return"js"===n||"cjs"===n?Object.assign(e,await importEnvironmentVariablesFromJSFile(a)):"json"===n?Object.assign(e,await importEnvironmentVariablesFromJSONFile(a)):Object.assign(e,importEnvironmentVariablesFromObject(await t))}),{});const r="disableDeprecationNotice"in Object(e)&&Boolean(e.disableDeprecationNotice);let o=!1;return{postcssPlugin:"postcss-env-fn",async AtRule(e,{result:t}){let n;try{n=getReplacedValue(e.params,await a)}catch{e.warn(t,`Failed to parse params '${e.params}' as an environment value. Leaving the original value intact.`)}void 0!==n&&n!==e.params&&(e.params=n,r||o||(o=!0,e.warn(t,"postcss-env-function is deprecated and will be removed.\nCheck the discussion on github for more details. https://github.com/csstools/postcss-plugins/discussions/192")))},async Declaration(e,{result:t}){let n;try{n=getReplacedValue(e.value,await a)}catch{e.warn(t,`Failed to parse value '${e.value}' as an environment value. Leaving the original value intact.`)}void 0!==n&&n!==e.value&&(e.value=n,r||o||(o=!0,e.warn(t,"postcss-env-function is deprecated and will be removed.\nWe are looking for insights and anecdotes on how these features are used so that we can design the best alternative.\nPlease let us know if our proposal will work for you.\nVisit the discussion on github for more details. https://github.com/csstools/postcss-plugins/discussions/192")))}}}creator.postcss=!0;export{creator as default}; diff --git a/plugins/postcss-env-function/src/index.js b/plugins/postcss-env-function/src/index.js index 7577e7dd1..e3b6c6a83 100644 --- a/plugins/postcss-env-function/src/index.js +++ b/plugins/postcss-env-function/src/index.js @@ -21,7 +21,7 @@ export default function creator(opts) { try { replacedValue = getReplacedValue(atRule.params, await environmentVariablesPromise); - } catch (error) { + } catch { atRule.warn( result, `Failed to parse params '${atRule.params}' as an environment value. Leaving the original value intact.`, @@ -46,7 +46,7 @@ export default function creator(opts) { try { replacedValue = getReplacedValue(decl.value, await environmentVariablesPromise); - } catch (error) { + } catch { decl.warn( result, `Failed to parse value '${decl.value}' as an environment value. Leaving the original value intact.`, diff --git a/plugins/postcss-extract/src/index.ts b/plugins/postcss-extract/src/index.ts index 79a4829db..3673cbee3 100644 --- a/plugins/postcss-extract/src/index.ts +++ b/plugins/postcss-extract/src/index.ts @@ -16,7 +16,6 @@ const creator: PluginCreator = (opts?: pluginOptions) => { const parsedQueries: Map = new Map(); Object.keys(options.queries ?? {}).forEach((query) => { - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion parsedQueries.set(query, selectorParser().astSync(options.queries[query])); }); diff --git a/plugins/postcss-extract/src/selector-engine/combinators/child.ts b/plugins/postcss-extract/src/selector-engine/combinators/child.ts index 436a7d75e..bf2ef0340 100644 --- a/plugins/postcss-extract/src/selector-engine/combinators/child.ts +++ b/plugins/postcss-extract/src/selector-engine/combinators/child.ts @@ -4,5 +4,7 @@ import type { NodeList } from '../../node-list'; export function childCombinator(list: NodeList): Array | Document> { return list.map((node) => { return node.parent; - }).filter((node) => !!node) as Array | Document>; + }).filter((node): node is Container | Document => { + return !!node; + }); } diff --git a/plugins/postcss-extract/src/selector-engine/matchers/attribute.ts b/plugins/postcss-extract/src/selector-engine/matchers/attribute.ts index 239f5fde7..62cd4d6cb 100644 --- a/plugins/postcss-extract/src/selector-engine/matchers/attribute.ts +++ b/plugins/postcss-extract/src/selector-engine/matchers/attribute.ts @@ -47,7 +47,7 @@ export function matchAttribute(list: NodeList, attributeName: string, attributeV if (typeof (node as unknown as Record)[matchingPropertyName] === 'boolean') { // Matches when the value is true - return ((node as unknown as Record)[matchingPropertyName] as boolean); + return ((node as unknown as Record)[matchingPropertyName]); } if (attributeValueIsNullish) { diff --git a/plugins/postcss-focus-within/dist/browser-global.js.map b/plugins/postcss-focus-within/dist/browser-global.js.map index f6bc8f087..5d2532e9e 100644 --- a/plugins/postcss-focus-within/dist/browser-global.js.map +++ b/plugins/postcss-focus-within/dist/browser-global.js.map @@ -1 +1 @@ -{"version":3,"file":"browser-global.js","sources":["../src/is-valid-replacement.mjs","../src/browser.js","../src/browser-global.js"],"sourcesContent":["const INVALID_SELECTOR_CHAR = [\n\t' ', // Can't use child selector\n\t'>', // Can't use direct child selector\n\t'~', // Can't use sibling selector\n\t':', // Can't use pseudo selector\n\t'+', // Can't use adjacent selector\n\t'@', // Can't use at\n\t'#', // Can't use id selector\n\t'(', // Can't use parenthesis\n\t')', // Can't use parenthesis\n];\n\nexport default function isValidReplacement(selector) {\n\tlet isValid = true;\n\n\t// Purposely archaic so it's interoperable in old browsers\n\tfor (let i = 0, length = INVALID_SELECTOR_CHAR.length; i < length && isValid; i++) {\n\t\tif (selector.indexOf(INVALID_SELECTOR_CHAR[i]) > -1) {\n\t\t\tisValid = false;\n\t\t}\n\t}\n\n\treturn isValid;\n}\n","/* global document */\nimport isValidReplacement from './is-valid-replacement.mjs';\nfunction generateHandler(replaceWith) {\n\tlet selector;\n\tlet remove;\n\tlet add;\n\tconst lastElements = [];\n\n\tif (replaceWith[0] === '.') {\n\t\tselector = replaceWith.slice(1);\n\t\tremove = (el) => el.classList.remove(selector);\n\t\tadd = (el) => el.classList.add(selector);\n\t} else {\n\t\t// A bit naive\n\t\tselector = replaceWith.slice(1, -1);\n\t\tremove = (el) => el.removeAttribute(selector, '');\n\t\tadd = (el) => el.setAttribute(selector, '');\n\t}\n\n\treturn function handleFocusChange() {\n\t\tlastElements.forEach(lastElement => remove(lastElement));\n\t\tlastElements.length = 0;\n\n\t\tlet activeElement = document.activeElement;\n\n\t\t// only add focus if it has not been added and is not the document element\n\t\tif (!/^(#document|HTML|BODY)$/.test(Object(activeElement).nodeName)) {\n\t\t\twhile (activeElement && activeElement.nodeType === 1) {\n\t\t\t\tadd(activeElement);\n\t\t\t\tlastElements.push(activeElement);\n\n\t\t\t\tactiveElement = activeElement.parentNode;\n\t\t\t}\n\t\t}\n\t};\n}\n\nexport default function focusWithin(opts) {\n\t// configuration\n\tconst options = {\n\t\tforce: false,\n\t\treplaceWith: '[focus-within]',\n\t};\n\n\tif (typeof opts !== 'undefined' && 'force' in opts) {\n\t\toptions.force = opts.force;\n\t}\n\n\tif (typeof opts !== 'undefined' && 'replaceWith' in opts) {\n\t\toptions.replaceWith = opts.replaceWith;\n\t}\n\n\tif (!isValidReplacement(options.replaceWith)) {\n\t\tthrow new Error(`${options.replaceWith} is not a valid replacement since it can't be applied to single elements.`);\n\t}\n\n\ttry {\n\t\tdocument.querySelector(':focus-within');\n\n\t\tif (!options.force) {\n\t\t\treturn;\n\t\t}\n\t} catch (ignoredError) { /* do nothing and continue */ }\n\n\tconst handleFocusChange = generateHandler(options.replaceWith);\n\n\tconst initialize = function initializeEventListeners() {\n\t\tif (document.documentElement.className.indexOf('js-focus-within') > -1) {\n\t\t\treturn;\n\t\t}\n\n\t\tdocument.documentElement.className = document.documentElement.className + ' js-focus-within';\n\t\tdocument.addEventListener('focus', handleFocusChange, true);\n\t\tdocument.addEventListener('blur', handleFocusChange, true);\n\t};\n\n\tif (document.readyState === 'complete') {\n\t\tinitialize();\n\t} else {\n\t\tdocument.addEventListener('DOMContentLoaded', initialize);\n\t}\n}\n","/* global self,window */\nimport { default as focusWithinInit } from './browser';\n\n(function (global) {\n\tglobal.focusWithinInit = focusWithinInit;\n}('object' === typeof window && window || 'object' === typeof self && self || {}));\n"],"names":["INVALID_SELECTOR_CHAR","isValidReplacement","selector","isValid","i","length","indexOf","focusWithin","opts","options","force","replaceWith","Error","document","querySelector","ignoredError","remove","add","lastElements","handleFocusChange","slice","el","classList","removeAttribute","setAttribute","forEach","lastElement","activeElement","test","Object","nodeName","nodeType","push","parentNode","initialize","initializeEventListeners","documentElement","className","addEventListener","readyState","window","self","focusWithinInit"],"mappings":"YAAA,IAAMA,EAAwB,CAC7B,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,KAGc,SAASC,mBAAmBC,GAI1C,IAHA,IAAIC,GAAU,EAGLC,EAAI,EAAGC,EAASL,EAAsBK,OAAQD,EAAIC,GAAUF,EAASC,IACzEF,EAASI,QAAQN,EAAsBI,KAAO,IACjDD,GAAU,GAIZ,OAAOA,CACR,CCce,SAASI,YAAYC,GAEnC,IAAMC,EAAU,CACfC,OAAO,EACPC,YAAa,kBAWd,QARoB,IAATH,GAAwB,UAAWA,IAC7C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AAU,iBAAoBC,MAAQA,MAAQ,IADtEC,gBAAkBA"} \ No newline at end of file +{"version":3,"file":"browser-global.js","sources":["../src/is-valid-replacement.mjs","../src/browser.js","../src/browser-global.js"],"sourcesContent":["const INVALID_SELECTOR_CHAR = [\n\t' ', // Can't use child selector\n\t'>', // Can't use direct child selector\n\t'~', // Can't use sibling selector\n\t':', // Can't use pseudo selector\n\t'+', // Can't use adjacent selector\n\t'@', // Can't use at\n\t'#', // Can't use id selector\n\t'(', // Can't use parenthesis\n\t')', // Can't use parenthesis\n];\n\nexport default function isValidReplacement(selector) {\n\tlet isValid = true;\n\n\t// Purposely archaic so it's interoperable in old browsers\n\tfor (let i = 0, length = INVALID_SELECTOR_CHAR.length; i < length && isValid; i++) {\n\t\tif (selector.indexOf(INVALID_SELECTOR_CHAR[i]) > -1) {\n\t\t\tisValid = false;\n\t\t}\n\t}\n\n\treturn isValid;\n}\n","import isValidReplacement from './is-valid-replacement.mjs';\nfunction generateHandler(replaceWith) {\n\tlet selector;\n\tlet remove;\n\tlet add;\n\tconst lastElements = [];\n\n\tif (replaceWith[0] === '.') {\n\t\tselector = replaceWith.slice(1);\n\t\tremove = (el) => el.classList.remove(selector);\n\t\tadd = (el) => el.classList.add(selector);\n\t} else {\n\t\t// A bit naive\n\t\tselector = replaceWith.slice(1, -1);\n\t\tremove = (el) => el.removeAttribute(selector, '');\n\t\tadd = (el) => el.setAttribute(selector, '');\n\t}\n\n\treturn function handleFocusChange() {\n\t\tlastElements.forEach(lastElement => remove(lastElement));\n\t\tlastElements.length = 0;\n\n\t\tlet activeElement = document.activeElement;\n\n\t\t// only add focus if it has not been added and is not the document element\n\t\tif (!/^(#document|HTML|BODY)$/.test(Object(activeElement).nodeName)) {\n\t\t\twhile (activeElement && activeElement.nodeType === 1) {\n\t\t\t\tadd(activeElement);\n\t\t\t\tlastElements.push(activeElement);\n\n\t\t\t\tactiveElement = activeElement.parentNode;\n\t\t\t}\n\t\t}\n\t};\n}\n\nexport default function focusWithin(opts) {\n\t// configuration\n\tconst options = {\n\t\tforce: false,\n\t\treplaceWith: '[focus-within]',\n\t};\n\n\tif (typeof opts !== 'undefined' && 'force' in opts) {\n\t\toptions.force = opts.force;\n\t}\n\n\tif (typeof opts !== 'undefined' && 'replaceWith' in opts) {\n\t\toptions.replaceWith = opts.replaceWith;\n\t}\n\n\tif (!isValidReplacement(options.replaceWith)) {\n\t\tthrow new Error(`${options.replaceWith} is not a valid replacement since it can't be applied to single elements.`);\n\t}\n\n\ttry {\n\t\tdocument.querySelector(':focus-within');\n\n\t\tif (!options.force) {\n\t\t\treturn;\n\t\t}\n\t} catch (_) {}\n\n\tconst handleFocusChange = generateHandler(options.replaceWith);\n\n\tconst initialize = function initializeEventListeners() {\n\t\tif (document.documentElement.className.indexOf('js-focus-within') > -1) {\n\t\t\treturn;\n\t\t}\n\n\t\tdocument.documentElement.className = document.documentElement.className + ' js-focus-within';\n\t\tdocument.addEventListener('focus', handleFocusChange, true);\n\t\tdocument.addEventListener('blur', handleFocusChange, true);\n\t};\n\n\tif (document.readyState === 'complete') {\n\t\tinitialize();\n\t} else {\n\t\tdocument.addEventListener('DOMContentLoaded', initialize);\n\t}\n}\n","import { default as focusWithinInit } from './browser';\n\n(function (global) {\n\tglobal.focusWithinInit = focusWithinInit;\n}('object' === typeof window && window || 'object' === typeof self && self || {}));\n"],"names":["INVALID_SELECTOR_CHAR","isValidReplacement","selector","isValid","i","length","indexOf","focusWithin","opts","options","force","replaceWith","Error","document","querySelector","_","remove","add","lastElements","handleFocusChange","slice","el","classList","removeAttribute","setAttribute","forEach","lastElement","activeElement","test","Object","nodeName","nodeType","push","parentNode","initialize","initializeEventListeners","documentElement","className","addEventListener","readyState","window","self","focusWithinInit"],"mappings":"YAAA,IAAMA,EAAwB,CAC7B,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,KAGc,SAASC,mBAAmBC,GAI1C,IAHA,IAAIC,GAAU,EAGLC,EAAI,EAAGC,EAASL,EAAsBK,OAAQ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BAAgBC,UAAY,mBAC1ExB,SAASyB,iBAAiB,QAASnB,GAAmB,GACtDN,SAASyB,iBAAiB,OAAQnB,GAAmB,KAG1B,aAAxBN,SAAS0B,WACZL,IAEArB,SAASyB,iBAAiB,mBAAoBJ,EAEhD,EC5EE,iBAAoBM,QAAUA,QAAU,iBAAoBC,MAAQA,MAAQ,IADtEC,gBAAkBA"} \ No newline at end of file diff --git a/plugins/postcss-focus-within/dist/browser.cjs.map b/plugins/postcss-focus-within/dist/browser.cjs.map index a725781d3..422699625 100644 --- a/plugins/postcss-focus-within/dist/browser.cjs.map +++ b/plugins/postcss-focus-within/dist/browser.cjs.map @@ -1 +1 @@ -{"version":3,"file":"browser.cjs","sources":["../src/is-valid-replacement.mjs","../src/browser.js"],"sourcesContent":["const INVALID_SELECTOR_CHAR = [\n\t' ', // Can't use child selector\n\t'>', // Can't use direct child selector\n\t'~', // Can't use sibling selector\n\t':', // Can't use pseudo selector\n\t'+', // Can't use adjacent selector\n\t'@', // Can't use at\n\t'#', // Can't use id selector\n\t'(', // Can't use parenthesis\n\t')', // Can't use parenthesis\n];\n\nexport default function isValidReplacement(selector) {\n\tlet isValid = true;\n\n\t// Purposely archaic so it's interoperable in old browsers\n\tfor (let i = 0, length = INVALID_SELECTOR_CHAR.length; i < length && isValid; i++) {\n\t\tif (selector.indexOf(INVALID_SELECTOR_CHAR[i]) > -1) {\n\t\t\tisValid = false;\n\t\t}\n\t}\n\n\treturn isValid;\n}\n","/* global document */\nimport isValidReplacement from './is-valid-replacement.mjs';\nfunction generateHandler(replaceWith) {\n\tlet selector;\n\tlet remove;\n\tlet add;\n\tconst lastElements = [];\n\n\tif (replaceWith[0] === '.') {\n\t\tselector = replaceWith.slice(1);\n\t\tremove = (el) => el.classList.remove(selector);\n\t\tadd = (el) => el.classList.add(selector);\n\t} else {\n\t\t// A bit naive\n\t\tselector = replaceWith.slice(1, -1);\n\t\tremove = (el) => el.removeAttribute(selector, '');\n\t\tadd = (el) => el.setAttribute(selector, '');\n\t}\n\n\treturn function handleFocusChange() {\n\t\tlastElements.forEach(lastElement => remove(lastElement));\n\t\tlastElements.length = 0;\n\n\t\tlet activeElement = document.activeElement;\n\n\t\t// only add focus if it has not been added and is not the document element\n\t\tif (!/^(#document|HTML|BODY)$/.test(Object(activeElement).nodeName)) {\n\t\t\twhile (activeElement && activeElement.nodeType === 1) {\n\t\t\t\tadd(activeElement);\n\t\t\t\tlastElements.push(activeElement);\n\n\t\t\t\tactiveElement = activeElement.parentNode;\n\t\t\t}\n\t\t}\n\t};\n}\n\nexport default function focusWithin(opts) {\n\t// configuration\n\tconst options = {\n\t\tforce: false,\n\t\treplaceWith: '[focus-within]',\n\t};\n\n\tif (typeof opts !== 'undefined' && 'force' in opts) {\n\t\toptions.force = opts.force;\n\t}\n\n\tif (typeof opts !== 'undefined' && 'replaceWith' in opts) {\n\t\toptions.replaceWith = opts.replaceWith;\n\t}\n\n\tif (!isValidReplacement(options.replaceWith)) {\n\t\tthrow new Error(`${options.replaceWith} is not a valid replacement since it can't be applied to single elements.`);\n\t}\n\n\ttry {\n\t\tdocument.querySelector(':focus-within');\n\n\t\tif (!options.force) {\n\t\t\treturn;\n\t\t}\n\t} catch (ignoredError) { /* do nothing and continue */ }\n\n\tconst handleFocusChange = generateHandler(options.replaceWith);\n\n\tconst initialize = function initializeEventListeners() {\n\t\tif (document.documentElement.className.indexOf('js-focus-within') > -1) {\n\t\t\treturn;\n\t\t}\n\n\t\tdocument.documentElement.className = document.documentElement.className + ' js-focus-within';\n\t\tdocument.addEventListener('focus', handleFocusChange, true);\n\t\tdocument.addEventListener('blur', handleFocusChange, true);\n\t};\n\n\tif (document.readyState === 'complete') {\n\t\tinitialize();\n\t} else {\n\t\tdocument.addEventListener('DOMContentLoaded', initialize);\n\t}\n}\n"],"names":["INVALID_SELECTOR_CHAR","isValidReplacement","selector","isValid","i","length","indexOf","focusWithin","opts","options","force","replaceWith","Error","document","querySelector","ignoredError","remove","add","lastElements","handleFocusChange","slice","el","classList","removeAttribute","setAttribute","forEach","lastElement","activeElement","test","Object","nodeName","nodeType","push","parentNode","initialize","initializeEventListeners","documentElement","className","addEventListener","readyState"],"mappings":"AAAA,IAAMA,EAAwB,CAC7B,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,KAGc,SAASC,mBAAmBC,GAI1C,IAHA,IAAIC,GAAU,EAGLC,EAAI,EAAGC,EAASL,EAAsBK,OAAQD,EAAIC,GAAUF,EAASC,IACzEF,EAASI,QAAQN,EAAsBI,KAAO,IACjDD,GAAU,GAIZ,OAAOA,CACR,gBCce,SAASI,YAAYC,GAEnC,IAAMC,EAAU,CACfC,OAAO,EACPC,YAAa,kBAWd,QARoB,IAATH,GAAwB,UAAWA,IAC7CC,EAAQC,MAAQF,EAAKE,YAGF,IAATF,GAAwB,gBAAiBA,IACnDC,EAAQE,YAAcH,EAAKG,cAGvBV,mBAAmBQ,EAAQE,aAC/B,MAAM,IAAIC,MAASH,EAAQE,yFAG5B,IAGC,GAFAE,SAASC,cAAc,kBAElBL,EAAQC,MACZ,MAEF,CAAE,MAAOK,GAAgB,CAEzB,IA9DwBJ,EACpBT,EACAc,EACAC,EACEC,EA0DAC,GA9DkBR,EA8DkBF,EAAQE,YA1D5CO,EAAe,GAEE,MAAnBP,EAAY,IACfT,EAAWS,EAAYS,MAAM,GAC7BJ,EAAS,SAAAA,OAACK,GAAE,OAAKA,EAAGC,UAAUN,OAAOd,EAAS,EAC9Ce,EAAM,SAAAA,IAACI,GAAE,OAAKA,EAAGC,UAAUL,IAAIf,EAAS,IAGxCA,EAAWS,EAAYS,MAAM,GAAI,GACjCJ,EAAS,SAAAA,OAACK,GAAE,OAAKA,EAAGE,gBAAgBrB,EAAU,GAAG,EACjDe,EAAM,SAAAA,IAACI,GAAE,OAAKA,EAAGG,aAAatB,EAAU,GAAG,GAGrC,SAASiB,oBACfD,EAAaO,SAAQ,SAAAC,GAAW,OAAIV,EAAOU,MAC3CR,EAAab,OAAS,EAEtB,IAAIsB,EAAgBd,SAASc,cAG7B,IAAK,0BAA0BC,KAAKC,OAAOF,GAAeG,UACzD,KAAOH,GAA4C,IAA3BA,EAAcI,UACrCd,EAAIU,GACJT,EAAac,KAAKL,GAElBA,EAAgBA,EAAcM,aAmC3BC,EAAa,SAASC,2BACvBtB,SAASuB,gBAAgBC,UAAU/B,QAAQ,oBAAsB,IAIrEO,SAASuB,gBAAgBC,UAAYxB,SAASuB,gBAAgBC,UAAY,mBAC1ExB,SAASyB,iBAAiB,QAASnB,GAAmB,GACtDN,SAASyB,iBAAiB,OAAQnB,GAAmB,KAG1B,aAAxBN,SAAS0B,WACZL,IAEArB,SAASyB,iBAAiB,mBAAoBJ,EAEhD"} \ No newline at end of file +{"version":3,"file":"browser.cjs","sources":["../src/is-valid-replacement.mjs","../src/browser.js"],"sourcesContent":["const INVALID_SELECTOR_CHAR = [\n\t' ', // Can't use child selector\n\t'>', // Can't use direct child selector\n\t'~', // Can't use sibling selector\n\t':', // Can't use pseudo selector\n\t'+', // Can't use adjacent selector\n\t'@', // Can't use at\n\t'#', // Can't use id selector\n\t'(', // Can't use parenthesis\n\t')', // Can't use parenthesis\n];\n\nexport default function isValidReplacement(selector) {\n\tlet isValid = true;\n\n\t// Purposely archaic so it's interoperable in old browsers\n\tfor (let i = 0, length = INVALID_SELECTOR_CHAR.length; i < length && isValid; i++) {\n\t\tif (selector.indexOf(INVALID_SELECTOR_CHAR[i]) > -1) {\n\t\t\tisValid = false;\n\t\t}\n\t}\n\n\treturn isValid;\n}\n","import isValidReplacement from './is-valid-replacement.mjs';\nfunction generateHandler(replaceWith) {\n\tlet selector;\n\tlet remove;\n\tlet add;\n\tconst lastElements = [];\n\n\tif (replaceWith[0] === '.') {\n\t\tselector = replaceWith.slice(1);\n\t\tremove = (el) => el.classList.remove(selector);\n\t\tadd = (el) => el.classList.add(selector);\n\t} else {\n\t\t// A bit naive\n\t\tselector = replaceWith.slice(1, -1);\n\t\tremove = (el) => el.removeAttribute(selector, '');\n\t\tadd = (el) => el.setAttribute(selector, '');\n\t}\n\n\treturn function handleFocusChange() {\n\t\tlastElements.forEach(lastElement => remove(lastElement));\n\t\tlastElements.length = 0;\n\n\t\tlet activeElement = document.activeElement;\n\n\t\t// only add focus if it has not been added and is not the document element\n\t\tif (!/^(#document|HTML|BODY)$/.test(Object(activeElement).nodeName)) {\n\t\t\twhile (activeElement && activeElement.nodeType === 1) {\n\t\t\t\tadd(activeElement);\n\t\t\t\tlastElements.push(activeElement);\n\n\t\t\t\tactiveElement = activeElement.parentNode;\n\t\t\t}\n\t\t}\n\t};\n}\n\nexport default function focusWithin(opts) {\n\t// configuration\n\tconst options = {\n\t\tforce: false,\n\t\treplaceWith: '[focus-within]',\n\t};\n\n\tif (typeof opts !== 'undefined' && 'force' in opts) {\n\t\toptions.force = opts.force;\n\t}\n\n\tif (typeof opts !== 'undefined' && 'replaceWith' in opts) {\n\t\toptions.replaceWith = opts.replaceWith;\n\t}\n\n\tif (!isValidReplacement(options.replaceWith)) {\n\t\tthrow new Error(`${options.replaceWith} is not a valid replacement since it can't be applied to single elements.`);\n\t}\n\n\ttry {\n\t\tdocument.querySelector(':focus-within');\n\n\t\tif (!options.force) {\n\t\t\treturn;\n\t\t}\n\t} catch (_) {}\n\n\tconst handleFocusChange = generateHandler(options.replaceWith);\n\n\tconst initialize = function initializeEventListeners() {\n\t\tif (document.documentElement.className.indexOf('js-focus-within') > -1) {\n\t\t\treturn;\n\t\t}\n\n\t\tdocument.documentElement.className = document.documentElement.className + ' js-focus-within';\n\t\tdocument.addEventListener('focus', handleFocusChange, true);\n\t\tdocument.addEventListener('blur', handleFocusChange, true);\n\t};\n\n\tif (document.readyState === 'complete') {\n\t\tinitialize();\n\t} else {\n\t\tdocument.addEventListener('DOMContentLoaded', initialize);\n\t}\n}\n"],"names":["INVALID_SELECTOR_CHAR","isValidReplacement","selector","isValid","i","length","indexOf","focusWithin","opts","options","force","replaceWith","Error","document","querySelector","_","remove","add","lastElements","handleFocusChange","slice","el","classList","removeAttribute","setAttribute","forEach","lastElement","activeElement","test","Object","nodeName","nodeType","push","parentNode","initialize","initializeEventListeners","documentElement","className","addEventListener","readyState"],"mappings":"AAAA,IAAMA,EAAwB,CAC7B,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,KAGc,SAASC,mBAAmBC,GAI1C,IAHA,IAAIC,GAAU,EAGLC,EAAI,EAAGC,EAASL,EAAsBK,OAAQD,EAAIC,GAAUF,EAASC,IACzEF,EAASI,QAAQN,EAAsBI,KAAO,IACjDD,GAAU,GAIZ,OAAOA,CACR,gBCae,SAASI,YAAYC,GAEnC,IAAMC,EAAU,CACfC,OAAO,EACPC,YAAa,kBAWd,QARoB,IAATH,GAAwB,UAAWA,IAC7CC,EAAQC,MAAQF,EAAKE,YAGF,IAATF,GAAwB,gBAAiBA,IACnDC,EAAQE,YAAcH,EAAKG,cAGvBV,mBAAmBQ,EAAQE,aAC/B,MAAM,IAAIC,MAASH,EAAQE,yFAG5B,IAGC,GAFAE,SAASC,cAAc,kBAElBL,EAAQC,MACZ,MAEF,CAAE,MAAOK,GAAI,CAEb,IA9DwBJ,EACpBT,EACAc,EACAC,EACEC,EA0DAC,GA9DkBR,EA8DkBF,EAAQE,YA1D5CO,EAAe,GAEE,MAAnBP,EAAY,IACfT,EAAWS,EAAYS,MAAM,GAC7BJ,EAAS,SAAAA,OAACK,GAAE,OAAKA,EAAGC,UAAUN,OAAOd,EAAS,EAC9Ce,EAAM,SAAAA,IAACI,GAAE,OAAKA,EAAGC,UAAUL,IAAIf,EAAS,IAGxCA,EAAWS,EAAYS,MAAM,GAAI,GACjCJ,EAAS,SAAAA,OAACK,GAAE,OAAKA,EAAGE,gBAAgBrB,EAAU,GAAG,EACjDe,EAAM,SAAAA,IAACI,GAAE,OAAKA,EAAGG,aAAatB,EAAU,GAAG,GAGrC,SAASiB,oBACfD,EAAaO,SAAQ,SAAAC,GAAW,OAAIV,EAAOU,MAC3CR,EAAab,OAAS,EAEtB,IAAIsB,EAAgBd,SAASc,cAG7B,IAAK,0BAA0BC,KAAKC,OAAOF,GAAeG,UACzD,KAAOH,GAA4C,IAA3BA,EAAcI,UACrCd,EAAIU,GACJT,EAAac,KAAKL,GAElBA,EAAgBA,EAAcM,aAmC3BC,EAAa,SAASC,2BACvBtB,SAASuB,gBAAgBC,UAAU/B,QAAQ,oBAAsB,IAIrEO,SAASuB,gBAAgBC,UAAYxB,SAASuB,gBAAgBC,UAAY,mBAC1ExB,SAASyB,iBAAiB,QAASnB,GAAmB,GACtDN,SAASyB,iBAAiB,OAAQnB,GAAmB,KAG1B,aAAxBN,SAAS0B,WACZL,IAEArB,SAASyB,iBAAiB,mBAAoBJ,EAEhD"} \ No newline at end of file diff --git a/plugins/postcss-focus-within/dist/browser.mjs.map b/plugins/postcss-focus-within/dist/browser.mjs.map index 66b4ca10e..345bf58b0 100644 --- a/plugins/postcss-focus-within/dist/browser.mjs.map +++ b/plugins/postcss-focus-within/dist/browser.mjs.map @@ -1 +1 @@ -{"version":3,"file":"browser.mjs","sources":["../src/is-valid-replacement.mjs","../src/browser.js"],"sourcesContent":["const INVALID_SELECTOR_CHAR = [\n\t' ', // Can't use child selector\n\t'>', // Can't use direct child selector\n\t'~', // Can't use sibling selector\n\t':', // Can't use pseudo selector\n\t'+', // Can't use adjacent selector\n\t'@', // Can't use at\n\t'#', // Can't use id selector\n\t'(', // Can't use parenthesis\n\t')', // Can't use parenthesis\n];\n\nexport default function isValidReplacement(selector) {\n\tlet isValid = true;\n\n\t// Purposely archaic so it's interoperable in old browsers\n\tfor (let i = 0, length = INVALID_SELECTOR_CHAR.length; i < length && isValid; i++) {\n\t\tif (selector.indexOf(INVALID_SELECTOR_CHAR[i]) > -1) {\n\t\t\tisValid = false;\n\t\t}\n\t}\n\n\treturn isValid;\n}\n","/* global document */\nimport isValidReplacement from './is-valid-replacement.mjs';\nfunction generateHandler(replaceWith) {\n\tlet selector;\n\tlet remove;\n\tlet add;\n\tconst lastElements = [];\n\n\tif (replaceWith[0] === '.') {\n\t\tselector = replaceWith.slice(1);\n\t\tremove = (el) => el.classList.remove(selector);\n\t\tadd = (el) => el.classList.add(selector);\n\t} else {\n\t\t// A bit naive\n\t\tselector = replaceWith.slice(1, -1);\n\t\tremove = (el) => el.removeAttribute(selector, '');\n\t\tadd = (el) => el.setAttribute(selector, '');\n\t}\n\n\treturn function handleFocusChange() {\n\t\tlastElements.forEach(lastElement => remove(lastElement));\n\t\tlastElements.length = 0;\n\n\t\tlet activeElement = document.activeElement;\n\n\t\t// only add focus if it has not been added and is not the document element\n\t\tif (!/^(#document|HTML|BODY)$/.test(Object(activeElement).nodeName)) {\n\t\t\twhile (activeElement && activeElement.nodeType === 1) {\n\t\t\t\tadd(activeElement);\n\t\t\t\tlastElements.push(activeElement);\n\n\t\t\t\tactiveElement = activeElement.parentNode;\n\t\t\t}\n\t\t}\n\t};\n}\n\nexport default function focusWithin(opts) {\n\t// configuration\n\tconst options = {\n\t\tforce: false,\n\t\treplaceWith: '[focus-within]',\n\t};\n\n\tif (typeof opts !== 'undefined' && 'force' in opts) {\n\t\toptions.force = opts.force;\n\t}\n\n\tif (typeof opts !== 'undefined' && 'replaceWith' in opts) {\n\t\toptions.replaceWith = opts.replaceWith;\n\t}\n\n\tif (!isValidReplacement(options.replaceWith)) {\n\t\tthrow new Error(`${options.replaceWith} is not a valid replacement since it can't be applied to single elements.`);\n\t}\n\n\ttry {\n\t\tdocument.querySelector(':focus-within');\n\n\t\tif (!options.force) {\n\t\t\treturn;\n\t\t}\n\t} catch (ignoredError) { /* do nothing and continue */ }\n\n\tconst handleFocusChange = generateHandler(options.replaceWith);\n\n\tconst initialize = function initializeEventListeners() {\n\t\tif (document.documentElement.className.indexOf('js-focus-within') > -1) {\n\t\t\treturn;\n\t\t}\n\n\t\tdocument.documentElement.className = document.documentElement.className + ' js-focus-within';\n\t\tdocument.addEventListener('focus', handleFocusChange, true);\n\t\tdocument.addEventListener('blur', handleFocusChange, true);\n\t};\n\n\tif (document.readyState === 'complete') {\n\t\tinitialize();\n\t} else {\n\t\tdocument.addEventListener('DOMContentLoaded', initialize);\n\t}\n}\n"],"names":["INVALID_SELECTOR_CHAR","isValidReplacement","selector","isValid","i","length","indexOf","focusWithin","opts","options","force","replaceWith","Error","document","querySelector","ignoredError","remove","add","lastElements","handleFocusChange","slice","el","classList","removeAttribute","setAttribute","forEach","lastElement","activeElement","test","Object","nodeName","nodeType","push","parentNode","initialize","initializeEventListeners","documentElement","className","addEventListener","readyState"],"mappings":"AAAA,IAAMA,EAAwB,CAC7B,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,KAGc,SAASC,mBAAmBC,GAI1C,IAHA,IAAIC,GAAU,EAGLC,EAAI,EAAGC,EAASL,EAAsBK,OAAQD,EAAIC,GAAUF,EAASC,IACzEF,EAASI,QAAQN,EAAsBI,KAAO,IACjDD,GAAU,GAIZ,OAAOA,CACR,CCce,SAASI,YAAYC,GAEnC,IAAMC,EAAU,CACfC,OAAO,EACPC,YAAa,kBAWd,QARoB,IAATH,GAAwB,UAAWA,IAC7CC,EAAQC,MAAQF,EAAKE,YAGF,IAATF,GAAwB,gBAAiBA,IACnDC,EAAQE,YAAcH,EAAKG,cAGvBV,mBAAmBQ,EAAQE,aAC/B,MAAM,IAAIC,MAASH,EAAQE,yFAG5B,IAGC,GAFAE,SAASC,cAAc,kBAElBL,EAAQC,MACZ,MAEF,CAAE,MAAOK,GAAgB,CAEzB,IA9DwBJ,EACpBT,EACAc,EACAC,EACEC,EA0DAC,GA9DkBR,EA8DkBF,EAAQE,YA1D5CO,EAAe,GAEE,MAAnBP,EAAY,IACfT,EAAWS,EAAYS,MAAM,GAC7BJ,EAAS,SAAAA,OAACK,GAAE,OAAKA,EAAGC,UAAUN,OAAOd,EAAS,EAC9Ce,EAAM,SAAAA,IAACI,GAAE,OAAKA,EAAGC,UAAUL,IAAIf,EAAS,IAGxCA,EAAWS,EAAYS,MAAM,GAAI,GACjCJ,EAAS,SAAAA,OAACK,GAAE,OAAKA,EAAGE,gBAAgBrB,EAAU,GAAG,EACjDe,EAAM,SAAAA,IAACI,GAAE,OAAKA,EAAGG,aAAatB,EAAU,GAAG,GAGrC,SAASiB,oBACfD,EAAaO,SAAQ,SAAAC,GAAW,OAAIV,EAAOU,MAC3CR,EAAab,OAAS,EAEtB,IAAIsB,EAAgBd,SAASc,cAG7B,IAAK,0BAA0BC,KAAKC,OAAOF,GAAeG,UACzD,KAAOH,GAA4C,IAA3BA,EAAcI,UACrCd,EAAIU,GACJT,EAAac,KAAKL,GAElBA,EAAgBA,EAAcM,aAmC3BC,EAAa,SAASC,2BACvBtB,SAASuB,gBAAgBC,UAAU/B,QAAQ,oBAAsB,IAIrEO,SAASuB,gBAAgBC,UAAYxB,SAASuB,gBAAgBC,UAAY,mBAC1ExB,SAASyB,iBAAiB,QAASnB,GAAmB,GACtDN,SAASyB,iBAAiB,OAAQnB,GAAmB,KAG1B,aAAxBN,SAAS0B,WACZL,IAEArB,SAASyB,iBAAiB,mBAAoBJ,EAEhD"} \ No newline at end of file +{"version":3,"file":"browser.mjs","sources":["../src/is-valid-replacement.mjs","../src/browser.js"],"sourcesContent":["const INVALID_SELECTOR_CHAR = [\n\t' ', // Can't use child selector\n\t'>', // Can't use direct child selector\n\t'~', // Can't use sibling selector\n\t':', // Can't use pseudo selector\n\t'+', // Can't use adjacent selector\n\t'@', // Can't use at\n\t'#', // Can't use id selector\n\t'(', // Can't use parenthesis\n\t')', // Can't use parenthesis\n];\n\nexport default function isValidReplacement(selector) {\n\tlet isValid = true;\n\n\t// Purposely archaic so it's interoperable in old browsers\n\tfor (let i = 0, length = INVALID_SELECTOR_CHAR.length; i < length && isValid; i++) {\n\t\tif (selector.indexOf(INVALID_SELECTOR_CHAR[i]) > -1) {\n\t\t\tisValid = false;\n\t\t}\n\t}\n\n\treturn isValid;\n}\n","import isValidReplacement from './is-valid-replacement.mjs';\nfunction generateHandler(replaceWith) {\n\tlet selector;\n\tlet remove;\n\tlet add;\n\tconst lastElements = [];\n\n\tif (replaceWith[0] === '.') {\n\t\tselector = replaceWith.slice(1);\n\t\tremove = (el) => el.classList.remove(selector);\n\t\tadd = (el) => el.classList.add(selector);\n\t} else {\n\t\t// A bit naive\n\t\tselector = replaceWith.slice(1, -1);\n\t\tremove = (el) => el.removeAttribute(selector, '');\n\t\tadd = (el) => el.setAttribute(selector, '');\n\t}\n\n\treturn function handleFocusChange() {\n\t\tlastElements.forEach(lastElement => remove(lastElement));\n\t\tlastElements.length = 0;\n\n\t\tlet activeElement = document.activeElement;\n\n\t\t// only add focus if it has not been added and is not the document element\n\t\tif (!/^(#document|HTML|BODY)$/.test(Object(activeElement).nodeName)) {\n\t\t\twhile (activeElement && activeElement.nodeType === 1) {\n\t\t\t\tadd(activeElement);\n\t\t\t\tlastElements.push(activeElement);\n\n\t\t\t\tactiveElement = activeElement.parentNode;\n\t\t\t}\n\t\t}\n\t};\n}\n\nexport default function focusWithin(opts) {\n\t// configuration\n\tconst options = {\n\t\tforce: false,\n\t\treplaceWith: '[focus-within]',\n\t};\n\n\tif (typeof opts !== 'undefined' && 'force' in opts) {\n\t\toptions.force = opts.force;\n\t}\n\n\tif (typeof opts !== 'undefined' && 'replaceWith' in opts) {\n\t\toptions.replaceWith = opts.replaceWith;\n\t}\n\n\tif (!isValidReplacement(options.replaceWith)) {\n\t\tthrow new Error(`${options.replaceWith} is not a valid replacement since it can't be applied to single elements.`);\n\t}\n\n\ttry {\n\t\tdocument.querySelector(':focus-within');\n\n\t\tif (!options.force) {\n\t\t\treturn;\n\t\t}\n\t} catch (_) {}\n\n\tconst handleFocusChange = generateHandler(options.replaceWith);\n\n\tconst initialize = function initializeEventListeners() {\n\t\tif (document.documentElement.className.indexOf('js-focus-within') > -1) {\n\t\t\treturn;\n\t\t}\n\n\t\tdocument.documentElement.className = document.documentElement.className + ' js-focus-within';\n\t\tdocument.addEventListener('focus', handleFocusChange, true);\n\t\tdocument.addEventListener('blur', handleFocusChange, true);\n\t};\n\n\tif (document.readyState === 'complete') {\n\t\tinitialize();\n\t} else {\n\t\tdocument.addEventListener('DOMContentLoaded', initialize);\n\t}\n}\n"],"names":["INVALID_SELECTOR_CHAR","isValidReplacement","selector","isValid","i","length","indexOf","focusWithin","opts","options","force","replaceWith","Error","document","querySelector","_","remove","add","lastElements","handleFocusChange","slice","el","classList","removeAttribute","setAttribute","forEach","lastElement","activeElement","test","Object","nodeName","nodeType","push","parentNode","initialize","initializeEventListeners","documentElement","className","addEventListener","readyState"],"mappings":"AAAA,IAAMA,EAAwB,CAC7B,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,KAGc,SAASC,mBAAmBC,GAI1C,IAHA,IAAIC,GAAU,EAGLC,EAAI,EAAGC,EAASL,EAAsBK,OAAQD,EAAIC,GAAUF,EAASC,IACzEF,EAASI,QAAQN,EAAsBI,KAAO,IACjDD,GAAU,GAIZ,OAAOA,CACR,CCae,SAASI,YAAYC,GAEnC,IAAMC,EAAU,CACfC,OAAO,EACPC,YAAa,kBAWd,QARoB,IAATH,GAAwB,UAAWA,IAC7CC,EAAQC,MAAQF,EAAKE,YAGF,IAATF,GAAwB,gBAAiBA,IACnDC,EAAQE,YAAcH,EAAKG,cAGvBV,mBAAmBQ,EAAQE,aAC/B,MAAM,IAAIC,MAASH,EAAQE,yFAG5B,IAGC,GAFAE,SAASC,cAAc,kBAElBL,EAAQC,MACZ,MAEF,CAAE,MAAOK,GAAI,CAEb,IA9DwBJ,EACpBT,EACAc,EACAC,EACEC,EA0DAC,GA9DkBR,EA8DkBF,EAAQE,YA1D5CO,EAAe,GAEE,MAAnBP,EAAY,IACfT,EAAWS,EAAYS,MAAM,GAC7BJ,EAAS,SAAAA,OAACK,GAAE,OAAKA,EAAGC,UAAUN,OAAOd,EAAS,EAC9Ce,EAAM,SAAAA,IAACI,GAAE,OAAKA,EAAGC,UAAUL,IAAIf,EAAS,IAGxCA,EAAWS,EAAYS,MAAM,GAAI,GACjCJ,EAAS,SAAAA,OAACK,GAAE,OAAKA,EAAGE,gBAAgBrB,EAAU,GAAG,EACjDe,EAAM,SAAAA,IAACI,GAAE,OAAKA,EAAGG,aAAatB,EAAU,GAAG,GAGrC,SAASiB,oBACfD,EAAaO,SAAQ,SAAAC,GAAW,OAAIV,EAAOU,MAC3CR,EAAab,OAAS,EAEtB,IAAIsB,EAAgBd,SAASc,cAG7B,IAAK,0BAA0BC,KAAKC,OAAOF,GAAeG,UACzD,KAAOH,GAA4C,IAA3BA,EAAcI,UACrCd,EAAIU,GACJT,EAAac,KAAKL,GAElBA,EAAgBA,EAAcM,aAmC3BC,EAAa,SAASC,2BACvBtB,SAASuB,gBAAgBC,UAAU/B,QAAQ,oBAAsB,IAIrEO,SAASuB,gBAAgBC,UAAYxB,SAASuB,gBAAgBC,UAAY,mBAC1ExB,SAASyB,iBAAiB,QAASnB,GAAmB,GACtDN,SAASyB,iBAAiB,OAAQnB,GAAmB,KAG1B,aAAxBN,SAAS0B,WACZL,IAEArB,SAASyB,iBAAiB,mBAAoBJ,EAEhD"} \ No newline at end of file diff --git a/plugins/postcss-focus-within/src/browser-global.js b/plugins/postcss-focus-within/src/browser-global.js index 2a45d68ed..e284520a4 100644 --- a/plugins/postcss-focus-within/src/browser-global.js +++ b/plugins/postcss-focus-within/src/browser-global.js @@ -1,4 +1,3 @@ -/* global self,window */ import { default as focusWithinInit } from './browser'; (function (global) { diff --git a/plugins/postcss-focus-within/src/browser.js b/plugins/postcss-focus-within/src/browser.js index 72234467f..131b694d7 100644 --- a/plugins/postcss-focus-within/src/browser.js +++ b/plugins/postcss-focus-within/src/browser.js @@ -1,4 +1,3 @@ -/* global document */ import isValidReplacement from './is-valid-replacement.mjs'; function generateHandler(replaceWith) { let selector; @@ -60,7 +59,7 @@ export default function focusWithin(opts) { if (!options.force) { return; } - } catch (ignoredError) { /* do nothing and continue */ } + } catch (_) {} const handleFocusChange = generateHandler(options.replaceWith); diff --git a/plugins/postcss-gamut-mapping/src/index.ts b/plugins/postcss-gamut-mapping/src/index.ts index 60b296f89..d7532a896 100644 --- a/plugins/postcss-gamut-mapping/src/index.ts +++ b/plugins/postcss-gamut-mapping/src/index.ts @@ -169,6 +169,7 @@ const creator: PluginCreator = () => { const parentClone = parent.clone(); parentClone.removeAll(); + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access parentClone.raws.before = '\n'; const clone = item.clone(); diff --git a/plugins/postcss-image-set-function/dist/index.cjs b/plugins/postcss-image-set-function/dist/index.cjs index 8e33821a3..fc9e6975b 100644 --- a/plugins/postcss-image-set-function/dist/index.cjs +++ b/plugins/postcss-image-set-function/dist/index.cjs @@ -1 +1 @@ -"use strict";var e=require("postcss-value-parser"),t=require("@csstools/utilities");const n=/^(?:cross-fade|image|(?:repeating-)?(?:conic|linear|radial)-gradient|url|var)$/i;function getImage(t){return!(!t||!t.type)&&("string"===t.type?"url("+e.stringify(t)+")":!("function"!==t.type||!n.test(t.value))&&e.stringify(t))}const i=new Map([["dpcm",2.54],["dpi",1],["dppx",96],["x",96]]);function getMedia(e,t,n){if("boolean"==typeof e)return!1;const i=Math.floor(e/96*100)/100;return t.atRule({name:"media",params:`(-webkit-min-device-pixel-ratio: ${i}), (min-resolution: ${e}dpi)`,source:n.source})}function getMediaDPI(t){if(!t)return!1;if("word"!==t.type)return!1;if(!isNumericNode(t))return!1;const n=e.unit(t.value);if(!n)return!1;const r=i.get(n.unit.toLowerCase());return!!r&&Number(n.number)*r}function isNumericNode(t){if(!t||!t.value)return!1;try{return!1!==e.unit(t.value)}catch(e){return!1}}const handleInvalidation=(e,t,n)=>{if("warn"===e.oninvalid)e.decl.warn(e.result,t,{word:String(n)});else if("throw"===e.oninvalid)throw e.decl.error(t,{word:String(n)})},processImageSet=(t,n,i)=>{const r=n.parent;if(!r)return;const o=new Map,s=n.value;for(let r=0;re-t)),u=l.map((e=>o.get(e)?.atRule)).filter((e=>!!e));if(!u.length)return;const c=o.get(l[0])?.value;if(!c)return;const f=u.slice(1);f.length&&r.after(f),n.cloneBefore({value:c.trim()}),i.preserve||(n.remove(),r.nodes?.length||r.remove())},r=/(?:^|[^\w-])(?:-webkit-)?image-set\(/i,o=/^(?:-webkit-)?image-set$/i,creator=n=>{const i=!("preserve"in Object(n))||Boolean(n?.preserve),s="onInvalid"in Object(n)?n?.onInvalid:"ignore";if("oninvalid"in Object(n))throw new Error('"oninvalid" was changed to "onInvalid" to match other plugins with similar options');return{postcssPlugin:"postcss-image-set-function",Declaration(n,{result:a,postcss:l}){const u=n.value;if(!r.test(u))return;if(t.hasFallback(n))return;let c;try{c=e(u)}catch(e){n.warn(a,`Failed to parse value '${u}' as an image-set function. Leaving the original value intact.`)}if(void 0===c)return;const f=[];c.walk((t=>{if("function"!==t.type)return;if(!o.test(t.value))return;let i=!1;if(e.walk(t.nodes,(e=>{"function"===e.type&&o.test(e.value)&&(i=!0)})),i)return handleInvalidation({decl:n,oninvalid:s,result:a},"nested image-set functions are not allowed",e.stringify(t)),!1;const r=t.nodes.filter((e=>"comment"!==e.type&&"space"!==e.type));f.push({imageSetFunction:t,imageSetOptionNodes:r})})),processImageSet(f,n,{decl:n,oninvalid:s,preserve:i,result:a,postcss:l})}}};creator.postcss=!0,module.exports=creator; +"use strict";var e=require("postcss-value-parser"),t=require("@csstools/utilities");const n=/^(?:cross-fade|image|(?:repeating-)?(?:conic|linear|radial)-gradient|url|var)$/i;function getImage(t){return!(!t||!t.type)&&("string"===t.type?"url("+e.stringify(t)+")":!("function"!==t.type||!n.test(t.value))&&e.stringify(t))}const i=new Map([["dpcm",2.54],["dpi",1],["dppx",96],["x",96]]);function getMedia(e,t,n){if("boolean"==typeof e)return!1;const i=Math.floor(e/96*100)/100;return t.atRule({name:"media",params:`(-webkit-min-device-pixel-ratio: ${i}), (min-resolution: ${e}dpi)`,source:n.source})}function getMediaDPI(t){if(!t)return!1;if("word"!==t.type)return!1;if(!isNumericNode(t))return!1;const n=e.unit(t.value);if(!n)return!1;const r=i.get(n.unit.toLowerCase());return!!r&&Number(n.number)*r}function isNumericNode(t){if(!t||!t.value)return!1;try{return!1!==e.unit(t.value)}catch{return!1}}const handleInvalidation=(e,t,n)=>{if("warn"===e.oninvalid)e.decl.warn(e.result,t,{word:String(n)});else if("throw"===e.oninvalid)throw e.decl.error(t,{word:String(n)})},processImageSet=(t,n,i)=>{const r=n.parent;if(!r)return;const o=new Map,s=n.value;for(let r=0;re-t)),u=l.map((e=>o.get(e)?.atRule)).filter((e=>!!e));if(!u.length)return;const c=o.get(l[0])?.value;if(!c)return;const f=u.slice(1);f.length&&r.after(f),n.cloneBefore({value:c.trim()}),i.preserve||(n.remove(),r.nodes?.length||r.remove())},r=/(?:^|[^\w-])(?:-webkit-)?image-set\(/i,o=/^(?:-webkit-)?image-set$/i,creator=n=>{const i=!("preserve"in Object(n))||Boolean(n?.preserve),s="onInvalid"in Object(n)?n?.onInvalid:"ignore";if("oninvalid"in Object(n))throw new Error('"oninvalid" was changed to "onInvalid" to match other plugins with similar options');return{postcssPlugin:"postcss-image-set-function",Declaration(n,{result:a,postcss:l}){const u=n.value;if(!r.test(u))return;if(t.hasFallback(n))return;let c;try{c=e(u)}catch{n.warn(a,`Failed to parse value '${u}' as an image-set function. Leaving the original value intact.`)}if(void 0===c)return;const f=[];c.walk((t=>{if("function"!==t.type)return;if(!o.test(t.value))return;let i=!1;if(e.walk(t.nodes,(e=>{"function"===e.type&&o.test(e.value)&&(i=!0)})),i)return handleInvalidation({decl:n,oninvalid:s,result:a},"nested image-set functions are not allowed",e.stringify(t)),!1;const r=t.nodes.filter((e=>"comment"!==e.type&&"space"!==e.type));f.push({imageSetFunction:t,imageSetOptionNodes:r})})),processImageSet(f,n,{decl:n,oninvalid:s,preserve:i,result:a,postcss:l})}}};creator.postcss=!0,module.exports=creator; diff --git a/plugins/postcss-image-set-function/dist/index.mjs b/plugins/postcss-image-set-function/dist/index.mjs index b07e52627..754293294 100644 --- a/plugins/postcss-image-set-function/dist/index.mjs +++ b/plugins/postcss-image-set-function/dist/index.mjs @@ -1 +1 @@ -import e from"postcss-value-parser";import{hasFallback as t}from"@csstools/utilities";const n=/^(?:cross-fade|image|(?:repeating-)?(?:conic|linear|radial)-gradient|url|var)$/i;function getImage(t){return!(!t||!t.type)&&("string"===t.type?"url("+e.stringify(t)+")":!("function"!==t.type||!n.test(t.value))&&e.stringify(t))}const i=new Map([["dpcm",2.54],["dpi",1],["dppx",96],["x",96]]);function getMedia(e,t,n){if("boolean"==typeof e)return!1;const i=Math.floor(e/96*100)/100;return t.atRule({name:"media",params:`(-webkit-min-device-pixel-ratio: ${i}), (min-resolution: ${e}dpi)`,source:n.source})}function getMediaDPI(t){if(!t)return!1;if("word"!==t.type)return!1;if(!isNumericNode(t))return!1;const n=e.unit(t.value);if(!n)return!1;const r=i.get(n.unit.toLowerCase());return!!r&&Number(n.number)*r}function isNumericNode(t){if(!t||!t.value)return!1;try{return!1!==e.unit(t.value)}catch(e){return!1}}const handleInvalidation=(e,t,n)=>{if("warn"===e.oninvalid)e.decl.warn(e.result,t,{word:String(n)});else if("throw"===e.oninvalid)throw e.decl.error(t,{word:String(n)})},processImageSet=(t,n,i)=>{const r=n.parent;if(!r)return;const o=new Map,s=n.value;for(let r=0;re-t)),u=l.map((e=>o.get(e)?.atRule)).filter((e=>!!e));if(!u.length)return;const c=o.get(l[0])?.value;if(!c)return;const f=u.slice(1);f.length&&r.after(f),n.cloneBefore({value:c.trim()}),i.preserve||(n.remove(),r.nodes?.length||r.remove())},r=/(?:^|[^\w-])(?:-webkit-)?image-set\(/i,o=/^(?:-webkit-)?image-set$/i,creator=n=>{const i=!("preserve"in Object(n))||Boolean(n?.preserve),s="onInvalid"in Object(n)?n?.onInvalid:"ignore";if("oninvalid"in Object(n))throw new Error('"oninvalid" was changed to "onInvalid" to match other plugins with similar options');return{postcssPlugin:"postcss-image-set-function",Declaration(n,{result:a,postcss:l}){const u=n.value;if(!r.test(u))return;if(t(n))return;let c;try{c=e(u)}catch(e){n.warn(a,`Failed to parse value '${u}' as an image-set function. Leaving the original value intact.`)}if(void 0===c)return;const f=[];c.walk((t=>{if("function"!==t.type)return;if(!o.test(t.value))return;let i=!1;if(e.walk(t.nodes,(e=>{"function"===e.type&&o.test(e.value)&&(i=!0)})),i)return handleInvalidation({decl:n,oninvalid:s,result:a},"nested image-set functions are not allowed",e.stringify(t)),!1;const r=t.nodes.filter((e=>"comment"!==e.type&&"space"!==e.type));f.push({imageSetFunction:t,imageSetOptionNodes:r})})),processImageSet(f,n,{decl:n,oninvalid:s,preserve:i,result:a,postcss:l})}}};creator.postcss=!0;export{creator as default}; +import e from"postcss-value-parser";import{hasFallback as t}from"@csstools/utilities";const n=/^(?:cross-fade|image|(?:repeating-)?(?:conic|linear|radial)-gradient|url|var)$/i;function getImage(t){return!(!t||!t.type)&&("string"===t.type?"url("+e.stringify(t)+")":!("function"!==t.type||!n.test(t.value))&&e.stringify(t))}const i=new Map([["dpcm",2.54],["dpi",1],["dppx",96],["x",96]]);function getMedia(e,t,n){if("boolean"==typeof e)return!1;const i=Math.floor(e/96*100)/100;return t.atRule({name:"media",params:`(-webkit-min-device-pixel-ratio: ${i}), (min-resolution: ${e}dpi)`,source:n.source})}function getMediaDPI(t){if(!t)return!1;if("word"!==t.type)return!1;if(!isNumericNode(t))return!1;const n=e.unit(t.value);if(!n)return!1;const r=i.get(n.unit.toLowerCase());return!!r&&Number(n.number)*r}function isNumericNode(t){if(!t||!t.value)return!1;try{return!1!==e.unit(t.value)}catch{return!1}}const handleInvalidation=(e,t,n)=>{if("warn"===e.oninvalid)e.decl.warn(e.result,t,{word:String(n)});else if("throw"===e.oninvalid)throw e.decl.error(t,{word:String(n)})},processImageSet=(t,n,i)=>{const r=n.parent;if(!r)return;const o=new Map,s=n.value;for(let r=0;re-t)),u=l.map((e=>o.get(e)?.atRule)).filter((e=>!!e));if(!u.length)return;const c=o.get(l[0])?.value;if(!c)return;const f=u.slice(1);f.length&&r.after(f),n.cloneBefore({value:c.trim()}),i.preserve||(n.remove(),r.nodes?.length||r.remove())},r=/(?:^|[^\w-])(?:-webkit-)?image-set\(/i,o=/^(?:-webkit-)?image-set$/i,creator=n=>{const i=!("preserve"in Object(n))||Boolean(n?.preserve),s="onInvalid"in Object(n)?n?.onInvalid:"ignore";if("oninvalid"in Object(n))throw new Error('"oninvalid" was changed to "onInvalid" to match other plugins with similar options');return{postcssPlugin:"postcss-image-set-function",Declaration(n,{result:a,postcss:l}){const u=n.value;if(!r.test(u))return;if(t(n))return;let c;try{c=e(u)}catch{n.warn(a,`Failed to parse value '${u}' as an image-set function. Leaving the original value intact.`)}if(void 0===c)return;const f=[];c.walk((t=>{if("function"!==t.type)return;if(!o.test(t.value))return;let i=!1;if(e.walk(t.nodes,(e=>{"function"===e.type&&o.test(e.value)&&(i=!0)})),i)return handleInvalidation({decl:n,oninvalid:s,result:a},"nested image-set functions are not allowed",e.stringify(t)),!1;const r=t.nodes.filter((e=>"comment"!==e.type&&"space"!==e.type));f.push({imageSetFunction:t,imageSetOptionNodes:r})})),processImageSet(f,n,{decl:n,oninvalid:s,preserve:i,result:a,postcss:l})}}};creator.postcss=!0;export{creator as default}; diff --git a/plugins/postcss-image-set-function/src/index.ts b/plugins/postcss-image-set-function/src/index.ts index 6864d6893..4f582323f 100644 --- a/plugins/postcss-image-set-function/src/index.ts +++ b/plugins/postcss-image-set-function/src/index.ts @@ -47,7 +47,7 @@ const creator: PluginCreator = (opts?: pluginOptions) => { try { valueAST = valueParser(value); - } catch (_) { + } catch { decl.warn( result, `Failed to parse value '${value}' as an image-set function. Leaving the original value intact.`, diff --git a/plugins/postcss-image-set-function/src/lib/get-media.ts b/plugins/postcss-image-set-function/src/lib/get-media.ts index c471db043..856a493e1 100644 --- a/plugins/postcss-image-set-function/src/lib/get-media.ts +++ b/plugins/postcss-image-set-function/src/lib/get-media.ts @@ -61,7 +61,7 @@ function isNumericNode(node: valueParser.Node): boolean { try { return valueParser.unit(node.value) !== false; - } catch (_) { + } catch { return false; } } diff --git a/plugins/postcss-image-set-function/src/lib/handle-invalidation.ts b/plugins/postcss-image-set-function/src/lib/handle-invalidation.ts index eedb526fc..c6afd571a 100644 --- a/plugins/postcss-image-set-function/src/lib/handle-invalidation.ts +++ b/plugins/postcss-image-set-function/src/lib/handle-invalidation.ts @@ -1,6 +1,6 @@ import type { Declaration, Result } from 'postcss'; -export const handleInvalidation = (opts: { oninvalid: 'warn' | 'throw' | unknown, decl: Declaration, result: Result }, message: string, word: string): void => { +export const handleInvalidation = (opts: { oninvalid: unknown, decl: Declaration, result: Result }, message: string, word: string): void => { if (opts.oninvalid === 'warn') { opts.decl.warn(opts.result, message, { word: String(word) }); } else if (opts.oninvalid === 'throw') { diff --git a/plugins/postcss-image-set-function/src/lib/is-comma.ts b/plugins/postcss-image-set-function/src/lib/is-comma.ts index 33f40aebf..b73e6bc85 100644 --- a/plugins/postcss-image-set-function/src/lib/is-comma.ts +++ b/plugins/postcss-image-set-function/src/lib/is-comma.ts @@ -1,6 +1,6 @@ import valueParser from 'postcss-value-parser'; // return whether a node is a valid comma -export function isComma(node: valueParser.Node): boolean { - return Object(node).type === 'div' && Object(node).value === ','; +export function isComma(node?: valueParser.Node): boolean { + return !!node && node.type === 'div' && node.value === ','; } diff --git a/plugins/postcss-image-set-function/src/lib/process-image-set.ts b/plugins/postcss-image-set-function/src/lib/process-image-set.ts index aea9e1078..7cce9acd2 100644 --- a/plugins/postcss-image-set-function/src/lib/process-image-set.ts +++ b/plugins/postcss-image-set-function/src/lib/process-image-set.ts @@ -81,9 +81,9 @@ export const processImageSet = (imageSetFunctions: Array, decl const mediaSizes = Array.from(mediasByDpr.keys()) .sort((a, b) => a - b); - const medias: Array = mediaSizes + const medias = mediaSizes .map(params => mediasByDpr.get(params)?.atRule) - .filter((x) => !!x) as Array; + .filter((x): x is AtRule => !!x); if (!medias.length) { return; diff --git a/plugins/postcss-is-pseudo-class/dist/index.cjs b/plugins/postcss-is-pseudo-class/dist/index.cjs index 3055fe924..c3846c8d0 100644 --- a/plugins/postcss-is-pseudo-class/dist/index.cjs +++ b/plugins/postcss-is-pseudo-class/dist/index.cjs @@ -1 +1 @@ -"use strict";var e=require("postcss-selector-parser"),o=require("@csstools/selector-specificity");function alwaysValidSelector(o){const s=e().astSync(o);let t=!0;return s.walk((e=>{if("class"!==e.type&&"comment"!==e.type&&"id"!==e.type&&"root"!==e.type&&"selector"!==e.type&&"string"!==e.type&&"tag"!==e.type&&"universal"!==e.type&&("attribute"!==e.type||e.insensitive)&&("combinator"!==e.type||"+"!==e.value&&">"!==e.value&&"~"!==e.value&&" "!==e.value)&&("pseudo"!==e.type||e.nodes?.length||":hover"!==e.value.toLowerCase()&&":focus"!==e.value.toLowerCase())){if("pseudo"===e.type&&1===e.nodes?.length&&":not"===e.value.toLowerCase()){let o=!0;if(e.nodes[0].walkCombinators((()=>{o=!1})),o)return}return t=!1,!1}})),t}function sortCompoundSelectorsInsideComplexSelector(o){if(!o||!o.nodes||1===o.nodes.length)return;const s=[];let t=[];for(let n=0;n"selector"===e.type&&"selector"===o.type&&e.nodes.length&&o.nodes.length?selectorTypeOrder(e.nodes[0],e.nodes[0].type)-selectorTypeOrder(o.nodes[0],o.nodes[0].type):"selector"===e.type&&e.nodes.length?selectorTypeOrder(e.nodes[0],e.nodes[0].type)-selectorTypeOrder(o,o.type):"selector"===o.type&&o.nodes.length?selectorTypeOrder(e,e.type)-selectorTypeOrder(o.nodes[0],o.nodes[0].type):selectorTypeOrder(e,e.type)-selectorTypeOrder(o,o.type)));const t=new Set(o.map((e=>e.type))),r=t.has("universal")&&(t.has("tag")||t.has("attribute")||t.has("class")||t.has("id")||t.has("pseudo"));for(let e=0;e=0;s--){const t=n[s-1];if(n[s].remove(),t&&"tag"===t.type&&"tag"===n[s].type){const t=e.pseudo({value:":is",nodes:[e.selector({value:"",nodes:[n[s]]})]});o.prepend(t)}else o.prepend(n[s])}}function selectorTypeOrder(o,t){return e.isPseudoElement(o)?s.pseudoElement:s[t]}const s={universal:0,tag:1,pseudoElement:2,id:3,class:4,attribute:5,pseudo:6,selector:7,string:8,root:9,comment:10};function childAdjacentChild(e){return!(!e||!e.nodes)&&("selector"===e.type&&(3===e.nodes.length&&(!(!e.nodes[0]||"pseudo"!==e.nodes[0].type||":-csstools-matches"!==e.nodes[0].value)&&(!(!e.nodes[1]||"combinator"!==e.nodes[1].type||"+"!==e.nodes[1].value&&"~"!==e.nodes[1].value)&&(!(!e.nodes[2]||"pseudo"!==e.nodes[2].type||":-csstools-matches"!==e.nodes[2].value)&&(!(!e.nodes[0].nodes||1!==e.nodes[0].nodes.length)&&("selector"===e.nodes[0].nodes[0].type&&(!(!e.nodes[0].nodes[0].nodes||3!==e.nodes[0].nodes[0].nodes.length)&&(!(!e.nodes[0].nodes[0].nodes||"combinator"!==e.nodes[0].nodes[0].nodes[1].type||">"!==e.nodes[0].nodes[0].nodes[1].value)&&(!(!e.nodes[2].nodes||1!==e.nodes[2].nodes.length)&&("selector"===e.nodes[2].nodes[0].type&&(!(!e.nodes[2].nodes[0].nodes||3!==e.nodes[2].nodes[0].nodes.length)&&(!(!e.nodes[2].nodes[0].nodes||"combinator"!==e.nodes[2].nodes[0].nodes[1].type||">"!==e.nodes[2].nodes[0].nodes[1].value)&&(e.nodes[0].nodes[0].insertAfter(e.nodes[0].nodes[0].nodes[0],e.nodes[2].nodes[0].nodes[0].clone()),e.nodes[2].nodes[0].nodes[1].remove(),e.nodes[2].nodes[0].nodes[0].remove(),e.nodes[0].replaceWith(e.nodes[0].nodes[0]),e.nodes[2].replaceWith(e.nodes[2].nodes[0]),!0))))))))))))))}function isInCompoundWithOneOtherElement(o){if(!o||!o.nodes)return!1;if("selector"!==o.type)return!1;if(2!==o.nodes.length)return!1;let s,t;return o.nodes[0]&&"pseudo"===o.nodes[0].type&&":-csstools-matches"===o.nodes[0].value?(s=0,t=1):o.nodes[1]&&"pseudo"===o.nodes[1].type&&":-csstools-matches"===o.nodes[1].value&&(s=1,t=0),!!s&&(!!o.nodes[t]&&(("selector"!==o.nodes[t].type||!o.nodes[t].some((o=>"combinator"===o.type||e.isPseudoElement(o))))&&("combinator"!==o.nodes[t].type&&(o.nodes[s].nodes[0].append(o.nodes[t].clone()),o.nodes[s].replaceWith(...o.nodes[s].nodes[0].nodes),o.nodes[t].remove(),!0))))}function isPseudoInFirstCompound(e){if(!e||!e.nodes)return!1;if("selector"!==e.type)return!1;let o=-1;for(let s=0;s{t.nodes[0].append(e.clone())})),n.forEach((e=>{t.nodes[0].append(e.clone())})),t.replaceWith(...t.nodes),s.forEach((e=>{e.remove()})),n.forEach((e=>{e.remove()})),!0}function complexSelectors(o,s,t,n){return o.flatMap((o=>{if(-1===o.indexOf(":-csstools-matches")&&-1===o.toLowerCase().indexOf(":is"))return o;const r=e().astSync(o);return r.walkPseudos((o=>{if(":is"===o.value.toLowerCase()&&o.nodes&&o.nodes.length&&"selector"===o.nodes[0].type&&0===o.nodes[0].nodes.length)return o.value=":not",void o.nodes[0].append(e.universal());if(":-csstools-matches"===o.value)if(!o.nodes||o.nodes.length){if(o.walkPseudos((o=>{if(e.isPseudoElement(o)){let e=o.value;if(e.startsWith("::-csstools-invalid-"))return;for(;e.startsWith(":");)e=e.slice(1);o.value=`::-csstools-invalid-${e}`,n()}})),1===o.nodes.length&&"selector"===o.nodes[0].type){if(1===o.nodes[0].nodes.length)return void o.replaceWith(o.nodes[0].nodes[0]);if(!o.nodes[0].some((e=>"combinator"===e.type)))return void o.replaceWith(...o.nodes[0].nodes)}1!==r.nodes.length||"selector"!==r.nodes[0].type||1!==r.nodes[0].nodes.length||r.nodes[0].nodes[0]!==o?childAdjacentChild(o.parent)||isInCompoundWithOneOtherElement(o.parent)||isPseudoInFirstCompound(o.parent)||("warning"===s.onComplexSelector&&t(),o.value=":is"):o.replaceWith(...o.nodes[0].nodes)}else o.remove()})),r.walk((e=>{"selector"===e.type&&"nodes"in e&&1===e.nodes.length&&"selector"===e.nodes[0].type&&e.replaceWith(e.nodes[0])})),r.walk((e=>{"nodes"in e&&sortCompoundSelectorsInsideComplexSelector(e)})),r.toString()})).filter((e=>!!e))}function splitSelectors(s,t,n=0){const r=":not(#"+t.specificityMatchingName+")",d=":not(."+t.specificityMatchingName+")",l=":not("+t.specificityMatchingName+")";return s.flatMap((s=>{if(-1===s.toLowerCase().indexOf(":is"))return s;let c=!1;const i=[];if(e().astSync(s).walkPseudos((e=>{if(":is"!==e.value.toLowerCase()||!e.nodes||!e.nodes.length)return;if("selector"===e.nodes[0].type&&0===e.nodes[0].nodes.length)return;if("pseudo"===e.parent?.parent?.type&&":not"===e.parent?.parent?.value?.toLowerCase())return void i.push([{start:e.parent.parent.sourceIndex,end:e.parent.parent.sourceIndex+e.parent.parent.toString().length,option:`:not(${e.nodes.toString()})`}]);if("pseudo"===e.parent?.parent?.type&&":has"===e.parent?.parent?.value?.toLowerCase())return void(e.value=":-csstools-matches");let s=e.parent;for(;s;){if(s.value&&":is"===s.value.toLowerCase()&&"pseudo"===s.type)return void(c=!0);s=s.parent}const t=o.selectorSpecificity(e),n=e.sourceIndex,a=n+e.toString().length,p=[];e.nodes.forEach((e=>{const s={start:n,end:a,option:""},c=o.selectorSpecificity(e);let i=e.toString().trim();const u=Math.max(0,t.a-c.a),h=Math.max(0,t.b-c.b),f=Math.max(0,t.c-c.c);for(let e=0;e{let o="";for(let t=0;t!!e))}function cartesianProduct(...e){const o=[],s=e.length-1;return function helper(t,n){for(let r=0,d=e[n].length;r{const o={specificityMatchingName:"does-not-exist",...e||{}};return{postcssPlugin:"postcss-is-pseudo-class",prepare(){const e=new WeakSet;return{postcssPlugin:"postcss-is-pseudo-class",Rule(s,{result:n}){if(!s.selector)return;if(!t.test(s.selector))return;if(e.has(s))return;let r=!1;const warnOnComplexSelector=()=>{"warning"===o.onComplexSelector&&(r||(r=!0,s.warn(n,`Complex selectors in '${s.selector}' can not be transformed to an equivalent selector without ':is()'.`)))};let d=!1;const warnOnPseudoElements=()=>{"warning"===o.onPseudoElement&&(d||(d=!0,s.warn(n,`Pseudo elements are not allowed in ':is()', unable to transform '${s.selector}'`)))};try{let t=!1;const n=[],r=complexSelectors(splitSelectors(s.selectors,{specificityMatchingName:o.specificityMatchingName}),{onComplexSelector:o.onComplexSelector},warnOnComplexSelector,warnOnPseudoElements);if(Array.from(new Set(r)).forEach((o=>{if(s.selectors.indexOf(o)>-1)n.push(o);else{if(alwaysValidSelector(o))return n.push(o),void(t=!0);e.add(s),s.cloneBefore({selector:o}),t=!0}})),n.length&&t&&(e.add(s),s.cloneBefore({selectors:n})),!o.preserve){if(!t)return;s.remove()}}catch(e){if(e.message.indexOf("call stack size exceeded")>-1)throw e;s.warn(n,`Failed to parse selector "${s.selector}" with error: ${e.message}`)}}}}}};creator.postcss=!0,module.exports=creator; +"use strict";var e=require("postcss-selector-parser"),s=require("@csstools/selector-specificity");function alwaysValidSelector(s){const o=e().astSync(s);let t=!0;return o.walk((e=>{if("class"!==e.type&&"comment"!==e.type&&"id"!==e.type&&"root"!==e.type&&"selector"!==e.type&&"string"!==e.type&&"tag"!==e.type&&"universal"!==e.type&&("attribute"!==e.type||e.insensitive)&&("combinator"!==e.type||"+"!==e.value&&">"!==e.value&&"~"!==e.value&&" "!==e.value)&&("pseudo"!==e.type||e.nodes?.length||":hover"!==e.value.toLowerCase()&&":focus"!==e.value.toLowerCase())){if("pseudo"===e.type&&1===e.nodes?.length&&":not"===e.value.toLowerCase()){let s=!0;if(e.nodes[0].walkCombinators((()=>{s=!1})),s)return}return t=!1,!1}})),t}function sortCompoundSelectorsInsideComplexSelector(s){if(!s||!s.nodes||1===s.nodes.length)return;const o=[];let t=[];for(let n=0;n"selector"===e.type&&"selector"===s.type&&e.nodes.length&&s.nodes.length?selectorTypeOrder(e.nodes[0],e.nodes[0].type)-selectorTypeOrder(s.nodes[0],s.nodes[0].type):"selector"===e.type&&e.nodes.length?selectorTypeOrder(e.nodes[0],e.nodes[0].type)-selectorTypeOrder(s,s.type):"selector"===s.type&&s.nodes.length?selectorTypeOrder(e,e.type)-selectorTypeOrder(s.nodes[0],s.nodes[0].type):selectorTypeOrder(e,e.type)-selectorTypeOrder(s,s.type)));const t=new Set(s.map((e=>e.type))),r=t.has("universal")&&(t.has("tag")||t.has("attribute")||t.has("class")||t.has("id")||t.has("pseudo"));for(let e=0;e=0;o--){const t=n[o-1];if(n[o].remove(),t&&"tag"===t.type&&"tag"===n[o].type){const t=e.pseudo({value:":is",nodes:[e.selector({value:"",nodes:[n[o]]})]});s.prepend(t)}else s.prepend(n[o])}}function selectorTypeOrder(s,t){return e.isPseudoElement(s)?o.pseudoElement:o[t]}const o={universal:0,tag:1,pseudoElement:2,id:3,class:4,attribute:5,pseudo:6,selector:7,string:8,root:9,comment:10};function childAdjacentChild(e){return!(!e||!e.nodes)&&("selector"===e.type&&(3===e.nodes.length&&(!(!e.nodes[0]||"pseudo"!==e.nodes[0].type||":-csstools-matches"!==e.nodes[0].value)&&(!(!e.nodes[1]||"combinator"!==e.nodes[1].type||"+"!==e.nodes[1].value&&"~"!==e.nodes[1].value)&&(!(!e.nodes[2]||"pseudo"!==e.nodes[2].type||":-csstools-matches"!==e.nodes[2].value)&&(!(!e.nodes[0].nodes||1!==e.nodes[0].nodes.length)&&("selector"===e.nodes[0].nodes[0].type&&(!(!e.nodes[0].nodes[0].nodes||3!==e.nodes[0].nodes[0].nodes.length)&&(!(!e.nodes[0].nodes[0].nodes||"combinator"!==e.nodes[0].nodes[0].nodes[1].type||">"!==e.nodes[0].nodes[0].nodes[1].value)&&(!(!e.nodes[2].nodes||1!==e.nodes[2].nodes.length)&&("selector"===e.nodes[2].nodes[0].type&&(!(!e.nodes[2].nodes[0].nodes||3!==e.nodes[2].nodes[0].nodes.length)&&(!(!e.nodes[2].nodes[0].nodes||"combinator"!==e.nodes[2].nodes[0].nodes[1].type||">"!==e.nodes[2].nodes[0].nodes[1].value)&&(e.nodes[0].nodes[0].insertAfter(e.nodes[0].nodes[0].nodes[0],e.nodes[2].nodes[0].nodes[0].clone()),e.nodes[2].nodes[0].nodes[1].remove(),e.nodes[2].nodes[0].nodes[0].remove(),e.nodes[0].replaceWith(e.nodes[0].nodes[0]),e.nodes[2].replaceWith(e.nodes[2].nodes[0]),!0))))))))))))))}function isInCompoundWithOneOtherElement(s){if(!s||!s.nodes)return!1;if(!e.isSelector(s))return!1;if(2!==s.nodes.length)return!1;let o=-1,t=-1;s.nodes[0]&&e.isPseudoClass(s.nodes[0])&&":-csstools-matches"===s.nodes[0].value?(o=0,t=1):s.nodes[1]&&e.isPseudoClass(s.nodes[1])&&":-csstools-matches"===s.nodes[1].value&&(o=1,t=0);const n=s.nodes[o];if(!n||!e.isPseudoClass(n)||1!==n.nodes.length)return!1;const r=s.nodes[t];return!!r&&(!e.isCombinator(r)&&(n.nodes[0].append(r.clone()),n.replaceWith(...n.nodes[0].nodes),r.remove(),!0))}function isPseudoInFirstCompound(s){if(!s||!s.nodes)return!1;if(!e.isSelector(s))return!1;let o=-1;for(let t=0;t{t.nodes[0].append(e.clone())})),r.forEach((e=>{t.nodes[0].append(e.clone())})),t.replaceWith(...t.nodes),n.forEach((e=>{e.remove()})),r.forEach((e=>{e.remove()})),!0}function complexSelectors(s,o,t,n){return s.flatMap((s=>{if(-1===s.indexOf(":-csstools-matches")&&-1===s.toLowerCase().indexOf(":is"))return s;const r=e().astSync(s);return r.walkPseudos((s=>{if(":is"===s.value.toLowerCase()&&s.nodes&&s.nodes.length&&"selector"===s.nodes[0].type&&0===s.nodes[0].nodes.length)return s.value=":not",void s.nodes[0].append(e.universal());if(":-csstools-matches"===s.value)if(!s.nodes||s.nodes.length){if(s.walkPseudos((s=>{if(e.isPseudoElement(s)){let e=s.value;if(e.startsWith("::-csstools-invalid-"))return;for(;e.startsWith(":");)e=e.slice(1);s.value=`::-csstools-invalid-${e}`,n()}})),1===s.nodes.length&&"selector"===s.nodes[0].type){if(1===s.nodes[0].nodes.length)return void s.replaceWith(s.nodes[0].nodes[0]);if(!s.nodes[0].some((e=>"combinator"===e.type)))return void s.replaceWith(...s.nodes[0].nodes)}1!==r.nodes.length||"selector"!==r.nodes[0].type||1!==r.nodes[0].nodes.length||r.nodes[0].nodes[0]!==s?childAdjacentChild(s.parent)||isInCompoundWithOneOtherElement(s.parent)||isPseudoInFirstCompound(s.parent)||("warning"===o.onComplexSelector&&t(),s.value=":is"):s.replaceWith(...s.nodes[0].nodes)}else s.remove()})),r.walk((e=>{"selector"===e.type&&"nodes"in e&&1===e.nodes.length&&"selector"===e.nodes[0].type&&e.replaceWith(e.nodes[0])})),r.walk((e=>{"nodes"in e&&sortCompoundSelectorsInsideComplexSelector(e)})),r.toString()})).filter((e=>!!e))}function splitSelectors(o,t,n=0){const r=":not(#"+t.specificityMatchingName+")",d=":not(."+t.specificityMatchingName+")",l=":not("+t.specificityMatchingName+")";return o.flatMap((o=>{if(-1===o.toLowerCase().indexOf(":is"))return o;let i=!1;const c=[];if(e().astSync(o).walkPseudos((e=>{if(":is"!==e.value.toLowerCase()||!e.nodes||!e.nodes.length)return;if("selector"===e.nodes[0].type&&0===e.nodes[0].nodes.length)return;if("pseudo"===e.parent?.parent?.type&&":not"===e.parent?.parent?.value?.toLowerCase())return void c.push([{start:e.parent.parent.sourceIndex,end:e.parent.parent.sourceIndex+e.parent.parent.toString().length,option:`:not(${e.nodes.toString()})`}]);if("pseudo"===e.parent?.parent?.type&&":has"===e.parent?.parent?.value?.toLowerCase())return void(e.value=":-csstools-matches");let o=e.parent;for(;o;){if(o.value&&":is"===o.value.toLowerCase()&&"pseudo"===o.type)return void(i=!0);o=o.parent}const t=s.selectorSpecificity(e),n=e.sourceIndex,a=n+e.toString().length,p=[];e.nodes.forEach((e=>{const o={start:n,end:a,option:""},i=s.selectorSpecificity(e);let c=e.toString().trim();const u=Math.max(0,t.a-i.a),h=Math.max(0,t.b-i.b),f=Math.max(0,t.c-i.c);for(let e=0;e{let s="";for(let t=0;t!!e))}function cartesianProduct(...e){const s=[],o=e.length-1;return function helper(t,n){for(let r=0,d=e[n].length;r{const s={specificityMatchingName:"does-not-exist",...e||{}};return{postcssPlugin:"postcss-is-pseudo-class",prepare(){const e=new WeakSet;return{postcssPlugin:"postcss-is-pseudo-class",Rule(o,{result:n}){if(!o.selector)return;if(!t.test(o.selector))return;if(e.has(o))return;let r=!1;const warnOnComplexSelector=()=>{"warning"===s.onComplexSelector&&(r||(r=!0,o.warn(n,`Complex selectors in '${o.selector}' can not be transformed to an equivalent selector without ':is()'.`)))};let d=!1;const warnOnPseudoElements=()=>{"warning"===s.onPseudoElement&&(d||(d=!0,o.warn(n,`Pseudo elements are not allowed in ':is()', unable to transform '${o.selector}'`)))};try{let t=!1;const n=[],r=complexSelectors(splitSelectors(o.selectors,{specificityMatchingName:s.specificityMatchingName}),{onComplexSelector:s.onComplexSelector},warnOnComplexSelector,warnOnPseudoElements);if(Array.from(new Set(r)).forEach((s=>{if(o.selectors.indexOf(s)>-1)n.push(s);else{if(alwaysValidSelector(s))return n.push(s),void(t=!0);e.add(o),o.cloneBefore({selector:s}),t=!0}})),n.length&&t&&(e.add(o),o.cloneBefore({selectors:n})),!s.preserve){if(!t)return;o.remove()}}catch(e){if(!(e instanceof Error))throw e;if(e.message.indexOf("call stack size exceeded")>-1)throw e;o.warn(n,`Failed to parse selector "${o.selector}" with error: ${e.message}`)}}}}}};creator.postcss=!0,module.exports=creator; diff --git a/plugins/postcss-is-pseudo-class/dist/index.mjs b/plugins/postcss-is-pseudo-class/dist/index.mjs index 2d34a4d22..ba85415d0 100644 --- a/plugins/postcss-is-pseudo-class/dist/index.mjs +++ b/plugins/postcss-is-pseudo-class/dist/index.mjs @@ -1 +1 @@ -import e from"postcss-selector-parser";import{selectorSpecificity as o}from"@csstools/selector-specificity";function alwaysValidSelector(o){const s=e().astSync(o);let t=!0;return s.walk((e=>{if("class"!==e.type&&"comment"!==e.type&&"id"!==e.type&&"root"!==e.type&&"selector"!==e.type&&"string"!==e.type&&"tag"!==e.type&&"universal"!==e.type&&("attribute"!==e.type||e.insensitive)&&("combinator"!==e.type||"+"!==e.value&&">"!==e.value&&"~"!==e.value&&" "!==e.value)&&("pseudo"!==e.type||e.nodes?.length||":hover"!==e.value.toLowerCase()&&":focus"!==e.value.toLowerCase())){if("pseudo"===e.type&&1===e.nodes?.length&&":not"===e.value.toLowerCase()){let o=!0;if(e.nodes[0].walkCombinators((()=>{o=!1})),o)return}return t=!1,!1}})),t}function sortCompoundSelectorsInsideComplexSelector(o){if(!o||!o.nodes||1===o.nodes.length)return;const s=[];let t=[];for(let n=0;n"selector"===e.type&&"selector"===o.type&&e.nodes.length&&o.nodes.length?selectorTypeOrder(e.nodes[0],e.nodes[0].type)-selectorTypeOrder(o.nodes[0],o.nodes[0].type):"selector"===e.type&&e.nodes.length?selectorTypeOrder(e.nodes[0],e.nodes[0].type)-selectorTypeOrder(o,o.type):"selector"===o.type&&o.nodes.length?selectorTypeOrder(e,e.type)-selectorTypeOrder(o.nodes[0],o.nodes[0].type):selectorTypeOrder(e,e.type)-selectorTypeOrder(o,o.type)));const t=new Set(o.map((e=>e.type))),r=t.has("universal")&&(t.has("tag")||t.has("attribute")||t.has("class")||t.has("id")||t.has("pseudo"));for(let e=0;e=0;s--){const t=n[s-1];if(n[s].remove(),t&&"tag"===t.type&&"tag"===n[s].type){const t=e.pseudo({value:":is",nodes:[e.selector({value:"",nodes:[n[s]]})]});o.prepend(t)}else o.prepend(n[s])}}function selectorTypeOrder(o,t){return e.isPseudoElement(o)?s.pseudoElement:s[t]}const s={universal:0,tag:1,pseudoElement:2,id:3,class:4,attribute:5,pseudo:6,selector:7,string:8,root:9,comment:10};function childAdjacentChild(e){return!(!e||!e.nodes)&&("selector"===e.type&&(3===e.nodes.length&&(!(!e.nodes[0]||"pseudo"!==e.nodes[0].type||":-csstools-matches"!==e.nodes[0].value)&&(!(!e.nodes[1]||"combinator"!==e.nodes[1].type||"+"!==e.nodes[1].value&&"~"!==e.nodes[1].value)&&(!(!e.nodes[2]||"pseudo"!==e.nodes[2].type||":-csstools-matches"!==e.nodes[2].value)&&(!(!e.nodes[0].nodes||1!==e.nodes[0].nodes.length)&&("selector"===e.nodes[0].nodes[0].type&&(!(!e.nodes[0].nodes[0].nodes||3!==e.nodes[0].nodes[0].nodes.length)&&(!(!e.nodes[0].nodes[0].nodes||"combinator"!==e.nodes[0].nodes[0].nodes[1].type||">"!==e.nodes[0].nodes[0].nodes[1].value)&&(!(!e.nodes[2].nodes||1!==e.nodes[2].nodes.length)&&("selector"===e.nodes[2].nodes[0].type&&(!(!e.nodes[2].nodes[0].nodes||3!==e.nodes[2].nodes[0].nodes.length)&&(!(!e.nodes[2].nodes[0].nodes||"combinator"!==e.nodes[2].nodes[0].nodes[1].type||">"!==e.nodes[2].nodes[0].nodes[1].value)&&(e.nodes[0].nodes[0].insertAfter(e.nodes[0].nodes[0].nodes[0],e.nodes[2].nodes[0].nodes[0].clone()),e.nodes[2].nodes[0].nodes[1].remove(),e.nodes[2].nodes[0].nodes[0].remove(),e.nodes[0].replaceWith(e.nodes[0].nodes[0]),e.nodes[2].replaceWith(e.nodes[2].nodes[0]),!0))))))))))))))}function isInCompoundWithOneOtherElement(o){if(!o||!o.nodes)return!1;if("selector"!==o.type)return!1;if(2!==o.nodes.length)return!1;let s,t;return o.nodes[0]&&"pseudo"===o.nodes[0].type&&":-csstools-matches"===o.nodes[0].value?(s=0,t=1):o.nodes[1]&&"pseudo"===o.nodes[1].type&&":-csstools-matches"===o.nodes[1].value&&(s=1,t=0),!!s&&(!!o.nodes[t]&&(("selector"!==o.nodes[t].type||!o.nodes[t].some((o=>"combinator"===o.type||e.isPseudoElement(o))))&&("combinator"!==o.nodes[t].type&&(o.nodes[s].nodes[0].append(o.nodes[t].clone()),o.nodes[s].replaceWith(...o.nodes[s].nodes[0].nodes),o.nodes[t].remove(),!0))))}function isPseudoInFirstCompound(e){if(!e||!e.nodes)return!1;if("selector"!==e.type)return!1;let o=-1;for(let s=0;s{t.nodes[0].append(e.clone())})),n.forEach((e=>{t.nodes[0].append(e.clone())})),t.replaceWith(...t.nodes),s.forEach((e=>{e.remove()})),n.forEach((e=>{e.remove()})),!0}function complexSelectors(o,s,t,n){return o.flatMap((o=>{if(-1===o.indexOf(":-csstools-matches")&&-1===o.toLowerCase().indexOf(":is"))return o;const r=e().astSync(o);return r.walkPseudos((o=>{if(":is"===o.value.toLowerCase()&&o.nodes&&o.nodes.length&&"selector"===o.nodes[0].type&&0===o.nodes[0].nodes.length)return o.value=":not",void o.nodes[0].append(e.universal());if(":-csstools-matches"===o.value)if(!o.nodes||o.nodes.length){if(o.walkPseudos((o=>{if(e.isPseudoElement(o)){let e=o.value;if(e.startsWith("::-csstools-invalid-"))return;for(;e.startsWith(":");)e=e.slice(1);o.value=`::-csstools-invalid-${e}`,n()}})),1===o.nodes.length&&"selector"===o.nodes[0].type){if(1===o.nodes[0].nodes.length)return void o.replaceWith(o.nodes[0].nodes[0]);if(!o.nodes[0].some((e=>"combinator"===e.type)))return void o.replaceWith(...o.nodes[0].nodes)}1!==r.nodes.length||"selector"!==r.nodes[0].type||1!==r.nodes[0].nodes.length||r.nodes[0].nodes[0]!==o?childAdjacentChild(o.parent)||isInCompoundWithOneOtherElement(o.parent)||isPseudoInFirstCompound(o.parent)||("warning"===s.onComplexSelector&&t(),o.value=":is"):o.replaceWith(...o.nodes[0].nodes)}else o.remove()})),r.walk((e=>{"selector"===e.type&&"nodes"in e&&1===e.nodes.length&&"selector"===e.nodes[0].type&&e.replaceWith(e.nodes[0])})),r.walk((e=>{"nodes"in e&&sortCompoundSelectorsInsideComplexSelector(e)})),r.toString()})).filter((e=>!!e))}function splitSelectors(s,t,n=0){const r=":not(#"+t.specificityMatchingName+")",d=":not(."+t.specificityMatchingName+")",l=":not("+t.specificityMatchingName+")";return s.flatMap((s=>{if(-1===s.toLowerCase().indexOf(":is"))return s;let a=!1;const c=[];if(e().astSync(s).walkPseudos((e=>{if(":is"!==e.value.toLowerCase()||!e.nodes||!e.nodes.length)return;if("selector"===e.nodes[0].type&&0===e.nodes[0].nodes.length)return;if("pseudo"===e.parent?.parent?.type&&":not"===e.parent?.parent?.value?.toLowerCase())return void c.push([{start:e.parent.parent.sourceIndex,end:e.parent.parent.sourceIndex+e.parent.parent.toString().length,option:`:not(${e.nodes.toString()})`}]);if("pseudo"===e.parent?.parent?.type&&":has"===e.parent?.parent?.value?.toLowerCase())return void(e.value=":-csstools-matches");let s=e.parent;for(;s;){if(s.value&&":is"===s.value.toLowerCase()&&"pseudo"===s.type)return void(a=!0);s=s.parent}const t=o(e),n=e.sourceIndex,i=n+e.toString().length,p=[];e.nodes.forEach((e=>{const s={start:n,end:i,option:""},a=o(e);let c=e.toString().trim();const u=Math.max(0,t.a-a.a),h=Math.max(0,t.b-a.b),f=Math.max(0,t.c-a.c);for(let e=0;e{let o="";for(let t=0;t!!e))}function cartesianProduct(...e){const o=[],s=e.length-1;return function helper(t,n){for(let r=0,d=e[n].length;r{const o={specificityMatchingName:"does-not-exist",...e||{}};return{postcssPlugin:"postcss-is-pseudo-class",prepare(){const e=new WeakSet;return{postcssPlugin:"postcss-is-pseudo-class",Rule(s,{result:n}){if(!s.selector)return;if(!t.test(s.selector))return;if(e.has(s))return;let r=!1;const warnOnComplexSelector=()=>{"warning"===o.onComplexSelector&&(r||(r=!0,s.warn(n,`Complex selectors in '${s.selector}' can not be transformed to an equivalent selector without ':is()'.`)))};let d=!1;const warnOnPseudoElements=()=>{"warning"===o.onPseudoElement&&(d||(d=!0,s.warn(n,`Pseudo elements are not allowed in ':is()', unable to transform '${s.selector}'`)))};try{let t=!1;const n=[],r=complexSelectors(splitSelectors(s.selectors,{specificityMatchingName:o.specificityMatchingName}),{onComplexSelector:o.onComplexSelector},warnOnComplexSelector,warnOnPseudoElements);if(Array.from(new Set(r)).forEach((o=>{if(s.selectors.indexOf(o)>-1)n.push(o);else{if(alwaysValidSelector(o))return n.push(o),void(t=!0);e.add(s),s.cloneBefore({selector:o}),t=!0}})),n.length&&t&&(e.add(s),s.cloneBefore({selectors:n})),!o.preserve){if(!t)return;s.remove()}}catch(e){if(e.message.indexOf("call stack size exceeded")>-1)throw e;s.warn(n,`Failed to parse selector "${s.selector}" with error: ${e.message}`)}}}}}};creator.postcss=!0;export{creator as default}; +import e from"postcss-selector-parser";import{selectorSpecificity as s}from"@csstools/selector-specificity";function alwaysValidSelector(s){const o=e().astSync(s);let t=!0;return o.walk((e=>{if("class"!==e.type&&"comment"!==e.type&&"id"!==e.type&&"root"!==e.type&&"selector"!==e.type&&"string"!==e.type&&"tag"!==e.type&&"universal"!==e.type&&("attribute"!==e.type||e.insensitive)&&("combinator"!==e.type||"+"!==e.value&&">"!==e.value&&"~"!==e.value&&" "!==e.value)&&("pseudo"!==e.type||e.nodes?.length||":hover"!==e.value.toLowerCase()&&":focus"!==e.value.toLowerCase())){if("pseudo"===e.type&&1===e.nodes?.length&&":not"===e.value.toLowerCase()){let s=!0;if(e.nodes[0].walkCombinators((()=>{s=!1})),s)return}return t=!1,!1}})),t}function sortCompoundSelectorsInsideComplexSelector(s){if(!s||!s.nodes||1===s.nodes.length)return;const o=[];let t=[];for(let n=0;n"selector"===e.type&&"selector"===s.type&&e.nodes.length&&s.nodes.length?selectorTypeOrder(e.nodes[0],e.nodes[0].type)-selectorTypeOrder(s.nodes[0],s.nodes[0].type):"selector"===e.type&&e.nodes.length?selectorTypeOrder(e.nodes[0],e.nodes[0].type)-selectorTypeOrder(s,s.type):"selector"===s.type&&s.nodes.length?selectorTypeOrder(e,e.type)-selectorTypeOrder(s.nodes[0],s.nodes[0].type):selectorTypeOrder(e,e.type)-selectorTypeOrder(s,s.type)));const t=new Set(s.map((e=>e.type))),r=t.has("universal")&&(t.has("tag")||t.has("attribute")||t.has("class")||t.has("id")||t.has("pseudo"));for(let e=0;e=0;o--){const t=n[o-1];if(n[o].remove(),t&&"tag"===t.type&&"tag"===n[o].type){const t=e.pseudo({value:":is",nodes:[e.selector({value:"",nodes:[n[o]]})]});s.prepend(t)}else s.prepend(n[o])}}function selectorTypeOrder(s,t){return e.isPseudoElement(s)?o.pseudoElement:o[t]}const o={universal:0,tag:1,pseudoElement:2,id:3,class:4,attribute:5,pseudo:6,selector:7,string:8,root:9,comment:10};function childAdjacentChild(e){return!(!e||!e.nodes)&&("selector"===e.type&&(3===e.nodes.length&&(!(!e.nodes[0]||"pseudo"!==e.nodes[0].type||":-csstools-matches"!==e.nodes[0].value)&&(!(!e.nodes[1]||"combinator"!==e.nodes[1].type||"+"!==e.nodes[1].value&&"~"!==e.nodes[1].value)&&(!(!e.nodes[2]||"pseudo"!==e.nodes[2].type||":-csstools-matches"!==e.nodes[2].value)&&(!(!e.nodes[0].nodes||1!==e.nodes[0].nodes.length)&&("selector"===e.nodes[0].nodes[0].type&&(!(!e.nodes[0].nodes[0].nodes||3!==e.nodes[0].nodes[0].nodes.length)&&(!(!e.nodes[0].nodes[0].nodes||"combinator"!==e.nodes[0].nodes[0].nodes[1].type||">"!==e.nodes[0].nodes[0].nodes[1].value)&&(!(!e.nodes[2].nodes||1!==e.nodes[2].nodes.length)&&("selector"===e.nodes[2].nodes[0].type&&(!(!e.nodes[2].nodes[0].nodes||3!==e.nodes[2].nodes[0].nodes.length)&&(!(!e.nodes[2].nodes[0].nodes||"combinator"!==e.nodes[2].nodes[0].nodes[1].type||">"!==e.nodes[2].nodes[0].nodes[1].value)&&(e.nodes[0].nodes[0].insertAfter(e.nodes[0].nodes[0].nodes[0],e.nodes[2].nodes[0].nodes[0].clone()),e.nodes[2].nodes[0].nodes[1].remove(),e.nodes[2].nodes[0].nodes[0].remove(),e.nodes[0].replaceWith(e.nodes[0].nodes[0]),e.nodes[2].replaceWith(e.nodes[2].nodes[0]),!0))))))))))))))}function isInCompoundWithOneOtherElement(s){if(!s||!s.nodes)return!1;if(!e.isSelector(s))return!1;if(2!==s.nodes.length)return!1;let o=-1,t=-1;s.nodes[0]&&e.isPseudoClass(s.nodes[0])&&":-csstools-matches"===s.nodes[0].value?(o=0,t=1):s.nodes[1]&&e.isPseudoClass(s.nodes[1])&&":-csstools-matches"===s.nodes[1].value&&(o=1,t=0);const n=s.nodes[o];if(!n||!e.isPseudoClass(n)||1!==n.nodes.length)return!1;const r=s.nodes[t];return!!r&&(!e.isCombinator(r)&&(n.nodes[0].append(r.clone()),n.replaceWith(...n.nodes[0].nodes),r.remove(),!0))}function isPseudoInFirstCompound(s){if(!s||!s.nodes)return!1;if(!e.isSelector(s))return!1;let o=-1;for(let t=0;t{t.nodes[0].append(e.clone())})),r.forEach((e=>{t.nodes[0].append(e.clone())})),t.replaceWith(...t.nodes),n.forEach((e=>{e.remove()})),r.forEach((e=>{e.remove()})),!0}function complexSelectors(s,o,t,n){return s.flatMap((s=>{if(-1===s.indexOf(":-csstools-matches")&&-1===s.toLowerCase().indexOf(":is"))return s;const r=e().astSync(s);return r.walkPseudos((s=>{if(":is"===s.value.toLowerCase()&&s.nodes&&s.nodes.length&&"selector"===s.nodes[0].type&&0===s.nodes[0].nodes.length)return s.value=":not",void s.nodes[0].append(e.universal());if(":-csstools-matches"===s.value)if(!s.nodes||s.nodes.length){if(s.walkPseudos((s=>{if(e.isPseudoElement(s)){let e=s.value;if(e.startsWith("::-csstools-invalid-"))return;for(;e.startsWith(":");)e=e.slice(1);s.value=`::-csstools-invalid-${e}`,n()}})),1===s.nodes.length&&"selector"===s.nodes[0].type){if(1===s.nodes[0].nodes.length)return void s.replaceWith(s.nodes[0].nodes[0]);if(!s.nodes[0].some((e=>"combinator"===e.type)))return void s.replaceWith(...s.nodes[0].nodes)}1!==r.nodes.length||"selector"!==r.nodes[0].type||1!==r.nodes[0].nodes.length||r.nodes[0].nodes[0]!==s?childAdjacentChild(s.parent)||isInCompoundWithOneOtherElement(s.parent)||isPseudoInFirstCompound(s.parent)||("warning"===o.onComplexSelector&&t(),s.value=":is"):s.replaceWith(...s.nodes[0].nodes)}else s.remove()})),r.walk((e=>{"selector"===e.type&&"nodes"in e&&1===e.nodes.length&&"selector"===e.nodes[0].type&&e.replaceWith(e.nodes[0])})),r.walk((e=>{"nodes"in e&&sortCompoundSelectorsInsideComplexSelector(e)})),r.toString()})).filter((e=>!!e))}function splitSelectors(o,t,n=0){const r=":not(#"+t.specificityMatchingName+")",d=":not(."+t.specificityMatchingName+")",l=":not("+t.specificityMatchingName+")";return o.flatMap((o=>{if(-1===o.toLowerCase().indexOf(":is"))return o;let a=!1;const i=[];if(e().astSync(o).walkPseudos((e=>{if(":is"!==e.value.toLowerCase()||!e.nodes||!e.nodes.length)return;if("selector"===e.nodes[0].type&&0===e.nodes[0].nodes.length)return;if("pseudo"===e.parent?.parent?.type&&":not"===e.parent?.parent?.value?.toLowerCase())return void i.push([{start:e.parent.parent.sourceIndex,end:e.parent.parent.sourceIndex+e.parent.parent.toString().length,option:`:not(${e.nodes.toString()})`}]);if("pseudo"===e.parent?.parent?.type&&":has"===e.parent?.parent?.value?.toLowerCase())return void(e.value=":-csstools-matches");let o=e.parent;for(;o;){if(o.value&&":is"===o.value.toLowerCase()&&"pseudo"===o.type)return void(a=!0);o=o.parent}const t=s(e),n=e.sourceIndex,c=n+e.toString().length,p=[];e.nodes.forEach((e=>{const o={start:n,end:c,option:""},a=s(e);let i=e.toString().trim();const u=Math.max(0,t.a-a.a),h=Math.max(0,t.b-a.b),f=Math.max(0,t.c-a.c);for(let e=0;e{let s="";for(let t=0;t!!e))}function cartesianProduct(...e){const s=[],o=e.length-1;return function helper(t,n){for(let r=0,d=e[n].length;r{const s={specificityMatchingName:"does-not-exist",...e||{}};return{postcssPlugin:"postcss-is-pseudo-class",prepare(){const e=new WeakSet;return{postcssPlugin:"postcss-is-pseudo-class",Rule(o,{result:n}){if(!o.selector)return;if(!t.test(o.selector))return;if(e.has(o))return;let r=!1;const warnOnComplexSelector=()=>{"warning"===s.onComplexSelector&&(r||(r=!0,o.warn(n,`Complex selectors in '${o.selector}' can not be transformed to an equivalent selector without ':is()'.`)))};let d=!1;const warnOnPseudoElements=()=>{"warning"===s.onPseudoElement&&(d||(d=!0,o.warn(n,`Pseudo elements are not allowed in ':is()', unable to transform '${o.selector}'`)))};try{let t=!1;const n=[],r=complexSelectors(splitSelectors(o.selectors,{specificityMatchingName:s.specificityMatchingName}),{onComplexSelector:s.onComplexSelector},warnOnComplexSelector,warnOnPseudoElements);if(Array.from(new Set(r)).forEach((s=>{if(o.selectors.indexOf(s)>-1)n.push(s);else{if(alwaysValidSelector(s))return n.push(s),void(t=!0);e.add(o),o.cloneBefore({selector:s}),t=!0}})),n.length&&t&&(e.add(o),o.cloneBefore({selectors:n})),!s.preserve){if(!t)return;o.remove()}}catch(e){if(!(e instanceof Error))throw e;if(e.message.indexOf("call stack size exceeded")>-1)throw e;o.warn(n,`Failed to parse selector "${o.selector}" with error: ${e.message}`)}}}}}};creator.postcss=!0;export{creator as default}; diff --git a/plugins/postcss-is-pseudo-class/src/index.ts b/plugins/postcss-is-pseudo-class/src/index.ts index 1cc9db81d..de282b709 100644 --- a/plugins/postcss-is-pseudo-class/src/index.ts +++ b/plugins/postcss-is-pseudo-class/src/index.ts @@ -82,7 +82,7 @@ const creator: PluginCreator = (opts?: pluginOptions) => { try { let didModify = false; - const selectorListOnOriginalNode = []; + const selectorListOnOriginalNode: Array = []; // 1. List behavior. const split = splitSelectors( @@ -140,6 +140,10 @@ const creator: PluginCreator = (opts?: pluginOptions) => { rule.remove(); } } catch (err) { + if (!(err instanceof Error)) { + throw err; + } + // Do not ignore infinite recursion errors. if (err.message.indexOf('call stack size exceeded') > -1) { throw err; diff --git a/plugins/postcss-is-pseudo-class/src/split-selectors/complex.ts b/plugins/postcss-is-pseudo-class/src/split-selectors/complex.ts index 4a08cbb5c..667850db0 100644 --- a/plugins/postcss-is-pseudo-class/src/split-selectors/complex.ts +++ b/plugins/postcss-is-pseudo-class/src/split-selectors/complex.ts @@ -22,6 +22,7 @@ export default function complexSelectors(selectors: Array, pluginOptions pseudo.nodes[0].nodes.length === 0 ) { pseudo.value = ':not'; + // eslint-disable-next-line @typescript-eslint/no-unsafe-argument pseudo.nodes[0].append(parser.universal()); return; } diff --git a/plugins/postcss-is-pseudo-class/src/split-selectors/complex/child-adjacent-child.ts b/plugins/postcss-is-pseudo-class/src/split-selectors/complex/child-adjacent-child.ts index 2c85b0b13..4dc48fabe 100644 --- a/plugins/postcss-is-pseudo-class/src/split-selectors/complex/child-adjacent-child.ts +++ b/plugins/postcss-is-pseudo-class/src/split-selectors/complex/child-adjacent-child.ts @@ -1,3 +1,5 @@ +import parser from 'postcss-selector-parser'; + // :-csstools-matches(.a > .b) + :-csstools-matches(.c > .d) // equivalent to // .a.c > .b + .d @@ -9,7 +11,7 @@ // .a.c ~ .b + .d // // because adjacent elements have the same parent element. -export function childAdjacentChild(selector): boolean { +export function childAdjacentChild(selector: parser.Container): boolean { if (!selector || !selector.nodes) { return false; } diff --git a/plugins/postcss-is-pseudo-class/src/split-selectors/complex/is-in-compound.ts b/plugins/postcss-is-pseudo-class/src/split-selectors/complex/is-in-compound.ts index c6efa071f..c3a140ff8 100644 --- a/plugins/postcss-is-pseudo-class/src/split-selectors/complex/is-in-compound.ts +++ b/plugins/postcss-is-pseudo-class/src/split-selectors/complex/is-in-compound.ts @@ -9,11 +9,12 @@ import parser from 'postcss-selector-parser'; // .b > .c.a // // because `:-csstools-matches()` matches the final element of the selector, -export function isInCompoundWithOneOtherElement(selector): boolean { +export function isInCompoundWithOneOtherElement(selector: parser.Container): boolean { if (!selector || !selector.nodes) { return false; } - if (selector.type !== 'selector') { + + if (!parser.isSelector(selector)) { return false; } @@ -21,39 +22,33 @@ export function isInCompoundWithOneOtherElement(selector): boolean { return false; } - let isPseudoIndex; - let simpleSelectorIndex; - if (selector.nodes[0] && selector.nodes[0].type === 'pseudo' && selector.nodes[0].value === ':-csstools-matches') { + let isPseudoIndex: number = -1; + let simpleSelectorIndex: number = -1; + if (selector.nodes[0] && parser.isPseudoClass(selector.nodes[0]) && selector.nodes[0].value === ':-csstools-matches') { isPseudoIndex = 0; simpleSelectorIndex = 1; - } else if (selector.nodes[1] && selector.nodes[1].type === 'pseudo' && selector.nodes[1].value === ':-csstools-matches') { + } else if (selector.nodes[1] && parser.isPseudoClass(selector.nodes[1]) && selector.nodes[1].value === ':-csstools-matches') { isPseudoIndex = 1; simpleSelectorIndex = 0; } - if (!isPseudoIndex) { + const isPseudo: parser.Node | undefined = selector.nodes[isPseudoIndex]; + if (!isPseudo || !parser.isPseudoClass(isPseudo) || isPseudo.nodes.length !== 1) { return false; } - if (!selector.nodes[simpleSelectorIndex]) { + const simpleSelector: parser.Node | undefined = selector.nodes[simpleSelectorIndex]; + if (!simpleSelector) { return false; } - if (selector.nodes[simpleSelectorIndex].type === 'selector') { - if (selector.nodes[simpleSelectorIndex].some((x) => { - return x.type === 'combinator' || parser.isPseudoElement(x); - })) { - return false; - } - } - - if (selector.nodes[simpleSelectorIndex].type === 'combinator') { + if (parser.isCombinator(simpleSelector)) { return false; } - selector.nodes[isPseudoIndex].nodes[0].append(selector.nodes[simpleSelectorIndex].clone()); - selector.nodes[isPseudoIndex].replaceWith(...selector.nodes[isPseudoIndex].nodes[0].nodes); - selector.nodes[simpleSelectorIndex].remove(); + isPseudo.nodes[0].append(simpleSelector.clone()); + isPseudo.replaceWith(...isPseudo.nodes[0].nodes); + simpleSelector.remove(); return true; } diff --git a/plugins/postcss-is-pseudo-class/src/split-selectors/complex/is-pseudo-in-first-compound.ts b/plugins/postcss-is-pseudo-class/src/split-selectors/complex/is-pseudo-in-first-compound.ts index 0b39a007a..68079bd89 100644 --- a/plugins/postcss-is-pseudo-class/src/split-selectors/complex/is-pseudo-in-first-compound.ts +++ b/plugins/postcss-is-pseudo-class/src/split-selectors/complex/is-pseudo-in-first-compound.ts @@ -1,23 +1,27 @@ // :-csstools-matches(.a > .b) > .c // equivalent to // .a > .b > .c + +import parser from 'postcss-selector-parser'; + // because `:is()` is in the left-most compound selector -export function isPseudoInFirstCompound(selector): boolean { +export function isPseudoInFirstCompound(selector: parser.Container): boolean { if (!selector || !selector.nodes) { return false; } - if (selector.type !== 'selector') { + + if (!parser.isSelector(selector)) { return false; } let isPseudoIndex = -1; for (let i = 0; i < selector.nodes.length; i++) { const node = selector.nodes[i]; - if (node.type === 'combinator') { + if (parser.isCombinator(node)) { return false; } - if (node.type === 'pseudo' && node.value === ':-csstools-matches') { + if (parser.isPseudoClass(node) && node.value === ':-csstools-matches') { if (!node.nodes || node.nodes.length !== 1) { return false; } @@ -27,12 +31,12 @@ export function isPseudoInFirstCompound(selector): boolean { } } - if (isPseudoIndex === -1) { + const isPseudo = selector.nodes[isPseudoIndex]; + if (!isPseudo || !parser.isPseudoClass(isPseudo)) { return false; } const before = selector.nodes.slice(0, isPseudoIndex); - const isPseudo = selector.nodes[isPseudoIndex]; const after = selector.nodes.slice(isPseudoIndex + 1); before.forEach((node) => { diff --git a/plugins/postcss-is-pseudo-class/src/split-selectors/compound-selector-order.ts b/plugins/postcss-is-pseudo-class/src/split-selectors/compound-selector-order.ts index d41ba18f5..a27179b9b 100644 --- a/plugins/postcss-is-pseudo-class/src/split-selectors/compound-selector-order.ts +++ b/plugins/postcss-is-pseudo-class/src/split-selectors/compound-selector-order.ts @@ -1,12 +1,12 @@ import parser from 'postcss-selector-parser'; -export function sortCompoundSelectorsInsideComplexSelector(node): void { +export function sortCompoundSelectorsInsideComplexSelector(node: parser.Container): void { if (!node || !node.nodes || node.nodes.length === 1) { return; } const compoundSelectors: Array> = []; - let currentCompoundSelector = []; + let currentCompoundSelector: Array = []; for (let i = 0; i < node.nodes.length; i++) { if (node.nodes[i].type === 'combinator') { // Push the current compound selector @@ -36,7 +36,7 @@ export function sortCompoundSelectorsInsideComplexSelector(node): void { compoundSelectors.push(currentCompoundSelector); - const sortedCompoundSelectors = []; + const sortedCompoundSelectors: Array = []; for (let i = 0; i < compoundSelectors.length; i++) { const compoundSelector = compoundSelectors[i]; @@ -99,7 +99,7 @@ export function sortCompoundSelectorsInsideComplexSelector(node): void { } } -function selectorTypeOrder(selector, type): number { +function selectorTypeOrder(selector: parser.Node, type: string): number { if (parser.isPseudoElement(selector)) { return selectorTypeOrderIndex.pseudoElement; } @@ -107,7 +107,7 @@ function selectorTypeOrder(selector, type): number { return selectorTypeOrderIndex[type]; } -const selectorTypeOrderIndex = { +const selectorTypeOrderIndex: Record = { universal: 0, tag: 1, pseudoElement: 2, diff --git a/plugins/postcss-is-pseudo-class/src/split-selectors/split-selectors.ts b/plugins/postcss-is-pseudo-class/src/split-selectors/split-selectors.ts index 1f6b42ba8..c0bb883fe 100644 --- a/plugins/postcss-is-pseudo-class/src/split-selectors/split-selectors.ts +++ b/plugins/postcss-is-pseudo-class/src/split-selectors/split-selectors.ts @@ -61,7 +61,7 @@ export default function splitSelectors(selectors: Array, pluginOptions: const start = pseudo.sourceIndex; const end = start + pseudo.toString().length; - const replacementsParts = []; + const replacementsParts: Array<{start: number, end: number, option: string}> = []; pseudo.nodes.forEach((child) => { const replacement = { @@ -98,7 +98,7 @@ export default function splitSelectors(selectors: Array, pluginOptions: return [selector]; } - let results = []; + let results: Array = []; cartesianProduct(...replacements).forEach((replacement) => { let result = ''; @@ -122,17 +122,17 @@ export default function splitSelectors(selectors: Array, pluginOptions: } return results; - }).filter((x) => { + }).filter((x: string) => { return !!x; }); } // https://en.wikipedia.org/wiki/Cartesian_product function cartesianProduct(...args: Array>): Array> { - const r = []; + const r: Array> = []; const max = args.length - 1; - function helper(arr, i): void { + function helper(arr: Array, i: number): void { for (let j = 0, l = args[i].length; j < l; j++) { const a = arr.slice(0); a.push(args[i][j]); diff --git a/plugins/postcss-is-pseudo-class/test/basic.css b/plugins/postcss-is-pseudo-class/test/basic.css index 3817c225d..046540285 100644 --- a/plugins/postcss-is-pseudo-class/test/basic.css +++ b/plugins/postcss-is-pseudo-class/test/basic.css @@ -177,3 +177,7 @@ header:is(.a .b) { :is(:nth-child(2n+1 of .foo), .foo) { color: green; } + +div:is(.a > .b) > .c { + color: green; +} diff --git a/plugins/postcss-is-pseudo-class/test/basic.does-not-exist.expect.css b/plugins/postcss-is-pseudo-class/test/basic.does-not-exist.expect.css index c2e04eaeb..4ae83af42 100644 --- a/plugins/postcss-is-pseudo-class/test/basic.does-not-exist.expect.css +++ b/plugins/postcss-is-pseudo-class/test/basic.does-not-exist.expect.css @@ -281,3 +281,7 @@ input:hover, input:focus, button:hover, button:focus { .foo:not(.something-random) { color: green; } + +.a > div.b > .c { + color: green; +} diff --git a/plugins/postcss-is-pseudo-class/test/basic.expect.css b/plugins/postcss-is-pseudo-class/test/basic.expect.css index bb3c858c8..bbb24b876 100644 --- a/plugins/postcss-is-pseudo-class/test/basic.expect.css +++ b/plugins/postcss-is-pseudo-class/test/basic.expect.css @@ -281,3 +281,7 @@ input:hover, input:focus, button:hover, button:focus { .foo:not(.does-not-exist) { color: green; } + +.a > div.b > .c { + color: green; +} diff --git a/plugins/postcss-is-pseudo-class/test/basic.oncomplex.no-warning.expect.css b/plugins/postcss-is-pseudo-class/test/basic.oncomplex.no-warning.expect.css index bb3c858c8..bbb24b876 100644 --- a/plugins/postcss-is-pseudo-class/test/basic.oncomplex.no-warning.expect.css +++ b/plugins/postcss-is-pseudo-class/test/basic.oncomplex.no-warning.expect.css @@ -281,3 +281,7 @@ input:hover, input:focus, button:hover, button:focus { .foo:not(.does-not-exist) { color: green; } + +.a > div.b > .c { + color: green; +} diff --git a/plugins/postcss-is-pseudo-class/test/basic.oncomplex.warning.expect.css b/plugins/postcss-is-pseudo-class/test/basic.oncomplex.warning.expect.css index bb3c858c8..bbb24b876 100644 --- a/plugins/postcss-is-pseudo-class/test/basic.oncomplex.warning.expect.css +++ b/plugins/postcss-is-pseudo-class/test/basic.oncomplex.warning.expect.css @@ -281,3 +281,7 @@ input:hover, input:focus, button:hover, button:focus { .foo:not(.does-not-exist) { color: green; } + +.a > div.b > .c { + color: green; +} diff --git a/plugins/postcss-is-pseudo-class/test/basic.preserve.expect.css b/plugins/postcss-is-pseudo-class/test/basic.preserve.expect.css index 032584e03..903f511fe 100644 --- a/plugins/postcss-is-pseudo-class/test/basic.preserve.expect.css +++ b/plugins/postcss-is-pseudo-class/test/basic.preserve.expect.css @@ -429,3 +429,11 @@ header:is(.a .b) { :is(:nth-child(2n+1 of .foo), .foo) { color: green; } + +.a > div.b > .c { + color: green; +} + +div:is(.a > .b) > .c { + color: green; +} diff --git a/plugins/postcss-is-pseudo-class/test/basic.with-cloned-declarations.expect.css b/plugins/postcss-is-pseudo-class/test/basic.with-cloned-declarations.expect.css index 301348a84..906c6a39c 100644 --- a/plugins/postcss-is-pseudo-class/test/basic.with-cloned-declarations.expect.css +++ b/plugins/postcss-is-pseudo-class/test/basic.with-cloned-declarations.expect.css @@ -431,3 +431,11 @@ header:is(.a .b) { :is(:nth-child(2n+1 of .foo), .foo) { color: green; } + +.a > div.b > .c { + color: green; +} + +div:is(.a > .b) > .c { + color: green; +} diff --git a/plugins/postcss-logical-viewport-units/src/has-feature.ts b/plugins/postcss-logical-viewport-units/src/has-feature.ts index 5e3097269..c477dbe38 100644 --- a/plugins/postcss-logical-viewport-units/src/has-feature.ts +++ b/plugins/postcss-logical-viewport-units/src/has-feature.ts @@ -11,7 +11,6 @@ export const predicate = { const t = tokenizer({ css: source }); - // eslint-disable-next-line no-constant-condition while (true) { const token = t.nextToken(); if (!token) { diff --git a/plugins/postcss-logical-viewport-units/src/transform.ts b/plugins/postcss-logical-viewport-units/src/transform.ts index 47597dbab..5ae8ed5c4 100644 --- a/plugins/postcss-logical-viewport-units/src/transform.ts +++ b/plugins/postcss-logical-viewport-units/src/transform.ts @@ -5,7 +5,6 @@ export function transform(source: string, replacements: { vi: 'vw' | 'vh', vb: ' const tokens = []; let didTransformUnits = false; - // eslint-disable-next-line no-constant-condition while (true) { const token = t.nextToken(); if (!token) { diff --git a/plugins/postcss-logical/dist/index.cjs b/plugins/postcss-logical/dist/index.cjs index 048aa3c91..d29251ccc 100644 --- a/plugins/postcss-logical/dist/index.cjs +++ b/plugins/postcss-logical/dist/index.cjs @@ -1 +1 @@ -"use strict";var r,e,n=require("postcss-value-parser");!function(r){r.Block="block",r.Inline="inline"}(r||(r={})),function(r){r.Start="start",r.End="end"}(e||(e={}));const o={BlockStart:"block-start",BlockEnd:"block-end",InlineStart:"inline-start",InlineEnd:"inline-end"};var t,i;function directionFlowToAxes(r){switch(r){case t.TopToBottom:return[i.Top,i.Bottom];case t.BottomToTop:return[i.Bottom,i.Top];case t.RightToLeft:return[i.Right,i.Left];case t.LeftToRight:return[i.Left,i.Right]}}function cloneDeclaration(r,e,n){return r.parent&&r.parent.some((r=>"decl"==r.type&&r.prop===n&&r.value===e))?[]:[r.clone({value:e,prop:n})]}function transformTransition(r,e,o){const{prop:t,value:i}=r,l=n(i),a=[];let s=[];l.nodes.forEach((r=>{if("div"===r.type&&","===r.value)return a.push(s),void(s=[]);s.push(r)})),a.push(s);for(let r=0;r=0;e--){const o=JSON.parse(JSON.stringify(n));o[t].value=d[e].prop,a.splice(r+1,0,o)}a.splice(r,1),r++}}}const d=[];for(let r=0;r"space"!==r.type));if(e.length>2||0===e.length){const n=`[postcss-logical] Invalid number of values for ${r.prop}. Found ${e.length} values, expected 1 or 2.`;throw r.error(n)}let o,t;return 1===e.length?(o=n.stringify(e[0]),t=o):(o=n.stringify(e[0]),t=n.stringify(e[1])),[o,t]}function transformBorder(r,e){return n=>cloneDeclaration(n,n.value,`border-${e}-${r}`)}function transformBorderProperty(r,e){return n=>{const[o,t]=e,[i,l]=parseValueCouple(n);return[...cloneDeclaration(n,i,`border-${o}-${r}`),...cloneDeclaration(n,l,`border-${t}-${r}`)]}}function transformBorderShorthand(r){return e=>r.flatMap((r=>cloneDeclaration(e,e.value,`border-${r}`)))}function transformBorderRadius(r){return e=>{let n;switch(e.prop.toLowerCase()){case"border-start-start-radius":n=`border-${r.inlineIsHorizontal?`${r.block[0]}-${r.inline[0]}`:`${r.inline[0]}-${r.block[0]}`}-radius`;break;case"border-start-end-radius":n=`border-${r.inlineIsHorizontal?`${r.block[0]}-${r.inline[1]}`:`${r.inline[1]}-${r.block[0]}`}-radius`;break;case"border-end-start-radius":n=`border-${r.inlineIsHorizontal?`${r.block[1]}-${r.inline[0]}`:`${r.inline[0]}-${r.block[1]}`}-radius`;break;case"border-end-end-radius":n=`border-${r.inlineIsHorizontal?`${r.block[1]}-${r.inline[1]}`:`${r.inline[1]}-${r.block[1]}`}-radius`;break}return n?cloneDeclaration(e,e.value,n):[]}}function transformLogicalSize(r){return e=>{const{value:n}=e,o=r.inlineIsHorizontal?"width":"height",t=r.inlineIsHorizontal?"height":"width",i=e.prop.toLowerCase().replace("inline-size",o).replace("block-size",t);return cloneDeclaration(e,n,i)}}function transformOffset(r){return e=>cloneDeclaration(e,e.value,r)}function transformOffsetShorthand(r){return e=>{const[n,o]=r,[t,i]=parseValueCouple(e);return[...cloneDeclaration(e,t,n),...cloneDeclaration(e,i,o)]}}function transformSide(r,e){return n=>cloneDeclaration(n,n.value,`${r}-${e}`)}function transformSideShorthand(r,e){return n=>{const[o,t]=e,[i,l]=parseValueCouple(n);return[...cloneDeclaration(n,i,`${r}-${o}`),...cloneDeclaration(n,l,`${r}-${t}`)]}}function logicalToPhysical(r,e){const[n,t]=e.block,[i,l]=e.inline;switch(r){case o.BlockStart:return n;case o.BlockEnd:return t;case o.InlineStart:return i;case o.InlineEnd:return l;default:throw new Error("Unsupported logical direction")}}function doTransform(r,e,o){const{prop:t,value:i}=r,l=n(i);l.nodes.forEach((r=>{if("word"===r.type){const n=r.value.toLowerCase();e.includes(n)&&(r.value=logicalToPhysical(n,o))}}));const a=l.toString();return a!==i?cloneDeclaration(r,a,t):[]}function prepareTransforms(r,t,i,l,a){return{"caption-side":(d=r,r=>doTransform(r,Object.values(o),d)),"text-align":r.inlineIsHorizontal?(s=r.inline,r=>{const{prop:o,value:t}=r,i=n(t),[l,a]=s;i.nodes.forEach((r=>{if("word"===r.type){const n=r.value.toLowerCase();if(n===e.End)return void(r.value=a);n===e.Start&&(r.value=l)}}));const d=i.toString();return d!==t?cloneDeclaration(r,d,o):[]}):null,"block-size":transformLogicalSize(r),"inline-size":transformLogicalSize(r),"min-block-size":transformLogicalSize(r),"max-block-size":transformLogicalSize(r),"min-inline-size":transformLogicalSize(r),"max-inline-size":transformLogicalSize(r),"margin-block-start":transformSide("margin",t),"margin-block-end":transformSide("margin",i),"margin-inline-start":transformSide("margin",l),"margin-inline-end":transformSide("margin",a),"margin-block":transformSideShorthand("margin",r.block),"margin-inline":transformSideShorthand("margin",r.inline),"inset-block":transformOffsetShorthand(r.block),"inset-block-start":transformOffset(t),"inset-block-end":transformOffset(i),"inset-inline":transformOffsetShorthand(r.inline),"inset-inline-start":transformOffset(l),"inset-inline-end":transformOffset(a),inset:r=>{const e=n(r.value).nodes.filter((r=>"space"!==r.type&&"comment"!==r.type));if(e.length>4){const n=`[postcss-logical] Invalid number of values for ${r.prop}. Found ${e.length} values, expected up to 4 values.`;throw r.error(n)}let o,t,i,l;if(1===e.length)o=n.stringify(e[0]),t=o,i=o,l=o;else if(2===e.length)o=n.stringify(e[0]),t=n.stringify(e[1]),i=o,l=t;else if(3===e.length)o=n.stringify(e[0]),t=n.stringify(e[1]),l=t,i=n.stringify(e[2]);else{if(4!==e.length)return[];o=n.stringify(e[0]),t=n.stringify(e[1]),i=n.stringify(e[2]),l=n.stringify(e[3])}return[...cloneDeclaration(r,o,"top"),...cloneDeclaration(r,t,"right"),...cloneDeclaration(r,i,"bottom"),...cloneDeclaration(r,l,"left")]},"padding-block-start":transformSide("padding",t),"padding-block-end":transformSide("padding",i),"padding-inline-start":transformSide("padding",l),"padding-inline-end":transformSide("padding",a),"padding-block":transformSideShorthand("padding",r.block),"padding-inline":transformSideShorthand("padding",r.inline),"border-block-start-width":transformBorder("width",t),"border-block-end-width":transformBorder("width",i),"border-inline-start-width":transformBorder("width",l),"border-inline-end-width":transformBorder("width",a),"border-block-width":transformBorderProperty("width",r.block),"border-inline-width":transformBorderProperty("width",r.inline),"border-block-start-style":transformBorder("style",t),"border-block-end-style":transformBorder("style",i),"border-inline-start-style":transformBorder("style",l),"border-inline-end-style":transformBorder("style",a),"border-block-style":transformBorderProperty("style",r.block),"border-inline-style":transformBorderProperty("style",r.inline),"border-block-start-color":transformBorder("color",t),"border-block-end-color":transformBorder("color",i),"border-inline-start-color":transformBorder("color",l),"border-inline-end-color":transformBorder("color",a),"border-block-color":transformBorderProperty("color",r.block),"border-inline-color":transformBorderProperty("color",r.inline),"border-block":transformBorderShorthand(r.block),"border-block-start":transformBorderShorthand([t]),"border-block-end":transformBorderShorthand([i]),"border-inline":transformBorderShorthand(r.inline),"border-inline-start":transformBorderShorthand([l]),"border-inline-end":transformBorderShorthand([a]),"border-start-start-radius":transformBorderRadius(r),"border-start-end-radius":transformBorderRadius(r),"border-end-start-radius":transformBorderRadius(r),"border-end-end-radius":transformBorderRadius(r)};var s,d}!function(r){r.TopToBottom="top-to-bottom",r.BottomToTop="bottom-to-top",r.RightToLeft="right-to-left",r.LeftToRight="left-to-right"}(t||(t={})),function(r){r.Top="top",r.Right="right",r.Bottom="bottom",r.Left="left"}(i||(i={}));const creator=r=>{const e=Object.assign({blockDirection:t.TopToBottom,inlineDirection:t.LeftToRight},r),n=Object.values(t);if(!n.includes(e.blockDirection))throw new Error(`[postcss-logical] "blockDirection" must be one of ${n.join(", ")}`);if(!n.includes(e.inlineDirection))throw new Error(`[postcss-logical] "inlineDirection" must be one of ${n.join(", ")}`);const[o,l]=directionFlowToAxes(e.blockDirection),[a,s]=directionFlowToAxes(e.inlineDirection);if(!Object.values(i).every((r=>[o,l,a,s].includes(r))))throw new Error('[postcss-logical] "blockDirection" and "inlineDirection" must be on separate axes');const makeTransform=r=>(e,{result:n})=>{if(!r)return;let o=[];try{o=r(e)}catch(r){return void e.warn(n,r instanceof Error?r.message:String(r))}o?.length&&(o.forEach((r=>{e.cloneBefore(r)})),e.remove())},d=prepareTransforms({block:[o,l],inline:[a,s],inlineIsHorizontal:[t.LeftToRight,t.RightToLeft].includes(e.inlineDirection)},o,l,a,s);return{postcssPlugin:"postcss-logical",Declaration:{"caption-side":makeTransform(d["caption-side"]),"text-align":makeTransform(d["text-align"]),"block-size":makeTransform(d["block-size"]),"inline-size":makeTransform(d["inline-size"]),"min-block-size":makeTransform(d["min-block-size"]),"max-block-size":makeTransform(d["max-block-size"]),"min-inline-size":makeTransform(d["min-inline-size"]),"max-inline-size":makeTransform(d["max-inline-size"]),"margin-block-start":makeTransform(d["margin-block-start"]),"margin-block-end":makeTransform(d["margin-block-end"]),"margin-inline-start":makeTransform(d["margin-inline-start"]),"margin-inline-end":makeTransform(d["margin-inline-end"]),"margin-block":makeTransform(d["margin-block"]),"margin-inline":makeTransform(d["margin-inline"]),"inset-block":makeTransform(d["inset-block"]),"inset-block-start":makeTransform(d["inset-block-start"]),"inset-block-end":makeTransform(d["inset-block-end"]),"inset-inline":makeTransform(d["inset-inline"]),"inset-inline-start":makeTransform(d["inset-inline-start"]),"inset-inline-end":makeTransform(d["inset-inline-end"]),inset:makeTransform(d.inset),"padding-block-start":makeTransform(d["padding-block-start"]),"padding-block-end":makeTransform(d["padding-block-end"]),"padding-inline-start":makeTransform(d["padding-inline-start"]),"padding-inline-end":makeTransform(d["padding-inline-end"]),"padding-block":makeTransform(d["padding-block"]),"padding-inline":makeTransform(d["padding-inline"]),"border-block-start-width":makeTransform(d["border-block-start-width"]),"border-block-end-width":makeTransform(d["border-block-end-width"]),"border-inline-start-width":makeTransform(d["border-inline-start-width"]),"border-inline-end-width":makeTransform(d["border-inline-end-width"]),"border-block-width":makeTransform(d["border-block-width"]),"border-inline-width":makeTransform(d["border-inline-width"]),"border-block-start-style":makeTransform(d["border-block-start-style"]),"border-block-end-style":makeTransform(d["border-block-end-style"]),"border-inline-start-style":makeTransform(d["border-inline-start-style"]),"border-inline-end-style":makeTransform(d["border-inline-end-style"]),"border-block-style":makeTransform(d["border-block-style"]),"border-inline-style":makeTransform(d["border-inline-style"]),"border-block-start-color":makeTransform(d["border-block-start-color"]),"border-block-end-color":makeTransform(d["border-block-end-color"]),"border-inline-start-color":makeTransform(d["border-inline-start-color"]),"border-inline-end-color":makeTransform(d["border-inline-end-color"]),"border-block-color":makeTransform(d["border-block-color"]),"border-inline-color":makeTransform(d["border-inline-color"]),"border-block":makeTransform(d["border-block"]),"border-block-start":makeTransform(d["border-block-start"]),"border-block-end":makeTransform(d["border-block-end"]),"border-inline":makeTransform(d["border-inline"]),"border-inline-start":makeTransform(d["border-inline-start"]),"border-inline-end":makeTransform(d["border-inline-end"]),"border-start-start-radius":makeTransform(d["border-start-start-radius"]),"border-start-end-radius":makeTransform(d["border-start-end-radius"]),"border-end-start-radius":makeTransform(d["border-end-start-radius"]),"border-end-end-radius":makeTransform(d["border-end-end-radius"]),transition:(r,{result:e,postcss:n})=>{let o=[];try{o=transformTransition(r,n,d)}catch(n){return void r.warn(e,n instanceof Error?n.message:String(n))}o?.length&&(o.forEach((e=>{r.cloneBefore(e)})),r.remove())}}}};creator.postcss=!0,module.exports=creator; +"use strict";var r,e,n=require("postcss-value-parser");!function(r){r.Block="block",r.Inline="inline"}(r||(r={})),function(r){r.Start="start",r.End="end"}(e||(e={}));const o={BlockStart:"block-start",BlockEnd:"block-end",InlineStart:"inline-start",InlineEnd:"inline-end"};var t,i;function directionFlowToAxes(r){switch(r){case t.TopToBottom:return[i.Top,i.Bottom];case t.BottomToTop:return[i.Bottom,i.Top];case t.RightToLeft:return[i.Right,i.Left];case t.LeftToRight:return[i.Left,i.Right]}}function cloneDeclaration(r,e,n){return r.parent&&r.parent.some((r=>"decl"==r.type&&r.prop===n&&r.value===e))?[]:[r.clone({value:e,prop:n})]}function transformTransition(r,e,o){const{prop:t,value:i}=r,l=n(i),a=[];let s=[];l.nodes.forEach((r=>{if("div"===r.type&&","===r.value)return a.push(s),void(s=[]);s.push(r)})),a.push(s);for(let r=0;r=0;e--){const o=JSON.parse(JSON.stringify(n));o[t].value=d[e].prop,a.splice(r+1,0,o)}a.splice(r,1),r++}}}const d=[];for(let r=0;r"space"!==r.type));if(e.length>2||0===e.length){const n=`[postcss-logical] Invalid number of values for ${r.prop}. Found ${e.length} values, expected 1 or 2.`;throw r.error(n)}let o,t;return 1===e.length?(o=n.stringify(e[0]),t=o):(o=n.stringify(e[0]),t=n.stringify(e[1])),[o,t]}function transformBorder(r,e){return n=>cloneDeclaration(n,n.value,`border-${e}-${r}`)}function transformBorderProperty(r,e){return n=>{const[o,t]=e,[i,l]=parseValueCouple(n);return[...cloneDeclaration(n,i,`border-${o}-${r}`),...cloneDeclaration(n,l,`border-${t}-${r}`)]}}function transformBorderShorthand(r){return e=>r.flatMap((r=>cloneDeclaration(e,e.value,`border-${r}`)))}function transformBorderRadius(r){return e=>{let n;switch(e.prop.toLowerCase()){case"border-start-start-radius":n=`border-${r.inlineIsHorizontal?`${r.block[0]}-${r.inline[0]}`:`${r.inline[0]}-${r.block[0]}`}-radius`;break;case"border-start-end-radius":n=`border-${r.inlineIsHorizontal?`${r.block[0]}-${r.inline[1]}`:`${r.inline[1]}-${r.block[0]}`}-radius`;break;case"border-end-start-radius":n=`border-${r.inlineIsHorizontal?`${r.block[1]}-${r.inline[0]}`:`${r.inline[0]}-${r.block[1]}`}-radius`;break;case"border-end-end-radius":n=`border-${r.inlineIsHorizontal?`${r.block[1]}-${r.inline[1]}`:`${r.inline[1]}-${r.block[1]}`}-radius`;break}return n?cloneDeclaration(e,e.value,n):[]}}function transformLogicalSize(r){return e=>{const{value:n}=e,o=r.inlineIsHorizontal?"width":"height",t=r.inlineIsHorizontal?"height":"width",i=e.prop.toLowerCase().replace("inline-size",o).replace("block-size",t);return cloneDeclaration(e,n,i)}}function transformOffset(r){return e=>cloneDeclaration(e,e.value,r)}function transformOffsetShorthand(r){return e=>{const[n,o]=r,[t,i]=parseValueCouple(e);return[...cloneDeclaration(e,t,n),...cloneDeclaration(e,i,o)]}}function transformSide(r,e){return n=>cloneDeclaration(n,n.value,`${r}-${e}`)}function transformSideShorthand(r,e){return n=>{const[o,t]=e,[i,l]=parseValueCouple(n);return[...cloneDeclaration(n,i,`${r}-${o}`),...cloneDeclaration(n,l,`${r}-${t}`)]}}function logicalToPhysical(r,e){const[n,t]=e.block,[i,l]=e.inline;switch(r){case o.BlockStart:return n;case o.BlockEnd:return t;case o.InlineStart:return i;case o.InlineEnd:return l;default:throw new Error("Unsupported logical direction")}}function doTransform(r,e,o){const{prop:t,value:i}=r,l=n(i);l.nodes.forEach((r=>{if("word"===r.type){const n=r.value.toLowerCase();e.includes(n)&&(r.value=logicalToPhysical(n,o))}}));const a=l.toString();return a!==i?cloneDeclaration(r,a,t):[]}function prepareTransforms(r,t,i,l,a){return{"caption-side":(d=r,r=>doTransform(r,Object.values(o),d)),"text-align":r.inlineIsHorizontal?(s=r.inline,r=>{const{prop:o,value:t}=r,i=n(t),[l,a]=s;i.nodes.forEach((r=>{if("word"===r.type){const n=r.value.toLowerCase();if(n===e.End)return void(r.value=a);if(n===e.Start)return void(r.value=l)}}));const d=i.toString();return d!==t?cloneDeclaration(r,d,o):[]}):null,"block-size":transformLogicalSize(r),"inline-size":transformLogicalSize(r),"min-block-size":transformLogicalSize(r),"max-block-size":transformLogicalSize(r),"min-inline-size":transformLogicalSize(r),"max-inline-size":transformLogicalSize(r),"margin-block-start":transformSide("margin",t),"margin-block-end":transformSide("margin",i),"margin-inline-start":transformSide("margin",l),"margin-inline-end":transformSide("margin",a),"margin-block":transformSideShorthand("margin",r.block),"margin-inline":transformSideShorthand("margin",r.inline),"inset-block":transformOffsetShorthand(r.block),"inset-block-start":transformOffset(t),"inset-block-end":transformOffset(i),"inset-inline":transformOffsetShorthand(r.inline),"inset-inline-start":transformOffset(l),"inset-inline-end":transformOffset(a),inset:r=>{const e=n(r.value).nodes.filter((r=>"space"!==r.type&&"comment"!==r.type));if(e.length>4){const n=`[postcss-logical] Invalid number of values for ${r.prop}. Found ${e.length} values, expected up to 4 values.`;throw r.error(n)}let o,t,i,l;if(1===e.length)o=n.stringify(e[0]),t=o,i=o,l=o;else if(2===e.length)o=n.stringify(e[0]),t=n.stringify(e[1]),i=o,l=t;else if(3===e.length)o=n.stringify(e[0]),t=n.stringify(e[1]),l=t,i=n.stringify(e[2]);else{if(4!==e.length)return[];o=n.stringify(e[0]),t=n.stringify(e[1]),i=n.stringify(e[2]),l=n.stringify(e[3])}return[...cloneDeclaration(r,o,"top"),...cloneDeclaration(r,t,"right"),...cloneDeclaration(r,i,"bottom"),...cloneDeclaration(r,l,"left")]},"padding-block-start":transformSide("padding",t),"padding-block-end":transformSide("padding",i),"padding-inline-start":transformSide("padding",l),"padding-inline-end":transformSide("padding",a),"padding-block":transformSideShorthand("padding",r.block),"padding-inline":transformSideShorthand("padding",r.inline),"border-block-start-width":transformBorder("width",t),"border-block-end-width":transformBorder("width",i),"border-inline-start-width":transformBorder("width",l),"border-inline-end-width":transformBorder("width",a),"border-block-width":transformBorderProperty("width",r.block),"border-inline-width":transformBorderProperty("width",r.inline),"border-block-start-style":transformBorder("style",t),"border-block-end-style":transformBorder("style",i),"border-inline-start-style":transformBorder("style",l),"border-inline-end-style":transformBorder("style",a),"border-block-style":transformBorderProperty("style",r.block),"border-inline-style":transformBorderProperty("style",r.inline),"border-block-start-color":transformBorder("color",t),"border-block-end-color":transformBorder("color",i),"border-inline-start-color":transformBorder("color",l),"border-inline-end-color":transformBorder("color",a),"border-block-color":transformBorderProperty("color",r.block),"border-inline-color":transformBorderProperty("color",r.inline),"border-block":transformBorderShorthand(r.block),"border-block-start":transformBorderShorthand([t]),"border-block-end":transformBorderShorthand([i]),"border-inline":transformBorderShorthand(r.inline),"border-inline-start":transformBorderShorthand([l]),"border-inline-end":transformBorderShorthand([a]),"border-start-start-radius":transformBorderRadius(r),"border-start-end-radius":transformBorderRadius(r),"border-end-start-radius":transformBorderRadius(r),"border-end-end-radius":transformBorderRadius(r)};var s,d}!function(r){r.TopToBottom="top-to-bottom",r.BottomToTop="bottom-to-top",r.RightToLeft="right-to-left",r.LeftToRight="left-to-right"}(t||(t={})),function(r){r.Top="top",r.Right="right",r.Bottom="bottom",r.Left="left"}(i||(i={}));const creator=r=>{const e=Object.assign({blockDirection:t.TopToBottom,inlineDirection:t.LeftToRight},r),n=Object.values(t);if(!n.includes(e.blockDirection))throw new Error(`[postcss-logical] "blockDirection" must be one of ${n.join(", ")}`);if(!n.includes(e.inlineDirection))throw new Error(`[postcss-logical] "inlineDirection" must be one of ${n.join(", ")}`);const[o,l]=directionFlowToAxes(e.blockDirection),[a,s]=directionFlowToAxes(e.inlineDirection);if(!Object.values(i).every((r=>[o,l,a,s].includes(r))))throw new Error('[postcss-logical] "blockDirection" and "inlineDirection" must be on separate axes');const makeTransform=r=>(e,{result:n})=>{if(!r)return;let o=[];try{o=r(e)}catch(r){return void e.warn(n,r instanceof Error?r.message:String(r))}o?.length&&(o.forEach((r=>{e.cloneBefore(r)})),e.remove())},d=prepareTransforms({block:[o,l],inline:[a,s],inlineIsHorizontal:[t.LeftToRight,t.RightToLeft].includes(e.inlineDirection)},o,l,a,s);return{postcssPlugin:"postcss-logical",Declaration:{"caption-side":makeTransform(d["caption-side"]),"text-align":makeTransform(d["text-align"]),"block-size":makeTransform(d["block-size"]),"inline-size":makeTransform(d["inline-size"]),"min-block-size":makeTransform(d["min-block-size"]),"max-block-size":makeTransform(d["max-block-size"]),"min-inline-size":makeTransform(d["min-inline-size"]),"max-inline-size":makeTransform(d["max-inline-size"]),"margin-block-start":makeTransform(d["margin-block-start"]),"margin-block-end":makeTransform(d["margin-block-end"]),"margin-inline-start":makeTransform(d["margin-inline-start"]),"margin-inline-end":makeTransform(d["margin-inline-end"]),"margin-block":makeTransform(d["margin-block"]),"margin-inline":makeTransform(d["margin-inline"]),"inset-block":makeTransform(d["inset-block"]),"inset-block-start":makeTransform(d["inset-block-start"]),"inset-block-end":makeTransform(d["inset-block-end"]),"inset-inline":makeTransform(d["inset-inline"]),"inset-inline-start":makeTransform(d["inset-inline-start"]),"inset-inline-end":makeTransform(d["inset-inline-end"]),inset:makeTransform(d.inset),"padding-block-start":makeTransform(d["padding-block-start"]),"padding-block-end":makeTransform(d["padding-block-end"]),"padding-inline-start":makeTransform(d["padding-inline-start"]),"padding-inline-end":makeTransform(d["padding-inline-end"]),"padding-block":makeTransform(d["padding-block"]),"padding-inline":makeTransform(d["padding-inline"]),"border-block-start-width":makeTransform(d["border-block-start-width"]),"border-block-end-width":makeTransform(d["border-block-end-width"]),"border-inline-start-width":makeTransform(d["border-inline-start-width"]),"border-inline-end-width":makeTransform(d["border-inline-end-width"]),"border-block-width":makeTransform(d["border-block-width"]),"border-inline-width":makeTransform(d["border-inline-width"]),"border-block-start-style":makeTransform(d["border-block-start-style"]),"border-block-end-style":makeTransform(d["border-block-end-style"]),"border-inline-start-style":makeTransform(d["border-inline-start-style"]),"border-inline-end-style":makeTransform(d["border-inline-end-style"]),"border-block-style":makeTransform(d["border-block-style"]),"border-inline-style":makeTransform(d["border-inline-style"]),"border-block-start-color":makeTransform(d["border-block-start-color"]),"border-block-end-color":makeTransform(d["border-block-end-color"]),"border-inline-start-color":makeTransform(d["border-inline-start-color"]),"border-inline-end-color":makeTransform(d["border-inline-end-color"]),"border-block-color":makeTransform(d["border-block-color"]),"border-inline-color":makeTransform(d["border-inline-color"]),"border-block":makeTransform(d["border-block"]),"border-block-start":makeTransform(d["border-block-start"]),"border-block-end":makeTransform(d["border-block-end"]),"border-inline":makeTransform(d["border-inline"]),"border-inline-start":makeTransform(d["border-inline-start"]),"border-inline-end":makeTransform(d["border-inline-end"]),"border-start-start-radius":makeTransform(d["border-start-start-radius"]),"border-start-end-radius":makeTransform(d["border-start-end-radius"]),"border-end-start-radius":makeTransform(d["border-end-start-radius"]),"border-end-end-radius":makeTransform(d["border-end-end-radius"]),transition:(r,{result:e,postcss:n})=>{let o=[];try{o=transformTransition(r,n,d)}catch(n){return void r.warn(e,n instanceof Error?n.message:String(n))}o?.length&&(o.forEach((e=>{r.cloneBefore(e)})),r.remove())}}}};creator.postcss=!0,module.exports=creator; diff --git a/plugins/postcss-logical/dist/index.mjs b/plugins/postcss-logical/dist/index.mjs index 6359f5928..c588585e6 100644 --- a/plugins/postcss-logical/dist/index.mjs +++ b/plugins/postcss-logical/dist/index.mjs @@ -1 +1 @@ -import r from"postcss-value-parser";var e,n;!function(r){r.Block="block",r.Inline="inline"}(e||(e={})),function(r){r.Start="start",r.End="end"}(n||(n={}));const o={BlockStart:"block-start",BlockEnd:"block-end",InlineStart:"inline-start",InlineEnd:"inline-end"};var t,i;function directionFlowToAxes(r){switch(r){case t.TopToBottom:return[i.Top,i.Bottom];case t.BottomToTop:return[i.Bottom,i.Top];case t.RightToLeft:return[i.Right,i.Left];case t.LeftToRight:return[i.Left,i.Right]}}function cloneDeclaration(r,e,n){return r.parent&&r.parent.some((r=>"decl"==r.type&&r.prop===n&&r.value===e))?[]:[r.clone({value:e,prop:n})]}function transformTransition(e,n,o){const{prop:t,value:i}=e,l=r(i),a=[];let s=[];l.nodes.forEach((r=>{if("div"===r.type&&","===r.value)return a.push(s),void(s=[]);s.push(r)})),a.push(s);for(let r=0;r=0;n--){const o=JSON.parse(JSON.stringify(e));o[t].value=d[n].prop,a.splice(r+1,0,o)}a.splice(r,1),r++}}}const d=[];for(let r=0;r"space"!==r.type));if(n.length>2||0===n.length){const r=`[postcss-logical] Invalid number of values for ${e.prop}. Found ${n.length} values, expected 1 or 2.`;throw e.error(r)}let o,t;return 1===n.length?(o=r.stringify(n[0]),t=o):(o=r.stringify(n[0]),t=r.stringify(n[1])),[o,t]}function transformBorder(r,e){return n=>cloneDeclaration(n,n.value,`border-${e}-${r}`)}function transformBorderProperty(r,e){return n=>{const[o,t]=e,[i,l]=parseValueCouple(n);return[...cloneDeclaration(n,i,`border-${o}-${r}`),...cloneDeclaration(n,l,`border-${t}-${r}`)]}}function transformBorderShorthand(r){return e=>r.flatMap((r=>cloneDeclaration(e,e.value,`border-${r}`)))}function transformBorderRadius(r){return e=>{let n;switch(e.prop.toLowerCase()){case"border-start-start-radius":n=`border-${r.inlineIsHorizontal?`${r.block[0]}-${r.inline[0]}`:`${r.inline[0]}-${r.block[0]}`}-radius`;break;case"border-start-end-radius":n=`border-${r.inlineIsHorizontal?`${r.block[0]}-${r.inline[1]}`:`${r.inline[1]}-${r.block[0]}`}-radius`;break;case"border-end-start-radius":n=`border-${r.inlineIsHorizontal?`${r.block[1]}-${r.inline[0]}`:`${r.inline[0]}-${r.block[1]}`}-radius`;break;case"border-end-end-radius":n=`border-${r.inlineIsHorizontal?`${r.block[1]}-${r.inline[1]}`:`${r.inline[1]}-${r.block[1]}`}-radius`;break}return n?cloneDeclaration(e,e.value,n):[]}}function transformLogicalSize(r){return e=>{const{value:n}=e,o=r.inlineIsHorizontal?"width":"height",t=r.inlineIsHorizontal?"height":"width",i=e.prop.toLowerCase().replace("inline-size",o).replace("block-size",t);return cloneDeclaration(e,n,i)}}function transformOffset(r){return e=>cloneDeclaration(e,e.value,r)}function transformOffsetShorthand(r){return e=>{const[n,o]=r,[t,i]=parseValueCouple(e);return[...cloneDeclaration(e,t,n),...cloneDeclaration(e,i,o)]}}function transformSide(r,e){return n=>cloneDeclaration(n,n.value,`${r}-${e}`)}function transformSideShorthand(r,e){return n=>{const[o,t]=e,[i,l]=parseValueCouple(n);return[...cloneDeclaration(n,i,`${r}-${o}`),...cloneDeclaration(n,l,`${r}-${t}`)]}}function logicalToPhysical(r,e){const[n,t]=e.block,[i,l]=e.inline;switch(r){case o.BlockStart:return n;case o.BlockEnd:return t;case o.InlineStart:return i;case o.InlineEnd:return l;default:throw new Error("Unsupported logical direction")}}function doTransform(e,n,o){const{prop:t,value:i}=e,l=r(i);l.nodes.forEach((r=>{if("word"===r.type){const e=r.value.toLowerCase();n.includes(e)&&(r.value=logicalToPhysical(e,o))}}));const a=l.toString();return a!==i?cloneDeclaration(e,a,t):[]}function prepareTransforms(e,t,i,l,a){return{"caption-side":(d=e,r=>doTransform(r,Object.values(o),d)),"text-align":e.inlineIsHorizontal?(s=e.inline,e=>{const{prop:o,value:t}=e,i=r(t),[l,a]=s;i.nodes.forEach((r=>{if("word"===r.type){const e=r.value.toLowerCase();if(e===n.End)return void(r.value=a);e===n.Start&&(r.value=l)}}));const d=i.toString();return d!==t?cloneDeclaration(e,d,o):[]}):null,"block-size":transformLogicalSize(e),"inline-size":transformLogicalSize(e),"min-block-size":transformLogicalSize(e),"max-block-size":transformLogicalSize(e),"min-inline-size":transformLogicalSize(e),"max-inline-size":transformLogicalSize(e),"margin-block-start":transformSide("margin",t),"margin-block-end":transformSide("margin",i),"margin-inline-start":transformSide("margin",l),"margin-inline-end":transformSide("margin",a),"margin-block":transformSideShorthand("margin",e.block),"margin-inline":transformSideShorthand("margin",e.inline),"inset-block":transformOffsetShorthand(e.block),"inset-block-start":transformOffset(t),"inset-block-end":transformOffset(i),"inset-inline":transformOffsetShorthand(e.inline),"inset-inline-start":transformOffset(l),"inset-inline-end":transformOffset(a),inset:e=>{const n=r(e.value).nodes.filter((r=>"space"!==r.type&&"comment"!==r.type));if(n.length>4){const r=`[postcss-logical] Invalid number of values for ${e.prop}. Found ${n.length} values, expected up to 4 values.`;throw e.error(r)}let o,t,i,l;if(1===n.length)o=r.stringify(n[0]),t=o,i=o,l=o;else if(2===n.length)o=r.stringify(n[0]),t=r.stringify(n[1]),i=o,l=t;else if(3===n.length)o=r.stringify(n[0]),t=r.stringify(n[1]),l=t,i=r.stringify(n[2]);else{if(4!==n.length)return[];o=r.stringify(n[0]),t=r.stringify(n[1]),i=r.stringify(n[2]),l=r.stringify(n[3])}return[...cloneDeclaration(e,o,"top"),...cloneDeclaration(e,t,"right"),...cloneDeclaration(e,i,"bottom"),...cloneDeclaration(e,l,"left")]},"padding-block-start":transformSide("padding",t),"padding-block-end":transformSide("padding",i),"padding-inline-start":transformSide("padding",l),"padding-inline-end":transformSide("padding",a),"padding-block":transformSideShorthand("padding",e.block),"padding-inline":transformSideShorthand("padding",e.inline),"border-block-start-width":transformBorder("width",t),"border-block-end-width":transformBorder("width",i),"border-inline-start-width":transformBorder("width",l),"border-inline-end-width":transformBorder("width",a),"border-block-width":transformBorderProperty("width",e.block),"border-inline-width":transformBorderProperty("width",e.inline),"border-block-start-style":transformBorder("style",t),"border-block-end-style":transformBorder("style",i),"border-inline-start-style":transformBorder("style",l),"border-inline-end-style":transformBorder("style",a),"border-block-style":transformBorderProperty("style",e.block),"border-inline-style":transformBorderProperty("style",e.inline),"border-block-start-color":transformBorder("color",t),"border-block-end-color":transformBorder("color",i),"border-inline-start-color":transformBorder("color",l),"border-inline-end-color":transformBorder("color",a),"border-block-color":transformBorderProperty("color",e.block),"border-inline-color":transformBorderProperty("color",e.inline),"border-block":transformBorderShorthand(e.block),"border-block-start":transformBorderShorthand([t]),"border-block-end":transformBorderShorthand([i]),"border-inline":transformBorderShorthand(e.inline),"border-inline-start":transformBorderShorthand([l]),"border-inline-end":transformBorderShorthand([a]),"border-start-start-radius":transformBorderRadius(e),"border-start-end-radius":transformBorderRadius(e),"border-end-start-radius":transformBorderRadius(e),"border-end-end-radius":transformBorderRadius(e)};var s,d}!function(r){r.TopToBottom="top-to-bottom",r.BottomToTop="bottom-to-top",r.RightToLeft="right-to-left",r.LeftToRight="left-to-right"}(t||(t={})),function(r){r.Top="top",r.Right="right",r.Bottom="bottom",r.Left="left"}(i||(i={}));const creator=r=>{const e=Object.assign({blockDirection:t.TopToBottom,inlineDirection:t.LeftToRight},r),n=Object.values(t);if(!n.includes(e.blockDirection))throw new Error(`[postcss-logical] "blockDirection" must be one of ${n.join(", ")}`);if(!n.includes(e.inlineDirection))throw new Error(`[postcss-logical] "inlineDirection" must be one of ${n.join(", ")}`);const[o,l]=directionFlowToAxes(e.blockDirection),[a,s]=directionFlowToAxes(e.inlineDirection);if(!Object.values(i).every((r=>[o,l,a,s].includes(r))))throw new Error('[postcss-logical] "blockDirection" and "inlineDirection" must be on separate axes');const makeTransform=r=>(e,{result:n})=>{if(!r)return;let o=[];try{o=r(e)}catch(r){return void e.warn(n,r instanceof Error?r.message:String(r))}o?.length&&(o.forEach((r=>{e.cloneBefore(r)})),e.remove())},d=prepareTransforms({block:[o,l],inline:[a,s],inlineIsHorizontal:[t.LeftToRight,t.RightToLeft].includes(e.inlineDirection)},o,l,a,s);return{postcssPlugin:"postcss-logical",Declaration:{"caption-side":makeTransform(d["caption-side"]),"text-align":makeTransform(d["text-align"]),"block-size":makeTransform(d["block-size"]),"inline-size":makeTransform(d["inline-size"]),"min-block-size":makeTransform(d["min-block-size"]),"max-block-size":makeTransform(d["max-block-size"]),"min-inline-size":makeTransform(d["min-inline-size"]),"max-inline-size":makeTransform(d["max-inline-size"]),"margin-block-start":makeTransform(d["margin-block-start"]),"margin-block-end":makeTransform(d["margin-block-end"]),"margin-inline-start":makeTransform(d["margin-inline-start"]),"margin-inline-end":makeTransform(d["margin-inline-end"]),"margin-block":makeTransform(d["margin-block"]),"margin-inline":makeTransform(d["margin-inline"]),"inset-block":makeTransform(d["inset-block"]),"inset-block-start":makeTransform(d["inset-block-start"]),"inset-block-end":makeTransform(d["inset-block-end"]),"inset-inline":makeTransform(d["inset-inline"]),"inset-inline-start":makeTransform(d["inset-inline-start"]),"inset-inline-end":makeTransform(d["inset-inline-end"]),inset:makeTransform(d.inset),"padding-block-start":makeTransform(d["padding-block-start"]),"padding-block-end":makeTransform(d["padding-block-end"]),"padding-inline-start":makeTransform(d["padding-inline-start"]),"padding-inline-end":makeTransform(d["padding-inline-end"]),"padding-block":makeTransform(d["padding-block"]),"padding-inline":makeTransform(d["padding-inline"]),"border-block-start-width":makeTransform(d["border-block-start-width"]),"border-block-end-width":makeTransform(d["border-block-end-width"]),"border-inline-start-width":makeTransform(d["border-inline-start-width"]),"border-inline-end-width":makeTransform(d["border-inline-end-width"]),"border-block-width":makeTransform(d["border-block-width"]),"border-inline-width":makeTransform(d["border-inline-width"]),"border-block-start-style":makeTransform(d["border-block-start-style"]),"border-block-end-style":makeTransform(d["border-block-end-style"]),"border-inline-start-style":makeTransform(d["border-inline-start-style"]),"border-inline-end-style":makeTransform(d["border-inline-end-style"]),"border-block-style":makeTransform(d["border-block-style"]),"border-inline-style":makeTransform(d["border-inline-style"]),"border-block-start-color":makeTransform(d["border-block-start-color"]),"border-block-end-color":makeTransform(d["border-block-end-color"]),"border-inline-start-color":makeTransform(d["border-inline-start-color"]),"border-inline-end-color":makeTransform(d["border-inline-end-color"]),"border-block-color":makeTransform(d["border-block-color"]),"border-inline-color":makeTransform(d["border-inline-color"]),"border-block":makeTransform(d["border-block"]),"border-block-start":makeTransform(d["border-block-start"]),"border-block-end":makeTransform(d["border-block-end"]),"border-inline":makeTransform(d["border-inline"]),"border-inline-start":makeTransform(d["border-inline-start"]),"border-inline-end":makeTransform(d["border-inline-end"]),"border-start-start-radius":makeTransform(d["border-start-start-radius"]),"border-start-end-radius":makeTransform(d["border-start-end-radius"]),"border-end-start-radius":makeTransform(d["border-end-start-radius"]),"border-end-end-radius":makeTransform(d["border-end-end-radius"]),transition:(r,{result:e,postcss:n})=>{let o=[];try{o=transformTransition(r,n,d)}catch(n){return void r.warn(e,n instanceof Error?n.message:String(n))}o?.length&&(o.forEach((e=>{r.cloneBefore(e)})),r.remove())}}}};creator.postcss=!0;export{creator as default}; +import r from"postcss-value-parser";var e,n;!function(r){r.Block="block",r.Inline="inline"}(e||(e={})),function(r){r.Start="start",r.End="end"}(n||(n={}));const o={BlockStart:"block-start",BlockEnd:"block-end",InlineStart:"inline-start",InlineEnd:"inline-end"};var t,i;function directionFlowToAxes(r){switch(r){case t.TopToBottom:return[i.Top,i.Bottom];case t.BottomToTop:return[i.Bottom,i.Top];case t.RightToLeft:return[i.Right,i.Left];case t.LeftToRight:return[i.Left,i.Right]}}function cloneDeclaration(r,e,n){return r.parent&&r.parent.some((r=>"decl"==r.type&&r.prop===n&&r.value===e))?[]:[r.clone({value:e,prop:n})]}function transformTransition(e,n,o){const{prop:t,value:i}=e,l=r(i),a=[];let s=[];l.nodes.forEach((r=>{if("div"===r.type&&","===r.value)return a.push(s),void(s=[]);s.push(r)})),a.push(s);for(let r=0;r=0;n--){const o=JSON.parse(JSON.stringify(e));o[t].value=d[n].prop,a.splice(r+1,0,o)}a.splice(r,1),r++}}}const d=[];for(let r=0;r"space"!==r.type));if(n.length>2||0===n.length){const r=`[postcss-logical] Invalid number of values for ${e.prop}. Found ${n.length} values, expected 1 or 2.`;throw e.error(r)}let o,t;return 1===n.length?(o=r.stringify(n[0]),t=o):(o=r.stringify(n[0]),t=r.stringify(n[1])),[o,t]}function transformBorder(r,e){return n=>cloneDeclaration(n,n.value,`border-${e}-${r}`)}function transformBorderProperty(r,e){return n=>{const[o,t]=e,[i,l]=parseValueCouple(n);return[...cloneDeclaration(n,i,`border-${o}-${r}`),...cloneDeclaration(n,l,`border-${t}-${r}`)]}}function transformBorderShorthand(r){return e=>r.flatMap((r=>cloneDeclaration(e,e.value,`border-${r}`)))}function transformBorderRadius(r){return e=>{let n;switch(e.prop.toLowerCase()){case"border-start-start-radius":n=`border-${r.inlineIsHorizontal?`${r.block[0]}-${r.inline[0]}`:`${r.inline[0]}-${r.block[0]}`}-radius`;break;case"border-start-end-radius":n=`border-${r.inlineIsHorizontal?`${r.block[0]}-${r.inline[1]}`:`${r.inline[1]}-${r.block[0]}`}-radius`;break;case"border-end-start-radius":n=`border-${r.inlineIsHorizontal?`${r.block[1]}-${r.inline[0]}`:`${r.inline[0]}-${r.block[1]}`}-radius`;break;case"border-end-end-radius":n=`border-${r.inlineIsHorizontal?`${r.block[1]}-${r.inline[1]}`:`${r.inline[1]}-${r.block[1]}`}-radius`;break}return n?cloneDeclaration(e,e.value,n):[]}}function transformLogicalSize(r){return e=>{const{value:n}=e,o=r.inlineIsHorizontal?"width":"height",t=r.inlineIsHorizontal?"height":"width",i=e.prop.toLowerCase().replace("inline-size",o).replace("block-size",t);return cloneDeclaration(e,n,i)}}function transformOffset(r){return e=>cloneDeclaration(e,e.value,r)}function transformOffsetShorthand(r){return e=>{const[n,o]=r,[t,i]=parseValueCouple(e);return[...cloneDeclaration(e,t,n),...cloneDeclaration(e,i,o)]}}function transformSide(r,e){return n=>cloneDeclaration(n,n.value,`${r}-${e}`)}function transformSideShorthand(r,e){return n=>{const[o,t]=e,[i,l]=parseValueCouple(n);return[...cloneDeclaration(n,i,`${r}-${o}`),...cloneDeclaration(n,l,`${r}-${t}`)]}}function logicalToPhysical(r,e){const[n,t]=e.block,[i,l]=e.inline;switch(r){case o.BlockStart:return n;case o.BlockEnd:return t;case o.InlineStart:return i;case o.InlineEnd:return l;default:throw new Error("Unsupported logical direction")}}function doTransform(e,n,o){const{prop:t,value:i}=e,l=r(i);l.nodes.forEach((r=>{if("word"===r.type){const e=r.value.toLowerCase();n.includes(e)&&(r.value=logicalToPhysical(e,o))}}));const a=l.toString();return a!==i?cloneDeclaration(e,a,t):[]}function prepareTransforms(e,t,i,l,a){return{"caption-side":(d=e,r=>doTransform(r,Object.values(o),d)),"text-align":e.inlineIsHorizontal?(s=e.inline,e=>{const{prop:o,value:t}=e,i=r(t),[l,a]=s;i.nodes.forEach((r=>{if("word"===r.type){const e=r.value.toLowerCase();if(e===n.End)return void(r.value=a);if(e===n.Start)return void(r.value=l)}}));const d=i.toString();return d!==t?cloneDeclaration(e,d,o):[]}):null,"block-size":transformLogicalSize(e),"inline-size":transformLogicalSize(e),"min-block-size":transformLogicalSize(e),"max-block-size":transformLogicalSize(e),"min-inline-size":transformLogicalSize(e),"max-inline-size":transformLogicalSize(e),"margin-block-start":transformSide("margin",t),"margin-block-end":transformSide("margin",i),"margin-inline-start":transformSide("margin",l),"margin-inline-end":transformSide("margin",a),"margin-block":transformSideShorthand("margin",e.block),"margin-inline":transformSideShorthand("margin",e.inline),"inset-block":transformOffsetShorthand(e.block),"inset-block-start":transformOffset(t),"inset-block-end":transformOffset(i),"inset-inline":transformOffsetShorthand(e.inline),"inset-inline-start":transformOffset(l),"inset-inline-end":transformOffset(a),inset:e=>{const n=r(e.value).nodes.filter((r=>"space"!==r.type&&"comment"!==r.type));if(n.length>4){const r=`[postcss-logical] Invalid number of values for ${e.prop}. Found ${n.length} values, expected up to 4 values.`;throw e.error(r)}let o,t,i,l;if(1===n.length)o=r.stringify(n[0]),t=o,i=o,l=o;else if(2===n.length)o=r.stringify(n[0]),t=r.stringify(n[1]),i=o,l=t;else if(3===n.length)o=r.stringify(n[0]),t=r.stringify(n[1]),l=t,i=r.stringify(n[2]);else{if(4!==n.length)return[];o=r.stringify(n[0]),t=r.stringify(n[1]),i=r.stringify(n[2]),l=r.stringify(n[3])}return[...cloneDeclaration(e,o,"top"),...cloneDeclaration(e,t,"right"),...cloneDeclaration(e,i,"bottom"),...cloneDeclaration(e,l,"left")]},"padding-block-start":transformSide("padding",t),"padding-block-end":transformSide("padding",i),"padding-inline-start":transformSide("padding",l),"padding-inline-end":transformSide("padding",a),"padding-block":transformSideShorthand("padding",e.block),"padding-inline":transformSideShorthand("padding",e.inline),"border-block-start-width":transformBorder("width",t),"border-block-end-width":transformBorder("width",i),"border-inline-start-width":transformBorder("width",l),"border-inline-end-width":transformBorder("width",a),"border-block-width":transformBorderProperty("width",e.block),"border-inline-width":transformBorderProperty("width",e.inline),"border-block-start-style":transformBorder("style",t),"border-block-end-style":transformBorder("style",i),"border-inline-start-style":transformBorder("style",l),"border-inline-end-style":transformBorder("style",a),"border-block-style":transformBorderProperty("style",e.block),"border-inline-style":transformBorderProperty("style",e.inline),"border-block-start-color":transformBorder("color",t),"border-block-end-color":transformBorder("color",i),"border-inline-start-color":transformBorder("color",l),"border-inline-end-color":transformBorder("color",a),"border-block-color":transformBorderProperty("color",e.block),"border-inline-color":transformBorderProperty("color",e.inline),"border-block":transformBorderShorthand(e.block),"border-block-start":transformBorderShorthand([t]),"border-block-end":transformBorderShorthand([i]),"border-inline":transformBorderShorthand(e.inline),"border-inline-start":transformBorderShorthand([l]),"border-inline-end":transformBorderShorthand([a]),"border-start-start-radius":transformBorderRadius(e),"border-start-end-radius":transformBorderRadius(e),"border-end-start-radius":transformBorderRadius(e),"border-end-end-radius":transformBorderRadius(e)};var s,d}!function(r){r.TopToBottom="top-to-bottom",r.BottomToTop="bottom-to-top",r.RightToLeft="right-to-left",r.LeftToRight="left-to-right"}(t||(t={})),function(r){r.Top="top",r.Right="right",r.Bottom="bottom",r.Left="left"}(i||(i={}));const creator=r=>{const e=Object.assign({blockDirection:t.TopToBottom,inlineDirection:t.LeftToRight},r),n=Object.values(t);if(!n.includes(e.blockDirection))throw new Error(`[postcss-logical] "blockDirection" must be one of ${n.join(", ")}`);if(!n.includes(e.inlineDirection))throw new Error(`[postcss-logical] "inlineDirection" must be one of ${n.join(", ")}`);const[o,l]=directionFlowToAxes(e.blockDirection),[a,s]=directionFlowToAxes(e.inlineDirection);if(!Object.values(i).every((r=>[o,l,a,s].includes(r))))throw new Error('[postcss-logical] "blockDirection" and "inlineDirection" must be on separate axes');const makeTransform=r=>(e,{result:n})=>{if(!r)return;let o=[];try{o=r(e)}catch(r){return void e.warn(n,r instanceof Error?r.message:String(r))}o?.length&&(o.forEach((r=>{e.cloneBefore(r)})),e.remove())},d=prepareTransforms({block:[o,l],inline:[a,s],inlineIsHorizontal:[t.LeftToRight,t.RightToLeft].includes(e.inlineDirection)},o,l,a,s);return{postcssPlugin:"postcss-logical",Declaration:{"caption-side":makeTransform(d["caption-side"]),"text-align":makeTransform(d["text-align"]),"block-size":makeTransform(d["block-size"]),"inline-size":makeTransform(d["inline-size"]),"min-block-size":makeTransform(d["min-block-size"]),"max-block-size":makeTransform(d["max-block-size"]),"min-inline-size":makeTransform(d["min-inline-size"]),"max-inline-size":makeTransform(d["max-inline-size"]),"margin-block-start":makeTransform(d["margin-block-start"]),"margin-block-end":makeTransform(d["margin-block-end"]),"margin-inline-start":makeTransform(d["margin-inline-start"]),"margin-inline-end":makeTransform(d["margin-inline-end"]),"margin-block":makeTransform(d["margin-block"]),"margin-inline":makeTransform(d["margin-inline"]),"inset-block":makeTransform(d["inset-block"]),"inset-block-start":makeTransform(d["inset-block-start"]),"inset-block-end":makeTransform(d["inset-block-end"]),"inset-inline":makeTransform(d["inset-inline"]),"inset-inline-start":makeTransform(d["inset-inline-start"]),"inset-inline-end":makeTransform(d["inset-inline-end"]),inset:makeTransform(d.inset),"padding-block-start":makeTransform(d["padding-block-start"]),"padding-block-end":makeTransform(d["padding-block-end"]),"padding-inline-start":makeTransform(d["padding-inline-start"]),"padding-inline-end":makeTransform(d["padding-inline-end"]),"padding-block":makeTransform(d["padding-block"]),"padding-inline":makeTransform(d["padding-inline"]),"border-block-start-width":makeTransform(d["border-block-start-width"]),"border-block-end-width":makeTransform(d["border-block-end-width"]),"border-inline-start-width":makeTransform(d["border-inline-start-width"]),"border-inline-end-width":makeTransform(d["border-inline-end-width"]),"border-block-width":makeTransform(d["border-block-width"]),"border-inline-width":makeTransform(d["border-inline-width"]),"border-block-start-style":makeTransform(d["border-block-start-style"]),"border-block-end-style":makeTransform(d["border-block-end-style"]),"border-inline-start-style":makeTransform(d["border-inline-start-style"]),"border-inline-end-style":makeTransform(d["border-inline-end-style"]),"border-block-style":makeTransform(d["border-block-style"]),"border-inline-style":makeTransform(d["border-inline-style"]),"border-block-start-color":makeTransform(d["border-block-start-color"]),"border-block-end-color":makeTransform(d["border-block-end-color"]),"border-inline-start-color":makeTransform(d["border-inline-start-color"]),"border-inline-end-color":makeTransform(d["border-inline-end-color"]),"border-block-color":makeTransform(d["border-block-color"]),"border-inline-color":makeTransform(d["border-inline-color"]),"border-block":makeTransform(d["border-block"]),"border-block-start":makeTransform(d["border-block-start"]),"border-block-end":makeTransform(d["border-block-end"]),"border-inline":makeTransform(d["border-inline"]),"border-inline-start":makeTransform(d["border-inline-start"]),"border-inline-end":makeTransform(d["border-inline-end"]),"border-start-start-radius":makeTransform(d["border-start-start-radius"]),"border-start-end-radius":makeTransform(d["border-start-end-radius"]),"border-end-start-radius":makeTransform(d["border-end-start-radius"]),"border-end-end-radius":makeTransform(d["border-end-end-radius"]),transition:(r,{result:e,postcss:n})=>{let o=[];try{o=transformTransition(r,n,d)}catch(n){return void r.warn(e,n instanceof Error?n.message:String(n))}o?.length&&(o.forEach((e=>{r.cloneBefore(e)})),r.remove())}}}};creator.postcss=!0;export{creator as default}; diff --git a/plugins/postcss-logical/src/lib/transform-text-align.ts b/plugins/postcss-logical/src/lib/transform-text-align.ts index 98a84157c..1728f29bf 100644 --- a/plugins/postcss-logical/src/lib/transform-text-align.ts +++ b/plugins/postcss-logical/src/lib/transform-text-align.ts @@ -13,7 +13,7 @@ export function transformTextAlign( valueAST.nodes.forEach((node) => { if (node.type === 'word') { - const valueCandidate = node.value.toLowerCase(); + const valueCandidate = node.value.toLowerCase() as DirectionValue; if (valueCandidate === DirectionValue.End) { node.value = end; @@ -22,6 +22,7 @@ export function transformTextAlign( if (valueCandidate === DirectionValue.Start) { node.value = start; + return; } } }); diff --git a/plugins/postcss-logical/src/lib/transform-transition.ts b/plugins/postcss-logical/src/lib/transform-transition.ts index 3880c1f32..c3998450c 100644 --- a/plugins/postcss-logical/src/lib/transform-transition.ts +++ b/plugins/postcss-logical/src/lib/transform-transition.ts @@ -46,7 +46,7 @@ export function transformTransition(declaration: Declaration, postcss: Postcss, } for (let k = transformedDeclarations.length - 1; k >= 0; k--) { - const clone = JSON.parse(JSON.stringify(chunk)); + const clone: Array = JSON.parse(JSON.stringify(chunk)) as Array; const clonedNode = clone[j]; clonedNode.value = transformedDeclarations[k].prop; diff --git a/plugins/postcss-media-minmax/src/transform.ts b/plugins/postcss-media-minmax/src/transform.ts index 6231d1462..ddd49c0b1 100644 --- a/plugins/postcss-media-minmax/src/transform.ts +++ b/plugins/postcss-media-minmax/src/transform.ts @@ -52,7 +52,7 @@ export function transform(mediaQueries: Array): string { return; } - const grandParent: unknown | MediaInParens = ancestry.get(parent); + const grandParent: unknown = ancestry.get(parent); if (!isMediaInParens(grandParent)) { return; } diff --git a/plugins/postcss-media-queries-aspect-ratio-number-values/src/transform-media-feature-value.ts b/plugins/postcss-media-queries-aspect-ratio-number-values/src/transform-media-feature-value.ts index 0c6767702..c98c1f075 100644 --- a/plugins/postcss-media-queries-aspect-ratio-number-values/src/transform-media-feature-value.ts +++ b/plugins/postcss-media-queries-aspect-ratio-number-values/src/transform-media-feature-value.ts @@ -260,7 +260,6 @@ function greatestCommonDivisor(a: number, b: number): number { [a, b] = [b, a]; } - // eslint-disable-next-line no-constant-condition while (true) { if (b == 0) { return a; diff --git a/plugins/postcss-minify/src/index.ts b/plugins/postcss-minify/src/index.ts index 3fd3f00cc..f354d6803 100644 --- a/plugins/postcss-minify/src/index.ts +++ b/plugins/postcss-minify/src/index.ts @@ -7,13 +7,14 @@ const HAS_SOURCE_MAP_REGEX = /sourceMappingURL/i; const HAS_WHITESPACE_OR_COMMENTS_REGEX = /\s|\/\*/; const IS_LAYER_REGEX = /^layer$/i; -function minify(cache: Map, x: string | undefined): string | undefined { +function minify(cache: Map, x: string): string { if (!x) { return x; } if (cache.has(x)) { - return cache.get(x); + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + return cache.get(x)!; } const y = x.trim(); @@ -123,7 +124,7 @@ const creator: PluginCreator = () => { setSemicolon(node); - node.params = minify(cache, node.params)!; + node.params = minify(cache, node.params); return; @@ -140,7 +141,7 @@ const creator: PluginCreator = () => { setSemicolon(node); - node.selector = minify(cache, node.selector)!; + node.selector = minify(cache, node.selector); return; @@ -159,7 +160,7 @@ const creator: PluginCreator = () => { node.raws.important = node.important ? '!important' : ''; node.raws.value = undefined; - node.value = minify(cache, node.value)!; + node.value = minify(cache, node.value); return; diff --git a/plugins/postcss-nested-calc/dist/index.cjs b/plugins/postcss-nested-calc/dist/index.cjs index 013b648ec..3bcbf3d1a 100644 --- a/plugins/postcss-nested-calc/dist/index.cjs +++ b/plugins/postcss-nested-calc/dist/index.cjs @@ -1 +1 @@ -"use strict";var e=require("postcss-value-parser"),t=require("@csstools/utilities");const r=/calc\(/gi;const creator=s=>{const a=Object.assign({preserve:!0},s);return{postcssPlugin:"postcss-nested-calc",Declaration(s,{result:o}){if((s.value.match(r)||[]).length<2)return;if(s.variable)return;if(t.hasFallback(s))return;const c=s.value;let l;try{l=e(c)}catch(e){return void s.warn(o,`Failed to parse value '${c}'. Leaving the original value intact.`)}if(void 0===l)return;e.walk(l.nodes,(t=>{t.type&&"function"===t.type&&"calc"===t.value.toLowerCase()&&e.walk(t.nodes,(e=>{if(e.type&&"function"===e.type)return"calc"===e.value.toLowerCase()&&void(e.value="")}))}),!0);const n=String(l);n!==c&&(s.cloneBefore({value:n}),a.preserve||s.remove())}}};creator.postcss=!0,module.exports=creator; +"use strict";var e=require("postcss-value-parser"),t=require("@csstools/utilities");const r=/calc\(/gi;const creator=s=>{const a=Object.assign({preserve:!0},s);return{postcssPlugin:"postcss-nested-calc",Declaration(s,{result:o}){if((s.value.match(r)||[]).length<2)return;if(s.variable)return;if(t.hasFallback(s))return;const c=s.value;let l;try{l=e(c)}catch{return void s.warn(o,`Failed to parse value '${c}'. Leaving the original value intact.`)}if(void 0===l)return;e.walk(l.nodes,(t=>{t.type&&"function"===t.type&&"calc"===t.value.toLowerCase()&&e.walk(t.nodes,(e=>{if(e.type&&"function"===e.type)return"calc"===e.value.toLowerCase()&&void(e.value="")}))}),!0);const n=String(l);n!==c&&(s.cloneBefore({value:n}),a.preserve||s.remove())}}};creator.postcss=!0,module.exports=creator; diff --git a/plugins/postcss-nested-calc/dist/index.mjs b/plugins/postcss-nested-calc/dist/index.mjs index c6bc9d565..917b34694 100644 --- a/plugins/postcss-nested-calc/dist/index.mjs +++ b/plugins/postcss-nested-calc/dist/index.mjs @@ -1 +1 @@ -import e from"postcss-value-parser";import{hasFallback as t}from"@csstools/utilities";const r=/calc\(/gi;const creator=s=>{const a=Object.assign({preserve:!0},s);return{postcssPlugin:"postcss-nested-calc",Declaration(s,{result:o}){if((s.value.match(r)||[]).length<2)return;if(s.variable)return;if(t(s))return;const n=s.value;let c;try{c=e(n)}catch(e){return void s.warn(o,`Failed to parse value '${n}'. Leaving the original value intact.`)}if(void 0===c)return;e.walk(c.nodes,(t=>{t.type&&"function"===t.type&&"calc"===t.value.toLowerCase()&&e.walk(t.nodes,(e=>{if(e.type&&"function"===e.type)return"calc"===e.value.toLowerCase()&&void(e.value="")}))}),!0);const l=String(c);l!==n&&(s.cloneBefore({value:l}),a.preserve||s.remove())}}};creator.postcss=!0;export{creator as default}; +import e from"postcss-value-parser";import{hasFallback as t}from"@csstools/utilities";const r=/calc\(/gi;const creator=s=>{const a=Object.assign({preserve:!0},s);return{postcssPlugin:"postcss-nested-calc",Declaration(s,{result:o}){if((s.value.match(r)||[]).length<2)return;if(s.variable)return;if(t(s))return;const n=s.value;let c;try{c=e(n)}catch{return void s.warn(o,`Failed to parse value '${n}'. Leaving the original value intact.`)}if(void 0===c)return;e.walk(c.nodes,(t=>{t.type&&"function"===t.type&&"calc"===t.value.toLowerCase()&&e.walk(t.nodes,(e=>{if(e.type&&"function"===e.type)return"calc"===e.value.toLowerCase()&&void(e.value="")}))}),!0);const l=String(c);l!==n&&(s.cloneBefore({value:l}),a.preserve||s.remove())}}};creator.postcss=!0;export{creator as default}; diff --git a/plugins/postcss-nested-calc/src/index.ts b/plugins/postcss-nested-calc/src/index.ts index 8b833358e..fe0f690ea 100644 --- a/plugins/postcss-nested-calc/src/index.ts +++ b/plugins/postcss-nested-calc/src/index.ts @@ -43,7 +43,7 @@ const creator: PluginCreator = (opts?: pluginOptions) => { try { valueAST = valueParser(originalValue); - } catch (_) { + } catch { decl.warn( result, `Failed to parse value '${originalValue}'. Leaving the original value intact.`, diff --git a/plugins/postcss-nesting/dist/index.cjs b/plugins/postcss-nesting/dist/index.cjs index f603f4e9e..625a96ccd 100644 --- a/plugins/postcss-nesting/dist/index.cjs +++ b/plugins/postcss-nesting/dist/index.cjs @@ -1 +1 @@ -"use strict";var e=require("postcss-selector-parser"),t=require("@csstools/selector-specificity"),n=require("@csstools/selector-resolve-nested");const r=e.pseudo({value:":is"});function sortCompoundSelectorsInsideComplexSelector(t){if(!t||!t.nodes)return;const n=[];let o=[];for(let s=0;s"tag"===e.type))){const n=r.clone({}),o=t.nodes[s];o.replaceWith(n),n.append(e.selector({nodes:[o],value:void 0}))}o.push(t.nodes[s])}else n.push(o),n.push([t.nodes[s]]),o=[];n.push(o);const s=[];for(let e=0;e"selector"===e.type&&"selector"===t.type&&e.nodes.length&&t.nodes.length?selectorTypeOrder(e.nodes[0])-selectorTypeOrder(t.nodes[0]):"selector"===e.type&&e.nodes.length?selectorTypeOrder(e.nodes[0])-selectorTypeOrder(t):"selector"===t.type&&t.nodes.length?selectorTypeOrder(e)-selectorTypeOrder(t.nodes[0]):selectorTypeOrder(e)-selectorTypeOrder(t)));for(let e=0;e=0;e--)s[e].remove(),t.prepend(s[e])}function selectorTypeOrder(t){return e.isPseudoElement(t)?o.pseudoElement:o[t.type]}const o={universal:0,tag:1,pseudoElement:2,id:3,class:4,attribute:5,pseudo:6,selector:7,string:8,root:9,comment:10};function isAtRule(e){return e&&"atrule"===e.type}function isNestRule(e){return e&&isAtRule(e)&&"nest"===e.name}function isRule(e){return e&&"rule"===e.type}function ampersandToScope$1(t,n){let r,o=t.parent;for(;o;){if("rule"===o.type)return;if(isAtRule(o)&&"scope"===o.name)return;o=o.parent}try{r=e().astSync(t.selector)}catch(e){return void t.warn(n,`Failed to parse selector : "${t.selector}" with message: "${e instanceof Error?e.message:e}"`)}r&&(r.walkNesting((t=>{const n=t.parent;t.replaceWith(e.pseudo({value:":scope"})),n&&sortCompoundSelectorsInsideComplexSelector(n)})),t.selector=r.toString())}function cleanupParent(e){if(!e.nodes.length)return void e.remove();const t=e.nodes.filter((e=>"comment"===e.type));t.length===e.nodes.length&&e.replaceWith(...t)}function groupDeclarations(e){const t=[],n=[];e.each((e=>{if(isDeclarationLike(e,n.length>0))t.push(e);else{if("comment"===e.type){let r=e.next();for(;r&&"comment"===r.type;)r=r.next();if(isDeclarationLike(r,n.length>0))return void t.push(e)}n.push(e)}})),e.removeAll(),t.forEach((t=>{e.append(t)})),n.forEach((t=>{e.append(t)}))}function isDeclarationLike(e,t){return!!e&&("decl"===e.type||"atrule"===e.type&&"mixin"===e.name.toLowerCase()&&!t)}function comma(e){const t=[];let n="",r=!1,o=0,s=!1,i=!1;for(const l of e)i?i=!1:"\\"===l?i=!0:s?l===s&&(s=!1):'"'===l||"'"===l?s=l:"("===l?o+=1:")"===l?o>0&&(o-=1):0===o&&","===l&&(r=!0),r?(""!==n&&t.push(n.trim()),n="",r=!1):n+=l;return t.push(n.trim()),t}function shiftNodesBeforeParent(e,t){const n=t.index(e);if(n){const e=t.cloneBefore().removeAll().append(t.nodes.slice(0,n));e.raws.semicolon=!0,cleanupParent(e)}t.before(e),t.raws.semicolon=!0}var s=["container","document","media","supports","layer","starting-style"];function transformAtruleWithinAtrule(e,t){var n,r;groupDeclarations(t),shiftNodesBeforeParent(e,t),e.params=(n=t.params,r=e.params,comma(n).map((e=>comma(r).map((t=>`${e} and ${t}`)).join(", "))).join(", ")),cleanupParent(t)}function isAtruleWithinAtrule(e,t){return s.includes(e.name)&&e.name===t.name}function atruleWithinRule$1(e,t,n,r,o){if(groupDeclarations(t),shiftNodesBeforeParent(e,t),e.nodes){const s=t.clone().removeAll().append(e.nodes);e.append(s),cleanupParent(t),r(s,n,o)}else cleanupParent(t)}function isAtruleWithinRule$1(e){return s.includes(e.name)}function combinationsWithSizeN(e,t){if(t<2)throw new Error("n must be greater than 1");if(e.length<2)throw new Error("s must be greater than 1");if(Math.pow(e.length,t)>1e4)throw new Error("Too many combinations when trying to resolve a nested selector with lists, reduce the complexity of your selectors");const n=[];for(let e=0;e=0;s--){let t=n[s];if(t>=e.length){if(t=0,n[s]=0,0===s)return r;n[s-1]+=1}o[s]=e[t]}r.push(o),n[n.length-1]++}}function nodesAreEquallySpecific(n){const r=n.map((t=>e().astSync(t))).map((e=>t.selectorSpecificity(e))),o=r[0];for(let e=1;ee().astSync(t))):[e().astSync(`:is(${t.join(",")})`)];const s=[];for(let t=0;t{"nesting"===e.type&&(n=!0)}));const r=t.nodes[0];let o=!1;r.each((e=>"combinator"===e.type&&(o=!0,!1))),n?o&&r.insertBefore(r.at(0),e.nesting({})):(r.insertBefore(r.at(0),e.combinator({value:" "})),r.insertBefore(r.at(0),e.nesting({}))),l=t.toString()}let c=[],a=0;if(e().astSync(l).walkNesting((()=>{a++})),a>1&&o.length>1)c=combinationsWithSizeN(o,a),i=c.length;else{i=o.length;for(let e=0;e{if("nesting"!==o.type)return;let s=c[t][n];n++,"root"===s.type&&1===s.nodes.length&&(s=s.nodes[0]);const i=e().astSync(`:is(${s.toString()})`),l=isSimpleSelector(s.nodes[0]),a=isCompoundSelector(s.nodes[0]),u=isSimpleSelector(o),p=isCompoundSelector(o);if(l&&u)return void o.replaceWith(s.clone());if((l||a)&&(u||p)){const e=o.parent;return l&&"selector"===s.type?o.replaceWith(s.clone().nodes[0]):o.replaceWith(...s.clone().nodes),void(e&&e.nodes.length>1&&sortCompoundSelectorsInsideComplexSelector(e))}if(l){const e=o.parent;return o.replaceWith(s.clone().nodes[0]),void(e&&sortCompoundSelectorsInsideComplexSelector(e))}if(a){const e=o.parent;return o.replaceWith(...s.clone().nodes),void(e&&sortCompoundSelectorsInsideComplexSelector(e))}if(nestingIsFirstAndOnlyInSelectorWithEitherSpaceOrChildCombinator(o)){const e=o.parent;return o.replaceWith(...s.clone().nodes),void(e&&sortCompoundSelectorsInsideComplexSelector(e))}if(nestingIsNotInsideCompoundSelector(o)){const e=o.parent;return o.replaceWith(...s.clone().nodes),void(e&&sortCompoundSelectorsInsideComplexSelector(e))}const d=o.parent;r.noIsPseudoSelector?o.replaceWith(...s.clone().nodes):o.replaceWith(...i.clone({}).nodes),d&&sortCompoundSelectorsInsideComplexSelector(d)})),s.push(o.toString())}}return s}function isSimpleSelector(e){return"combinator"!==e.type&&!(e.parent&&e.parent.nodes.length>1)}function isCompoundSelector(e,t=null){if(isSimpleSelector(e))return!1;if(!e.parent)return!1;if(!!e.parent.nodes.find((e=>"combinator"===e.type)))return!1;return!(!!e.parent.nodes.find((e=>"nesting"===e.type))&&t&&!isCompoundSelector(t))}function nestingIsFirstAndOnlyInSelectorWithEitherSpaceOrChildCombinator(e){if(!e.parent)return!1;if(0!==e.parent.nodes.indexOf(e))return!1;for(let t=1;t"!==e.parent.nodes[t].value)return!1;return!0}function nestingIsNotInsideCompoundSelector(e){if(isSimpleSelector(e))return!0;if(!e.parent)return!1;for(let t=0;te.split("&").length>=2&&-1===e.indexOf("|")))}function transformRuleWithinRule$1(e,t,n,r){let o=[];try{o=mergeSelectors$1(t.selectors,e.selectors,r)}catch(r){return void e.warn(n,`Failed to parse selectors : "${t.selector}" / "${e.selector}" with message: "${r instanceof Error?r.message:r}"`)}if(!o.length)return;groupDeclarations(t),shiftNodesBeforeParent(e,t),e.selectors=o;"rule"===e.type&&"rule"===t.type&&e.selector===t.selector&&e.append(...t.nodes),cleanupParent(t)}function isValidRuleWithinRule$1(e){return e.selectors.every((e=>-1===e.indexOf("|")))}function walk$1(e,t,n){e.each((r=>{const o=r.parent;isNestRule(r)&&!n.silenceAtNestWarning&&e.warn(t,`\`@nest\` was removed from the CSS Nesting specification and will be removed from PostCSS Nesting in the next major version.\nChange \`@nest ${r.params} {}\` to \`${r.params} {}\` to migrate to the latest standard.`),isRule(r)&&isRule(o)&&isValidRuleWithinRule$1(r)?transformRuleWithinRule$1(r,o,t,n):isNestRule(r)&&isRule(o)&&isValidNestRuleWithinRule(r)?transformNestRuleWithinRule(r,o,t,walk$1,n):isAtRule(r)&&isRule(o)&&isAtruleWithinRule$1(r)?atruleWithinRule$1(r,o,t,walk$1,n):isAtRule(r)&&isAtRule(o)&&isAtruleWithinAtrule(r,o)&&transformAtruleWithinAtrule(r,o),"nodes"in r&&r.nodes.length&&walk$1(r,t,n)}))}const creator$2=e=>{const t=Object.assign({noIsPseudoSelector:!1,silenceAtNestWarning:!1},e);return{postcssPlugin:"postcss-nesting",Rule(e,{result:n}){walk$1(e,n,t),e.selector.includes("&")&&ersandToScope$1(e,n)}}};creator$2.postcss=!0;const i=e();function mergeSelectors(e,t,r,o){let s;try{s=n.resolveNestedSelector(i.astSync(t),i.astSync(r))}catch(n){return e.warn(o,`Failed to parse selectors : "${r}" / "${t}" with message: "${n instanceof Error?n.message:n}"`),!1}return!!s&&s.toString()}function ampersandToScope(t,n){{let r=t.parent;for(;r;){if("rule"===r.type)return;if(isAtRule(r)&&"scope"===r.name)return;r=r.parent}try{let n=!1;if(e().astSync(t.selector).walkNesting((()=>(n=!0,!1))),!n)return}catch(e){return void t.warn(n,`Failed to parse selector : "${t.selector}" with message: "${e instanceof Error?e.message:e}"`)}}const r=mergeSelectors(t,t.selector,":scope",n);r&&(t.selector=r)}function atruleWithinRule(e,t,n,r){if(shiftNodesBeforeParent(e,t),e.nodes){const o=t.clone().removeAll().append(e.nodes);e.append(o),cleanupParent(t),r(o,n)}else cleanupParent(t)}function isAtruleWithinRule(e){return s.includes(e.name)}function transformRuleWithinRule(e,t,n){const r=mergeSelectors(e,e.selector,t.selector,n);if(!r)return;shiftNodesBeforeParent(e,t),e.selector=r;"rule"===e.type&&"rule"===t.type&&e.selector===t.selector&&e.append(...t.nodes),cleanupParent(t)}function isValidRuleWithinRule(e){return e.selectors.every((e=>-1===e.indexOf("|")))}function walk(e,t){e.each((e=>{const n=e.parent;isRule(e)&&isRule(n)&&isValidRuleWithinRule(e)?transformRuleWithinRule(e,n,t):isAtRule(e)&&isRule(n)&&isAtruleWithinRule(e)&&atruleWithinRule(e,n,t,walk),"nodes"in e&&e.nodes.length&&walk(e,t)}))}const creator$1=()=>({postcssPlugin:"postcss-nesting",Rule(e,{result:t}){walk(e,t),e.selector.includes("&")&&ersandToScope(e,t)},AtRule:{nest(e){throw e.error(`\`@nest\` was removed from the CSS Nesting specification and will be removed from PostCSS Nesting in the next major version.\nChange \`@nest ${e.params} {}\` to \`${e.params} {}\` to migrate to the latest standard.`)}}});creator$1.postcss=!0;const creator=e=>{const t=Object.assign({edition:"2021"},e);switch(t.edition){case"2021":return creator$2(e);case"2024-02":return creator$1();default:throw new Error(`Invalid edition: ${t.edition}`)}};creator.postcss=!0,module.exports=creator; +"use strict";var e=require("postcss-selector-parser"),t=require("@csstools/selector-specificity"),n=require("@csstools/selector-resolve-nested");const r=e.pseudo({value:":is"});function sortCompoundSelectorsInsideComplexSelector(t){if(!t||!t.nodes)return;const n=[];let o=[];for(let s=0;s"tag"===e.type))){const n=r.clone({}),o=t.nodes[s];o.replaceWith(n),n.append(e.selector({nodes:[o],value:void 0}))}o.push(t.nodes[s])}else n.push(o),n.push([t.nodes[s]]),o=[];n.push(o);const s=[];for(let e=0;e"selector"===e.type&&"selector"===t.type&&e.nodes.length&&t.nodes.length?selectorTypeOrder(e.nodes[0])-selectorTypeOrder(t.nodes[0]):"selector"===e.type&&e.nodes.length?selectorTypeOrder(e.nodes[0])-selectorTypeOrder(t):"selector"===t.type&&t.nodes.length?selectorTypeOrder(e)-selectorTypeOrder(t.nodes[0]):selectorTypeOrder(e)-selectorTypeOrder(t)));for(let e=0;e=0;e--)s[e].remove(),t.prepend(s[e])}function selectorTypeOrder(t){return e.isPseudoElement(t)?o.pseudoElement:o[t.type]}const o={universal:0,tag:1,pseudoElement:2,id:3,class:4,attribute:5,pseudo:6,selector:7,string:8,root:9,comment:10};function isAtRule(e){return e&&"atrule"===e.type}function isNestRule(e){return e&&isAtRule(e)&&"nest"===e.name}function isRule(e){return e&&"rule"===e.type}function ampersandToScope$1(t,n){let r,o=t.parent;for(;o;){if("rule"===o.type)return;if(isAtRule(o)&&"scope"===o.name)return;o=o.parent}try{r=e().astSync(t.selector)}catch(e){return void t.warn(n,`Failed to parse selector : "${t.selector}" with message: "${e instanceof Error?e.message:e}"`)}r&&(r.walkNesting((t=>{const n=t.parent;t.replaceWith(e.pseudo({value:":scope"})),n&&sortCompoundSelectorsInsideComplexSelector(n)})),t.selector=r.toString())}function cleanupParent(e){if(!e.nodes.length)return void e.remove();const t=e.nodes.filter((e=>"comment"===e.type));t.length===e.nodes.length&&e.replaceWith(...t)}function groupDeclarations(e){const t=[],n=[];e.each((e=>{if(isDeclarationLike(e,n.length>0))t.push(e);else{if("comment"===e.type){let r=e.next();for(;r&&"comment"===r.type;)r=r.next();if(isDeclarationLike(r,n.length>0))return void t.push(e)}n.push(e)}})),e.removeAll(),t.forEach((t=>{e.append(t)})),n.forEach((t=>{e.append(t)}))}function isDeclarationLike(e,t){return!!e&&("decl"===e.type||"atrule"===e.type&&"mixin"===e.name.toLowerCase()&&!t)}function comma(e){const t=[];let n="",r=!1,o=0,s=!1,i=!1;for(const l of e)i?i=!1:"\\"===l?i=!0:s?l===s&&(s=!1):'"'===l||"'"===l?s=l:"("===l?o+=1:")"===l?o>0&&(o-=1):0===o&&","===l&&(r=!0),r?(""!==n&&t.push(n.trim()),n="",r=!1):n+=l;return t.push(n.trim()),t}function shiftNodesBeforeParent(e,t){const n=t.index(e);if(n){const e=t.cloneBefore().removeAll().append(t.nodes.slice(0,n));e.raws.semicolon=!0,cleanupParent(e)}t.before(e),t.raws.semicolon=!0}var s=["container","document","media","supports","layer","starting-style"];function transformAtruleWithinAtrule(e,t){var n,r;groupDeclarations(t),shiftNodesBeforeParent(e,t),e.params=(n=t.params,r=e.params,comma(n).map((e=>comma(r).map((t=>`${e} and ${t}`)).join(", "))).join(", ")),cleanupParent(t)}function isAtruleWithinAtrule(e,t){return s.includes(e.name)&&e.name===t.name}function atruleWithinRule$1(e,t,n,r,o){if(groupDeclarations(t),shiftNodesBeforeParent(e,t),e.nodes){const s=t.clone().removeAll().append(e.nodes);e.append(s),cleanupParent(t),r(s,n,o)}else cleanupParent(t)}function isAtruleWithinRule$1(e){return s.includes(e.name)}function combinationsWithSizeN(e,t){if(t<2)throw new Error("n must be greater than 1");if(e.length<2)throw new Error("s must be greater than 1");if(Math.pow(e.length,t)>1e4)throw new Error("Too many combinations when trying to resolve a nested selector with lists, reduce the complexity of your selectors");const n=[];for(let e=0;e=0;s--){let t=n[s];if(t>=e.length){if(t=0,n[s]=0,0===s)return r;n[s-1]+=1}o[s]=e[t].clone()}r.push(o),n[n.length-1]++}}function nodesAreEquallySpecific(n){const r=n.map((t=>e().astSync(t))).map((e=>t.selectorSpecificity(e))),o=r[0];for(let e=1;ee().astSync(t))):[e().astSync(`:is(${t.join(",")})`)];const s=[];for(let t=0;t{"nesting"===e.type&&(n=!0)}));const r=t.nodes[0];let o=!1;r.each((e=>"combinator"===e.type&&(o=!0,!1))),n?o&&r.insertBefore(r.at(0),e.nesting()):(r.insertBefore(r.at(0),e.combinator({value:" "})),r.insertBefore(r.at(0),e.nesting())),l=t.toString()}let c=[],a=0;if(e().astSync(l).walkNesting((()=>{a++})),a>1&&o.length>1)c=combinationsWithSizeN(o,a),i=c.length;else{i=o.length;for(let e=0;e{if("nesting"!==o.type)return;let s=c[t][n];n++,"root"===s.type&&1===s.nodes.length&&(s=s.nodes[0]);const i=e().astSync(`:is(${s.toString()})`),l=isSimpleSelector(s.nodes[0]),a=isCompoundSelector(s.nodes[0]),u=isSimpleSelector(o),p=isCompoundSelector(o);if(l&&u)return void o.replaceWith(s.clone());if((l||a)&&(u||p)){const e=o.parent;return l&&"selector"===s.type?o.replaceWith(s.clone().nodes[0]):o.replaceWith(...s.clone().nodes),void(e&&e.nodes.length>1&&sortCompoundSelectorsInsideComplexSelector(e))}if(l){const e=o.parent;return o.replaceWith(s.clone().nodes[0]),void(e&&sortCompoundSelectorsInsideComplexSelector(e))}if(a){const e=o.parent;return o.replaceWith(...s.clone().nodes),void(e&&sortCompoundSelectorsInsideComplexSelector(e))}if(nestingIsFirstAndOnlyInSelectorWithEitherSpaceOrChildCombinator(o)){const e=o.parent;return o.replaceWith(...s.clone().nodes),void(e&&sortCompoundSelectorsInsideComplexSelector(e))}if(nestingIsNotInsideCompoundSelector(o)){const e=o.parent;return o.replaceWith(...s.clone().nodes),void(e&&sortCompoundSelectorsInsideComplexSelector(e))}const d=o.parent;r.noIsPseudoSelector?o.replaceWith(...s.clone().nodes):o.replaceWith(...i.clone({}).nodes),d&&sortCompoundSelectorsInsideComplexSelector(d)})),s.push(o.toString())}}return s}function isSimpleSelector(e){return"combinator"!==e.type&&!(e.parent&&e.parent.nodes.length>1)}function isCompoundSelector(e,t=null){if(isSimpleSelector(e))return!1;if(!e.parent)return!1;if(!!e.parent.nodes.find((e=>"combinator"===e.type)))return!1;return!(!!e.parent.nodes.find((e=>"nesting"===e.type))&&t&&!isCompoundSelector(t))}function nestingIsFirstAndOnlyInSelectorWithEitherSpaceOrChildCombinator(e){if(!e.parent)return!1;if(0!==e.parent.nodes.indexOf(e))return!1;for(let t=1;t"!==e.parent.nodes[t].value)return!1;return!0}function nestingIsNotInsideCompoundSelector(e){if(isSimpleSelector(e))return!0;if(!e.parent)return!1;for(let t=0;te.split("&").length>=2&&-1===e.indexOf("|")))}function transformRuleWithinRule$1(e,t,n,r){let o=[];try{o=mergeSelectors$1(t.selectors,e.selectors,r)}catch(r){return void e.warn(n,`Failed to parse selectors : "${t.selector}" / "${e.selector}" with message: "${r instanceof Error?r.message:r}"`)}if(!o.length)return;groupDeclarations(t),shiftNodesBeforeParent(e,t),e.selectors=o;"rule"===e.type&&"rule"===t.type&&e.selector===t.selector&&e.append(...t.nodes),cleanupParent(t)}function isValidRuleWithinRule$1(e){return e.selectors.every((e=>-1===e.indexOf("|")))}function walk$1(e,t,n){e.each((r=>{const o=r.parent;isNestRule(r)&&!n.silenceAtNestWarning&&e.warn(t,`\`@nest\` was removed from the CSS Nesting specification and will be removed from PostCSS Nesting in the next major version.\nChange \`@nest ${r.params} {}\` to \`${r.params} {}\` to migrate to the latest standard.`),isRule(r)&&isRule(o)&&isValidRuleWithinRule$1(r)?transformRuleWithinRule$1(r,o,t,n):isNestRule(r)&&isRule(o)&&isValidNestRuleWithinRule(r)?transformNestRuleWithinRule(r,o,t,walk$1,n):isAtRule(r)&&isRule(o)&&isAtruleWithinRule$1(r)?atruleWithinRule$1(r,o,t,walk$1,n):isAtRule(r)&&isAtRule(o)&&isAtruleWithinAtrule(r,o)&&transformAtruleWithinAtrule(r,o),"nodes"in r&&r.nodes.length&&walk$1(r,t,n)}))}const creator$2=e=>{const t=Object.assign({noIsPseudoSelector:!1,silenceAtNestWarning:!1},e);return{postcssPlugin:"postcss-nesting",Rule(e,{result:n}){walk$1(e,n,t),e.selector.includes("&")&&ersandToScope$1(e,n)}}};creator$2.postcss=!0;const i=e();function mergeSelectors(e,t,r,o){let s;try{s=n.resolveNestedSelector(i.astSync(t),i.astSync(r))}catch(n){return e.warn(o,`Failed to parse selectors : "${r}" / "${t}" with message: "${n instanceof Error?n.message:n}"`),!1}return!!s&&s.toString()}function ampersandToScope(t,n){{let r=t.parent;for(;r;){if("rule"===r.type)return;if(isAtRule(r)&&"scope"===r.name)return;r=r.parent}try{let n=!1;if(e().astSync(t.selector).walkNesting((()=>(n=!0,!1))),!n)return}catch(e){return void t.warn(n,`Failed to parse selector : "${t.selector}" with message: "${e instanceof Error?e.message:e}"`)}}const r=mergeSelectors(t,t.selector,":scope",n);r&&(t.selector=r)}function atruleWithinRule(e,t,n,r){if(shiftNodesBeforeParent(e,t),e.nodes){const o=t.clone().removeAll().append(e.nodes);e.append(o),cleanupParent(t),r(o,n)}else cleanupParent(t)}function isAtruleWithinRule(e){return s.includes(e.name)}function transformRuleWithinRule(e,t,n){const r=mergeSelectors(e,e.selector,t.selector,n);if(!r)return;shiftNodesBeforeParent(e,t),e.selector=r;"rule"===e.type&&"rule"===t.type&&e.selector===t.selector&&e.append(...t.nodes),cleanupParent(t)}function isValidRuleWithinRule(e){return e.selectors.every((e=>-1===e.indexOf("|")))}function walk(e,t){e.each((e=>{const n=e.parent;isRule(e)&&isRule(n)&&isValidRuleWithinRule(e)?transformRuleWithinRule(e,n,t):isAtRule(e)&&isRule(n)&&isAtruleWithinRule(e)&&atruleWithinRule(e,n,t,walk),"nodes"in e&&e.nodes.length&&walk(e,t)}))}const creator$1=()=>({postcssPlugin:"postcss-nesting",Rule(e,{result:t}){walk(e,t),e.selector.includes("&")&&ersandToScope(e,t)},AtRule:{nest(e){throw e.error(`\`@nest\` was removed from the CSS Nesting specification and will be removed from PostCSS Nesting in the next major version.\nChange \`@nest ${e.params} {}\` to \`${e.params} {}\` to migrate to the latest standard.`)}}});creator$1.postcss=!0;const creator=e=>{const t=Object.assign({edition:"2021"},e);switch(t.edition){case"2021":return creator$2(e);case"2024-02":return creator$1();default:throw new Error(`Invalid edition: ${t.edition}`)}};creator.postcss=!0,module.exports=creator; diff --git a/plugins/postcss-nesting/dist/index.mjs b/plugins/postcss-nesting/dist/index.mjs index ba87816f6..7db55e943 100644 --- a/plugins/postcss-nesting/dist/index.mjs +++ b/plugins/postcss-nesting/dist/index.mjs @@ -1 +1 @@ -import e from"postcss-selector-parser";import{selectorSpecificity as t}from"@csstools/selector-specificity";import{resolveNestedSelector as n}from"@csstools/selector-resolve-nested";const r=e.pseudo({value:":is"});function sortCompoundSelectorsInsideComplexSelector(t){if(!t||!t.nodes)return;const n=[];let o=[];for(let s=0;s"tag"===e.type))){const n=r.clone({}),o=t.nodes[s];o.replaceWith(n),n.append(e.selector({nodes:[o],value:void 0}))}o.push(t.nodes[s])}else n.push(o),n.push([t.nodes[s]]),o=[];n.push(o);const s=[];for(let e=0;e"selector"===e.type&&"selector"===t.type&&e.nodes.length&&t.nodes.length?selectorTypeOrder(e.nodes[0])-selectorTypeOrder(t.nodes[0]):"selector"===e.type&&e.nodes.length?selectorTypeOrder(e.nodes[0])-selectorTypeOrder(t):"selector"===t.type&&t.nodes.length?selectorTypeOrder(e)-selectorTypeOrder(t.nodes[0]):selectorTypeOrder(e)-selectorTypeOrder(t)));for(let e=0;e=0;e--)s[e].remove(),t.prepend(s[e])}function selectorTypeOrder(t){return e.isPseudoElement(t)?o.pseudoElement:o[t.type]}const o={universal:0,tag:1,pseudoElement:2,id:3,class:4,attribute:5,pseudo:6,selector:7,string:8,root:9,comment:10};function isAtRule(e){return e&&"atrule"===e.type}function isNestRule(e){return e&&isAtRule(e)&&"nest"===e.name}function isRule(e){return e&&"rule"===e.type}function ampersandToScope$1(t,n){let r,o=t.parent;for(;o;){if("rule"===o.type)return;if(isAtRule(o)&&"scope"===o.name)return;o=o.parent}try{r=e().astSync(t.selector)}catch(e){return void t.warn(n,`Failed to parse selector : "${t.selector}" with message: "${e instanceof Error?e.message:e}"`)}r&&(r.walkNesting((t=>{const n=t.parent;t.replaceWith(e.pseudo({value:":scope"})),n&&sortCompoundSelectorsInsideComplexSelector(n)})),t.selector=r.toString())}function cleanupParent(e){if(!e.nodes.length)return void e.remove();const t=e.nodes.filter((e=>"comment"===e.type));t.length===e.nodes.length&&e.replaceWith(...t)}function groupDeclarations(e){const t=[],n=[];e.each((e=>{if(isDeclarationLike(e,n.length>0))t.push(e);else{if("comment"===e.type){let r=e.next();for(;r&&"comment"===r.type;)r=r.next();if(isDeclarationLike(r,n.length>0))return void t.push(e)}n.push(e)}})),e.removeAll(),t.forEach((t=>{e.append(t)})),n.forEach((t=>{e.append(t)}))}function isDeclarationLike(e,t){return!!e&&("decl"===e.type||"atrule"===e.type&&"mixin"===e.name.toLowerCase()&&!t)}function comma(e){const t=[];let n="",r=!1,o=0,s=!1,i=!1;for(const l of e)i?i=!1:"\\"===l?i=!0:s?l===s&&(s=!1):'"'===l||"'"===l?s=l:"("===l?o+=1:")"===l?o>0&&(o-=1):0===o&&","===l&&(r=!0),r?(""!==n&&t.push(n.trim()),n="",r=!1):n+=l;return t.push(n.trim()),t}function shiftNodesBeforeParent(e,t){const n=t.index(e);if(n){const e=t.cloneBefore().removeAll().append(t.nodes.slice(0,n));e.raws.semicolon=!0,cleanupParent(e)}t.before(e),t.raws.semicolon=!0}var s=["container","document","media","supports","layer","starting-style"];function transformAtruleWithinAtrule(e,t){var n,r;groupDeclarations(t),shiftNodesBeforeParent(e,t),e.params=(n=t.params,r=e.params,comma(n).map((e=>comma(r).map((t=>`${e} and ${t}`)).join(", "))).join(", ")),cleanupParent(t)}function isAtruleWithinAtrule(e,t){return s.includes(e.name)&&e.name===t.name}function atruleWithinRule$1(e,t,n,r,o){if(groupDeclarations(t),shiftNodesBeforeParent(e,t),e.nodes){const s=t.clone().removeAll().append(e.nodes);e.append(s),cleanupParent(t),r(s,n,o)}else cleanupParent(t)}function isAtruleWithinRule$1(e){return s.includes(e.name)}function combinationsWithSizeN(e,t){if(t<2)throw new Error("n must be greater than 1");if(e.length<2)throw new Error("s must be greater than 1");if(Math.pow(e.length,t)>1e4)throw new Error("Too many combinations when trying to resolve a nested selector with lists, reduce the complexity of your selectors");const n=[];for(let e=0;e=0;s--){let t=n[s];if(t>=e.length){if(t=0,n[s]=0,0===s)return r;n[s-1]+=1}o[s]=e[t]}r.push(o),n[n.length-1]++}}function nodesAreEquallySpecific(n){const r=n.map((t=>e().astSync(t))).map((e=>t(e))),o=r[0];for(let e=1;ee().astSync(t))):[e().astSync(`:is(${t.join(",")})`)];const s=[];for(let t=0;t{"nesting"===e.type&&(n=!0)}));const r=t.nodes[0];let o=!1;r.each((e=>"combinator"===e.type&&(o=!0,!1))),n?o&&r.insertBefore(r.at(0),e.nesting({})):(r.insertBefore(r.at(0),e.combinator({value:" "})),r.insertBefore(r.at(0),e.nesting({}))),l=t.toString()}let c=[],a=0;if(e().astSync(l).walkNesting((()=>{a++})),a>1&&o.length>1)c=combinationsWithSizeN(o,a),i=c.length;else{i=o.length;for(let e=0;e{if("nesting"!==o.type)return;let s=c[t][n];n++,"root"===s.type&&1===s.nodes.length&&(s=s.nodes[0]);const i=e().astSync(`:is(${s.toString()})`),l=isSimpleSelector(s.nodes[0]),a=isCompoundSelector(s.nodes[0]),u=isSimpleSelector(o),p=isCompoundSelector(o);if(l&&u)return void o.replaceWith(s.clone());if((l||a)&&(u||p)){const e=o.parent;return l&&"selector"===s.type?o.replaceWith(s.clone().nodes[0]):o.replaceWith(...s.clone().nodes),void(e&&e.nodes.length>1&&sortCompoundSelectorsInsideComplexSelector(e))}if(l){const e=o.parent;return o.replaceWith(s.clone().nodes[0]),void(e&&sortCompoundSelectorsInsideComplexSelector(e))}if(a){const e=o.parent;return o.replaceWith(...s.clone().nodes),void(e&&sortCompoundSelectorsInsideComplexSelector(e))}if(nestingIsFirstAndOnlyInSelectorWithEitherSpaceOrChildCombinator(o)){const e=o.parent;return o.replaceWith(...s.clone().nodes),void(e&&sortCompoundSelectorsInsideComplexSelector(e))}if(nestingIsNotInsideCompoundSelector(o)){const e=o.parent;return o.replaceWith(...s.clone().nodes),void(e&&sortCompoundSelectorsInsideComplexSelector(e))}const d=o.parent;r.noIsPseudoSelector?o.replaceWith(...s.clone().nodes):o.replaceWith(...i.clone({}).nodes),d&&sortCompoundSelectorsInsideComplexSelector(d)})),s.push(o.toString())}}return s}function isSimpleSelector(e){return"combinator"!==e.type&&!(e.parent&&e.parent.nodes.length>1)}function isCompoundSelector(e,t=null){if(isSimpleSelector(e))return!1;if(!e.parent)return!1;if(!!e.parent.nodes.find((e=>"combinator"===e.type)))return!1;return!(!!e.parent.nodes.find((e=>"nesting"===e.type))&&t&&!isCompoundSelector(t))}function nestingIsFirstAndOnlyInSelectorWithEitherSpaceOrChildCombinator(e){if(!e.parent)return!1;if(0!==e.parent.nodes.indexOf(e))return!1;for(let t=1;t"!==e.parent.nodes[t].value)return!1;return!0}function nestingIsNotInsideCompoundSelector(e){if(isSimpleSelector(e))return!0;if(!e.parent)return!1;for(let t=0;te.split("&").length>=2&&-1===e.indexOf("|")))}function transformRuleWithinRule$1(e,t,n,r){let o=[];try{o=mergeSelectors$1(t.selectors,e.selectors,r)}catch(r){return void e.warn(n,`Failed to parse selectors : "${t.selector}" / "${e.selector}" with message: "${r instanceof Error?r.message:r}"`)}if(!o.length)return;groupDeclarations(t),shiftNodesBeforeParent(e,t),e.selectors=o;"rule"===e.type&&"rule"===t.type&&e.selector===t.selector&&e.append(...t.nodes),cleanupParent(t)}function isValidRuleWithinRule$1(e){return e.selectors.every((e=>-1===e.indexOf("|")))}function walk$1(e,t,n){e.each((r=>{const o=r.parent;isNestRule(r)&&!n.silenceAtNestWarning&&e.warn(t,`\`@nest\` was removed from the CSS Nesting specification and will be removed from PostCSS Nesting in the next major version.\nChange \`@nest ${r.params} {}\` to \`${r.params} {}\` to migrate to the latest standard.`),isRule(r)&&isRule(o)&&isValidRuleWithinRule$1(r)?transformRuleWithinRule$1(r,o,t,n):isNestRule(r)&&isRule(o)&&isValidNestRuleWithinRule(r)?transformNestRuleWithinRule(r,o,t,walk$1,n):isAtRule(r)&&isRule(o)&&isAtruleWithinRule$1(r)?atruleWithinRule$1(r,o,t,walk$1,n):isAtRule(r)&&isAtRule(o)&&isAtruleWithinAtrule(r,o)&&transformAtruleWithinAtrule(r,o),"nodes"in r&&r.nodes.length&&walk$1(r,t,n)}))}const creator$2=e=>{const t=Object.assign({noIsPseudoSelector:!1,silenceAtNestWarning:!1},e);return{postcssPlugin:"postcss-nesting",Rule(e,{result:n}){walk$1(e,n,t),e.selector.includes("&")&&ersandToScope$1(e,n)}}};creator$2.postcss=!0;const i=e();function mergeSelectors(e,t,r,o){let s;try{s=n(i.astSync(t),i.astSync(r))}catch(n){return e.warn(o,`Failed to parse selectors : "${r}" / "${t}" with message: "${n instanceof Error?n.message:n}"`),!1}return!!s&&s.toString()}function ampersandToScope(t,n){{let r=t.parent;for(;r;){if("rule"===r.type)return;if(isAtRule(r)&&"scope"===r.name)return;r=r.parent}try{let n=!1;if(e().astSync(t.selector).walkNesting((()=>(n=!0,!1))),!n)return}catch(e){return void t.warn(n,`Failed to parse selector : "${t.selector}" with message: "${e instanceof Error?e.message:e}"`)}}const r=mergeSelectors(t,t.selector,":scope",n);r&&(t.selector=r)}function atruleWithinRule(e,t,n,r){if(shiftNodesBeforeParent(e,t),e.nodes){const o=t.clone().removeAll().append(e.nodes);e.append(o),cleanupParent(t),r(o,n)}else cleanupParent(t)}function isAtruleWithinRule(e){return s.includes(e.name)}function transformRuleWithinRule(e,t,n){const r=mergeSelectors(e,e.selector,t.selector,n);if(!r)return;shiftNodesBeforeParent(e,t),e.selector=r;"rule"===e.type&&"rule"===t.type&&e.selector===t.selector&&e.append(...t.nodes),cleanupParent(t)}function isValidRuleWithinRule(e){return e.selectors.every((e=>-1===e.indexOf("|")))}function walk(e,t){e.each((e=>{const n=e.parent;isRule(e)&&isRule(n)&&isValidRuleWithinRule(e)?transformRuleWithinRule(e,n,t):isAtRule(e)&&isRule(n)&&isAtruleWithinRule(e)&&atruleWithinRule(e,n,t,walk),"nodes"in e&&e.nodes.length&&walk(e,t)}))}const creator$1=()=>({postcssPlugin:"postcss-nesting",Rule(e,{result:t}){walk(e,t),e.selector.includes("&")&&ersandToScope(e,t)},AtRule:{nest(e){throw e.error(`\`@nest\` was removed from the CSS Nesting specification and will be removed from PostCSS Nesting in the next major version.\nChange \`@nest ${e.params} {}\` to \`${e.params} {}\` to migrate to the latest standard.`)}}});creator$1.postcss=!0;const creator=e=>{const t=Object.assign({edition:"2021"},e);switch(t.edition){case"2021":return creator$2(e);case"2024-02":return creator$1();default:throw new Error(`Invalid edition: ${t.edition}`)}};creator.postcss=!0;export{creator as default}; +import e from"postcss-selector-parser";import{selectorSpecificity as t}from"@csstools/selector-specificity";import{resolveNestedSelector as n}from"@csstools/selector-resolve-nested";const r=e.pseudo({value:":is"});function sortCompoundSelectorsInsideComplexSelector(t){if(!t||!t.nodes)return;const n=[];let o=[];for(let s=0;s"tag"===e.type))){const n=r.clone({}),o=t.nodes[s];o.replaceWith(n),n.append(e.selector({nodes:[o],value:void 0}))}o.push(t.nodes[s])}else n.push(o),n.push([t.nodes[s]]),o=[];n.push(o);const s=[];for(let e=0;e"selector"===e.type&&"selector"===t.type&&e.nodes.length&&t.nodes.length?selectorTypeOrder(e.nodes[0])-selectorTypeOrder(t.nodes[0]):"selector"===e.type&&e.nodes.length?selectorTypeOrder(e.nodes[0])-selectorTypeOrder(t):"selector"===t.type&&t.nodes.length?selectorTypeOrder(e)-selectorTypeOrder(t.nodes[0]):selectorTypeOrder(e)-selectorTypeOrder(t)));for(let e=0;e=0;e--)s[e].remove(),t.prepend(s[e])}function selectorTypeOrder(t){return e.isPseudoElement(t)?o.pseudoElement:o[t.type]}const o={universal:0,tag:1,pseudoElement:2,id:3,class:4,attribute:5,pseudo:6,selector:7,string:8,root:9,comment:10};function isAtRule(e){return e&&"atrule"===e.type}function isNestRule(e){return e&&isAtRule(e)&&"nest"===e.name}function isRule(e){return e&&"rule"===e.type}function ampersandToScope$1(t,n){let r,o=t.parent;for(;o;){if("rule"===o.type)return;if(isAtRule(o)&&"scope"===o.name)return;o=o.parent}try{r=e().astSync(t.selector)}catch(e){return void t.warn(n,`Failed to parse selector : "${t.selector}" with message: "${e instanceof Error?e.message:e}"`)}r&&(r.walkNesting((t=>{const n=t.parent;t.replaceWith(e.pseudo({value:":scope"})),n&&sortCompoundSelectorsInsideComplexSelector(n)})),t.selector=r.toString())}function cleanupParent(e){if(!e.nodes.length)return void e.remove();const t=e.nodes.filter((e=>"comment"===e.type));t.length===e.nodes.length&&e.replaceWith(...t)}function groupDeclarations(e){const t=[],n=[];e.each((e=>{if(isDeclarationLike(e,n.length>0))t.push(e);else{if("comment"===e.type){let r=e.next();for(;r&&"comment"===r.type;)r=r.next();if(isDeclarationLike(r,n.length>0))return void t.push(e)}n.push(e)}})),e.removeAll(),t.forEach((t=>{e.append(t)})),n.forEach((t=>{e.append(t)}))}function isDeclarationLike(e,t){return!!e&&("decl"===e.type||"atrule"===e.type&&"mixin"===e.name.toLowerCase()&&!t)}function comma(e){const t=[];let n="",r=!1,o=0,s=!1,i=!1;for(const l of e)i?i=!1:"\\"===l?i=!0:s?l===s&&(s=!1):'"'===l||"'"===l?s=l:"("===l?o+=1:")"===l?o>0&&(o-=1):0===o&&","===l&&(r=!0),r?(""!==n&&t.push(n.trim()),n="",r=!1):n+=l;return t.push(n.trim()),t}function shiftNodesBeforeParent(e,t){const n=t.index(e);if(n){const e=t.cloneBefore().removeAll().append(t.nodes.slice(0,n));e.raws.semicolon=!0,cleanupParent(e)}t.before(e),t.raws.semicolon=!0}var s=["container","document","media","supports","layer","starting-style"];function transformAtruleWithinAtrule(e,t){var n,r;groupDeclarations(t),shiftNodesBeforeParent(e,t),e.params=(n=t.params,r=e.params,comma(n).map((e=>comma(r).map((t=>`${e} and ${t}`)).join(", "))).join(", ")),cleanupParent(t)}function isAtruleWithinAtrule(e,t){return s.includes(e.name)&&e.name===t.name}function atruleWithinRule$1(e,t,n,r,o){if(groupDeclarations(t),shiftNodesBeforeParent(e,t),e.nodes){const s=t.clone().removeAll().append(e.nodes);e.append(s),cleanupParent(t),r(s,n,o)}else cleanupParent(t)}function isAtruleWithinRule$1(e){return s.includes(e.name)}function combinationsWithSizeN(e,t){if(t<2)throw new Error("n must be greater than 1");if(e.length<2)throw new Error("s must be greater than 1");if(Math.pow(e.length,t)>1e4)throw new Error("Too many combinations when trying to resolve a nested selector with lists, reduce the complexity of your selectors");const n=[];for(let e=0;e=0;s--){let t=n[s];if(t>=e.length){if(t=0,n[s]=0,0===s)return r;n[s-1]+=1}o[s]=e[t].clone()}r.push(o),n[n.length-1]++}}function nodesAreEquallySpecific(n){const r=n.map((t=>e().astSync(t))).map((e=>t(e))),o=r[0];for(let e=1;ee().astSync(t))):[e().astSync(`:is(${t.join(",")})`)];const s=[];for(let t=0;t{"nesting"===e.type&&(n=!0)}));const r=t.nodes[0];let o=!1;r.each((e=>"combinator"===e.type&&(o=!0,!1))),n?o&&r.insertBefore(r.at(0),e.nesting()):(r.insertBefore(r.at(0),e.combinator({value:" "})),r.insertBefore(r.at(0),e.nesting())),l=t.toString()}let c=[],a=0;if(e().astSync(l).walkNesting((()=>{a++})),a>1&&o.length>1)c=combinationsWithSizeN(o,a),i=c.length;else{i=o.length;for(let e=0;e{if("nesting"!==o.type)return;let s=c[t][n];n++,"root"===s.type&&1===s.nodes.length&&(s=s.nodes[0]);const i=e().astSync(`:is(${s.toString()})`),l=isSimpleSelector(s.nodes[0]),a=isCompoundSelector(s.nodes[0]),u=isSimpleSelector(o),p=isCompoundSelector(o);if(l&&u)return void o.replaceWith(s.clone());if((l||a)&&(u||p)){const e=o.parent;return l&&"selector"===s.type?o.replaceWith(s.clone().nodes[0]):o.replaceWith(...s.clone().nodes),void(e&&e.nodes.length>1&&sortCompoundSelectorsInsideComplexSelector(e))}if(l){const e=o.parent;return o.replaceWith(s.clone().nodes[0]),void(e&&sortCompoundSelectorsInsideComplexSelector(e))}if(a){const e=o.parent;return o.replaceWith(...s.clone().nodes),void(e&&sortCompoundSelectorsInsideComplexSelector(e))}if(nestingIsFirstAndOnlyInSelectorWithEitherSpaceOrChildCombinator(o)){const e=o.parent;return o.replaceWith(...s.clone().nodes),void(e&&sortCompoundSelectorsInsideComplexSelector(e))}if(nestingIsNotInsideCompoundSelector(o)){const e=o.parent;return o.replaceWith(...s.clone().nodes),void(e&&sortCompoundSelectorsInsideComplexSelector(e))}const d=o.parent;r.noIsPseudoSelector?o.replaceWith(...s.clone().nodes):o.replaceWith(...i.clone({}).nodes),d&&sortCompoundSelectorsInsideComplexSelector(d)})),s.push(o.toString())}}return s}function isSimpleSelector(e){return"combinator"!==e.type&&!(e.parent&&e.parent.nodes.length>1)}function isCompoundSelector(e,t=null){if(isSimpleSelector(e))return!1;if(!e.parent)return!1;if(!!e.parent.nodes.find((e=>"combinator"===e.type)))return!1;return!(!!e.parent.nodes.find((e=>"nesting"===e.type))&&t&&!isCompoundSelector(t))}function nestingIsFirstAndOnlyInSelectorWithEitherSpaceOrChildCombinator(e){if(!e.parent)return!1;if(0!==e.parent.nodes.indexOf(e))return!1;for(let t=1;t"!==e.parent.nodes[t].value)return!1;return!0}function nestingIsNotInsideCompoundSelector(e){if(isSimpleSelector(e))return!0;if(!e.parent)return!1;for(let t=0;te.split("&").length>=2&&-1===e.indexOf("|")))}function transformRuleWithinRule$1(e,t,n,r){let o=[];try{o=mergeSelectors$1(t.selectors,e.selectors,r)}catch(r){return void e.warn(n,`Failed to parse selectors : "${t.selector}" / "${e.selector}" with message: "${r instanceof Error?r.message:r}"`)}if(!o.length)return;groupDeclarations(t),shiftNodesBeforeParent(e,t),e.selectors=o;"rule"===e.type&&"rule"===t.type&&e.selector===t.selector&&e.append(...t.nodes),cleanupParent(t)}function isValidRuleWithinRule$1(e){return e.selectors.every((e=>-1===e.indexOf("|")))}function walk$1(e,t,n){e.each((r=>{const o=r.parent;isNestRule(r)&&!n.silenceAtNestWarning&&e.warn(t,`\`@nest\` was removed from the CSS Nesting specification and will be removed from PostCSS Nesting in the next major version.\nChange \`@nest ${r.params} {}\` to \`${r.params} {}\` to migrate to the latest standard.`),isRule(r)&&isRule(o)&&isValidRuleWithinRule$1(r)?transformRuleWithinRule$1(r,o,t,n):isNestRule(r)&&isRule(o)&&isValidNestRuleWithinRule(r)?transformNestRuleWithinRule(r,o,t,walk$1,n):isAtRule(r)&&isRule(o)&&isAtruleWithinRule$1(r)?atruleWithinRule$1(r,o,t,walk$1,n):isAtRule(r)&&isAtRule(o)&&isAtruleWithinAtrule(r,o)&&transformAtruleWithinAtrule(r,o),"nodes"in r&&r.nodes.length&&walk$1(r,t,n)}))}const creator$2=e=>{const t=Object.assign({noIsPseudoSelector:!1,silenceAtNestWarning:!1},e);return{postcssPlugin:"postcss-nesting",Rule(e,{result:n}){walk$1(e,n,t),e.selector.includes("&")&&ersandToScope$1(e,n)}}};creator$2.postcss=!0;const i=e();function mergeSelectors(e,t,r,o){let s;try{s=n(i.astSync(t),i.astSync(r))}catch(n){return e.warn(o,`Failed to parse selectors : "${r}" / "${t}" with message: "${n instanceof Error?n.message:n}"`),!1}return!!s&&s.toString()}function ampersandToScope(t,n){{let r=t.parent;for(;r;){if("rule"===r.type)return;if(isAtRule(r)&&"scope"===r.name)return;r=r.parent}try{let n=!1;if(e().astSync(t.selector).walkNesting((()=>(n=!0,!1))),!n)return}catch(e){return void t.warn(n,`Failed to parse selector : "${t.selector}" with message: "${e instanceof Error?e.message:e}"`)}}const r=mergeSelectors(t,t.selector,":scope",n);r&&(t.selector=r)}function atruleWithinRule(e,t,n,r){if(shiftNodesBeforeParent(e,t),e.nodes){const o=t.clone().removeAll().append(e.nodes);e.append(o),cleanupParent(t),r(o,n)}else cleanupParent(t)}function isAtruleWithinRule(e){return s.includes(e.name)}function transformRuleWithinRule(e,t,n){const r=mergeSelectors(e,e.selector,t.selector,n);if(!r)return;shiftNodesBeforeParent(e,t),e.selector=r;"rule"===e.type&&"rule"===t.type&&e.selector===t.selector&&e.append(...t.nodes),cleanupParent(t)}function isValidRuleWithinRule(e){return e.selectors.every((e=>-1===e.indexOf("|")))}function walk(e,t){e.each((e=>{const n=e.parent;isRule(e)&&isRule(n)&&isValidRuleWithinRule(e)?transformRuleWithinRule(e,n,t):isAtRule(e)&&isRule(n)&&isAtruleWithinRule(e)&&atruleWithinRule(e,n,t,walk),"nodes"in e&&e.nodes.length&&walk(e,t)}))}const creator$1=()=>({postcssPlugin:"postcss-nesting",Rule(e,{result:t}){walk(e,t),e.selector.includes("&")&&ersandToScope(e,t)},AtRule:{nest(e){throw e.error(`\`@nest\` was removed from the CSS Nesting specification and will be removed from PostCSS Nesting in the next major version.\nChange \`@nest ${e.params} {}\` to \`${e.params} {}\` to migrate to the latest standard.`)}}});creator$1.postcss=!0;const creator=e=>{const t=Object.assign({edition:"2021"},e);switch(t.edition){case"2021":return creator$2(e);case"2024-02":return creator$1();default:throw new Error(`Invalid edition: ${t.edition}`)}};creator.postcss=!0;export{creator as default}; diff --git a/plugins/postcss-nesting/src/editions/2021/lib/merge-selectors/combinations-of-size-n.ts b/plugins/postcss-nesting/src/editions/2021/lib/merge-selectors/combinations-of-size-n.ts index 74d7bc2b4..4955a5a43 100644 --- a/plugins/postcss-nesting/src/editions/2021/lib/merge-selectors/combinations-of-size-n.ts +++ b/plugins/postcss-nesting/src/editions/2021/lib/merge-selectors/combinations-of-size-n.ts @@ -1,4 +1,6 @@ -export function combinationsWithSizeN(set: Array, n: number): Array> { +import type { Root } from 'postcss-selector-parser'; + +export function combinationsWithSizeN(set: Array, n: number): Array> { // set is the list of parent selectors // n is the amount of `&` selectors in the current selector. // all combinations of values in the set with an array size of n must be generated to match the nesting selector behavior. @@ -20,6 +22,7 @@ export function combinationsWithSizeN(set: Array, n: number): Array, n: number): Array = []; @@ -43,12 +47,11 @@ export function combinationsWithSizeN(set: Array, n: number): Array> = []; + const result: Array> = []; - // eslint-disable-next-line no-constant-condition while (true) { - const ss : Array = []; - for (let i = n-1; i >=0; i--) { + const ss: Array = []; + for (let i = n - 1; i >= 0; i--) { let currentCounter = counters[i]; if (currentCounter >= set.length) { currentCounter = 0; @@ -57,14 +60,14 @@ export function combinationsWithSizeN(set: Array, n: number): Array x.type === 'tag')) { - const isPseudoClone = isPseudo.clone({}) as Pseudo; + const isPseudoClone = isPseudo.clone({}); const child = node.nodes[i]; child.replaceWith(isPseudoClone); isPseudoClone.append(parser.selector({ @@ -49,7 +49,7 @@ export function sortCompoundSelectorsInsideComplexSelector(node: Container = []; for (let i = 0; i < compoundSelectors.length; i++) { const compoundSelector = compoundSelectors[i]; compoundSelector.sort((a, b) => { @@ -87,7 +87,7 @@ function selectorTypeOrder(selector: Node): number { return selectorTypeOrderIndex[selector.type]; } -const selectorTypeOrderIndex = { +const selectorTypeOrderIndex: Record = { universal: 0, tag: 1, pseudoElement: 2, diff --git a/plugins/postcss-nesting/src/editions/2021/lib/merge-selectors/merge-selectors.ts b/plugins/postcss-nesting/src/editions/2021/lib/merge-selectors/merge-selectors.ts index 166aeca4d..4bb6526c2 100644 --- a/plugins/postcss-nesting/src/editions/2021/lib/merge-selectors/merge-selectors.ts +++ b/plugins/postcss-nesting/src/editions/2021/lib/merge-selectors/merge-selectors.ts @@ -1,5 +1,5 @@ import parser from 'postcss-selector-parser'; -import type { Root, Nesting } from 'postcss-selector-parser'; +import type { Nesting } from 'postcss-selector-parser'; import { combinationsWithSizeN } from './combinations-of-size-n'; import { sortCompoundSelectorsInsideComplexSelector } from './compound-selector-order'; import { nodesAreEquallySpecific } from './specificity'; @@ -8,7 +8,7 @@ import { options } from '../options'; export default function mergeSelectors(fromSelectors: Array, toSelectors: Array, opts: options): Array { const fromListHasUniformSpecificity = nodesAreEquallySpecific(fromSelectors); - let fromSelectorsAST = []; + let fromSelectorsAST: Array = []; if (fromListHasUniformSpecificity || opts.noIsPseudoSelector) { fromSelectorsAST = fromSelectors.map((selector) => { @@ -18,7 +18,7 @@ export default function mergeSelectors(fromSelectors: Array, toSelectors fromSelectorsAST = [parser().astSync(`:is(${fromSelectors.join(',')})`)]; } - const result = []; + const result: Array = []; for (let x = 0; x < toSelectors.length; x++) { let toSelector = toSelectors[x]; @@ -46,16 +46,18 @@ export default function mergeSelectors(fromSelectors: Array, toSelectors if (!isNestContaining) { selectorAST.insertBefore(selectorAST.at(0), parser.combinator({ value: ' ' })); - selectorAST.insertBefore(selectorAST.at(0), parser.nesting({})); + // @ts-expect-error - `parser.nesting` is not recognized + selectorAST.insertBefore(selectorAST.at(0), parser.nesting()); // eslint-disable-line @typescript-eslint/no-unsafe-argument } else if (startsWithCombinator) { - selectorAST.insertBefore(selectorAST.at(0), parser.nesting({})); + // @ts-expect-error - `parser.nesting` is not recognized + selectorAST.insertBefore(selectorAST.at(0), parser.nesting()); // eslint-disable-line @typescript-eslint/no-unsafe-argument } toSelector = toSelectorAST.toString(); } let iterations: number; - let fromSelectorCombinations = []; + let fromSelectorCombinations: Array> = []; let nestingCounter = 0; parser().astSync(toSelector).walkNesting(() => { @@ -85,7 +87,7 @@ export default function mergeSelectors(fromSelectors: Array, toSelectors return; } - let fromSelectorAST = fromSelectorCombinations[y][counter]; + let fromSelectorAST: parser.Root | parser.Selector = fromSelectorCombinations[y][counter]; counter++; // If the from selector is simple we extract the first non root, non selector node @@ -174,7 +176,7 @@ export default function mergeSelectors(fromSelectors: Array, toSelectors if (opts.noIsPseudoSelector) { nesting.replaceWith(...(fromSelectorAST.clone().nodes)); } else { - nesting.replaceWith(...((fromSelectorWithIsAST.clone({}) as Root).nodes)); + nesting.replaceWith(...((fromSelectorWithIsAST.clone({})).nodes)); } if (parent) { @@ -189,7 +191,7 @@ export default function mergeSelectors(fromSelectors: Array, toSelectors return result; } -function isSimpleSelector(selector): boolean { +function isSimpleSelector(selector: parser.Node): boolean { if (selector.type === 'combinator') { return false; } @@ -201,7 +203,7 @@ function isSimpleSelector(selector): boolean { return true; } -function isCompoundSelector(selector, toSelector = null): boolean { +function isCompoundSelector(selector: parser.Node, toSelector: parser.Node | null = null): boolean { if (isSimpleSelector(selector)) { return false; } @@ -230,7 +232,7 @@ function isCompoundSelector(selector, toSelector = null): boolean { } -function nestingIsFirstAndOnlyInSelectorWithEitherSpaceOrChildCombinator(selector): boolean { +function nestingIsFirstAndOnlyInSelectorWithEitherSpaceOrChildCombinator(selector: parser.Node): boolean { if (!selector.parent) { return false; } diff --git a/plugins/postcss-nesting/src/editions/2021/lib/nest-rule-within-rule.ts b/plugins/postcss-nesting/src/editions/2021/lib/nest-rule-within-rule.ts index 5f17cf58b..a78662c45 100644 --- a/plugins/postcss-nesting/src/editions/2021/lib/nest-rule-within-rule.ts +++ b/plugins/postcss-nesting/src/editions/2021/lib/nest-rule-within-rule.ts @@ -7,7 +7,7 @@ import { options } from './options.js'; import cleanupParent from '../../shared/lib/cleanup-parent.js'; export default function transformNestRuleWithinRule(node: AtRule, parent: Rule, result: Result, walk: walkFunc, opts: options): void { - let selectors = []; + let selectors: Array = []; try { selectors = mergeSelectors(parent.selectors, comma(node.params), opts); diff --git a/plugins/postcss-nesting/src/editions/2021/lib/rule-within-rule.ts b/plugins/postcss-nesting/src/editions/2021/lib/rule-within-rule.ts index 9d5faef3f..c154dd598 100644 --- a/plugins/postcss-nesting/src/editions/2021/lib/rule-within-rule.ts +++ b/plugins/postcss-nesting/src/editions/2021/lib/rule-within-rule.ts @@ -6,7 +6,7 @@ import shiftNodesBeforeParent from '../../shared/lib/shift-nodes-before-parent.j import { options } from './options.js'; export default function transformRuleWithinRule(node: Rule, parent: Rule, result: Result, opts: options): void { - let selectors = []; + let selectors: Array = []; // update the selectors of the node to be merged with the parent try { diff --git a/plugins/postcss-nesting/src/editions/shared/lib/shift-nodes-before-parent.ts b/plugins/postcss-nesting/src/editions/shared/lib/shift-nodes-before-parent.ts index 745fa0a29..4a9f484d0 100644 --- a/plugins/postcss-nesting/src/editions/shared/lib/shift-nodes-before-parent.ts +++ b/plugins/postcss-nesting/src/editions/shared/lib/shift-nodes-before-parent.ts @@ -7,11 +7,13 @@ export default function shiftNodesBeforeParent(node: ChildNode, parent: Containe // conditionally move previous siblings into a clone of the parent if (index) { const newParent = parent.cloneBefore().removeAll().append(parent.nodes.slice(0, index)); + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access newParent.raws.semicolon = true; /* nested rules end with "}" and do not have this flag set */ cleanupParent(newParent); } // move the current node before the parent (and after the conditional clone) parent.before(node); + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access parent.raws.semicolon = true; /* nested rules end with "}" and do not have this flag set */ } diff --git a/plugins/postcss-nesting/src/index.ts b/plugins/postcss-nesting/src/index.ts index e17244980..a18bc974c 100644 --- a/plugins/postcss-nesting/src/index.ts +++ b/plugins/postcss-nesting/src/index.ts @@ -30,6 +30,7 @@ const creator: PluginCreator = (opts?: pluginOptions) => { case '2024-02': return plugin2024_02(opts); default: + // eslint-disable-next-line @typescript-eslint/restrict-template-expressions throw new Error(`Invalid edition: ${options.edition}`); } }; diff --git a/plugins/postcss-normalize-display-values/dist/index.cjs b/plugins/postcss-normalize-display-values/dist/index.cjs index 41fd8fb86..df31390bb 100644 --- a/plugins/postcss-normalize-display-values/dist/index.cjs +++ b/plugins/postcss-normalize-display-values/dist/index.cjs @@ -1 +1 @@ -"use strict";var e=require("postcss-value-parser"),l=new Map([["block,flow","block"],["block,flow-root","flow-root"],["inline,flow","inline"],["inline,flow-root","inline-block"],["run-in,flow","run-in"],["list-item,block,flow","list-item"],["inline,flow,list-item","inline list-item"],["block,flex","flex"],["inline,flex","inline-flex"],["block,grid","grid"],["inline,grid","inline-grid"],["inline,ruby","ruby"],["block,table","table"],["inline,table","inline-table"],["table-cell,flow","table-cell"],["table-caption,flow","table-caption"],["ruby-base,flow","ruby-base"],["ruby-text,flow","ruby-text"]]);function transform(n){const{nodes:t}=e(n);if(1===t.length)return n;const o=t.filter((e=>"word"===e.type)).map((e=>e.value.toLowerCase()));if(o.length<=1)return n;const i=l.get(o.join(","));return i||n}const n=/^display$/i,creator=e=>{const l=!("preserve"in Object(e))||Boolean(e?.preserve);return{postcssPlugin:"postcss-normalize-display-values",prepare(){const e=new Map;return{postcssPlugin:"postcss-normalize-display-values",Declaration(t){if(!n.test(t.prop))return;const o=t.value;if(!o)return;if(e.has(o))return void(t.value!==e.get(o)&&(t.cloneBefore({value:e.get(o)}),l||t.remove()));const i=transform(o);e.set(o,i),t.value!==i&&(t.cloneBefore({value:i}),l||t.remove())}}}}};creator.postcss=!0,module.exports=creator; +"use strict";var e=require("postcss-value-parser"),l=new Map([["block,flex","flex"],["block,flow","block"],["block,flow-root","flow-root"],["block,grid","grid"],["block,table","table"],["inline,flex","inline-flex"],["inline,flow","inline"],["inline,flow,list-item","inline list-item"],["inline,flow-root","inline-block"],["inline,grid","inline-grid"],["inline,ruby","ruby"],["inline,table","inline-table"],["list-item,block,flow","list-item"],["ruby-base,flow","ruby-base"],["ruby-text,flow","ruby-text"],["run-in,flow","run-in"],["table-caption,flow","table-caption"],["table-cell,flow","table-cell"]]);function transform(n){if(!n.trim())return n;const{nodes:i}=e(n);if(i.length<=1)return n;const t=i.filter((e=>"word"===e.type)).map((e=>e.value.toLowerCase()));if(t.length<=1)return n;const o=l.get(t.join(","));return o||n}const n=/^display$/i,creator=e=>{const l=!("preserve"in Object(e))||Boolean(e?.preserve);return{postcssPlugin:"postcss-normalize-display-values",Declaration(e){if(!n.test(e.prop))return;const i=e.value;if(!i)return;const t=transform(i);e.value!==t&&(e.cloneBefore({value:t}),l||e.remove())}}};creator.postcss=!0,module.exports=creator; diff --git a/plugins/postcss-normalize-display-values/dist/index.mjs b/plugins/postcss-normalize-display-values/dist/index.mjs index b15f3ec8e..c4acf6670 100644 --- a/plugins/postcss-normalize-display-values/dist/index.mjs +++ b/plugins/postcss-normalize-display-values/dist/index.mjs @@ -1 +1 @@ -import e from"postcss-value-parser";var l=new Map([["block,flow","block"],["block,flow-root","flow-root"],["inline,flow","inline"],["inline,flow-root","inline-block"],["run-in,flow","run-in"],["list-item,block,flow","list-item"],["inline,flow,list-item","inline list-item"],["block,flex","flex"],["inline,flex","inline-flex"],["block,grid","grid"],["inline,grid","inline-grid"],["inline,ruby","ruby"],["block,table","table"],["inline,table","inline-table"],["table-cell,flow","table-cell"],["table-caption,flow","table-caption"],["ruby-base,flow","ruby-base"],["ruby-text,flow","ruby-text"]]);function transform(n){const{nodes:o}=e(n);if(1===o.length)return n;const t=o.filter((e=>"word"===e.type)).map((e=>e.value.toLowerCase()));if(t.length<=1)return n;const i=l.get(t.join(","));return i||n}const n=/^display$/i,creator=e=>{const l=!("preserve"in Object(e))||Boolean(e?.preserve);return{postcssPlugin:"postcss-normalize-display-values",prepare(){const e=new Map;return{postcssPlugin:"postcss-normalize-display-values",Declaration(o){if(!n.test(o.prop))return;const t=o.value;if(!t)return;if(e.has(t))return void(o.value!==e.get(t)&&(o.cloneBefore({value:e.get(t)}),l||o.remove()));const i=transform(t);e.set(t,i),o.value!==i&&(o.cloneBefore({value:i}),l||o.remove())}}}}};creator.postcss=!0;export{creator as default}; +import e from"postcss-value-parser";var l=new Map([["block,flex","flex"],["block,flow","block"],["block,flow-root","flow-root"],["block,grid","grid"],["block,table","table"],["inline,flex","inline-flex"],["inline,flow","inline"],["inline,flow,list-item","inline list-item"],["inline,flow-root","inline-block"],["inline,grid","inline-grid"],["inline,ruby","ruby"],["inline,table","inline-table"],["list-item,block,flow","list-item"],["ruby-base,flow","ruby-base"],["ruby-text,flow","ruby-text"],["run-in,flow","run-in"],["table-caption,flow","table-caption"],["table-cell,flow","table-cell"]]);function transform(n){if(!n.trim())return n;const{nodes:t}=e(n);if(t.length<=1)return n;const i=t.filter((e=>"word"===e.type)).map((e=>e.value.toLowerCase()));if(i.length<=1)return n;const o=l.get(i.join(","));return o||n}const n=/^display$/i,creator=e=>{const l=!("preserve"in Object(e))||Boolean(e?.preserve);return{postcssPlugin:"postcss-normalize-display-values",Declaration(e){if(!n.test(e.prop))return;const t=e.value;if(!t)return;const i=transform(t);e.value!==i&&(e.cloneBefore({value:i}),l||e.remove())}}};creator.postcss=!0;export{creator as default}; diff --git a/plugins/postcss-normalize-display-values/src/index.ts b/plugins/postcss-normalize-display-values/src/index.ts index f389e4ea1..d95862891 100644 --- a/plugins/postcss-normalize-display-values/src/index.ts +++ b/plugins/postcss-normalize-display-values/src/index.ts @@ -1,11 +1,15 @@ -import type { Plugin, PluginCreator } from 'postcss'; +import type { PluginCreator } from 'postcss'; import valueParser from 'postcss-value-parser'; import mappings from './mappings'; function transform(value: string): string { + if (!value.trim()) { + return value; + } + const { nodes } = valueParser(value); - if (nodes.length === 1) { + if (nodes.length <= 1) { return value; } @@ -39,46 +43,26 @@ const creator: PluginCreator = (opts?: pluginOptions) => { return { postcssPlugin: 'postcss-normalize-display-values', - prepare(): Plugin { - const cache = new Map(); - return { - postcssPlugin: 'postcss-normalize-display-values', - Declaration(decl): void { - if (!IS_DISPLAY_REGEX.test(decl.prop)) { - return; - } - - const value = decl.value; - if (!value) { - return; - } - - if (cache.has(value)) { - if (decl.value !== cache.get(value)) { - decl.cloneBefore({ value: cache.get(value) }); - - if (!preserve) { - decl.remove(); - } - } - - return; - } - - const result = transform(value); - cache.set(value, result); - - if (decl.value === result) { - return; - } - - decl.cloneBefore({ value: result }); - - if (!preserve) { - decl.remove(); - } - }, - }; + Declaration(decl): void { + if (!IS_DISPLAY_REGEX.test(decl.prop)) { + return; + } + + const value = decl.value; + if (!value) { + return; + } + + const result = transform(value); + if (decl.value === result) { + return; + } + + decl.cloneBefore({ value: result }); + + if (!preserve) { + decl.remove(); + } }, }; }; diff --git a/plugins/postcss-normalize-display-values/src/mappings.ts b/plugins/postcss-normalize-display-values/src/mappings.ts index 05396e69f..0ead25f91 100644 --- a/plugins/postcss-normalize-display-values/src/mappings.ts +++ b/plugins/postcss-normalize-display-values/src/mappings.ts @@ -2,22 +2,22 @@ * Specification: https://www.w3.org/TR/css-display-3/#the-display-properties */ export default new Map([ + ['block,flex', 'flex'], ['block,flow', 'block'], ['block,flow-root', 'flow-root'], + ['block,grid', 'grid'], + ['block,table', 'table'], + ['inline,flex', 'inline-flex'], ['inline,flow', 'inline'], - ['inline,flow-root', 'inline-block'], - ['run-in,flow', 'run-in'], - ['list-item,block,flow', 'list-item'], ['inline,flow,list-item', 'inline list-item'], - ['block,flex', 'flex'], - ['inline,flex', 'inline-flex'], - ['block,grid', 'grid'], + ['inline,flow-root', 'inline-block'], ['inline,grid', 'inline-grid'], ['inline,ruby', 'ruby'], - ['block,table', 'table'], ['inline,table', 'inline-table'], - ['table-cell,flow', 'table-cell'], - ['table-caption,flow', 'table-caption'], + ['list-item,block,flow', 'list-item'], ['ruby-base,flow', 'ruby-base'], ['ruby-text,flow', 'ruby-text'], + ['run-in,flow', 'run-in'], + ['table-caption,flow', 'table-caption'], + ['table-cell,flow', 'table-cell'], ]); diff --git a/plugins/postcss-overflow-shorthand/dist/index.cjs b/plugins/postcss-overflow-shorthand/dist/index.cjs index b2ae16318..6b1ec5b34 100644 --- a/plugins/postcss-overflow-shorthand/dist/index.cjs +++ b/plugins/postcss-overflow-shorthand/dist/index.cjs @@ -1 +1 @@ -"use strict";var e=require("postcss-value-parser");const creator=r=>{const o=Object.assign({preserve:!0},r);return{postcssPlugin:"postcss-overflow-shorthand",Declaration(r,{result:s}){if("overflow"!==r.prop.toLowerCase())return;let t="",a="";const l=r.value;try{const r=e(l).nodes.slice().filter((e=>"comment"!==e.type&&"space"!==e.type));if(r.length<2)return;t=e.stringify(r[0]),a=e.stringify(r[1])}catch(e){return void r.warn(s,`Failed to parse value '${l}' as a shorthand for "overflow". Leaving the original value intact.`)}t&&a&&(t.toLowerCase()===a.toLowerCase()?r.cloneBefore({value:t}):(r.cloneBefore({prop:"overflow-x",value:t}),r.cloneBefore({prop:"overflow-y",value:a})),o.preserve||r.remove())}}};creator.postcss=!0,module.exports=creator; +"use strict";var e=require("postcss-value-parser");const creator=r=>{const o=Object.assign({preserve:!0},r);return{postcssPlugin:"postcss-overflow-shorthand",Declaration(r,{result:s}){if("overflow"!==r.prop.toLowerCase())return;let t="",a="";const l=r.value;try{const r=e(l).nodes.slice().filter((e=>"comment"!==e.type&&"space"!==e.type));if(r.length<2)return;t=e.stringify(r[0]),a=e.stringify(r[1])}catch{return void r.warn(s,`Failed to parse value '${l}' as a shorthand for "overflow". Leaving the original value intact.`)}t&&a&&(t.toLowerCase()===a.toLowerCase()?r.cloneBefore({value:t}):(r.cloneBefore({prop:"overflow-x",value:t}),r.cloneBefore({prop:"overflow-y",value:a})),o.preserve||r.remove())}}};creator.postcss=!0,module.exports=creator; diff --git a/plugins/postcss-overflow-shorthand/dist/index.mjs b/plugins/postcss-overflow-shorthand/dist/index.mjs index b044dc559..99bd5b704 100644 --- a/plugins/postcss-overflow-shorthand/dist/index.mjs +++ b/plugins/postcss-overflow-shorthand/dist/index.mjs @@ -1 +1 @@ -import e from"postcss-value-parser";const creator=o=>{const r=Object.assign({preserve:!0},o);return{postcssPlugin:"postcss-overflow-shorthand",Declaration(o,{result:t}){if("overflow"!==o.prop.toLowerCase())return;let s="",a="";const l=o.value;try{const o=e(l).nodes.slice().filter((e=>"comment"!==e.type&&"space"!==e.type));if(o.length<2)return;s=e.stringify(o[0]),a=e.stringify(o[1])}catch(e){return void o.warn(t,`Failed to parse value '${l}' as a shorthand for "overflow". Leaving the original value intact.`)}s&&a&&(s.toLowerCase()===a.toLowerCase()?o.cloneBefore({value:s}):(o.cloneBefore({prop:"overflow-x",value:s}),o.cloneBefore({prop:"overflow-y",value:a})),r.preserve||o.remove())}}};creator.postcss=!0;export{creator as default}; +import e from"postcss-value-parser";const creator=o=>{const r=Object.assign({preserve:!0},o);return{postcssPlugin:"postcss-overflow-shorthand",Declaration(o,{result:t}){if("overflow"!==o.prop.toLowerCase())return;let s="",a="";const l=o.value;try{const o=e(l).nodes.slice().filter((e=>"comment"!==e.type&&"space"!==e.type));if(o.length<2)return;s=e.stringify(o[0]),a=e.stringify(o[1])}catch{return void o.warn(t,`Failed to parse value '${l}' as a shorthand for "overflow". Leaving the original value intact.`)}s&&a&&(s.toLowerCase()===a.toLowerCase()?o.cloneBefore({value:s}):(o.cloneBefore({prop:"overflow-x",value:s}),o.cloneBefore({prop:"overflow-y",value:a})),r.preserve||o.remove())}}};creator.postcss=!0;export{creator as default}; diff --git a/plugins/postcss-overflow-shorthand/src/index.ts b/plugins/postcss-overflow-shorthand/src/index.ts index ccca1a809..21f917399 100644 --- a/plugins/postcss-overflow-shorthand/src/index.ts +++ b/plugins/postcss-overflow-shorthand/src/index.ts @@ -40,7 +40,7 @@ const creator: PluginCreator = (opts?: pluginOptions) => { xValue = valueParser.stringify(relevantNodes[0]); yValue = valueParser.stringify(relevantNodes[1]); - } catch (_) { + } catch { decl.warn( result, `Failed to parse value '${originalValue}' as a shorthand for "overflow". Leaving the original value intact.`, diff --git a/plugins/postcss-place/dist/index.cjs b/plugins/postcss-place/dist/index.cjs index 70e9b45af..a4fb35081 100644 --- a/plugins/postcss-place/dist/index.cjs +++ b/plugins/postcss-place/dist/index.cjs @@ -1 +1 @@ -"use strict";var e=require("postcss-value-parser");function onCSSDeclaration(r,o,s){const n=r.prop.match(t)?.[1].toLowerCase();if(!n)return;let a;try{a=e(r.value)}catch(e){r.warn(o,`Failed to parse value '${r.value}'. Leaving the original value intact.`)}if(void 0===a)return;let i=[];i=a.nodes.length?a.nodes.filter((e=>"word"===e.type||"function"===e.type)).map((t=>e.stringify(t))):[e.stringify(a.nodes)],r.cloneBefore({prop:`align-${n}`,value:i[0]}),r.cloneBefore({prop:`justify-${n}`,value:i[1]||i[0]}),s.preserve||r.remove()}const t=/^place-(content|items|self)/i,creator=e=>{const r=Object.assign({preserve:!0},e);return{postcssPlugin:"postcss-place",Declaration(e,{result:o}){t.test(e.prop)&&onCSSDeclaration(e,o,r)}}};creator.postcss=!0,module.exports=creator; +"use strict";var e=require("postcss-value-parser");function onCSSDeclaration(r,o,s){const n=r.prop.match(t)?.[1].toLowerCase();if(!n)return;let a;try{a=e(r.value)}catch{r.warn(o,`Failed to parse value '${r.value}'. Leaving the original value intact.`)}if(void 0===a)return;let i=[];i=a.nodes.length?a.nodes.filter((e=>"word"===e.type||"function"===e.type)).map((t=>e.stringify(t))):[e.stringify(a.nodes)],r.cloneBefore({prop:`align-${n}`,value:i[0]}),r.cloneBefore({prop:`justify-${n}`,value:i[1]||i[0]}),s.preserve||r.remove()}const t=/^place-(content|items|self)/i,creator=e=>{const r=Object.assign({preserve:!0},e);return{postcssPlugin:"postcss-place",Declaration(e,{result:o}){t.test(e.prop)&&onCSSDeclaration(e,o,r)}}};creator.postcss=!0,module.exports=creator; diff --git a/plugins/postcss-place/dist/index.mjs b/plugins/postcss-place/dist/index.mjs index c54e1cc91..0fd889d12 100644 --- a/plugins/postcss-place/dist/index.mjs +++ b/plugins/postcss-place/dist/index.mjs @@ -1 +1 @@ -import e from"postcss-value-parser";function onCSSDeclaration(o,r,s){const n=o.prop.match(t)?.[1].toLowerCase();if(!n)return;let a;try{a=e(o.value)}catch(e){o.warn(r,`Failed to parse value '${o.value}'. Leaving the original value intact.`)}if(void 0===a)return;let i=[];i=a.nodes.length?a.nodes.filter((e=>"word"===e.type||"function"===e.type)).map((t=>e.stringify(t))):[e.stringify(a.nodes)],o.cloneBefore({prop:`align-${n}`,value:i[0]}),o.cloneBefore({prop:`justify-${n}`,value:i[1]||i[0]}),s.preserve||o.remove()}const t=/^place-(content|items|self)/i,creator=e=>{const o=Object.assign({preserve:!0},e);return{postcssPlugin:"postcss-place",Declaration(e,{result:r}){t.test(e.prop)&&onCSSDeclaration(e,r,o)}}};creator.postcss=!0;export{creator as default}; +import e from"postcss-value-parser";function onCSSDeclaration(o,r,s){const n=o.prop.match(t)?.[1].toLowerCase();if(!n)return;let a;try{a=e(o.value)}catch{o.warn(r,`Failed to parse value '${o.value}'. Leaving the original value intact.`)}if(void 0===a)return;let i=[];i=a.nodes.length?a.nodes.filter((e=>"word"===e.type||"function"===e.type)).map((t=>e.stringify(t))):[e.stringify(a.nodes)],o.cloneBefore({prop:`align-${n}`,value:i[0]}),o.cloneBefore({prop:`justify-${n}`,value:i[1]||i[0]}),s.preserve||o.remove()}const t=/^place-(content|items|self)/i,creator=e=>{const o=Object.assign({preserve:!0},e);return{postcssPlugin:"postcss-place",Declaration(e,{result:r}){t.test(e.prop)&&onCSSDeclaration(e,r,o)}}};creator.postcss=!0;export{creator as default}; diff --git a/plugins/postcss-place/src/on-css-declaration.ts b/plugins/postcss-place/src/on-css-declaration.ts index fe80273ea..3d9daade4 100644 --- a/plugins/postcss-place/src/on-css-declaration.ts +++ b/plugins/postcss-place/src/on-css-declaration.ts @@ -13,7 +13,7 @@ export function onCSSDeclaration(decl: Declaration, result: Result , options: { try { value = valueParser(decl.value); - } catch (_) { + } catch { decl.warn( result, `Failed to parse value '${decl.value}'. Leaving the original value intact.`, diff --git a/plugins/postcss-progressive-custom-properties/dist/index.cjs b/plugins/postcss-progressive-custom-properties/dist/index.cjs index dfa8b1916..09cec2ebf 100644 --- a/plugins/postcss-progressive-custom-properties/dist/index.cjs +++ b/plugins/postcss-progressive-custom-properties/dist/index.cjs @@ -1 +1 @@ -"use strict";var e=require("postcss-value-parser");const a=["at","bottom","center","circle","closest-corner","closest-side","ellipse","farthest-corner","farthest-side","from","in","left","right","to","top"];function doublePositionGradients(e){const r=[],p=e.value.toLowerCase();if("function"===e.type&&("conic-gradient"===p||"linear-gradient"===p||"radial-gradient"===p||"repeating-conic-gradient"===p||"repeating-linear-gradient"===p||"repeating-radial-gradient"===p)){let p=0,t=!1,i=!1;e:for(let o=0;oa.includes(e.sniff)));let s=!1;try{e(a).walk((a=>{"function"===a.type&&p.test(a.value)&&(s=!0);try{const r=e.unit(a.value);!1!==r&&(a.dimension=r)}catch{}for(let e=0;e({postcssPlugin:"postcss-progressive-custom-properties",prepare(){const e=new WeakMap;return{postcssPlugin:"postcss-progressive-custom-properties",OnceExit(a,{postcss:r}){a.walkDecls((a=>{if(!a.parent)return;const p=e.get(a.parent)||{conditionalRules:[],propNames:new Set,lastConditionParams:{support:void 0},lastConditionalRule:void 0};if(e.set(a.parent,p),a.variable){if(!p.propNames.has(a.prop))return void p.propNames.add(a.prop)}else{const e=a.prop.toLowerCase();if(!p.propNames.has(e))return void p.propNames.add(e)}if(!a.variable&&!t.test(a.value))return;if(i.test(a.value))return;if(o.test(a.value))return;const s=!a.variable,l=conditionsFromValue(a.value,s).support.join(" and ");if(!l)return;if(p.lastConditionParams.support!==l&&(p.lastConditionalRule=void 0),p.lastConditionalRule)return p.lastConditionalRule.append(a.clone()),void a.remove();const y=[];if(l&&y.push(r.atRule({name:"supports",params:l,source:a.parent.source,raws:{before:"\n\n",after:"\n"}})),!y.length)return;for(let e=0;e{const r=e.get(a);r&&0!==r.conditionalRules.length&&r.conditionalRules.reverse().forEach((e=>{a.after(e)}))}))}}}});creator.postcss=!0,module.exports=creator; +"use strict";var e=require("postcss-value-parser");const a=["at","bottom","center","circle","closest-corner","closest-side","ellipse","farthest-corner","farthest-side","from","in","left","right","to","top"];function doublePositionGradients(e){const r=[],p=e.value.toLowerCase();if("function"===e.type&&("conic-gradient"===p||"linear-gradient"===p||"radial-gradient"===p||"repeating-conic-gradient"===p||"repeating-linear-gradient"===p||"repeating-radial-gradient"===p)){let p=0,t=!1,i=!1;e:for(let o=0;oa.includes(e.sniff)));let s=!1;try{e(a).walk((a=>{"function"===a.type&&p.test(a.value)&&(s=!0);try{const r=e.unit(a.value);!1!==r&&(a.dimension=r)}catch{}for(let e=0;e({postcssPlugin:"postcss-progressive-custom-properties",prepare(){const e=new WeakMap;return{postcssPlugin:"postcss-progressive-custom-properties",OnceExit(a,{postcss:r}){a.walkDecls((a=>{if(!a.parent)return;const p=e.get(a.parent)||{conditionalRules:[],propNames:new Set,lastConditionParams:{support:void 0},lastConditionalRule:void 0};if(e.set(a.parent,p),a.variable){if(!p.propNames.has(a.prop))return void p.propNames.add(a.prop)}else{const e=a.prop.toLowerCase();if(!p.propNames.has(e))return void p.propNames.add(e)}if(!a.variable&&!t.test(a.value))return;if(i.test(a.value))return;if(o.test(a.value))return;const s=!a.variable,l=conditionsFromValue(a.value,s).support.join(" and ");if(!l)return;if(p.lastConditionParams.support!==l&&(p.lastConditionalRule=void 0),p.lastConditionalRule)return p.lastConditionalRule.append(a.clone()),void a.remove();const y=[];if(l&&y.push(r.atRule({name:"supports",params:l,source:a.parent.source,raws:{before:"\n\n",after:"\n"}})),!y.length)return;for(let e=0;e{const r=e.get(a);r&&0!==r.conditionalRules.length&&r.conditionalRules.reverse().forEach((e=>{a.after(e)}))}))}}}});creator.postcss=!0,module.exports=creator; diff --git a/plugins/postcss-progressive-custom-properties/dist/index.mjs b/plugins/postcss-progressive-custom-properties/dist/index.mjs index f57f664d0..d6b7914da 100644 --- a/plugins/postcss-progressive-custom-properties/dist/index.mjs +++ b/plugins/postcss-progressive-custom-properties/dist/index.mjs @@ -1 +1 @@ -import e from"postcss-value-parser";const a=["at","bottom","center","circle","closest-corner","closest-side","ellipse","farthest-corner","farthest-side","from","in","left","right","to","top"];function doublePositionGradients(e){const r=[],p=e.value.toLowerCase();if("function"===e.type&&("conic-gradient"===p||"linear-gradient"===p||"radial-gradient"===p||"repeating-conic-gradient"===p||"repeating-linear-gradient"===p||"repeating-radial-gradient"===p)){let p=0,t=!1,i=!1;e:for(let o=0;oa.includes(e.sniff)));let s=!1;try{e(a).walk((a=>{"function"===a.type&&p.test(a.value)&&(s=!0);try{const r=e.unit(a.value);!1!==r&&(a.dimension=r)}catch{}for(let e=0;e({postcssPlugin:"postcss-progressive-custom-properties",prepare(){const e=new WeakMap;return{postcssPlugin:"postcss-progressive-custom-properties",OnceExit(a,{postcss:r}){a.walkDecls((a=>{if(!a.parent)return;const p=e.get(a.parent)||{conditionalRules:[],propNames:new Set,lastConditionParams:{support:void 0},lastConditionalRule:void 0};if(e.set(a.parent,p),a.variable){if(!p.propNames.has(a.prop))return void p.propNames.add(a.prop)}else{const e=a.prop.toLowerCase();if(!p.propNames.has(e))return void p.propNames.add(e)}if(!a.variable&&!t.test(a.value))return;if(i.test(a.value))return;if(o.test(a.value))return;const s=!a.variable,l=conditionsFromValue(a.value,s).support.join(" and ");if(!l)return;if(p.lastConditionParams.support!==l&&(p.lastConditionalRule=void 0),p.lastConditionalRule)return p.lastConditionalRule.append(a.clone()),void a.remove();const y=[];if(l&&y.push(r.atRule({name:"supports",params:l,source:a.parent.source,raws:{before:"\n\n",after:"\n"}})),!y.length)return;for(let e=0;e{const r=e.get(a);r&&0!==r.conditionalRules.length&&r.conditionalRules.reverse().forEach((e=>{a.after(e)}))}))}}}});creator.postcss=!0;export{creator as default}; +import e from"postcss-value-parser";const a=["at","bottom","center","circle","closest-corner","closest-side","ellipse","farthest-corner","farthest-side","from","in","left","right","to","top"];function doublePositionGradients(e){const r=[],p=e.value.toLowerCase();if("function"===e.type&&("conic-gradient"===p||"linear-gradient"===p||"radial-gradient"===p||"repeating-conic-gradient"===p||"repeating-linear-gradient"===p||"repeating-radial-gradient"===p)){let p=0,t=!1,i=!1;e:for(let o=0;oa.includes(e.sniff)));let s=!1;try{e(a).walk((a=>{"function"===a.type&&p.test(a.value)&&(s=!0);try{const r=e.unit(a.value);!1!==r&&(a.dimension=r)}catch{}for(let e=0;e({postcssPlugin:"postcss-progressive-custom-properties",prepare(){const e=new WeakMap;return{postcssPlugin:"postcss-progressive-custom-properties",OnceExit(a,{postcss:r}){a.walkDecls((a=>{if(!a.parent)return;const p=e.get(a.parent)||{conditionalRules:[],propNames:new Set,lastConditionParams:{support:void 0},lastConditionalRule:void 0};if(e.set(a.parent,p),a.variable){if(!p.propNames.has(a.prop))return void p.propNames.add(a.prop)}else{const e=a.prop.toLowerCase();if(!p.propNames.has(e))return void p.propNames.add(e)}if(!a.variable&&!t.test(a.value))return;if(i.test(a.value))return;if(o.test(a.value))return;const s=!a.variable,l=conditionsFromValue(a.value,s).support.join(" and ");if(!l)return;if(p.lastConditionParams.support!==l&&(p.lastConditionalRule=void 0),p.lastConditionalRule)return p.lastConditionalRule.append(a.clone()),void a.remove();const y=[];if(l&&y.push(r.atRule({name:"supports",params:l,source:a.parent.source,raws:{before:"\n\n",after:"\n"}})),!y.length)return;for(let e=0;e{const r=e.get(a);r&&0!==r.conditionalRules.length&&r.conditionalRules.reverse().forEach((e=>{a.after(e)}))}))}}}});creator.postcss=!0;export{creator as default}; diff --git a/plugins/postcss-progressive-custom-properties/scripts/matcher-for-value.mjs b/plugins/postcss-progressive-custom-properties/scripts/matcher-for-value.mjs index 0775344b7..84d57acbf 100644 --- a/plugins/postcss-progressive-custom-properties/scripts/matcher-for-value.mjs +++ b/plugins/postcss-progressive-custom-properties/scripts/matcher-for-value.mjs @@ -33,7 +33,7 @@ export function matcherForValue(value) { } else { return ast.nodes; } - } catch (_) { + } catch { /* ignore */ } } diff --git a/plugins/postcss-progressive-custom-properties/src/conditions-from-values.ts b/plugins/postcss-progressive-custom-properties/src/conditions-from-values.ts index ed488d8d2..f647b7ca8 100644 --- a/plugins/postcss-progressive-custom-properties/src/conditions-from-values.ts +++ b/plugins/postcss-progressive-custom-properties/src/conditions-from-values.ts @@ -46,7 +46,7 @@ export function conditionsFromValue(value: string, mustContainVar = false): { su supportConditions.push(...doublePositionGradients(node)); }); - } catch (_) { + } catch { /* ignore */ } diff --git a/plugins/postcss-progressive-custom-properties/src/index.ts b/plugins/postcss-progressive-custom-properties/src/index.ts index 5b08697e5..7eaf398df 100644 --- a/plugins/postcss-progressive-custom-properties/src/index.ts +++ b/plugins/postcss-progressive-custom-properties/src/index.ts @@ -119,6 +119,7 @@ const creator: PluginCreator = () => { const parentClone = decl.parent.clone(); parentClone.removeAll(); + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access parentClone.raws.before = '\n'; parentClone.append(decl.clone()); diff --git a/plugins/postcss-progressive-custom-properties/src/matchers.ts b/plugins/postcss-progressive-custom-properties/src/matchers.ts index ed23ab063..08ac72588 100644 --- a/plugins/postcss-progressive-custom-properties/src/matchers.ts +++ b/plugins/postcss-progressive-custom-properties/src/matchers.ts @@ -1,2585 +1,2585 @@ export const matchers = [ { - 'supports': 'color-mix(in lch, red, blue)', - 'property': 'color', - 'sniff': 'color-mix', - 'matchers': [ + "supports": "color-mix(in lch, red, blue)", + "property": "color", + "sniff": "color-mix", + "matchers": [ { - 'type': 'function', - 'value': 'color-mix', - 'nodes': [ + "type": "function", + "value": "color-mix", + "nodes": [ { - 'type': 'word', - 'value': 'in', + "type": "word", + "value": "in" }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'div', - 'value': ',', + "type": "div", + "value": "," }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'div', - 'value': ',', + "type": "div", + "value": "," }, { - 'type': 'word', - 'isVariable': true, - }, - ], + "type": "word", + "isVariable": true + } + ] }, { - 'type': 'function', - 'value': 'color-mix', - 'nodes': [ + "type": "function", + "value": "color-mix", + "nodes": [ { - 'type': 'word', - 'value': 'in', + "type": "word", + "value": "in" }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'div', - 'value': ',', + "type": "div", + "value": "," }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'div', - 'value': ',', + "type": "div", + "value": "," }, { - 'type': 'word', - 'isVariable': true, - }, - ], + "type": "word", + "isVariable": true + } + ] }, { - 'type': 'function', - 'value': 'color-mix', - 'nodes': [ + "type": "function", + "value": "color-mix", + "nodes": [ { - 'type': 'word', - 'value': 'in', + "type": "word", + "value": "in" }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'div', - 'value': ',', + "type": "div", + "value": "," }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'div', - 'value': ',', + "type": "div", + "value": "," }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, - }, - ], + "type": "word", + "isVariable": true + } + ] }, { - 'type': 'function', - 'value': 'color-mix', - 'nodes': [ + "type": "function", + "value": "color-mix", + "nodes": [ { - 'type': 'word', - 'value': 'in', + "type": "word", + "value": "in" }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'div', - 'value': ',', + "type": "div", + "value": "," }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'div', - 'value': ',', + "type": "div", + "value": "," }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, - }, - ], + "type": "word", + "isVariable": true + } + ] }, { - 'type': 'function', - 'value': 'color-mix', - 'nodes': [ + "type": "function", + "value": "color-mix", + "nodes": [ { - 'type': 'word', - 'value': 'in', + "type": "word", + "value": "in" }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'div', - 'value': ',', + "type": "div", + "value": "," }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'div', - 'value': ',', + "type": "div", + "value": "," }, { - 'type': 'word', - 'isVariable': true, - }, - ], + "type": "word", + "isVariable": true + } + ] }, { - 'type': 'function', - 'value': 'color-mix', - 'nodes': [ + "type": "function", + "value": "color-mix", + "nodes": [ { - 'type': 'word', - 'value': 'in', + "type": "word", + "value": "in" }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'div', - 'value': ',', + "type": "div", + "value": "," }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'div', - 'value': ',', + "type": "div", + "value": "," }, { - 'type': 'word', - 'isVariable': true, - }, - ], + "type": "word", + "isVariable": true + } + ] }, { - 'type': 'function', - 'value': 'color-mix', - 'nodes': [ + "type": "function", + "value": "color-mix", + "nodes": [ { - 'type': 'word', - 'value': 'in', + "type": "word", + "value": "in" }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'div', - 'value': ',', + "type": "div", + "value": "," }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'div', - 'value': ',', + "type": "div", + "value": "," }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, - }, - ], + "type": "word", + "isVariable": true + } + ] }, { - 'type': 'function', - 'value': 'color-mix', - 'nodes': [ + "type": "function", + "value": "color-mix", + "nodes": [ { - 'type': 'word', - 'value': 'in', + "type": "word", + "value": "in" }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'div', - 'value': ',', + "type": "div", + "value": "," }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'div', - 'value': ',', + "type": "div", + "value": "," }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, - }, - ], - }, - ], + "type": "word", + "isVariable": true + } + ] + } + ] }, { - 'supports': 'lab(from red l 1 1% / calc(alpha + 0.1))', - 'property': 'color', - 'sniff': 'from ', - 'matchers': [ + "supports": "lab(from red l 1 1% / calc(alpha + 0.1))", + "property": "color", + "sniff": "from ", + "matchers": [ { - 'type': 'function', - 'value': 'rgb', - 'nodes': [ + "type": "function", + "value": "rgb", + "nodes": [ { - 'type': 'word', - 'value': 'from', + "type": "word", + "value": "from" }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, - }, - ], + "type": "word", + "isVariable": true + } + ] }, { - 'type': 'function', - 'value': 'rgb', - 'nodes': [ + "type": "function", + "value": "rgb", + "nodes": [ { - 'type': 'word', - 'value': 'from', + "type": "word", + "value": "from" }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'div', - 'value': '/', + "type": "div", + "value": "/" }, { - 'type': 'word', - 'isVariable': true, - }, - ], + "type": "word", + "isVariable": true + } + ] }, { - 'type': 'function', - 'value': 'rgba', - 'nodes': [ + "type": "function", + "value": "rgba", + "nodes": [ { - 'type': 'word', - 'value': 'from', + "type": "word", + "value": "from" }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, - }, - ], + "type": "word", + "isVariable": true + } + ] }, { - 'type': 'function', - 'value': 'rgba', - 'nodes': [ + "type": "function", + "value": "rgba", + "nodes": [ { - 'type': 'word', - 'value': 'from', + "type": "word", + "value": "from" }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'div', - 'value': '/', + "type": "div", + "value": "/" }, { - 'type': 'word', - 'isVariable': true, - }, - ], + "type": "word", + "isVariable": true + } + ] }, { - 'type': 'function', - 'value': 'hsl', - 'nodes': [ + "type": "function", + "value": "hsl", + "nodes": [ { - 'type': 'word', - 'value': 'from', + "type": "word", + "value": "from" }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, - }, - ], + "type": "word", + "isVariable": true + } + ] }, { - 'type': 'function', - 'value': 'hsl', - 'nodes': [ + "type": "function", + "value": "hsl", + "nodes": [ { - 'type': 'word', - 'value': 'from', + "type": "word", + "value": "from" }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'div', - 'value': '/', + "type": "div", + "value": "/" }, { - 'type': 'word', - 'isVariable': true, - }, - ], + "type": "word", + "isVariable": true + } + ] }, { - 'type': 'function', - 'value': 'hsla', - 'nodes': [ + "type": "function", + "value": "hsla", + "nodes": [ { - 'type': 'word', - 'value': 'from', + "type": "word", + "value": "from" }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, - }, - ], + "type": "word", + "isVariable": true + } + ] }, { - 'type': 'function', - 'value': 'hsla', - 'nodes': [ + "type": "function", + "value": "hsla", + "nodes": [ { - 'type': 'word', - 'value': 'from', + "type": "word", + "value": "from" }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'div', - 'value': '/', + "type": "div", + "value": "/" }, { - 'type': 'word', - 'isVariable': true, - }, - ], + "type": "word", + "isVariable": true + } + ] }, { - 'type': 'function', - 'value': 'hwb', - 'nodes': [ + "type": "function", + "value": "hwb", + "nodes": [ { - 'type': 'word', - 'value': 'from', + "type": "word", + "value": "from" }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, - }, - ], + "type": "word", + "isVariable": true + } + ] }, { - 'type': 'function', - 'value': 'hwb', - 'nodes': [ + "type": "function", + "value": "hwb", + "nodes": [ { - 'type': 'word', - 'value': 'from', + "type": "word", + "value": "from" }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'div', - 'value': '/', + "type": "div", + "value": "/" }, { - 'type': 'word', - 'isVariable': true, - }, - ], + "type": "word", + "isVariable": true + } + ] }, { - 'type': 'function', - 'value': 'lch', - 'nodes': [ + "type": "function", + "value": "lch", + "nodes": [ { - 'type': 'word', - 'value': 'from', + "type": "word", + "value": "from" }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, - }, - ], + "type": "word", + "isVariable": true + } + ] }, { - 'type': 'function', - 'value': 'lch', - 'nodes': [ + "type": "function", + "value": "lch", + "nodes": [ { - 'type': 'word', - 'value': 'from', + "type": "word", + "value": "from" }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'div', - 'value': '/', + "type": "div", + "value": "/" }, { - 'type': 'word', - 'isVariable': true, - }, - ], + "type": "word", + "isVariable": true + } + ] }, { - 'type': 'function', - 'value': 'oklch', - 'nodes': [ + "type": "function", + "value": "oklch", + "nodes": [ { - 'type': 'word', - 'value': 'from', + "type": "word", + "value": "from" }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, - }, - ], + "type": "word", + "isVariable": true + } + ] }, { - 'type': 'function', - 'value': 'oklch', - 'nodes': [ + "type": "function", + "value": "oklch", + "nodes": [ { - 'type': 'word', - 'value': 'from', + "type": "word", + "value": "from" }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'div', - 'value': '/', + "type": "div", + "value": "/" }, { - 'type': 'word', - 'isVariable': true, - }, - ], + "type": "word", + "isVariable": true + } + ] }, { - 'type': 'function', - 'value': 'lab', - 'nodes': [ + "type": "function", + "value": "lab", + "nodes": [ { - 'type': 'word', - 'value': 'from', + "type": "word", + "value": "from" }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, - }, - ], + "type": "word", + "isVariable": true + } + ] }, { - 'type': 'function', - 'value': 'lab', - 'nodes': [ + "type": "function", + "value": "lab", + "nodes": [ { - 'type': 'word', - 'value': 'from', + "type": "word", + "value": "from" }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'div', - 'value': '/', + "type": "div", + "value": "/" }, { - 'type': 'word', - 'isVariable': true, - }, - ], + "type": "word", + "isVariable": true + } + ] }, { - 'type': 'function', - 'value': 'oklab', - 'nodes': [ + "type": "function", + "value": "oklab", + "nodes": [ { - 'type': 'word', - 'value': 'from', + "type": "word", + "value": "from" }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, - }, - ], + "type": "word", + "isVariable": true + } + ] }, { - 'type': 'function', - 'value': 'oklab', - 'nodes': [ + "type": "function", + "value": "oklab", + "nodes": [ { - 'type': 'word', - 'value': 'from', + "type": "word", + "value": "from" }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'div', - 'value': '/', + "type": "div", + "value": "/" }, { - 'type': 'word', - 'isVariable': true, - }, - ], + "type": "word", + "isVariable": true + } + ] }, { - 'type': 'function', - 'value': 'color', - 'nodes': [ + "type": "function", + "value": "color", + "nodes": [ { - 'type': 'word', - 'value': 'from', + "type": "word", + "value": "from" }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, - }, - ], + "type": "word", + "isVariable": true + } + ] }, { - 'type': 'function', - 'value': 'color', - 'nodes': [ + "type": "function", + "value": "color", + "nodes": [ { - 'type': 'word', - 'value': 'from', + "type": "word", + "value": "from" }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'div', - 'value': '/', + "type": "div", + "value": "/" }, { - 'type': 'word', - 'isVariable': true, - }, - ], - }, - ], + "type": "word", + "isVariable": true + } + ] + } + ] }, { - 'supports': 'color(display-p3 0 0 0%)', - 'property': 'color', - 'sniff': 'color', - 'matchers': [ + "supports": "color(display-p3 0 0 0%)", + "property": "color", + "sniff": "color", + "matchers": [ { - 'type': 'function', - 'value': 'color', - 'nodes': [ + "type": "function", + "value": "color", + "nodes": [ { - 'type': 'word', - 'value': 'srgb', + "type": "word", + "value": "srgb" }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, - }, - ], + "type": "word", + "isVariable": true + } + ] }, { - 'type': 'function', - 'value': 'color', - 'nodes': [ + "type": "function", + "value": "color", + "nodes": [ { - 'type': 'word', - 'value': 'srgb', + "type": "word", + "value": "srgb" }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'div', - 'value': '/', + "type": "div", + "value": "/" }, { - 'type': 'word', - 'isVariable': true, - }, - ], - }, - ], + "type": "word", + "isVariable": true + } + ] + } + ] }, { - 'supports': 'color(display-p3 0 0 0%)', - 'property': 'color', - 'sniff': 'color', - 'matchers': [ + "supports": "color(display-p3 0 0 0%)", + "property": "color", + "sniff": "color", + "matchers": [ { - 'type': 'function', - 'value': 'color', - 'nodes': [ + "type": "function", + "value": "color", + "nodes": [ { - 'type': 'word', - 'value': 'display-p3', + "type": "word", + "value": "display-p3" }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, - }, - ], + "type": "word", + "isVariable": true + } + ] }, { - 'type': 'function', - 'value': 'color', - 'nodes': [ + "type": "function", + "value": "color", + "nodes": [ { - 'type': 'word', - 'value': 'display-p3', + "type": "word", + "value": "display-p3" }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'div', - 'value': '/', + "type": "div", + "value": "/" }, { - 'type': 'word', - 'isVariable': true, - }, - ], - }, - ], + "type": "word", + "isVariable": true + } + ] + } + ] }, { - 'supports': 'color(xyz 0 0 0%)', - 'property': 'color', - 'sniff': 'color', - 'matchers': [ + "supports": "color(xyz 0 0 0%)", + "property": "color", + "sniff": "color", + "matchers": [ { - 'type': 'function', - 'value': 'color', - 'nodes': [ + "type": "function", + "value": "color", + "nodes": [ { - 'type': 'word', - 'value': 'srgb-linear', + "type": "word", + "value": "srgb-linear" }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, - }, - ], + "type": "word", + "isVariable": true + } + ] }, { - 'type': 'function', - 'value': 'color', - 'nodes': [ + "type": "function", + "value": "color", + "nodes": [ { - 'type': 'word', - 'value': 'srgb-linear', + "type": "word", + "value": "srgb-linear" }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'div', - 'value': '/', + "type": "div", + "value": "/" }, { - 'type': 'word', - 'isVariable': true, - }, - ], - }, - ], + "type": "word", + "isVariable": true + } + ] + } + ] }, { - 'supports': 'color(xyz 0 0 0%)', - 'property': 'color', - 'sniff': 'color', - 'matchers': [ + "supports": "color(xyz 0 0 0%)", + "property": "color", + "sniff": "color", + "matchers": [ { - 'type': 'function', - 'value': 'color', - 'nodes': [ + "type": "function", + "value": "color", + "nodes": [ { - 'type': 'word', - 'value': 'a98-rgb', + "type": "word", + "value": "a98-rgb" }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, - }, - ], + "type": "word", + "isVariable": true + } + ] }, { - 'type': 'function', - 'value': 'color', - 'nodes': [ + "type": "function", + "value": "color", + "nodes": [ { - 'type': 'word', - 'value': 'a98-rgb', + "type": "word", + "value": "a98-rgb" }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'div', - 'value': '/', + "type": "div", + "value": "/" }, { - 'type': 'word', - 'isVariable': true, - }, - ], - }, - ], + "type": "word", + "isVariable": true + } + ] + } + ] }, { - 'supports': 'color(xyz 0 0 0%)', - 'property': 'color', - 'sniff': 'color', - 'matchers': [ + "supports": "color(xyz 0 0 0%)", + "property": "color", + "sniff": "color", + "matchers": [ { - 'type': 'function', - 'value': 'color', - 'nodes': [ + "type": "function", + "value": "color", + "nodes": [ { - 'type': 'word', - 'value': 'prophoto-rgb', + "type": "word", + "value": "prophoto-rgb" }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, - }, - ], + "type": "word", + "isVariable": true + } + ] }, { - 'type': 'function', - 'value': 'color', - 'nodes': [ + "type": "function", + "value": "color", + "nodes": [ { - 'type': 'word', - 'value': 'prophoto-rgb', + "type": "word", + "value": "prophoto-rgb" }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'div', - 'value': '/', + "type": "div", + "value": "/" }, { - 'type': 'word', - 'isVariable': true, - }, - ], - }, - ], + "type": "word", + "isVariable": true + } + ] + } + ] }, { - 'supports': 'color(xyz 0 0 0%)', - 'property': 'color', - 'sniff': 'color', - 'matchers': [ + "supports": "color(xyz 0 0 0%)", + "property": "color", + "sniff": "color", + "matchers": [ { - 'type': 'function', - 'value': 'color', - 'nodes': [ + "type": "function", + "value": "color", + "nodes": [ { - 'type': 'word', - 'value': 'rec2020', + "type": "word", + "value": "rec2020" }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, - }, - ], + "type": "word", + "isVariable": true + } + ] }, { - 'type': 'function', - 'value': 'color', - 'nodes': [ + "type": "function", + "value": "color", + "nodes": [ { - 'type': 'word', - 'value': 'rec2020', + "type": "word", + "value": "rec2020" }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'div', - 'value': '/', + "type": "div", + "value": "/" }, { - 'type': 'word', - 'isVariable': true, - }, - ], - }, - ], + "type": "word", + "isVariable": true + } + ] + } + ] }, { - 'supports': 'color(xyz 0 0 0%)', - 'property': 'color', - 'sniff': 'color', - 'matchers': [ + "supports": "color(xyz 0 0 0%)", + "property": "color", + "sniff": "color", + "matchers": [ { - 'type': 'function', - 'value': 'color', - 'nodes': [ + "type": "function", + "value": "color", + "nodes": [ { - 'type': 'word', - 'value': 'xyz-d50', + "type": "word", + "value": "xyz-d50" }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, - }, - ], + "type": "word", + "isVariable": true + } + ] }, { - 'type': 'function', - 'value': 'color', - 'nodes': [ + "type": "function", + "value": "color", + "nodes": [ { - 'type': 'word', - 'value': 'xyz-d50', + "type": "word", + "value": "xyz-d50" }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'div', - 'value': '/', + "type": "div", + "value": "/" }, { - 'type': 'word', - 'isVariable': true, - }, - ], - }, - ], + "type": "word", + "isVariable": true + } + ] + } + ] }, { - 'supports': 'color(xyz 0 0 0%)', - 'property': 'color', - 'sniff': 'color', - 'matchers': [ + "supports": "color(xyz 0 0 0%)", + "property": "color", + "sniff": "color", + "matchers": [ { - 'type': 'function', - 'value': 'color', - 'nodes': [ + "type": "function", + "value": "color", + "nodes": [ { - 'type': 'word', - 'value': 'xyz-d65', + "type": "word", + "value": "xyz-d65" }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, - }, - ], + "type": "word", + "isVariable": true + } + ] }, { - 'type': 'function', - 'value': 'color', - 'nodes': [ + "type": "function", + "value": "color", + "nodes": [ { - 'type': 'word', - 'value': 'xyz-d65', + "type": "word", + "value": "xyz-d65" }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'div', - 'value': '/', + "type": "div", + "value": "/" }, { - 'type': 'word', - 'isVariable': true, - }, - ], - }, - ], + "type": "word", + "isVariable": true + } + ] + } + ] }, { - 'supports': 'color(xyz 0 0 0%)', - 'property': 'color', - 'sniff': 'color', - 'matchers': [ + "supports": "color(xyz 0 0 0%)", + "property": "color", + "sniff": "color", + "matchers": [ { - 'type': 'function', - 'value': 'color', - 'nodes': [ + "type": "function", + "value": "color", + "nodes": [ { - 'type': 'word', - 'value': 'xyz', + "type": "word", + "value": "xyz" }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, - }, - ], + "type": "word", + "isVariable": true + } + ] }, { - 'type': 'function', - 'value': 'color', - 'nodes': [ + "type": "function", + "value": "color", + "nodes": [ { - 'type': 'word', - 'value': 'xyz', + "type": "word", + "value": "xyz" }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'div', - 'value': '/', + "type": "div", + "value": "/" }, { - 'type': 'word', - 'isVariable': true, - }, - ], - }, - ], + "type": "word", + "isVariable": true + } + ] + } + ] }, { - 'supports': 'hsl(0, 0%, 0%)', - 'property': 'color', - 'sniff': 'hsl', - 'matchers': [ + "supports": "hsl(0, 0%, 0%)", + "property": "color", + "sniff": "hsl", + "matchers": [ { - 'type': 'function', - 'value': 'hsl', - 'nodes': [ + "type": "function", + "value": "hsl", + "nodes": [ { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'div', - 'value': ',', + "type": "div", + "value": "," }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'div', - 'value': ',', + "type": "div", + "value": "," }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'div', - 'value': ',', + "type": "div", + "value": "," }, { - 'type': 'word', - 'isVariable': true, - }, - ], - }, - ], + "type": "word", + "isVariable": true + } + ] + } + ] }, { - 'supports': 'hsl(0 0% 0% / 0)', - 'property': 'color', - 'sniff': 'hsl', - 'matchers': [ + "supports": "hsl(0 0% 0% / 0)", + "property": "color", + "sniff": "hsl", + "matchers": [ { - 'type': 'function', - 'value': 'hsl', - 'nodes': [ + "type": "function", + "value": "hsl", + "nodes": [ { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, - }, - ], + "type": "word", + "isVariable": true + } + ] }, { - 'type': 'function', - 'value': 'hsl', - 'nodes': [ + "type": "function", + "value": "hsl", + "nodes": [ { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'div', - 'value': '/', + "type": "div", + "value": "/" }, { - 'type': 'word', - 'isVariable': true, - }, - ], - }, - ], + "type": "word", + "isVariable": true + } + ] + } + ] }, { - 'supports': 'hsla(0 0% 0% / 0)', - 'property': 'color', - 'sniff': 'hsla', - 'matchers': [ + "supports": "hsla(0 0% 0% / 0)", + "property": "color", + "sniff": "hsla", + "matchers": [ { - 'type': 'function', - 'value': 'hsla', - 'nodes': [ + "type": "function", + "value": "hsla", + "nodes": [ { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'div', - 'value': '/', + "type": "div", + "value": "/" }, { - 'type': 'word', - 'isVariable': true, - }, - ], - }, - ], + "type": "word", + "isVariable": true + } + ] + } + ] }, { - 'supports': 'hwb(0 0% 0%)', - 'property': 'color', - 'sniff': 'hwb', - 'matchers': [ + "supports": "hwb(0 0% 0%)", + "property": "color", + "sniff": "hwb", + "matchers": [ { - 'type': 'function', - 'value': 'hwb', - 'nodes': [ + "type": "function", + "value": "hwb", + "nodes": [ { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, - }, - ], + "type": "word", + "isVariable": true + } + ] }, { - 'type': 'function', - 'value': 'hwb', - 'nodes': [ + "type": "function", + "value": "hwb", + "nodes": [ { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'div', - 'value': '/', + "type": "div", + "value": "/" }, { - 'type': 'word', - 'isVariable': true, - }, - ], - }, - ], + "type": "word", + "isVariable": true + } + ] + } + ] }, { - 'supports': 'lab(0% 0 0%)', - 'property': 'color', - 'sniff': 'lab', - 'matchers': [ + "supports": "lab(0% 0 0%)", + "property": "color", + "sniff": "lab", + "matchers": [ { - 'type': 'function', - 'value': 'lab', - 'nodes': [ + "type": "function", + "value": "lab", + "nodes": [ { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, - }, - ], + "type": "word", + "isVariable": true + } + ] }, { - 'type': 'function', - 'value': 'lab', - 'nodes': [ + "type": "function", + "value": "lab", + "nodes": [ { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'div', - 'value': '/', + "type": "div", + "value": "/" }, { - 'type': 'word', - 'isVariable': true, - }, - ], - }, - ], + "type": "word", + "isVariable": true + } + ] + } + ] }, { - 'supports': 'lab(0% 0 0%)', - 'property': 'color', - 'sniff': 'lch', - 'matchers': [ + "supports": "lab(0% 0 0%)", + "property": "color", + "sniff": "lch", + "matchers": [ { - 'type': 'function', - 'value': 'lch', - 'nodes': [ + "type": "function", + "value": "lch", + "nodes": [ { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, - }, - ], + "type": "word", + "isVariable": true + } + ] }, { - 'type': 'function', - 'value': 'lch', - 'nodes': [ + "type": "function", + "value": "lch", + "nodes": [ { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'div', - 'value': '/', + "type": "div", + "value": "/" }, { - 'type': 'word', - 'isVariable': true, - }, - ], - }, - ], + "type": "word", + "isVariable": true + } + ] + } + ] }, { - 'supports': 'oklab(0% 0 0%)', - 'property': 'color', - 'sniff': 'oklab', - 'matchers': [ + "supports": "oklab(0% 0 0%)", + "property": "color", + "sniff": "oklab", + "matchers": [ { - 'type': 'function', - 'value': 'oklab', - 'nodes': [ + "type": "function", + "value": "oklab", + "nodes": [ { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, - }, - ], + "type": "word", + "isVariable": true + } + ] }, { - 'type': 'function', - 'value': 'oklab', - 'nodes': [ + "type": "function", + "value": "oklab", + "nodes": [ { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'div', - 'value': '/', + "type": "div", + "value": "/" }, { - 'type': 'word', - 'isVariable': true, - }, - ], - }, - ], + "type": "word", + "isVariable": true + } + ] + } + ] }, { - 'supports': 'oklab(0% 0 0%)', - 'property': 'color', - 'sniff': 'oklch', - 'matchers': [ + "supports": "oklab(0% 0 0%)", + "property": "color", + "sniff": "oklch", + "matchers": [ { - 'type': 'function', - 'value': 'oklch', - 'nodes': [ + "type": "function", + "value": "oklch", + "nodes": [ { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, - }, - ], + "type": "word", + "isVariable": true + } + ] }, { - 'type': 'function', - 'value': 'oklch', - 'nodes': [ + "type": "function", + "value": "oklch", + "nodes": [ { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'div', - 'value': '/', + "type": "div", + "value": "/" }, { - 'type': 'word', - 'isVariable': true, - }, - ], - }, - ], + "type": "word", + "isVariable": true + } + ] + } + ] }, { - 'supports': 'rgb(0, 0, 0, 0)', - 'property': 'color', - 'sniff': 'rgb', - 'matchers': [ + "supports": "rgb(0, 0, 0, 0)", + "property": "color", + "sniff": "rgb", + "matchers": [ { - 'type': 'function', - 'value': 'rgb', - 'nodes': [ + "type": "function", + "value": "rgb", + "nodes": [ { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'div', - 'value': ',', + "type": "div", + "value": "," }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'div', - 'value': ',', + "type": "div", + "value": "," }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'div', - 'value': ',', + "type": "div", + "value": "," }, { - 'type': 'word', - 'isVariable': true, - }, - ], - }, - ], + "type": "word", + "isVariable": true + } + ] + } + ] }, { - 'supports': 'rgb(0 0 0 / 0)', - 'property': 'color', - 'sniff': 'rgb', - 'matchers': [ + "supports": "rgb(0 0 0 / 0)", + "property": "color", + "sniff": "rgb", + "matchers": [ { - 'type': 'function', - 'value': 'rgb', - 'nodes': [ + "type": "function", + "value": "rgb", + "nodes": [ { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, - }, - ], + "type": "word", + "isVariable": true + } + ] }, { - 'type': 'function', - 'value': 'rgb', - 'nodes': [ + "type": "function", + "value": "rgb", + "nodes": [ { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'div', - 'value': '/', + "type": "div", + "value": "/" }, { - 'type': 'word', - 'isVariable': true, - }, - ], - }, - ], + "type": "word", + "isVariable": true + } + ] + } + ] }, { - 'supports': 'rgba(0 0 0 / 0)', - 'property': 'color', - 'sniff': 'rgba', - 'matchers': [ + "supports": "rgba(0 0 0 / 0)", + "property": "color", + "sniff": "rgba", + "matchers": [ { - 'type': 'function', - 'value': 'rgba', - 'nodes': [ + "type": "function", + "value": "rgba", + "nodes": [ { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'div', - 'value': '/', + "type": "div", + "value": "/" }, { - 'type': 'word', - 'isVariable': true, - }, - ], - }, - ], + "type": "word", + "isVariable": true + } + ] + } + ] }, { - 'supports': 'light-dark(red, red)', - 'property': 'color', - 'sniff': 'light-dark', - 'matchers': [ + "supports": "light-dark(red, red)", + "property": "color", + "sniff": "light-dark", + "matchers": [ { - 'type': 'function', - 'value': 'light-dark', - 'nodes': [ + "type": "function", + "value": "light-dark", + "nodes": [ { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'div', - 'value': ',', + "type": "div", + "value": "," }, { - 'type': 'word', - 'isVariable': true, - }, - ], - }, - ], + "type": "word", + "isVariable": true + } + ] + } + ] }, { - 'supports': 'contrast-color(red max)', - 'property': 'color', - 'sniff': 'contrast-color', - 'matchers': [ + "supports": "contrast-color(red max)", + "property": "color", + "sniff": "contrast-color", + "matchers": [ { - 'type': 'function', - 'value': 'contrast-color', - 'nodes': [ + "type": "function", + "value": "contrast-color", + "nodes": [ { - 'type': 'word', - 'isVariable': true, - }, - ], + "type": "word", + "isVariable": true + } + ] }, { - 'type': 'function', - 'value': 'contrast-color', - 'nodes': [ + "type": "function", + "value": "contrast-color", + "nodes": [ { - 'type': 'word', - 'isVariable': true, + "type": "word", + "isVariable": true }, { - 'type': 'space', + "type": "space" }, { - 'type': 'word', - 'isVariable': true, - }, - ], - }, - ], + "type": "word", + "isVariable": true + } + ] + } + ] }, { - 'supports': '1ic', - 'property': 'font-size', - 'sniff': 'ic', - 'matchers': [ - { - 'type': 'word', - 'value': '1ic', - 'dimension': { - 'unit': 'ic', - }, - }, - ], - }, -]; \ No newline at end of file + "supports": "1ic", + "property": "font-size", + "sniff": "ic", + "matchers": [ + { + "type": "word", + "value": "1ic", + "dimension": { + "unit": "ic" + } + } + ] + } +] \ No newline at end of file diff --git a/plugins/postcss-pseudo-class-any-link/dist/index.cjs b/plugins/postcss-pseudo-class-any-link/dist/index.cjs index 1f8f74148..b2185c05a 100644 --- a/plugins/postcss-pseudo-class-any-link/dist/index.cjs +++ b/plugins/postcss-pseudo-class-any-link/dist/index.cjs @@ -1 +1 @@ -"use strict";var e=require("postcss-selector-parser");const t=e().astSync(":link").nodes[0],s=e().astSync(":visited").nodes[0],n=e().astSync("area[href]").nodes[0],o=e().astSync("[href]").nodes[0];function replaceAnyLink(e,t,s,n){const o=[],r=[];try{for(let t=0;t{const r=[];if(e.walkPseudos((e=>{if(":not"===e.value.toLowerCase())return!1;if(":any-link"!==e.value.toLowerCase()||e.nodes&&e.nodes.length)return;if(!l)return void r.push([t.clone(),s.clone()]);const c=getTagElementsNextToPseudo(e);c.includes("area")?r.push([t.clone(),s.clone(),o.clone()]):c.length?r.push([t.clone(),s.clone()]):r.push([t.clone(),s.clone(),n.clone()])})),!r.length)return;cartesianProduct(...r).forEach((t=>{const s=e.clone();s.walkPseudos((e=>{":any-link"!==e.value.toLowerCase()||e.nodes&&e.nodes.length||(insertNode(e.parent,e,t.shift()),e.remove())})),c.push(s.toString())}))})).processSync(r),c}function cartesianProduct(...e){const t=[],s=e.length-1;return function helper(n,o){for(let r=0,l=e[o].length;r=0&&("combinator"!==t.nodes[s].type&&!e.isPseudoElement(t.nodes[s].type));s--)r=s;if("tag"!==o){for(let s=c;s{const t={preserve:!0,...e},s={areaHrefNeedsFixing:!1,...Object(t.subFeatures)};return{postcssPlugin:"postcss-pseudo-class-any-link",prepare(){const e=new WeakSet;return{postcssPlugin:"postcss-pseudo-class-any-link",Rule(n,{result:o}){if(!n.selector.toLowerCase().includes(":any-link"))return;if(e.has(n))return;if((n.raws.selector&&n.raws.selector.raw||n.selector).endsWith(":"))return;replaceAnyLink(n,o,t.preserve,s.areaHrefNeedsFixing)&&e.add(n)}}}}};creator.postcss=!0,module.exports=creator; +"use strict";var e=require("postcss-selector-parser");const t=e().astSync(":link").nodes[0],s=e().astSync(":visited").nodes[0],n=e().astSync("area[href]").nodes[0],o=e().astSync("[href]").nodes[0];function replaceAnyLink(e,t,s,n){const o=[],r=[];try{for(let t=0;t{const r=[];if(e.walkPseudos((e=>{if(":not"===e.value.toLowerCase())return!1;if(":any-link"!==e.value.toLowerCase()||e.nodes&&e.nodes.length)return;if(!l)return void r.push([t.clone(),s.clone()]);const c=getTagElementsNextToPseudo(e);c.includes("area")?r.push([t.clone(),s.clone(),o.clone()]):c.length?r.push([t.clone(),s.clone()]):r.push([t.clone(),s.clone(),n.clone()])})),!r.length)return;cartesianProduct(...r).forEach((t=>{const s=e.clone();s.walkPseudos((e=>{":any-link"!==e.value.toLowerCase()||e.nodes&&e.nodes.length||(insertNode(e.parent,e,t.shift()),e.remove())})),c.push(s.toString())}))})).processSync(r),c}function cartesianProduct(...e){const t=[],s=e.length-1;return function helper(n,o){for(let r=0,l=e[o].length;r=0&&("combinator"!==t.nodes[s].type&&!e.isPseudoElement(t.nodes[s].type));s--)r=s;if("tag"!==o){for(let s=c;s{const t={preserve:e?.preserve??!0,subFeatures:{areaHrefNeedsFixing:e?.subFeatures?.areaHrefNeedsFixing??!1}};return{postcssPlugin:"postcss-pseudo-class-any-link",prepare(){const e=new WeakSet;return{postcssPlugin:"postcss-pseudo-class-any-link",Rule(s,{result:n}){if(!s.selector.toLowerCase().includes(":any-link"))return;if(e.has(s))return;if((s.raws.selector&&s.raws.selector.raw||s.selector).endsWith(":"))return;replaceAnyLink(s,n,t.preserve,t.subFeatures.areaHrefNeedsFixing)&&e.add(s)}}}}};creator.postcss=!0,module.exports=creator; diff --git a/plugins/postcss-pseudo-class-any-link/dist/index.mjs b/plugins/postcss-pseudo-class-any-link/dist/index.mjs index 192a428dc..4694eccaa 100644 --- a/plugins/postcss-pseudo-class-any-link/dist/index.mjs +++ b/plugins/postcss-pseudo-class-any-link/dist/index.mjs @@ -1 +1 @@ -import e from"postcss-selector-parser";const t=e().astSync(":link").nodes[0],s=e().astSync(":visited").nodes[0],n=e().astSync("area[href]").nodes[0],o=e().astSync("[href]").nodes[0];function replaceAnyLink(e,t,s,n){const o=[],r=[];try{for(let t=0;t{const r=[];if(e.walkPseudos((e=>{if(":not"===e.value.toLowerCase())return!1;if(":any-link"!==e.value.toLowerCase()||e.nodes&&e.nodes.length)return;if(!l)return void r.push([t.clone(),s.clone()]);const c=getTagElementsNextToPseudo(e);c.includes("area")?r.push([t.clone(),s.clone(),o.clone()]):c.length?r.push([t.clone(),s.clone()]):r.push([t.clone(),s.clone(),n.clone()])})),!r.length)return;cartesianProduct(...r).forEach((t=>{const s=e.clone();s.walkPseudos((e=>{":any-link"!==e.value.toLowerCase()||e.nodes&&e.nodes.length||(insertNode(e.parent,e,t.shift()),e.remove())})),c.push(s.toString())}))})).processSync(r),c}function cartesianProduct(...e){const t=[],s=e.length-1;return function helper(n,o){for(let r=0,l=e[o].length;r=0&&("combinator"!==t.nodes[s].type&&!e.isPseudoElement(t.nodes[s].type));s--)r=s;if("tag"!==o){for(let s=c;s{const t={preserve:!0,...e},s={areaHrefNeedsFixing:!1,...Object(t.subFeatures)};return{postcssPlugin:"postcss-pseudo-class-any-link",prepare(){const e=new WeakSet;return{postcssPlugin:"postcss-pseudo-class-any-link",Rule(n,{result:o}){if(!n.selector.toLowerCase().includes(":any-link"))return;if(e.has(n))return;if((n.raws.selector&&n.raws.selector.raw||n.selector).endsWith(":"))return;replaceAnyLink(n,o,t.preserve,s.areaHrefNeedsFixing)&&e.add(n)}}}}};creator.postcss=!0;export{creator as default}; +import e from"postcss-selector-parser";const t=e().astSync(":link").nodes[0],s=e().astSync(":visited").nodes[0],n=e().astSync("area[href]").nodes[0],o=e().astSync("[href]").nodes[0];function replaceAnyLink(e,t,s,n){const o=[],r=[];try{for(let t=0;t{const r=[];if(e.walkPseudos((e=>{if(":not"===e.value.toLowerCase())return!1;if(":any-link"!==e.value.toLowerCase()||e.nodes&&e.nodes.length)return;if(!l)return void r.push([t.clone(),s.clone()]);const c=getTagElementsNextToPseudo(e);c.includes("area")?r.push([t.clone(),s.clone(),o.clone()]):c.length?r.push([t.clone(),s.clone()]):r.push([t.clone(),s.clone(),n.clone()])})),!r.length)return;cartesianProduct(...r).forEach((t=>{const s=e.clone();s.walkPseudos((e=>{":any-link"!==e.value.toLowerCase()||e.nodes&&e.nodes.length||(insertNode(e.parent,e,t.shift()),e.remove())})),c.push(s.toString())}))})).processSync(r),c}function cartesianProduct(...e){const t=[],s=e.length-1;return function helper(n,o){for(let r=0,l=e[o].length;r=0&&("combinator"!==t.nodes[s].type&&!e.isPseudoElement(t.nodes[s].type));s--)r=s;if("tag"!==o){for(let s=c;s{const t={preserve:e?.preserve??!0,subFeatures:{areaHrefNeedsFixing:e?.subFeatures?.areaHrefNeedsFixing??!1}};return{postcssPlugin:"postcss-pseudo-class-any-link",prepare(){const e=new WeakSet;return{postcssPlugin:"postcss-pseudo-class-any-link",Rule(s,{result:n}){if(!s.selector.toLowerCase().includes(":any-link"))return;if(e.has(s))return;if((s.raws.selector&&s.raws.selector.raw||s.selector).endsWith(":"))return;replaceAnyLink(s,n,t.preserve,t.subFeatures.areaHrefNeedsFixing)&&e.add(s)}}}}};creator.postcss=!0;export{creator as default}; diff --git a/plugins/postcss-pseudo-class-any-link/src/index.ts b/plugins/postcss-pseudo-class-any-link/src/index.ts index d0f96da2d..92009582d 100644 --- a/plugins/postcss-pseudo-class-any-link/src/index.ts +++ b/plugins/postcss-pseudo-class-any-link/src/index.ts @@ -13,13 +13,10 @@ export type pluginOptions = { const creator: PluginCreator = (opts?: pluginOptions) => { const options = { - preserve: true, - ...opts, - }; - - const subFeatures = { - areaHrefNeedsFixing: false, - ...Object(options.subFeatures), + preserve: opts?.preserve ?? true, + subFeatures: { + areaHrefNeedsFixing: opts?.subFeatures?.areaHrefNeedsFixing ?? false, + }, }; return { @@ -45,7 +42,7 @@ const creator: PluginCreator = (opts?: pluginOptions) => { return; } - const didReplace = replaceAnyLink(rule, result, options.preserve, subFeatures.areaHrefNeedsFixing); + const didReplace = replaceAnyLink(rule, result, options.preserve, options.subFeatures.areaHrefNeedsFixing); if (didReplace) { transformedNodes.add(rule); } diff --git a/plugins/postcss-rebase-url/src/rebase.mjs b/plugins/postcss-rebase-url/src/rebase.mjs index 49e90fe20..80d98479b 100644 --- a/plugins/postcss-rebase-url/src/rebase.mjs +++ b/plugins/postcss-rebase-url/src/rebase.mjs @@ -32,7 +32,7 @@ export function rebase(url, fromDir, fromEntryPointDir) { if (x.port || x.protocol) { return false; } - } catch { } // eslint-disable-line no-empty + } catch {} const absPath = path.posix.resolve( path.posix.join(fromDir, url), diff --git a/plugins/postcss-slow-plugins/CHANGELOG.md b/plugins/postcss-slow-plugins/CHANGELOG.md index a7b71ddd9..aed74c290 100644 --- a/plugins/postcss-slow-plugins/CHANGELOG.md +++ b/plugins/postcss-slow-plugins/CHANGELOG.md @@ -1,5 +1,9 @@ # Changes to PostCSS Slow Plugins +### 1.0.3 + +- Improve wording + ### 1.0.2 _December 15, 2023_ diff --git a/plugins/postcss-slow-plugins/README.md b/plugins/postcss-slow-plugins/README.md index b1b9c5e31..947427d22 100644 --- a/plugins/postcss-slow-plugins/README.md +++ b/plugins/postcss-slow-plugins/README.md @@ -15,7 +15,7 @@ Typical causes of slow PostCSS setups are : - you have a lot of plugins - a specific plugin is very slow -This plugin is intended to make it visible which plugins are the most impactful to remove/disable. +This plugin is intended to make it visible which plugins are the most impactful on the duration of CSS processing. We also welcome anyone to report performance issues so that we can improve the performance of popular plugins. However we ask that everyone is respectful when doing so. @@ -34,8 +34,8 @@ This will take a long time. Seriously, a very long time. It will profile your build twice for each plugin : -- once with only that plugin disabled -- once with only that plugin enabled +- once with only that plugin **disabled** +- once with only that plugin **enabled** When profiling it will run your build 20 times to get a mean duration. @@ -57,37 +57,37 @@ So expect this to take `N * 20 * 2` times longer than your normal build. Analyzing with file: plugins/postcss-slow-plugins/test/basic.css -Most impactful to remove, ordered by drop in duration when excluded: -┌─────────┬────────────┬──────────────┬───────────┬──────────────────────────────────────────┬───────────────────────┐ -│ (index) │ duration │ kb's per ms │ drop │ name │ index in plugins list │ -├─────────┼────────────┼──────────────┼───────────┼──────────────────────────────────────────┼───────────────────────┤ -│ 0 │ '10.692ms' │ '0.937kb/ms' │ '--' │ '-- all plugins --' │ '--' │ -│ 1 │ '6.884ms' │ '1.455kb/ms' │ '3.808ms' │ 'postcss-gradients-interpolation-method' │ 9 │ -│ 2 │ '7.128ms' │ '1.405kb/ms' │ '3.564ms' │ 'postcss-progressive-custom-properties' │ 25 │ -│ 3 │ '7.138ms' │ '1.403kb/ms' │ '3.554ms' │ 'postcss-normalize-display-values' │ 18 │ -│ 4 │ '7.281ms' │ '1.376kb/ms' │ '3.411ms' │ 'postcss-color-mix-function' │ 10 │ -│ 5 │ '7.286ms' │ '1.375kb/ms' │ '3.406ms' │ 'postcss-stepped-value-functions' │ 20 │ -│ 6 │ '7.299ms' │ '1.372kb/ms' │ '3.393ms' │ 'postcss-cascade-layers' │ 23 │ -│ 7 │ '7.327ms' │ '1.367kb/ms' │ '3.366ms' │ 'postcss-trigonometric-functions' │ 21 │ -│ 8 │ '7.329ms' │ '1.367kb/ms' │ '3.363ms' │ 'postcss-color-function' │ 14 │ -│ 9 │ '7.332ms' │ '1.366kb/ms' │ '3.361ms' │ 'postcss-ic-unit' │ 19 │ -│ 10 │ '7.342ms' │ '1.364kb/ms' │ '3.350ms' │ 'postcss-lab-function' │ 12 │ -└─────────┴────────────┴──────────────┴───────────┴──────────────────────────────────────────┴───────────────────────┘ -Most impactful to remove, ordered by increase in duration when running alone: +Most impactful to improve, ordered by drop in duration when excluded: +┌─────────┬───────────┬─────────────┬──────────┬──────────────────────────────────────────┬───────────────────────┐ +│ (index) │ duration │ kb's per ms │ drop │ name │ index in plugins list │ +├─────────┼───────────┼─────────────┼──────────┼──────────────────────────────────────────┼───────────────────────┤ +│ 0 │ '10.69ms' │ '0.93kb/ms' │ '--' │ '-- all plugins --' │ '--' │ +│ 1 │ '6.88ms' │ '1.45kb/ms' │ '3.80ms' │ 'postcss-gradients-interpolation-method' │ 9 │ +│ 2 │ '7.12ms' │ '1.40kb/ms' │ '3.56ms' │ 'postcss-progressive-custom-properties' │ 25 │ +│ 3 │ '7.13ms' │ '1.40kb/ms' │ '3.55ms' │ 'postcss-normalize-display-values' │ 18 │ +│ 4 │ '7.28ms' │ '1.37kb/ms' │ '3.41ms' │ 'postcss-color-mix-function' │ 10 │ +│ 5 │ '7.28ms' │ '1.37kb/ms' │ '3.40ms' │ 'postcss-stepped-value-functions' │ 20 │ +│ 6 │ '7.29ms' │ '1.37kb/ms' │ '3.39ms' │ 'postcss-cascade-layers' │ 23 │ +│ 7 │ '7.32ms' │ '1.36kb/ms' │ '3.36ms' │ 'postcss-trigonometric-functions' │ 21 │ +│ 8 │ '7.32ms' │ '1.36kb/ms' │ '3.36ms' │ 'postcss-color-function' │ 14 │ +│ 9 │ '7.33ms' │ '1.36kb/ms' │ '3.36ms' │ 'postcss-ic-unit' │ 19 │ +│ 10 │ '7.34ms' │ '1.36kb/ms' │ '3.35ms' │ 'postcss-lab-function' │ 12 │ +└─────────┴───────────┴─────────────┴──────────┴──────────────────────────────────────────┴───────────────────────┘ +Most impactful to improve, ordered by increase in duration when running alone: ┌─────────┬───────────┬──────────────┬──────────────────────────────────────────┬───────────────────────┐ │ (index) │ duration │ kb's per ms │ name │ index in plugins list │ ├─────────┼───────────┼──────────────┼──────────────────────────────────────────┼───────────────────────┤ -│ 0 │ '2.171ms' │ '4.613kb/ms' │ 'postcss-gradients-interpolation-method' │ 9 │ -│ 1 │ '2.000ms' │ '5.007kb/ms' │ 'postcss-relative-color-syntax' │ 11 │ -│ 2 │ '1.965ms' │ '5.097kb/ms' │ 'postcss-lab-function' │ 12 │ -│ 3 │ '1.948ms' │ '5.142kb/ms' │ 'postcss-color-mix-function' │ 10 │ -│ 4 │ '1.833ms' │ '5.465kb/ms' │ 'postcss-nesting' │ 3 │ -│ 5 │ '1.821ms' │ '5.500kb/ms' │ 'postcss-custom-media' │ 0 │ -│ 6 │ '1.819ms' │ '5.507kb/ms' │ 'postcss-color-function' │ 14 │ -│ 7 │ '1.762ms' │ '5.684kb/ms' │ 'postcss-normalize-display-values' │ 18 │ -│ 8 │ '1.750ms' │ '5.724kb/ms' │ 'postcss-custom-selectors' │ 4 │ -│ 9 │ '1.734ms' │ '5.777kb/ms' │ 'postcss-stepped-value-functions' │ 20 │ -│ 10 │ '1.729ms' │ '5.792kb/ms' │ 'postcss-trigonometric-functions' │ 21 │ +│ 0 │ '2.17ms' │ '4.61kb/ms' │ 'postcss-gradients-interpolation-method' │ 9 │ +│ 1 │ '2.00ms' │ '5.00kb/ms' │ 'postcss-relative-color-syntax' │ 11 │ +│ 2 │ '1.96ms' │ '5.09kb/ms' │ 'postcss-lab-function' │ 12 │ +│ 3 │ '1.94ms' │ '5.14kb/ms' │ 'postcss-color-mix-function' │ 10 │ +│ 4 │ '1.83ms' │ '5.46kb/ms' │ 'postcss-nesting' │ 3 │ +│ 5 │ '1.82ms' │ '5.50kb/ms' │ 'postcss-custom-media' │ 0 │ +│ 6 │ '1.81ms' │ '5.50kb/ms' │ 'postcss-color-function' │ 14 │ +│ 7 │ '1.76ms' │ '5.68kb/ms' │ 'postcss-normalize-display-values' │ 18 │ +│ 8 │ '1.75ms' │ '5.72kb/ms' │ 'postcss-custom-selectors' │ 4 │ +│ 9 │ '1.73ms' │ '5.77kb/ms' │ 'postcss-stepped-value-functions' │ 20 │ +│ 10 │ '1.72ms' │ '5.79kb/ms' │ 'postcss-trigonometric-functions' │ 21 │ └─────────┴───────────┴──────────────┴──────────────────────────────────────────┴───────────────────────┘ ``` diff --git a/plugins/postcss-slow-plugins/dist/index.cjs b/plugins/postcss-slow-plugins/dist/index.cjs index a36f363ae..9b8207cda 100644 --- a/plugins/postcss-slow-plugins/dist/index.cjs +++ b/plugins/postcss-slow-plugins/dist/index.cjs @@ -1 +1 @@ -"use strict";const creator=s=>{const o=s?.ignore??[];return{postcssPlugin:"postcss-slow-plugins",async Once(s,{result:n,postcss:t}){console.log("Analyzing with file:\n "+s.source?.input.from+"\n");const e=s.source?.input.css??"",i=[...n.processor.plugins.filter((s=>"postcssPlugin"in s&&"postcss-slow-plugins"!==s.postcssPlugin))],r=(await t(i).process(e??"",n.opts)).css.length/1024,medianDuration=async s=>{const o=[];for(let n=0;n<21;n++){const n=performance.now();await s(),o.push(performance.now()-n)}return o.sort(((s,o)=>s-o)),o[10]},c=await medianDuration((async()=>{(await t(i).process(e??"",n.opts)).css}));{const s=[];for(let p=0;ps!==i[p])),a=await medianDuration((async()=>{(await t(u).process(e??"",n.opts)).css})),d=c-a;s.push({duration:`${a.toFixed(3)}ms`,"kb's per ms":`${(r/a).toFixed(3)}kb/ms`,drop:d,name:l,"index in plugins list":p})}s.sort(((s,o)=>Number(o.drop)-Number(s.drop))),s.splice(0,0,{duration:`${c.toFixed(3)}ms`,"kb's per ms":`${(r/c).toFixed(3)}kb/ms`,drop:"--",name:"-- all plugins --","index in plugins list":"--"}),s.map((s=>("string"==typeof s.drop||(s.drop=`${s.drop.toFixed(3)}ms`),s))),console.log("Most impactful to remove, ordered by drop in duration when excluded:"),console.table(s.slice(0,11))}{const s=[];for(let p=0;ps===i[p]||"postcssPlugin"in s&&o.includes(s.postcssPlugin)))],a=await medianDuration((async()=>{(await t(u).process(e??"",n.opts)).css})),d=c-a;s.push({duration:`${a.toFixed(3)}ms`,"kb's per ms":`${(r/a).toFixed(3)}kb/ms`,drop:d,name:l,"index in plugins list":p})}s.sort(((s,o)=>Number(s.drop)-Number(o.drop))),s.map((s=>(delete s.drop,s))),console.log("Most impactful to remove, ordered by increase in duration when running alone:"),console.table(s.slice(0,11))}}}};creator.postcss=!0,module.exports=creator; +"use strict";const creator=s=>{const o=s?.ignore??[];return{postcssPlugin:"postcss-slow-plugins",async Once(s,{result:n,postcss:t}){console.log("Analyzing with file:\n "+s.source?.input.from+"\n");const e=s.source?.input.css??"",i=[...n.processor.plugins.filter((s=>"postcssPlugin"in s&&"postcss-slow-plugins"!==s.postcssPlugin))],r=(await t(i).process(e??"",n.opts)).css.length/1024,medianDuration=async s=>{const o=[];for(let n=0;n<21;n++){const n=performance.now();await s(),o.push(performance.now()-n)}return o.sort(((s,o)=>s-o)),o[10]},p=await medianDuration((async()=>{await t(i).process(e??"",n.opts)}));{const s=[];for(let c=0;cs!==i[c])),a=await medianDuration((async()=>{await t(u).process(e??"",n.opts)})),d=p-a;s.push({duration:`${a.toFixed(2)}ms`,"kb's per ms":`${(r/a).toFixed(2)}kb/ms`,drop:d,name:l,"index in plugins list":c})}s.sort(((s,o)=>Number(o.drop)-Number(s.drop))),s.splice(0,0,{duration:`${p.toFixed(2)}ms`,"kb's per ms":`${(r/p).toFixed(2)}kb/ms`,drop:"--",name:"-- all plugins --","index in plugins list":"--"}),s.map((s=>("string"==typeof s.drop||(s.drop=`${s.drop.toFixed(2)}ms`),s))),console.log("Most impactful to improve, ordered by drop in duration when excluded:"),console.table(s.slice(0,11))}{const s=[];for(let c=0;cs===i[c]||"postcssPlugin"in s&&o.includes(s.postcssPlugin)))],a=await medianDuration((async()=>{await t(u).process(e??"",n.opts)})),d=p-a;s.push({duration:`${a.toFixed(2)}ms`,"kb's per ms":`${(r/a).toFixed(2)}kb/ms`,drop:d,name:l,"index in plugins list":c})}s.sort(((s,o)=>Number(s.drop)-Number(o.drop))),s.map((s=>(delete s.drop,s))),console.log("Most impactful to improve, ordered by increase in duration when running alone:"),console.table(s.slice(0,11))}}}};creator.postcss=!0,module.exports=creator; diff --git a/plugins/postcss-slow-plugins/dist/index.mjs b/plugins/postcss-slow-plugins/dist/index.mjs index 93db2e9e9..2c91e1b63 100644 --- a/plugins/postcss-slow-plugins/dist/index.mjs +++ b/plugins/postcss-slow-plugins/dist/index.mjs @@ -1 +1 @@ -const creator=s=>{const o=s?.ignore??[];return{postcssPlugin:"postcss-slow-plugins",async Once(s,{result:n,postcss:t}){console.log("Analyzing with file:\n "+s.source?.input.from+"\n");const e=s.source?.input.css??"",i=[...n.processor.plugins.filter((s=>"postcssPlugin"in s&&"postcss-slow-plugins"!==s.postcssPlugin))],r=(await t(i).process(e??"",n.opts)).css.length/1024,medianDuration=async s=>{const o=[];for(let n=0;n<21;n++){const n=performance.now();await s(),o.push(performance.now()-n)}return o.sort(((s,o)=>s-o)),o[10]},c=await medianDuration((async()=>{(await t(i).process(e??"",n.opts)).css}));{const s=[];for(let p=0;ps!==i[p])),a=await medianDuration((async()=>{(await t(u).process(e??"",n.opts)).css})),d=c-a;s.push({duration:`${a.toFixed(3)}ms`,"kb's per ms":`${(r/a).toFixed(3)}kb/ms`,drop:d,name:l,"index in plugins list":p})}s.sort(((s,o)=>Number(o.drop)-Number(s.drop))),s.splice(0,0,{duration:`${c.toFixed(3)}ms`,"kb's per ms":`${(r/c).toFixed(3)}kb/ms`,drop:"--",name:"-- all plugins --","index in plugins list":"--"}),s.map((s=>("string"==typeof s.drop||(s.drop=`${s.drop.toFixed(3)}ms`),s))),console.log("Most impactful to remove, ordered by drop in duration when excluded:"),console.table(s.slice(0,11))}{const s=[];for(let p=0;ps===i[p]||"postcssPlugin"in s&&o.includes(s.postcssPlugin)))],a=await medianDuration((async()=>{(await t(u).process(e??"",n.opts)).css})),d=c-a;s.push({duration:`${a.toFixed(3)}ms`,"kb's per ms":`${(r/a).toFixed(3)}kb/ms`,drop:d,name:l,"index in plugins list":p})}s.sort(((s,o)=>Number(s.drop)-Number(o.drop))),s.map((s=>(delete s.drop,s))),console.log("Most impactful to remove, ordered by increase in duration when running alone:"),console.table(s.slice(0,11))}}}};creator.postcss=!0;export{creator as default}; +const creator=s=>{const o=s?.ignore??[];return{postcssPlugin:"postcss-slow-plugins",async Once(s,{result:n,postcss:t}){console.log("Analyzing with file:\n "+s.source?.input.from+"\n");const e=s.source?.input.css??"",i=[...n.processor.plugins.filter((s=>"postcssPlugin"in s&&"postcss-slow-plugins"!==s.postcssPlugin))],p=(await t(i).process(e??"",n.opts)).css.length/1024,medianDuration=async s=>{const o=[];for(let n=0;n<21;n++){const n=performance.now();await s(),o.push(performance.now()-n)}return o.sort(((s,o)=>s-o)),o[10]},r=await medianDuration((async()=>{await t(i).process(e??"",n.opts)}));{const s=[];for(let l=0;ls!==i[l])),a=await medianDuration((async()=>{await t(u).process(e??"",n.opts)})),d=r-a;s.push({duration:`${a.toFixed(2)}ms`,"kb's per ms":`${(p/a).toFixed(2)}kb/ms`,drop:d,name:c,"index in plugins list":l})}s.sort(((s,o)=>Number(o.drop)-Number(s.drop))),s.splice(0,0,{duration:`${r.toFixed(2)}ms`,"kb's per ms":`${(p/r).toFixed(2)}kb/ms`,drop:"--",name:"-- all plugins --","index in plugins list":"--"}),s.map((s=>("string"==typeof s.drop||(s.drop=`${s.drop.toFixed(2)}ms`),s))),console.log("Most impactful to improve, ordered by drop in duration when excluded:"),console.table(s.slice(0,11))}{const s=[];for(let l=0;ls===i[l]||"postcssPlugin"in s&&o.includes(s.postcssPlugin)))],a=await medianDuration((async()=>{await t(u).process(e??"",n.opts)})),d=r-a;s.push({duration:`${a.toFixed(2)}ms`,"kb's per ms":`${(p/a).toFixed(2)}kb/ms`,drop:d,name:c,"index in plugins list":l})}s.sort(((s,o)=>Number(s.drop)-Number(o.drop))),s.map((s=>(delete s.drop,s))),console.log("Most impactful to improve, ordered by increase in duration when running alone:"),console.table(s.slice(0,11))}}}};creator.postcss=!0;export{creator as default}; diff --git a/plugins/postcss-slow-plugins/docs/README.md b/plugins/postcss-slow-plugins/docs/README.md index dd0d38bc3..48dd055a0 100644 --- a/plugins/postcss-slow-plugins/docs/README.md +++ b/plugins/postcss-slow-plugins/docs/README.md @@ -26,7 +26,7 @@ Typical causes of slow PostCSS setups are : - you have a lot of plugins - a specific plugin is very slow -This plugin is intended to make it visible which plugins are the most impactful to remove/disable. +This plugin is intended to make it visible which plugins are the most impactful on the duration of CSS processing. We also welcome anyone to report performance issues so that we can improve the performance of popular plugins. However we ask that everyone is respectful when doing so. @@ -45,8 +45,8 @@ This will take a long time. Seriously, a very long time. It will profile your build twice for each plugin : -- once with only that plugin disabled -- once with only that plugin enabled +- once with only that plugin **disabled** +- once with only that plugin **enabled** When profiling it will run your build 20 times to get a mean duration. @@ -68,37 +68,37 @@ So expect this to take `N * 20 * 2` times longer than your normal build. Analyzing with file: plugins/postcss-slow-plugins/test/basic.css -Most impactful to remove, ordered by drop in duration when excluded: -┌─────────┬────────────┬──────────────┬───────────┬──────────────────────────────────────────┬───────────────────────┐ -│ (index) │ duration │ kb's per ms │ drop │ name │ index in plugins list │ -├─────────┼────────────┼──────────────┼───────────┼──────────────────────────────────────────┼───────────────────────┤ -│ 0 │ '10.692ms' │ '0.937kb/ms' │ '--' │ '-- all plugins --' │ '--' │ -│ 1 │ '6.884ms' │ '1.455kb/ms' │ '3.808ms' │ 'postcss-gradients-interpolation-method' │ 9 │ -│ 2 │ '7.128ms' │ '1.405kb/ms' │ '3.564ms' │ 'postcss-progressive-custom-properties' │ 25 │ -│ 3 │ '7.138ms' │ '1.403kb/ms' │ '3.554ms' │ 'postcss-normalize-display-values' │ 18 │ -│ 4 │ '7.281ms' │ '1.376kb/ms' │ '3.411ms' │ 'postcss-color-mix-function' │ 10 │ -│ 5 │ '7.286ms' │ '1.375kb/ms' │ '3.406ms' │ 'postcss-stepped-value-functions' │ 20 │ -│ 6 │ '7.299ms' │ '1.372kb/ms' │ '3.393ms' │ 'postcss-cascade-layers' │ 23 │ -│ 7 │ '7.327ms' │ '1.367kb/ms' │ '3.366ms' │ 'postcss-trigonometric-functions' │ 21 │ -│ 8 │ '7.329ms' │ '1.367kb/ms' │ '3.363ms' │ 'postcss-color-function' │ 14 │ -│ 9 │ '7.332ms' │ '1.366kb/ms' │ '3.361ms' │ 'postcss-ic-unit' │ 19 │ -│ 10 │ '7.342ms' │ '1.364kb/ms' │ '3.350ms' │ 'postcss-lab-function' │ 12 │ -└─────────┴────────────┴──────────────┴───────────┴──────────────────────────────────────────┴───────────────────────┘ -Most impactful to remove, ordered by increase in duration when running alone: +Most impactful to improve, ordered by drop in duration when excluded: +┌─────────┬───────────┬─────────────┬──────────┬──────────────────────────────────────────┬───────────────────────┐ +│ (index) │ duration │ kb's per ms │ drop │ name │ index in plugins list │ +├─────────┼───────────┼─────────────┼──────────┼──────────────────────────────────────────┼───────────────────────┤ +│ 0 │ '10.69ms' │ '0.93kb/ms' │ '--' │ '-- all plugins --' │ '--' │ +│ 1 │ '6.88ms' │ '1.45kb/ms' │ '3.80ms' │ 'postcss-gradients-interpolation-method' │ 9 │ +│ 2 │ '7.12ms' │ '1.40kb/ms' │ '3.56ms' │ 'postcss-progressive-custom-properties' │ 25 │ +│ 3 │ '7.13ms' │ '1.40kb/ms' │ '3.55ms' │ 'postcss-normalize-display-values' │ 18 │ +│ 4 │ '7.28ms' │ '1.37kb/ms' │ '3.41ms' │ 'postcss-color-mix-function' │ 10 │ +│ 5 │ '7.28ms' │ '1.37kb/ms' │ '3.40ms' │ 'postcss-stepped-value-functions' │ 20 │ +│ 6 │ '7.29ms' │ '1.37kb/ms' │ '3.39ms' │ 'postcss-cascade-layers' │ 23 │ +│ 7 │ '7.32ms' │ '1.36kb/ms' │ '3.36ms' │ 'postcss-trigonometric-functions' │ 21 │ +│ 8 │ '7.32ms' │ '1.36kb/ms' │ '3.36ms' │ 'postcss-color-function' │ 14 │ +│ 9 │ '7.33ms' │ '1.36kb/ms' │ '3.36ms' │ 'postcss-ic-unit' │ 19 │ +│ 10 │ '7.34ms' │ '1.36kb/ms' │ '3.35ms' │ 'postcss-lab-function' │ 12 │ +└─────────┴───────────┴─────────────┴──────────┴──────────────────────────────────────────┴───────────────────────┘ +Most impactful to improve, ordered by increase in duration when running alone: ┌─────────┬───────────┬──────────────┬──────────────────────────────────────────┬───────────────────────┐ │ (index) │ duration │ kb's per ms │ name │ index in plugins list │ ├─────────┼───────────┼──────────────┼──────────────────────────────────────────┼───────────────────────┤ -│ 0 │ '2.171ms' │ '4.613kb/ms' │ 'postcss-gradients-interpolation-method' │ 9 │ -│ 1 │ '2.000ms' │ '5.007kb/ms' │ 'postcss-relative-color-syntax' │ 11 │ -│ 2 │ '1.965ms' │ '5.097kb/ms' │ 'postcss-lab-function' │ 12 │ -│ 3 │ '1.948ms' │ '5.142kb/ms' │ 'postcss-color-mix-function' │ 10 │ -│ 4 │ '1.833ms' │ '5.465kb/ms' │ 'postcss-nesting' │ 3 │ -│ 5 │ '1.821ms' │ '5.500kb/ms' │ 'postcss-custom-media' │ 0 │ -│ 6 │ '1.819ms' │ '5.507kb/ms' │ 'postcss-color-function' │ 14 │ -│ 7 │ '1.762ms' │ '5.684kb/ms' │ 'postcss-normalize-display-values' │ 18 │ -│ 8 │ '1.750ms' │ '5.724kb/ms' │ 'postcss-custom-selectors' │ 4 │ -│ 9 │ '1.734ms' │ '5.777kb/ms' │ 'postcss-stepped-value-functions' │ 20 │ -│ 10 │ '1.729ms' │ '5.792kb/ms' │ 'postcss-trigonometric-functions' │ 21 │ +│ 0 │ '2.17ms' │ '4.61kb/ms' │ 'postcss-gradients-interpolation-method' │ 9 │ +│ 1 │ '2.00ms' │ '5.00kb/ms' │ 'postcss-relative-color-syntax' │ 11 │ +│ 2 │ '1.96ms' │ '5.09kb/ms' │ 'postcss-lab-function' │ 12 │ +│ 3 │ '1.94ms' │ '5.14kb/ms' │ 'postcss-color-mix-function' │ 10 │ +│ 4 │ '1.83ms' │ '5.46kb/ms' │ 'postcss-nesting' │ 3 │ +│ 5 │ '1.82ms' │ '5.50kb/ms' │ 'postcss-custom-media' │ 0 │ +│ 6 │ '1.81ms' │ '5.50kb/ms' │ 'postcss-color-function' │ 14 │ +│ 7 │ '1.76ms' │ '5.68kb/ms' │ 'postcss-normalize-display-values' │ 18 │ +│ 8 │ '1.75ms' │ '5.72kb/ms' │ 'postcss-custom-selectors' │ 4 │ +│ 9 │ '1.73ms' │ '5.77kb/ms' │ 'postcss-stepped-value-functions' │ 20 │ +│ 10 │ '1.72ms' │ '5.79kb/ms' │ 'postcss-trigonometric-functions' │ 21 │ └─────────┴───────────┴──────────────┴──────────────────────────────────────────┴───────────────────────┘ ``` diff --git a/plugins/postcss-slow-plugins/src/index.ts b/plugins/postcss-slow-plugins/src/index.ts index 69035dc59..77dfb28af 100644 --- a/plugins/postcss-slow-plugins/src/index.ts +++ b/plugins/postcss-slow-plugins/src/index.ts @@ -34,7 +34,7 @@ const creator: PluginCreator = (opts?: pluginOptions) => { }; const baseline = await medianDuration(async () => { - (await postcss(plugins).process(inputCSS ?? '', result.opts)).css; + (await postcss(plugins).process(inputCSS ?? '', result.opts)); }); { @@ -55,14 +55,14 @@ const creator: PluginCreator = (opts?: pluginOptions) => { const pluginsWithoutCurrent = plugins.filter((x) => x !== plugins[i]); const durationWithoutPlugin = await medianDuration(async () => { - (await postcss(pluginsWithoutCurrent).process(inputCSS ?? '', result.opts)).css; + (await postcss(pluginsWithoutCurrent).process(inputCSS ?? '', result.opts)); }); const durationDrop = baseline - durationWithoutPlugin; results.push({ - duration: `${durationWithoutPlugin.toFixed(3)}ms`, - 'kb\'s per ms': `${(outputCSS_KB / durationWithoutPlugin).toFixed(3)}kb/ms`, + duration: `${durationWithoutPlugin.toFixed(2)}ms`, + 'kb\'s per ms': `${(outputCSS_KB / durationWithoutPlugin).toFixed(2)}kb/ms`, drop: durationDrop, name: name, 'index in plugins list': i, @@ -72,8 +72,8 @@ const creator: PluginCreator = (opts?: pluginOptions) => { results.sort((a, b) => Number(b.drop) - Number(a.drop)); results.splice(0, 0, { - duration: `${baseline.toFixed(3)}ms`, - 'kb\'s per ms': `${(outputCSS_KB / baseline).toFixed(3)}kb/ms`, + duration: `${baseline.toFixed(2)}ms`, + 'kb\'s per ms': `${(outputCSS_KB / baseline).toFixed(2)}kb/ms`, drop: '--', name: '-- all plugins --', 'index in plugins list': '--', @@ -84,11 +84,11 @@ const creator: PluginCreator = (opts?: pluginOptions) => { return x; } - x.drop = `${x.drop.toFixed(3)}ms`; + x.drop = `${x.drop.toFixed(2)}ms`; return x; }); - console.log('Most impactful to remove, ordered by drop in duration when excluded:'); + console.log('Most impactful to improve, ordered by drop in duration when excluded:'); console.table(results.slice(0, 11)); } @@ -118,14 +118,14 @@ const creator: PluginCreator = (opts?: pluginOptions) => { ]; const durationWithOnlyPlugin = await medianDuration(async () => { - (await postcss(pluginsWithOnlyCurrent).process(inputCSS ?? '', result.opts)).css; + (await postcss(pluginsWithOnlyCurrent).process(inputCSS ?? '', result.opts)); }); const durationDrop = baseline - durationWithOnlyPlugin; results.push({ - duration: `${durationWithOnlyPlugin.toFixed(3)}ms`, - 'kb\'s per ms': `${(outputCSS_KB / durationWithOnlyPlugin).toFixed(3)}kb/ms`, + duration: `${durationWithOnlyPlugin.toFixed(2)}ms`, + 'kb\'s per ms': `${(outputCSS_KB / durationWithOnlyPlugin).toFixed(2)}kb/ms`, drop: durationDrop, name: name, 'index in plugins list': i, @@ -139,7 +139,7 @@ const creator: PluginCreator = (opts?: pluginOptions) => { return x; }); - console.log('Most impactful to remove, ordered by increase in duration when running alone:'); + console.log('Most impactful to improve, ordered by increase in duration when running alone:'); console.table(results.slice(0, 11)); } }, diff --git a/plugins/postcss-text-decoration-shorthand/dist/index.cjs b/plugins/postcss-text-decoration-shorthand/dist/index.cjs index 804ffc0d3..4ce1d76df 100644 --- a/plugins/postcss-text-decoration-shorthand/dist/index.cjs +++ b/plugins/postcss-text-decoration-shorthand/dist/index.cjs @@ -1 +1 @@ -"use strict";var e=require("postcss-value-parser"),o=require("@csstools/color-helpers");const r=/^text-decoration$/i,creator=o=>{const c=Object.assign({preserve:!0},o);return{postcssPlugin:"postcss-text-decoration-shorthand",prepare(){const o=new Map;return{postcssPlugin:"postcss-text-decoration-shorthand",OnceExit(){o.clear()},Declaration(u){if(!r.test(u.prop))return;const a=u.parent;if(!a)return;const i=a.index(u);if(a.nodes.some((e=>"decl"===e.type&&r.test(e.prop)&&o.get(u.value)===e.value&&a.index(e)!==i)))return;const d=e(u.value),p=d.nodes.filter((e=>"space"!==e.type&&"comment"!==e.type));if(p.find((e=>"var"===e.value.toLowerCase()&&"function"===e.type)))return;if(p.find((e=>"word"===e.type&&t.includes(e.value))))return;const f={line:[],style:null,color:null,thickness:null};for(let o=0;o{const c=Object.assign({preserve:!0},o);return{postcssPlugin:"postcss-text-decoration-shorthand",prepare(){const o=new Map;return{postcssPlugin:"postcss-text-decoration-shorthand",OnceExit(){o.clear()},Declaration(u){if(!r.test(u.prop))return;const a=u.parent;if(!a)return;const i=a.index(u);if(a.nodes.some((e=>"decl"===e.type&&r.test(e.prop)&&o.get(u.value)===e.value&&a.index(e)!==i)))return;const d=e(u.value),p=d.nodes.filter((e=>"space"!==e.type&&"comment"!==e.type));if(p.find((e=>"var"===e.value.toLowerCase()&&"function"===e.type)))return;if(p.find((e=>"word"===e.type&&t.includes(e.value))))return;const f={line:[],style:null,color:null,thickness:null};for(let o=0;o{const c=Object.assign({preserve:!0},o);return{postcssPlugin:"postcss-text-decoration-shorthand",prepare(){const o=new Map;return{postcssPlugin:"postcss-text-decoration-shorthand",OnceExit(){o.clear()},Declaration(a){if(!r.test(a.prop))return;const u=a.parent;if(!u)return;const i=u.index(a);if(u.nodes.some((e=>"decl"===e.type&&r.test(e.prop)&&o.get(a.value)===e.value&&u.index(e)!==i)))return;const d=e(a.value),p=d.nodes.filter((e=>"space"!==e.type&&"comment"!==e.type));if(p.find((e=>"var"===e.value.toLowerCase()&&"function"===e.type)))return;if(p.find((e=>"word"===e.type&&t.includes(e.value))))return;const f={line:[],style:null,color:null,thickness:null};for(let o=0;o{const c=Object.assign({preserve:!0},o);return{postcssPlugin:"postcss-text-decoration-shorthand",prepare(){const o=new Map;return{postcssPlugin:"postcss-text-decoration-shorthand",OnceExit(){o.clear()},Declaration(a){if(!r.test(a.prop))return;const u=a.parent;if(!u)return;const i=u.index(a);if(u.nodes.some((e=>"decl"===e.type&&r.test(e.prop)&&o.get(a.value)===e.value&&u.index(e)!==i)))return;const d=e(a.value),p=d.nodes.filter((e=>"space"!==e.type&&"comment"!==e.type));if(p.find((e=>"var"===e.value.toLowerCase()&&"function"===e.type)))return;if(p.find((e=>"word"===e.type&&t.includes(e.value))))return;const f={line:[],style:null,color:null,thickness:null};for(let o=0;o = (opts?: pluginOptions) => { const startNode = currentNode; let endNode = currentNode; - // eslint-disable-next-line no-constant-condition while (true) { const nextNode = relevantNodes[i + 1]; if (nextNode && nextNode.type === 'word' && lineKeywords.includes(nextNode.value.toLowerCase())) { @@ -136,7 +135,7 @@ const creator: PluginCreator = (opts?: pluginOptions) => { let valueAndUnit; try { valueAndUnit = valueParser.unit(currentNode.value); - } catch (_) { + } catch { return; } diff --git a/plugins/postcss-todo-or-die/dist/index.cjs b/plugins/postcss-todo-or-die/dist/index.cjs index 46726e43b..ddc9dc3f6 100644 --- a/plugins/postcss-todo-or-die/dist/index.cjs +++ b/plugins/postcss-todo-or-die/dist/index.cjs @@ -1 +1 @@ -"use strict";var e=require("browserslist"),o=require("@csstools/css-tokenizer"),n=require("@csstools/css-parser-algorithms");function died(e){return"string"==typeof e}function matchBeforeDateCondition(e,o,n){const t=new Date;t.setUTCFullYear(e),t.setUTCMonth(o),t.setUTCDate(n);return(new Date).getTime()=t[4].value)return`Died because A (${n[1]}) is no longer less than B (${t[1]})`;break;case">":if(n[4].value<=t[4].value)return`Died because A (${n[1]}) is no longer greater than B (${t[1]})`;break;case"=":if(n[4].value!==t[4].value)return`Died because A (${n[1]}) is no longer equal to B (${t[1]})`}return!0}}function matchNotCondition(e){const n=e.a,t=e.b;if(!(n[0]!==t[0]||o.isTokenDimension(n)&&o.isTokenDimension(t)&&n[4].unit.toLowerCase()!==t[4].unit.toLowerCase())){switch(e.operator){case"<":if(n[4].value":if(n[4].value>t[4].value)return`Died because A (${n[1]}) is greater than B (${t[1]})`;break;case"=":if(n[4].value===t[4].value)return`Died because A (${n[1]}) equals B (${t[1]})`}return!0}}function parseBeforeDateCondition(e){const t=e.value.filter((e=>!n.isWhitespaceNode(e)&&!n.isCommentNode(e)));if(t.length>3)return!1;const r=t[0],s=t[1],i=t[2];if(!r||!s||!i)return!1;if(!n.isTokenNode(r)||!n.isTokenNode(s)||!n.isTokenNode(i))return!1;const a=r.value,u=s.value,c=i.value;return!(!o.isTokenNumber(a)||a[4].type!==o.NumberType.Integer)&&(!(!o.isTokenNumber(u)||u[4].type!==o.NumberType.Integer)&&(!(!o.isTokenNumber(c)||c[4].type!==o.NumberType.Integer)&&{year:a[4].value,month:u[4].value,day:c[4].value}))}function parseBrowserslistCondition(e){const t=e.value.filter((e=>!n.isWhitespaceNode(e)&&!n.isCommentNode(e)));if(t.length>1)return!1;const r=t[0];if(!r)return!1;if(!n.isTokenNode(r))return!1;const s=r.value;return!!o.isTokenString(s)&&s[4].value}const t=[o.TokenType.Ident,o.TokenType.Number,o.TokenType.Percentage,o.TokenType.Dimension],r=["<",">","="];function parseIfCondition(e){const s=e.value.filter((e=>!n.isWhitespaceNode(e)&&!n.isCommentNode(e)));if(s.length>3)return!1;const i=s[0],a=s[1],u=s[2];if(!i||!a||!u)return!1;if(!n.isTokenNode(i)||!n.isTokenNode(a)||!n.isTokenNode(u))return!1;const c=i.value,d=a.value,l=u.value;return!!o.isTokenDelim(d)&&(!!r.includes(d[4].value)&&(!!t.includes(c[0])&&(!!t.includes(l[0])&&{a:c,b:l,operator:d[4].value})))}function parseNotCondition(e){const o=parseIfCondition(e);return!!o&&{a:o.a,b:o.b,operator:o.operator}}const creator=()=>{const t=new Set(e());return{postcssPlugin:"postcss-todo-or-die",async Once(e,{result:r}){const s=[];e.walkAtRules((e=>{if("todo-or-die"===e.name.toLowerCase()){if(!e.params.trim())throw e.error("Rule must have valid params");s.push(e)}}));for(const e of s){const errorHandler=o=>{throw e.error(o.message)},s=o.tokenizer({css:e.params},{onParseError:errorHandler}),i=[];for(;!s.endOfFile();)i.push(s.nextToken());i.push(s.nextToken());const a=n.parseCommaSeparatedListOfComponentValues(i,{onParseError:errorHandler});if(!a.length)return void e.warn(r,"Rule must have some valid params.");for(let o=0;o!n.isWhitespaceNode(e)&&!n.isCommentNode(e)));if(1!==s.length)return void e.warn(r,"Conditions must be split by commas when adding multiple in a list.");if(!n.isFunctionNode(s[0]))return void e.warn(r,"Conditions must be one of the supported functions.");switch(s[0].name[4].value.toLowerCase()){case"if":{const o=parseIfCondition(s[0]);if(!o)return void e.warn(r,"Incorrect arguments in `if()` function.");const n=matchIfCondition(o);if(died(n))throw e.error(n);break}case"not":{const o=parseNotCondition(s[0]);if(!o)return void e.warn(r,"Incorrect arguments in `not()` function.");const n=matchNotCondition(o);if(died(n))throw e.error(n);break}case"browserslist":{const o=parseBrowserslistCondition(s[0]);if(!o)return void e.warn(r,"Incorrect arguments in `browserslist()` function.");const n=matchBrowserslistCondition(o,t);if(died(n))throw e.error(n);break}case"before-date":{const o=parseBeforeDateCondition(s[0]);if(!o)return void e.warn(r,"Incorrect arguments in `before-date()` function.");const n=matchBeforeDateCondition(o.year,o.month,o.day);if(died(n))throw e.error(n);break}}}e.nodes?e.replaceWith(e.nodes):e.remove()}}}};creator.postcss=!0,module.exports=creator; +"use strict";var e=require("browserslist"),o=require("@csstools/css-tokenizer"),t=require("@csstools/css-parser-algorithms");function died(e){return"string"==typeof e}function matchBeforeDateCondition(e,o,t){const n=new Date;n.setUTCFullYear(e),n.setUTCMonth(o),n.setUTCDate(t);return(new Date).getTime()=n[4].value)return`Died because A (${t[1]}) is no longer less than B (${n[1]})`;break;case">":if(t[4].value<=n[4].value)return`Died because A (${t[1]}) is no longer greater than B (${n[1]})`;break;case"=":if(t[4].value!==n[4].value)return`Died because A (${t[1]}) is no longer equal to B (${n[1]})`}return!0}}function matchNotCondition(e){const t=e.a,n=e.b;if(!(t[0]!==n[0]||o.isTokenDimension(t)&&o.isTokenDimension(n)&&t[4].unit.toLowerCase()!==n[4].unit.toLowerCase())){switch(e.operator){case"<":if(t[4].value":if(t[4].value>n[4].value)return`Died because A (${t[1]}) is greater than B (${n[1]})`;break;case"=":if(t[4].value===n[4].value)return`Died because A (${t[1]}) equals B (${n[1]})`}return!0}}function parseBeforeDateCondition(e){const n=e.value.filter((e=>!t.isWhitespaceNode(e)&&!t.isCommentNode(e)));if(n.length>3)return!1;const r=n[0],i=n[1],s=n[2];if(!r||!i||!s)return!1;if(!t.isTokenNode(r)||!t.isTokenNode(i)||!t.isTokenNode(s))return!1;const a=r.value,u=i.value,c=s.value;return!(!o.isTokenNumber(a)||a[4].type!==o.NumberType.Integer)&&(!(!o.isTokenNumber(u)||u[4].type!==o.NumberType.Integer)&&(!(!o.isTokenNumber(c)||c[4].type!==o.NumberType.Integer)&&{year:a[4].value,month:u[4].value,day:c[4].value}))}function parseBrowserslistCondition(e){const n=e.value.filter((e=>!t.isWhitespaceNode(e)&&!t.isCommentNode(e)));if(n.length>1)return!1;const r=n[0];if(!r)return!1;if(!t.isTokenNode(r))return!1;const i=r.value;return!!o.isTokenString(i)&&i[4].value}const n=[o.TokenType.Ident,o.TokenType.Number,o.TokenType.Percentage,o.TokenType.Dimension],r=["<",">","="];function parseIfCondition(e){const i=e.value.filter((e=>!t.isWhitespaceNode(e)&&!t.isCommentNode(e)));if(i.length>3)return!1;const s=i[0],a=i[1],u=i[2];if(!s||!a||!u)return!1;if(!t.isTokenNode(s)||!t.isTokenNode(a)||!t.isTokenNode(u))return!1;const c=s.value,d=a.value,l=u.value;return!!o.isTokenDelim(d)&&(!!r.includes(d[4].value)&&(!!n.includes(c[0])&&(!!n.includes(l[0])&&{a:c,b:l,operator:d[4].value})))}function parseNotCondition(e){const o=parseIfCondition(e);return!!o&&{a:o.a,b:o.b,operator:o.operator}}const creator=()=>{const n=new Set(e());return{postcssPlugin:"postcss-todo-or-die",Once(e,{result:r}){const i=[];e.walkAtRules((e=>{if("todo-or-die"===e.name.toLowerCase()){if(!e.params.trim())throw e.error("Rule must have valid params");i.push(e)}}));for(const e of i){const errorHandler=o=>{throw e.error(o.message)},i=o.tokenize({css:e.params},{onParseError:errorHandler}),s=t.parseCommaSeparatedListOfComponentValues(i,{onParseError:errorHandler});if(!s.length)return void e.warn(r,"Rule must have some valid params.");for(let o=0;o!t.isWhitespaceNode(e)&&!t.isCommentNode(e)));if(1!==i.length)return void e.warn(r,"Conditions must be split by commas when adding multiple in a list.");if(!t.isFunctionNode(i[0]))return void e.warn(r,"Conditions must be one of the supported functions.");switch(i[0].name[4].value.toLowerCase()){case"if":{const o=parseIfCondition(i[0]);if(!o)return void e.warn(r,"Incorrect arguments in `if()` function.");const t=matchIfCondition(o);if(died(t))throw e.error(t);break}case"not":{const o=parseNotCondition(i[0]);if(!o)return void e.warn(r,"Incorrect arguments in `not()` function.");const t=matchNotCondition(o);if(died(t))throw e.error(t);break}case"browserslist":{const o=parseBrowserslistCondition(i[0]);if(!o)return void e.warn(r,"Incorrect arguments in `browserslist()` function.");const t=matchBrowserslistCondition(o,n);if(died(t))throw e.error(t);break}case"before-date":{const o=parseBeforeDateCondition(i[0]);if(!o)return void e.warn(r,"Incorrect arguments in `before-date()` function.");const t=matchBeforeDateCondition(o.year,o.month,o.day);if(died(t))throw e.error(t);break}}}e.nodes?e.replaceWith(e.nodes):e.remove()}}}};creator.postcss=!0,module.exports=creator; diff --git a/plugins/postcss-todo-or-die/dist/index.mjs b/plugins/postcss-todo-or-die/dist/index.mjs index cd105474a..06226d0af 100644 --- a/plugins/postcss-todo-or-die/dist/index.mjs +++ b/plugins/postcss-todo-or-die/dist/index.mjs @@ -1 +1 @@ -import e from"browserslist";import{isTokenDimension as t,isTokenNumber as r,NumberType as n,isTokenString as o,TokenType as s,isTokenDelim as i,tokenizer as a}from"@csstools/css-tokenizer";import{isWhitespaceNode as u,isCommentNode as c,isTokenNode as l,parseCommaSeparatedListOfComponentValues as f,isFunctionNode as d}from"@csstools/css-parser-algorithms";function died(e){return"string"==typeof e}function matchBeforeDateCondition(e,t,r){const n=new Date;n.setUTCFullYear(e),n.setUTCMonth(t),n.setUTCDate(r);return(new Date).getTime()=n[4].value)return`Died because A (${r[1]}) is no longer less than B (${n[1]})`;break;case">":if(r[4].value<=n[4].value)return`Died because A (${r[1]}) is no longer greater than B (${n[1]})`;break;case"=":if(r[4].value!==n[4].value)return`Died because A (${r[1]}) is no longer equal to B (${n[1]})`}return!0}}function matchNotCondition(e){const r=e.a,n=e.b;if(!(r[0]!==n[0]||t(r)&&t(n)&&r[4].unit.toLowerCase()!==n[4].unit.toLowerCase())){switch(e.operator){case"<":if(r[4].value":if(r[4].value>n[4].value)return`Died because A (${r[1]}) is greater than B (${n[1]})`;break;case"=":if(r[4].value===n[4].value)return`Died because A (${r[1]}) equals B (${n[1]})`}return!0}}function parseBeforeDateCondition(e){const t=e.value.filter((e=>!u(e)&&!c(e)));if(t.length>3)return!1;const o=t[0],s=t[1],i=t[2];if(!o||!s||!i)return!1;if(!l(o)||!l(s)||!l(i))return!1;const a=o.value,f=s.value,d=i.value;return!(!r(a)||a[4].type!==n.Integer)&&(!(!r(f)||f[4].type!==n.Integer)&&(!(!r(d)||d[4].type!==n.Integer)&&{year:a[4].value,month:f[4].value,day:d[4].value}))}function parseBrowserslistCondition(e){const t=e.value.filter((e=>!u(e)&&!c(e)));if(t.length>1)return!1;const r=t[0];if(!r)return!1;if(!l(r))return!1;const n=r.value;return!!o(n)&&n[4].value}const h=[s.Ident,s.Number,s.Percentage,s.Dimension],m=["<",">","="];function parseIfCondition(e){const t=e.value.filter((e=>!u(e)&&!c(e)));if(t.length>3)return!1;const r=t[0],n=t[1],o=t[2];if(!r||!n||!o)return!1;if(!l(r)||!l(n)||!l(o))return!1;const s=r.value,a=n.value,f=o.value;return!!i(a)&&(!!m.includes(a[4].value)&&(!!h.includes(s[0])&&(!!h.includes(f[0])&&{a:s,b:f,operator:a[4].value})))}function parseNotCondition(e){const t=parseIfCondition(e);return!!t&&{a:t.a,b:t.b,operator:t.operator}}const creator=()=>{const t=new Set(e());return{postcssPlugin:"postcss-todo-or-die",async Once(e,{result:r}){const n=[];e.walkAtRules((e=>{if("todo-or-die"===e.name.toLowerCase()){if(!e.params.trim())throw e.error("Rule must have valid params");n.push(e)}}));for(const e of n){const errorHandler=t=>{throw e.error(t.message)},n=a({css:e.params},{onParseError:errorHandler}),o=[];for(;!n.endOfFile();)o.push(n.nextToken());o.push(n.nextToken());const s=f(o,{onParseError:errorHandler});if(!s.length)return void e.warn(r,"Rule must have some valid params.");for(let n=0;n!u(e)&&!c(e)));if(1!==o.length)return void e.warn(r,"Conditions must be split by commas when adding multiple in a list.");if(!d(o[0]))return void e.warn(r,"Conditions must be one of the supported functions.");switch(o[0].name[4].value.toLowerCase()){case"if":{const t=parseIfCondition(o[0]);if(!t)return void e.warn(r,"Incorrect arguments in `if()` function.");const n=matchIfCondition(t);if(died(n))throw e.error(n);break}case"not":{const t=parseNotCondition(o[0]);if(!t)return void e.warn(r,"Incorrect arguments in `not()` function.");const n=matchNotCondition(t);if(died(n))throw e.error(n);break}case"browserslist":{const n=parseBrowserslistCondition(o[0]);if(!n)return void e.warn(r,"Incorrect arguments in `browserslist()` function.");const s=matchBrowserslistCondition(n,t);if(died(s))throw e.error(s);break}case"before-date":{const t=parseBeforeDateCondition(o[0]);if(!t)return void e.warn(r,"Incorrect arguments in `before-date()` function.");const n=matchBeforeDateCondition(t.year,t.month,t.day);if(died(n))throw e.error(n);break}}}e.nodes?e.replaceWith(e.nodes):e.remove()}}}};creator.postcss=!0;export{creator as default}; +import e from"browserslist";import{isTokenDimension as t,isTokenNumber as r,NumberType as n,isTokenString as o,TokenType as s,isTokenDelim as i,tokenize as a}from"@csstools/css-tokenizer";import{isWhitespaceNode as u,isCommentNode as c,isTokenNode as l,parseCommaSeparatedListOfComponentValues as f,isFunctionNode as d}from"@csstools/css-parser-algorithms";function died(e){return"string"==typeof e}function matchBeforeDateCondition(e,t,r){const n=new Date;n.setUTCFullYear(e),n.setUTCMonth(t),n.setUTCDate(r);return(new Date).getTime()=n[4].value)return`Died because A (${r[1]}) is no longer less than B (${n[1]})`;break;case">":if(r[4].value<=n[4].value)return`Died because A (${r[1]}) is no longer greater than B (${n[1]})`;break;case"=":if(r[4].value!==n[4].value)return`Died because A (${r[1]}) is no longer equal to B (${n[1]})`}return!0}}function matchNotCondition(e){const r=e.a,n=e.b;if(!(r[0]!==n[0]||t(r)&&t(n)&&r[4].unit.toLowerCase()!==n[4].unit.toLowerCase())){switch(e.operator){case"<":if(r[4].value":if(r[4].value>n[4].value)return`Died because A (${r[1]}) is greater than B (${n[1]})`;break;case"=":if(r[4].value===n[4].value)return`Died because A (${r[1]}) equals B (${n[1]})`}return!0}}function parseBeforeDateCondition(e){const t=e.value.filter((e=>!u(e)&&!c(e)));if(t.length>3)return!1;const o=t[0],s=t[1],i=t[2];if(!o||!s||!i)return!1;if(!l(o)||!l(s)||!l(i))return!1;const a=o.value,f=s.value,d=i.value;return!(!r(a)||a[4].type!==n.Integer)&&(!(!r(f)||f[4].type!==n.Integer)&&(!(!r(d)||d[4].type!==n.Integer)&&{year:a[4].value,month:f[4].value,day:d[4].value}))}function parseBrowserslistCondition(e){const t=e.value.filter((e=>!u(e)&&!c(e)));if(t.length>1)return!1;const r=t[0];if(!r)return!1;if(!l(r))return!1;const n=r.value;return!!o(n)&&n[4].value}const h=[s.Ident,s.Number,s.Percentage,s.Dimension],m=["<",">","="];function parseIfCondition(e){const t=e.value.filter((e=>!u(e)&&!c(e)));if(t.length>3)return!1;const r=t[0],n=t[1],o=t[2];if(!r||!n||!o)return!1;if(!l(r)||!l(n)||!l(o))return!1;const s=r.value,a=n.value,f=o.value;return!!i(a)&&(!!m.includes(a[4].value)&&(!!h.includes(s[0])&&(!!h.includes(f[0])&&{a:s,b:f,operator:a[4].value})))}function parseNotCondition(e){const t=parseIfCondition(e);return!!t&&{a:t.a,b:t.b,operator:t.operator}}const creator=()=>{const t=new Set(e());return{postcssPlugin:"postcss-todo-or-die",Once(e,{result:r}){const n=[];e.walkAtRules((e=>{if("todo-or-die"===e.name.toLowerCase()){if(!e.params.trim())throw e.error("Rule must have valid params");n.push(e)}}));for(const e of n){const errorHandler=t=>{throw e.error(t.message)},n=a({css:e.params},{onParseError:errorHandler}),o=f(n,{onParseError:errorHandler});if(!o.length)return void e.warn(r,"Rule must have some valid params.");for(let n=0;n!u(e)&&!c(e)));if(1!==s.length)return void e.warn(r,"Conditions must be split by commas when adding multiple in a list.");if(!d(s[0]))return void e.warn(r,"Conditions must be one of the supported functions.");switch(s[0].name[4].value.toLowerCase()){case"if":{const t=parseIfCondition(s[0]);if(!t)return void e.warn(r,"Incorrect arguments in `if()` function.");const n=matchIfCondition(t);if(died(n))throw e.error(n);break}case"not":{const t=parseNotCondition(s[0]);if(!t)return void e.warn(r,"Incorrect arguments in `not()` function.");const n=matchNotCondition(t);if(died(n))throw e.error(n);break}case"browserslist":{const n=parseBrowserslistCondition(s[0]);if(!n)return void e.warn(r,"Incorrect arguments in `browserslist()` function.");const o=matchBrowserslistCondition(n,t);if(died(o))throw e.error(o);break}case"before-date":{const t=parseBeforeDateCondition(s[0]);if(!t)return void e.warn(r,"Incorrect arguments in `before-date()` function.");const n=matchBeforeDateCondition(t.year,t.month,t.day);if(died(n))throw e.error(n);break}}}e.nodes?e.replaceWith(e.nodes):e.remove()}}}};creator.postcss=!0;export{creator as default}; diff --git a/plugins/postcss-todo-or-die/src/index.ts b/plugins/postcss-todo-or-die/src/index.ts index f1adb4eb4..f6f5164d2 100644 --- a/plugins/postcss-todo-or-die/src/index.ts +++ b/plugins/postcss-todo-or-die/src/index.ts @@ -1,6 +1,6 @@ import type { AtRule, PluginCreator } from 'postcss'; import browserslist from 'browserslist'; -import { CSSToken, ParseError, tokenizer } from '@csstools/css-tokenizer'; +import { ParseError, tokenize } from '@csstools/css-tokenizer'; import { died } from './died'; import { isCommentNode, isFunctionNode, isWhitespaceNode, parseCommaSeparatedListOfComponentValues } from '@csstools/css-parser-algorithms'; import { matchBeforeDateCondition } from './match/before-date'; @@ -17,7 +17,7 @@ const creator: PluginCreator = () => { return { postcssPlugin: 'postcss-todo-or-die', - async Once(root, { result }): Promise { + Once(root, { result }): void { const atRules: Array = []; root.walkAtRules((atRule) => { @@ -37,24 +37,12 @@ const creator: PluginCreator = () => { throw atRule.error(err.message); }; - const t = tokenizer({ + const tokens = tokenize({ css: atRule.params, }, { onParseError: errorHandler, }); - const tokens: Array = []; - - { - while (!t.endOfFile()) { - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - tokens.push(t.nextToken()!); - } - - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - tokens.push(t.nextToken()!); // EOF-token - } - const todoOrDieConditions = parseCommaSeparatedListOfComponentValues(tokens, { onParseError: errorHandler, }); diff --git a/rollup/default.mjs b/rollup/default.mjs index e0212ab8f..261e25196 100644 --- a/rollup/default.mjs +++ b/rollup/default.mjs @@ -12,7 +12,7 @@ const packageInfo = JSON.parse(fs.readFileSync('./package.json', 'utf-8')); const isTypescript = (() => { try { return fs.statSync('./tsconfig.json').isFile() && fs.statSync('./src/index.ts').isFile(); - } catch (_) { + } catch { return false; } })(); diff --git a/tsconfig.json b/tsconfig.json index 0bfa8f800..1fdb5d013 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -6,6 +6,8 @@ "lib": ["ES2022"], "module": "ESNext", "declaration": true, - "isolatedModules": true + "isolatedModules": true, + "useUnknownInCatchVariables": false, + "strict": false } }