diff --git a/.github/bin/generate-docs/api-documenter.mjs b/.github/bin/generate-docs/api-documenter.mjs new file mode 100644 index 000000000..9143b4ea6 --- /dev/null +++ b/.github/bin/generate-docs/api-documenter.mjs @@ -0,0 +1,56 @@ +import { spawn } from 'child_process'; +import { platform } from 'process'; +import path from 'path'; +import fs from 'fs'; + +import { listWorkspaces } from "../list-workspaces/list-workspaces.mjs"; + +const workspaces = await listWorkspaces(); + +for (const workspace of workspaces) { + await runApiDocumenter(workspace); +} + +async function runApiDocumenter(workspace) { + await new Promise((resolve, reject) => { + if (workspace.private) { + resolve(true); + + return; + } + + const docsExist = fs.existsSync(path.join(workspace.path, 'docs', workspace.unscopedName + '.api.json')); + if (!docsExist) { + resolve(true); + + return; + } + + const publishCmd = spawn( + 'npm', + [ + 'exec', + '--', + 'api-documenter', + 'markdown', + '--input-folder', + path.join(workspace.path, 'docs'), + '--output-folder', + path.join(workspace.path, 'api-reference'), + ], + { + stdio: 'inherit', + shell: platform === 'win32' + } + ); + + publishCmd.on('close', (code) => { + if (0 !== code) { + reject(new Error(`'npm publish' exited with code ${code} for ${packageName}`)); + return; + } + + resolve(true); + }); + }); +} diff --git a/.github/bin/list-workspaces/list-workspaces.mjs b/.github/bin/list-workspaces/list-workspaces.mjs index 5c5080bcd..b6c7ea334 100644 --- a/.github/bin/list-workspaces/list-workspaces.mjs +++ b/.github/bin/list-workspaces/list-workspaces.mjs @@ -39,6 +39,7 @@ export async function listWorkspaces() { result.push({ path: packagePath, name: packageJSON.name, + unscopedName: packageJSON.name.replace(/^@[^/]+\//, ''), private: packageJSON.private, dependencies: [ ...Object.keys(Object(packageJSON.dependencies)), diff --git a/.gitignore b/.gitignore index b9dd6e7b6..bcb52d0bb 100644 --- a/.gitignore +++ b/.gitignore @@ -10,3 +10,4 @@ reports !e2e/package-lock.json !sites/package-lock.json .cached-commit +_types diff --git a/api-extractor.json b/api-extractor.json new file mode 100644 index 000000000..33f47559e --- /dev/null +++ b/api-extractor.json @@ -0,0 +1,436 @@ +/** +* Config file for API Extractor. For more info, please visit: https://api-extractor.com +*/ +{ + "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json", + + /** + * Optionally specifies another JSON config file that this file extends from. This provides a way for + * standard settings to be shared across multiple projects. + * + * If the path starts with "./" or "../", the path is resolved relative to the folder of the file that contains + * the "extends" field. Otherwise, the first path segment is interpreted as an NPM package name, and will be + * resolved using NodeJS require(). + * + * SUPPORTED TOKENS: none + * DEFAULT VALUE: "" + */ + // "extends": "./shared/api-extractor-base.json" + // "extends": "my-package/include/api-extractor-base.json" + + /** + * Determines the "" token that can be used with other config file settings. The project folder + * typically contains the tsconfig.json and package.json config files, but the path is user-defined. + * + * The path is resolved relative to the folder of the config file that contains the setting. + * + * The default value for "projectFolder" is the token "", which means the folder is determined by traversing + * parent folders, starting from the folder containing api-extractor.json, and stopping at the first folder + * that contains a tsconfig.json file. If a tsconfig.json file cannot be found in this way, then an error + * will be reported. + * + * SUPPORTED TOKENS: + * DEFAULT VALUE: "" + */ + // "projectFolder": "..", + + /** + * (REQUIRED) Specifies the .d.ts file to be used as the starting point for analysis. API Extractor + * analyzes the symbols exported by this module. + * + * The file extension must be ".d.ts" and not ".ts". + * + * The path is resolved relative to the folder of the config file that contains the setting; to change this, + * prepend a folder token such as "". + * + * SUPPORTED TOKENS: , , + */ + "mainEntryPointFilePath": "/dist/_types/index.d.ts", + + /** + * A list of NPM package names whose exports should be treated as part of this package. + * + * For example, suppose that Webpack is used to generate a distributed bundle for the project "library1", + * and another NPM package "library2" is embedded in this bundle. Some types from library2 may become part + * of the exported API for library1, but by default API Extractor would generate a .d.ts rollup that explicitly + * imports library2. To avoid this, we can specify: + * + * "bundledPackages": [ "library2" ], + * + * This would direct API Extractor to embed those types directly in the .d.ts rollup, as if they had been + * local files for library1. + */ + "bundledPackages": [], + + /** + * Specifies what type of newlines API Extractor should use when writing output files. By default, the output files + * will be written with Windows-style newlines. To use POSIX-style newlines, specify "lf" instead. + * To use the OS's default newline kind, specify "os". + * + * DEFAULT VALUE: "crlf" + */ + "newlineKind": "lf", + + /** + * Set to true when invoking API Extractor's test harness. When `testMode` is true, the `toolVersion` field in the + * .api.json file is assigned an empty string to prevent spurious diffs in output files tracked for tests. + * + * DEFAULT VALUE: "false" + */ + // "testMode": false, + + /** + * Specifies how API Extractor sorts members of an enum when generating the .api.json file. By default, the output + * files will be sorted alphabetically, which is "by-name". To keep the ordering in the source code, specify + * "preserve". + * + * DEFAULT VALUE: "by-name" + */ + // "enumMemberOrder": "by-name", + + /** + * Determines how the TypeScript compiler engine will be invoked by API Extractor. + */ + "compiler": { + /** + * Specifies the path to the tsconfig.json file to be used by API Extractor when analyzing the project. + * + * The path is resolved relative to the folder of the config file that contains the setting; to change this, + * prepend a folder token such as "". + * + * Note: This setting will be ignored if "overrideTsconfig" is used. + * + * SUPPORTED TOKENS: , , + * DEFAULT VALUE: "/tsconfig.json" + */ + // "tsconfigFilePath": "/tsconfig.json", + /** + * Provides a compiler configuration that will be used instead of reading the tsconfig.json file from disk. + * The object must conform to the TypeScript tsconfig schema: + * + * http://json.schemastore.org/tsconfig + * + * If omitted, then the tsconfig.json file will be read from the "projectFolder". + * + * DEFAULT VALUE: no overrideTsconfig section + */ + // "overrideTsconfig": { + // . . . + // } + /** + * This option causes the compiler to be invoked with the --skipLibCheck option. This option is not recommended + * and may cause API Extractor to produce incomplete or incorrect declarations, but it may be required when + * dependencies contain declarations that are incompatible with the TypeScript engine that API Extractor uses + * for its analysis. Where possible, the underlying issue should be fixed rather than relying on skipLibCheck. + * + * DEFAULT VALUE: false + */ + // "skipLibCheck": true, + }, + + /** + * Configures how the API report file (*.api.md) will be generated. + */ + "apiReport": { + /** + * (REQUIRED) Whether to generate an API report. + */ + "enabled": false + + /** + * The filename for the API report files. It will be combined with "reportFolder" or "reportTempFolder" to produce + * a full file path. + * + * The file extension should be ".api.md", and the string should not contain a path separator such as "\" or "/". + * + * SUPPORTED TOKENS: , + * DEFAULT VALUE: ".api.md" + */ + // "reportFileName": ".api.md", + + /** + * Specifies the folder where the API report file is written. The file name portion is determined by + * the "reportFileName" setting. + * + * The API report file is normally tracked by Git. Changes to it can be used to trigger a branch policy, + * e.g. for an API review. + * + * The path is resolved relative to the folder of the config file that contains the setting; to change this, + * prepend a folder token such as "". + * + * SUPPORTED TOKENS: , , + * DEFAULT VALUE: "/temp/" + */ + // "reportFolder": "/temp/", + + /** + * Specifies the folder where the temporary report file is written. The file name portion is determined by + * the "reportFileName" setting. + * + * After the temporary file is written to disk, it is compared with the file in the "reportFolder". + * If they are different, a production build will fail. + * + * The path is resolved relative to the folder of the config file that contains the setting; to change this, + * prepend a folder token such as "". + * + * SUPPORTED TOKENS: , , + * DEFAULT VALUE: "/temp/" + */ + // "reportTempFolder": "/temp/", + + /** + * Whether "forgotten exports" should be included in the API report file. Forgotten exports are declarations + * flagged with `ae-forgotten-export` warnings. See https://api-extractor.com/pages/messages/ae-forgotten-export/ to + * learn more. + * + * DEFAULT VALUE: "false" + */ + // "includeForgottenExports": false + }, + + /** + * Configures how the doc model file (*.api.json) will be generated. + */ + "docModel": { + /** + * (REQUIRED) Whether to generate a doc model file. + */ + "enabled": false, + + /** + * The output path for the doc model file. The file extension should be ".api.json". + * + * The path is resolved relative to the folder of the config file that contains the setting; to change this, + * prepend a folder token such as "". + * + * SUPPORTED TOKENS: , , + * DEFAULT VALUE: "/temp/.api.json" + */ + "apiJsonFilePath": "/docs/.api.json" + + /** + * Whether "forgotten exports" should be included in the doc model file. Forgotten exports are declarations + * flagged with `ae-forgotten-export` warnings. See https://api-extractor.com/pages/messages/ae-forgotten-export/ to + * learn more. + * + * DEFAULT VALUE: "false" + */ + // "includeForgottenExports": false, + + /** + * The base URL where the project's source code can be viewed on a website such as GitHub or + * Azure DevOps. This URL path corresponds to the `` path on disk. + * + * This URL is concatenated with the file paths serialized to the doc model to produce URL file paths to individual API items. + * For example, if the `projectFolderUrl` is "https://github.com/microsoft/rushstack/tree/main/apps/api-extractor" and an API + * item's file path is "api/ExtractorConfig.ts", the full URL file path would be + * "https://github.com/microsoft/rushstack/tree/main/apps/api-extractor/api/ExtractorConfig.js". + * + * Can be omitted if you don't need source code links in your API documentation reference. + * + * SUPPORTED TOKENS: none + * DEFAULT VALUE: "" + */ + // "projectFolderUrl": "http://github.com/path/to/your/projectFolder" + }, + + /** + * Configures how the .d.ts rollup file will be generated. + */ + "dtsRollup": { + /** + * (REQUIRED) Whether to generate the .d.ts rollup file. + */ + "enabled": true, + + /** + * Specifies the output path for a .d.ts rollup file to be generated without any trimming. + * This file will include all declarations that are exported by the main entry point. + * + * If the path is an empty string, then this file will not be written. + * + * The path is resolved relative to the folder of the config file that contains the setting; to change this, + * prepend a folder token such as "". + * + * SUPPORTED TOKENS: , , + * DEFAULT VALUE: "/dist/.d.ts" + */ + "untrimmedFilePath": "/dist/index.d.ts", + + /** + * Specifies the output path for a .d.ts rollup file to be generated with trimming for an "alpha" release. + * This file will include only declarations that are marked as "@public", "@beta", or "@alpha". + * + * The path is resolved relative to the folder of the config file that contains the setting; to change this, + * prepend a folder token such as "". + * + * SUPPORTED TOKENS: , , + * DEFAULT VALUE: "" + */ + // "alphaTrimmedFilePath": "/dist/-alpha.d.ts", + + /** + * Specifies the output path for a .d.ts rollup file to be generated with trimming for a "beta" release. + * This file will include only declarations that are marked as "@public" or "@beta". + * + * The path is resolved relative to the folder of the config file that contains the setting; to change this, + * prepend a folder token such as "". + * + * SUPPORTED TOKENS: , , + * DEFAULT VALUE: "" + */ + // "betaTrimmedFilePath": "/dist/-beta.d.ts", + + /** + * Specifies the output path for a .d.ts rollup file to be generated with trimming for a "public" release. + * This file will include only declarations that are marked as "@public". + * + * If the path is an empty string, then this file will not be written. + * + * The path is resolved relative to the folder of the config file that contains the setting; to change this, + * prepend a folder token such as "". + * + * SUPPORTED TOKENS: , , + * DEFAULT VALUE: "" + */ + // "publicTrimmedFilePath": "/dist/-public.d.ts", + + /** + * When a declaration is trimmed, by default it will be replaced by a code comment such as + * "Excluded from this release type: exampleMember". Set "omitTrimmingComments" to true to remove the + * declaration completely. + * + * DEFAULT VALUE: false + */ + "omitTrimmingComments": true + }, + + /** + * Configures how the tsdoc-metadata.json file will be generated. + */ + "tsdocMetadata": { + /** + * Whether to generate the tsdoc-metadata.json file. + * + * DEFAULT VALUE: true + */ + "enabled": false + /** + * Specifies where the TSDoc metadata file should be written. + * + * The path is resolved relative to the folder of the config file that contains the setting; to change this, + * prepend a folder token such as "". + * + * The default value is "", which causes the path to be automatically inferred from the "tsdocMetadata", + * "typings" or "main" fields of the project's package.json. If none of these fields are set, the lookup + * falls back to "tsdoc-metadata.json" in the package folder. + * + * SUPPORTED TOKENS: , , + * DEFAULT VALUE: "" + */ + // "tsdocMetadataFilePath": "/dist/tsdoc-metadata.json" + }, + + /** + * Configures how API Extractor reports error and warning messages produced during analysis. + * + * There are three sources of messages: compiler messages, API Extractor messages, and TSDoc messages. + */ + "messages": { + /** + * Configures handling of diagnostic messages reported by the TypeScript compiler engine while analyzing + * the input .d.ts files. + * + * TypeScript message identifiers start with "TS" followed by an integer. For example: "TS2551" + * + * DEFAULT VALUE: A single "default" entry with logLevel=warning. + */ + "compilerMessageReporting": { + /** + * Configures the default routing for messages that don't match an explicit rule in this table. + */ + "default": { + /** + * Specifies whether the message should be written to the the tool's output log. Note that + * the "addToApiReportFile" property may supersede this option. + * + * Possible values: "error", "warning", "none" + * + * Errors cause the build to fail and return a nonzero exit code. Warnings cause a production build fail + * and return a nonzero exit code. For a non-production build (e.g. when "api-extractor run" includes + * the "--local" option), the warning is displayed but the build will not fail. + * + * DEFAULT VALUE: "warning" + */ + "logLevel": "error" + + /** + * When addToApiReportFile is true: If API Extractor is configured to write an API report file (.api.md), + * then the message will be written inside that file; otherwise, the message is instead logged according to + * the "logLevel" option. + * + * DEFAULT VALUE: false + */ + // "addToApiReportFile": false + } + + // "TS2551": { + // "logLevel": "warning", + // "addToApiReportFile": true + // }, + // + // . . . + }, + + /** + * Configures handling of messages reported by API Extractor during its analysis. + * + * API Extractor message identifiers start with "ae-". For example: "ae-extra-release-tag" + * + * DEFAULT VALUE: See api-extractor-defaults.json for the complete table of extractorMessageReporting mappings + */ + "extractorMessageReporting": { + "default": { + "logLevel": "error" + // "addToApiReportFile": false + }, + + "ae-extra-release-tag": { + "logLevel": "none", + "addToApiReportFile": false + }, + + "ae-missing-release-tag": { + "logLevel": "none", + "addToApiReportFile": false + }, + + "ae-forgotten-export": { + "logLevel": "error" + } + // + // . . . + }, + + /** + * Configures handling of messages reported by the TSDoc parser when analyzing code comments. + * + * TSDoc message identifiers start with "tsdoc-". For example: "tsdoc-link-tag-unescaped-text" + * + * DEFAULT VALUE: A single "default" entry with logLevel=warning. + */ + "tsdocMessageReporting": { + "default": { + "logLevel": "none", + "addToApiReportFile": false + } + + // "tsdoc-link-tag-unescaped-text": { + // "logLevel": "warning", + // "addToApiReportFile": true + // }, + // + // . . . + } + } +} diff --git a/e2e/typescript/commonjs/tsconfig.json b/e2e/typescript/commonjs/tsconfig.json index d93d2cfb3..042eefb8e 100644 --- a/e2e/typescript/commonjs/tsconfig.json +++ b/e2e/typescript/commonjs/tsconfig.json @@ -6,7 +6,6 @@ "declarationDir": "./dist", "lib": ["es2020"], "module": "CommonJS", - "moduleResolution": "node", "outDir": "./dist", "target": "es2020", "strict": true diff --git a/e2e/typescript/esm--node-next/dist/index.js b/e2e/typescript/esm--node-next/dist/index.js index eb302a875..38549d61a 100644 --- a/e2e/typescript/esm--node-next/dist/index.js +++ b/e2e/typescript/esm--node-next/dist/index.js @@ -1,10 +1,5 @@ -"use strict"; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -const assert_1 = __importDefault(require("assert")); -const postcss_preset_env_1 = __importDefault(require("postcss-preset-env")); -(0, postcss_preset_env_1.default)({ preserve: true }); -assert_1.default.ok(postcss_preset_env_1.default.postcss, 'should have "postcss flag"'); -assert_1.default.equal(typeof postcss_preset_env_1.default, 'function', 'should return a function'); +import assert from 'assert'; +import plugin from 'postcss-preset-env'; +plugin({ preserve: true }); +assert.ok(plugin.postcss, 'should have "postcss flag"'); +assert.equal(typeof plugin, 'function', 'should return a function'); diff --git a/e2e/typescript/esm--node-next/package.json b/e2e/typescript/esm--node-next/package.json index 0e7160a8f..a586445c7 100644 --- a/e2e/typescript/esm--node-next/package.json +++ b/e2e/typescript/esm--node-next/package.json @@ -2,9 +2,11 @@ "name": "@csstools/e2e--typescript--esm--node-next", "version": "0.0.0", "private": true, + "type": "module", "description": "Can you use PostCSS with one of our plugins from a Typescript file?", "scripts": { - "build": "tsc" + "build": "tsc", + "test": "node ./dist/index.js" }, "devDependencies": { "postcss-preset-env": "file:../../../plugin-packs/postcss-preset-env", diff --git a/e2e/typescript/esm/tsconfig.json b/e2e/typescript/esm/tsconfig.json index d10d1857f..c0b8982d5 100644 --- a/e2e/typescript/esm/tsconfig.json +++ b/e2e/typescript/esm/tsconfig.json @@ -5,8 +5,8 @@ "declaration": true, "declarationDir": "./dist", "lib": ["es2020"], - "module": "ES6", - "moduleResolution": "node", + "module": "Node16", + "moduleResolution": "Node16", "outDir": "./dist", "target": "es2020", "strict": true diff --git a/experimental/css-has-pseudo/CHANGELOG.md b/experimental/css-has-pseudo/CHANGELOG.md index 2b4facc2f..b5fc0d913 100644 --- a/experimental/css-has-pseudo/CHANGELOG.md +++ b/experimental/css-has-pseudo/CHANGELOG.md @@ -1,5 +1,9 @@ # Changes to CSS Has Pseudo +### Unreleased (patch) + +- Fix type definitions + ### 0.6.0 _July 8, 2022_ diff --git a/experimental/css-has-pseudo/api-extractor.json b/experimental/css-has-pseudo/api-extractor.json new file mode 100644 index 000000000..42058be51 --- /dev/null +++ b/experimental/css-has-pseudo/api-extractor.json @@ -0,0 +1,4 @@ +{ + "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json", + "extends": "../../api-extractor.json" +} diff --git a/experimental/css-has-pseudo/dist/index.d.ts b/experimental/css-has-pseudo/dist/index.d.ts index 37159ca64..4b66a8014 100644 --- a/experimental/css-has-pseudo/dist/index.d.ts +++ b/experimental/css-has-pseudo/dist/index.d.ts @@ -1,3 +1,6 @@ import type { PluginCreator } from 'postcss'; + declare const creator: PluginCreator; export default creator; + +export { } diff --git a/experimental/css-has-pseudo/package.json b/experimental/css-has-pseudo/package.json index 0bd569042..1faaf5677 100644 --- a/experimental/css-has-pseudo/package.json +++ b/experimental/css-has-pseudo/package.json @@ -17,14 +17,18 @@ "engines": { "node": "^14 || ^16 || >=18" }, + "type": "module", "main": "dist/index.cjs", "module": "dist/index.mjs", - "types": "dist/index.d.ts", "exports": { ".": { - "import": "./dist/index.mjs", - "require": "./dist/index.cjs", - "default": "./dist/index.mjs" + "import": { + "types": "./dist/index.d.ts", + "default": "./dist/index.mjs" + }, + "require": { + "default": "./dist/index.cjs" + } }, "./browser": { "import": "./dist/browser.mjs", diff --git a/experimental/postcss-gradient-stop-increments/CHANGELOG.md b/experimental/postcss-gradient-stop-increments/CHANGELOG.md index 7a44bda9f..08b522165 100644 --- a/experimental/postcss-gradient-stop-increments/CHANGELOG.md +++ b/experimental/postcss-gradient-stop-increments/CHANGELOG.md @@ -1,5 +1,9 @@ # Changes to PostCSS Gradient Stop Increments +### Unreleased (patch) + +- Fix type definitions + ### 1.0.4 _September 24, 2023_ diff --git a/experimental/postcss-gradient-stop-increments/api-extractor.json b/experimental/postcss-gradient-stop-increments/api-extractor.json new file mode 100644 index 000000000..42058be51 --- /dev/null +++ b/experimental/postcss-gradient-stop-increments/api-extractor.json @@ -0,0 +1,4 @@ +{ + "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json", + "extends": "../../api-extractor.json" +} diff --git a/experimental/postcss-gradient-stop-increments/dist/index.cjs b/experimental/postcss-gradient-stop-increments/dist/index.cjs index 628c765b0..b7c14a54f 100644 --- a/experimental/postcss-gradient-stop-increments/dist/index.cjs +++ b/experimental/postcss-gradient-stop-increments/dist/index.cjs @@ -1 +1 @@ -"use strict";var e=require("@csstools/css-parser-algorithms"),n=require("@csstools/css-calc"),o=require("@csstools/css-tokenizer");const t=/(repeating-)?(linear|radial|conic)-gradient\(/i,a=/^(repeating-)?(linear|radial|conic)-gradient$/i,i=/^(abs|acos|asin|atan|atan2|calc|clamp|cos|exp|hypot|log|max|min|mod|pow|rem|round|sign|sin|sqrt|tan)$/i,creator=n=>{const r=Object.assign({preserve:!1},n);return{postcssPlugin:"postcss-gradient-stop-increments",Declaration(n){if(!t.test(n.value))return;const s=o.tokenize({css:n.value});if(!s.find((e=>e[0]===o.TokenType.Delim&&"+"===e[4].value)))return;const u=e.stringify(e.replaceComponentValues(e.parseCommaSeparatedListOfComponentValues(s),(n=>{if(!e.isFunctionNode(n))return;const t=n.getName();if(!a.test(t))return;let r=null;for(let t=0;t0))}function isZeroOrNegative(n){return!(!e.isTokenNode(n)||n.value[0]!==o.TokenType.Percentage&&n.value[0]!==o.TokenType.Dimension&&n.value[0]!==o.TokenType.Number||!(n.value[4].value<=0))}function incrementLengthNode(t,a,i){if(!t)return i;const r=new e.FunctionNode([o.TokenType.Function,"calc(",-1,-1,{value:"calc"}],[o.TokenType.CloseParen,")",-1,-1,void 0],[t,new e.WhitespaceNode([[o.TokenType.Whitespace," ",-1,-1,void 0]]),a,new e.WhitespaceNode([[o.TokenType.Whitespace," ",-1,-1,void 0]]),i]),[[s]]=n.calcFromComponentValues([[r]]);return s}function maxOfLastAndCurrentLengthNode(t,a){if(!t)return a;const i=new e.FunctionNode([o.TokenType.Function,"max(",-1,-1,{value:"max"}],[o.TokenType.CloseParen,")",-1,-1,void 0],[t,new e.TokenNode([o.TokenType.Comma,",",-1,-1,void 0]),new e.WhitespaceNode([[o.TokenType.Whitespace," ",-1,-1,void 0]]),a]),[[r]]=n.calcFromComponentValues([[i]]);return r}creator.postcss=!0,module.exports=creator; +"use strict";var e=require("@csstools/css-parser-algorithms"),n=require("@csstools/css-calc"),o=require("@csstools/css-tokenizer");const t=/(repeating-)?(linear|radial|conic)-gradient\(/i,a=/^(repeating-)?(linear|radial|conic)-gradient$/i,i=/^(abs|acos|asin|atan|atan2|calc|clamp|cos|exp|hypot|log|max|min|mod|pow|rem|round|sign|sin|sqrt|tan)$/i,creator=n=>{const r=Object.assign({preserve:!1},n);return{postcssPlugin:"postcss-gradient-stop-increments",Declaration(n){if(!t.test(n.value))return;const s=o.tokenize({css:n.value});if(!s.find((e=>e[0]===o.TokenType.Delim&&"+"===e[4].value)))return;const u=e.stringify(e.replaceComponentValues(e.parseCommaSeparatedListOfComponentValues(s),(n=>{if(!e.isFunctionNode(n))return;const t=n.getName();if(!a.test(t))return;let r=null;for(let t=0;t0))}function isZeroOrNegative(n){return!(!e.isTokenNode(n)||n.value[0]!==o.TokenType.Percentage&&n.value[0]!==o.TokenType.Dimension&&n.value[0]!==o.TokenType.Number||!(n.value[4].value<=0))}function incrementLengthNode(t,a,i){if(!t)return i;const r=new e.FunctionNode([o.TokenType.Function,"calc(",-1,-1,{value:"calc"}],[o.TokenType.CloseParen,")",-1,-1,void 0],[t,new e.WhitespaceNode([[o.TokenType.Whitespace," ",-1,-1,void 0]]),a,new e.WhitespaceNode([[o.TokenType.Whitespace," ",-1,-1,void 0]]),i]),[[s]]=n.calcFromComponentValues([[r]]);return s}function maxOfLastAndCurrentLengthNode(t,a){if(!t)return a;const i=new e.FunctionNode([o.TokenType.Function,"max(",-1,-1,{value:"max"}],[o.TokenType.CloseParen,")",-1,-1,void 0],[t,new e.TokenNode([o.TokenType.Comma,",",-1,-1,void 0]),new e.WhitespaceNode([[o.TokenType.Whitespace," ",-1,-1,void 0]]),a]),[[r]]=n.calcFromComponentValues([[i]]);return r}creator.postcss=!0,module.exports=creator; diff --git a/experimental/postcss-gradient-stop-increments/dist/index.d.ts b/experimental/postcss-gradient-stop-increments/dist/index.d.ts index 8547e0f53..9a55a7819 100644 --- a/experimental/postcss-gradient-stop-increments/dist/index.d.ts +++ b/experimental/postcss-gradient-stop-increments/dist/index.d.ts @@ -1,8 +1,12 @@ import type { PluginCreator } from 'postcss'; + +declare const creator: PluginCreator; +export default creator; + /** postcss-gradient-stop-increments plugin options */ -export type pluginOptions = { +export declare type pluginOptions = { /** Preserve the original notation. default: false */ preserve?: boolean; }; -declare const creator: PluginCreator; -export default creator; + +export { } diff --git a/experimental/postcss-gradient-stop-increments/dist/index.mjs b/experimental/postcss-gradient-stop-increments/dist/index.mjs index 421e72c2f..36bd6a4d1 100644 --- a/experimental/postcss-gradient-stop-increments/dist/index.mjs +++ b/experimental/postcss-gradient-stop-increments/dist/index.mjs @@ -1 +1 @@ -import{stringify as e,replaceComponentValues as n,parseCommaSeparatedListOfComponentValues as t,isFunctionNode as a,isTokenNode as r,isCommentNode as i,TokenNode as s,FunctionNode as o,WhitespaceNode as l}from"@csstools/css-parser-algorithms";import{calcFromComponentValues as u}from"@csstools/css-calc";import{tokenize as c,TokenType as v,NumberType as m}from"@csstools/css-tokenizer";const f=/(repeating-)?(linear|radial|conic)-gradient\(/i,g=/^(repeating-)?(linear|radial|conic)-gradient$/i,d=/^(abs|acos|asin|atan|atan2|calc|clamp|cos|exp|hypot|log|max|min|mod|pow|rem|round|sign|sin|sqrt|tan)$/i,creator=o=>{const l=Object.assign({preserve:!1},o);return{postcssPlugin:"postcss-gradient-stop-increments",Declaration(o){if(!f.test(o.value))return;const u=c({css:o.value});if(!u.find((e=>e[0]===v.Delim&&"+"===e[4].value)))return;const p=e(n(t(u),(e=>{if(!a(e))return;const n=e.getName();if(!g.test(n))return;let t=null;for(let n=0;n0))}function isZeroOrNegative(e){return!(!r(e)||e.value[0]!==v.Percentage&&e.value[0]!==v.Dimension&&e.value[0]!==v.Number||!(e.value[4].value<=0))}function incrementLengthNode(e,n,t){if(!e)return t;const a=new o([v.Function,"calc(",-1,-1,{value:"calc"}],[v.CloseParen,")",-1,-1,void 0],[e,new l([[v.Whitespace," ",-1,-1,void 0]]),n,new l([[v.Whitespace," ",-1,-1,void 0]]),t]),[[r]]=u([[a]]);return r}function maxOfLastAndCurrentLengthNode(e,n){if(!e)return n;const t=new o([v.Function,"max(",-1,-1,{value:"max"}],[v.CloseParen,")",-1,-1,void 0],[e,new s([v.Comma,",",-1,-1,void 0]),new l([[v.Whitespace," ",-1,-1,void 0]]),n]),[[a]]=u([[t]]);return a}creator.postcss=!0;export{creator as default}; +import{stringify as e,replaceComponentValues as n,parseCommaSeparatedListOfComponentValues as t,isFunctionNode as a,isTokenNode as r,isCommentNode as i,TokenNode as s,FunctionNode as o,WhitespaceNode as l}from"@csstools/css-parser-algorithms";import{calcFromComponentValues as u}from"@csstools/css-calc";import{tokenize as c,TokenType as v,NumberType as m}from"@csstools/css-tokenizer";const f=/(repeating-)?(linear|radial|conic)-gradient\(/i,g=/^(repeating-)?(linear|radial|conic)-gradient$/i,d=/^(abs|acos|asin|atan|atan2|calc|clamp|cos|exp|hypot|log|max|min|mod|pow|rem|round|sign|sin|sqrt|tan)$/i,creator=o=>{const l=Object.assign({preserve:!1},o);return{postcssPlugin:"postcss-gradient-stop-increments",Declaration(o){if(!f.test(o.value))return;const u=c({css:o.value});if(!u.find((e=>e[0]===v.Delim&&"+"===e[4].value)))return;const p=e(n(t(u),(e=>{if(!a(e))return;const n=e.getName();if(!g.test(n))return;let t=null;for(let n=0;n0))}function isZeroOrNegative(e){return!(!r(e)||e.value[0]!==v.Percentage&&e.value[0]!==v.Dimension&&e.value[0]!==v.Number||!(e.value[4].value<=0))}function incrementLengthNode(e,n,t){if(!e)return t;const a=new o([v.Function,"calc(",-1,-1,{value:"calc"}],[v.CloseParen,")",-1,-1,void 0],[e,new l([[v.Whitespace," ",-1,-1,void 0]]),n,new l([[v.Whitespace," ",-1,-1,void 0]]),t]),[[r]]=u([[a]]);return r}function maxOfLastAndCurrentLengthNode(e,n){if(!e)return n;const t=new o([v.Function,"max(",-1,-1,{value:"max"}],[v.CloseParen,")",-1,-1,void 0],[e,new s([v.Comma,",",-1,-1,void 0]),new l([[v.Whitespace," ",-1,-1,void 0]]),n]),[[a]]=u([[t]]);return a}creator.postcss=!0;export{creator as default}; diff --git a/experimental/postcss-gradient-stop-increments/package.json b/experimental/postcss-gradient-stop-increments/package.json index 615d2e7d5..14818a193 100644 --- a/experimental/postcss-gradient-stop-increments/package.json +++ b/experimental/postcss-gradient-stop-increments/package.json @@ -27,15 +27,18 @@ "engines": { "node": "^14 || ^16 || >=18" }, + "type": "module", "main": "dist/index.cjs", "module": "dist/index.mjs", - "types": "dist/index.d.ts", "exports": { ".": { - "types": "./dist/index.d.ts", - "import": "./dist/index.mjs", - "require": "./dist/index.cjs", - "default": "./dist/index.mjs" + "import": { + "types": "./dist/index.d.ts", + "default": "./dist/index.mjs" + }, + "require": { + "default": "./dist/index.cjs" + } } }, "files": [ diff --git a/experimental/postcss-nesting/CHANGELOG.md b/experimental/postcss-nesting/CHANGELOG.md index 62f488a4e..928166e34 100644 --- a/experimental/postcss-nesting/CHANGELOG.md +++ b/experimental/postcss-nesting/CHANGELOG.md @@ -1,5 +1,9 @@ # Changes to PostCSS Nesting Experimental +### Unreleased (patch) + +- Fix type definitions + ### 2.0.0 _January 24, 2023_ diff --git a/experimental/postcss-nesting/api-extractor.json b/experimental/postcss-nesting/api-extractor.json new file mode 100644 index 000000000..42058be51 --- /dev/null +++ b/experimental/postcss-nesting/api-extractor.json @@ -0,0 +1,4 @@ +{ + "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json", + "extends": "../../api-extractor.json" +} diff --git a/experimental/postcss-nesting/dist/index.cjs b/experimental/postcss-nesting/dist/index.cjs index 8cf16c032..323956326 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=>{var n;"root"===(null==(n=t.parent)||null==(n=n.parent)?void 0:n.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){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; diff --git a/experimental/postcss-nesting/dist/index.d.ts b/experimental/postcss-nesting/dist/index.d.ts index 89d75c8fd..73f8cdb79 100644 --- a/experimental/postcss-nesting/dist/index.d.ts +++ b/experimental/postcss-nesting/dist/index.d.ts @@ -1,3 +1,6 @@ import type { PluginCreator } from 'postcss'; + declare const creator: PluginCreator; export default creator; + +export { } diff --git a/experimental/postcss-nesting/dist/index.mjs b/experimental/postcss-nesting/dist/index.mjs index 3f8f025d9..ebd787d73 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=>{var n;"root"===(null==(n=t.parent)||null==(n=n.parent)?void 0:n.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 l=e().astSync(`:is(${r.join(",")})`);for(let r=0;r{"nesting"===e.type&&(a=!0)})),!a){const s=i.nodes[0];let l=!1;if(s.each((e=>"combinator"===e.type&&(l=!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]}"`)}l||s.insertBefore(s.at(0),e.combinator({value:" "})),s.insertBefore(s.at(0),e.nesting({}))}i.walk((e=>{"nesting"===e.type&&e.replaceWith(l.clone({}))})),s.push(i.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,l=!1;for(const i of e)l?l=!1:"\\"===i?l=!0:s?i===s&&(s=!1):'"'===i||"'"===i?s=i:"("===i?o+=1:")"===i?o>0&&(o-=1):0===o&&","===i&&(r=!0),r?(""!==n&&t.push(n.trim()),n="",r=!1):n+=i;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){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}; diff --git a/experimental/postcss-nesting/dist/lib/ampersand-to-scope.d.ts b/experimental/postcss-nesting/dist/lib/ampersand-to-scope.d.ts deleted file mode 100644 index f82c36f94..000000000 --- a/experimental/postcss-nesting/dist/lib/ampersand-to-scope.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import type { Result, Rule } from 'postcss'; -export default function ampersandToScope(rule: Rule, result: Result): void; diff --git a/experimental/postcss-nesting/dist/lib/atrule-within-atrule.d.ts b/experimental/postcss-nesting/dist/lib/atrule-within-atrule.d.ts deleted file mode 100644 index f06ffa9a7..000000000 --- a/experimental/postcss-nesting/dist/lib/atrule-within-atrule.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -import type { AtRule } from 'postcss'; -export default function transformAtruleWithinAtrule(node: AtRule, parent: AtRule): void; -export declare function isAtruleWithinAtrule(node: AtRule, parent: AtRule): boolean; diff --git a/experimental/postcss-nesting/dist/lib/atrule-within-rule.d.ts b/experimental/postcss-nesting/dist/lib/atrule-within-rule.d.ts deleted file mode 100644 index 3632d999d..000000000 --- a/experimental/postcss-nesting/dist/lib/atrule-within-rule.d.ts +++ /dev/null @@ -1,4 +0,0 @@ -import { walkFunc } from './walk-func.js'; -import type { AtRule, Result, Rule } from 'postcss'; -export default function atruleWithinRule(node: AtRule, parent: Rule, result: Result, walk: walkFunc): void; -export declare function isAtruleWithinRule(node: AtRule): boolean; diff --git a/experimental/postcss-nesting/dist/lib/cleanup-parent.d.ts b/experimental/postcss-nesting/dist/lib/cleanup-parent.d.ts deleted file mode 100644 index 5547db143..000000000 --- a/experimental/postcss-nesting/dist/lib/cleanup-parent.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import type { ChildNode, Container } from 'postcss'; -export default function cleanupParent(parent: Container): void; diff --git a/experimental/postcss-nesting/dist/lib/group-declarations.d.ts b/experimental/postcss-nesting/dist/lib/group-declarations.d.ts deleted file mode 100644 index 116434201..000000000 --- a/experimental/postcss-nesting/dist/lib/group-declarations.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import type { ChildNode, Container } from 'postcss'; -export default function groupDeclarations(node: Container): void; diff --git a/experimental/postcss-nesting/dist/lib/is-type-of-rule.d.ts b/experimental/postcss-nesting/dist/lib/is-type-of-rule.d.ts deleted file mode 100644 index 1df997c8f..000000000 --- a/experimental/postcss-nesting/dist/lib/is-type-of-rule.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -import type { AtRule, Node, Rule } from 'postcss'; -export declare function isAtRule(node?: Node): node is AtRule; -export declare function isRule(node?: Node): node is Rule; diff --git a/experimental/postcss-nesting/dist/lib/list.d.ts b/experimental/postcss-nesting/dist/lib/list.d.ts deleted file mode 100644 index 67a64736d..000000000 --- a/experimental/postcss-nesting/dist/lib/list.d.ts +++ /dev/null @@ -1 +0,0 @@ -export declare function comma(string: string): string[]; diff --git a/experimental/postcss-nesting/dist/lib/merge-params.d.ts b/experimental/postcss-nesting/dist/lib/merge-params.d.ts deleted file mode 100644 index 0547e8f7b..000000000 --- a/experimental/postcss-nesting/dist/lib/merge-params.d.ts +++ /dev/null @@ -1 +0,0 @@ -export default function mergeParams(fromParams: string, toParams: string): string; diff --git a/experimental/postcss-nesting/dist/lib/merge-selectors/merge-selectors.d.ts b/experimental/postcss-nesting/dist/lib/merge-selectors/merge-selectors.d.ts deleted file mode 100644 index 760ba6abe..000000000 --- a/experimental/postcss-nesting/dist/lib/merge-selectors/merge-selectors.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import type { Node, Result } from 'postcss'; -export default function mergeSelectors(node: Node, postcssResult: Result, fromSelectors: Array, toSelectors: Array): any[]; diff --git a/experimental/postcss-nesting/dist/lib/rule-within-rule.d.ts b/experimental/postcss-nesting/dist/lib/rule-within-rule.d.ts deleted file mode 100644 index 9d1e0ee5c..000000000 --- a/experimental/postcss-nesting/dist/lib/rule-within-rule.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import type { Result, Rule } from 'postcss'; -export default function transformRuleWithinRule(node: Rule, parent: Rule, result: Result): void; diff --git a/experimental/postcss-nesting/dist/lib/shift-nodes-before-parent.d.ts b/experimental/postcss-nesting/dist/lib/shift-nodes-before-parent.d.ts deleted file mode 100644 index 0876f2ba6..000000000 --- a/experimental/postcss-nesting/dist/lib/shift-nodes-before-parent.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import type { ChildNode, Container } from 'postcss'; -export default function shiftNodesBeforeParent(node: ChildNode, parent: Container): void; diff --git a/experimental/postcss-nesting/dist/lib/valid-atrules.d.ts b/experimental/postcss-nesting/dist/lib/valid-atrules.d.ts deleted file mode 100644 index d451d2bc5..000000000 --- a/experimental/postcss-nesting/dist/lib/valid-atrules.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -declare const _default: string[]; -export default _default; diff --git a/experimental/postcss-nesting/dist/lib/walk-func.d.ts b/experimental/postcss-nesting/dist/lib/walk-func.d.ts deleted file mode 100644 index eaa8ff3c3..000000000 --- a/experimental/postcss-nesting/dist/lib/walk-func.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import type { Container, Result } from 'postcss'; -export type walkFunc = (node: Container, result: Result) => void; diff --git a/experimental/postcss-nesting/dist/lib/walk.d.ts b/experimental/postcss-nesting/dist/lib/walk.d.ts deleted file mode 100644 index c4a943457..000000000 --- a/experimental/postcss-nesting/dist/lib/walk.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import type { Container, Result } from 'postcss'; -export default function walk(node: Container, result: Result): void; diff --git a/experimental/postcss-nesting/package.json b/experimental/postcss-nesting/package.json index 056bdaa55..cfc378a77 100644 --- a/experimental/postcss-nesting/package.json +++ b/experimental/postcss-nesting/package.json @@ -17,14 +17,18 @@ "engines": { "node": "^14 || ^16 || >=18" }, + "type": "module", "main": "dist/index.cjs", "module": "dist/index.mjs", - "types": "dist/index.d.ts", "exports": { ".": { - "import": "./dist/index.mjs", - "require": "./dist/index.cjs", - "default": "./dist/index.mjs" + "import": { + "types": "./dist/index.d.ts", + "default": "./dist/index.mjs" + }, + "require": { + "default": "./dist/index.cjs" + } } }, "files": [ diff --git a/knip.json b/knip.json index 465bb4aa9..abed13f68 100644 --- a/knip.json +++ b/knip.json @@ -102,6 +102,7 @@ "ignoreDependencies": [ "@babel/core", "@babel/preset-env", + "@microsoft/api-extractor", "@rollup/plugin-babel", "@rollup/plugin-commonjs", "@rollup/plugin-node-resolve", diff --git a/package-lock.json b/package-lock.json index 89267825f..7e2f7d197 100644 --- a/package-lock.json +++ b/package-lock.json @@ -28,6 +28,7 @@ "devDependencies": { "@babel/core": "^7.23.6", "@babel/preset-env": "^7.23.6", + "@microsoft/api-extractor": "^7.38.4", "@rollup/plugin-babel": "^6.0.3", "@rollup/plugin-commonjs": "^25.0.7", "@rollup/plugin-node-resolve": "^15.2.3", @@ -2289,22 +2290,6 @@ "url": "https://opencollective.com/eslint" } }, - "node_modules/@eslint/eslintrc/node_modules/ajv": { - "version": "6.12.6", - "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz", - "integrity": "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==", - "dev": true, - "dependencies": { - "fast-deep-equal": "^3.1.1", - "fast-json-stable-stringify": "^2.0.0", - "json-schema-traverse": "^0.4.1", - "uri-js": "^4.2.2" - }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/epoberezkin" - } - }, "node_modules/@eslint/eslintrc/node_modules/brace-expansion": { "version": "1.1.11", "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", @@ -2330,12 +2315,6 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/@eslint/eslintrc/node_modules/json-schema-traverse": { - "version": "0.4.1", - "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", - "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", - "dev": true - }, "node_modules/@eslint/eslintrc/node_modules/minimatch": { "version": "3.1.2", "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", @@ -2590,6 +2569,117 @@ "node": ">= 0.4" } }, + "node_modules/@microsoft/api-extractor": { + "version": "7.38.5", + "resolved": "https://registry.npmjs.org/@microsoft/api-extractor/-/api-extractor-7.38.5.tgz", + "integrity": "sha512-c/w2zfqBcBJxaCzpJNvFoouWewcYrUOfeu5ZkWCCIXTF9a/gXM85RGevEzlMAIEGM/kssAAZSXRJIZ3Q5vLFow==", + "dev": true, + "dependencies": { + "@microsoft/api-extractor-model": "7.28.3", + "@microsoft/tsdoc": "0.14.2", + "@microsoft/tsdoc-config": "~0.16.1", + "@rushstack/node-core-library": "3.62.0", + "@rushstack/rig-package": "0.5.1", + "@rushstack/ts-command-line": "4.17.1", + "colors": "~1.2.1", + "lodash": "~4.17.15", + "resolve": "~1.22.1", + "semver": "~7.5.4", + "source-map": "~0.6.1", + "typescript": "~5.0.4" + }, + "bin": { + "api-extractor": "bin/api-extractor" + } + }, + "node_modules/@microsoft/api-extractor-model": { + "version": "7.28.3", + "resolved": "https://registry.npmjs.org/@microsoft/api-extractor-model/-/api-extractor-model-7.28.3.tgz", + "integrity": "sha512-wT/kB2oDbdZXITyDh2SQLzaWwTOFbV326fP0pUwNW00WeliARs0qjmXBWmGWardEzp2U3/axkO3Lboqun6vrig==", + "dev": true, + "dependencies": { + "@microsoft/tsdoc": "0.14.2", + "@microsoft/tsdoc-config": "~0.16.1", + "@rushstack/node-core-library": "3.62.0" + } + }, + "node_modules/@microsoft/api-extractor/node_modules/lru-cache": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz", + "integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==", + "dev": true, + "dependencies": { + "yallist": "^4.0.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/@microsoft/api-extractor/node_modules/semver": { + "version": "7.5.4", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.5.4.tgz", + "integrity": "sha512-1bCSESV6Pv+i21Hvpxp3Dx+pSD8lIPt8uVjRrxAUt/nbswYc+tK6Y2btiULjd4+fnq15PX+nqQDC7Oft7WkwcA==", + "dev": true, + "dependencies": { + "lru-cache": "^6.0.0" + }, + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/@microsoft/api-extractor/node_modules/typescript": { + "version": "5.0.4", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.0.4.tgz", + "integrity": "sha512-cW9T5W9xY37cc+jfEnaUvX91foxtHkza3Nw3wkoF4sSlKn0MONdkdEndig/qPBWXNkmplh3NzayQzCiHM4/hqw==", + "dev": true, + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=12.20" + } + }, + "node_modules/@microsoft/api-extractor/node_modules/yallist": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", + "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==", + "dev": true + }, + "node_modules/@microsoft/tsdoc": { + "version": "0.14.2", + "resolved": "https://registry.npmjs.org/@microsoft/tsdoc/-/tsdoc-0.14.2.tgz", + "integrity": "sha512-9b8mPpKrfeGRuhFH5iO1iwCLeIIsV6+H1sRfxbkoGXIyQE2BTsPd9zqSqQJ+pv5sJ/hT5M1zvOFL02MnEezFug==", + "dev": true + }, + "node_modules/@microsoft/tsdoc-config": { + "version": "0.16.2", + "resolved": "https://registry.npmjs.org/@microsoft/tsdoc-config/-/tsdoc-config-0.16.2.tgz", + "integrity": "sha512-OGiIzzoBLgWWR0UdRJX98oYO+XKGf7tiK4Zk6tQ/E4IJqGCe7dvkTvgDZV5cFJUzLGDOjeAXrnZoA6QkVySuxw==", + "dev": true, + "dependencies": { + "@microsoft/tsdoc": "0.14.2", + "ajv": "~6.12.6", + "jju": "~1.4.0", + "resolve": "~1.19.0" + } + }, + "node_modules/@microsoft/tsdoc-config/node_modules/resolve": { + "version": "1.19.0", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.19.0.tgz", + "integrity": "sha512-rArEXAgsBG4UgRGcynxWIWKFvh/XZCcS8UJdHhwy91zwAvCZIbcs+vAbflgBnNjYMs/i/i+/Ux6IZhML1yPvxg==", + "dev": true, + "dependencies": { + "is-core-module": "^2.1.0", + "path-parse": "^1.0.6" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/@mrhenry/core-web": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/@mrhenry/core-web/-/core-web-1.2.1.tgz", @@ -3592,6 +3682,84 @@ "win32" ] }, + "node_modules/@rushstack/node-core-library": { + "version": "3.62.0", + "resolved": "https://registry.npmjs.org/@rushstack/node-core-library/-/node-core-library-3.62.0.tgz", + "integrity": "sha512-88aJn2h8UpSvdwuDXBv1/v1heM6GnBf3RjEy6ZPP7UnzHNCqOHA2Ut+ScYUbXcqIdfew9JlTAe3g+cnX9xQ/Aw==", + "dev": true, + "dependencies": { + "colors": "~1.2.1", + "fs-extra": "~7.0.1", + "import-lazy": "~4.0.0", + "jju": "~1.4.0", + "resolve": "~1.22.1", + "semver": "~7.5.4", + "z-schema": "~5.0.2" + }, + "peerDependencies": { + "@types/node": "*" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@rushstack/node-core-library/node_modules/lru-cache": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz", + "integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==", + "dev": true, + "dependencies": { + "yallist": "^4.0.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/@rushstack/node-core-library/node_modules/semver": { + "version": "7.5.4", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.5.4.tgz", + "integrity": "sha512-1bCSESV6Pv+i21Hvpxp3Dx+pSD8lIPt8uVjRrxAUt/nbswYc+tK6Y2btiULjd4+fnq15PX+nqQDC7Oft7WkwcA==", + "dev": true, + "dependencies": { + "lru-cache": "^6.0.0" + }, + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/@rushstack/node-core-library/node_modules/yallist": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", + "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==", + "dev": true + }, + "node_modules/@rushstack/rig-package": { + "version": "0.5.1", + "resolved": "https://registry.npmjs.org/@rushstack/rig-package/-/rig-package-0.5.1.tgz", + "integrity": "sha512-pXRYSe29TjRw7rqxD4WS3HN/sRSbfr+tJs4a9uuaSIBAITbUggygdhuG0VrO0EO+QqH91GhYMN4S6KRtOEmGVA==", + "dev": true, + "dependencies": { + "resolve": "~1.22.1", + "strip-json-comments": "~3.1.1" + } + }, + "node_modules/@rushstack/ts-command-line": { + "version": "4.17.1", + "resolved": "https://registry.npmjs.org/@rushstack/ts-command-line/-/ts-command-line-4.17.1.tgz", + "integrity": "sha512-2jweO1O57BYP5qdBGl6apJLB+aRIn5ccIRTPDyULh0KMwVzFqWtw6IZWt1qtUoZD/pD2RNkIOosH6Cq45rIYeg==", + "dev": true, + "dependencies": { + "@types/argparse": "1.0.38", + "argparse": "~1.0.9", + "colors": "~1.2.1", + "string-argv": "~0.3.1" + } + }, "node_modules/@sindresorhus/merge-streams": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/@sindresorhus/merge-streams/-/merge-streams-1.0.0.tgz", @@ -3687,6 +3855,22 @@ "node": ">=18.0.0" } }, + "node_modules/@stryker-mutator/core/node_modules/ajv": { + "version": "8.12.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.12.0.tgz", + "integrity": "sha512-sRu1kpcO9yLtYxBKvqfTeh9KzZEwO3STyX1HT+4CaDzC6HpTGYhIhPIzj9XuKU7KYDwnaeh5hcOwjy1QuJzBPA==", + "dev": true, + "dependencies": { + "fast-deep-equal": "^3.1.1", + "json-schema-traverse": "^1.0.0", + "require-from-string": "^2.0.2", + "uri-js": "^4.2.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, "node_modules/@stryker-mutator/core/node_modules/chalk": { "version": "5.3.0", "resolved": "https://registry.npmjs.org/chalk/-/chalk-5.3.0.tgz", @@ -3721,6 +3905,12 @@ "url": "https://github.com/sponsors/isaacs" } }, + "node_modules/@stryker-mutator/core/node_modules/json-schema-traverse": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", + "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", + "dev": true + }, "node_modules/@stryker-mutator/core/node_modules/lru-cache": { "version": "6.0.0", "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz", @@ -3748,6 +3938,15 @@ "node": ">=10" } }, + "node_modules/@stryker-mutator/core/node_modules/source-map": { + "version": "0.7.4", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.7.4.tgz", + "integrity": "sha512-l3BikUxvPOcn5E74dZiq5BGsTb5yEwhaTSzccU6t4sDOH8NWJCstKO5QT2CvtFoK6F0saL7p9xHAqHOlCPJygA==", + "dev": true, + "engines": { + "node": ">= 8" + } + }, "node_modules/@stryker-mutator/core/node_modules/yallist": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", @@ -3820,6 +4019,12 @@ "integrity": "sha512-C5Mc6rdnsaJDjO3UpGW/CQTHtCKaYlScZTly4JIu97Jxo/odCiH0ITnDXSJPTOrEKk/ycSZ0AOgTmkDtkOsvIA==", "dev": true }, + "node_modules/@types/argparse": { + "version": "1.0.38", + "resolved": "https://registry.npmjs.org/@types/argparse/-/argparse-1.0.38.tgz", + "integrity": "sha512-ebDJ9b0e702Yr7pWgB0jzm+CX4Srzz8RcXtLJDJB+BSccqMa36uyH/zUsSYao5+BD1ytv3k3rPYCq4mAE1hsXA==", + "dev": true + }, "node_modules/@types/estree": { "version": "1.0.5", "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.5.tgz", @@ -4234,14 +4439,14 @@ } }, "node_modules/ajv": { - "version": "8.12.0", - "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.12.0.tgz", - "integrity": "sha512-sRu1kpcO9yLtYxBKvqfTeh9KzZEwO3STyX1HT+4CaDzC6HpTGYhIhPIzj9XuKU7KYDwnaeh5hcOwjy1QuJzBPA==", + "version": "6.12.6", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz", + "integrity": "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==", "dev": true, "dependencies": { "fast-deep-equal": "^3.1.1", - "json-schema-traverse": "^1.0.0", - "require-from-string": "^2.0.2", + "fast-json-stable-stringify": "^2.0.0", + "json-schema-traverse": "^0.4.1", "uri-js": "^4.2.2" }, "funding": { @@ -4298,10 +4503,13 @@ } }, "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 + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz", + "integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==", + "dev": true, + "dependencies": { + "sprintf-js": "~1.0.2" + } }, "node_modules/arity-n": { "version": "1.0.4", @@ -4853,6 +5061,15 @@ "integrity": "sha512-jeC1axXpnb0/2nn/Y1LPuLdgXBLH7aDcHu4KEKfqw3CUhX7ZpfBSlPKyqXE6btIgEzfWtrX3/tyBCaCvXvMkOw==", "dev": true }, + "node_modules/colors": { + "version": "1.2.5", + "resolved": "https://registry.npmjs.org/colors/-/colors-1.2.5.tgz", + "integrity": "sha512-erNRLao/Y3Fv54qUa0LBB+//Uf3YwMUmdJinN20yMXm9zdKKqH9wt7R9IIVZ+K7ShzfpLV/Zg8+VyrBJYB4lpg==", + "dev": true, + "engines": { + "node": ">=0.1.90" + } + }, "node_modules/commander": { "version": "11.1.0", "resolved": "https://registry.npmjs.org/commander/-/commander-11.1.0.tgz", @@ -5352,16 +5569,6 @@ "source-map": "~0.6.1" } }, - "node_modules/escodegen/node_modules/source-map": { - "version": "0.6.1", - "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", - "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", - "dev": true, - "optional": true, - "engines": { - "node": ">=0.10.0" - } - }, "node_modules/eslint": { "version": "8.55.0", "resolved": "https://registry.npmjs.org/eslint/-/eslint-8.55.0.tgz", @@ -5445,22 +5652,6 @@ "url": "https://opencollective.com/eslint" } }, - "node_modules/eslint/node_modules/ajv": { - "version": "6.12.6", - "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz", - "integrity": "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==", - "dev": true, - "dependencies": { - "fast-deep-equal": "^3.1.1", - "fast-json-stable-stringify": "^2.0.0", - "json-schema-traverse": "^0.4.1", - "uri-js": "^4.2.2" - }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/epoberezkin" - } - }, "node_modules/eslint/node_modules/ansi-styles": { "version": "4.3.0", "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", @@ -5556,12 +5747,6 @@ "node": ">=8" } }, - "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", - "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", - "dev": true - }, "node_modules/eslint/node_modules/minimatch": { "version": "3.1.2", "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", @@ -5991,17 +6176,17 @@ } }, "node_modules/fs-extra": { - "version": "10.1.0", - "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-10.1.0.tgz", - "integrity": "sha512-oRXApq54ETRj4eMiFzGnHWGy+zo5raudjuxN0b8H7s/RU2oW0Wvsx9O0ACRN/kRq9E8Vu/ReskGB5o3ji+FzHQ==", + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-7.0.1.tgz", + "integrity": "sha512-YJDaCJZEnBmcbw13fvdAM9AwNOJwOzrE4pqMqBq5nFiEqXUqHwlK4B+3pUw6JNvfSPtX05xFHtYy/1ni01eGCw==", "dev": true, "dependencies": { - "graceful-fs": "^4.2.0", - "jsonfile": "^6.0.1", - "universalify": "^2.0.0" + "graceful-fs": "^4.1.2", + "jsonfile": "^4.0.0", + "universalify": "^0.1.0" }, "engines": { - "node": ">=12" + "node": ">=6 <7 || >=8" } }, "node_modules/fs.realpath": { @@ -6128,24 +6313,6 @@ "node": ">=6 <7 || >=8" } }, - "node_modules/get-uri/node_modules/jsonfile": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-4.0.0.tgz", - "integrity": "sha512-m6F1R3z8jjlf2imQHS2Qez5sjKWQzbuuhuJ/FKYFRZvPE3PuHcSMVZzfsLhGVOkfd20obL5SWEBew5ShlquNxg==", - "dev": true, - "optionalDependencies": { - "graceful-fs": "^4.1.6" - } - }, - "node_modules/get-uri/node_modules/universalify": { - "version": "0.1.2", - "resolved": "https://registry.npmjs.org/universalify/-/universalify-0.1.2.tgz", - "integrity": "sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg==", - "dev": true, - "engines": { - "node": ">= 4.0.0" - } - }, "node_modules/glob": { "version": "8.1.0", "resolved": "https://registry.npmjs.org/glob/-/glob-8.1.0.tgz", @@ -6498,6 +6665,15 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/import-lazy": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/import-lazy/-/import-lazy-4.0.0.tgz", + "integrity": "sha512-rKtvo6a868b5Hu3heneU+L4yEQ4jYKLtjpnPeUdK7h0yzXGmyBTypknlkCvHFBqfX9YlorEiMM6Dnq/5atfHkw==", + "dev": true, + "engines": { + "node": ">=8" + } + }, "node_modules/imurmurhash": { "version": "0.1.4", "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz", @@ -6777,6 +6953,12 @@ "jiti": "bin/jiti.js" } }, + "node_modules/jju": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/jju/-/jju-1.4.0.tgz", + "integrity": "sha512-8wb9Yw966OSxApiCt0K3yNJL8pnNeIv+OEq2YMidz4FKP6nonSRoOXc80iXY4JaN2FC11B9qsNmDsm+ZOfMROA==", + "dev": true + }, "node_modules/js-tokens": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", @@ -6795,6 +6977,12 @@ "js-yaml": "bin/js-yaml.js" } }, + "node_modules/js-yaml/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/jsesc": { "version": "2.5.2", "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-2.5.2.tgz", @@ -6823,9 +7011,9 @@ } }, "node_modules/json-schema-traverse": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", - "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", + "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", "dev": true }, "node_modules/json-stable-stringify-without-jsonify": { @@ -6853,13 +7041,10 @@ } }, "node_modules/jsonfile": { - "version": "6.1.0", - "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.1.0.tgz", - "integrity": "sha512-5dgndWOriYSm5cnYaJNhalLNDKOqFwyDB/rr1E9ZsGciGvKPs8R2xYGCacuf3z6K1YKDz182fd+fY3cn3pMqXQ==", + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-4.0.0.tgz", + "integrity": "sha512-m6F1R3z8jjlf2imQHS2Qez5sjKWQzbuuhuJ/FKYFRZvPE3PuHcSMVZzfsLhGVOkfd20obL5SWEBew5ShlquNxg==", "dev": true, - "dependencies": { - "universalify": "^2.0.0" - }, "optionalDependencies": { "graceful-fs": "^4.1.6" } @@ -7080,12 +7265,24 @@ "integrity": "sha512-FT1yDzDYEoYWhnSGnpE/4Kj1fLZkDFyqRb7fNt6FdYOSxlUWAtp42Eh6Wb0rGIv/m9Bgo7x4GhQbm5Ys4SG5ow==", "dev": true }, + "node_modules/lodash.get": { + "version": "4.4.2", + "resolved": "https://registry.npmjs.org/lodash.get/-/lodash.get-4.4.2.tgz", + "integrity": "sha512-z+Uw/vLuy6gQe8cfaFWD7p0wVv8fJl3mbzXh33RS+0oW2wvUqiRXiQ69gLWSLpgB5/6sU+r6BlQR0MBILadqTQ==", + "dev": true + }, "node_modules/lodash.groupby": { "version": "4.6.0", "resolved": "https://registry.npmjs.org/lodash.groupby/-/lodash.groupby-4.6.0.tgz", "integrity": "sha512-5dcWxm23+VAoz+awKmBaiBvzox8+RqMgFhi7UvX9DHZr2HdxHXM/Wrf8cfKpsW37RNrvtPn6hSwNqurSILbmJw==", "dev": true }, + "node_modules/lodash.isequal": { + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/lodash.isequal/-/lodash.isequal-4.5.0.tgz", + "integrity": "sha512-pDo3lu8Jhfjqls6GkMgpahsF9kCyayhgykjyLMNFTKWrpVdAQtYyB4muAMWozBB4ig/dtWAmsMxLEI8wuz+DYQ==", + "dev": true + }, "node_modules/lodash.merge": { "version": "4.6.2", "resolved": "https://registry.npmjs.org/lodash.merge/-/lodash.merge-4.6.2.tgz", @@ -8855,6 +9052,41 @@ "node": ">=12.10" } }, + "node_modules/rename-overwrite/node_modules/fs-extra": { + "version": "10.1.0", + "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-10.1.0.tgz", + "integrity": "sha512-oRXApq54ETRj4eMiFzGnHWGy+zo5raudjuxN0b8H7s/RU2oW0Wvsx9O0ACRN/kRq9E8Vu/ReskGB5o3ji+FzHQ==", + "dev": true, + "dependencies": { + "graceful-fs": "^4.2.0", + "jsonfile": "^6.0.1", + "universalify": "^2.0.0" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/rename-overwrite/node_modules/jsonfile": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.1.0.tgz", + "integrity": "sha512-5dgndWOriYSm5cnYaJNhalLNDKOqFwyDB/rr1E9ZsGciGvKPs8R2xYGCacuf3z6K1YKDz182fd+fY3cn3pMqXQ==", + "dev": true, + "dependencies": { + "universalify": "^2.0.0" + }, + "optionalDependencies": { + "graceful-fs": "^4.1.6" + } + }, + "node_modules/rename-overwrite/node_modules/universalify": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.1.tgz", + "integrity": "sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==", + "dev": true, + "engines": { + "node": ">= 10.0.0" + } + }, "node_modules/require-directory": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", @@ -9322,12 +9554,12 @@ "dev": true }, "node_modules/source-map": { - "version": "0.7.4", - "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.7.4.tgz", - "integrity": "sha512-l3BikUxvPOcn5E74dZiq5BGsTb5yEwhaTSzccU6t4sDOH8NWJCstKO5QT2CvtFoK6F0saL7p9xHAqHOlCPJygA==", + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", "dev": true, "engines": { - "node": ">= 8" + "node": ">=0.10.0" } }, "node_modules/source-map-js": { @@ -9348,15 +9580,6 @@ "source-map": "^0.6.0" } }, - "node_modules/source-map-support/node_modules/source-map": { - "version": "0.6.1", - "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", - "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", - "dev": true, - "engines": { - "node": ">=0.10.0" - } - }, "node_modules/spdx-correct": { "version": "3.2.0", "resolved": "https://registry.npmjs.org/spdx-correct/-/spdx-correct-3.2.0.tgz", @@ -9398,6 +9621,12 @@ "readable-stream": "^3.0.0" } }, + "node_modules/sprintf-js": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz", + "integrity": "sha512-D9cPgkvLlV3t3IzL0D0YLvGA9Ahk4PcvVwUbN0dSGr1aP0Nrt4AEnTUbuGvquEC0mA64Gqt1fzirlRs5ibXx8g==", + "dev": true + }, "node_modules/ssri": { "version": "10.0.5", "resolved": "https://registry.npmjs.org/ssri/-/ssri-10.0.5.tgz", @@ -9438,24 +9667,6 @@ "node": ">=6 <7 || >=8" } }, - "node_modules/streamroller/node_modules/jsonfile": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-4.0.0.tgz", - "integrity": "sha512-m6F1R3z8jjlf2imQHS2Qez5sjKWQzbuuhuJ/FKYFRZvPE3PuHcSMVZzfsLhGVOkfd20obL5SWEBew5ShlquNxg==", - "dev": true, - "optionalDependencies": { - "graceful-fs": "^4.1.6" - } - }, - "node_modules/streamroller/node_modules/universalify": { - "version": "0.1.2", - "resolved": "https://registry.npmjs.org/universalify/-/universalify-0.1.2.tgz", - "integrity": "sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg==", - "dev": true, - "engines": { - "node": ">= 4.0.0" - } - }, "node_modules/streamx": { "version": "2.15.6", "resolved": "https://registry.npmjs.org/streamx/-/streamx-2.15.6.tgz", @@ -9475,6 +9686,15 @@ "safe-buffer": "~5.2.0" } }, + "node_modules/string-argv": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/string-argv/-/string-argv-0.3.2.tgz", + "integrity": "sha512-aqD2Q0144Z+/RqG52NeHEkZauTAUWJO8c6yTftGJKO3Tja5tUgIfmIl6kExvhtxSDP7fXB6DvzkfMpCd/F3G+Q==", + "dev": true, + "engines": { + "node": ">=0.6.19" + } + }, "node_modules/string-width": { "version": "4.2.3", "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", @@ -9846,6 +10066,28 @@ "node": ">=10.0.0" } }, + "node_modules/table/node_modules/ajv": { + "version": "8.12.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.12.0.tgz", + "integrity": "sha512-sRu1kpcO9yLtYxBKvqfTeh9KzZEwO3STyX1HT+4CaDzC6HpTGYhIhPIzj9XuKU7KYDwnaeh5hcOwjy1QuJzBPA==", + "dev": true, + "dependencies": { + "fast-deep-equal": "^3.1.1", + "json-schema-traverse": "^1.0.0", + "require-from-string": "^2.0.2", + "uri-js": "^4.2.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/table/node_modules/json-schema-traverse": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", + "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", + "dev": true + }, "node_modules/tar-fs": { "version": "3.0.4", "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-3.0.4.tgz", @@ -10174,12 +10416,12 @@ } }, "node_modules/universalify": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.1.tgz", - "integrity": "sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==", + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/universalify/-/universalify-0.1.2.tgz", + "integrity": "sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg==", "dev": true, "engines": { - "node": ">= 10.0.0" + "node": ">= 4.0.0" } }, "node_modules/update-browserslist-db": { @@ -10253,6 +10495,15 @@ "node": "^12.13.0 || ^14.15.0 || >=16.0.0" } }, + "node_modules/validator": { + "version": "13.11.0", + "resolved": "https://registry.npmjs.org/validator/-/validator-13.11.0.tgz", + "integrity": "sha512-Ii+sehpSfZy+At5nPdnyMhx78fEoPDkR2XW/zimHEL3MyGJQOCQ7WeP20jPYRz7ZCpcKLB21NxuXHF3bxjStBQ==", + "dev": true, + "engines": { + "node": ">= 0.10" + } + }, "node_modules/version-selector-type": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/version-selector-type/-/version-selector-type-3.0.0.tgz", @@ -10552,6 +10803,36 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/z-schema": { + "version": "5.0.5", + "resolved": "https://registry.npmjs.org/z-schema/-/z-schema-5.0.5.tgz", + "integrity": "sha512-D7eujBWkLa3p2sIpJA0d1pr7es+a7m0vFAnZLlCEKq/Ij2k0MLi9Br2UPxoxdYystm5K1yeBGzub0FlYUEWj2Q==", + "dev": true, + "dependencies": { + "lodash.get": "^4.4.2", + "lodash.isequal": "^4.5.0", + "validator": "^13.7.0" + }, + "bin": { + "z-schema": "bin/z-schema" + }, + "engines": { + "node": ">=8.0.0" + }, + "optionalDependencies": { + "commander": "^9.4.1" + } + }, + "node_modules/z-schema/node_modules/commander": { + "version": "9.5.0", + "resolved": "https://registry.npmjs.org/commander/-/commander-9.5.0.tgz", + "integrity": "sha512-KRs7WVDKg86PWiuAqhDrAQnTXZKraVcCc6vFdL14qrZ/DcWwuRo7VoiYXalXO7S5GKpqYiVEwCbgFDfxNHKJBQ==", + "dev": true, + "optional": true, + "engines": { + "node": "^12.20.0 || >=14" + } + }, "node_modules/zod": { "version": "3.22.4", "resolved": "https://registry.npmjs.org/zod/-/zod-3.22.4.tgz", diff --git a/package.json b/package.json index 55677090a..107cd225b 100644 --- a/package.json +++ b/package.json @@ -28,6 +28,7 @@ "devDependencies": { "@babel/core": "^7.23.6", "@babel/preset-env": "^7.23.6", + "@microsoft/api-extractor": "^7.38.4", "@rollup/plugin-babel": "^6.0.3", "@rollup/plugin-commonjs": "^25.0.7", "@rollup/plugin-node-resolve": "^15.2.3", @@ -55,6 +56,6 @@ "knip": "knip" }, "volta": { - "node": "20.5.0" + "node": "20.10.0" } } diff --git a/packages/base-cli/api-extractor.json b/packages/base-cli/api-extractor.json new file mode 100644 index 000000000..42058be51 --- /dev/null +++ b/packages/base-cli/api-extractor.json @@ -0,0 +1,4 @@ +{ + "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json", + "extends": "../../api-extractor.json" +} diff --git a/packages/base-cli/dist/args.d.ts b/packages/base-cli/dist/args.d.ts deleted file mode 100644 index 74e1d3483..000000000 --- a/packages/base-cli/dist/args.d.ts +++ /dev/null @@ -1,16 +0,0 @@ -export type Arguments = { - stdin: boolean; - stdout: boolean; - inputs: Array; - output: string | undefined; - outputDir: string | undefined; - externalMap: boolean; - inlineMap: boolean; - replace: boolean; - pluginOptions: Record; - debug: boolean; -}; -export declare enum SignalValue { - InvalidArguments = "INVALID_ARGUMENTS" -} -export declare function parseArguments(args: Array, allowedPluginOpts: Array, helpLogger: () => void): Arguments | SignalValue; diff --git a/packages/base-cli/dist/get-stdin.d.ts b/packages/base-cli/dist/get-stdin.d.ts deleted file mode 100644 index e40e6c58f..000000000 --- a/packages/base-cli/dist/get-stdin.d.ts +++ /dev/null @@ -1 +0,0 @@ -export declare function getStdin(): Promise; diff --git a/packages/base-cli/dist/help.d.ts b/packages/base-cli/dist/help.d.ts deleted file mode 100644 index 9c6178ebf..000000000 --- a/packages/base-cli/dist/help.d.ts +++ /dev/null @@ -1 +0,0 @@ -export declare function helpTextLogger(command: string, name: string, description: string, exampleOptions?: Record | null): () => void; diff --git a/packages/base-cli/dist/index.d.ts b/packages/base-cli/dist/index.d.ts index 8f1b5ea92..9b8c5ea39 100644 --- a/packages/base-cli/dist/index.d.ts +++ b/packages/base-cli/dist/index.d.ts @@ -1,5 +1,28 @@ import type { PluginCreator } from 'postcss'; -export { parseArguments } from './args'; -export { helpTextLogger } from './help'; -type PluginCreatorOptions = Record | null; + +export declare type Arguments = { + stdin: boolean; + stdout: boolean; + inputs: Array; + output: string | undefined; + outputDir: string | undefined; + externalMap: boolean; + inlineMap: boolean; + replace: boolean; + pluginOptions: Record; + debug: boolean; +}; + export declare function cli(plugin: PluginCreator, allowedPluginOpts: Array, helpLogger: () => void, standalone?: boolean): Promise; + +export declare function helpTextLogger(command: string, name: string, description: string, exampleOptions?: Record | null): () => void; + +export declare function parseArguments(args: Array, allowedPluginOpts: Array, helpLogger: () => void): Arguments | SignalValue; + +export declare type PluginCreatorOptions = Record | null; + +export declare enum SignalValue { + InvalidArguments = "INVALID_ARGUMENTS" +} + +export { } diff --git a/packages/base-cli/dist/io-fs-to-fs.d.ts b/packages/base-cli/dist/io-fs-to-fs.d.ts deleted file mode 100644 index 58c29b384..000000000 --- a/packages/base-cli/dist/io-fs-to-fs.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -import type { Plugin } from 'postcss'; -import { Arguments } from './args'; -export declare function fsToFs(plugin: Plugin, argo: Arguments): Promise; diff --git a/packages/base-cli/dist/io-fs-to-stdout.d.ts b/packages/base-cli/dist/io-fs-to-stdout.d.ts deleted file mode 100644 index d657e78e1..000000000 --- a/packages/base-cli/dist/io-fs-to-stdout.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -import type { Plugin } from 'postcss'; -import { Arguments } from './args'; -export declare function fsToStdout(plugin: Plugin, argo: Arguments): Promise; diff --git a/packages/base-cli/dist/io-stdin-to-fs.d.ts b/packages/base-cli/dist/io-stdin-to-fs.d.ts deleted file mode 100644 index 4f136e51b..000000000 --- a/packages/base-cli/dist/io-stdin-to-fs.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -import type { Plugin } from 'postcss'; -import { Arguments } from './args'; -export declare function stdinToFs(plugin: Plugin, argo: Arguments, helpLogger: () => void): Promise; diff --git a/packages/base-cli/dist/io-stdin-to-stdout.d.ts b/packages/base-cli/dist/io-stdin-to-stdout.d.ts deleted file mode 100644 index 4c75c03c0..000000000 --- a/packages/base-cli/dist/io-stdin-to-stdout.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -import { Arguments } from './args'; -import type { Plugin } from 'postcss'; -export declare function stdinToStdout(plugin: Plugin, argo: Arguments, helpLogger: () => void): Promise; diff --git a/packages/base-cli/package.json b/packages/base-cli/package.json index 071594d9c..4749c90a3 100644 --- a/packages/base-cli/package.json +++ b/packages/base-cli/package.json @@ -18,15 +18,18 @@ "engines": { "node": "^14 || ^16 || >=18" }, + "type": "module", "main": "dist/index.cjs", "module": "dist/index.mjs", - "types": "dist/index.d.ts", "exports": { ".": { - "types": "./dist/index.d.ts", - "import": "./dist/index.mjs", - "require": "./dist/index.cjs", - "default": "./dist/index.mjs" + "import": { + "types": "./dist/index.d.ts", + "default": "./dist/index.mjs" + }, + "require": { + "default": "./dist/index.cjs" + } } }, "peerDependencies": { diff --git a/packages/base-cli/src/index.ts b/packages/base-cli/src/index.ts index 563df61c8..6dca4db32 100644 --- a/packages/base-cli/src/index.ts +++ b/packages/base-cli/src/index.ts @@ -8,7 +8,8 @@ import { fsToFs } from './io-fs-to-fs'; export { parseArguments } from './args'; export { helpTextLogger } from './help'; -type PluginCreatorOptions = Record | null; +export type { Arguments, SignalValue } from './args'; +export type PluginCreatorOptions = Record | null; export async function cli(plugin: PluginCreator, allowedPluginOpts: Array, helpLogger: () => void, standalone = true) { // Get process and plugin options from the command line diff --git a/packages/cascade-layer-name-parser/CHANGELOG.md b/packages/cascade-layer-name-parser/CHANGELOG.md index 0103fffeb..22813e007 100644 --- a/packages/cascade-layer-name-parser/CHANGELOG.md +++ b/packages/cascade-layer-name-parser/CHANGELOG.md @@ -2,7 +2,7 @@ ### Unreleased (patch) -- Small fixes in type definitions +- Fix type definitions ### 1.0.5 diff --git a/packages/cascade-layer-name-parser/api-extractor.json b/packages/cascade-layer-name-parser/api-extractor.json new file mode 100644 index 000000000..42058be51 --- /dev/null +++ b/packages/cascade-layer-name-parser/api-extractor.json @@ -0,0 +1,4 @@ +{ + "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json", + "extends": "../../api-extractor.json" +} diff --git a/packages/cascade-layer-name-parser/dist/index.cjs b/packages/cascade-layer-name-parser/dist/index.cjs index 08d613788..6d8efe7f3 100644 --- a/packages/cascade-layer-name-parser/dist/index.cjs +++ b/packages/cascade-layer-name-parser/dist/index.cjs @@ -1 +1 @@ -"use strict";var e=require("@csstools/css-tokenizer"),n=require("@csstools/css-parser-algorithms");class LayerName{parts;constructor(e){this.parts=e}tokens(){return[...this.parts]}slice(n,r){const t=[];for(let n=0;nn[0]===e.TokenType.Ident||n[0]===e.TokenType.Delim)),r,...n.parts.filter((n=>n[0]===e.TokenType.Ident||n[0]===e.TokenType.Delim))])}segments(){return this.parts.filter((n=>n[0]===e.TokenType.Ident)).map((e=>e[4].value))}name(){return this.parts.filter((n=>n[0]===e.TokenType.Ident||n[0]===e.TokenType.Delim)).map((e=>e[1])).join("")}equal(e){const n=this.segments(),r=e.segments();if(n.length!==r.length)return!1;for(let e=0;e{}),o=["6.4.2. Layer Naming and Nesting","Layer name syntax"," = [ '.' ]*"],i=r[0][2],l=r[r.length-1][3],p=[];for(let r=0;re.tokens()));let c=!1,T=!1,y=null;for(let n=0;n{const r=n.segments();e:for(let t=0;t=o&&(s=n,o=t)}-1===s?e.push(r):e.splice(s+1,0,r)}})),e},exports.parse=function parse(n,r){const t=e.tokenizer({css:n},{onParseError:null==r?void 0:r.onParseError}),a=[];for(;!t.endOfFile();)a.push(t.nextToken());return a.push(t.nextToken()),parseFromTokens(a,r)},exports.parseFromTokens=parseFromTokens; +"use strict";var e=require("@csstools/css-tokenizer"),n=require("@csstools/css-parser-algorithms");class LayerName{parts;constructor(e){this.parts=e}tokens(){return[...this.parts]}slice(n,r){const t=[];for(let n=0;nn[0]===e.TokenType.Ident||n[0]===e.TokenType.Delim)),r,...n.parts.filter((n=>n[0]===e.TokenType.Ident||n[0]===e.TokenType.Delim))])}segments(){return this.parts.filter((n=>n[0]===e.TokenType.Ident)).map((e=>e[4].value))}name(){return this.parts.filter((n=>n[0]===e.TokenType.Ident||n[0]===e.TokenType.Delim)).map((e=>e[1])).join("")}equal(e){const n=this.segments(),r=e.segments();if(n.length!==r.length)return!1;for(let e=0;e{}),o=["6.4.2. Layer Naming and Nesting","Layer name syntax"," = [ '.' ]*"],i=r[0][2],l=r[r.length-1][3],p=[];for(let r=0;re.tokens()));let c=!1,T=!1,y=null;for(let n=0;n{const r=n.segments();e:for(let t=0;t=o&&(s=n,o=t)}-1===s?e.push(r):e.splice(s+1,0,r)}})),e},exports.parse=function parse(n,r){const t=e.tokenizer({css:n},{onParseError:r?.onParseError}),a=[];for(;!t.endOfFile();)a.push(t.nextToken());return a.push(t.nextToken()),parseFromTokens(a,r)},exports.parseFromTokens=parseFromTokens; diff --git a/packages/cascade-layer-name-parser/dist/index.d.ts b/packages/cascade-layer-name-parser/dist/index.d.ts index 2592bc2e1..225d9fdac 100644 --- a/packages/cascade-layer-name-parser/dist/index.d.ts +++ b/packages/cascade-layer-name-parser/dist/index.d.ts @@ -1,3 +1,31 @@ -export { LayerName } from './nodes/layer-name'; -export { addLayerToModel } from './util/model'; -export { parse, parseFromTokens } from './parser/parse'; +import { CSSToken } from '@csstools/css-tokenizer'; +import { ParseError } from '@csstools/css-tokenizer'; + +export declare function addLayerToModel(layers: Array, currentLayerNames: Array): LayerName[]; + +export declare class LayerName { + parts: Array; + constructor(parts: Array); + tokens(): Array; + slice(start: number, end: number): LayerName; + concat(other: LayerName): LayerName; + segments(): Array; + name(): string; + equal(other: LayerName): boolean; + toString(): string; + toJSON(): { + parts: CSSToken[]; + segments: string[]; + name: string; + }; +} + +export declare function parse(source: string, options?: { + onParseError?: (error: ParseError) => void; +}): LayerName[]; + +export declare function parseFromTokens(tokens: Array, options?: { + onParseError?: (error: ParseError) => void; +}): LayerName[]; + +export { } diff --git a/packages/cascade-layer-name-parser/dist/index.mjs b/packages/cascade-layer-name-parser/dist/index.mjs index e9cc05e99..dffec78fa 100644 --- a/packages/cascade-layer-name-parser/dist/index.mjs +++ b/packages/cascade-layer-name-parser/dist/index.mjs @@ -1 +1 @@ -import{TokenType as e,stringify as t,ParseError as n,tokenizer as r}from"@csstools/css-tokenizer";import{parseCommaSeparatedListOfComponentValues as a,isTokenNode as s,isCommentNode as l,isWhitespaceNode as i}from"@csstools/css-parser-algorithms";class LayerName{parts;constructor(e){this.parts=e}tokens(){return[...this.parts]}slice(t,n){const r=[];for(let t=0;tt[0]===e.Ident||t[0]===e.Delim)),n,...t.parts.filter((t=>t[0]===e.Ident||t[0]===e.Delim))])}segments(){return this.parts.filter((t=>t[0]===e.Ident)).map((e=>e[4].value))}name(){return this.parts.filter((t=>t[0]===e.Ident||t[0]===e.Delim)).map((e=>e[1])).join("")}equal(e){const t=this.segments(),n=e.segments();if(t.length!==n.length)return!1;for(let e=0;e{const n=t.segments();e:for(let r=0;r=l&&(s=t,l=r)}-1===s?e.push(n):e.splice(s+1,0,n)}})),e}function parseFromTokens(t,r){const o=a(t,{onParseError:null==r?void 0:r.onParseError}),m=(null==r?void 0:r.onParseError)??(()=>{}),c=["6.4.2. Layer Naming and Nesting","Layer name syntax"," = [ '.' ]*"],d=t[0][2],u=t[t.length-1][3],p=[];for(let t=0;te.tokens()));let h=!1,f=!1,y=null;for(let t=0;tt[0]===e.Ident||t[0]===e.Delim)),n,...t.parts.filter((t=>t[0]===e.Ident||t[0]===e.Delim))])}segments(){return this.parts.filter((t=>t[0]===e.Ident)).map((e=>e[4].value))}name(){return this.parts.filter((t=>t[0]===e.Ident||t[0]===e.Delim)).map((e=>e[1])).join("")}equal(e){const t=this.segments(),n=e.segments();if(t.length!==n.length)return!1;for(let e=0;e{const n=t.segments();e:for(let r=0;r=i&&(s=t,i=r)}-1===s?e.push(n):e.splice(s+1,0,n)}})),e}function parseFromTokens(t,r){const l=a(t,{onParseError:r?.onParseError}),m=r?.onParseError??(()=>{}),c=["6.4.2. Layer Naming and Nesting","Layer name syntax"," = [ '.' ]*"],d=t[0][2],u=t[t.length-1][3],p=[];for(let t=0;te.tokens()));let h=!1,f=!1,y=null;for(let t=0;t; - constructor(parts: Array); - tokens(): Array; - slice(start: number, end: number): LayerName; - concat(other: LayerName): LayerName; - segments(): Array; - name(): string; - equal(other: LayerName): boolean; - toString(): string; - toJSON(): { - parts: CSSToken[]; - segments: string[]; - name: string; - }; -} diff --git a/packages/cascade-layer-name-parser/dist/parser/parse.d.ts b/packages/cascade-layer-name-parser/dist/parser/parse.d.ts deleted file mode 100644 index 0b0c36edb..000000000 --- a/packages/cascade-layer-name-parser/dist/parser/parse.d.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { CSSToken, ParseError } from '@csstools/css-tokenizer'; -import { LayerName } from '../nodes/layer-name'; -type Options = { - onParseError?: (error: ParseError) => void; -}; -export declare function parseFromTokens(tokens: Array, options?: Options): LayerName[]; -export declare function parse(source: string, options?: Options): LayerName[]; -export {}; diff --git a/packages/cascade-layer-name-parser/dist/util/model.d.ts b/packages/cascade-layer-name-parser/dist/util/model.d.ts deleted file mode 100644 index 7347ce264..000000000 --- a/packages/cascade-layer-name-parser/dist/util/model.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import { LayerName } from '../nodes/layer-name'; -export declare function addLayerToModel(layers: Array, currentLayerNames: Array): LayerName[]; diff --git a/packages/cascade-layer-name-parser/package.json b/packages/cascade-layer-name-parser/package.json index e244cb90a..44ba17bb7 100644 --- a/packages/cascade-layer-name-parser/package.json +++ b/packages/cascade-layer-name-parser/package.json @@ -27,15 +27,18 @@ "engines": { "node": "^14 || ^16 || >=18" }, + "type": "module", "main": "dist/index.cjs", "module": "dist/index.mjs", - "types": "dist/index.d.ts", "exports": { ".": { - "types": "./dist/index.d.ts", - "import": "./dist/index.mjs", - "require": "./dist/index.cjs", - "default": "./dist/index.mjs" + "import": { + "types": "./dist/index.d.ts", + "default": "./dist/index.mjs" + }, + "require": { + "default": "./dist/index.cjs" + } } }, "files": [ diff --git a/packages/cascade-layer-name-parser/src/parser/parse.ts b/packages/cascade-layer-name-parser/src/parser/parse.ts index fa99c314e..31d556b09 100644 --- a/packages/cascade-layer-name-parser/src/parser/parse.ts +++ b/packages/cascade-layer-name-parser/src/parser/parse.ts @@ -3,11 +3,12 @@ import { parseCommaSeparatedListOfComponentValues } from '@csstools/css-parser-a import { CSSToken, tokenizer, TokenType, ParseError } from '@csstools/css-tokenizer'; import { LayerName } from '../nodes/layer-name'; -type Options = { - onParseError?: (error: ParseError) => void -} - -export function parseFromTokens(tokens: Array, options?: Options) { +export function parseFromTokens( + tokens: Array, + options?: { + onParseError?: (error: ParseError) => void + }, +) { const componentValuesLists = parseCommaSeparatedListOfComponentValues(tokens, { onParseError: options?.onParseError, }); @@ -170,7 +171,12 @@ export function parseFromTokens(tokens: Array, options?: Options) { return result; } -export function parse(source: string, options?: Options) { +export function parse( + source: string, + options?: { + onParseError?: (error: ParseError) => void + }, +) { const t = tokenizer({ css: source }, { onParseError: options?.onParseError, }); diff --git a/packages/color-helpers/CHANGELOG.md b/packages/color-helpers/CHANGELOG.md index 08757f1cc..d66794d7f 100644 --- a/packages/color-helpers/CHANGELOG.md +++ b/packages/color-helpers/CHANGELOG.md @@ -1,8 +1,9 @@ # Changes to Color Helpers -### Unreleased (patch) +### Unreleased (major) -- Small fixes in type definitions +- Remove barrel files +- Fix type definitions - Use higher precision color conversion matrices. ### 3.0.2 diff --git a/packages/color-helpers/api-extractor.json b/packages/color-helpers/api-extractor.json new file mode 100644 index 000000000..42058be51 --- /dev/null +++ b/packages/color-helpers/api-extractor.json @@ -0,0 +1,4 @@ +{ + "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json", + "extends": "../../api-extractor.json" +} diff --git a/packages/color-helpers/dist/calculations/binary-search-gamut.d.ts b/packages/color-helpers/dist/calculations/binary-search-gamut.d.ts deleted file mode 100644 index ddb9dcc92..000000000 --- a/packages/color-helpers/dist/calculations/binary-search-gamut.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import type { Color } from '../types/color'; -export declare function binarySearchGamut(startOKLCH: Color, toDestination: (x: Color) => Color, fromDestination: (x: Color) => Color): Color; diff --git a/packages/color-helpers/dist/calculations/contrast.d.ts b/packages/color-helpers/dist/calculations/contrast.d.ts deleted file mode 100644 index 22d355bcb..000000000 --- a/packages/color-helpers/dist/calculations/contrast.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import type { Color } from '../types/color'; -export declare function contrast(RGB1: Color, RGB2: Color): number; diff --git a/packages/color-helpers/dist/calculations/delta-EOK.d.ts b/packages/color-helpers/dist/calculations/delta-EOK.d.ts deleted file mode 100644 index 7fa98dee9..000000000 --- a/packages/color-helpers/dist/calculations/delta-EOK.d.ts +++ /dev/null @@ -1,14 +0,0 @@ -import type { Color } from '../types/color'; -/** - * @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 - * @param {number[]} sample - Array of OKLab values: L as 0..1, a and b as -1..1 - * @return {number} How different a color sample is from reference - * - * @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 - */ -export declare function deltaEOK(reference: Color, sample: Color): number; diff --git a/packages/color-helpers/dist/calculations/index.d.ts b/packages/color-helpers/dist/calculations/index.d.ts deleted file mode 100644 index 86e5f3579..000000000 --- a/packages/color-helpers/dist/calculations/index.d.ts +++ /dev/null @@ -1,5 +0,0 @@ -export * from './binary-search-gamut'; -export * from './map-gamut'; -export * from './delta-EOK'; -export * from './contrast'; -export * from './multiply-matrices'; diff --git a/packages/color-helpers/dist/calculations/map-gamut.d.ts b/packages/color-helpers/dist/calculations/map-gamut.d.ts deleted file mode 100644 index b1a0bbbb6..000000000 --- a/packages/color-helpers/dist/calculations/map-gamut.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import type { Color } from '../types/color'; -export declare function mapGamut(startOKLCH: Color, toDestination: (x: Color) => Color, fromDestination: (x: Color) => Color): Color; diff --git a/packages/color-helpers/dist/calculations/multiply-matrices.d.ts b/packages/color-helpers/dist/calculations/multiply-matrices.d.ts deleted file mode 100644 index b78e13fd5..000000000 --- a/packages/color-helpers/dist/calculations/multiply-matrices.d.ts +++ /dev/null @@ -1,12 +0,0 @@ -/** - * 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 - */ -export declare function multiplyMatrices(a: Array> | Array, b: Array> | Array): Array> | Array; diff --git a/packages/color-helpers/dist/conversions/constants.d.ts b/packages/color-helpers/dist/conversions/constants.d.ts deleted file mode 100644 index 4d2e7a1e4..000000000 --- a/packages/color-helpers/dist/conversions/constants.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -export declare const D50: number[]; -export declare const D65: number[]; diff --git a/packages/color-helpers/dist/conversions/d50-to-d65.d.ts b/packages/color-helpers/dist/conversions/d50-to-d65.d.ts deleted file mode 100644 index 577959659..000000000 --- a/packages/color-helpers/dist/conversions/d50-to-d65.d.ts +++ /dev/null @@ -1,9 +0,0 @@ -import type { Color } from '../types/color'; -/** - * 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). - */ -export declare function D50_to_D65(XYZ: Color): Color; diff --git a/packages/color-helpers/dist/conversions/d65-to-d50.d.ts b/packages/color-helpers/dist/conversions/d65-to-d50.d.ts deleted file mode 100644 index 9db131cbf..000000000 --- a/packages/color-helpers/dist/conversions/d65-to-d50.d.ts +++ /dev/null @@ -1,10 +0,0 @@ -import type { Color } from '../types/color'; -/** - * 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 - */ -export declare function D65_to_D50(XYZ: Color): Color; diff --git a/packages/color-helpers/dist/conversions/gam-2020.d.ts b/packages/color-helpers/dist/conversions/gam-2020.d.ts deleted file mode 100644 index 0ab19f47b..000000000 --- a/packages/color-helpers/dist/conversions/gam-2020.d.ts +++ /dev/null @@ -1,10 +0,0 @@ -import type { Color } from '../types/color'; -/** - * Convert an array of linear-light rec2020 RGB in the range 0.0-1.0 - * to gamma corrected form ITU-R BT.2020-2 p.4 - * - * @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 declare function gam_2020(RGB: Color): Color; diff --git a/packages/color-helpers/dist/conversions/gam-a98rgb.d.ts b/packages/color-helpers/dist/conversions/gam-a98rgb.d.ts deleted file mode 100644 index 3dbca9882..000000000 --- a/packages/color-helpers/dist/conversions/gam-a98rgb.d.ts +++ /dev/null @@ -1,10 +0,0 @@ -import type { Color } from '../types/color'; -/** - * Convert an array of linear-light a98-rgb in the range 0.0-1.0 - * to gamma corrected form. Negative values are also now accepted - * - * @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 declare function gam_a98rgb(RGB: Color): Color; diff --git a/packages/color-helpers/dist/conversions/gam-p3.d.ts b/packages/color-helpers/dist/conversions/gam-p3.d.ts deleted file mode 100644 index 18d6d464e..000000000 --- a/packages/color-helpers/dist/conversions/gam-p3.d.ts +++ /dev/null @@ -1,10 +0,0 @@ -import type { Color } from '../types/color'; -/** - * Convert an array of linear-light display-p3 RGB in the range 0.0-1.0 - * to gamma corrected form - * - * @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 declare function gam_P3(RGB: Color): Color; diff --git a/packages/color-helpers/dist/conversions/gam-pro-photo.d.ts b/packages/color-helpers/dist/conversions/gam-pro-photo.d.ts deleted file mode 100644 index 0fbbf4c51..000000000 --- a/packages/color-helpers/dist/conversions/gam-pro-photo.d.ts +++ /dev/null @@ -1,12 +0,0 @@ -import type { Color } from '../types/color'; -/** - * Convert an array of linear-light prophoto-rgb in the range 0.0-1.0 - * to gamma corrected form. - * Transfer curve is gamma 1.8 with a small linear portion. - * - * @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 declare function gam_ProPhoto(RGB: Color): Color; -export declare function foo(): void; diff --git a/packages/color-helpers/dist/conversions/gam-srgb.d.ts b/packages/color-helpers/dist/conversions/gam-srgb.d.ts deleted file mode 100644 index fc951cd90..000000000 --- a/packages/color-helpers/dist/conversions/gam-srgb.d.ts +++ /dev/null @@ -1,14 +0,0 @@ -import type { Color } from '../types/color'; -/** - * Convert an array of linear-light sRGB values in the range 0.0-1.0 to gamma corrected form - * Extended transfer function: - * For negative values, linear portion extends on reflection - * of axis, then uses reflected pow below that - * - * @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://en.wikipedia.org/wiki/SRGB - */ -export declare function gam_sRGB(RGB: Color): Color; diff --git a/packages/color-helpers/dist/conversions/hsl-to-srgb.d.ts b/packages/color-helpers/dist/conversions/hsl-to-srgb.d.ts deleted file mode 100644 index 3598a5447..000000000 --- a/packages/color-helpers/dist/conversions/hsl-to-srgb.d.ts +++ /dev/null @@ -1,14 +0,0 @@ -import type { Color } from '../types/color'; -/** - * @param {number} hue - Hue as degrees 0..360 - * @param {number} sat - Saturation as percentage 0..100 - * @param {number} light - Lightness as percentage 0..100 - * @return {number[]} Array of RGB components 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/hslToRgb.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). - * - * @see https://github.com/w3c/csswg-drafts/blob/main/css-color-4/hslToRgb.js - */ -export declare function HSL_to_sRGB(HSL: Color): Color; diff --git a/packages/color-helpers/dist/conversions/hue-to-rgb.d.ts b/packages/color-helpers/dist/conversions/hue-to-rgb.d.ts deleted file mode 100644 index 8cb5ff7cd..000000000 --- a/packages/color-helpers/dist/conversions/hue-to-rgb.d.ts +++ /dev/null @@ -1,8 +0,0 @@ -/** - * @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/utilities.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). - * - * @see https://github.com/w3c/csswg-drafts/blob/main/css-color-4/utilities.js - */ -export declare function hueToRGB(t1: number, t2: number, hue: number): number; diff --git a/packages/color-helpers/dist/conversions/hwb-to-srgb.d.ts b/packages/color-helpers/dist/conversions/hwb-to-srgb.d.ts deleted file mode 100644 index 2527a6416..000000000 --- a/packages/color-helpers/dist/conversions/hwb-to-srgb.d.ts +++ /dev/null @@ -1,14 +0,0 @@ -import type { Color } from '../types/color'; -/** - * @param {number} hue - Hue as degrees 0..360 - * @param {number} white - Whiteness as percentage 0..100 - * @param {number} black - Blackness as percentage 0..100 - * @return {number[]} Array of RGB components 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/hwbToRgb.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). - * - * @see https://github.com/w3c/csswg-drafts/blob/main/css-color-4/hwbToRgb.js - */ -export declare function HWB_to_sRGB(HWB: Color): Color; diff --git a/packages/color-helpers/dist/conversions/index.d.ts b/packages/color-helpers/dist/conversions/index.d.ts deleted file mode 100644 index 9a2ed427c..000000000 --- a/packages/color-helpers/dist/conversions/index.d.ts +++ /dev/null @@ -1,40 +0,0 @@ -export * from './constants'; -export * from './d50-to-d65'; -export * from './d65-to-d50'; -export * from './gam-2020'; -export * from './gam-a98rgb'; -export * from './gam-p3'; -export * from './gam-pro-photo'; -export * from './gam-srgb'; -export * from './hsl-to-srgb'; -export * from './hue-to-rgb'; -export * from './hwb-to-srgb'; -export * from './lab-to-lch'; -export * from './lab-to-xyz'; -export * from './lch-to-lab'; -export * from './lin-2020'; -export * from './lin-2020-to-xyz'; -export * from './lin-a98rgb'; -export * from './lin-a98rgb-to-xyz'; -export * from './lin-p3'; -export * from './lin-p3-to-xyz'; -export * from './lin-pro-photo'; -export * from './lin-pro-photo-to-xyz'; -export * from './lin-srgb'; -export * from './lin-srgb-to-xyz'; -export * from './naive-cmyk-to-srgb'; -export * from './oklab-to-oklch'; -export * from './oklab-to-xyz'; -export * from './oklch-to-oklab'; -export * from './srgb-to-hsl'; -export * from './srgb-to-hwb'; -export * from './srgb-to-luminance'; -export * from './xyz-to-lab'; -export * from './xyz-to-lin-2020'; -export * from './xyz-to-lin-a98rgb'; -export * from './xyz-to-lin-p3'; -export * from './xyz-to-lin-pro-photo'; -export * from './xyz-to-lin-srgb'; -export * from './xyz-to-oklab'; -export * from './xyz-to-uv'; -export * from './xyz-to-xy'; diff --git a/packages/color-helpers/dist/conversions/lab-to-lch.d.ts b/packages/color-helpers/dist/conversions/lab-to-lch.d.ts deleted file mode 100644 index dc9b715a4..000000000 --- a/packages/color-helpers/dist/conversions/lab-to-lch.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -import type { Color } from '../types/color'; -/** - * @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 declare function Lab_to_LCH(Lab: Color): Color; diff --git a/packages/color-helpers/dist/conversions/lab-to-xyz.d.ts b/packages/color-helpers/dist/conversions/lab-to-xyz.d.ts deleted file mode 100644 index 41e28669a..000000000 --- a/packages/color-helpers/dist/conversions/lab-to-xyz.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import type { Color } from '../types/color'; -export declare function Lab_to_XYZ(Lab: Color): Color; diff --git a/packages/color-helpers/dist/conversions/lch-to-lab.d.ts b/packages/color-helpers/dist/conversions/lch-to-lab.d.ts deleted file mode 100644 index 0e029502c..000000000 --- a/packages/color-helpers/dist/conversions/lch-to-lab.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -import type { Color } from '../types/color'; -/** - * @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 declare function LCH_to_Lab(LCH: Color): Color; diff --git a/packages/color-helpers/dist/conversions/lin-2020-to-xyz.d.ts b/packages/color-helpers/dist/conversions/lin-2020-to-xyz.d.ts deleted file mode 100644 index a2c3300a6..000000000 --- a/packages/color-helpers/dist/conversions/lin-2020-to-xyz.d.ts +++ /dev/null @@ -1,12 +0,0 @@ -import type { Color } from '../types/color'; -/** - * Convert an array of linear-light rec2020 values to CIE XYZ - * using 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). - * - * @see http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html - */ -export declare function lin_2020_to_XYZ(rgb: Color): Color; diff --git a/packages/color-helpers/dist/conversions/lin-2020.d.ts b/packages/color-helpers/dist/conversions/lin-2020.d.ts deleted file mode 100644 index ad510b212..000000000 --- a/packages/color-helpers/dist/conversions/lin-2020.d.ts +++ /dev/null @@ -1,11 +0,0 @@ -import type { Color } from '../types/color'; -/** - * Convert an array of rec2020 RGB values in the range 0.0 - 1.0 - * to linear light (un-companded) form. - * ITU-R BT.2020-2 p.4 - * - * @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 declare function lin_2020(RGB: Color): Color; diff --git a/packages/color-helpers/dist/conversions/lin-a98rgb-to-xyz.d.ts b/packages/color-helpers/dist/conversions/lin-a98rgb-to-xyz.d.ts deleted file mode 100644 index f35928bb1..000000000 --- a/packages/color-helpers/dist/conversions/lin-a98rgb-to-xyz.d.ts +++ /dev/null @@ -1,18 +0,0 @@ -import type { Color } from '../types/color'; -/** - * 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 - */ -export declare function lin_a98rgb_to_XYZ(rgb: Color): Color; diff --git a/packages/color-helpers/dist/conversions/lin-a98rgb.d.ts b/packages/color-helpers/dist/conversions/lin-a98rgb.d.ts deleted file mode 100644 index f69602d95..000000000 --- a/packages/color-helpers/dist/conversions/lin-a98rgb.d.ts +++ /dev/null @@ -1,10 +0,0 @@ -import type { Color } from '../types/color'; -/** - * Convert an array of a98-rgb values in the range 0.0 - 1.0 - * to linear light (un-companded) form. Negative values are also now accepted - * - * @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 declare function lin_a98rgb(RGB: Color): Color; diff --git a/packages/color-helpers/dist/conversions/lin-p3-to-xyz.d.ts b/packages/color-helpers/dist/conversions/lin-p3-to-xyz.d.ts deleted file mode 100644 index 0ff5c9687..000000000 --- a/packages/color-helpers/dist/conversions/lin-p3-to-xyz.d.ts +++ /dev/null @@ -1,12 +0,0 @@ -import type { Color } from '../types/color'; -/** - * Convert an array of linear-light display-p3 values to CIE XYZ - * using 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). - * - * @see http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html - */ -export declare function lin_P3_to_XYZ(rgb: Color): Color; diff --git a/packages/color-helpers/dist/conversions/lin-p3.d.ts b/packages/color-helpers/dist/conversions/lin-p3.d.ts deleted file mode 100644 index 4fd2c5fd5..000000000 --- a/packages/color-helpers/dist/conversions/lin-p3.d.ts +++ /dev/null @@ -1,10 +0,0 @@ -import type { Color } from '../types/color'; -/** - * Convert an array of display-p3 RGB values in the range 0.0 - 1.0 - * to linear light (un-companded) form. - * - * @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 declare function lin_P3(RGB: Color): Color; diff --git a/packages/color-helpers/dist/conversions/lin-pro-photo-to-xyz.d.ts b/packages/color-helpers/dist/conversions/lin-pro-photo-to-xyz.d.ts deleted file mode 100644 index f8e1ce4ef..000000000 --- a/packages/color-helpers/dist/conversions/lin-pro-photo-to-xyz.d.ts +++ /dev/null @@ -1,12 +0,0 @@ -import type { Color } from '../types/color'; -/** - * Convert an array of linear-light prophoto-rgb values to CIE XYZ - * using D50 (so no chromatic adaptation needed afterwards) - * - * @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 - */ -export declare function lin_ProPhoto_to_XYZ(rgb: Color): Color; diff --git a/packages/color-helpers/dist/conversions/lin-pro-photo.d.ts b/packages/color-helpers/dist/conversions/lin-pro-photo.d.ts deleted file mode 100644 index b29ff99f9..000000000 --- a/packages/color-helpers/dist/conversions/lin-pro-photo.d.ts +++ /dev/null @@ -1,11 +0,0 @@ -import type { Color } from '../types/color'; -/** - * 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 - * gamma 1.8 with a small linear portion. Extended transfer function - * - * @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 declare function lin_ProPhoto(RGB: Color): Color; diff --git a/packages/color-helpers/dist/conversions/lin-srgb-to-xyz.d.ts b/packages/color-helpers/dist/conversions/lin-srgb-to-xyz.d.ts deleted file mode 100644 index e99c9bd54..000000000 --- a/packages/color-helpers/dist/conversions/lin-srgb-to-xyz.d.ts +++ /dev/null @@ -1,10 +0,0 @@ -import type { Color } from '../types/color'; -/** - * 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). - */ -export declare function lin_sRGB_to_XYZ(rgb: Color): Color; diff --git a/packages/color-helpers/dist/conversions/lin-srgb.d.ts b/packages/color-helpers/dist/conversions/lin-srgb.d.ts deleted file mode 100644 index 5f0bf371f..000000000 --- a/packages/color-helpers/dist/conversions/lin-srgb.d.ts +++ /dev/null @@ -1,15 +0,0 @@ -import type { Color } from '../types/color'; -/** - * Convert an array of of sRGB values where in-gamut values are in the range - * [0 - 1] to linear light (un-companded) form. - * Extended transfer function: - * For negative values, linear portion is extended on reflection of axis, - * then reflected power function is used. - * - * @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://en.wikipedia.org/wiki/SRGB - */ -export declare function lin_sRGB(RGB: Color): Color; diff --git a/packages/color-helpers/dist/conversions/naive-cmyk-to-srgb.d.ts b/packages/color-helpers/dist/conversions/naive-cmyk-to-srgb.d.ts deleted file mode 100644 index 90f321c41..000000000 --- a/packages/color-helpers/dist/conversions/naive-cmyk-to-srgb.d.ts +++ /dev/null @@ -1,14 +0,0 @@ -import type { Color } from '../types/color'; -/** - * CMYK is an array of four values in the range [0.0, 1.0] the output is an - * array of [RGB] also in the [0.0, 1.0] range because the naive algorithm - * does not generate out of gamut colors neither does it generate accurate - * simulations of practical CMYK colors - * - * @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/utilities.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). - * - * @see https://github.com/w3c/csswg-drafts/blob/main/css-color-4/utilities.js - */ -export declare function naive_CMYK_to_sRGB(CMYK: [number, number, number, number]): Color; diff --git a/packages/color-helpers/dist/conversions/oklab-to-oklch.d.ts b/packages/color-helpers/dist/conversions/oklab-to-oklch.d.ts deleted file mode 100644 index 6e6b36d73..000000000 --- a/packages/color-helpers/dist/conversions/oklab-to-oklch.d.ts +++ /dev/null @@ -1,9 +0,0 @@ -import type { Color } from '../types/color'; -/** - * @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 - */ -export declare function OKLab_to_OKLCH(OKLab: Color): Color; diff --git a/packages/color-helpers/dist/conversions/oklab-to-xyz.d.ts b/packages/color-helpers/dist/conversions/oklab-to-xyz.d.ts deleted file mode 100644 index cd822fd9f..000000000 --- a/packages/color-helpers/dist/conversions/oklab-to-xyz.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import type { Color } from '../types/color'; -export declare function OKLab_to_XYZ(OKLab: Color): Color; diff --git a/packages/color-helpers/dist/conversions/oklch-to-oklab.d.ts b/packages/color-helpers/dist/conversions/oklch-to-oklab.d.ts deleted file mode 100644 index e651b5c31..000000000 --- a/packages/color-helpers/dist/conversions/oklch-to-oklab.d.ts +++ /dev/null @@ -1,9 +0,0 @@ -import type { Color } from '../types/color'; -/** - * @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 - */ -export declare function OKLCH_to_OKLab(OKLCH: Color): Color; diff --git a/packages/color-helpers/dist/conversions/srgb-to-hsl.d.ts b/packages/color-helpers/dist/conversions/srgb-to-hsl.d.ts deleted file mode 100644 index 6d7b77e89..000000000 --- a/packages/color-helpers/dist/conversions/srgb-to-hsl.d.ts +++ /dev/null @@ -1,16 +0,0 @@ -import type { Color } from '../types/color'; -/** - * Convert an array of gamma-corrected sRGB values in the 0.0 to 1.0 range to HSL. - * - * @param {Color} RGB [r, g, b] - * - Red component 0..1 - * - Green component 0..1 - * - Blue component 0..1 - * @return {number[]} Array of HSL values: Hue as degrees 0..360, Saturation and Lightness as percentages 0..100 - * - * @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/utilities.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). - * - * @see https://github.com/w3c/csswg-drafts/blob/main/css-color-4/rgbToHsl.js - */ -export declare function sRGB_to_HSL(RGB: Color): Color; diff --git a/packages/color-helpers/dist/conversions/srgb-to-hwb.d.ts b/packages/color-helpers/dist/conversions/srgb-to-hwb.d.ts deleted file mode 100644 index 4e3078b27..000000000 --- a/packages/color-helpers/dist/conversions/srgb-to-hwb.d.ts +++ /dev/null @@ -1,11 +0,0 @@ -import type { Color } from '../types/color'; -/** - * Convert an array of gamma-corrected sRGB values in the 0.0 to 1.0 range to HWB. - * - * @param {Color} RGB [r, g, b] - * - Red component 0..1 - * - Green component 0..1 - * - Blue component 0..1 - * @return {number[]} Array of HWB values - */ -export declare function sRGB_to_HWB(RGB: Color): Color; diff --git a/packages/color-helpers/dist/conversions/srgb-to-luminance.d.ts b/packages/color-helpers/dist/conversions/srgb-to-luminance.d.ts deleted file mode 100644 index 5e8cd84a9..000000000 --- a/packages/color-helpers/dist/conversions/srgb-to-luminance.d.ts +++ /dev/null @@ -1,12 +0,0 @@ -import type { Color } from '../types/color'; -/** - * Convert an array of gamma-corrected sRGB values in the 0.0 to 1.0 range - * to linear-light sRGB, then to CIE XYZ and return luminance (the Y value) - * - * @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/utilities.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). - * - * @see https://github.com/w3c/csswg-drafts/blob/main/css-color-4/utilities.js - */ -export declare function sRGB_to_luminance(RGB: Color): number; diff --git a/packages/color-helpers/dist/conversions/xyz-to-lab.d.ts b/packages/color-helpers/dist/conversions/xyz-to-lab.d.ts deleted file mode 100644 index 8ae164cdc..000000000 --- a/packages/color-helpers/dist/conversions/xyz-to-lab.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import type { Color } from '../types/color'; -export declare function XYZ_to_Lab(XYZ: Color): Color; diff --git a/packages/color-helpers/dist/conversions/xyz-to-lin-2020.d.ts b/packages/color-helpers/dist/conversions/xyz-to-lin-2020.d.ts deleted file mode 100644 index eebe97385..000000000 --- a/packages/color-helpers/dist/conversions/xyz-to-lin-2020.d.ts +++ /dev/null @@ -1,9 +0,0 @@ -import type { Color } from '../types/color'; -/** - * 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). - */ -export declare function XYZ_to_lin_2020(XYZ: Color): Color; diff --git a/packages/color-helpers/dist/conversions/xyz-to-lin-a98rgb.d.ts b/packages/color-helpers/dist/conversions/xyz-to-lin-a98rgb.d.ts deleted file mode 100644 index 8e2b3de29..000000000 --- a/packages/color-helpers/dist/conversions/xyz-to-lin-a98rgb.d.ts +++ /dev/null @@ -1,9 +0,0 @@ -import type { Color } from '../types/color'; -/** - * 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). - */ -export declare function XYZ_to_lin_a98rgb(XYZ: Color): Color; diff --git a/packages/color-helpers/dist/conversions/xyz-to-lin-p3.d.ts b/packages/color-helpers/dist/conversions/xyz-to-lin-p3.d.ts deleted file mode 100644 index 624ca5827..000000000 --- a/packages/color-helpers/dist/conversions/xyz-to-lin-p3.d.ts +++ /dev/null @@ -1,9 +0,0 @@ -import type { Color } from '../types/color'; -/** - * 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). - */ -export declare function XYZ_to_lin_P3(XYZ: Color): Color; diff --git a/packages/color-helpers/dist/conversions/xyz-to-lin-pro-photo.d.ts b/packages/color-helpers/dist/conversions/xyz-to-lin-pro-photo.d.ts deleted file mode 100644 index a07e002ae..000000000 --- a/packages/color-helpers/dist/conversions/xyz-to-lin-pro-photo.d.ts +++ /dev/null @@ -1,11 +0,0 @@ -import type { Color } from '../types/color'; -/** - * Convert XYZ to linear-light prophoto-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). - * - * @see http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html - */ -export declare function XYZ_to_lin_ProPhoto(XYZ: Color): Color; diff --git a/packages/color-helpers/dist/conversions/xyz-to-lin-srgb.d.ts b/packages/color-helpers/dist/conversions/xyz-to-lin-srgb.d.ts deleted file mode 100644 index 087949fbf..000000000 --- a/packages/color-helpers/dist/conversions/xyz-to-lin-srgb.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -import type { Color } from '../types/color'; -/** - * @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 declare function XYZ_to_lin_sRGB(XYZ: Color): Color; diff --git a/packages/color-helpers/dist/conversions/xyz-to-oklab.d.ts b/packages/color-helpers/dist/conversions/xyz-to-oklab.d.ts deleted file mode 100644 index 68a8f59ea..000000000 --- a/packages/color-helpers/dist/conversions/xyz-to-oklab.d.ts +++ /dev/null @@ -1,10 +0,0 @@ -import type { Color } from '../types/color'; -/** - * @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 - */ -export declare function XYZ_to_OKLab(XYZ: Color): Color; diff --git a/packages/color-helpers/dist/conversions/xyz-to-uv.d.ts b/packages/color-helpers/dist/conversions/xyz-to-uv.d.ts deleted file mode 100644 index 576bcca0e..000000000 --- a/packages/color-helpers/dist/conversions/xyz-to-uv.d.ts +++ /dev/null @@ -1,11 +0,0 @@ -import type { Color } from '../types/color'; -/** - * Convert an array of three XYZ values to u*,v* chromaticity coordinates - * - * @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/utilities.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). - * - * @see https://github.com/w3c/csswg-drafts/blob/main/css-color-4/utilities.js - */ -export declare function XYZ_to_uv(XYZ: Color): [number, number]; diff --git a/packages/color-helpers/dist/conversions/xyz-to-xy.d.ts b/packages/color-helpers/dist/conversions/xyz-to-xy.d.ts deleted file mode 100644 index e7a6dee72..000000000 --- a/packages/color-helpers/dist/conversions/xyz-to-xy.d.ts +++ /dev/null @@ -1,11 +0,0 @@ -import type { Color } from '../types/color'; -/** - * Convert an array of three XYZ values to x,y chromaticity coordinates - * - * @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/utilities.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). - * - * @see https://github.com/w3c/csswg-drafts/blob/main/css-color-4/utilities.js - */ -export declare function XYZ_to_xy(XYZ: Color): [number, number]; diff --git a/packages/color-helpers/dist/conversions/xyz/index.d.ts b/packages/color-helpers/dist/conversions/xyz/index.d.ts deleted file mode 100644 index b844701c0..000000000 --- a/packages/color-helpers/dist/conversions/xyz/index.d.ts +++ /dev/null @@ -1,253 +0,0 @@ -import type { Color } from '../../types/color'; -/** - * @param {Color} color [r, g, b] - * - Red as number 0..1; - * - Green as number 0..1; - * - Blue as number 0..1; - * @return {Color} D50 XYZ [x, y, z] - */ -export declare function sRGB_to_XYZ_D50(x: Color): Color; -/** - * @param {Color} color [x, y, z] - * - X as number 0..1; - * - Y as number 0..1; - * - Z as number 0..1; - * @return {Color} sRGB [r, g, b] - * - Red as number 0..1; - * - Green as number 0..1; - * - Blue as number 0..1; - */ -export declare function XYZ_D50_to_sRGB(x: Color): Color; -/** - * @param {Color} color [h, s, l] - * - Hue as degrees 0..360; - * - Saturation as number 0..100; - * - Lightness as number 0..100; - * @return {Color} D50 XYZ [x, y, z] - */ -export declare function HSL_to_XYZ_D50(x: Color): Color; -/** - * @param {Color} color [x, y, z] - * - X as number 0..1; - * - Y as number 0..1; - * - Z as number 0..1; - * @return {Color} HSL [r, g, b] - * - Hue as degrees 0..360; - * - Saturation as number 0..100; - * - Lightness as number 0..100; - */ -export declare function XYZ_D50_to_HSL(x: Color): Color; -/** - * @param {Color} color [h, w, b] - * - Hue as degrees 0..360; - * - Whiteness as number 0..100; - * - Blackness as number 0..100; - * @return {Color} D50 XYZ [x, y, z] - */ -export declare function HWB_to_XYZ_D50(x: Color): Color; -/** - * @param {Color} color [x, y, z] - * - X as number 0..1; - * - Y as number 0..1; - * - Z as number 0..1; - * @return {Color} HWB [r, g, b] - * - Hue as degrees 0..360; - * - Whiteness as number 0..100; - * - Blackness as number 0..100; - */ -export declare function XYZ_D50_to_HWB(x: Color): Color; -/** - * @param {Color} color [l, a, b] - * - Lightness as number 0..100; - * - a as number -160..160; - * - b as number -160..160; - * @return {Color} D50 XYZ [x, y, z] - */ -export declare function Lab_to_XYZ_D50(x: Color): Color; -/** - * @param {Color} color [x, y, z] - * - X as number 0..1; - * - Y as number 0..1; - * - Z as number 0..1; - * @return {Color} Lab [r, g, b] - * - Lightness as number 0..100; - * - a as number -160..160; - * - b as number -160..160; - */ -export declare function XYZ_D50_to_Lab(x: Color): Color; -/** - * @param {Color} color [l, c, h] - * - Lightness as number 0..100; - * - Chroma as number 0..230; - * - Hue as degrees 0..360; - * @return {Color} D50 XYZ [x, y, z] - */ -export declare function LCH_to_XYZ_D50(x: Color): Color; -/** - * @param {Color} color [x, y, z] - * - X as number 0..1; - * - Y as number 0..1; - * - Z as number 0..1; - * @return {Color} LCH [r, g, b] - * - Lightness as number 0..100; - * - Chroma as number 0..230; - * - Hue as degrees 0..360; - */ -export declare function XYZ_D50_to_LCH(x: Color): Color; -/** - * @param {Color} color [l, a, b] - * - Lightness as number 0..1; - * - a as number 0..0.5; - * - b as number 0..0.5; - * @return {Color} D50 XYZ [x, y, z] - */ -export declare function OKLab_to_XYZ_D50(x: Color): Color; -/** - * @param {Color} color [x, y, z] - * - X as number 0..1; - * - Y as number 0..1; - * - Z as number 0..1; - * @return {Color} OKLab [r, g, b] - * - Lightness as number 0..1; - * - a as number 0..0.5; - * - b as number 0..0.5; - */ -export declare function XYZ_D50_to_OKLab(x: Color): Color; -/** - * @param {Color} color [l, c, h] - * - Lightness as number 0..1; - * - Chroma as number 0..0.5; - * - Hue as degrees 0..360; - * @return {Color} D50 XYZ [x, y, z] - */ -export declare function OKLCH_to_XYZ_D50(x: Color): Color; -/** - * @param {Color} color [x, y, z] - * - X as number 0..1; - * - Y as number 0..1; - * - Z as number 0..1; - * @return {Color} OKLCH [r, g, b] - * - Lightness as number 0..1; - * - Chroma as number 0..0.5; - * - Hue as degrees 0..360; - */ -export declare function XYZ_D50_to_OKLCH(x: Color): Color; -/** - * @param {Color} color [r, g, b] - * - Red as number 0..1; - * - Green as number 0..1; - * - Blue as number 0..1; - * @return {Color} D50 XYZ [x, y, z] - */ -export declare function lin_sRGB_to_XYZ_D50(x: Color): Color; -/** - * @param {Color} color [x, y, z] - * - X as number 0..1; - * - Y as number 0..1; - * - Z as number 0..1; - * @return {Color} linear sRGB [r, g, b] - * - Red as number 0..1; - * - Green as number 0..1; - * - Blue as number 0..1; - */ -export declare function XYZ_D50_to_lin_sRGB(x: Color): Color; -/** - * @param {Color} color [r, g, b] - * - Red as number 0..1; - * - Green as number 0..1; - * - Blue as number 0..1; - * @return {Color} D50 XYZ [x, y, z] - */ -export declare function a98_RGB_to_XYZ_D50(x: Color): Color; -/** - * @param {Color} color [x, y, z] - * - X as number 0..1; - * - Y as number 0..1; - * - Z as number 0..1; - * @return {Color} a98 sRGB [r, g, b] - * - Red as number 0..1; - * - Green as number 0..1; - * - Blue as number 0..1; - */ -export declare function XYZ_D50_to_a98_RGB(x: Color): Color; -/** - * @param {Color} color [r, g, b] - * - Red as number 0..1; - * - Green as number 0..1; - * - Blue as number 0..1; - * @return {Color} D50 XYZ [x, y, z] - */ -export declare function P3_to_XYZ_D50(x: Color): Color; -/** - * @param {Color} color [x, y, z] - * - X as number 0..1; - * - Y as number 0..1; - * - Z as number 0..1; - * @return {Color} P3 [r, g, b] - * - R as number 0..1; - * - G as number 0..1; - * - B as number 0..1; - */ -export declare function XYZ_D50_to_P3(x: Color): Color; -/** - * @param {Color} color [r, g, b] - * - Red as number 0..1; - * - Green as number 0..1; - * - Blue as number 0..1; - * @return {Color} D50 XYZ [x, y, z] - */ -export declare function rec_2020_to_XYZ_D50(x: Color): Color; -/** - * @param {Color} color [x, y, z] - * - X as number 0..1; - * - Y as number 0..1; - * - Z as number 0..1; - * @return {Color} rec 2020 [r, g, b] - * - Red as number 0..1; - * - Green as number 0..1; - * - Blue as number 0..1; - */ -export declare function XYZ_D50_to_rec_2020(x: Color): Color; -/** - * @param {Color} color [r, g, b] - * - Red as number 0..1; - * - Green as number 0..1; - * - Blue as number 0..1; - * @return {Color} D50 XYZ [x, y, z] - */ -export declare function ProPhoto_RGB_to_XYZ_D50(x: Color): Color; -/** - * @param {Color} color [x, y, z] - * - X as number 0..1; - * - Y as number 0..1; - * - Z as number 0..1; - * @return {Color} ProPhoto [r, g, b] - * - Red as number 0..1; - * - Green as number 0..1; - * - Blue as number 0..1; - */ -export declare function XYZ_D50_to_ProPhoto(x: Color): Color; -/** - * @param {Color} color [x, y, z] - * - X as number 0..1; - * - Y as number 0..1; - * - Z as number 0..1; - * @return {Color} D50 XYZ [x, y, z] - */ -export declare function XYZ_D65_to_XYZ_D50(x: Color): Color; -/** - * @param {Color} color [x, y, z] - * - X as number 0..1; - * - Y as number 0..1; - * - Z as number 0..1; - * @return {Color} D65 XYZ [x, y, z] - */ -export declare function XYZ_D50_to_XYZ_D65(x: Color): Color; -/** - * @param {Color} color [x, y, z] - * - X as number 0..1; - * - Y as number 0..1; - * - Z as number 0..1; - * @return {Color} D50 XYZ [x, y, z] - */ -export declare function XYZ_D50_to_XYZ_D50(x: Color): Color; diff --git a/packages/color-helpers/dist/index.cjs b/packages/color-helpers/dist/index.cjs index 9ef29bb92..41e8ee1d5 100644 --- a/packages/color-helpers/dist/index.cjs +++ b/packages/color-helpers/dist/index.cjs @@ -1,148 +1,19 @@ "use strict"; -/** - * @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/map-gamut.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). - */function clip(t){return t.map((t=>t<0?0:t>1?1: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). - * - * @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)]} -/** - * @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 - * @param {number[]} sample - Array of OKLab values: L as 0..1, a and b as -1..1 - * @return {number} How different a color sample is from reference - * - * @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,_){const[o,n,r]=t,[e,a,i]=_,l=o-e,u=n-a,c=r-i;return Math.sqrt(l**2+u**2+c**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/map-gamut.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). - */function inGamut(t){const[_,o,n]=t;return _>=-1e-4&&_<=1.0001&&o>=-1e-4&&o<=1.0001&&n>=-1e-4&&n<=1.0001}var t=Object.freeze({__proto__:null,clip:clip,inGamut:inGamut});const _=.02,o=1e-5;function binarySearchGamut(t,n,r){const e=t;let a=0,i=e[1];for(;i-a>o;){const t=(a+i)/2;e[1]=t;const o=n(e);if(inGamut(o)){a=t;continue}const l=clip(o);if(deltaEOK(OKLCH_to_OKLab(r(l)),OKLCH_to_OKLab(e))<_)return l;i=t}return clip(n([...e]))} -/** - * Convert an array of of sRGB values where in-gamut values are in the range - * [0 - 1] to linear light (un-companded) form. - * Extended transfer function: - * For negative values, linear portion is extended on reflection of axis, - * then reflected power function is used. - * - * @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://en.wikipedia.org/wiki/SRGB - */ -function lin_sRGB(t){return t.map((function(t){const _=t<0?-1:1,o=Math.abs(t);return o<=.04045?t/12.92:_*Math.pow((o+.055)/1.055,2.4)}))} /** * 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,_){const o=t.length;let n,r;n=Array.isArray(t[0])?t:[t],r=Array.isArray(_[0])?_:_.map((t=>[t]));const e=r[0].length,a=r[0].map(((t,_)=>r.map((t=>t[_]))));let i=n.map((t=>a.map((_=>Array.isArray(t)?t.reduce(((t,o,n)=>t+o*(_[n]||0)),0):_.reduce(((_,o)=>_+o*t),0)))));return 1===o&&(i=i[0]),1===e?i.map((t=>t[0])):i} -/** - * 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)} -/** - * Convert an array of gamma-corrected sRGB values in the 0.0 to 1.0 range - * to linear-light sRGB, then to CIE XYZ and return luminance (the Y value) - * - * @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/utilities.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). - * - * @see https://github.com/w3c/csswg-drafts/blob/main/css-color-4/utilities.js - */function sRGB_to_luminance(t){return lin_sRGB_to_XYZ(lin_sRGB(t))[1]} -/** - * Return WCAG 2.1 contrast ratio for two sRGB values given as arrays - * - * of 0.0 to 1.0 - * @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/utilities.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). - * - * @see https://github.com/w3c/csswg-drafts/blob/main/css-color-4/utilities.js - * @see https://www.w3.org/TR/WCAG21/#dfn-contrast-ratio - */var n=Object.freeze({__proto__:null,binarySearchGamut:binarySearchGamut,contrast:function contrast(t,_){const o=sRGB_to_luminance(t),n=sRGB_to_luminance(_);return o>n?(o+.05)/(n+.05):(n+.05)/(o+.05)},deltaEOK:deltaEOK,mapGamut:function mapGamut(t,_,o){return binarySearchGamut(t,_,o)},multiplyMatrices:multiplyMatrices});const r=[.3457/.3585,1,.2958/.3585]; -/** - * 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 multiplyMatrices(t,_){const o=t.length;let e,n;e=Array.isArray(t[0])?t:[t],n=Array.isArray(_[0])?_:_.map((t=>[t]));const r=n[0].length,a=n[0].map(((t,_)=>n.map((t=>t[_]))));let i=e.map((t=>a.map((_=>Array.isArray(t)?t.reduce(((t,o,e)=>t+o*(_[e]||0)),0):_.reduce(((_,o)=>_+o*t),0)))));return 1===o&&(i=i[0]),1===r?i.map((t=>t[0])):i} /** * 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)} -/** - * Convert an array of linear-light rec2020 RGB in the range 0.0-1.0 - * to gamma corrected form ITU-R BT.2020-2 p.4 - * - * @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 _=1.09929682680944;return t.map((function(t){const o=t<0?-1:1,n=Math.abs(t);return n>.018053968510807?o*(_*Math.pow(n,.45)-(_-1)):4.5*t}))} -/** - * Convert an array of linear-light a98-rgb in the range 0.0-1.0 - * to gamma corrected form. Negative values are also now accepted - * - * @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_a98rgb(t){return t.map((function(t){const _=t<0?-1:1,o=Math.abs(t);return _*Math.pow(o,256/563)}))} -/** - * Convert an array of linear-light sRGB values in the range 0.0-1.0 to gamma corrected form - * Extended transfer function: - * For negative values, linear portion extends on reflection - * of axis, then uses reflected pow below that - * - * @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://en.wikipedia.org/wiki/SRGB - */function gam_sRGB(t){return t.map((function(t){const _=t<0?-1:1,o=Math.abs(t);return o>.0031308?_*(1.055*Math.pow(o,1/2.4)-.055):12.92*t}))} -/** - * Convert an array of linear-light display-p3 RGB in the range 0.0-1.0 - * to gamma corrected form - * - * @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_P3(t){return gam_sRGB(t)} -/** - * Convert an array of linear-light prophoto-rgb in the range 0.0-1.0 - * to gamma corrected form. - * Transfer curve is gamma 1.8 with a small linear portion. - * - * @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){return t.map((function(t){const _=t<0?-1:1,o=Math.abs(t);return o>=.001953125?_*Math.pow(o,1/1.8):16*t}))} /** * @param {number} hue - Hue as degrees 0..360 * @param {number} sat - Saturation as percentage 0..100 @@ -150,19 +21,9 @@ function D50_to_D65(t){return multiplyMatrices([[.955473421488075,-.023098454948 * @return {number[]} Array of RGB components 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/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 _=t[0],o=t[1],n=t[2];function f(t){const r=(t+_/30)%12,e=o*Math.min(n,1-n);return n-e*Math.max(-1,Math.min(r-3,9-r,1))}return _%=360,_<0&&(_+=360),o/=100,n/=100,[f(0),f(8),f(4)]} -/** - * @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/utilities.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). - * - * @see https://github.com/w3c/csswg-drafts/blob/main/css-color-4/utilities.js - */ + */function HSL_to_sRGB(t){let _=t[0],o=t[1],e=t[2];function f(t){const n=(t+_/30)%12,r=o*Math.min(e,1-e);return e-r*Math.max(-1,Math.min(n-3,9-n,1))}return _%=360,_<0&&(_+=360),o/=100,e/=100,[f(0),f(8),f(4)]} /** * @param {number} hue - Hue as degrees 0..360 * @param {number} white - Whiteness as percentage 0..100 @@ -170,79 +31,64 @@ function HSL_to_sRGB(t){let _=t[0],o=t[1],n=t[2];function f(t){const r=(t+_/30)% * @return {number[]} Array of RGB components 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/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 _=t[0];let o=t[1],n=t[2];if(o/=100,n/=100,o+n>=1){const t=o/(o+n);return[t,t,t]}const r=HSL_to_sRGB([_,100,50]);for(let t=0;t<3;t++)r[t]*=1-o-n,r[t]+=o;return r} + */function HWB_to_sRGB(t){const _=t[0];let o=t[1],e=t[2];if(o/=100,e/=100,o+e>=1){const t=o/(o+e);return[t,t,t]}const n=HSL_to_sRGB([_,100,50]);for(let t=0;t<3;t++)n[t]*=1-o-e,n[t]+=o;return 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). - */function Lab_to_LCH(t){const _=180*Math.atan2(t[2],t[1])/Math.PI;return[t[0],Math.sqrt(Math.pow(t[1],2)+Math.pow(t[2],2)),_>=0?_:_+360]} + */const t=[.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(t){const _=24389/27,o=216/24389,n=[];n[1]=(t[0]+16)/116,n[0]=t[1]/500+n[1],n[2]=n[1]-t[2]/200;return[Math.pow(n[0],3)>o?Math.pow(n[0],3):(116*n[0]-16)/_,t[0]>8?Math.pow((t[0]+16)/116,3):t[0]/_,Math.pow(n[2],3)>o?Math.pow(n[2],3):(116*n[2]-16)/_].map(((t,_)=>t*r[_]))} + */function Lab_to_XYZ(_){const o=24389/27,e=216/24389,n=[];n[1]=(_[0]+16)/116,n[0]=_[1]/500+n[1],n[2]=n[1]-_[2]/200;return[Math.pow(n[0],3)>e?Math.pow(n[0],3):(116*n[0]-16)/o,_[0]>8?Math.pow((_[0]+16)/116,3):_[0]/o,Math.pow(n[2],3)>e?Math.pow(n[2],3):(116*n[2]-16)/o].map(((_,o)=>_*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)]} +/** + * 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). - */function LCH_to_Lab(t){return[t[0],t[1]*Math.cos(t[2]*Math.PI/180),t[1]*Math.sin(t[2]*Math.PI/180)]} + * @see https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js + */function OKLab_to_XYZ(t){const _=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]],_.map((t=>t**3)))} /** * Convert an array of rec2020 RGB values in the range 0.0 - 1.0 * to linear light (un-companded) form. * ITU-R BT.2020-2 p.4 * * @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 _=1.09929682680944;return t.map((function(t){const o=t<0?-1:1,n=Math.abs(t);return n<.08124285829863151?t/4.5:o*Math.pow((n+_-1)/_,1/.45)}))} + */function lin_2020(t){const _=1.09929682680944;return t.map((function(t){const o=t<0?-1:1,e=Math.abs(t);return e<.08124285829863151?t/4.5:o*Math.pow((e+_-1)/_,1/.45)}))} /** * Convert an array of linear-light rec2020 values to CIE XYZ * using 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). - * * @see http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html - */function lin_2020_to_XYZ(t){return multiplyMatrices([[63426534/99577255,20160776/139408157,47086771/278816314],[26158966/99577255,.677998071518871,8267143/139408157],[0,19567812/697040785,1.0609850577107909]],t)} -/** - * Convert an array of a98-rgb values in the range 0.0 - 1.0 - * to linear light (un-companded) form. Negative values are also now accepted - * - * @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_a98rgb(t){return t.map((function(t){const _=t<0?-1:1,o=Math.abs(t);return _*Math.pow(o,563/256)}))} + */ /** - * 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 + * Convert an array of of sRGB values where in-gamut values are in the range + * [0 - 1] to linear light (un-companded) form. + * Extended transfer function: + * For negative values, linear portion is extended on reflection of axis, + * then reflected power function is used. * * @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 - */function lin_a98rgb_to_XYZ(t){return multiplyMatrices([[573536/994567,263643/1420810,187206/994567],[591459/1989134,6239551/9945670,374412/4972835],[53769/1989134,351524/4972835,4929758/4972835]],t)} + * @see https://en.wikipedia.org/wiki/SRGB + */ +function lin_sRGB(t){return t.map((function(t){const _=t<0?-1:1,o=Math.abs(t);return o<=.04045?t/12.92:_*Math.pow((o+.055)/1.055,2.4)}))} /** * Convert an array of display-p3 RGB values in the range 0.0 - 1.0 * to linear light (un-companded) form. * * @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)} /** @@ -250,9 +96,7 @@ function HWB_to_sRGB(t){const _=t[0];let o=t[1],n=t[2];if(o/=100,n/=100,o+n>=1){ * using 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). - * * @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)} /** @@ -261,48 +105,36 @@ function HWB_to_sRGB(t){const _=t[0];let o=t[1],n=t[2];if(o/=100,n/=100,o+n>=1){ * gamma 1.8 with a small linear portion. Extended transfer function * * @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_ProPhoto(t){return t.map((function(t){const _=t<0?-1:1,o=Math.abs(t);return o<=.03125?t/16:_*Math.pow(o,1.8)}))} + */ /** - * Convert an array of linear-light prophoto-rgb values to CIE XYZ - * using D50 (so no chromatic adaptation needed afterwards) + * 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). - * - * @see http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html - */function lin_ProPhoto_to_XYZ(t){return multiplyMatrices([[.7977604896723027,.13518583717574031,.0313493495815248],[.2880711282292934,.7118432178101014,8565396060525902e-20],[0,0,.8251046025104601]],t)} + */ +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)} /** - * CMYK is an array of four values in the range [0.0, 1.0] the output is an - * array of [RGB] also in the [0.0, 1.0] range because the naive algorithm - * does not generate out of gamut colors neither does it generate accurate - * simulations of practical CMYK colors + * 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/utilities.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). - * - * @see https://github.com/w3c/csswg-drafts/blob/main/css-color-4/utilities.js - */ + * @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)} /** * @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 _=180*Math.atan2(t[2],t[1])/Math.PI;return[t[0],Math.sqrt(t[1]**2+t[2]**2),_>=0?_:_+360]} + */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)} /** - * Given OKLab, convert to XYZ relative to D65 + * Convert an array of linear-light sRGB values in the range 0.0-1.0 to gamma corrected form + * Extended transfer function: + * For negative values, linear portion extends on reflection + * of axis, then uses reflected pow below that * * @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 _=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]],_.map((t=>t**3)))} + * @see https://en.wikipedia.org/wiki/SRGB + */function gam_sRGB(t){return t.map((function(t){const _=t<0?-1:1,o=Math.abs(t);return o>.0031308?_*(1.055*Math.pow(o,1/2.4)-.055):12.92*t}))} /** * Convert an array of gamma-corrected sRGB values in the 0.0 to 1.0 range to HSL. * @@ -316,74 +148,71 @@ function OKLab_to_OKLCH(t){const _=180*Math.atan2(t[2],t[1])/Math.PI;return[t[0] * @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/rgbToHsl.js - */function sRGB_to_HSL(t){const _=t[0],o=t[1],n=t[2],r=Math.max(_,o,n),e=Math.min(_,o,n),a=(e+r)/2,i=r-e;let l=NaN,u=0;if(0!==Math.round(1e5*i)){switch(u=0===Math.round(1e5*a)||1e5===Math.round(1e5*a)?0:(r-a)/Math.min(a,1-a),r){case _:l=(o-n)/i+(ot/r[_])).map((t=>t>.008856451679035631?Math.cbrt(t):(903.2962962962963*t+16)/116));return[116*_[1]-16,500*(_[0]-_[1]),200*(_[1]-_[2])]} + */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)} /** - * Convert XYZ to linear-light rec2020 + * Convert an array of linear-light display-p3 RGB in the range 0.0-1.0 + * to gamma corrected form * * @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_2020(t){return multiplyMatrices([[30757411/17917100,-6372589/17917100,-4539589/17917100],[-.666684351832489,1.616481236634939,467509/29648200],[792561/44930125,-1921689/44930125,.942103121235474]],t)} + */function gam_P3(t){return gam_sRGB(t)} /** - * Convert XYZ to linear-light a98-rgb + * Assuming XYZ is relative to D50, convert to CIE Lab + * from CIE standard, which now defines these as a rational fraction * * @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_a98rgb(t){return multiplyMatrices([[1829569/896150,-506331/896150,-308931/896150],[-851781/878810,1648619/878810,36519/878810],[16779/1248040,-147721/1248040,1266979/1248040]],t)} + */function XYZ_to_Lab(_){const o=_.map(((_,o)=>_/t[o])).map((t=>t>.008856451679035631?Math.cbrt(t):(903.2962962962963*t+16)/116));return[116*o[1]-16,500*(o[0]-o[1]),200*(o[1]-o[2])]} /** - * 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)} -/** - * Convert XYZ to linear-light prophoto-rgb * + * 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 _=multiplyMatrices([[.819022437996703,.3619062600528904,-.1288737815209879],[.0329836539323885,.9292868615863434,.0361446663506424],[.0481771893596242,.2642395317527308,.6335478284694309]],t);return multiplyMatrices([[.210454268309314,.7936177747023054,-.0040720430116193],[1.9779985324311684,-2.42859224204858,.450593709617411],[.0259040424655478,.7827717124575296,-.8086757549230774]],_.map((t=>Math.cbrt(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). - * - * @see http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html - */function XYZ_to_lin_ProPhoto(t){return multiplyMatrices([[1.3457989731028281,-.25558010007997534,-.05110628506753401],[-.5446224939028347,1.5082327413132781,.02053603239147973],[0,0,1.2119675456389454]],t)} + */function Lab_to_LCH(t){const _=180*Math.atan2(t[2],t[1])/Math.PI;return[t[0],Math.sqrt(Math.pow(t[1],2)+Math.pow(t[2],2)),_>=0?_:_+360]} /** * @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)} + * @see https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js + */function OKLab_to_OKLCH(t){const _=180*Math.atan2(t[2],t[1])/Math.PI;return[t[0],Math.sqrt(t[1]**2+t[2]**2),_>=0?_:_+360]} /** - * @license W3C https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document + * 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). - * - * 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 _=multiplyMatrices([[.819022437996703,.3619062600528904,-.1288737815209879],[.0329836539323885,.9292868615863434,.0361446663506424],[.0481771893596242,.2642395317527308,.6335478284694309]],t);return multiplyMatrices([[.210454268309314,.7936177747023054,-.0040720430116193],[1.9779985324311684,-2.42859224204858,.450593709617411],[.0259040424655478,.7827717124575296,-.8086757549230774]],_.map((t=>Math.cbrt(t))))} + */ /** - * Convert an array of three XYZ values to u*,v* chromaticity coordinates + * Convert an array of linear-light rec2020 RGB in the range 0.0-1.0 + * to gamma corrected form ITU-R BT.2020-2 p.4 * * @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/utilities.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). - * - * @see https://github.com/w3c/csswg-drafts/blob/main/css-color-4/utilities.js - */var e=Object.freeze({__proto__:null,D50:r,D50_to_D65:D50_to_D65,D65:[.3127/.329,1,.3583/.329],D65_to_D50:D65_to_D50,HSL_to_sRGB:HSL_to_sRGB,HWB_to_sRGB:HWB_to_sRGB,LCH_to_Lab:LCH_to_Lab,Lab_to_LCH:Lab_to_LCH,Lab_to_XYZ:Lab_to_XYZ,OKLCH_to_OKLab:OKLCH_to_OKLab,OKLab_to_OKLCH:OKLab_to_OKLCH,OKLab_to_XYZ:OKLab_to_XYZ,XYZ_to_Lab:XYZ_to_Lab,XYZ_to_OKLab:XYZ_to_OKLab,XYZ_to_lin_2020:XYZ_to_lin_2020,XYZ_to_lin_P3:XYZ_to_lin_P3,XYZ_to_lin_ProPhoto:XYZ_to_lin_ProPhoto,XYZ_to_lin_a98rgb:XYZ_to_lin_a98rgb,XYZ_to_lin_sRGB:XYZ_to_lin_sRGB,XYZ_to_uv:function XYZ_to_uv(t){const _=t[0],o=t[1],n=_+15*o+3*t[2];return[4*_/n,9*o/n]} + * @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 _=1.09929682680944;return t.map((function(t){const o=t<0?-1:1,e=Math.abs(t);return e>.018053968510807?o*(_*Math.pow(e,.45)-(_-1)):4.5*t}))} /** - * Convert an array of three XYZ values to x,y chromaticity coordinates + * Convert XYZ to linear-light prophoto-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). + * @see http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html + */function inGamut(t){const[_,o,e]=t;return _>=-1e-4&&_<=1.0001&&o>=-1e-4&&o<=1.0001&&e>=-1e-4&&e<=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 + * @param {number[]} sample - Array of OKLab values: L as 0..1, a and b as -1..1 + * @return {number} How different a color sample is from reference * - * @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/utilities.js - */,XYZ_to_xy:function XYZ_to_xy(t){const _=t[0],o=t[1],n=_+o+t[2];return[_/n,o/n]},foo:function foo(){},gam_2020:gam_2020,gam_P3:gam_P3,gam_ProPhoto:gam_ProPhoto,gam_a98rgb:gam_a98rgb,gam_sRGB:gam_sRGB,hueToRGB:function hueToRGB(t,_,o){return o<0&&(o+=6),o>=6&&(o-=6),o<1?(_-t)*o+t:o<3?_:o<4?(_-t)*(4-o)+t:t},lin_2020:lin_2020,lin_2020_to_XYZ:lin_2020_to_XYZ,lin_P3:lin_P3,lin_P3_to_XYZ:lin_P3_to_XYZ,lin_ProPhoto:lin_ProPhoto,lin_ProPhoto_to_XYZ:lin_ProPhoto_to_XYZ,lin_a98rgb:lin_a98rgb,lin_a98rgb_to_XYZ:lin_a98rgb_to_XYZ,lin_sRGB:lin_sRGB,lin_sRGB_to_XYZ:lin_sRGB_to_XYZ,naive_CMYK_to_sRGB:function naive_CMYK_to_sRGB(t){const _=t[0],o=t[1],n=t[2],r=t[3];return[1-Math.min(1,_*(1-r)+r),1-Math.min(1,o*(1-r)+r),1-Math.min(1,n*(1-r)+r)]},sRGB_to_HSL:sRGB_to_HSL,sRGB_to_HWB:function sRGB_to_HWB(t){const _=sRGB_to_HSL(t),o=Math.min(t[0],t[1],t[2]),n=1-Math.max(t[0],t[1],t[2]);return[_[0],100*o,100*n]},sRGB_to_luminance:sRGB_to_luminance});var a=Object.freeze({__proto__:null,HSL_to_XYZ_D50:function HSL_to_XYZ_D50(t){let _=t;return _=HSL_to_sRGB(_),_=lin_sRGB(_),_=lin_sRGB_to_XYZ(_),_=D65_to_D50(_),_},HWB_to_XYZ_D50:function HWB_to_XYZ_D50(t){let _=t;return _=HWB_to_sRGB(_),_=lin_sRGB(_),_=lin_sRGB_to_XYZ(_),_=D65_to_D50(_),_},LCH_to_XYZ_D50:function LCH_to_XYZ_D50(t){let _=t;return _=LCH_to_Lab(_),_=Lab_to_XYZ(_),_},Lab_to_XYZ_D50:function Lab_to_XYZ_D50(t){let _=t;return _=Lab_to_XYZ(_),_},OKLCH_to_XYZ_D50:function OKLCH_to_XYZ_D50(t){let _=t;return _=OKLCH_to_OKLab(_),_=OKLab_to_XYZ(_),_=D65_to_D50(_),_},OKLab_to_XYZ_D50:function OKLab_to_XYZ_D50(t){let _=t;return _=OKLab_to_XYZ(_),_=D65_to_D50(_),_},P3_to_XYZ_D50:function P3_to_XYZ_D50(t){let _=t;return _=lin_P3(_),_=lin_P3_to_XYZ(_),_=D65_to_D50(_),_},ProPhoto_RGB_to_XYZ_D50:function ProPhoto_RGB_to_XYZ_D50(t){let _=t;return _=lin_ProPhoto(_),_=lin_ProPhoto_to_XYZ(_),_},XYZ_D50_to_HSL:function XYZ_D50_to_HSL(t){let _=t;return _=D50_to_D65(_),_=XYZ_to_lin_sRGB(_),_=gam_sRGB(_),_=sRGB_to_HSL(_),_},XYZ_D50_to_HWB:function XYZ_D50_to_HWB(t){let _=t;_=D50_to_D65(_),_=XYZ_to_lin_sRGB(_);const o=gam_sRGB(_);_=sRGB_to_HSL(o);const n=Math.min(o[0],o[1],o[2]),r=1-Math.max(o[0],o[1],o[2]);return[_[0],100*n,100*r]},XYZ_D50_to_LCH:function XYZ_D50_to_LCH(t){let _=t;return _=XYZ_to_Lab(_),_=Lab_to_LCH(_),_},XYZ_D50_to_Lab:function XYZ_D50_to_Lab(t){let _=t;return _=XYZ_to_Lab(_),_},XYZ_D50_to_OKLCH:function XYZ_D50_to_OKLCH(t){let _=t;return _=D50_to_D65(_),_=XYZ_to_OKLab(_),_=OKLab_to_OKLCH(_),_},XYZ_D50_to_OKLab:function XYZ_D50_to_OKLab(t){let _=t;return _=D50_to_D65(_),_=XYZ_to_OKLab(_),_},XYZ_D50_to_P3:function XYZ_D50_to_P3(t){let _=t;return _=D50_to_D65(_),_=XYZ_to_lin_P3(_),_=gam_P3(_),_},XYZ_D50_to_ProPhoto:function XYZ_D50_to_ProPhoto(t){let _=t;return _=XYZ_to_lin_ProPhoto(_),_=gam_ProPhoto(_),_},XYZ_D50_to_XYZ_D50:function XYZ_D50_to_XYZ_D50(t){return t},XYZ_D50_to_XYZ_D65:function XYZ_D50_to_XYZ_D65(t){let _=t;return _=D50_to_D65(_),_},XYZ_D50_to_a98_RGB:function XYZ_D50_to_a98_RGB(t){let _=t;return _=D50_to_D65(_),_=XYZ_to_lin_a98rgb(_),_=gam_a98rgb(_),_},XYZ_D50_to_lin_sRGB:function XYZ_D50_to_lin_sRGB(t){let _=t;return _=D50_to_D65(_),_=XYZ_to_lin_sRGB(_),_},XYZ_D50_to_rec_2020:function XYZ_D50_to_rec_2020(t){let _=t;return _=D50_to_D65(_),_=XYZ_to_lin_2020(_),_=gam_2020(_),_},XYZ_D50_to_sRGB:function XYZ_D50_to_sRGB(t){let _=t;return _=D50_to_D65(_),_=XYZ_to_lin_sRGB(_),_=gam_sRGB(_),_},XYZ_D65_to_XYZ_D50:function XYZ_D65_to_XYZ_D50(t){let _=t;return _=D65_to_D50(_),_},a98_RGB_to_XYZ_D50:function a98_RGB_to_XYZ_D50(t){let _=t;return _=lin_a98rgb(_),_=lin_a98rgb_to_XYZ(_),_=D65_to_D50(_),_},lin_sRGB_to_XYZ_D50:function lin_sRGB_to_XYZ_D50(t){let _=t;return _=lin_sRGB_to_XYZ(_),_=D65_to_D50(_),_},rec_2020_to_XYZ_D50:function rec_2020_to_XYZ_D50(t){let _=t;return _=lin_2020(_),_=lin_2020_to_XYZ(_),_=D65_to_D50(_),_},sRGB_to_XYZ_D50:function sRGB_to_XYZ_D50(t){let _=t;return _=lin_sRGB(_),_=lin_sRGB_to_XYZ(_),_=D65_to_D50(_),_}});exports.calculations=n,exports.conversions=e,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.utils=t,exports.xyz=a; + * @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,_){const[o,e,n]=t,[r,a,i]=_,l=o-r,u=e-a,s=n-i;return Math.sqrt(l**2+u**2+s**2)}const _=.02,o=1e-5;function binarySearchGamut(t,e,n){const r=t;let a=0,i=r[1];for(;i-a>o;){const t=(a+i)/2;r[1]=t;const o=e(r);if(inGamut(o)){a=t;continue}const l=clip(o);if(deltaEOK(OKLCH_to_OKLab(n(l)),OKLCH_to_OKLab(r))<_)return l;i=t}return clip(e([...r]))}exports.HSL_to_XYZ_D50=function HSL_to_XYZ_D50(t){let _=t;return _=HSL_to_sRGB(_),_=lin_sRGB(_),_=lin_sRGB_to_XYZ(_),_=D65_to_D50(_),_},exports.HWB_to_XYZ_D50=function HWB_to_XYZ_D50(t){let _=t;return _=HWB_to_sRGB(_),_=lin_sRGB(_),_=lin_sRGB_to_XYZ(_),_=D65_to_D50(_),_},exports.LCH_to_XYZ_D50=function LCH_to_XYZ_D50(t){let _=t;var o;return _=[(o=_)[0],o[1]*Math.cos(o[2]*Math.PI/180),o[1]*Math.sin(o[2]*Math.PI/180)],_=Lab_to_XYZ(_),_},exports.Lab_to_XYZ_D50=function Lab_to_XYZ_D50(t){let _=t;return _=Lab_to_XYZ(_),_},exports.OKLCH_to_OKLab=OKLCH_to_OKLab,exports.OKLCH_to_XYZ_D50=function OKLCH_to_XYZ_D50(t){let _=t;return _=OKLCH_to_OKLab(_),_=OKLab_to_XYZ(_),_=D65_to_D50(_),_},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 _=t;return _=OKLab_to_XYZ(_),_=D65_to_D50(_),_},exports.P3_to_XYZ_D50=function P3_to_XYZ_D50(t){let _=t;return _=lin_P3(_),_=lin_P3_to_XYZ(_),_=D65_to_D50(_),_},exports.ProPhoto_RGB_to_XYZ_D50=function ProPhoto_RGB_to_XYZ_D50(t){let _=t;return _=_.map((function(t){const _=t<0?-1:1,o=Math.abs(t);return o<=.03125?t/16:_*Math.pow(o,1.8)})),_=multiplyMatrices([[.7977604896723027,.13518583717574031,.0313493495815248],[.2880711282292934,.7118432178101014,8565396060525902e-20],[0,0,.8251046025104601]],_),_},exports.XYZ_D50_to_HSL=function XYZ_D50_to_HSL(t){let _=t;return _=D50_to_D65(_),_=XYZ_to_lin_sRGB(_),_=gam_sRGB(_),_=sRGB_to_HSL(_),_},exports.XYZ_D50_to_HWB=function XYZ_D50_to_HWB(t){let _=t;_=D50_to_D65(_),_=XYZ_to_lin_sRGB(_);const o=gam_sRGB(_);_=sRGB_to_HSL(o);const e=Math.min(o[0],o[1],o[2]),n=1-Math.max(o[0],o[1],o[2]);return[_[0],100*e,100*n]},exports.XYZ_D50_to_LCH=function XYZ_D50_to_LCH(t){let _=t;return _=XYZ_to_Lab(_),_=Lab_to_LCH(_),_},exports.XYZ_D50_to_Lab=function XYZ_D50_to_Lab(t){let _=t;return _=XYZ_to_Lab(_),_},exports.XYZ_D50_to_OKLCH=function XYZ_D50_to_OKLCH(t){let _=t;return _=D50_to_D65(_),_=XYZ_to_OKLab(_),_=OKLab_to_OKLCH(_),_},exports.XYZ_D50_to_OKLab=function XYZ_D50_to_OKLab(t){let _=t;return _=D50_to_D65(_),_=XYZ_to_OKLab(_),_},exports.XYZ_D50_to_P3=function XYZ_D50_to_P3(t){let _=t;return _=D50_to_D65(_),_=XYZ_to_lin_P3(_),_=gam_P3(_),_},exports.XYZ_D50_to_ProPhoto=function XYZ_D50_to_ProPhoto(t){let _=t;return _=multiplyMatrices([[1.3457989731028281,-.25558010007997534,-.05110628506753401],[-.5446224939028347,1.5082327413132781,.02053603239147973],[0,0,1.2119675456389454]],_),_=_.map((function(t){const _=t<0?-1:1,o=Math.abs(t);return o>=.001953125?_*Math.pow(o,1/1.8):16*t})),_},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 _=t;return _=D50_to_D65(_),_},exports.XYZ_D50_to_a98_RGB=function XYZ_D50_to_a98_RGB(t){let _=t;return _=D50_to_D65(_),_=multiplyMatrices([[1829569/896150,-506331/896150,-308931/896150],[-851781/878810,1648619/878810,36519/878810],[16779/1248040,-147721/1248040,1266979/1248040]],_),_=_.map((function(t){const _=t<0?-1:1,o=Math.abs(t);return _*Math.pow(o,256/563)})),_},exports.XYZ_D50_to_lin_sRGB=function XYZ_D50_to_lin_sRGB(t){let _=t;return _=D50_to_D65(_),_=XYZ_to_lin_sRGB(_),_},exports.XYZ_D50_to_rec_2020=function XYZ_D50_to_rec_2020(t){let _=t;return _=D50_to_D65(_),_=multiplyMatrices([[30757411/17917100,-6372589/17917100,-4539589/17917100],[-.666684351832489,1.616481236634939,467509/29648200],[792561/44930125,-1921689/44930125,.942103121235474]],_),_=gam_2020(_),_},exports.XYZ_D50_to_sRGB=function XYZ_D50_to_sRGB(t){let _=t;return _=D50_to_D65(_),_=XYZ_to_lin_sRGB(_),_=gam_sRGB(_),_},exports.XYZ_D65_to_XYZ_D50=function XYZ_D65_to_XYZ_D50(t){let _=t;return _=D65_to_D50(_),_},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 _=t;return _=_.map((function(t){const _=t<0?-1:1,o=Math.abs(t);return _*Math.pow(o,563/256)})),_=multiplyMatrices([[573536/994567,263643/1420810,187206/994567],[591459/1989134,6239551/9945670,374412/4972835],[53769/1989134,351524/4972835,4929758/4972835]],_),_=D65_to_D50(_),_},exports.clip=clip,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 _=t;return _=lin_sRGB_to_XYZ(_),_=D65_to_D50(_),_},exports.mapGamut=function mapGamut(t,_,o){return binarySearchGamut(t,_,o)},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 _=t;return _=lin_2020(_),_=multiplyMatrices([[63426534/99577255,20160776/139408157,47086771/278816314],[26158966/99577255,.677998071518871,8267143/139408157],[0,19567812/697040785,1.0609850577107909]],_),_=D65_to_D50(_),_},exports.sRGB_to_XYZ_D50=function sRGB_to_XYZ_D50(t){let _=t;return _=lin_sRGB(_),_=lin_sRGB_to_XYZ(_),_=D65_to_D50(_),_}; diff --git a/packages/color-helpers/dist/index.d.ts b/packages/color-helpers/dist/index.d.ts index 15af8c666..5b4405bda 100644 --- a/packages/color-helpers/dist/index.d.ts +++ b/packages/color-helpers/dist/index.d.ts @@ -1,6 +1,398 @@ -export * as calculations from './calculations'; -export * as conversions from './conversions'; -export * as utils from './utils'; -export * as xyz from './conversions/xyz'; -export type { Color } from './types/color'; -export { namedColors } from './named-colors'; +/** + * @param {Color} color [r, g, b] + * - Red as number 0..1; + * - Green as number 0..1; + * - Blue as number 0..1; + * @return {Color} D50 XYZ [x, y, z] + */ +export declare function a98_RGB_to_XYZ_D50(x: Color): Color; + +export declare function clip(color: Color): Color; + +export declare type Color = [number, number, number]; + +/** + * Convert an array of linear-light display-p3 RGB in the range 0.0-1.0 + * to gamma corrected form + * + * @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 declare function gam_P3(RGB: Color): Color; + +/** + * Convert an array of linear-light sRGB values in the range 0.0-1.0 to gamma corrected form + * Extended transfer function: + * For negative values, linear portion extends on reflection + * of axis, then uses reflected pow below that + * + * @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://en.wikipedia.org/wiki/SRGB + */ +export declare function gam_sRGB(RGB: Color): Color; + +/** + * @param {Color} color [h, s, l] + * - Hue as degrees 0..360; + * - Saturation as number 0..100; + * - Lightness as number 0..100; + * @return {Color} D50 XYZ [x, y, z] + */ +export declare function HSL_to_XYZ_D50(x: Color): Color; + +/** + * @param {Color} color [h, w, b] + * - Hue as degrees 0..360; + * - Whiteness as number 0..100; + * - Blackness as number 0..100; + * @return {Color} D50 XYZ [x, y, z] + */ +export declare function HWB_to_XYZ_D50(x: Color): Color; + +export declare function inGamut(x: Color): boolean; + +/** + * @param {Color} color [l, a, b] + * - Lightness as number 0..100; + * - a as number -160..160; + * - b as number -160..160; + * @return {Color} D50 XYZ [x, y, z] + */ +export declare function Lab_to_XYZ_D50(x: Color): Color; + +/** + * @param {Color} color [l, c, h] + * - Lightness as number 0..100; + * - Chroma as number 0..230; + * - Hue as degrees 0..360; + * @return {Color} D50 XYZ [x, y, z] + */ +export declare function LCH_to_XYZ_D50(x: Color): Color; + +/** + * Convert an array of display-p3 RGB values in the range 0.0 - 1.0 + * to linear light (un-companded) form. + * + * @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 declare function lin_P3(RGB: Color): Color; + +/** + * Convert an array of linear-light display-p3 values to CIE XYZ + * using 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). + * @see http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html + */ +export declare function lin_P3_to_XYZ(rgb: Color): Color; + +/** + * Convert an array of of sRGB values where in-gamut values are in the range + * [0 - 1] to linear light (un-companded) form. + * Extended transfer function: + * For negative values, linear portion is extended on reflection of axis, + * then reflected power function is used. + * + * @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://en.wikipedia.org/wiki/SRGB + */ +export declare function lin_sRGB(RGB: Color): Color; + +/** + * 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). + */ +export declare function lin_sRGB_to_XYZ(rgb: Color): Color; + +/** + * @param {Color} color [r, g, b] + * - Red as number 0..1; + * - Green as number 0..1; + * - Blue as number 0..1; + * @return {Color} D50 XYZ [x, y, z] + */ +export declare function lin_sRGB_to_XYZ_D50(x: Color): Color; + +export declare function mapGamut(startOKLCH: Color, toDestination: (x: Color) => Color, fromDestination: (x: Color) => Color): Color; + +export declare const namedColors: Record; + +/** + * @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 + */ +export declare function OKLab_to_OKLCH(OKLab: Color): Color; + +/** + * 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 + */ +export declare function OKLab_to_XYZ(OKLab: Color): Color; + +/** + * @param {Color} color [l, a, b] + * - Lightness as number 0..1; + * - a as number 0..0.5; + * - b as number 0..0.5; + * @return {Color} D50 XYZ [x, y, z] + */ +export declare function OKLab_to_XYZ_D50(x: Color): Color; + +/** + * @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 + */ +export declare function OKLCH_to_OKLab(OKLCH: Color): Color; + +/** + * @param {Color} color [l, c, h] + * - Lightness as number 0..1; + * - Chroma as number 0..0.5; + * - Hue as degrees 0..360; + * @return {Color} D50 XYZ [x, y, z] + */ +export declare function OKLCH_to_XYZ_D50(x: Color): Color; + +/** + * @param {Color} color [r, g, b] + * - Red as number 0..1; + * - Green as number 0..1; + * - Blue as number 0..1; + * @return {Color} D50 XYZ [x, y, z] + */ +export declare function P3_to_XYZ_D50(x: Color): Color; + +/** + * @param {Color} color [r, g, b] + * - Red as number 0..1; + * - Green as number 0..1; + * - Blue as number 0..1; + * @return {Color} D50 XYZ [x, y, z] + */ +export declare function ProPhoto_RGB_to_XYZ_D50(x: Color): Color; + +/** + * @param {Color} color [r, g, b] + * - Red as number 0..1; + * - Green as number 0..1; + * - Blue as number 0..1; + * @return {Color} D50 XYZ [x, y, z] + */ +export declare function rec_2020_to_XYZ_D50(x: Color): Color; + +/** + * @param {Color} color [r, g, b] + * - Red as number 0..1; + * - Green as number 0..1; + * - Blue as number 0..1; + * @return {Color} D50 XYZ [x, y, z] + */ +export declare function sRGB_to_XYZ_D50(x: Color): Color; + +/** + * @param {Color} color [x, y, z] + * - X as number 0..1; + * - Y as number 0..1; + * - Z as number 0..1; + * @return {Color} a98 sRGB [r, g, b] + * - Red as number 0..1; + * - Green as number 0..1; + * - Blue as number 0..1; + */ +export declare function XYZ_D50_to_a98_RGB(x: Color): Color; + +/** + * @param {Color} color [x, y, z] + * - X as number 0..1; + * - Y as number 0..1; + * - Z as number 0..1; + * @return {Color} HSL [r, g, b] + * - Hue as degrees 0..360; + * - Saturation as number 0..100; + * - Lightness as number 0..100; + */ +export declare function XYZ_D50_to_HSL(x: Color): Color; + +/** + * @param {Color} color [x, y, z] + * - X as number 0..1; + * - Y as number 0..1; + * - Z as number 0..1; + * @return {Color} HWB [r, g, b] + * - Hue as degrees 0..360; + * - Whiteness as number 0..100; + * - Blackness as number 0..100; + */ +export declare function XYZ_D50_to_HWB(x: Color): Color; + +/** + * @param {Color} color [x, y, z] + * - X as number 0..1; + * - Y as number 0..1; + * - Z as number 0..1; + * @return {Color} Lab [r, g, b] + * - Lightness as number 0..100; + * - a as number -160..160; + * - b as number -160..160; + */ +export declare function XYZ_D50_to_Lab(x: Color): Color; + +/** + * @param {Color} color [x, y, z] + * - X as number 0..1; + * - Y as number 0..1; + * - Z as number 0..1; + * @return {Color} LCH [r, g, b] + * - Lightness as number 0..100; + * - Chroma as number 0..230; + * - Hue as degrees 0..360; + */ +export declare function XYZ_D50_to_LCH(x: Color): Color; + +/** + * @param {Color} color [x, y, z] + * - X as number 0..1; + * - Y as number 0..1; + * - Z as number 0..1; + * @return {Color} linear sRGB [r, g, b] + * - Red as number 0..1; + * - Green as number 0..1; + * - Blue as number 0..1; + */ +export declare function XYZ_D50_to_lin_sRGB(x: Color): Color; + +/** + * @param {Color} color [x, y, z] + * - X as number 0..1; + * - Y as number 0..1; + * - Z as number 0..1; + * @return {Color} OKLab [r, g, b] + * - Lightness as number 0..1; + * - a as number 0..0.5; + * - b as number 0..0.5; + */ +export declare function XYZ_D50_to_OKLab(x: Color): Color; + +/** + * @param {Color} color [x, y, z] + * - X as number 0..1; + * - Y as number 0..1; + * - Z as number 0..1; + * @return {Color} OKLCH [r, g, b] + * - Lightness as number 0..1; + * - Chroma as number 0..0.5; + * - Hue as degrees 0..360; + */ +export declare function XYZ_D50_to_OKLCH(x: Color): Color; + +/** + * @param {Color} color [x, y, z] + * - X as number 0..1; + * - Y as number 0..1; + * - Z as number 0..1; + * @return {Color} P3 [r, g, b] + * - R as number 0..1; + * - G as number 0..1; + * - B as number 0..1; + */ +export declare function XYZ_D50_to_P3(x: Color): Color; + +/** + * @param {Color} color [x, y, z] + * - X as number 0..1; + * - Y as number 0..1; + * - Z as number 0..1; + * @return {Color} ProPhoto [r, g, b] + * - Red as number 0..1; + * - Green as number 0..1; + * - Blue as number 0..1; + */ +export declare function XYZ_D50_to_ProPhoto(x: Color): Color; + +/** + * @param {Color} color [x, y, z] + * - X as number 0..1; + * - Y as number 0..1; + * - Z as number 0..1; + * @return {Color} rec 2020 [r, g, b] + * - Red as number 0..1; + * - Green as number 0..1; + * - Blue as number 0..1; + */ +export declare function XYZ_D50_to_rec_2020(x: Color): Color; + +/** + * @param {Color} color [x, y, z] + * - X as number 0..1; + * - Y as number 0..1; + * - Z as number 0..1; + * @return {Color} sRGB [r, g, b] + * - Red as number 0..1; + * - Green as number 0..1; + * - Blue as number 0..1; + */ +export declare function XYZ_D50_to_sRGB(x: Color): Color; + +/** + * @param {Color} color [x, y, z] + * - X as number 0..1; + * - Y as number 0..1; + * - Z as number 0..1; + * @return {Color} D50 XYZ [x, y, z] + */ +export declare function XYZ_D50_to_XYZ_D50(x: Color): Color; + +/** + * @param {Color} color [x, y, z] + * - X as number 0..1; + * - Y as number 0..1; + * - Z as number 0..1; + * @return {Color} D65 XYZ [x, y, z] + */ +export declare function XYZ_D50_to_XYZ_D65(x: Color): Color; + +/** + * @param {Color} color [x, y, z] + * - X as number 0..1; + * - Y as number 0..1; + * - Z as number 0..1; + * @return {Color} D50 XYZ [x, y, z] + */ +export declare function XYZ_D65_to_XYZ_D50(x: Color): Color; + +/** + * 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). + */ +export declare function XYZ_to_lin_P3(XYZ: Color): Color; + +/** + * @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 declare function XYZ_to_lin_sRGB(XYZ: Color): Color; + +/** + * @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 + */ +export declare function XYZ_to_OKLab(XYZ: Color): Color; + +export { } diff --git a/packages/color-helpers/dist/index.mjs b/packages/color-helpers/dist/index.mjs index 9b34907a2..0971c853a 100644 --- a/packages/color-helpers/dist/index.mjs +++ b/packages/color-helpers/dist/index.mjs @@ -1,148 +1,19 @@ -/** - * @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/map-gamut.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). - */ -function clip(t){return t.map((t=>t<0?0:t>1?1: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). - * - * @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)]} -/** - * @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 - * @param {number[]} sample - Array of OKLab values: L as 0..1, a and b as -1..1 - * @return {number} How different a color sample is from reference - * - * @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,_){const[o,n,r]=t,[e,a,i]=_,l=o-e,u=n-a,c=r-i;return Math.sqrt(l**2+u**2+c**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/map-gamut.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). - */function inGamut(t){const[_,o,n]=t;return _>=-1e-4&&_<=1.0001&&o>=-1e-4&&o<=1.0001&&n>=-1e-4&&n<=1.0001}var t=Object.freeze({__proto__:null,clip:clip,inGamut:inGamut});const _=.02,o=1e-5;function binarySearchGamut(t,n,r){const e=t;let a=0,i=e[1];for(;i-a>o;){const t=(a+i)/2;e[1]=t;const o=n(e);if(inGamut(o)){a=t;continue}const l=clip(o);if(deltaEOK(OKLCH_to_OKLab(r(l)),OKLCH_to_OKLab(e))<_)return l;i=t}return clip(n([...e]))} -/** - * Convert an array of of sRGB values where in-gamut values are in the range - * [0 - 1] to linear light (un-companded) form. - * Extended transfer function: - * For negative values, linear portion is extended on reflection of axis, - * then reflected power function is used. - * - * @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://en.wikipedia.org/wiki/SRGB - */ -function lin_sRGB(t){return t.map((function(t){const _=t<0?-1:1,o=Math.abs(t);return o<=.04045?t/12.92:_*Math.pow((o+.055)/1.055,2.4)}))} /** * 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,_){const o=t.length;let n,r;n=Array.isArray(t[0])?t:[t],r=Array.isArray(_[0])?_:_.map((t=>[t]));const e=r[0].length,a=r[0].map(((t,_)=>r.map((t=>t[_]))));let i=n.map((t=>a.map((_=>Array.isArray(t)?t.reduce(((t,o,n)=>t+o*(_[n]||0)),0):_.reduce(((_,o)=>_+o*t),0)))));return 1===o&&(i=i[0]),1===e?i.map((t=>t[0])):i} -/** - * 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)} -/** - * Convert an array of gamma-corrected sRGB values in the 0.0 to 1.0 range - * to linear-light sRGB, then to CIE XYZ and return luminance (the Y value) - * - * @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/utilities.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). - * - * @see https://github.com/w3c/csswg-drafts/blob/main/css-color-4/utilities.js - */function sRGB_to_luminance(t){return lin_sRGB_to_XYZ(lin_sRGB(t))[1]} -/** - * Return WCAG 2.1 contrast ratio for two sRGB values given as arrays - * - * of 0.0 to 1.0 - * @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/utilities.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). - * - * @see https://github.com/w3c/csswg-drafts/blob/main/css-color-4/utilities.js - * @see https://www.w3.org/TR/WCAG21/#dfn-contrast-ratio - */var n=Object.freeze({__proto__:null,binarySearchGamut:binarySearchGamut,contrast:function contrast(t,_){const o=sRGB_to_luminance(t),n=sRGB_to_luminance(_);return o>n?(o+.05)/(n+.05):(n+.05)/(o+.05)},deltaEOK:deltaEOK,mapGamut:function mapGamut(t,_,o){return binarySearchGamut(t,_,o)},multiplyMatrices:multiplyMatrices});const r=[.3457/.3585,1,.2958/.3585]; -/** - * 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 multiplyMatrices(t,_){const n=t.length;let o,e;o=Array.isArray(t[0])?t:[t],e=Array.isArray(_[0])?_:_.map((t=>[t]));const r=e[0].length,a=e[0].map(((t,_)=>e.map((t=>t[_]))));let i=o.map((t=>a.map((_=>Array.isArray(t)?t.reduce(((t,n,o)=>t+n*(_[o]||0)),0):_.reduce(((_,n)=>_+n*t),0)))));return 1===n&&(i=i[0]),1===r?i.map((t=>t[0])):i} /** * 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)} -/** - * Convert an array of linear-light rec2020 RGB in the range 0.0-1.0 - * to gamma corrected form ITU-R BT.2020-2 p.4 - * - * @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 _=1.09929682680944;return t.map((function(t){const o=t<0?-1:1,n=Math.abs(t);return n>.018053968510807?o*(_*Math.pow(n,.45)-(_-1)):4.5*t}))} -/** - * Convert an array of linear-light a98-rgb in the range 0.0-1.0 - * to gamma corrected form. Negative values are also now accepted - * - * @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_a98rgb(t){return t.map((function(t){const _=t<0?-1:1,o=Math.abs(t);return _*Math.pow(o,256/563)}))} -/** - * Convert an array of linear-light sRGB values in the range 0.0-1.0 to gamma corrected form - * Extended transfer function: - * For negative values, linear portion extends on reflection - * of axis, then uses reflected pow below that - * - * @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://en.wikipedia.org/wiki/SRGB - */function gam_sRGB(t){return t.map((function(t){const _=t<0?-1:1,o=Math.abs(t);return o>.0031308?_*(1.055*Math.pow(o,1/2.4)-.055):12.92*t}))} -/** - * Convert an array of linear-light display-p3 RGB in the range 0.0-1.0 - * to gamma corrected form - * - * @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_P3(t){return gam_sRGB(t)} -/** - * Convert an array of linear-light prophoto-rgb in the range 0.0-1.0 - * to gamma corrected form. - * Transfer curve is gamma 1.8 with a small linear portion. - * - * @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){return t.map((function(t){const _=t<0?-1:1,o=Math.abs(t);return o>=.001953125?_*Math.pow(o,1/1.8):16*t}))} /** * @param {number} hue - Hue as degrees 0..360 * @param {number} sat - Saturation as percentage 0..100 @@ -150,19 +21,9 @@ function D50_to_D65(t){return multiplyMatrices([[.955473421488075,-.023098454948 * @return {number[]} Array of RGB components 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/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 _=t[0],o=t[1],n=t[2];function f(t){const r=(t+_/30)%12,e=o*Math.min(n,1-n);return n-e*Math.max(-1,Math.min(r-3,9-r,1))}return _%=360,_<0&&(_+=360),o/=100,n/=100,[f(0),f(8),f(4)]} -/** - * @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/utilities.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). - * - * @see https://github.com/w3c/csswg-drafts/blob/main/css-color-4/utilities.js - */ + */function HSL_to_sRGB(t){let _=t[0],n=t[1],o=t[2];function f(t){const e=(t+_/30)%12,r=n*Math.min(o,1-o);return o-r*Math.max(-1,Math.min(e-3,9-e,1))}return _%=360,_<0&&(_+=360),n/=100,o/=100,[f(0),f(8),f(4)]} /** * @param {number} hue - Hue as degrees 0..360 * @param {number} white - Whiteness as percentage 0..100 @@ -170,79 +31,64 @@ function HSL_to_sRGB(t){let _=t[0],o=t[1],n=t[2];function f(t){const r=(t+_/30)% * @return {number[]} Array of RGB components 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/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 _=t[0];let o=t[1],n=t[2];if(o/=100,n/=100,o+n>=1){const t=o/(o+n);return[t,t,t]}const r=HSL_to_sRGB([_,100,50]);for(let t=0;t<3;t++)r[t]*=1-o-n,r[t]+=o;return r} + */function HWB_to_sRGB(t){const _=t[0];let n=t[1],o=t[2];if(n/=100,o/=100,n+o>=1){const t=n/(n+o);return[t,t,t]}const e=HSL_to_sRGB([_,100,50]);for(let t=0;t<3;t++)e[t]*=1-n-o,e[t]+=n;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). - */function Lab_to_LCH(t){const _=180*Math.atan2(t[2],t[1])/Math.PI;return[t[0],Math.sqrt(Math.pow(t[1],2)+Math.pow(t[2],2)),_>=0?_:_+360]} + */const t=[.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(t){const _=24389/27,o=216/24389,n=[];n[1]=(t[0]+16)/116,n[0]=t[1]/500+n[1],n[2]=n[1]-t[2]/200;return[Math.pow(n[0],3)>o?Math.pow(n[0],3):(116*n[0]-16)/_,t[0]>8?Math.pow((t[0]+16)/116,3):t[0]/_,Math.pow(n[2],3)>o?Math.pow(n[2],3):(116*n[2]-16)/_].map(((t,_)=>t*r[_]))} + */function Lab_to_XYZ(_){const n=24389/27,o=216/24389,e=[];e[1]=(_[0]+16)/116,e[0]=_[1]/500+e[1],e[2]=e[1]-_[2]/200;return[Math.pow(e[0],3)>o?Math.pow(e[0],3):(116*e[0]-16)/n,_[0]>8?Math.pow((_[0]+16)/116,3):_[0]/n,Math.pow(e[2],3)>o?Math.pow(e[2],3):(116*e[2]-16)/n].map(((_,n)=>_*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)]} +/** + * 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). - */function LCH_to_Lab(t){return[t[0],t[1]*Math.cos(t[2]*Math.PI/180),t[1]*Math.sin(t[2]*Math.PI/180)]} + * @see https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js + */function OKLab_to_XYZ(t){const _=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]],_.map((t=>t**3)))} /** * Convert an array of rec2020 RGB values in the range 0.0 - 1.0 * to linear light (un-companded) form. * ITU-R BT.2020-2 p.4 * * @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 _=1.09929682680944;return t.map((function(t){const o=t<0?-1:1,n=Math.abs(t);return n<.08124285829863151?t/4.5:o*Math.pow((n+_-1)/_,1/.45)}))} + */function lin_2020(t){const _=1.09929682680944;return t.map((function(t){const n=t<0?-1:1,o=Math.abs(t);return o<.08124285829863151?t/4.5:n*Math.pow((o+_-1)/_,1/.45)}))} /** * Convert an array of linear-light rec2020 values to CIE XYZ * using 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). - * * @see http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html - */function lin_2020_to_XYZ(t){return multiplyMatrices([[63426534/99577255,20160776/139408157,47086771/278816314],[26158966/99577255,.677998071518871,8267143/139408157],[0,19567812/697040785,1.0609850577107909]],t)} -/** - * Convert an array of a98-rgb values in the range 0.0 - 1.0 - * to linear light (un-companded) form. Negative values are also now accepted - * - * @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_a98rgb(t){return t.map((function(t){const _=t<0?-1:1,o=Math.abs(t);return _*Math.pow(o,563/256)}))} + */ /** - * 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 + * Convert an array of of sRGB values where in-gamut values are in the range + * [0 - 1] to linear light (un-companded) form. + * Extended transfer function: + * For negative values, linear portion is extended on reflection of axis, + * then reflected power function is used. * * @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 - */function lin_a98rgb_to_XYZ(t){return multiplyMatrices([[573536/994567,263643/1420810,187206/994567],[591459/1989134,6239551/9945670,374412/4972835],[53769/1989134,351524/4972835,4929758/4972835]],t)} + * @see https://en.wikipedia.org/wiki/SRGB + */ +function lin_sRGB(t){return t.map((function(t){const _=t<0?-1:1,n=Math.abs(t);return n<=.04045?t/12.92:_*Math.pow((n+.055)/1.055,2.4)}))} /** * Convert an array of display-p3 RGB values in the range 0.0 - 1.0 * to linear light (un-companded) form. * * @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)} /** @@ -250,9 +96,7 @@ function HWB_to_sRGB(t){const _=t[0];let o=t[1],n=t[2];if(o/=100,n/=100,o+n>=1){ * using 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). - * * @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)} /** @@ -261,48 +105,36 @@ function HWB_to_sRGB(t){const _=t[0];let o=t[1],n=t[2];if(o/=100,n/=100,o+n>=1){ * gamma 1.8 with a small linear portion. Extended transfer function * * @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_ProPhoto(t){return t.map((function(t){const _=t<0?-1:1,o=Math.abs(t);return o<=.03125?t/16:_*Math.pow(o,1.8)}))} + */ /** - * Convert an array of linear-light prophoto-rgb values to CIE XYZ - * using D50 (so no chromatic adaptation needed afterwards) + * 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). - * - * @see http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html - */function lin_ProPhoto_to_XYZ(t){return multiplyMatrices([[.7977604896723027,.13518583717574031,.0313493495815248],[.2880711282292934,.7118432178101014,8565396060525902e-20],[0,0,.8251046025104601]],t)} + */ +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)} /** - * CMYK is an array of four values in the range [0.0, 1.0] the output is an - * array of [RGB] also in the [0.0, 1.0] range because the naive algorithm - * does not generate out of gamut colors neither does it generate accurate - * simulations of practical CMYK colors + * 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/utilities.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). - * - * @see https://github.com/w3c/csswg-drafts/blob/main/css-color-4/utilities.js - */ + * @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)} /** * @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 _=180*Math.atan2(t[2],t[1])/Math.PI;return[t[0],Math.sqrt(t[1]**2+t[2]**2),_>=0?_:_+360]} + */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)} /** - * Given OKLab, convert to XYZ relative to D65 + * Convert an array of linear-light sRGB values in the range 0.0-1.0 to gamma corrected form + * Extended transfer function: + * For negative values, linear portion extends on reflection + * of axis, then uses reflected pow below that * * @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 _=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]],_.map((t=>t**3)))} + * @see https://en.wikipedia.org/wiki/SRGB + */function gam_sRGB(t){return t.map((function(t){const _=t<0?-1:1,n=Math.abs(t);return n>.0031308?_*(1.055*Math.pow(n,1/2.4)-.055):12.92*t}))} /** * Convert an array of gamma-corrected sRGB values in the 0.0 to 1.0 range to HSL. * @@ -316,74 +148,71 @@ function OKLab_to_OKLCH(t){const _=180*Math.atan2(t[2],t[1])/Math.PI;return[t[0] * @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/rgbToHsl.js - */function sRGB_to_HSL(t){const _=t[0],o=t[1],n=t[2],r=Math.max(_,o,n),e=Math.min(_,o,n),a=(e+r)/2,i=r-e;let l=NaN,u=0;if(0!==Math.round(1e5*i)){switch(u=0===Math.round(1e5*a)||1e5===Math.round(1e5*a)?0:(r-a)/Math.min(a,1-a),r){case _:l=(o-n)/i+(ot/r[_])).map((t=>t>.008856451679035631?Math.cbrt(t):(903.2962962962963*t+16)/116));return[116*_[1]-16,500*(_[0]-_[1]),200*(_[1]-_[2])]} + */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)} /** - * Convert XYZ to linear-light rec2020 + * Convert an array of linear-light display-p3 RGB in the range 0.0-1.0 + * to gamma corrected form * * @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_2020(t){return multiplyMatrices([[30757411/17917100,-6372589/17917100,-4539589/17917100],[-.666684351832489,1.616481236634939,467509/29648200],[792561/44930125,-1921689/44930125,.942103121235474]],t)} + */function gam_P3(t){return gam_sRGB(t)} /** - * Convert XYZ to linear-light a98-rgb + * Assuming XYZ is relative to D50, convert to CIE Lab + * from CIE standard, which now defines these as a rational fraction * * @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_a98rgb(t){return multiplyMatrices([[1829569/896150,-506331/896150,-308931/896150],[-851781/878810,1648619/878810,36519/878810],[16779/1248040,-147721/1248040,1266979/1248040]],t)} + */function XYZ_to_Lab(_){const n=_.map(((_,n)=>_/t[n])).map((t=>t>.008856451679035631?Math.cbrt(t):(903.2962962962963*t+16)/116));return[116*n[1]-16,500*(n[0]-n[1]),200*(n[1]-n[2])]} /** - * 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)} -/** - * Convert XYZ to linear-light prophoto-rgb * + * 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 _=multiplyMatrices([[.819022437996703,.3619062600528904,-.1288737815209879],[.0329836539323885,.9292868615863434,.0361446663506424],[.0481771893596242,.2642395317527308,.6335478284694309]],t);return multiplyMatrices([[.210454268309314,.7936177747023054,-.0040720430116193],[1.9779985324311684,-2.42859224204858,.450593709617411],[.0259040424655478,.7827717124575296,-.8086757549230774]],_.map((t=>Math.cbrt(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). - * - * @see http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html - */function XYZ_to_lin_ProPhoto(t){return multiplyMatrices([[1.3457989731028281,-.25558010007997534,-.05110628506753401],[-.5446224939028347,1.5082327413132781,.02053603239147973],[0,0,1.2119675456389454]],t)} + */function Lab_to_LCH(t){const _=180*Math.atan2(t[2],t[1])/Math.PI;return[t[0],Math.sqrt(Math.pow(t[1],2)+Math.pow(t[2],2)),_>=0?_:_+360]} /** * @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)} + * @see https://github.com/w3c/csswg-drafts/blob/main/css-color-4/conversions.js + */function OKLab_to_OKLCH(t){const _=180*Math.atan2(t[2],t[1])/Math.PI;return[t[0],Math.sqrt(t[1]**2+t[2]**2),_>=0?_:_+360]} /** - * @license W3C https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document + * 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). - * - * 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 _=multiplyMatrices([[.819022437996703,.3619062600528904,-.1288737815209879],[.0329836539323885,.9292868615863434,.0361446663506424],[.0481771893596242,.2642395317527308,.6335478284694309]],t);return multiplyMatrices([[.210454268309314,.7936177747023054,-.0040720430116193],[1.9779985324311684,-2.42859224204858,.450593709617411],[.0259040424655478,.7827717124575296,-.8086757549230774]],_.map((t=>Math.cbrt(t))))} + */ /** - * Convert an array of three XYZ values to u*,v* chromaticity coordinates + * Convert an array of linear-light rec2020 RGB in the range 0.0-1.0 + * to gamma corrected form ITU-R BT.2020-2 p.4 * * @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/utilities.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). - * - * @see https://github.com/w3c/csswg-drafts/blob/main/css-color-4/utilities.js - */var e=Object.freeze({__proto__:null,D50:r,D50_to_D65:D50_to_D65,D65:[.3127/.329,1,.3583/.329],D65_to_D50:D65_to_D50,HSL_to_sRGB:HSL_to_sRGB,HWB_to_sRGB:HWB_to_sRGB,LCH_to_Lab:LCH_to_Lab,Lab_to_LCH:Lab_to_LCH,Lab_to_XYZ:Lab_to_XYZ,OKLCH_to_OKLab:OKLCH_to_OKLab,OKLab_to_OKLCH:OKLab_to_OKLCH,OKLab_to_XYZ:OKLab_to_XYZ,XYZ_to_Lab:XYZ_to_Lab,XYZ_to_OKLab:XYZ_to_OKLab,XYZ_to_lin_2020:XYZ_to_lin_2020,XYZ_to_lin_P3:XYZ_to_lin_P3,XYZ_to_lin_ProPhoto:XYZ_to_lin_ProPhoto,XYZ_to_lin_a98rgb:XYZ_to_lin_a98rgb,XYZ_to_lin_sRGB:XYZ_to_lin_sRGB,XYZ_to_uv:function XYZ_to_uv(t){const _=t[0],o=t[1],n=_+15*o+3*t[2];return[4*_/n,9*o/n]} + * @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 _=1.09929682680944;return t.map((function(t){const n=t<0?-1:1,o=Math.abs(t);return o>.018053968510807?n*(_*Math.pow(o,.45)-(_-1)):4.5*t}))} /** - * Convert an array of three XYZ values to x,y chromaticity coordinates + * Convert XYZ to linear-light prophoto-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). + * @see http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html + */function sRGB_to_XYZ_D50(t){let _=t;return _=lin_sRGB(_),_=lin_sRGB_to_XYZ(_),_=D65_to_D50(_),_}function XYZ_D50_to_sRGB(t){let _=t;return _=D50_to_D65(_),_=XYZ_to_lin_sRGB(_),_=gam_sRGB(_),_}function HSL_to_XYZ_D50(t){let _=t;return _=HSL_to_sRGB(_),_=lin_sRGB(_),_=lin_sRGB_to_XYZ(_),_=D65_to_D50(_),_}function XYZ_D50_to_HSL(t){let _=t;return _=D50_to_D65(_),_=XYZ_to_lin_sRGB(_),_=gam_sRGB(_),_=sRGB_to_HSL(_),_}function HWB_to_XYZ_D50(t){let _=t;return _=HWB_to_sRGB(_),_=lin_sRGB(_),_=lin_sRGB_to_XYZ(_),_=D65_to_D50(_),_}function XYZ_D50_to_HWB(t){let _=t;_=D50_to_D65(_),_=XYZ_to_lin_sRGB(_);const n=gam_sRGB(_);_=sRGB_to_HSL(n);const o=Math.min(n[0],n[1],n[2]),e=1-Math.max(n[0],n[1],n[2]);return[_[0],100*o,100*e]}function Lab_to_XYZ_D50(t){let _=t;return _=Lab_to_XYZ(_),_}function XYZ_D50_to_Lab(t){let _=t;return _=XYZ_to_Lab(_),_}function LCH_to_XYZ_D50(t){let _=t;var n;return _=[(n=_)[0],n[1]*Math.cos(n[2]*Math.PI/180),n[1]*Math.sin(n[2]*Math.PI/180)],_=Lab_to_XYZ(_),_}function XYZ_D50_to_LCH(t){let _=t;return _=XYZ_to_Lab(_),_=Lab_to_LCH(_),_}function OKLab_to_XYZ_D50(t){let _=t;return _=OKLab_to_XYZ(_),_=D65_to_D50(_),_}function XYZ_D50_to_OKLab(t){let _=t;return _=D50_to_D65(_),_=XYZ_to_OKLab(_),_}function OKLCH_to_XYZ_D50(t){let _=t;return _=OKLCH_to_OKLab(_),_=OKLab_to_XYZ(_),_=D65_to_D50(_),_}function XYZ_D50_to_OKLCH(t){let _=t;return _=D50_to_D65(_),_=XYZ_to_OKLab(_),_=OKLab_to_OKLCH(_),_}function lin_sRGB_to_XYZ_D50(t){let _=t;return _=lin_sRGB_to_XYZ(_),_=D65_to_D50(_),_}function XYZ_D50_to_lin_sRGB(t){let _=t;return _=D50_to_D65(_),_=XYZ_to_lin_sRGB(_),_}function a98_RGB_to_XYZ_D50(t){let _=t;return _=_.map((function(t){const _=t<0?-1:1,n=Math.abs(t);return _*Math.pow(n,563/256)})),_=multiplyMatrices([[573536/994567,263643/1420810,187206/994567],[591459/1989134,6239551/9945670,374412/4972835],[53769/1989134,351524/4972835,4929758/4972835]],_),_=D65_to_D50(_),_}function XYZ_D50_to_a98_RGB(t){let _=t;return _=D50_to_D65(_),_=multiplyMatrices([[1829569/896150,-506331/896150,-308931/896150],[-851781/878810,1648619/878810,36519/878810],[16779/1248040,-147721/1248040,1266979/1248040]],_),_=_.map((function(t){const _=t<0?-1:1,n=Math.abs(t);return _*Math.pow(n,256/563)})),_}function P3_to_XYZ_D50(t){let _=t;return _=lin_P3(_),_=lin_P3_to_XYZ(_),_=D65_to_D50(_),_}function XYZ_D50_to_P3(t){let _=t;return _=D50_to_D65(_),_=XYZ_to_lin_P3(_),_=gam_P3(_),_}function rec_2020_to_XYZ_D50(t){let _=t;return _=lin_2020(_),_=multiplyMatrices([[63426534/99577255,20160776/139408157,47086771/278816314],[26158966/99577255,.677998071518871,8267143/139408157],[0,19567812/697040785,1.0609850577107909]],_),_=D65_to_D50(_),_}function XYZ_D50_to_rec_2020(t){let _=t;return _=D50_to_D65(_),_=multiplyMatrices([[30757411/17917100,-6372589/17917100,-4539589/17917100],[-.666684351832489,1.616481236634939,467509/29648200],[792561/44930125,-1921689/44930125,.942103121235474]],_),_=gam_2020(_),_}function ProPhoto_RGB_to_XYZ_D50(t){let _=t;return _=_.map((function(t){const _=t<0?-1:1,n=Math.abs(t);return n<=.03125?t/16:_*Math.pow(n,1.8)})),_=multiplyMatrices([[.7977604896723027,.13518583717574031,.0313493495815248],[.2880711282292934,.7118432178101014,8565396060525902e-20],[0,0,.8251046025104601]],_),_}function XYZ_D50_to_ProPhoto(t){let _=t;return _=multiplyMatrices([[1.3457989731028281,-.25558010007997534,-.05110628506753401],[-.5446224939028347,1.5082327413132781,.02053603239147973],[0,0,1.2119675456389454]],_),_=_.map((function(t){const _=t<0?-1:1,n=Math.abs(t);return n>=.001953125?_*Math.pow(n,1/1.8):16*t})),_}function XYZ_D65_to_XYZ_D50(t){let _=t;return _=D65_to_D50(_),_}function XYZ_D50_to_XYZ_D65(t){let _=t;return _=D50_to_D65(_),_}function XYZ_D50_to_XYZ_D50(t){return t}function inGamut(t){const[_,n,o]=t;return _>=-1e-4&&_<=1.0001&&n>=-1e-4&&n<=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 + * @param {number[]} sample - Array of OKLab values: L as 0..1, a and b as -1..1 + * @return {number} How different a color sample is from reference * - * @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/utilities.js - */,XYZ_to_xy:function XYZ_to_xy(t){const _=t[0],o=t[1],n=_+o+t[2];return[_/n,o/n]},foo:function foo(){},gam_2020:gam_2020,gam_P3:gam_P3,gam_ProPhoto:gam_ProPhoto,gam_a98rgb:gam_a98rgb,gam_sRGB:gam_sRGB,hueToRGB:function hueToRGB(t,_,o){return o<0&&(o+=6),o>=6&&(o-=6),o<1?(_-t)*o+t:o<3?_:o<4?(_-t)*(4-o)+t:t},lin_2020:lin_2020,lin_2020_to_XYZ:lin_2020_to_XYZ,lin_P3:lin_P3,lin_P3_to_XYZ:lin_P3_to_XYZ,lin_ProPhoto:lin_ProPhoto,lin_ProPhoto_to_XYZ:lin_ProPhoto_to_XYZ,lin_a98rgb:lin_a98rgb,lin_a98rgb_to_XYZ:lin_a98rgb_to_XYZ,lin_sRGB:lin_sRGB,lin_sRGB_to_XYZ:lin_sRGB_to_XYZ,naive_CMYK_to_sRGB:function naive_CMYK_to_sRGB(t){const _=t[0],o=t[1],n=t[2],r=t[3];return[1-Math.min(1,_*(1-r)+r),1-Math.min(1,o*(1-r)+r),1-Math.min(1,n*(1-r)+r)]},sRGB_to_HSL:sRGB_to_HSL,sRGB_to_HWB:function sRGB_to_HWB(t){const _=sRGB_to_HSL(t),o=Math.min(t[0],t[1],t[2]),n=1-Math.max(t[0],t[1],t[2]);return[_[0],100*o,100*n]},sRGB_to_luminance:sRGB_to_luminance});var a=Object.freeze({__proto__:null,HSL_to_XYZ_D50:function HSL_to_XYZ_D50(t){let _=t;return _=HSL_to_sRGB(_),_=lin_sRGB(_),_=lin_sRGB_to_XYZ(_),_=D65_to_D50(_),_},HWB_to_XYZ_D50:function HWB_to_XYZ_D50(t){let _=t;return _=HWB_to_sRGB(_),_=lin_sRGB(_),_=lin_sRGB_to_XYZ(_),_=D65_to_D50(_),_},LCH_to_XYZ_D50:function LCH_to_XYZ_D50(t){let _=t;return _=LCH_to_Lab(_),_=Lab_to_XYZ(_),_},Lab_to_XYZ_D50:function Lab_to_XYZ_D50(t){let _=t;return _=Lab_to_XYZ(_),_},OKLCH_to_XYZ_D50:function OKLCH_to_XYZ_D50(t){let _=t;return _=OKLCH_to_OKLab(_),_=OKLab_to_XYZ(_),_=D65_to_D50(_),_},OKLab_to_XYZ_D50:function OKLab_to_XYZ_D50(t){let _=t;return _=OKLab_to_XYZ(_),_=D65_to_D50(_),_},P3_to_XYZ_D50:function P3_to_XYZ_D50(t){let _=t;return _=lin_P3(_),_=lin_P3_to_XYZ(_),_=D65_to_D50(_),_},ProPhoto_RGB_to_XYZ_D50:function ProPhoto_RGB_to_XYZ_D50(t){let _=t;return _=lin_ProPhoto(_),_=lin_ProPhoto_to_XYZ(_),_},XYZ_D50_to_HSL:function XYZ_D50_to_HSL(t){let _=t;return _=D50_to_D65(_),_=XYZ_to_lin_sRGB(_),_=gam_sRGB(_),_=sRGB_to_HSL(_),_},XYZ_D50_to_HWB:function XYZ_D50_to_HWB(t){let _=t;_=D50_to_D65(_),_=XYZ_to_lin_sRGB(_);const o=gam_sRGB(_);_=sRGB_to_HSL(o);const n=Math.min(o[0],o[1],o[2]),r=1-Math.max(o[0],o[1],o[2]);return[_[0],100*n,100*r]},XYZ_D50_to_LCH:function XYZ_D50_to_LCH(t){let _=t;return _=XYZ_to_Lab(_),_=Lab_to_LCH(_),_},XYZ_D50_to_Lab:function XYZ_D50_to_Lab(t){let _=t;return _=XYZ_to_Lab(_),_},XYZ_D50_to_OKLCH:function XYZ_D50_to_OKLCH(t){let _=t;return _=D50_to_D65(_),_=XYZ_to_OKLab(_),_=OKLab_to_OKLCH(_),_},XYZ_D50_to_OKLab:function XYZ_D50_to_OKLab(t){let _=t;return _=D50_to_D65(_),_=XYZ_to_OKLab(_),_},XYZ_D50_to_P3:function XYZ_D50_to_P3(t){let _=t;return _=D50_to_D65(_),_=XYZ_to_lin_P3(_),_=gam_P3(_),_},XYZ_D50_to_ProPhoto:function XYZ_D50_to_ProPhoto(t){let _=t;return _=XYZ_to_lin_ProPhoto(_),_=gam_ProPhoto(_),_},XYZ_D50_to_XYZ_D50:function XYZ_D50_to_XYZ_D50(t){return t},XYZ_D50_to_XYZ_D65:function XYZ_D50_to_XYZ_D65(t){let _=t;return _=D50_to_D65(_),_},XYZ_D50_to_a98_RGB:function XYZ_D50_to_a98_RGB(t){let _=t;return _=D50_to_D65(_),_=XYZ_to_lin_a98rgb(_),_=gam_a98rgb(_),_},XYZ_D50_to_lin_sRGB:function XYZ_D50_to_lin_sRGB(t){let _=t;return _=D50_to_D65(_),_=XYZ_to_lin_sRGB(_),_},XYZ_D50_to_rec_2020:function XYZ_D50_to_rec_2020(t){let _=t;return _=D50_to_D65(_),_=XYZ_to_lin_2020(_),_=gam_2020(_),_},XYZ_D50_to_sRGB:function XYZ_D50_to_sRGB(t){let _=t;return _=D50_to_D65(_),_=XYZ_to_lin_sRGB(_),_=gam_sRGB(_),_},XYZ_D65_to_XYZ_D50:function XYZ_D65_to_XYZ_D50(t){let _=t;return _=D65_to_D50(_),_},a98_RGB_to_XYZ_D50:function a98_RGB_to_XYZ_D50(t){let _=t;return _=lin_a98rgb(_),_=lin_a98rgb_to_XYZ(_),_=D65_to_D50(_),_},lin_sRGB_to_XYZ_D50:function lin_sRGB_to_XYZ_D50(t){let _=t;return _=lin_sRGB_to_XYZ(_),_=D65_to_D50(_),_},rec_2020_to_XYZ_D50:function rec_2020_to_XYZ_D50(t){let _=t;return _=lin_2020(_),_=lin_2020_to_XYZ(_),_=D65_to_D50(_),_},sRGB_to_XYZ_D50:function sRGB_to_XYZ_D50(t){let _=t;return _=lin_sRGB(_),_=lin_sRGB_to_XYZ(_),_=D65_to_D50(_),_}});const i={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]};export{n as calculations,e as conversions,i as namedColors,t as utils,a as 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/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,_){const[n,o,e]=t,[r,a,i]=_,l=n-r,u=o-a,c=e-i;return Math.sqrt(l**2+u**2+c**2)}const _=.02,n=1e-5;function binarySearchGamut(t,o,e){const r=t;let a=0,i=r[1];for(;i-a>n;){const t=(a+i)/2;r[1]=t;const n=o(r);if(inGamut(n)){a=t;continue}const l=clip(n);if(deltaEOK(OKLCH_to_OKLab(e(l)),OKLCH_to_OKLab(r))<_)return l;i=t}return clip(o([...r]))}function mapGamut(t,_,n){return binarySearchGamut(t,_,n)}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]};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,gam_P3,gam_sRGB,inGamut,lin_P3,lin_P3_to_XYZ,lin_sRGB,lin_sRGB_to_XYZ,lin_sRGB_to_XYZ_D50,mapGamut,o as namedColors,rec_2020_to_XYZ_D50,sRGB_to_XYZ_D50}; diff --git a/packages/color-helpers/dist/named-colors/index.d.ts b/packages/color-helpers/dist/named-colors/index.d.ts deleted file mode 100644 index ea04dd4db..000000000 --- a/packages/color-helpers/dist/named-colors/index.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import type { Color } from '../types/color'; -export declare const namedColors: Record; diff --git a/packages/color-helpers/dist/types/color.d.ts b/packages/color-helpers/dist/types/color.d.ts deleted file mode 100644 index 4d390a28c..000000000 --- a/packages/color-helpers/dist/types/color.d.ts +++ /dev/null @@ -1 +0,0 @@ -export type Color = [number, number, number]; diff --git a/packages/color-helpers/dist/utils/clip.d.ts b/packages/color-helpers/dist/utils/clip.d.ts deleted file mode 100644 index f5c617086..000000000 --- a/packages/color-helpers/dist/utils/clip.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -import type { Color } from '../types/color'; -/** - * @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/map-gamut.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). - */ -export declare function clip(color: Color): Color; diff --git a/packages/color-helpers/dist/utils/in-gamut.d.ts b/packages/color-helpers/dist/utils/in-gamut.d.ts deleted file mode 100644 index 7dd55becc..000000000 --- a/packages/color-helpers/dist/utils/in-gamut.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -import type { Color } from '../types/color'; -/** - * @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/map-gamut.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). - */ -export declare function inGamut(x: Color): boolean; diff --git a/packages/color-helpers/dist/utils/index.d.ts b/packages/color-helpers/dist/utils/index.d.ts deleted file mode 100644 index b73e4598c..000000000 --- a/packages/color-helpers/dist/utils/index.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -export * from './clip'; -export * from './in-gamut'; diff --git a/packages/color-helpers/package.json b/packages/color-helpers/package.json index 7d18aaa3c..3bcd284d8 100644 --- a/packages/color-helpers/package.json +++ b/packages/color-helpers/package.json @@ -27,15 +27,18 @@ "engines": { "node": "^14 || ^16 || >=18" }, + "type": "module", "main": "dist/index.cjs", "module": "dist/index.mjs", - "types": "dist/index.d.ts", "exports": { ".": { - "types": "./dist/index.d.ts", - "import": "./dist/index.mjs", - "require": "./dist/index.cjs", - "default": "./dist/index.mjs" + "import": { + "types": "./dist/index.d.ts", + "default": "./dist/index.mjs" + }, + "require": { + "default": "./dist/index.cjs" + } } }, "files": [ diff --git a/packages/color-helpers/src/calculations/binary-search-gamut.ts b/packages/color-helpers/src/calculations/binary-search-gamut.ts index def3d35bd..f1dbc2946 100644 --- a/packages/color-helpers/src/calculations/binary-search-gamut.ts +++ b/packages/color-helpers/src/calculations/binary-search-gamut.ts @@ -2,7 +2,7 @@ import { clip } from '../utils/clip'; import { OKLCH_to_OKLab } from '../conversions/oklch-to-oklab'; import { deltaEOK } from './delta-EOK'; import type { Color } from '../types/color'; -import { inGamut } from '../utils'; +import { inGamut } from '../utils/in-gamut'; const JND = 0.02; const EPSILON = 0.00001; diff --git a/packages/color-helpers/src/calculations/contrast.ts b/packages/color-helpers/src/calculations/contrast.ts deleted file mode 100644 index 30ba3b109..000000000 --- a/packages/color-helpers/src/calculations/contrast.ts +++ /dev/null @@ -1,24 +0,0 @@ -/** - * Return WCAG 2.1 contrast ratio for two sRGB values given as arrays - * - * of 0.0 to 1.0 - * @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/utilities.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). - * - * @see https://github.com/w3c/csswg-drafts/blob/main/css-color-4/utilities.js - * @see https://www.w3.org/TR/WCAG21/#dfn-contrast-ratio - */ -import { sRGB_to_luminance } from '../conversions/srgb-to-luminance'; -import type { Color } from '../types/color'; - -export function contrast(RGB1: Color, RGB2: Color): number { - const L1 = sRGB_to_luminance(RGB1); - const L2 = sRGB_to_luminance(RGB2); - - if (L1 > L2) { - return (L1 + 0.05) / (L2 + 0.05); - } - - return (L2 + 0.05) / (L1 + 0.05); -} diff --git a/packages/color-helpers/src/calculations/delta-EOK.ts b/packages/color-helpers/src/calculations/delta-EOK.ts index b39bb8e41..698dc1709 100644 --- a/packages/color-helpers/src/calculations/delta-EOK.ts +++ b/packages/color-helpers/src/calculations/delta-EOK.ts @@ -7,9 +7,7 @@ import type { Color } from '../types/color'; * @return {number} How different a color sample is from reference * * @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 */ export function deltaEOK(reference: Color, sample: Color): number { diff --git a/packages/color-helpers/src/calculations/index.ts b/packages/color-helpers/src/calculations/index.ts deleted file mode 100644 index 86e5f3579..000000000 --- a/packages/color-helpers/src/calculations/index.ts +++ /dev/null @@ -1,5 +0,0 @@ -export * from './binary-search-gamut'; -export * from './map-gamut'; -export * from './delta-EOK'; -export * from './contrast'; -export * from './multiply-matrices'; diff --git a/packages/color-helpers/src/calculations/multiply-matrices.ts b/packages/color-helpers/src/calculations/multiply-matrices.ts index 055e4b002..318c7177e 100644 --- a/packages/color-helpers/src/calculations/multiply-matrices.ts +++ b/packages/color-helpers/src/calculations/multiply-matrices.ts @@ -4,9 +4,7 @@ * @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. diff --git a/packages/color-helpers/src/conversions/constants.ts b/packages/color-helpers/src/conversions/constants.ts index 04b1a4cbe..798729416 100644 --- a/packages/color-helpers/src/conversions/constants.ts +++ b/packages/color-helpers/src/conversions/constants.ts @@ -1,3 +1,2 @@ // standard white points, defined by 4-figure CIE x,y chromaticities export const D50 = [0.3457 / 0.3585, 1.00000, (1.0 - 0.3457 - 0.3585) / 0.3585]; -export const D65 = [0.3127 / 0.3290, 1.00000, (1.0 - 0.3127 - 0.3290) / 0.3290]; diff --git a/packages/color-helpers/src/conversions/d50-to-d65.ts b/packages/color-helpers/src/conversions/d50-to-d65.ts index 7009a76e4..23eb69d5b 100644 --- a/packages/color-helpers/src/conversions/d50-to-d65.ts +++ b/packages/color-helpers/src/conversions/d50-to-d65.ts @@ -5,7 +5,6 @@ import { multiplyMatrices } from '../calculations/multiply-matrices'; * 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). */ export function D50_to_D65(XYZ: Color): Color { diff --git a/packages/color-helpers/src/conversions/d65-to-d50.ts b/packages/color-helpers/src/conversions/d65-to-d50.ts index 8dc17c34a..f8665d797 100644 --- a/packages/color-helpers/src/conversions/d65-to-d50.ts +++ b/packages/color-helpers/src/conversions/d65-to-d50.ts @@ -4,9 +4,7 @@ import { multiplyMatrices } from '../calculations/multiply-matrices'; /** * 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 */ export function D65_to_D50(XYZ: Color): Color { diff --git a/packages/color-helpers/src/conversions/gam-2020.ts b/packages/color-helpers/src/conversions/gam-2020.ts index 727f2dfe8..b896c5dd0 100644 --- a/packages/color-helpers/src/conversions/gam-2020.ts +++ b/packages/color-helpers/src/conversions/gam-2020.ts @@ -5,7 +5,6 @@ import type { Color } from '../types/color'; * to gamma corrected form ITU-R BT.2020-2 p.4 * * @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 gam_2020(RGB: Color): Color { diff --git a/packages/color-helpers/src/conversions/gam-a98rgb.ts b/packages/color-helpers/src/conversions/gam-a98rgb.ts index 07da031e7..76acfb1df 100644 --- a/packages/color-helpers/src/conversions/gam-a98rgb.ts +++ b/packages/color-helpers/src/conversions/gam-a98rgb.ts @@ -5,7 +5,6 @@ import type { Color } from '../types/color'; * to gamma corrected form. Negative values are also now accepted * * @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 gam_a98rgb(RGB: Color): Color { diff --git a/packages/color-helpers/src/conversions/gam-p3.ts b/packages/color-helpers/src/conversions/gam-p3.ts index 0cc8815e5..bb055f311 100644 --- a/packages/color-helpers/src/conversions/gam-p3.ts +++ b/packages/color-helpers/src/conversions/gam-p3.ts @@ -6,7 +6,6 @@ import { gam_sRGB } from '../conversions/gam-srgb'; * to gamma corrected form * * @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 gam_P3(RGB: Color): Color { diff --git a/packages/color-helpers/src/conversions/gam-pro-photo.ts b/packages/color-helpers/src/conversions/gam-pro-photo.ts index 0e8fba05e..cf0329f5f 100644 --- a/packages/color-helpers/src/conversions/gam-pro-photo.ts +++ b/packages/color-helpers/src/conversions/gam-pro-photo.ts @@ -6,7 +6,6 @@ import type { Color } from '../types/color'; * Transfer curve is gamma 1.8 with a small linear portion. * * @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 gam_ProPhoto(RGB: Color): Color { @@ -23,5 +22,3 @@ export function gam_ProPhoto(RGB: Color): Color { return 16 * val; }) as Color; } - -export function foo() { } diff --git a/packages/color-helpers/src/conversions/gam-srgb.ts b/packages/color-helpers/src/conversions/gam-srgb.ts index 44054720d..68d6261d5 100644 --- a/packages/color-helpers/src/conversions/gam-srgb.ts +++ b/packages/color-helpers/src/conversions/gam-srgb.ts @@ -7,9 +7,7 @@ import type { Color } from '../types/color'; * of axis, then uses reflected pow below that * * @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://en.wikipedia.org/wiki/SRGB */ export function gam_sRGB(RGB: Color): Color { diff --git a/packages/color-helpers/src/conversions/hsl-to-srgb.ts b/packages/color-helpers/src/conversions/hsl-to-srgb.ts index cbb6e0c37..8e09a1988 100644 --- a/packages/color-helpers/src/conversions/hsl-to-srgb.ts +++ b/packages/color-helpers/src/conversions/hsl-to-srgb.ts @@ -7,9 +7,7 @@ import type { Color } from '../types/color'; * @return {number[]} Array of RGB components 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/hslToRgb.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). - * * @see https://github.com/w3c/csswg-drafts/blob/main/css-color-4/hslToRgb.js */ export function HSL_to_sRGB(HSL: Color): Color { diff --git a/packages/color-helpers/src/conversions/hue-to-rgb.ts b/packages/color-helpers/src/conversions/hue-to-rgb.ts deleted file mode 100644 index b1cc563d3..000000000 --- a/packages/color-helpers/src/conversions/hue-to-rgb.ts +++ /dev/null @@ -1,25 +0,0 @@ -/** - * @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/utilities.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). - * - * @see https://github.com/w3c/csswg-drafts/blob/main/css-color-4/utilities.js - */ -export function hueToRGB(t1: number, t2: number, hue: number): number { - if (hue < 0) { - hue += 6; - } - if (hue >= 6) { - hue -= 6; - } - - if (hue < 1) { - return (t2 - t1) * hue + t1; - } else if (hue < 3) { - return t2; - } else if (hue < 4) { - return (t2 - t1) * (4 - hue) + t1; - } else { - return t1; - } -} diff --git a/packages/color-helpers/src/conversions/hwb-to-srgb.ts b/packages/color-helpers/src/conversions/hwb-to-srgb.ts index ff551cc46..01194e526 100644 --- a/packages/color-helpers/src/conversions/hwb-to-srgb.ts +++ b/packages/color-helpers/src/conversions/hwb-to-srgb.ts @@ -8,9 +8,7 @@ import { HSL_to_sRGB } from './hsl-to-srgb'; * @return {number[]} Array of RGB components 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/hwbToRgb.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). - * * @see https://github.com/w3c/csswg-drafts/blob/main/css-color-4/hwbToRgb.js */ export function HWB_to_sRGB(HWB: Color): Color { diff --git a/packages/color-helpers/src/conversions/index.ts b/packages/color-helpers/src/conversions/index.ts deleted file mode 100644 index 9a2ed427c..000000000 --- a/packages/color-helpers/src/conversions/index.ts +++ /dev/null @@ -1,40 +0,0 @@ -export * from './constants'; -export * from './d50-to-d65'; -export * from './d65-to-d50'; -export * from './gam-2020'; -export * from './gam-a98rgb'; -export * from './gam-p3'; -export * from './gam-pro-photo'; -export * from './gam-srgb'; -export * from './hsl-to-srgb'; -export * from './hue-to-rgb'; -export * from './hwb-to-srgb'; -export * from './lab-to-lch'; -export * from './lab-to-xyz'; -export * from './lch-to-lab'; -export * from './lin-2020'; -export * from './lin-2020-to-xyz'; -export * from './lin-a98rgb'; -export * from './lin-a98rgb-to-xyz'; -export * from './lin-p3'; -export * from './lin-p3-to-xyz'; -export * from './lin-pro-photo'; -export * from './lin-pro-photo-to-xyz'; -export * from './lin-srgb'; -export * from './lin-srgb-to-xyz'; -export * from './naive-cmyk-to-srgb'; -export * from './oklab-to-oklch'; -export * from './oklab-to-xyz'; -export * from './oklch-to-oklab'; -export * from './srgb-to-hsl'; -export * from './srgb-to-hwb'; -export * from './srgb-to-luminance'; -export * from './xyz-to-lab'; -export * from './xyz-to-lin-2020'; -export * from './xyz-to-lin-a98rgb'; -export * from './xyz-to-lin-p3'; -export * from './xyz-to-lin-pro-photo'; -export * from './xyz-to-lin-srgb'; -export * from './xyz-to-oklab'; -export * from './xyz-to-uv'; -export * from './xyz-to-xy'; diff --git a/packages/color-helpers/src/conversions/lab-to-lch.ts b/packages/color-helpers/src/conversions/lab-to-lch.ts index 5a3f9b470..a750ecfba 100644 --- a/packages/color-helpers/src/conversions/lab-to-lch.ts +++ b/packages/color-helpers/src/conversions/lab-to-lch.ts @@ -2,7 +2,6 @@ import type { Color } from '../types/color'; /** * @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 Lab_to_LCH(Lab: Color): Color { diff --git a/packages/color-helpers/src/conversions/lab-to-xyz.ts b/packages/color-helpers/src/conversions/lab-to-xyz.ts index 76e0d498b..13b584979 100644 --- a/packages/color-helpers/src/conversions/lab-to-xyz.ts +++ b/packages/color-helpers/src/conversions/lab-to-xyz.ts @@ -1,15 +1,12 @@ import type { Color } from '../types/color'; +import { D50 } from '../conversions/constants'; /** * 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 */ -import { D50 } from '../conversions/constants'; - export function Lab_to_XYZ(Lab: Color): Color { const κ = 24389 / 27; // 29^3/3^3 const ε = 216 / 24389; // 6^3/29^3 diff --git a/packages/color-helpers/src/conversions/lch-to-lab.ts b/packages/color-helpers/src/conversions/lch-to-lab.ts index f9de135d4..4f98b7011 100644 --- a/packages/color-helpers/src/conversions/lch-to-lab.ts +++ b/packages/color-helpers/src/conversions/lch-to-lab.ts @@ -2,7 +2,6 @@ import type { Color } from '../types/color'; /** * @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 LCH_to_Lab(LCH: Color): Color { 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 72733b7ea..177e8d78d 100644 --- a/packages/color-helpers/src/conversions/lin-2020-to-xyz.ts +++ b/packages/color-helpers/src/conversions/lin-2020-to-xyz.ts @@ -6,9 +6,7 @@ import { multiplyMatrices } from '../calculations/multiply-matrices'; * using 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). - * * @see http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html */ export function lin_2020_to_XYZ(rgb: Color): Color { diff --git a/packages/color-helpers/src/conversions/lin-2020.ts b/packages/color-helpers/src/conversions/lin-2020.ts index 30fb2c4d6..6d97b5b8f 100644 --- a/packages/color-helpers/src/conversions/lin-2020.ts +++ b/packages/color-helpers/src/conversions/lin-2020.ts @@ -6,7 +6,6 @@ import type { Color } from '../types/color'; * ITU-R BT.2020-2 p.4 * * @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 lin_2020(RGB: Color): Color { 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 7df6036f2..c7cbd5940 100644 --- a/packages/color-helpers/src/conversions/lin-a98rgb-to-xyz.ts +++ b/packages/color-helpers/src/conversions/lin-a98rgb-to-xyz.ts @@ -10,9 +10,7 @@ import { multiplyMatrices } from '../calculations/multiply-matrices'; * 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 diff --git a/packages/color-helpers/src/conversions/lin-a98rgb.ts b/packages/color-helpers/src/conversions/lin-a98rgb.ts index a34f71b00..c19a5a4c8 100644 --- a/packages/color-helpers/src/conversions/lin-a98rgb.ts +++ b/packages/color-helpers/src/conversions/lin-a98rgb.ts @@ -5,7 +5,6 @@ import type { Color } from '../types/color'; * to linear light (un-companded) form. Negative values are also now accepted * * @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 lin_a98rgb(RGB: Color): Color { 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 a9f5864e2..b2b660511 100644 --- a/packages/color-helpers/src/conversions/lin-p3-to-xyz.ts +++ b/packages/color-helpers/src/conversions/lin-p3-to-xyz.ts @@ -6,9 +6,7 @@ import { multiplyMatrices } from '../calculations/multiply-matrices'; * using 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). - * * @see http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html */ export function lin_P3_to_XYZ(rgb: Color): Color { diff --git a/packages/color-helpers/src/conversions/lin-p3.ts b/packages/color-helpers/src/conversions/lin-p3.ts index e8b616fc9..8c663537d 100644 --- a/packages/color-helpers/src/conversions/lin-p3.ts +++ b/packages/color-helpers/src/conversions/lin-p3.ts @@ -6,7 +6,6 @@ import { lin_sRGB } from '../conversions/lin-srgb'; * to linear light (un-companded) form. * * @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 lin_P3(RGB: Color): Color { 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 b1ca8f8f6..687ed98ed 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 @@ -6,9 +6,7 @@ import { multiplyMatrices } from '../calculations/multiply-matrices'; * using D50 (so no chromatic adaptation needed afterwards) * * @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 */ export function lin_ProPhoto_to_XYZ(rgb: Color): Color { diff --git a/packages/color-helpers/src/conversions/lin-pro-photo.ts b/packages/color-helpers/src/conversions/lin-pro-photo.ts index 2a8dd4f01..9ecf05d1f 100644 --- a/packages/color-helpers/src/conversions/lin-pro-photo.ts +++ b/packages/color-helpers/src/conversions/lin-pro-photo.ts @@ -6,7 +6,6 @@ import type { Color } from '../types/color'; * gamma 1.8 with a small linear portion. Extended transfer function * * @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 lin_ProPhoto(RGB: Color): Color { 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 dfff66c01..2e8988303 100644 --- a/packages/color-helpers/src/conversions/lin-srgb-to-xyz.ts +++ b/packages/color-helpers/src/conversions/lin-srgb-to-xyz.ts @@ -6,7 +6,6 @@ import { multiplyMatrices } from '../calculations/multiply-matrices'; * 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). */ export function lin_sRGB_to_XYZ(rgb: Color): Color { diff --git a/packages/color-helpers/src/conversions/lin-srgb.ts b/packages/color-helpers/src/conversions/lin-srgb.ts index 2f658f02b..ccb5d5f44 100644 --- a/packages/color-helpers/src/conversions/lin-srgb.ts +++ b/packages/color-helpers/src/conversions/lin-srgb.ts @@ -8,9 +8,7 @@ import type { Color } from '../types/color'; * then reflected power function is used. * * @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://en.wikipedia.org/wiki/SRGB */ export function lin_sRGB(RGB: Color): Color { diff --git a/packages/color-helpers/src/conversions/naive-cmyk-to-srgb.ts b/packages/color-helpers/src/conversions/naive-cmyk-to-srgb.ts deleted file mode 100644 index 1c7c02af1..000000000 --- a/packages/color-helpers/src/conversions/naive-cmyk-to-srgb.ts +++ /dev/null @@ -1,23 +0,0 @@ -import type { Color } from '../types/color'; - -/** - * CMYK is an array of four values in the range [0.0, 1.0] the output is an - * array of [RGB] also in the [0.0, 1.0] range because the naive algorithm - * does not generate out of gamut colors neither does it generate accurate - * simulations of practical CMYK colors - * - * @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/utilities.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). - * - * @see https://github.com/w3c/csswg-drafts/blob/main/css-color-4/utilities.js - */ -export function naive_CMYK_to_sRGB(CMYK: [number, number, number, number]): Color { - const cyan = CMYK[0], magenta = CMYK[1], yellow = CMYK[2], black = CMYK[3]; - - const red = 1 - Math.min(1, cyan * (1 - black) + black); - const green = 1 - Math.min(1, magenta * (1 - black) + black); - const blue = 1 - Math.min(1, yellow * (1 - black) + black); - - return [red, green, blue]; -} diff --git a/packages/color-helpers/src/conversions/oklab-to-oklch.ts b/packages/color-helpers/src/conversions/oklab-to-oklch.ts index 642a5f4ce..536add344 100644 --- a/packages/color-helpers/src/conversions/oklab-to-oklch.ts +++ b/packages/color-helpers/src/conversions/oklab-to-oklch.ts @@ -2,9 +2,7 @@ import type { Color } from '../types/color'; /** * @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 */ export function OKLab_to_OKLCH(OKLab: Color): Color { diff --git a/packages/color-helpers/src/conversions/oklab-to-xyz.ts b/packages/color-helpers/src/conversions/oklab-to-xyz.ts index a5370725a..20e5ede78 100644 --- a/packages/color-helpers/src/conversions/oklab-to-xyz.ts +++ b/packages/color-helpers/src/conversions/oklab-to-xyz.ts @@ -1,16 +1,13 @@ import type { Color } from '../types/color'; +import { multiplyMatrices } from '../calculations/multiply-matrices'; /** * 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 */ -import { multiplyMatrices } from '../calculations/multiply-matrices'; - export function OKLab_to_XYZ(OKLab: Color): Color { const LMStoXYZ = [ [1.2268798758459243, -0.5578149944602171, 0.2813910456659647], diff --git a/packages/color-helpers/src/conversions/oklch-to-oklab.ts b/packages/color-helpers/src/conversions/oklch-to-oklab.ts index 5a043e877..0d1fb5128 100644 --- a/packages/color-helpers/src/conversions/oklch-to-oklab.ts +++ b/packages/color-helpers/src/conversions/oklch-to-oklab.ts @@ -2,9 +2,7 @@ import type { Color } from '../types/color'; /** * @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 */ diff --git a/packages/color-helpers/src/conversions/srgb-to-hwb.ts b/packages/color-helpers/src/conversions/srgb-to-hwb.ts deleted file mode 100644 index cfcfedfa6..000000000 --- a/packages/color-helpers/src/conversions/srgb-to-hwb.ts +++ /dev/null @@ -1,19 +0,0 @@ -import type { Color } from '../types/color'; -import { sRGB_to_HSL } from './srgb-to-hsl'; - -/** - * Convert an array of gamma-corrected sRGB values in the 0.0 to 1.0 range to HWB. - * - * @param {Color} RGB [r, g, b] - * - Red component 0..1 - * - Green component 0..1 - * - Blue component 0..1 - * @return {number[]} Array of HWB values - */ -export function sRGB_to_HWB(RGB: Color): Color { - const y = sRGB_to_HSL(RGB); - - const white = Math.min(RGB[0], RGB[1], RGB[2]); - const black = 1 - Math.max(RGB[0], RGB[1], RGB[2]); - return ([y[0], white * 100, black * 100]); -} diff --git a/packages/color-helpers/src/conversions/srgb-to-luminance.ts b/packages/color-helpers/src/conversions/srgb-to-luminance.ts deleted file mode 100644 index dddee8340..000000000 --- a/packages/color-helpers/src/conversions/srgb-to-luminance.ts +++ /dev/null @@ -1,18 +0,0 @@ -import type { Color } from '../types/color'; -import { lin_sRGB } from '../conversions/lin-srgb'; -import { lin_sRGB_to_XYZ } from '../conversions/lin-srgb-to-xyz'; - -/** - * Convert an array of gamma-corrected sRGB values in the 0.0 to 1.0 range - * to linear-light sRGB, then to CIE XYZ and return luminance (the Y value) - * - * @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/utilities.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). - * - * @see https://github.com/w3c/csswg-drafts/blob/main/css-color-4/utilities.js - */ -export function sRGB_to_luminance(RGB: Color): number { - const XYZ = lin_sRGB_to_XYZ(lin_sRGB(RGB)); - return XYZ[1]; -} diff --git a/packages/color-helpers/src/conversions/xyz-to-lab.ts b/packages/color-helpers/src/conversions/xyz-to-lab.ts index c38e514df..531de3946 100644 --- a/packages/color-helpers/src/conversions/xyz-to-lab.ts +++ b/packages/color-helpers/src/conversions/xyz-to-lab.ts @@ -1,15 +1,13 @@ import type { Color } from '../types/color'; +import { D50 } from '../conversions/constants'; /** * Assuming XYZ is relative to D50, convert to CIE Lab * from CIE standard, which now defines these as a rational fraction * * @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). */ -import { D50 } from '../conversions/constants'; - export function XYZ_to_Lab(XYZ: Color): Color { const ε = 216 / 24389; // 6^3/29^3 const κ = 24389 / 27; // 29^3/3^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 99a8bb3a9..04280e07c 100644 --- a/packages/color-helpers/src/conversions/xyz-to-lin-2020.ts +++ b/packages/color-helpers/src/conversions/xyz-to-lin-2020.ts @@ -5,7 +5,6 @@ import { multiplyMatrices } from '../calculations/multiply-matrices'; * 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). */ export function XYZ_to_lin_2020(XYZ: Color): Color { 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 120d8dd28..4d504bd44 100644 --- a/packages/color-helpers/src/conversions/xyz-to-lin-a98rgb.ts +++ b/packages/color-helpers/src/conversions/xyz-to-lin-a98rgb.ts @@ -5,7 +5,6 @@ import { multiplyMatrices } from '../calculations/multiply-matrices'; * 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). */ export function XYZ_to_lin_a98rgb(XYZ: Color): Color { 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 4056b7e27..20024744d 100644 --- a/packages/color-helpers/src/conversions/xyz-to-lin-p3.ts +++ b/packages/color-helpers/src/conversions/xyz-to-lin-p3.ts @@ -5,7 +5,6 @@ import { multiplyMatrices } from '../calculations/multiply-matrices'; * 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). */ export function XYZ_to_lin_P3(XYZ: Color): Color { 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 8adad22fc..d3430b2a0 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 @@ -5,9 +5,7 @@ import { multiplyMatrices } from '../calculations/multiply-matrices'; * Convert XYZ to linear-light prophoto-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). - * * @see http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html */ export function XYZ_to_lin_ProPhoto(XYZ: Color): Color { 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 ae382bca1..8a2e1f609 100644 --- a/packages/color-helpers/src/conversions/xyz-to-lin-srgb.ts +++ b/packages/color-helpers/src/conversions/xyz-to-lin-srgb.ts @@ -3,7 +3,6 @@ import { multiplyMatrices } from '../calculations/multiply-matrices'; /** * @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 { diff --git a/packages/color-helpers/src/conversions/xyz-to-oklab.ts b/packages/color-helpers/src/conversions/xyz-to-oklab.ts index b4f33a8da..5611bbd61 100644 --- a/packages/color-helpers/src/conversions/xyz-to-oklab.ts +++ b/packages/color-helpers/src/conversions/xyz-to-oklab.ts @@ -3,7 +3,6 @@ import { multiplyMatrices } from '../calculations/multiply-matrices'; /** * @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 diff --git a/packages/color-helpers/src/conversions/xyz-to-uv.ts b/packages/color-helpers/src/conversions/xyz-to-uv.ts deleted file mode 100644 index cf1f86f11..000000000 --- a/packages/color-helpers/src/conversions/xyz-to-uv.ts +++ /dev/null @@ -1,18 +0,0 @@ -import type { Color } from '../types/color'; - -/** - * Convert an array of three XYZ values to u*,v* chromaticity coordinates - * - * @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/utilities.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). - * - * @see https://github.com/w3c/csswg-drafts/blob/main/css-color-4/utilities.js - */ -export function XYZ_to_uv(XYZ: Color): [number, number] { - const X = XYZ[0]; - const Y = XYZ[1]; - const Z = XYZ[2]; - const denom = X + 15 * Y + 3 * Z; - return [4 * X / denom, 9 * Y / denom]; -} diff --git a/packages/color-helpers/src/conversions/xyz-to-xy.ts b/packages/color-helpers/src/conversions/xyz-to-xy.ts deleted file mode 100644 index 633bfe0b0..000000000 --- a/packages/color-helpers/src/conversions/xyz-to-xy.ts +++ /dev/null @@ -1,18 +0,0 @@ -import type { Color } from '../types/color'; - -/** - * Convert an array of three XYZ values to x,y chromaticity coordinates - * - * @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/utilities.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). - * - * @see https://github.com/w3c/csswg-drafts/blob/main/css-color-4/utilities.js - */ -export function XYZ_to_xy(XYZ: Color): [number, number] { - const X = XYZ[0]; - const Y = XYZ[1]; - const Z = XYZ[2]; - const sum = X + Y + Z; - return [X / sum, Y / sum]; -} diff --git a/packages/color-helpers/src/index.ts b/packages/color-helpers/src/index.ts index 15af8c666..0321b3079 100644 --- a/packages/color-helpers/src/index.ts +++ b/packages/color-helpers/src/index.ts @@ -1,6 +1,50 @@ -export * as calculations from './calculations'; -export * as conversions from './conversions'; -export * as utils from './utils'; -export * as xyz from './conversions/xyz'; +export { + sRGB_to_XYZ_D50, + XYZ_D50_to_sRGB, + HSL_to_XYZ_D50, + XYZ_D50_to_HSL, + HWB_to_XYZ_D50, + XYZ_D50_to_HWB, + Lab_to_XYZ_D50, + XYZ_D50_to_Lab, + LCH_to_XYZ_D50, + XYZ_D50_to_LCH, + OKLab_to_XYZ_D50, + XYZ_D50_to_OKLab, + OKLCH_to_XYZ_D50, + XYZ_D50_to_OKLCH, + lin_sRGB_to_XYZ_D50, + XYZ_D50_to_lin_sRGB, + a98_RGB_to_XYZ_D50, + XYZ_D50_to_a98_RGB, + P3_to_XYZ_D50, + XYZ_D50_to_P3, + rec_2020_to_XYZ_D50, + XYZ_D50_to_rec_2020, + ProPhoto_RGB_to_XYZ_D50, + XYZ_D50_to_ProPhoto, + XYZ_D65_to_XYZ_D50, + XYZ_D50_to_XYZ_D65, + XYZ_D50_to_XYZ_D50, +} from './conversions/xyz'; + +export { inGamut } from './utils/in-gamut'; +export { clip } from './utils/clip'; + +export { mapGamut } from './calculations/map-gamut'; + +export { OKLCH_to_OKLab } from './conversions/oklch-to-oklab'; +export { OKLab_to_OKLCH } from './conversions/oklab-to-oklch'; +export { OKLab_to_XYZ } from './conversions/oklab-to-xyz'; +export { XYZ_to_OKLab } from './conversions/xyz-to-oklab'; +export { XYZ_to_lin_P3 } from './conversions/xyz-to-lin-p3'; +export { XYZ_to_lin_sRGB } from './conversions/xyz-to-lin-srgb'; +export { gam_P3 } from './conversions/gam-p3'; +export { gam_sRGB } from './conversions/gam-srgb'; +export { lin_P3 } from './conversions/lin-p3'; +export { lin_P3_to_XYZ } from './conversions/lin-p3-to-xyz'; +export { lin_sRGB } from './conversions/lin-srgb'; +export { lin_sRGB_to_XYZ } from './conversions/lin-srgb-to-xyz'; + export type { Color } from './types/color'; export { namedColors } from './named-colors'; diff --git a/packages/color-helpers/src/utils/clip.ts b/packages/color-helpers/src/utils/clip.ts index 0a5c7cd90..f96c131b6 100644 --- a/packages/color-helpers/src/utils/clip.ts +++ b/packages/color-helpers/src/utils/clip.ts @@ -1,10 +1,5 @@ import type { Color } from '../types/color'; -/** - * @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/map-gamut.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). - */ export function clip(color: Color): Color { return color.map(val => { if (val < 0) { diff --git a/packages/color-helpers/src/utils/in-gamut.ts b/packages/color-helpers/src/utils/in-gamut.ts index dff0d3216..a3f49f99e 100644 --- a/packages/color-helpers/src/utils/in-gamut.ts +++ b/packages/color-helpers/src/utils/in-gamut.ts @@ -1,10 +1,5 @@ import type { Color } from '../types/color'; -/** - * @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/map-gamut.js. Copyright © 2022 W3C® (MIT, ERCIM, Keio, Beihang). - */ export function inGamut(x: Color): boolean { const [xX, xY, xZ] = x; return xX >= -0.0001 && xX <= 1.0001 && xY >= -0.0001 && xY <= 1.0001 && xZ >= -0.0001 && xZ <= 1.0001; diff --git a/packages/color-helpers/src/utils/index.ts b/packages/color-helpers/src/utils/index.ts deleted file mode 100644 index b73e4598c..000000000 --- a/packages/color-helpers/src/utils/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -export * from './clip'; -export * from './in-gamut'; diff --git a/packages/color-helpers/test/_import.mjs b/packages/color-helpers/test/_import.mjs index e7d81f6e9..cd1bd0e58 100644 --- a/packages/color-helpers/test/_import.mjs +++ b/packages/color-helpers/test/_import.mjs @@ -1,7 +1,4 @@ import assert from 'assert'; -import { calculations } from '@csstools/color-helpers'; +import { clip } from '@csstools/color-helpers'; -const { deltaEOK } = calculations; - -assert.equal(typeof deltaEOK, 'function', 'should export nested libraries'); -assert.equal(typeof calculations.deltaEOK, 'function', 'should be possible to import from index'); +assert.equal(typeof clip, 'function', 'should export nested libraries'); diff --git a/packages/color-helpers/test/_require.cjs b/packages/color-helpers/test/_require.cjs index 16a9da00a..00aeceec5 100644 --- a/packages/color-helpers/test/_require.cjs +++ b/packages/color-helpers/test/_require.cjs @@ -1,6 +1,4 @@ const assert = require('assert'); -const { deltaEOK } = require('@csstools/color-helpers').calculations; -const { calculations } = require('@csstools/color-helpers'); +const { clip } = require('@csstools/color-helpers'); -assert.equal(typeof deltaEOK, 'function', 'should export nested libraries'); -assert.equal(typeof calculations.deltaEOK, 'function', 'should be possible to import from index'); +assert.equal(typeof clip, 'function', 'should export nested libraries'); diff --git a/packages/css-calc/CHANGELOG.md b/packages/css-calc/CHANGELOG.md index 38be1e77a..788246c3f 100644 --- a/packages/css-calc/CHANGELOG.md +++ b/packages/css-calc/CHANGELOG.md @@ -2,7 +2,7 @@ ### Unreleased (patch) -- Small fixes in type definitions +- Fix type definitions ### 1.1.4 diff --git a/packages/css-calc/api-extractor.json b/packages/css-calc/api-extractor.json new file mode 100644 index 000000000..42058be51 --- /dev/null +++ b/packages/css-calc/api-extractor.json @@ -0,0 +1,4 @@ +{ + "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json", + "extends": "../../api-extractor.json" +} diff --git a/packages/css-calc/dist/calculation.d.ts b/packages/css-calc/dist/calculation.d.ts deleted file mode 100644 index 963a38544..000000000 --- a/packages/css-calc/dist/calculation.d.ts +++ /dev/null @@ -1,8 +0,0 @@ -import type { Operation } from './operation/operation'; -import type { TokenNode } from '@csstools/css-parser-algorithms'; -export type Calculation = { - inputs: Array; - operation: Operation; -}; -export declare function isCalculation(x: unknown): x is Calculation; -export declare function solve(calculation: Calculation | -1): TokenNode | -1; diff --git a/packages/css-calc/dist/functions/abs.d.ts b/packages/css-calc/dist/functions/abs.d.ts deleted file mode 100644 index e8971e3b8..000000000 --- a/packages/css-calc/dist/functions/abs.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -import type { Calculation } from '../calculation'; -import type { FunctionNode, TokenNode } from '@csstools/css-parser-algorithms'; -export declare function solveAbs(absNode: FunctionNode, a: TokenNode): Calculation | -1; diff --git a/packages/css-calc/dist/functions/acos.d.ts b/packages/css-calc/dist/functions/acos.d.ts deleted file mode 100644 index 964f74704..000000000 --- a/packages/css-calc/dist/functions/acos.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -import type { Calculation } from '../calculation'; -import type { FunctionNode, TokenNode } from '@csstools/css-parser-algorithms'; -export declare function solveACos(acosNode: FunctionNode, a: TokenNode): Calculation | -1; diff --git a/packages/css-calc/dist/functions/asin.d.ts b/packages/css-calc/dist/functions/asin.d.ts deleted file mode 100644 index a1465cb7e..000000000 --- a/packages/css-calc/dist/functions/asin.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -import type { Calculation } from '../calculation'; -import type { FunctionNode, TokenNode } from '@csstools/css-parser-algorithms'; -export declare function solveASin(asinNode: FunctionNode, a: TokenNode): Calculation | -1; diff --git a/packages/css-calc/dist/functions/atan.d.ts b/packages/css-calc/dist/functions/atan.d.ts deleted file mode 100644 index f800a7bf4..000000000 --- a/packages/css-calc/dist/functions/atan.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -import type { Calculation } from '../calculation'; -import type { FunctionNode, TokenNode } from '@csstools/css-parser-algorithms'; -export declare function solveATan(atanNode: FunctionNode, a: TokenNode): Calculation | -1; diff --git a/packages/css-calc/dist/functions/atan2.d.ts b/packages/css-calc/dist/functions/atan2.d.ts deleted file mode 100644 index 651308f69..000000000 --- a/packages/css-calc/dist/functions/atan2.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -import type { Calculation } from '../calculation'; -import type { FunctionNode, TokenNode } from '@csstools/css-parser-algorithms'; -export declare function solveATan2(atan2Node: FunctionNode, a: TokenNode, b: TokenNode): Calculation | -1; diff --git a/packages/css-calc/dist/functions/calc.d.ts b/packages/css-calc/dist/functions/calc.d.ts deleted file mode 100644 index 6eabc645c..000000000 --- a/packages/css-calc/dist/functions/calc.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -import type { Calculation } from '../calculation'; -import type { Globals } from '../util/globals'; -import { FunctionNode } from '@csstools/css-parser-algorithms'; -export declare const mathFunctions: Map; -declare function abs(absNode: FunctionNode, globals: Globals): Calculation | -1; -export {}; diff --git a/packages/css-calc/dist/functions/clamp.d.ts b/packages/css-calc/dist/functions/clamp.d.ts deleted file mode 100644 index 19a49c4be..000000000 --- a/packages/css-calc/dist/functions/clamp.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -import type { Calculation } from '../calculation'; -import type { FunctionNode, TokenNode } from '@csstools/css-parser-algorithms'; -export declare function solveClamp(clampNode: FunctionNode, minimum: TokenNode | -1, central: TokenNode | -1, maximum: TokenNode | -1): Calculation | -1; diff --git a/packages/css-calc/dist/functions/cos.d.ts b/packages/css-calc/dist/functions/cos.d.ts deleted file mode 100644 index 74359259b..000000000 --- a/packages/css-calc/dist/functions/cos.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -import type { Calculation } from '../calculation'; -import type { FunctionNode, TokenNode } from '@csstools/css-parser-algorithms'; -export declare function solveCos(cosNode: FunctionNode, a: TokenNode): Calculation | -1; diff --git a/packages/css-calc/dist/functions/exp.d.ts b/packages/css-calc/dist/functions/exp.d.ts deleted file mode 100644 index 0d1a64d9c..000000000 --- a/packages/css-calc/dist/functions/exp.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -import type { Calculation } from '../calculation'; -import type { FunctionNode, TokenNode } from '@csstools/css-parser-algorithms'; -export declare function solveExp(expNode: FunctionNode, a: TokenNode): Calculation | -1; diff --git a/packages/css-calc/dist/functions/globals-and-constants.d.ts b/packages/css-calc/dist/functions/globals-and-constants.d.ts deleted file mode 100644 index d968bd11a..000000000 --- a/packages/css-calc/dist/functions/globals-and-constants.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -import { ComponentValue } from '@csstools/css-parser-algorithms'; -import { Globals } from '../util/globals'; -export declare function resolveGlobalsAndConstants(nodes: Array, globals: Globals): Array; diff --git a/packages/css-calc/dist/functions/hypot.d.ts b/packages/css-calc/dist/functions/hypot.d.ts deleted file mode 100644 index 9d22357fa..000000000 --- a/packages/css-calc/dist/functions/hypot.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -import type { Calculation } from '../calculation'; -import type { ComponentValue, FunctionNode } from '@csstools/css-parser-algorithms'; -export declare function solveHypot(hypotNode: FunctionNode, solvedNodes: Array): Calculation | -1; diff --git a/packages/css-calc/dist/functions/log.d.ts b/packages/css-calc/dist/functions/log.d.ts deleted file mode 100644 index 9ed692936..000000000 --- a/packages/css-calc/dist/functions/log.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -import type { Calculation } from '../calculation'; -import type { ComponentValue, FunctionNode } from '@csstools/css-parser-algorithms'; -export declare function solveLog(logNode: FunctionNode, solvedNodes: Array): Calculation | -1; diff --git a/packages/css-calc/dist/functions/max.d.ts b/packages/css-calc/dist/functions/max.d.ts deleted file mode 100644 index 4181d6e5e..000000000 --- a/packages/css-calc/dist/functions/max.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -import type { Calculation } from '../calculation'; -import type { ComponentValue, FunctionNode } from '@csstools/css-parser-algorithms'; -export declare function solveMax(maxNode: FunctionNode, solvedNodes: Array): Calculation | -1; diff --git a/packages/css-calc/dist/functions/min.d.ts b/packages/css-calc/dist/functions/min.d.ts deleted file mode 100644 index 9f76b07ce..000000000 --- a/packages/css-calc/dist/functions/min.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -import type { Calculation } from '../calculation'; -import type { ComponentValue, FunctionNode } from '@csstools/css-parser-algorithms'; -export declare function solveMin(minNode: FunctionNode, solvedNodes: Array): Calculation | -1; diff --git a/packages/css-calc/dist/functions/mod.d.ts b/packages/css-calc/dist/functions/mod.d.ts deleted file mode 100644 index 0a6172e1f..000000000 --- a/packages/css-calc/dist/functions/mod.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -import type { Calculation } from '../calculation'; -import type { FunctionNode, TokenNode } from '@csstools/css-parser-algorithms'; -export declare function solveMod(modNode: FunctionNode, a: TokenNode, b: TokenNode): Calculation | -1; diff --git a/packages/css-calc/dist/functions/pow.d.ts b/packages/css-calc/dist/functions/pow.d.ts deleted file mode 100644 index 33efc20cd..000000000 --- a/packages/css-calc/dist/functions/pow.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -import type { Calculation } from '../calculation'; -import type { FunctionNode, TokenNode } from '@csstools/css-parser-algorithms'; -export declare function solvePow(powNode: FunctionNode, a: TokenNode, b: TokenNode): Calculation | -1; diff --git a/packages/css-calc/dist/functions/rem.d.ts b/packages/css-calc/dist/functions/rem.d.ts deleted file mode 100644 index ebaacfd1c..000000000 --- a/packages/css-calc/dist/functions/rem.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -import type { Calculation } from '../calculation'; -import type { FunctionNode, TokenNode } from '@csstools/css-parser-algorithms'; -export declare function solveRem(remNode: FunctionNode, a: TokenNode, b: TokenNode): Calculation | -1; diff --git a/packages/css-calc/dist/functions/result-to-calculation.d.ts b/packages/css-calc/dist/functions/result-to-calculation.d.ts deleted file mode 100644 index 82c182f82..000000000 --- a/packages/css-calc/dist/functions/result-to-calculation.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { CSSToken } from '@csstools/css-tokenizer'; -import { FunctionNode } from '@csstools/css-parser-algorithms'; -import { Calculation } from '../calculation'; -export declare function resultToCalculation(node: FunctionNode, aToken: CSSToken, result: number): Calculation | -1; -export declare function dimensionToCalculation(node: FunctionNode, unit: string, result: number): Calculation | -1; -export declare function numberToCalculation(node: FunctionNode, result: number): Calculation | -1; diff --git a/packages/css-calc/dist/functions/round.d.ts b/packages/css-calc/dist/functions/round.d.ts deleted file mode 100644 index 87b8d78f5..000000000 --- a/packages/css-calc/dist/functions/round.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -import type { Calculation } from '../calculation'; -import type { FunctionNode, TokenNode } from '@csstools/css-parser-algorithms'; -export declare function solveRound(roundNode: FunctionNode, roundingStrategy: string, a: TokenNode, b: TokenNode): Calculation | -1; diff --git a/packages/css-calc/dist/functions/sign.d.ts b/packages/css-calc/dist/functions/sign.d.ts deleted file mode 100644 index 391f3b567..000000000 --- a/packages/css-calc/dist/functions/sign.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -import type { Calculation } from '../calculation'; -import type { FunctionNode, TokenNode } from '@csstools/css-parser-algorithms'; -export declare function solveSign(signNode: FunctionNode, a: TokenNode): Calculation | -1; diff --git a/packages/css-calc/dist/functions/sin.d.ts b/packages/css-calc/dist/functions/sin.d.ts deleted file mode 100644 index 9a0f484b0..000000000 --- a/packages/css-calc/dist/functions/sin.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -import type { Calculation } from '../calculation'; -import type { FunctionNode, TokenNode } from '@csstools/css-parser-algorithms'; -export declare function solveSin(sinNode: FunctionNode, a: TokenNode): Calculation | -1; diff --git a/packages/css-calc/dist/functions/sqrt.d.ts b/packages/css-calc/dist/functions/sqrt.d.ts deleted file mode 100644 index a9a43a695..000000000 --- a/packages/css-calc/dist/functions/sqrt.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -import type { Calculation } from '../calculation'; -import type { FunctionNode, TokenNode } from '@csstools/css-parser-algorithms'; -export declare function solveSqrt(sqrtNode: FunctionNode, a: TokenNode): Calculation | -1; diff --git a/packages/css-calc/dist/functions/tan.d.ts b/packages/css-calc/dist/functions/tan.d.ts deleted file mode 100644 index 6294895d6..000000000 --- a/packages/css-calc/dist/functions/tan.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -import type { Calculation } from '../calculation'; -import type { FunctionNode, TokenNode } from '@csstools/css-parser-algorithms'; -export declare function solveTan(tanNode: FunctionNode, a: TokenNode): Calculation | -1; diff --git a/packages/css-calc/dist/index.cjs b/packages/css-calc/dist/index.cjs index a91635300..65d449dcd 100644 --- a/packages/css-calc/dist/index.cjs +++ b/packages/css-calc/dist/index.cjs @@ -1 +1 @@ -"use strict";var e=require("@csstools/css-parser-algorithms"),n=require("@csstools/css-tokenizer");const o=/[A-Z]/g;function toLowerCaseAZ(e){return e.replace(o,(e=>String.fromCharCode(e.charCodeAt(0)+32)))}const t={cm:"px",in:"px",mm:"px",pc:"px",pt:"px",px:"px",q:"px",deg:"deg",grad:"deg",rad:"deg",turn:"deg",ms:"s",s:"s",hz:"hz",khz:"hz"},r=new Map([["cm",e=>e],["mm",e=>10*e],["q",e=>40*e],["in",e=>e/2.54],["pc",e=>e/2.54*6],["pt",e=>e/2.54*72],["px",e=>e/2.54*96]]),u=new Map([["deg",e=>e],["grad",e=>e/.9],["rad",e=>e/180*Math.PI],["turn",e=>e/360]]),i=new Map([["deg",e=>.9*e],["grad",e=>e],["rad",e=>.9*e/180*Math.PI],["turn",e=>.9*e/360]]),a=new Map([["hz",e=>e],["khz",e=>e/1e3]]),l=new Map([["cm",e=>2.54*e],["mm",e=>25.4*e],["q",e=>25.4*e*4],["in",e=>e],["pc",e=>6*e],["pt",e=>72*e],["px",e=>96*e]]),s=new Map([["hz",e=>1e3*e],["khz",e=>e]]),c=new Map([["cm",e=>e/10],["mm",e=>e],["q",e=>4*e],["in",e=>e/25.4],["pc",e=>e/25.4*6],["pt",e=>e/25.4*72],["px",e=>e/25.4*96]]),T=new Map([["ms",e=>e],["s",e=>e/1e3]]),p=new Map([["cm",e=>e/6*2.54],["mm",e=>e/6*25.4],["q",e=>e/6*25.4*4],["in",e=>e/6],["pc",e=>e],["pt",e=>e/6*72],["px",e=>e/6*96]]),v=new Map([["cm",e=>e/72*2.54],["mm",e=>e/72*25.4],["q",e=>e/72*25.4*4],["in",e=>e/72],["pc",e=>e/72*6],["pt",e=>e],["px",e=>e/72*96]]),m=new Map([["cm",e=>e/96*2.54],["mm",e=>e/96*25.4],["q",e=>e/96*25.4*4],["in",e=>e/96],["pc",e=>e/96*6],["pt",e=>e/96*72],["px",e=>e]]),N=new Map([["cm",e=>e/4/10],["mm",e=>e/4],["q",e=>e],["in",e=>e/4/25.4],["pc",e=>e/4/25.4*6],["pt",e=>e/4/25.4*72],["px",e=>e/4/25.4*96]]),f=new Map([["deg",e=>180*e/Math.PI],["grad",e=>180*e/Math.PI/.9],["rad",e=>e],["turn",e=>180*e/Math.PI/360]]),y=new Map([["ms",e=>1e3*e],["s",e=>e]]),k=new Map([["deg",e=>360*e],["grad",e=>360*e/.9],["rad",e=>360*e/180*Math.PI],["turn",e=>e]]),d=new Map([["cm",r],["mm",c],["q",N],["in",l],["pc",p],["pt",v],["px",m],["ms",T],["s",y],["deg",u],["grad",i],["rad",f],["turn",k],["hz",a],["khz",s]]);function convertUnit(e,o){if(e[0]!==n.TokenType.Dimension)return o;if(o[0]!==n.TokenType.Dimension)return o;const t=toLowerCaseAZ(e[4].unit),r=toLowerCaseAZ(o[4].unit);if(t===r)return o;const u=d.get(r);if(!u)return o;const i=u.get(t);if(!i)return o;const a=i(o[4].value);return[n.TokenType.Dimension,a.toString()+e[4].unit,o[2],o[3],{value:a,unit:e[4].unit,type:Number.isInteger(a)?n.NumberType.Integer:n.NumberType.Number}]}function toCanonicalUnit(e){if(e[0]!==n.TokenType.Dimension)return e;const o=toLowerCaseAZ(e[4].unit),r=t[o];if(o===r)return e;const u=d.get(o);if(!u)return e;const i=u.get(r);if(!i)return e;const a=i(e[4].value);return[n.TokenType.Dimension,a.toString()+r,e[2],e[3],{value:a,unit:r,type:Number.isInteger(a)?n.NumberType.Integer:n.NumberType.Number}]}function addition(o){if(2!==o.length)return-1;const t=o[0].value;let r=o[1].value;if(t[0]===n.TokenType.Number&&r[0]===n.TokenType.Number){const o=t[4].value+r[4].value;return new e.TokenNode([n.TokenType.Number,o.toString(),t[2],r[3],{value:o,type:t[4].type===n.NumberType.Integer&&r[4].type===n.NumberType.Integer?n.NumberType.Integer:n.NumberType.Number}])}if(t[0]===n.TokenType.Percentage&&r[0]===n.TokenType.Percentage){const o=t[4].value+r[4].value;return new e.TokenNode([n.TokenType.Percentage,o.toString()+"%",t[2],r[3],{value:o}])}if(t[0]===n.TokenType.Dimension&&r[0]===n.TokenType.Dimension&&(r=convertUnit(t,r),toLowerCaseAZ(t[4].unit)===toLowerCaseAZ(r[4].unit))){const o=t[4].value+r[4].value;return new e.TokenNode([n.TokenType.Dimension,o.toString()+t[4].unit,t[2],r[3],{value:o,type:t[4].type===n.NumberType.Integer&&r[4].type===n.NumberType.Integer?n.NumberType.Integer:n.NumberType.Number,unit:t[4].unit}])}return-1}function division(o){if(2!==o.length)return-1;const t=o[0].value,r=o[1].value;if(t[0]===n.TokenType.Number&&r[0]===n.TokenType.Number){const o=t[4].value/r[4].value;return new e.TokenNode([n.TokenType.Number,o.toString(),t[2],r[3],{value:o,type:Number.isInteger(o)?n.NumberType.Integer:n.NumberType.Number}])}if(t[0]===n.TokenType.Percentage&&r[0]===n.TokenType.Number){const o=t[4].value/r[4].value;return new e.TokenNode([n.TokenType.Percentage,o.toString()+"%",t[2],r[3],{value:o}])}if(t[0]===n.TokenType.Dimension&&r[0]===n.TokenType.Number){const o=t[4].value/r[4].value;return new e.TokenNode([n.TokenType.Dimension,o.toString()+t[4].unit,t[2],r[3],{value:o,type:Number.isInteger(o)?n.NumberType.Integer:n.NumberType.Number,unit:t[4].unit}])}return-1}function isCalculation(e){return!!e&&"object"==typeof e&&"inputs"in e&&Array.isArray(e.inputs)&&"operation"in e}function solve(n){if(-1===n)return-1;const o=[];for(let t=0;te.type))).size)return-1;const r=t.value;if(!isNumeric(r))return-1;const u=o.map((e=>convertUnit(r,e.value)));if(!arrayOfSameNumeric(u))return-1;const i=u.map((e=>e[4].value)),a=Math.hypot(...i);return resultToCalculation(n,r,a)}function solveMax(n,o){const t=o[0];if(!t||!e.isTokenNode(t))return-1;if(1!==new Set(o.map((e=>e.type))).size)return-1;const r=t.value;if(!isNumeric(r))return-1;const u=o.map((e=>convertUnit(r,e.value)));if(!arrayOfSameNumeric(u))return-1;const i=u.map((e=>e[4].value)),a=Math.max(...i);return resultToCalculation(n,r,a)}function solveMin(n,o){const t=o[0];if(!t||!e.isTokenNode(t))return-1;if(1!==new Set(o.map((e=>e.type))).size)return-1;const r=t.value;if(!isNumeric(r))return-1;const u=o.map((e=>convertUnit(r,e.value)));if(!arrayOfSameNumeric(u))return-1;const i=u.map((e=>e[4].value)),a=Math.min(...i);return resultToCalculation(n,r,a)}function solveMod(e,n,o){const t=n.value;if(!isNumeric(t))return-1;const r=convertUnit(t,o.value);if(!twoOfSameNumeric(t,r))return-1;let u;return u=0===r[4].value?Number.NaN:Number.isFinite(t[4].value)&&(Number.isFinite(r[4].value)||(r[4].value!==Number.POSITIVE_INFINITY||t[4].value!==Number.NEGATIVE_INFINITY&&!Object.is(0*t[4].value,-0))&&(r[4].value!==Number.NEGATIVE_INFINITY||t[4].value!==Number.POSITIVE_INFINITY&&!Object.is(0*t[4].value,0)))?Number.isFinite(r[4].value)?(t[4].value%r[4].value+r[4].value)%r[4].value:t[4].value:Number.NaN,resultToCalculation(e,t,u)}function solvePow(e,o,t){const r=o.value,u=t.value;if(r[0]!==n.TokenType.Number)return-1;if(!twoOfSameNumeric(r,u))return-1;return numberToCalculation(e,Math.pow(r[4].value,u[4].value))}function solveRem(e,n,o){const t=n.value;if(!isNumeric(t))return-1;const r=convertUnit(t,o.value);if(!twoOfSameNumeric(t,r))return-1;let u;return u=0===r[4].value?Number.NaN:Number.isFinite(t[4].value)?Number.isFinite(r[4].value)?t[4].value%r[4].value:t[4].value:Number.NaN,resultToCalculation(e,t,u)}function solveRound(e,n,o,t){const r=o.value;if(!isNumeric(r))return-1;const u=convertUnit(r,t.value);if(!twoOfSameNumeric(r,u))return-1;let i;if(0===u[4].value)i=Number.NaN;else if(Number.isFinite(r[4].value)||Number.isFinite(u[4].value))if(!Number.isFinite(r[4].value)&&Number.isFinite(u[4].value))i=r[4].value;else if(Number.isFinite(r[4].value)&&!Number.isFinite(u[4].value))switch(n){case"down":i=r[4].value<0?-1/0:Object.is(-0,0*r[4].value)?-0:0;break;case"up":i=r[4].value>0?1/0:Object.is(0,0*r[4].value)?0:-0;break;default:i=Object.is(0,0*r[4].value)?0:-0}else if(Number.isFinite(u[4].value))switch(n){case"down":i=Math.floor(r[4].value/u[4].value)*u[4].value;break;case"up":i=Math.ceil(r[4].value/u[4].value)*u[4].value;break;case"to-zero":i=Math.trunc(r[4].value/u[4].value)*u[4].value;break;default:{let e=Math.floor(r[4].value/u[4].value)*u[4].value,n=Math.ceil(r[4].value/u[4].value)*u[4].value;if(e>n){const o=e;e=n,n=o}const o=Math.abs(r[4].value-e),t=Math.abs(r[4].value-n);i=o===t?n:o0?1/0:-1/0:Math.tan(l),numberToCalculation(e,l)}function subtraction(o){if(2!==o.length)return-1;const t=o[0].value;let r=o[1].value;if(t[0]===n.TokenType.Number&&r[0]===n.TokenType.Number){const o=t[4].value-r[4].value;return new e.TokenNode([n.TokenType.Number,o.toString(),t[2],r[3],{value:o,type:t[4].type===n.NumberType.Integer&&r[4].type===n.NumberType.Integer?n.NumberType.Integer:n.NumberType.Number}])}if(t[0]===n.TokenType.Percentage&&r[0]===n.TokenType.Percentage){const o=t[4].value-r[4].value;return new e.TokenNode([n.TokenType.Percentage,o.toString()+"%",t[2],r[3],{value:o}])}if(t[0]===n.TokenType.Dimension&&r[0]===n.TokenType.Dimension&&(r=convertUnit(t,r),toLowerCaseAZ(t[4].unit)===toLowerCaseAZ(r[4].unit))){const o=t[4].value-r[4].value;return new e.TokenNode([n.TokenType.Dimension,o.toString()+t[4].unit,t[2],r[3],{value:o,type:t[4].type===n.NumberType.Integer&&r[4].type===n.NumberType.Integer?n.NumberType.Integer:n.NumberType.Number,unit:t[4].unit}])}return-1}function solveLog(o,t){if(1===t.length){const r=t[0];if(!r||!e.isTokenNode(r))return-1;const u=r.value;if(u[0]!==n.TokenType.Number)return-1;return numberToCalculation(o,Math.log(u[4].value))}if(2===t.length){const r=t[0];if(!r||!e.isTokenNode(r))return-1;const u=r.value;if(u[0]!==n.TokenType.Number)return-1;const i=t[1];if(!i||!e.isTokenNode(i))return-1;const a=i.value;if(a[0]!==n.TokenType.Number)return-1;return numberToCalculation(o,Math.log(u[4].value)/Math.log(a[4].value))}return-1}const b=new Map([["abs",function abs(e,n){return singleNodeSolver(e,n,solveAbs)}],["acos",function acos(e,n){return singleNodeSolver(e,n,solveACos)}],["asin",function asin(e,n){return singleNodeSolver(e,n,solveASin)}],["atan",function atan(e,n){return singleNodeSolver(e,n,solveATan)}],["atan2",function atan2(e,n){return twoCommaSeparatedNodesSolver(e,n,solveATan2)}],["calc",calc$1],["clamp",function clamp(o,t){const r=resolveGlobalsAndConstants([...o.value.filter((n=>!e.isCommentNode(n)&&!e.isWhitespaceNode(n)))],t),u=[],i=[],a=[];{let o=u;for(let t=0;t!e.isCommentNode(n)&&!e.isWhitespaceNode(n)))],t);let u="";const i=[],a=[];{let o=i;for(let t=0;t!e.isCommentNode(n)&&!e.isWhitespaceNode(n)))],t);if(1===r.length&&e.isTokenNode(r[0]))return{inputs:[r[0]],operation:unary};let u=0;for(;u!e.isCommentNode(n)&&!e.isWhitespaceNode(n)))],t),i=solve(calc$1(new e.FunctionNode([n.TokenType.Function,"calc(",-1,-1,{value:"calc"}],[n.TokenType.CloseParen,")",-1,-1,void 0],u),t));return-1===i?-1:r(o,i)}function twoCommaSeparatedNodesSolver(o,t,r){const u=resolveGlobalsAndConstants([...o.value.filter((n=>!e.isCommentNode(n)&&!e.isWhitespaceNode(n)))],t),i=[],a=[];{let o=i;for(let t=0;t!e.isCommentNode(n)&&!e.isWhitespaceNode(n)))],t),i=[];{const o=[];let r=[];for(let t=0;t{if(e.isFunctionNode(n)){const e=b.get(toLowerCaseAZ(n.getName()));if(e){const r=patchCalcResult(solve(e(n,t)),o);if(-1!==r)return r}}}))}const h=new Set(b.keys());exports.calc=function calc(o,t){return calcFromComponentValues(e.parseCommaSeparatedListOfComponentValues(n.tokenize({css:o}),{}),t).map((e=>e.map((e=>n.stringify(...e.tokens()))).join(""))).join(",")},exports.calcFromComponentValues=calcFromComponentValues,exports.mathFunctionNames=h; +"use strict";var e=require("@csstools/css-parser-algorithms"),n=require("@csstools/css-tokenizer");const o=/[A-Z]/g;function toLowerCaseAZ(e){return e.replace(o,(e=>String.fromCharCode(e.charCodeAt(0)+32)))}const t={cm:"px",in:"px",mm:"px",pc:"px",pt:"px",px:"px",q:"px",deg:"deg",grad:"deg",rad:"deg",turn:"deg",ms:"s",s:"s",hz:"hz",khz:"hz"},r=new Map([["cm",e=>e],["mm",e=>10*e],["q",e=>40*e],["in",e=>e/2.54],["pc",e=>e/2.54*6],["pt",e=>e/2.54*72],["px",e=>e/2.54*96]]),u=new Map([["deg",e=>e],["grad",e=>e/.9],["rad",e=>e/180*Math.PI],["turn",e=>e/360]]),i=new Map([["deg",e=>.9*e],["grad",e=>e],["rad",e=>.9*e/180*Math.PI],["turn",e=>.9*e/360]]),a=new Map([["hz",e=>e],["khz",e=>e/1e3]]),l=new Map([["cm",e=>2.54*e],["mm",e=>25.4*e],["q",e=>25.4*e*4],["in",e=>e],["pc",e=>6*e],["pt",e=>72*e],["px",e=>96*e]]),s=new Map([["hz",e=>1e3*e],["khz",e=>e]]),c=new Map([["cm",e=>e/10],["mm",e=>e],["q",e=>4*e],["in",e=>e/25.4],["pc",e=>e/25.4*6],["pt",e=>e/25.4*72],["px",e=>e/25.4*96]]),T=new Map([["ms",e=>e],["s",e=>e/1e3]]),p=new Map([["cm",e=>e/6*2.54],["mm",e=>e/6*25.4],["q",e=>e/6*25.4*4],["in",e=>e/6],["pc",e=>e],["pt",e=>e/6*72],["px",e=>e/6*96]]),v=new Map([["cm",e=>e/72*2.54],["mm",e=>e/72*25.4],["q",e=>e/72*25.4*4],["in",e=>e/72],["pc",e=>e/72*6],["pt",e=>e],["px",e=>e/72*96]]),m=new Map([["cm",e=>e/96*2.54],["mm",e=>e/96*25.4],["q",e=>e/96*25.4*4],["in",e=>e/96],["pc",e=>e/96*6],["pt",e=>e/96*72],["px",e=>e]]),N=new Map([["cm",e=>e/4/10],["mm",e=>e/4],["q",e=>e],["in",e=>e/4/25.4],["pc",e=>e/4/25.4*6],["pt",e=>e/4/25.4*72],["px",e=>e/4/25.4*96]]),f=new Map([["deg",e=>180*e/Math.PI],["grad",e=>180*e/Math.PI/.9],["rad",e=>e],["turn",e=>180*e/Math.PI/360]]),y=new Map([["ms",e=>1e3*e],["s",e=>e]]),k=new Map([["deg",e=>360*e],["grad",e=>360*e/.9],["rad",e=>360*e/180*Math.PI],["turn",e=>e]]),d=new Map([["cm",r],["mm",c],["q",N],["in",l],["pc",p],["pt",v],["px",m],["ms",T],["s",y],["deg",u],["grad",i],["rad",f],["turn",k],["hz",a],["khz",s]]);function convertUnit(e,o){if(e[0]!==n.TokenType.Dimension)return o;if(o[0]!==n.TokenType.Dimension)return o;const t=toLowerCaseAZ(e[4].unit),r=toLowerCaseAZ(o[4].unit);if(t===r)return o;const u=d.get(r);if(!u)return o;const i=u.get(t);if(!i)return o;const a=i(o[4].value);return[n.TokenType.Dimension,a.toString()+e[4].unit,o[2],o[3],{value:a,unit:e[4].unit,type:Number.isInteger(a)?n.NumberType.Integer:n.NumberType.Number}]}function toCanonicalUnit(e){if(e[0]!==n.TokenType.Dimension)return e;const o=toLowerCaseAZ(e[4].unit),r=t[o];if(o===r)return e;const u=d.get(o);if(!u)return e;const i=u.get(r);if(!i)return e;const a=i(e[4].value);return[n.TokenType.Dimension,a.toString()+r,e[2],e[3],{value:a,unit:r,type:Number.isInteger(a)?n.NumberType.Integer:n.NumberType.Number}]}function addition(o){if(2!==o.length)return-1;const t=o[0].value;let r=o[1].value;if(t[0]===n.TokenType.Number&&r[0]===n.TokenType.Number){const o=t[4].value+r[4].value;return new e.TokenNode([n.TokenType.Number,o.toString(),t[2],r[3],{value:o,type:t[4].type===n.NumberType.Integer&&r[4].type===n.NumberType.Integer?n.NumberType.Integer:n.NumberType.Number}])}if(t[0]===n.TokenType.Percentage&&r[0]===n.TokenType.Percentage){const o=t[4].value+r[4].value;return new e.TokenNode([n.TokenType.Percentage,o.toString()+"%",t[2],r[3],{value:o}])}if(t[0]===n.TokenType.Dimension&&r[0]===n.TokenType.Dimension&&(r=convertUnit(t,r),toLowerCaseAZ(t[4].unit)===toLowerCaseAZ(r[4].unit))){const o=t[4].value+r[4].value;return new e.TokenNode([n.TokenType.Dimension,o.toString()+t[4].unit,t[2],r[3],{value:o,type:t[4].type===n.NumberType.Integer&&r[4].type===n.NumberType.Integer?n.NumberType.Integer:n.NumberType.Number,unit:t[4].unit}])}return-1}function division(o){if(2!==o.length)return-1;const t=o[0].value,r=o[1].value;if(t[0]===n.TokenType.Number&&r[0]===n.TokenType.Number){const o=t[4].value/r[4].value;return new e.TokenNode([n.TokenType.Number,o.toString(),t[2],r[3],{value:o,type:Number.isInteger(o)?n.NumberType.Integer:n.NumberType.Number}])}if(t[0]===n.TokenType.Percentage&&r[0]===n.TokenType.Number){const o=t[4].value/r[4].value;return new e.TokenNode([n.TokenType.Percentage,o.toString()+"%",t[2],r[3],{value:o}])}if(t[0]===n.TokenType.Dimension&&r[0]===n.TokenType.Number){const o=t[4].value/r[4].value;return new e.TokenNode([n.TokenType.Dimension,o.toString()+t[4].unit,t[2],r[3],{value:o,type:Number.isInteger(o)?n.NumberType.Integer:n.NumberType.Number,unit:t[4].unit}])}return-1}function isCalculation(e){return!!e&&"object"==typeof e&&"inputs"in e&&Array.isArray(e.inputs)&&"operation"in e}function solve(n){if(-1===n)return-1;const o=[];for(let t=0;te.type))).size)return-1;const r=t.value;if(!isNumeric(r))return-1;const u=o.map((e=>convertUnit(r,e.value)));if(!arrayOfSameNumeric(u))return-1;const i=u.map((e=>e[4].value)),a=Math.hypot(...i);return resultToCalculation(n,r,a)}function solveMax(n,o){const t=o[0];if(!t||!e.isTokenNode(t))return-1;if(1!==new Set(o.map((e=>e.type))).size)return-1;const r=t.value;if(!isNumeric(r))return-1;const u=o.map((e=>convertUnit(r,e.value)));if(!arrayOfSameNumeric(u))return-1;const i=u.map((e=>e[4].value)),a=Math.max(...i);return resultToCalculation(n,r,a)}function solveMin(n,o){const t=o[0];if(!t||!e.isTokenNode(t))return-1;if(1!==new Set(o.map((e=>e.type))).size)return-1;const r=t.value;if(!isNumeric(r))return-1;const u=o.map((e=>convertUnit(r,e.value)));if(!arrayOfSameNumeric(u))return-1;const i=u.map((e=>e[4].value)),a=Math.min(...i);return resultToCalculation(n,r,a)}function solveMod(e,n,o){const t=n.value;if(!isNumeric(t))return-1;const r=convertUnit(t,o.value);if(!twoOfSameNumeric(t,r))return-1;let u;return u=0===r[4].value?Number.NaN:Number.isFinite(t[4].value)&&(Number.isFinite(r[4].value)||(r[4].value!==Number.POSITIVE_INFINITY||t[4].value!==Number.NEGATIVE_INFINITY&&!Object.is(0*t[4].value,-0))&&(r[4].value!==Number.NEGATIVE_INFINITY||t[4].value!==Number.POSITIVE_INFINITY&&!Object.is(0*t[4].value,0)))?Number.isFinite(r[4].value)?(t[4].value%r[4].value+r[4].value)%r[4].value:t[4].value:Number.NaN,resultToCalculation(e,t,u)}function solvePow(e,o,t){const r=o.value,u=t.value;if(r[0]!==n.TokenType.Number)return-1;if(!twoOfSameNumeric(r,u))return-1;return numberToCalculation(e,Math.pow(r[4].value,u[4].value))}function solveRem(e,n,o){const t=n.value;if(!isNumeric(t))return-1;const r=convertUnit(t,o.value);if(!twoOfSameNumeric(t,r))return-1;let u;return u=0===r[4].value?Number.NaN:Number.isFinite(t[4].value)?Number.isFinite(r[4].value)?t[4].value%r[4].value:t[4].value:Number.NaN,resultToCalculation(e,t,u)}function solveRound(e,n,o,t){const r=o.value;if(!isNumeric(r))return-1;const u=convertUnit(r,t.value);if(!twoOfSameNumeric(r,u))return-1;let i;if(0===u[4].value)i=Number.NaN;else if(Number.isFinite(r[4].value)||Number.isFinite(u[4].value))if(!Number.isFinite(r[4].value)&&Number.isFinite(u[4].value))i=r[4].value;else if(Number.isFinite(r[4].value)&&!Number.isFinite(u[4].value))switch(n){case"down":i=r[4].value<0?-1/0:Object.is(-0,0*r[4].value)?-0:0;break;case"up":i=r[4].value>0?1/0:Object.is(0,0*r[4].value)?0:-0;break;default:i=Object.is(0,0*r[4].value)?0:-0}else if(Number.isFinite(u[4].value))switch(n){case"down":i=Math.floor(r[4].value/u[4].value)*u[4].value;break;case"up":i=Math.ceil(r[4].value/u[4].value)*u[4].value;break;case"to-zero":i=Math.trunc(r[4].value/u[4].value)*u[4].value;break;default:{let e=Math.floor(r[4].value/u[4].value)*u[4].value,n=Math.ceil(r[4].value/u[4].value)*u[4].value;if(e>n){const o=e;e=n,n=o}const o=Math.abs(r[4].value-e),t=Math.abs(r[4].value-n);i=o===t?n:o0?1/0:-1/0:Math.tan(l),numberToCalculation(e,l)}function subtraction(o){if(2!==o.length)return-1;const t=o[0].value;let r=o[1].value;if(t[0]===n.TokenType.Number&&r[0]===n.TokenType.Number){const o=t[4].value-r[4].value;return new e.TokenNode([n.TokenType.Number,o.toString(),t[2],r[3],{value:o,type:t[4].type===n.NumberType.Integer&&r[4].type===n.NumberType.Integer?n.NumberType.Integer:n.NumberType.Number}])}if(t[0]===n.TokenType.Percentage&&r[0]===n.TokenType.Percentage){const o=t[4].value-r[4].value;return new e.TokenNode([n.TokenType.Percentage,o.toString()+"%",t[2],r[3],{value:o}])}if(t[0]===n.TokenType.Dimension&&r[0]===n.TokenType.Dimension&&(r=convertUnit(t,r),toLowerCaseAZ(t[4].unit)===toLowerCaseAZ(r[4].unit))){const o=t[4].value-r[4].value;return new e.TokenNode([n.TokenType.Dimension,o.toString()+t[4].unit,t[2],r[3],{value:o,type:t[4].type===n.NumberType.Integer&&r[4].type===n.NumberType.Integer?n.NumberType.Integer:n.NumberType.Number,unit:t[4].unit}])}return-1}function solveLog(o,t){if(1===t.length){const r=t[0];if(!r||!e.isTokenNode(r))return-1;const u=r.value;if(u[0]!==n.TokenType.Number)return-1;return numberToCalculation(o,Math.log(u[4].value))}if(2===t.length){const r=t[0];if(!r||!e.isTokenNode(r))return-1;const u=r.value;if(u[0]!==n.TokenType.Number)return-1;const i=t[1];if(!i||!e.isTokenNode(i))return-1;const a=i.value;if(a[0]!==n.TokenType.Number)return-1;return numberToCalculation(o,Math.log(u[4].value)/Math.log(a[4].value))}return-1}const b=new Map([["abs",function abs(e,n){return singleNodeSolver(e,n,solveAbs)}],["acos",function acos(e,n){return singleNodeSolver(e,n,solveACos)}],["asin",function asin(e,n){return singleNodeSolver(e,n,solveASin)}],["atan",function atan(e,n){return singleNodeSolver(e,n,solveATan)}],["atan2",function atan2(e,n){return twoCommaSeparatedNodesSolver(e,n,solveATan2)}],["calc",calc$1],["clamp",function clamp(o,t){const r=resolveGlobalsAndConstants([...o.value.filter((n=>!e.isCommentNode(n)&&!e.isWhitespaceNode(n)))],t),u=[],i=[],a=[];{let o=u;for(let t=0;t!e.isCommentNode(n)&&!e.isWhitespaceNode(n)))],t);let u="";const i=[],a=[];{let o=i;for(let t=0;t!e.isCommentNode(n)&&!e.isWhitespaceNode(n)))],t);if(1===r.length&&e.isTokenNode(r[0]))return{inputs:[r[0]],operation:unary};let u=0;for(;u!e.isCommentNode(n)&&!e.isWhitespaceNode(n)))],t),i=solve(calc$1(new e.FunctionNode([n.TokenType.Function,"calc(",-1,-1,{value:"calc"}],[n.TokenType.CloseParen,")",-1,-1,void 0],u),t));return-1===i?-1:r(o,i)}function twoCommaSeparatedNodesSolver(o,t,r){const u=resolveGlobalsAndConstants([...o.value.filter((n=>!e.isCommentNode(n)&&!e.isWhitespaceNode(n)))],t),i=[],a=[];{let o=i;for(let t=0;t!e.isCommentNode(n)&&!e.isWhitespaceNode(n)))],t),i=[];{const o=[];let r=[];for(let t=0;t{if(e.isFunctionNode(n)){const e=b.get(toLowerCaseAZ(n.getName()));if(e){const r=patchCalcResult(solve(e(n,t)),o);if(-1!==r)return r}}}))}const h=new Set(b.keys());exports.calc=function calc(o,t){return calcFromComponentValues(e.parseCommaSeparatedListOfComponentValues(n.tokenize({css:o}),{}),t).map((e=>e.map((e=>n.stringify(...e.tokens()))).join(""))).join(",")},exports.calcFromComponentValues=calcFromComponentValues,exports.mathFunctionNames=h; diff --git a/packages/css-calc/dist/index.d.ts b/packages/css-calc/dist/index.d.ts index b7e6856b8..9d31d3b50 100644 --- a/packages/css-calc/dist/index.d.ts +++ b/packages/css-calc/dist/index.d.ts @@ -1,6 +1,37 @@ -export type { conversionOptions } from './options'; -import type { conversionOptions } from './options'; import { ComponentValue } from '@csstools/css-parser-algorithms'; +import type { TokenDimension } from '@csstools/css-tokenizer'; +import type { TokenNumber } from '@csstools/css-tokenizer'; +import type { TokenPercentage } from '@csstools/css-tokenizer'; + export declare function calc(css: string, options?: conversionOptions): string; + export declare function calcFromComponentValues(componentValuesList: Array>, options?: conversionOptions): ComponentValue[][]; + +export declare type conversionOptions = { + /** + * Pass global values as a map of key value pairs. + */ + globals?: GlobalsWithStrings; + /** + * The default precision is fairly high. + * It aims to be high enough to make rounding unnoticeable in the browser. + * You can set it to a lower number to suite your needs. + */ + precision?: number; + /** + * By default this package will try to preserve units. + * The heuristic to do this is very simplistic. + * We take the first unit we encounter and try to convert other dimensions to that unit. + * + * This better matches what users expect from a CSS dev tool. + * + * If you want to have outputs that are closes to CSS serialized values you can set `true`. + */ + toCanonicalUnits?: boolean; +}; + +export declare type GlobalsWithStrings = Map; + export declare const mathFunctionNames: Set; + +export { } diff --git a/packages/css-calc/dist/index.mjs b/packages/css-calc/dist/index.mjs index 0bf6b70e0..a45745b55 100644 --- a/packages/css-calc/dist/index.mjs +++ b/packages/css-calc/dist/index.mjs @@ -1 +1 @@ -import{TokenNode as e,isTokenNode as n,isCommentNode as t,isWhitespaceNode as r,isSimpleBlockNode as u,isFunctionNode as i,FunctionNode as a,WhitespaceNode as o,parseCommaSeparatedListOfComponentValues as l,replaceComponentValues as c}from"@csstools/css-parser-algorithms";import{TokenType as s,NumberType as v,isToken as m,tokenizer as f,tokenize as p,stringify as N}from"@csstools/css-tokenizer";const g=/[A-Z]/g;function toLowerCaseAZ(e){return e.replace(g,(e=>String.fromCharCode(e.charCodeAt(0)+32)))}const b={cm:"px",in:"px",mm:"px",pc:"px",pt:"px",px:"px",q:"px",deg:"deg",grad:"deg",rad:"deg",turn:"deg",ms:"s",s:"s",hz:"hz",khz:"hz"},d=new Map([["cm",e=>e],["mm",e=>10*e],["q",e=>40*e],["in",e=>e/2.54],["pc",e=>e/2.54*6],["pt",e=>e/2.54*72],["px",e=>e/2.54*96]]),w=new Map([["deg",e=>e],["grad",e=>e/.9],["rad",e=>e/180*Math.PI],["turn",e=>e/360]]),h=new Map([["deg",e=>.9*e],["grad",e=>e],["rad",e=>.9*e/180*Math.PI],["turn",e=>.9*e/360]]),C=new Map([["hz",e=>e],["khz",e=>e/1e3]]),I=new Map([["cm",e=>2.54*e],["mm",e=>25.4*e],["q",e=>25.4*e*4],["in",e=>e],["pc",e=>6*e],["pt",e=>72*e],["px",e=>96*e]]),S=new Map([["hz",e=>1e3*e],["khz",e=>e]]),y=new Map([["cm",e=>e/10],["mm",e=>e],["q",e=>4*e],["in",e=>e/25.4],["pc",e=>e/25.4*6],["pt",e=>e/25.4*72],["px",e=>e/25.4*96]]),M=new Map([["ms",e=>e],["s",e=>e/1e3]]),P=new Map([["cm",e=>e/6*2.54],["mm",e=>e/6*25.4],["q",e=>e/6*25.4*4],["in",e=>e/6],["pc",e=>e],["pt",e=>e/6*72],["px",e=>e/6*96]]),D=new Map([["cm",e=>e/72*2.54],["mm",e=>e/72*25.4],["q",e=>e/72*25.4*4],["in",e=>e/72],["pc",e=>e/72*6],["pt",e=>e],["px",e=>e/72*96]]),T=new Map([["cm",e=>e/96*2.54],["mm",e=>e/96*25.4],["q",e=>e/96*25.4*4],["in",e=>e/96],["pc",e=>e/96*6],["pt",e=>e/96*72],["px",e=>e]]),A=new Map([["cm",e=>e/4/10],["mm",e=>e/4],["q",e=>e],["in",e=>e/4/25.4],["pc",e=>e/4/25.4*6],["pt",e=>e/4/25.4*72],["px",e=>e/4/25.4*96]]),k=new Map([["deg",e=>180*e/Math.PI],["grad",e=>180*e/Math.PI/.9],["rad",e=>e],["turn",e=>180*e/Math.PI/360]]),F=new Map([["ms",e=>1e3*e],["s",e=>e]]),x=new Map([["deg",e=>360*e],["grad",e=>360*e/.9],["rad",e=>360*e/180*Math.PI],["turn",e=>e]]),O=new Map([["cm",d],["mm",y],["q",A],["in",I],["pc",P],["pt",D],["px",T],["ms",M],["s",F],["deg",w],["grad",h],["rad",k],["turn",x],["hz",C],["khz",S]]);function convertUnit(e,n){if(e[0]!==s.Dimension)return n;if(n[0]!==s.Dimension)return n;const t=toLowerCaseAZ(e[4].unit),r=toLowerCaseAZ(n[4].unit);if(t===r)return n;const u=O.get(r);if(!u)return n;const i=u.get(t);if(!i)return n;const a=i(n[4].value);return[s.Dimension,a.toString()+e[4].unit,n[2],n[3],{value:a,unit:e[4].unit,type:Number.isInteger(a)?v.Integer:v.Number}]}function toCanonicalUnit(e){if(e[0]!==s.Dimension)return e;const n=toLowerCaseAZ(e[4].unit),t=b[n];if(n===t)return e;const r=O.get(n);if(!r)return e;const u=r.get(t);if(!u)return e;const i=u(e[4].value);return[s.Dimension,i.toString()+t,e[2],e[3],{value:i,unit:t,type:Number.isInteger(i)?v.Integer:v.Number}]}function addition(n){if(2!==n.length)return-1;const t=n[0].value;let r=n[1].value;if(t[0]===s.Number&&r[0]===s.Number){const n=t[4].value+r[4].value;return new e([s.Number,n.toString(),t[2],r[3],{value:n,type:t[4].type===v.Integer&&r[4].type===v.Integer?v.Integer:v.Number}])}if(t[0]===s.Percentage&&r[0]===s.Percentage){const n=t[4].value+r[4].value;return new e([s.Percentage,n.toString()+"%",t[2],r[3],{value:n}])}if(t[0]===s.Dimension&&r[0]===s.Dimension&&(r=convertUnit(t,r),toLowerCaseAZ(t[4].unit)===toLowerCaseAZ(r[4].unit))){const n=t[4].value+r[4].value;return new e([s.Dimension,n.toString()+t[4].unit,t[2],r[3],{value:n,type:t[4].type===v.Integer&&r[4].type===v.Integer?v.Integer:v.Number,unit:t[4].unit}])}return-1}function division(n){if(2!==n.length)return-1;const t=n[0].value,r=n[1].value;if(t[0]===s.Number&&r[0]===s.Number){const n=t[4].value/r[4].value;return new e([s.Number,n.toString(),t[2],r[3],{value:n,type:Number.isInteger(n)?v.Integer:v.Number}])}if(t[0]===s.Percentage&&r[0]===s.Number){const n=t[4].value/r[4].value;return new e([s.Percentage,n.toString()+"%",t[2],r[3],{value:n}])}if(t[0]===s.Dimension&&r[0]===s.Number){const n=t[4].value/r[4].value;return new e([s.Dimension,n.toString()+t[4].unit,t[2],r[3],{value:n,type:Number.isInteger(n)?v.Integer:v.Number,unit:t[4].unit}])}return-1}function isCalculation(e){return!!e&&"object"==typeof e&&"inputs"in e&&Array.isArray(e.inputs)&&"operation"in e}function solve(e){if(-1===e)return-1;const t=[];for(let r=0;re.type))).size)return-1;const u=r.value;if(!isNumeric(u))return-1;const i=t.map((e=>convertUnit(u,e.value)));if(!arrayOfSameNumeric(i))return-1;const a=i.map((e=>e[4].value)),o=Math.hypot(...a);return resultToCalculation(e,u,o)}function solveMax(e,t){const r=t[0];if(!r||!n(r))return-1;if(1!==new Set(t.map((e=>e.type))).size)return-1;const u=r.value;if(!isNumeric(u))return-1;const i=t.map((e=>convertUnit(u,e.value)));if(!arrayOfSameNumeric(i))return-1;const a=i.map((e=>e[4].value)),o=Math.max(...a);return resultToCalculation(e,u,o)}function solveMin(e,t){const r=t[0];if(!r||!n(r))return-1;if(1!==new Set(t.map((e=>e.type))).size)return-1;const u=r.value;if(!isNumeric(u))return-1;const i=t.map((e=>convertUnit(u,e.value)));if(!arrayOfSameNumeric(i))return-1;const a=i.map((e=>e[4].value)),o=Math.min(...a);return resultToCalculation(e,u,o)}function solveMod(e,n,t){const r=n.value;if(!isNumeric(r))return-1;const u=convertUnit(r,t.value);if(!twoOfSameNumeric(r,u))return-1;let i;return i=0===u[4].value?Number.NaN:Number.isFinite(r[4].value)&&(Number.isFinite(u[4].value)||(u[4].value!==Number.POSITIVE_INFINITY||r[4].value!==Number.NEGATIVE_INFINITY&&!Object.is(0*r[4].value,-0))&&(u[4].value!==Number.NEGATIVE_INFINITY||r[4].value!==Number.POSITIVE_INFINITY&&!Object.is(0*r[4].value,0)))?Number.isFinite(u[4].value)?(r[4].value%u[4].value+u[4].value)%u[4].value:r[4].value:Number.NaN,resultToCalculation(e,r,i)}function solvePow(e,n,t){const r=n.value,u=t.value;if(r[0]!==s.Number)return-1;if(!twoOfSameNumeric(r,u))return-1;return numberToCalculation(e,Math.pow(r[4].value,u[4].value))}function solveRem(e,n,t){const r=n.value;if(!isNumeric(r))return-1;const u=convertUnit(r,t.value);if(!twoOfSameNumeric(r,u))return-1;let i;return i=0===u[4].value?Number.NaN:Number.isFinite(r[4].value)?Number.isFinite(u[4].value)?r[4].value%u[4].value:r[4].value:Number.NaN,resultToCalculation(e,r,i)}function solveRound(e,n,t,r){const u=t.value;if(!isNumeric(u))return-1;const i=convertUnit(u,r.value);if(!twoOfSameNumeric(u,i))return-1;let a;if(0===i[4].value)a=Number.NaN;else if(Number.isFinite(u[4].value)||Number.isFinite(i[4].value))if(!Number.isFinite(u[4].value)&&Number.isFinite(i[4].value))a=u[4].value;else if(Number.isFinite(u[4].value)&&!Number.isFinite(i[4].value))switch(n){case"down":a=u[4].value<0?-1/0:Object.is(-0,0*u[4].value)?-0:0;break;case"up":a=u[4].value>0?1/0:Object.is(0,0*u[4].value)?0:-0;break;default:a=Object.is(0,0*u[4].value)?0:-0}else if(Number.isFinite(i[4].value))switch(n){case"down":a=Math.floor(u[4].value/i[4].value)*i[4].value;break;case"up":a=Math.ceil(u[4].value/i[4].value)*i[4].value;break;case"to-zero":a=Math.trunc(u[4].value/i[4].value)*i[4].value;break;default:{let e=Math.floor(u[4].value/i[4].value)*i[4].value,n=Math.ceil(u[4].value/i[4].value)*i[4].value;if(e>n){const t=e;e=n,n=t}const t=Math.abs(u[4].value-e),r=Math.abs(u[4].value-n);a=t===r?n:t0?1/0:-1/0:Math.tan(i),numberToCalculation(e,i)}function subtraction(n){if(2!==n.length)return-1;const t=n[0].value;let r=n[1].value;if(t[0]===s.Number&&r[0]===s.Number){const n=t[4].value-r[4].value;return new e([s.Number,n.toString(),t[2],r[3],{value:n,type:t[4].type===v.Integer&&r[4].type===v.Integer?v.Integer:v.Number}])}if(t[0]===s.Percentage&&r[0]===s.Percentage){const n=t[4].value-r[4].value;return new e([s.Percentage,n.toString()+"%",t[2],r[3],{value:n}])}if(t[0]===s.Dimension&&r[0]===s.Dimension&&(r=convertUnit(t,r),toLowerCaseAZ(t[4].unit)===toLowerCaseAZ(r[4].unit))){const n=t[4].value-r[4].value;return new e([s.Dimension,n.toString()+t[4].unit,t[2],r[3],{value:n,type:t[4].type===v.Integer&&r[4].type===v.Integer?v.Integer:v.Number,unit:t[4].unit}])}return-1}function solveLog(e,t){if(1===t.length){const r=t[0];if(!r||!n(r))return-1;const u=r.value;if(u[0]!==s.Number)return-1;return numberToCalculation(e,Math.log(u[4].value))}if(2===t.length){const r=t[0];if(!r||!n(r))return-1;const u=r.value;if(u[0]!==s.Number)return-1;const i=t[1];if(!i||!n(i))return-1;const a=i.value;if(a[0]!==s.Number)return-1;return numberToCalculation(e,Math.log(u[4].value)/Math.log(a[4].value))}return-1}const Z=new Map([["abs",function abs(e,n){return singleNodeSolver(e,n,solveAbs)}],["acos",function acos(e,n){return singleNodeSolver(e,n,solveACos)}],["asin",function asin(e,n){return singleNodeSolver(e,n,solveASin)}],["atan",function atan(e,n){return singleNodeSolver(e,n,solveATan)}],["atan2",function atan2(e,n){return twoCommaSeparatedNodesSolver(e,n,solveATan2)}],["calc",calc$1],["clamp",function clamp(e,u){const i=resolveGlobalsAndConstants([...e.value.filter((e=>!t(e)&&!r(e)))],u),o=[],l=[],c=[];{let e=o;for(let t=0;t!t(e)&&!r(e)))],u);let o="";const l=[],c=[];{let e=l;for(let t=0;t!t(e)&&!r(e)))],a);if(1===o.length&&n(o[0]))return{inputs:[o[0]],operation:unary};let l=0;for(;l!t(e)&&!r(e)))],n),o=solve(calc$1(new a([s.Function,"calc(",-1,-1,{value:"calc"}],[s.CloseParen,")",-1,-1,void 0],i),n));return-1===o?-1:u(e,o)}function twoCommaSeparatedNodesSolver(e,u,i){const o=resolveGlobalsAndConstants([...e.value.filter((e=>!t(e)&&!r(e)))],u),l=[],c=[];{let e=l;for(let t=0;t!t(e)&&!r(e)))],u),l=[];{const e=[];let t=[];for(let r=0;re.map((e=>N(...e.tokens()))).join(""))).join(",")}function calcFromComponentValues(e,n){const t=tokenizeGlobals(null==n?void 0:n.globals);return c(e,(e=>{if(i(e)){const r=Z.get(toLowerCaseAZ(e.getName()));if(r){const u=patchCalcResult(solve(r(e,t)),n);if(-1!==u)return u}}}))}const z=new Set(Z.keys());export{calc,calcFromComponentValues,z as mathFunctionNames}; +import{TokenNode as e,isTokenNode as n,isCommentNode as t,isWhitespaceNode as r,isSimpleBlockNode as u,isFunctionNode as i,FunctionNode as a,WhitespaceNode as o,parseCommaSeparatedListOfComponentValues as l,replaceComponentValues as c}from"@csstools/css-parser-algorithms";import{TokenType as s,NumberType as v,isToken as m,tokenizer as f,tokenize as p,stringify as N}from"@csstools/css-tokenizer";const g=/[A-Z]/g;function toLowerCaseAZ(e){return e.replace(g,(e=>String.fromCharCode(e.charCodeAt(0)+32)))}const b={cm:"px",in:"px",mm:"px",pc:"px",pt:"px",px:"px",q:"px",deg:"deg",grad:"deg",rad:"deg",turn:"deg",ms:"s",s:"s",hz:"hz",khz:"hz"},d=new Map([["cm",e=>e],["mm",e=>10*e],["q",e=>40*e],["in",e=>e/2.54],["pc",e=>e/2.54*6],["pt",e=>e/2.54*72],["px",e=>e/2.54*96]]),w=new Map([["deg",e=>e],["grad",e=>e/.9],["rad",e=>e/180*Math.PI],["turn",e=>e/360]]),h=new Map([["deg",e=>.9*e],["grad",e=>e],["rad",e=>.9*e/180*Math.PI],["turn",e=>.9*e/360]]),C=new Map([["hz",e=>e],["khz",e=>e/1e3]]),I=new Map([["cm",e=>2.54*e],["mm",e=>25.4*e],["q",e=>25.4*e*4],["in",e=>e],["pc",e=>6*e],["pt",e=>72*e],["px",e=>96*e]]),S=new Map([["hz",e=>1e3*e],["khz",e=>e]]),y=new Map([["cm",e=>e/10],["mm",e=>e],["q",e=>4*e],["in",e=>e/25.4],["pc",e=>e/25.4*6],["pt",e=>e/25.4*72],["px",e=>e/25.4*96]]),M=new Map([["ms",e=>e],["s",e=>e/1e3]]),P=new Map([["cm",e=>e/6*2.54],["mm",e=>e/6*25.4],["q",e=>e/6*25.4*4],["in",e=>e/6],["pc",e=>e],["pt",e=>e/6*72],["px",e=>e/6*96]]),D=new Map([["cm",e=>e/72*2.54],["mm",e=>e/72*25.4],["q",e=>e/72*25.4*4],["in",e=>e/72],["pc",e=>e/72*6],["pt",e=>e],["px",e=>e/72*96]]),T=new Map([["cm",e=>e/96*2.54],["mm",e=>e/96*25.4],["q",e=>e/96*25.4*4],["in",e=>e/96],["pc",e=>e/96*6],["pt",e=>e/96*72],["px",e=>e]]),A=new Map([["cm",e=>e/4/10],["mm",e=>e/4],["q",e=>e],["in",e=>e/4/25.4],["pc",e=>e/4/25.4*6],["pt",e=>e/4/25.4*72],["px",e=>e/4/25.4*96]]),k=new Map([["deg",e=>180*e/Math.PI],["grad",e=>180*e/Math.PI/.9],["rad",e=>e],["turn",e=>180*e/Math.PI/360]]),F=new Map([["ms",e=>1e3*e],["s",e=>e]]),x=new Map([["deg",e=>360*e],["grad",e=>360*e/.9],["rad",e=>360*e/180*Math.PI],["turn",e=>e]]),O=new Map([["cm",d],["mm",y],["q",A],["in",I],["pc",P],["pt",D],["px",T],["ms",M],["s",F],["deg",w],["grad",h],["rad",k],["turn",x],["hz",C],["khz",S]]);function convertUnit(e,n){if(e[0]!==s.Dimension)return n;if(n[0]!==s.Dimension)return n;const t=toLowerCaseAZ(e[4].unit),r=toLowerCaseAZ(n[4].unit);if(t===r)return n;const u=O.get(r);if(!u)return n;const i=u.get(t);if(!i)return n;const a=i(n[4].value);return[s.Dimension,a.toString()+e[4].unit,n[2],n[3],{value:a,unit:e[4].unit,type:Number.isInteger(a)?v.Integer:v.Number}]}function toCanonicalUnit(e){if(e[0]!==s.Dimension)return e;const n=toLowerCaseAZ(e[4].unit),t=b[n];if(n===t)return e;const r=O.get(n);if(!r)return e;const u=r.get(t);if(!u)return e;const i=u(e[4].value);return[s.Dimension,i.toString()+t,e[2],e[3],{value:i,unit:t,type:Number.isInteger(i)?v.Integer:v.Number}]}function addition(n){if(2!==n.length)return-1;const t=n[0].value;let r=n[1].value;if(t[0]===s.Number&&r[0]===s.Number){const n=t[4].value+r[4].value;return new e([s.Number,n.toString(),t[2],r[3],{value:n,type:t[4].type===v.Integer&&r[4].type===v.Integer?v.Integer:v.Number}])}if(t[0]===s.Percentage&&r[0]===s.Percentage){const n=t[4].value+r[4].value;return new e([s.Percentage,n.toString()+"%",t[2],r[3],{value:n}])}if(t[0]===s.Dimension&&r[0]===s.Dimension&&(r=convertUnit(t,r),toLowerCaseAZ(t[4].unit)===toLowerCaseAZ(r[4].unit))){const n=t[4].value+r[4].value;return new e([s.Dimension,n.toString()+t[4].unit,t[2],r[3],{value:n,type:t[4].type===v.Integer&&r[4].type===v.Integer?v.Integer:v.Number,unit:t[4].unit}])}return-1}function division(n){if(2!==n.length)return-1;const t=n[0].value,r=n[1].value;if(t[0]===s.Number&&r[0]===s.Number){const n=t[4].value/r[4].value;return new e([s.Number,n.toString(),t[2],r[3],{value:n,type:Number.isInteger(n)?v.Integer:v.Number}])}if(t[0]===s.Percentage&&r[0]===s.Number){const n=t[4].value/r[4].value;return new e([s.Percentage,n.toString()+"%",t[2],r[3],{value:n}])}if(t[0]===s.Dimension&&r[0]===s.Number){const n=t[4].value/r[4].value;return new e([s.Dimension,n.toString()+t[4].unit,t[2],r[3],{value:n,type:Number.isInteger(n)?v.Integer:v.Number,unit:t[4].unit}])}return-1}function isCalculation(e){return!!e&&"object"==typeof e&&"inputs"in e&&Array.isArray(e.inputs)&&"operation"in e}function solve(e){if(-1===e)return-1;const t=[];for(let r=0;re.type))).size)return-1;const u=r.value;if(!isNumeric(u))return-1;const i=t.map((e=>convertUnit(u,e.value)));if(!arrayOfSameNumeric(i))return-1;const a=i.map((e=>e[4].value)),o=Math.hypot(...a);return resultToCalculation(e,u,o)}function solveMax(e,t){const r=t[0];if(!r||!n(r))return-1;if(1!==new Set(t.map((e=>e.type))).size)return-1;const u=r.value;if(!isNumeric(u))return-1;const i=t.map((e=>convertUnit(u,e.value)));if(!arrayOfSameNumeric(i))return-1;const a=i.map((e=>e[4].value)),o=Math.max(...a);return resultToCalculation(e,u,o)}function solveMin(e,t){const r=t[0];if(!r||!n(r))return-1;if(1!==new Set(t.map((e=>e.type))).size)return-1;const u=r.value;if(!isNumeric(u))return-1;const i=t.map((e=>convertUnit(u,e.value)));if(!arrayOfSameNumeric(i))return-1;const a=i.map((e=>e[4].value)),o=Math.min(...a);return resultToCalculation(e,u,o)}function solveMod(e,n,t){const r=n.value;if(!isNumeric(r))return-1;const u=convertUnit(r,t.value);if(!twoOfSameNumeric(r,u))return-1;let i;return i=0===u[4].value?Number.NaN:Number.isFinite(r[4].value)&&(Number.isFinite(u[4].value)||(u[4].value!==Number.POSITIVE_INFINITY||r[4].value!==Number.NEGATIVE_INFINITY&&!Object.is(0*r[4].value,-0))&&(u[4].value!==Number.NEGATIVE_INFINITY||r[4].value!==Number.POSITIVE_INFINITY&&!Object.is(0*r[4].value,0)))?Number.isFinite(u[4].value)?(r[4].value%u[4].value+u[4].value)%u[4].value:r[4].value:Number.NaN,resultToCalculation(e,r,i)}function solvePow(e,n,t){const r=n.value,u=t.value;if(r[0]!==s.Number)return-1;if(!twoOfSameNumeric(r,u))return-1;return numberToCalculation(e,Math.pow(r[4].value,u[4].value))}function solveRem(e,n,t){const r=n.value;if(!isNumeric(r))return-1;const u=convertUnit(r,t.value);if(!twoOfSameNumeric(r,u))return-1;let i;return i=0===u[4].value?Number.NaN:Number.isFinite(r[4].value)?Number.isFinite(u[4].value)?r[4].value%u[4].value:r[4].value:Number.NaN,resultToCalculation(e,r,i)}function solveRound(e,n,t,r){const u=t.value;if(!isNumeric(u))return-1;const i=convertUnit(u,r.value);if(!twoOfSameNumeric(u,i))return-1;let a;if(0===i[4].value)a=Number.NaN;else if(Number.isFinite(u[4].value)||Number.isFinite(i[4].value))if(!Number.isFinite(u[4].value)&&Number.isFinite(i[4].value))a=u[4].value;else if(Number.isFinite(u[4].value)&&!Number.isFinite(i[4].value))switch(n){case"down":a=u[4].value<0?-1/0:Object.is(-0,0*u[4].value)?-0:0;break;case"up":a=u[4].value>0?1/0:Object.is(0,0*u[4].value)?0:-0;break;default:a=Object.is(0,0*u[4].value)?0:-0}else if(Number.isFinite(i[4].value))switch(n){case"down":a=Math.floor(u[4].value/i[4].value)*i[4].value;break;case"up":a=Math.ceil(u[4].value/i[4].value)*i[4].value;break;case"to-zero":a=Math.trunc(u[4].value/i[4].value)*i[4].value;break;default:{let e=Math.floor(u[4].value/i[4].value)*i[4].value,n=Math.ceil(u[4].value/i[4].value)*i[4].value;if(e>n){const t=e;e=n,n=t}const t=Math.abs(u[4].value-e),r=Math.abs(u[4].value-n);a=t===r?n:t0?1/0:-1/0:Math.tan(i),numberToCalculation(e,i)}function subtraction(n){if(2!==n.length)return-1;const t=n[0].value;let r=n[1].value;if(t[0]===s.Number&&r[0]===s.Number){const n=t[4].value-r[4].value;return new e([s.Number,n.toString(),t[2],r[3],{value:n,type:t[4].type===v.Integer&&r[4].type===v.Integer?v.Integer:v.Number}])}if(t[0]===s.Percentage&&r[0]===s.Percentage){const n=t[4].value-r[4].value;return new e([s.Percentage,n.toString()+"%",t[2],r[3],{value:n}])}if(t[0]===s.Dimension&&r[0]===s.Dimension&&(r=convertUnit(t,r),toLowerCaseAZ(t[4].unit)===toLowerCaseAZ(r[4].unit))){const n=t[4].value-r[4].value;return new e([s.Dimension,n.toString()+t[4].unit,t[2],r[3],{value:n,type:t[4].type===v.Integer&&r[4].type===v.Integer?v.Integer:v.Number,unit:t[4].unit}])}return-1}function solveLog(e,t){if(1===t.length){const r=t[0];if(!r||!n(r))return-1;const u=r.value;if(u[0]!==s.Number)return-1;return numberToCalculation(e,Math.log(u[4].value))}if(2===t.length){const r=t[0];if(!r||!n(r))return-1;const u=r.value;if(u[0]!==s.Number)return-1;const i=t[1];if(!i||!n(i))return-1;const a=i.value;if(a[0]!==s.Number)return-1;return numberToCalculation(e,Math.log(u[4].value)/Math.log(a[4].value))}return-1}const Z=new Map([["abs",function abs(e,n){return singleNodeSolver(e,n,solveAbs)}],["acos",function acos(e,n){return singleNodeSolver(e,n,solveACos)}],["asin",function asin(e,n){return singleNodeSolver(e,n,solveASin)}],["atan",function atan(e,n){return singleNodeSolver(e,n,solveATan)}],["atan2",function atan2(e,n){return twoCommaSeparatedNodesSolver(e,n,solveATan2)}],["calc",calc$1],["clamp",function clamp(e,u){const i=resolveGlobalsAndConstants([...e.value.filter((e=>!t(e)&&!r(e)))],u),o=[],l=[],c=[];{let e=o;for(let t=0;t!t(e)&&!r(e)))],u);let o="";const l=[],c=[];{let e=l;for(let t=0;t!t(e)&&!r(e)))],a);if(1===o.length&&n(o[0]))return{inputs:[o[0]],operation:unary};let l=0;for(;l!t(e)&&!r(e)))],n),o=solve(calc$1(new a([s.Function,"calc(",-1,-1,{value:"calc"}],[s.CloseParen,")",-1,-1,void 0],i),n));return-1===o?-1:u(e,o)}function twoCommaSeparatedNodesSolver(e,u,i){const o=resolveGlobalsAndConstants([...e.value.filter((e=>!t(e)&&!r(e)))],u),l=[],c=[];{let e=l;for(let t=0;t!t(e)&&!r(e)))],u),l=[];{const e=[];let t=[];for(let r=0;re.map((e=>N(...e.tokens()))).join(""))).join(",")}function calcFromComponentValues(e,n){const t=tokenizeGlobals(n?.globals);return c(e,(e=>{if(i(e)){const r=Z.get(toLowerCaseAZ(e.getName()));if(r){const u=patchCalcResult(solve(r(e,t)),n);if(-1!==u)return u}}}))}const z=new Set(Z.keys());export{calc,calcFromComponentValues,z as mathFunctionNames}; diff --git a/packages/css-calc/dist/operation/addition.d.ts b/packages/css-calc/dist/operation/addition.d.ts deleted file mode 100644 index 70e02cfd4..000000000 --- a/packages/css-calc/dist/operation/addition.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import { TokenNode } from '@csstools/css-parser-algorithms'; -export declare function addition(inputs: Array): TokenNode | -1; diff --git a/packages/css-calc/dist/operation/division.d.ts b/packages/css-calc/dist/operation/division.d.ts deleted file mode 100644 index 5d6b01fdd..000000000 --- a/packages/css-calc/dist/operation/division.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import { TokenNode } from '@csstools/css-parser-algorithms'; -export declare function division(inputs: Array): TokenNode | -1; diff --git a/packages/css-calc/dist/operation/multiplication.d.ts b/packages/css-calc/dist/operation/multiplication.d.ts deleted file mode 100644 index d48978d65..000000000 --- a/packages/css-calc/dist/operation/multiplication.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import { TokenNode } from '@csstools/css-parser-algorithms'; -export declare function multiplication(inputs: Array): TokenNode | -1; diff --git a/packages/css-calc/dist/operation/operation.d.ts b/packages/css-calc/dist/operation/operation.d.ts deleted file mode 100644 index aed9e0e38..000000000 --- a/packages/css-calc/dist/operation/operation.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import type { TokenNode } from '@csstools/css-parser-algorithms'; -export type Operation = (inputs: Array) => TokenNode | -1; diff --git a/packages/css-calc/dist/operation/subtraction.d.ts b/packages/css-calc/dist/operation/subtraction.d.ts deleted file mode 100644 index 0ac3f6bed..000000000 --- a/packages/css-calc/dist/operation/subtraction.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import { TokenNode } from '@csstools/css-parser-algorithms'; -export declare function subtraction(inputs: Array): TokenNode | -1; diff --git a/packages/css-calc/dist/operation/unary.d.ts b/packages/css-calc/dist/operation/unary.d.ts deleted file mode 100644 index b27463ecb..000000000 --- a/packages/css-calc/dist/operation/unary.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import type { TokenNode } from '@csstools/css-parser-algorithms'; -export declare function unary(inputs: Array): TokenNode | -1; diff --git a/packages/css-calc/dist/options.d.ts b/packages/css-calc/dist/options.d.ts deleted file mode 100644 index f24a05fd4..000000000 --- a/packages/css-calc/dist/options.d.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { GlobalsWithStrings } from './util/globals'; -export type conversionOptions = { - /** - * Pass global values as a map of key value pairs. - */ - globals?: GlobalsWithStrings; - /** - * The default precision is fairly high. - * It aims to be high enough to make rounding unnoticeable in the browser. - * You can set it to a lower number to suite your needs. - */ - precision?: number; - /** - * By default this package will try to preserve units. - * The heuristic to do this is very simplistic. - * We take the first unit we encounter and try to convert other dimensions to that unit. - * - * This better matches what users expect from a CSS dev tool. - * - * If you want to have outputs that are closes to CSS serialized values you can set `true`. - */ - toCanonicalUnits?: boolean; -}; diff --git a/packages/css-calc/dist/unit-conversions/canonical.d.ts b/packages/css-calc/dist/unit-conversions/canonical.d.ts deleted file mode 100644 index 1c593d502..000000000 --- a/packages/css-calc/dist/unit-conversions/canonical.d.ts +++ /dev/null @@ -1 +0,0 @@ -export declare const canonicalUnits: Record; diff --git a/packages/css-calc/dist/unit-conversions/cm.d.ts b/packages/css-calc/dist/unit-conversions/cm.d.ts deleted file mode 100644 index 030a42d8a..000000000 --- a/packages/css-calc/dist/unit-conversions/cm.d.ts +++ /dev/null @@ -1 +0,0 @@ -export declare const convert_cm: Map number>; diff --git a/packages/css-calc/dist/unit-conversions/deg.d.ts b/packages/css-calc/dist/unit-conversions/deg.d.ts deleted file mode 100644 index 7e0fb6c0a..000000000 --- a/packages/css-calc/dist/unit-conversions/deg.d.ts +++ /dev/null @@ -1 +0,0 @@ -export declare const convert_deg: Map number>; diff --git a/packages/css-calc/dist/unit-conversions/grad.d.ts b/packages/css-calc/dist/unit-conversions/grad.d.ts deleted file mode 100644 index 9423ffcfa..000000000 --- a/packages/css-calc/dist/unit-conversions/grad.d.ts +++ /dev/null @@ -1 +0,0 @@ -export declare const convert_grad: Map number>; diff --git a/packages/css-calc/dist/unit-conversions/hz.d.ts b/packages/css-calc/dist/unit-conversions/hz.d.ts deleted file mode 100644 index 9957a80e1..000000000 --- a/packages/css-calc/dist/unit-conversions/hz.d.ts +++ /dev/null @@ -1 +0,0 @@ -export declare const convert_hz: Map number>; diff --git a/packages/css-calc/dist/unit-conversions/in.d.ts b/packages/css-calc/dist/unit-conversions/in.d.ts deleted file mode 100644 index 5bf4ed817..000000000 --- a/packages/css-calc/dist/unit-conversions/in.d.ts +++ /dev/null @@ -1 +0,0 @@ -export declare const convert_in: Map number>; diff --git a/packages/css-calc/dist/unit-conversions/index.d.ts b/packages/css-calc/dist/unit-conversions/index.d.ts deleted file mode 100644 index b93c1175e..000000000 --- a/packages/css-calc/dist/unit-conversions/index.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -import type { CSSToken } from '@csstools/css-tokenizer'; -export declare function convertUnit(a: CSSToken, b: T): T; -export declare function toCanonicalUnit(a: T): T; diff --git a/packages/css-calc/dist/unit-conversions/khz.d.ts b/packages/css-calc/dist/unit-conversions/khz.d.ts deleted file mode 100644 index c1df1229a..000000000 --- a/packages/css-calc/dist/unit-conversions/khz.d.ts +++ /dev/null @@ -1 +0,0 @@ -export declare const convert_khz: Map number>; diff --git a/packages/css-calc/dist/unit-conversions/mm.d.ts b/packages/css-calc/dist/unit-conversions/mm.d.ts deleted file mode 100644 index 570b24476..000000000 --- a/packages/css-calc/dist/unit-conversions/mm.d.ts +++ /dev/null @@ -1 +0,0 @@ -export declare const convert_mm: Map number>; diff --git a/packages/css-calc/dist/unit-conversions/ms.d.ts b/packages/css-calc/dist/unit-conversions/ms.d.ts deleted file mode 100644 index 68d9231d3..000000000 --- a/packages/css-calc/dist/unit-conversions/ms.d.ts +++ /dev/null @@ -1 +0,0 @@ -export declare const convert_ms: Map number>; diff --git a/packages/css-calc/dist/unit-conversions/pc.d.ts b/packages/css-calc/dist/unit-conversions/pc.d.ts deleted file mode 100644 index d13b7da9b..000000000 --- a/packages/css-calc/dist/unit-conversions/pc.d.ts +++ /dev/null @@ -1 +0,0 @@ -export declare const convert_pc: Map number>; diff --git a/packages/css-calc/dist/unit-conversions/pt.d.ts b/packages/css-calc/dist/unit-conversions/pt.d.ts deleted file mode 100644 index 09407c956..000000000 --- a/packages/css-calc/dist/unit-conversions/pt.d.ts +++ /dev/null @@ -1 +0,0 @@ -export declare const convert_pt: Map number>; diff --git a/packages/css-calc/dist/unit-conversions/px.d.ts b/packages/css-calc/dist/unit-conversions/px.d.ts deleted file mode 100644 index 641ea77f5..000000000 --- a/packages/css-calc/dist/unit-conversions/px.d.ts +++ /dev/null @@ -1 +0,0 @@ -export declare const convert_px: Map number>; diff --git a/packages/css-calc/dist/unit-conversions/q.d.ts b/packages/css-calc/dist/unit-conversions/q.d.ts deleted file mode 100644 index 5862e51de..000000000 --- a/packages/css-calc/dist/unit-conversions/q.d.ts +++ /dev/null @@ -1 +0,0 @@ -export declare const convert_q: Map number>; diff --git a/packages/css-calc/dist/unit-conversions/rad.d.ts b/packages/css-calc/dist/unit-conversions/rad.d.ts deleted file mode 100644 index 70faf8e9e..000000000 --- a/packages/css-calc/dist/unit-conversions/rad.d.ts +++ /dev/null @@ -1 +0,0 @@ -export declare const convert_rad: Map number>; diff --git a/packages/css-calc/dist/unit-conversions/s.d.ts b/packages/css-calc/dist/unit-conversions/s.d.ts deleted file mode 100644 index 8240e359c..000000000 --- a/packages/css-calc/dist/unit-conversions/s.d.ts +++ /dev/null @@ -1 +0,0 @@ -export declare const convert_s: Map number>; diff --git a/packages/css-calc/dist/unit-conversions/turn.d.ts b/packages/css-calc/dist/unit-conversions/turn.d.ts deleted file mode 100644 index e721ff8e2..000000000 --- a/packages/css-calc/dist/unit-conversions/turn.d.ts +++ /dev/null @@ -1 +0,0 @@ -export declare const convert_turn: Map number>; diff --git a/packages/css-calc/dist/util/canonical-unit.d.ts b/packages/css-calc/dist/util/canonical-unit.d.ts deleted file mode 100644 index 49f5e457e..000000000 --- a/packages/css-calc/dist/util/canonical-unit.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import type { FunctionNode, TokenNode } from '@csstools/css-parser-algorithms'; -export declare function patchCanonicalUnit(x: TokenNode | FunctionNode | -1): TokenNode | FunctionNode | -1; diff --git a/packages/css-calc/dist/util/globals.d.ts b/packages/css-calc/dist/util/globals.d.ts deleted file mode 100644 index c9e43b74f..000000000 --- a/packages/css-calc/dist/util/globals.d.ts +++ /dev/null @@ -1,4 +0,0 @@ -import type { TokenDimension, TokenNumber, TokenPercentage } from '@csstools/css-tokenizer'; -export type Globals = Map; -export type GlobalsWithStrings = Map; -export declare function tokenizeGlobals(x: GlobalsWithStrings | undefined): Globals; diff --git a/packages/css-calc/dist/util/infinity.d.ts b/packages/css-calc/dist/util/infinity.d.ts deleted file mode 100644 index 588d3e131..000000000 --- a/packages/css-calc/dist/util/infinity.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import { FunctionNode, TokenNode } from '@csstools/css-parser-algorithms'; -export declare function patchInfinity(x: TokenNode | FunctionNode | -1): TokenNode | FunctionNode | -1; diff --git a/packages/css-calc/dist/util/kind-of-number.d.ts b/packages/css-calc/dist/util/kind-of-number.d.ts deleted file mode 100644 index dac78981a..000000000 --- a/packages/css-calc/dist/util/kind-of-number.d.ts +++ /dev/null @@ -1,5 +0,0 @@ -import { CSSToken, TokenDimension, TokenNumber, TokenPercentage } from '@csstools/css-tokenizer'; -export declare function isNumeric(x: CSSToken): x is TokenDimension | TokenPercentage | TokenNumber; -export declare function isDimensionOrNumber(x: CSSToken): x is TokenDimension | TokenNumber; -export declare function arrayOfSameNumeric(x: Array): x is Array; -export declare function twoOfSameNumeric(x: T, y: CSSToken): y is T; diff --git a/packages/css-calc/dist/util/minus-zero.d.ts b/packages/css-calc/dist/util/minus-zero.d.ts deleted file mode 100644 index 67b9e553f..000000000 --- a/packages/css-calc/dist/util/minus-zero.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import type { FunctionNode, TokenNode } from '@csstools/css-parser-algorithms'; -export declare function patchMinusZero(x: TokenNode | FunctionNode | -1): TokenNode | FunctionNode | -1; diff --git a/packages/css-calc/dist/util/nan.d.ts b/packages/css-calc/dist/util/nan.d.ts deleted file mode 100644 index a7e03354a..000000000 --- a/packages/css-calc/dist/util/nan.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import { FunctionNode, TokenNode } from '@csstools/css-parser-algorithms'; -export declare function patchNaN(x: TokenNode | FunctionNode | -1): TokenNode | FunctionNode | -1; diff --git a/packages/css-calc/dist/util/patch-result.d.ts b/packages/css-calc/dist/util/patch-result.d.ts deleted file mode 100644 index 03330b3e4..000000000 --- a/packages/css-calc/dist/util/patch-result.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -import { FunctionNode, TokenNode } from '@csstools/css-parser-algorithms'; -import { conversionOptions } from '../options'; -export declare function patchCalcResult(x: TokenNode | FunctionNode | -1, options?: conversionOptions): TokenNode | FunctionNode | -1; diff --git a/packages/css-calc/dist/util/precision.d.ts b/packages/css-calc/dist/util/precision.d.ts deleted file mode 100644 index 424909c1d..000000000 --- a/packages/css-calc/dist/util/precision.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import type { FunctionNode, TokenNode } from '@csstools/css-parser-algorithms'; -export declare function patchPrecision(x: TokenNode | FunctionNode | -1, precision?: number): TokenNode | FunctionNode | -1; diff --git a/packages/css-calc/dist/util/to-lower-case-a-z.d.ts b/packages/css-calc/dist/util/to-lower-case-a-z.d.ts deleted file mode 100644 index 396b252e7..000000000 --- a/packages/css-calc/dist/util/to-lower-case-a-z.d.ts +++ /dev/null @@ -1 +0,0 @@ -export declare function toLowerCaseAZ(x: string): string; diff --git a/packages/css-calc/package.json b/packages/css-calc/package.json index 3744fe1e9..07f478812 100644 --- a/packages/css-calc/package.json +++ b/packages/css-calc/package.json @@ -27,15 +27,18 @@ "engines": { "node": "^14 || ^16 || >=18" }, + "type": "module", "main": "dist/index.cjs", "module": "dist/index.mjs", - "types": "dist/index.d.ts", "exports": { ".": { - "types": "./dist/index.d.ts", - "import": "./dist/index.mjs", - "require": "./dist/index.cjs", - "default": "./dist/index.mjs" + "import": { + "types": "./dist/index.d.ts", + "default": "./dist/index.mjs" + }, + "require": { + "default": "./dist/index.cjs" + } } }, "files": [ diff --git a/packages/css-calc/src/index.ts b/packages/css-calc/src/index.ts index ae5bf76ea..53e0ed9b2 100644 --- a/packages/css-calc/src/index.ts +++ b/packages/css-calc/src/index.ts @@ -1,4 +1,4 @@ -export type { conversionOptions } from './options'; +export type { conversionOptions, GlobalsWithStrings } from './options'; import type { conversionOptions } from './options'; import { ComponentValue, isFunctionNode, parseCommaSeparatedListOfComponentValues } from '@csstools/css-parser-algorithms'; import { mathFunctions } from './functions/calc'; diff --git a/packages/css-calc/src/options.ts b/packages/css-calc/src/options.ts index 2c1a9e279..2c994646f 100644 --- a/packages/css-calc/src/options.ts +++ b/packages/css-calc/src/options.ts @@ -1,4 +1,5 @@ import { GlobalsWithStrings } from './util/globals'; +export type { GlobalsWithStrings } from './util/globals'; export type conversionOptions = { /** diff --git a/packages/css-color-parser/CHANGELOG.md b/packages/css-color-parser/CHANGELOG.md index 15889d900..5cc63b317 100644 --- a/packages/css-color-parser/CHANGELOG.md +++ b/packages/css-color-parser/CHANGELOG.md @@ -4,7 +4,7 @@ - Add the `Experimental` syntax flag, to be used in future features. - Add a `serializeHSL` function. -- Small fixes in type definitions +- Fix type definitions - Improve JS Doc comments ### 1.4.0 diff --git a/packages/css-color-parser/api-extractor.json b/packages/css-color-parser/api-extractor.json new file mode 100644 index 000000000..42058be51 --- /dev/null +++ b/packages/css-color-parser/api-extractor.json @@ -0,0 +1,4 @@ +{ + "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json", + "extends": "../../api-extractor.json" +} diff --git a/packages/css-color-parser/dist/color-data.d.ts b/packages/css-color-parser/dist/color-data.d.ts deleted file mode 100644 index 1b41b4beb..000000000 --- a/packages/css-color-parser/dist/color-data.d.ts +++ /dev/null @@ -1,61 +0,0 @@ -import type { Color } from '@csstools/color-helpers'; -import type { ComponentValue } from '@csstools/css-parser-algorithms'; -import { ColorNotation } from './color-notation'; -import { TokenNumber } from '@csstools/css-tokenizer'; -export type ColorData = { - colorNotation: ColorNotation; - channels: Color; - alpha: number | ComponentValue; - syntaxFlags: Set; -}; -export declare enum SyntaxFlag { - /** Is a color keyword, e.g. `transparent`, `currentColor`, ... */ - ColorKeyword = "color-keyword", - /** Has an explicit alpha channel */ - HasAlpha = "has-alpha", - /** Has a channel with a dimension value, e.g. `50deg` */ - HasDimensionValues = "has-dimension-values", - /** Has a channel with the `none` keyword */ - HasNoneKeywords = "has-none-keywords", - /** Has a channel with a number value */ - HasNumberValues = "has-number-values", - /** Has an alpha channel with a percentage value */ - HasPercentageAlpha = "has-percentage-alpha", - /** Has a channel with a percentage value */ - HasPercentageValues = "has-percentage-values", - /** Has an alpha channel with a `var()` function value */ - HasVariableAlpha = "has-variable-alpha", - /** Is Hex notation */ - Hex = "hex", - /** Is legacy HSL, e.g. `hsl(50deg, 0%, 0%)` */ - LegacyHSL = "legacy-hsl", - /** Is legacy RGB, e.g. `rgb(0, 0, 0)` */ - LegacyRGB = "legacy-rgb", - /** Is a named color, e.g. `red`, `blue` */ - NamedColor = "named-color", - /** Is a relative color syntax, e.g. `rgb(from purple r g b)` */ - RelativeColorSyntax = "relative-color-syntax", - /** Is a mixed color, e.g. `color-mix(in oklch, red, blue)` */ - ColorMix = "color-mix", - /** Is an experimental color syntax */ - Experimental = "experimental" -} -export declare function colorData_to_XYZ_D50(colorData: ColorData): ColorData; -export declare function colorDataTo(colorData: ColorData, toNotation: ColorNotation): ColorData; -export declare function convertPowerlessComponentsToZeroValuesForDisplay(a: Color, colorNotation: ColorNotation): Color; -export declare function normalizeRelativeColorDataChannels(x: ColorData): Map; -export declare function noneToZeroInRelativeColorDataChannels(x: Map): Map; -/** - * Check if a color data object fits the `sRGB` gamut. - * - * @param {ColorData} x - The color data to be checked. - * @returns {boolean} Whether the color data fits the `sRGB` gamut. - */ -export declare function colorDataFitsRGB_Gamut(x: ColorData): boolean; -/** - * Check if a color data object fits the `display-p3` gamut. - * - * @param {ColorData} x - The color data to be checked. - * @returns {boolean} Whether the color data fits the `display-p3` gamut. - */ -export declare function colorDataFitsDisplayP3_Gamut(x: ColorData): boolean; diff --git a/packages/css-color-parser/dist/color-notation.d.ts b/packages/css-color-parser/dist/color-notation.d.ts deleted file mode 100644 index 2349b20fd..000000000 --- a/packages/css-color-parser/dist/color-notation.d.ts +++ /dev/null @@ -1,34 +0,0 @@ -export declare enum ColorNotation { - /** Adobe 1999, expressed through `color(a98-rgb 0 0 0)` */ - A98_RGB = "a98-rgb", - /** Display P3, expressed through `color(display-p3 0 0 0)` */ - Display_P3 = "display-p3", - /** Hex, expressed through `#000` */ - HEX = "hex", - /** HSL, expressed through `hsl(0 0% 0%)` */ - HSL = "hsl", - /** HWB, expressed through `hwb(0 0% 0%)` */ - HWB = "hwb", - /** LCH, expressed through `lch(0 0% 0deg)` */ - LCH = "lch", - /** Lab, expressed through `lab(0 0 0)` */ - Lab = "lab", - /** Linear sRGB, expressed through `color(linear-srgb 0 0 0)` */ - Linear_sRGB = "srgb-linear", - /** Oklch, expressed through `oklch(0 0% 0deg)` */ - OKLCH = "oklch", - /** Oklab, expressed through `oklab(0 0 0)` */ - OKLab = "oklab", - /** ProPhoto RGB, expressed through `color(prophoto-rgb 0 0 0)` */ - ProPhoto_RGB = "prophoto-rgb", - /** RGB, expressed through `rgb(0 0 0)` */ - RGB = "rgb", - /** sRGB, expressed through `color(srgb 0 0 0)` */ - sRGB = "srgb", - /** Rec. 2020, expressed through `color(rec2020 0 0 0)` */ - Rec2020 = "rec2020", - /** XYZ, expressed through `color(xyz-d50 0 0 0)` */ - XYZ_D50 = "xyz-d50", - /** XYZ, expressed through `color(xyz-d65 0 0 0)` */ - XYZ_D65 = "xyz-d65" -} diff --git a/packages/css-color-parser/dist/color-parser.d.ts b/packages/css-color-parser/dist/color-parser.d.ts deleted file mode 100644 index 325c0657b..000000000 --- a/packages/css-color-parser/dist/color-parser.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -import type { ColorData } from './color-data'; -import type { ComponentValue } from '@csstools/css-parser-algorithms'; -export type ColorParser = (x: ComponentValue) => ColorData | false; diff --git a/packages/css-color-parser/dist/functions/color-keyword.d.ts b/packages/css-color-parser/dist/functions/color-keyword.d.ts deleted file mode 100644 index 6652208f2..000000000 --- a/packages/css-color-parser/dist/functions/color-keyword.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import type { ColorData } from '../color-data'; -export declare function colorKeyword(name: string): ColorData | false; diff --git a/packages/css-color-parser/dist/functions/color-mix.d.ts b/packages/css-color-parser/dist/functions/color-mix.d.ts deleted file mode 100644 index 8fc6aeda8..000000000 --- a/packages/css-color-parser/dist/functions/color-mix.d.ts +++ /dev/null @@ -1,4 +0,0 @@ -import type { ColorData } from '../color-data'; -import type { ColorParser } from '../color-parser'; -import type { FunctionNode } from '@csstools/css-parser-algorithms'; -export declare function colorMix(colorMixNode: FunctionNode, colorParser: ColorParser): ColorData | false; diff --git a/packages/css-color-parser/dist/functions/color-normalize-channel-values.d.ts b/packages/css-color-parser/dist/functions/color-normalize-channel-values.d.ts deleted file mode 100644 index 51b6624d4..000000000 --- a/packages/css-color-parser/dist/functions/color-normalize-channel-values.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -import type { ColorData } from '../color-data'; -import { CSSToken } from '@csstools/css-tokenizer'; -export declare function normalize_Color_ChannelValues(token: CSSToken, index: number, colorData: ColorData): CSSToken | false; diff --git a/packages/css-color-parser/dist/functions/color.d.ts b/packages/css-color-parser/dist/functions/color.d.ts deleted file mode 100644 index 34b95e2c3..000000000 --- a/packages/css-color-parser/dist/functions/color.d.ts +++ /dev/null @@ -1,4 +0,0 @@ -import { ColorData } from '../color-data'; -import type { ColorParser } from '../color-parser'; -import { FunctionNode } from '@csstools/css-parser-algorithms'; -export declare function color(colorFunctionNode: FunctionNode, colorParser: ColorParser): ColorData | false; diff --git a/packages/css-color-parser/dist/functions/hex.d.ts b/packages/css-color-parser/dist/functions/hex.d.ts deleted file mode 100644 index 8b66473e0..000000000 --- a/packages/css-color-parser/dist/functions/hex.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -import type { ColorData } from '../color-data'; -import type { TokenHash } from '@csstools/css-tokenizer'; -export declare function hex(hexToken: TokenHash): ColorData | false; diff --git a/packages/css-color-parser/dist/functions/hsl-normalize-channel-values.d.ts b/packages/css-color-parser/dist/functions/hsl-normalize-channel-values.d.ts deleted file mode 100644 index 068bcae7e..000000000 --- a/packages/css-color-parser/dist/functions/hsl-normalize-channel-values.d.ts +++ /dev/null @@ -1,4 +0,0 @@ -import type { ColorData } from '../color-data'; -import { CSSToken } from '@csstools/css-tokenizer'; -export declare function normalize_legacy_HSL_ChannelValues(token: CSSToken, index: number, colorData: ColorData): CSSToken | false; -export declare function normalize_modern_HSL_ChannelValues(token: CSSToken, index: number, colorData: ColorData): CSSToken | false; diff --git a/packages/css-color-parser/dist/functions/hsl.d.ts b/packages/css-color-parser/dist/functions/hsl.d.ts deleted file mode 100644 index 919acdda6..000000000 --- a/packages/css-color-parser/dist/functions/hsl.d.ts +++ /dev/null @@ -1,4 +0,0 @@ -import type { ColorData } from '../color-data'; -import type { ColorParser } from '../color-parser'; -import { FunctionNode } from '@csstools/css-parser-algorithms'; -export declare function hsl(hslNode: FunctionNode, colorParser: ColorParser): ColorData | false; diff --git a/packages/css-color-parser/dist/functions/hue-normalize-channel-value.d.ts b/packages/css-color-parser/dist/functions/hue-normalize-channel-value.d.ts deleted file mode 100644 index 41a96c643..000000000 --- a/packages/css-color-parser/dist/functions/hue-normalize-channel-value.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -import type { TokenNumber } from '@csstools/css-tokenizer'; -import { CSSToken } from '@csstools/css-tokenizer'; -export declare function normalizeHue(token: CSSToken): TokenNumber | false; diff --git a/packages/css-color-parser/dist/functions/hwb-normalize-channel-values.d.ts b/packages/css-color-parser/dist/functions/hwb-normalize-channel-values.d.ts deleted file mode 100644 index 81da6aacb..000000000 --- a/packages/css-color-parser/dist/functions/hwb-normalize-channel-values.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -import type { ColorData } from '../color-data'; -import { CSSToken } from '@csstools/css-tokenizer'; -export declare function normalize_HWB_ChannelValues(token: CSSToken, index: number, colorData: ColorData): CSSToken | false; diff --git a/packages/css-color-parser/dist/functions/hwb.d.ts b/packages/css-color-parser/dist/functions/hwb.d.ts deleted file mode 100644 index 1ddffe98d..000000000 --- a/packages/css-color-parser/dist/functions/hwb.d.ts +++ /dev/null @@ -1,4 +0,0 @@ -import type { ColorData } from '../color-data'; -import type { ColorParser } from '../color-parser'; -import type { FunctionNode } from '@csstools/css-parser-algorithms'; -export declare function hwb(hwbNode: FunctionNode, colorParser: ColorParser): ColorData | false; diff --git a/packages/css-color-parser/dist/functions/lab-normalize-channel-values.d.ts b/packages/css-color-parser/dist/functions/lab-normalize-channel-values.d.ts deleted file mode 100644 index 73587504c..000000000 --- a/packages/css-color-parser/dist/functions/lab-normalize-channel-values.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -import type { ColorData } from '../color-data'; -import { CSSToken } from '@csstools/css-tokenizer'; -export declare function normalize_Lab_ChannelValues(token: CSSToken, index: number, colorData: ColorData): CSSToken | false; diff --git a/packages/css-color-parser/dist/functions/lab.d.ts b/packages/css-color-parser/dist/functions/lab.d.ts deleted file mode 100644 index fbbf35aad..000000000 --- a/packages/css-color-parser/dist/functions/lab.d.ts +++ /dev/null @@ -1,4 +0,0 @@ -import type { ColorData } from '../color-data'; -import type { ColorParser } from '../color-parser'; -import type { FunctionNode } from '@csstools/css-parser-algorithms'; -export declare function lab(labNode: FunctionNode, colorParser: ColorParser): ColorData | false; diff --git a/packages/css-color-parser/dist/functions/lch-normalize-channel-values.d.ts b/packages/css-color-parser/dist/functions/lch-normalize-channel-values.d.ts deleted file mode 100644 index a2227e446..000000000 --- a/packages/css-color-parser/dist/functions/lch-normalize-channel-values.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -import type { ColorData } from '../color-data'; -import { CSSToken } from '@csstools/css-tokenizer'; -export declare function normalize_LCH_ChannelValues(token: CSSToken, index: number, colorData: ColorData): CSSToken | false; diff --git a/packages/css-color-parser/dist/functions/lch.d.ts b/packages/css-color-parser/dist/functions/lch.d.ts deleted file mode 100644 index 917889031..000000000 --- a/packages/css-color-parser/dist/functions/lch.d.ts +++ /dev/null @@ -1,4 +0,0 @@ -import type { ColorData } from '../color-data'; -import type { ColorParser } from '../color-parser'; -import type { FunctionNode } from '@csstools/css-parser-algorithms'; -export declare function lch(lchNode: FunctionNode, colorParser: ColorParser): ColorData | false; diff --git a/packages/css-color-parser/dist/functions/named-color.d.ts b/packages/css-color-parser/dist/functions/named-color.d.ts deleted file mode 100644 index 376a093a6..000000000 --- a/packages/css-color-parser/dist/functions/named-color.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import type { ColorData } from '../color-data'; -export declare function namedColor(name: string): ColorData | false; diff --git a/packages/css-color-parser/dist/functions/normalize-channel-values.d.ts b/packages/css-color-parser/dist/functions/normalize-channel-values.d.ts deleted file mode 100644 index c32172fdf..000000000 --- a/packages/css-color-parser/dist/functions/normalize-channel-values.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -import type { ColorData } from '../color-data'; -import { CSSToken } from '@csstools/css-tokenizer'; -export type normalizeChannelValuesFn = (token: CSSToken, index: number, colorData: ColorData) => CSSToken | false; diff --git a/packages/css-color-parser/dist/functions/normalize.d.ts b/packages/css-color-parser/dist/functions/normalize.d.ts deleted file mode 100644 index 0b57af5e4..000000000 --- a/packages/css-color-parser/dist/functions/normalize.d.ts +++ /dev/null @@ -1 +0,0 @@ -export declare function normalize(x: number, scale: number, min: number, max: number): number; diff --git a/packages/css-color-parser/dist/functions/oklab-normalize-channel-values.d.ts b/packages/css-color-parser/dist/functions/oklab-normalize-channel-values.d.ts deleted file mode 100644 index 97b827928..000000000 --- a/packages/css-color-parser/dist/functions/oklab-normalize-channel-values.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -import type { ColorData } from '../color-data'; -import { CSSToken } from '@csstools/css-tokenizer'; -export declare function normalize_OKLab_ChannelValues(token: CSSToken, index: number, colorData: ColorData): CSSToken | false; diff --git a/packages/css-color-parser/dist/functions/oklab.d.ts b/packages/css-color-parser/dist/functions/oklab.d.ts deleted file mode 100644 index 96e03847b..000000000 --- a/packages/css-color-parser/dist/functions/oklab.d.ts +++ /dev/null @@ -1,4 +0,0 @@ -import type { ColorData } from '../color-data'; -import type { ColorParser } from '../color-parser'; -import type { FunctionNode } from '@csstools/css-parser-algorithms'; -export declare function oklab(oklabNode: FunctionNode, colorParser: ColorParser): ColorData | false; diff --git a/packages/css-color-parser/dist/functions/oklch-normalize-channel-values.d.ts b/packages/css-color-parser/dist/functions/oklch-normalize-channel-values.d.ts deleted file mode 100644 index afd514b38..000000000 --- a/packages/css-color-parser/dist/functions/oklch-normalize-channel-values.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -import type { ColorData } from '../color-data'; -import { CSSToken } from '@csstools/css-tokenizer'; -export declare function normalize_OKLCH_ChannelValues(token: CSSToken, index: number, colorData: ColorData): CSSToken | false; diff --git a/packages/css-color-parser/dist/functions/oklch.d.ts b/packages/css-color-parser/dist/functions/oklch.d.ts deleted file mode 100644 index d70197e74..000000000 --- a/packages/css-color-parser/dist/functions/oklch.d.ts +++ /dev/null @@ -1,4 +0,0 @@ -import type { ColorData } from '../color-data'; -import type { ColorParser } from '../color-parser'; -import type { FunctionNode } from '@csstools/css-parser-algorithms'; -export declare function oklch(oklchNode: FunctionNode, colorParser: ColorParser): ColorData | false; diff --git a/packages/css-color-parser/dist/functions/rgb-normalize-channel-values.d.ts b/packages/css-color-parser/dist/functions/rgb-normalize-channel-values.d.ts deleted file mode 100644 index eb3e89bcf..000000000 --- a/packages/css-color-parser/dist/functions/rgb-normalize-channel-values.d.ts +++ /dev/null @@ -1,4 +0,0 @@ -import type { ColorData } from '../color-data'; -import { CSSToken } from '@csstools/css-tokenizer'; -export declare function normalize_legacy_sRGB_ChannelValues(token: CSSToken, index: number, colorData: ColorData): CSSToken | false; -export declare function normalize_modern_sRGB_ChannelValues(token: CSSToken, index: number, colorData: ColorData): CSSToken | false; diff --git a/packages/css-color-parser/dist/functions/rgb.d.ts b/packages/css-color-parser/dist/functions/rgb.d.ts deleted file mode 100644 index c4aacca10..000000000 --- a/packages/css-color-parser/dist/functions/rgb.d.ts +++ /dev/null @@ -1,4 +0,0 @@ -import type { ColorData } from '../color-data'; -import type { ColorParser } from '../color-parser'; -import { FunctionNode } from '@csstools/css-parser-algorithms'; -export declare function rgb(rgbNode: FunctionNode, colorParser: ColorParser): ColorData | false; diff --git a/packages/css-color-parser/dist/functions/three-channel-legacy-syntax.d.ts b/packages/css-color-parser/dist/functions/three-channel-legacy-syntax.d.ts deleted file mode 100644 index 5bfe8c385..000000000 --- a/packages/css-color-parser/dist/functions/three-channel-legacy-syntax.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -import type { ColorData } from '../color-data'; -import type { FunctionNode } from '@csstools/css-parser-algorithms'; -import { ColorNotation } from '../color-notation'; -import { SyntaxFlag } from '../color-data'; -import { normalizeChannelValuesFn } from './normalize-channel-values'; -export declare function threeChannelLegacySyntax(colorFunctionNode: FunctionNode, normalizeChannelValues: normalizeChannelValuesFn, colorNotation: ColorNotation, syntaxFlags: Array): ColorData | false; diff --git a/packages/css-color-parser/dist/functions/three-channel-space-separated.d.ts b/packages/css-color-parser/dist/functions/three-channel-space-separated.d.ts deleted file mode 100644 index 8fb7e41b7..000000000 --- a/packages/css-color-parser/dist/functions/three-channel-space-separated.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { ColorData } from '../color-data'; -import { FunctionNode } from '@csstools/css-parser-algorithms'; -import { ColorNotation } from '../color-notation'; -import { SyntaxFlag } from '../color-data'; -import { normalizeChannelValuesFn } from './normalize-channel-values'; -import { ColorParser } from '../color-parser'; -export declare function threeChannelSpaceSeparated(colorFunctionNode: FunctionNode, normalizeChannelValues: normalizeChannelValuesFn, colorNotation: ColorNotation, syntaxFlags: Array, colorParser: ColorParser): ColorData | false; diff --git a/packages/css-color-parser/dist/gamut-mapping/p3.d.ts b/packages/css-color-parser/dist/gamut-mapping/p3.d.ts deleted file mode 100644 index d0130b521..000000000 --- a/packages/css-color-parser/dist/gamut-mapping/p3.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import { Color } from '@csstools/color-helpers'; -export declare function XYZ_D50_to_P3_Gamut(color: Color): Color; diff --git a/packages/css-color-parser/dist/gamut-mapping/srgb.d.ts b/packages/css-color-parser/dist/gamut-mapping/srgb.d.ts deleted file mode 100644 index 87b3ad800..000000000 --- a/packages/css-color-parser/dist/gamut-mapping/srgb.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import { Color } from '@csstools/color-helpers'; -export declare function XYZ_D50_to_sRGB_Gamut(color: Color): Color; diff --git a/packages/css-color-parser/dist/index.cjs b/packages/css-color-parser/dist/index.cjs index 21dcf0941..52d4c22c2 100644 --- a/packages/css-color-parser/dist/index.cjs +++ b/packages/css-color-parser/dist/index.cjs @@ -1 +1 @@ -"use strict";var e,o,n=require("@csstools/css-tokenizer"),a=require("@csstools/color-helpers"),t=require("@csstools/css-parser-algorithms"),r=require("@csstools/css-calc");function colorData_to_XYZ_D50(e){switch(e.colorNotation){case exports.ColorNotation.HEX:case exports.ColorNotation.RGB:case exports.ColorNotation.sRGB:return{...e,colorNotation:exports.ColorNotation.XYZ_D50,channels:a.xyz.sRGB_to_XYZ_D50(e.channels.map((e=>Number.isNaN(e)?0:e)))};case exports.ColorNotation.Linear_sRGB:return{...e,colorNotation:exports.ColorNotation.XYZ_D50,channels:a.xyz.lin_sRGB_to_XYZ_D50(e.channels.map((e=>Number.isNaN(e)?0:e)))};case exports.ColorNotation.Display_P3:return{...e,colorNotation:exports.ColorNotation.XYZ_D50,channels:a.xyz.P3_to_XYZ_D50(e.channels.map((e=>Number.isNaN(e)?0:e)))};case exports.ColorNotation.Rec2020:return{...e,colorNotation:exports.ColorNotation.XYZ_D50,channels:a.xyz.rec_2020_to_XYZ_D50(e.channels.map((e=>Number.isNaN(e)?0:e)))};case exports.ColorNotation.A98_RGB:return{...e,colorNotation:exports.ColorNotation.XYZ_D50,channels:a.xyz.a98_RGB_to_XYZ_D50(e.channels.map((e=>Number.isNaN(e)?0:e)))};case exports.ColorNotation.ProPhoto_RGB:return{...e,colorNotation:exports.ColorNotation.XYZ_D50,channels:a.xyz.ProPhoto_RGB_to_XYZ_D50(e.channels.map((e=>Number.isNaN(e)?0:e)))};case exports.ColorNotation.HSL:return{...e,colorNotation:exports.ColorNotation.XYZ_D50,channels:a.xyz.HSL_to_XYZ_D50(e.channels.map((e=>Number.isNaN(e)?0:e)))};case exports.ColorNotation.HWB:return{...e,colorNotation:exports.ColorNotation.XYZ_D50,channels:a.xyz.HWB_to_XYZ_D50(e.channels.map((e=>Number.isNaN(e)?0:e)))};case exports.ColorNotation.Lab:return{...e,colorNotation:exports.ColorNotation.XYZ_D50,channels:a.xyz.Lab_to_XYZ_D50(e.channels.map((e=>Number.isNaN(e)?0:e)))};case exports.ColorNotation.OKLab:return{...e,colorNotation:exports.ColorNotation.XYZ_D50,channels:a.xyz.OKLab_to_XYZ_D50(e.channels.map((e=>Number.isNaN(e)?0:e)))};case exports.ColorNotation.LCH:return{...e,colorNotation:exports.ColorNotation.XYZ_D50,channels:a.xyz.LCH_to_XYZ_D50(e.channels.map((e=>Number.isNaN(e)?0:e)))};case exports.ColorNotation.OKLCH:return{...e,colorNotation:exports.ColorNotation.XYZ_D50,channels:a.xyz.OKLCH_to_XYZ_D50(e.channels.map((e=>Number.isNaN(e)?0:e)))};case exports.ColorNotation.XYZ_D50:return{...e,colorNotation:exports.ColorNotation.XYZ_D50,channels:a.xyz.XYZ_D50_to_XYZ_D50(e.channels.map((e=>Number.isNaN(e)?0:e)))};case exports.ColorNotation.XYZ_D65:return{...e,colorNotation:exports.ColorNotation.XYZ_D50,channels:a.xyz.XYZ_D65_to_XYZ_D50(e.channels.map((e=>Number.isNaN(e)?0:e)))};default:throw new Error("Unsupported color notation")}}exports.ColorNotation=void 0,(e=exports.ColorNotation||(exports.ColorNotation={})).A98_RGB="a98-rgb",e.Display_P3="display-p3",e.HEX="hex",e.HSL="hsl",e.HWB="hwb",e.LCH="lch",e.Lab="lab",e.Linear_sRGB="srgb-linear",e.OKLCH="oklch",e.OKLab="oklab",e.ProPhoto_RGB="prophoto-rgb",e.RGB="rgb",e.sRGB="srgb",e.Rec2020="rec2020",e.XYZ_D50="xyz-d50",e.XYZ_D65="xyz-d65",exports.SyntaxFlag=void 0,(o=exports.SyntaxFlag||(exports.SyntaxFlag={})).ColorKeyword="color-keyword",o.HasAlpha="has-alpha",o.HasDimensionValues="has-dimension-values",o.HasNoneKeywords="has-none-keywords",o.HasNumberValues="has-number-values",o.HasPercentageAlpha="has-percentage-alpha",o.HasPercentageValues="has-percentage-values",o.HasVariableAlpha="has-variable-alpha",o.Hex="hex",o.LegacyHSL="legacy-hsl",o.LegacyRGB="legacy-rgb",o.NamedColor="named-color",o.RelativeColorSyntax="relative-color-syntax",o.ColorMix="color-mix",o.Experimental="experimental";const s=new Set([exports.ColorNotation.A98_RGB,exports.ColorNotation.Display_P3,exports.ColorNotation.HEX,exports.ColorNotation.Linear_sRGB,exports.ColorNotation.ProPhoto_RGB,exports.ColorNotation.RGB,exports.ColorNotation.sRGB,exports.ColorNotation.Rec2020,exports.ColorNotation.XYZ_D50,exports.ColorNotation.XYZ_D65]);function colorDataTo(e,o){const n={...e};if(e.colorNotation!==o){const e=colorData_to_XYZ_D50(n);switch(o){case exports.ColorNotation.HEX:case exports.ColorNotation.RGB:n.colorNotation=exports.ColorNotation.RGB,n.channels=a.xyz.XYZ_D50_to_sRGB(e.channels);break;case exports.ColorNotation.sRGB:n.colorNotation=exports.ColorNotation.sRGB,n.channels=a.xyz.XYZ_D50_to_sRGB(e.channels);break;case exports.ColorNotation.Linear_sRGB:n.colorNotation=exports.ColorNotation.Linear_sRGB,n.channels=a.xyz.XYZ_D50_to_lin_sRGB(e.channels);break;case exports.ColorNotation.Display_P3:n.colorNotation=exports.ColorNotation.Display_P3,n.channels=a.xyz.XYZ_D50_to_P3(e.channels);break;case exports.ColorNotation.Rec2020:n.colorNotation=exports.ColorNotation.Rec2020,n.channels=a.xyz.XYZ_D50_to_rec_2020(e.channels);break;case exports.ColorNotation.ProPhoto_RGB:n.colorNotation=exports.ColorNotation.ProPhoto_RGB,n.channels=a.xyz.XYZ_D50_to_ProPhoto(e.channels);break;case exports.ColorNotation.A98_RGB:n.colorNotation=exports.ColorNotation.A98_RGB,n.channels=a.xyz.XYZ_D50_to_a98_RGB(e.channels);break;case exports.ColorNotation.HSL:n.colorNotation=exports.ColorNotation.HSL,n.channels=a.xyz.XYZ_D50_to_HSL(e.channels);break;case exports.ColorNotation.HWB:n.colorNotation=exports.ColorNotation.HWB,n.channels=a.xyz.XYZ_D50_to_HWB(e.channels);break;case exports.ColorNotation.Lab:n.colorNotation=exports.ColorNotation.Lab,n.channels=a.xyz.XYZ_D50_to_Lab(e.channels);break;case exports.ColorNotation.LCH:n.colorNotation=exports.ColorNotation.LCH,n.channels=a.xyz.XYZ_D50_to_LCH(e.channels);break;case exports.ColorNotation.OKLCH:n.colorNotation=exports.ColorNotation.OKLCH,n.channels=a.xyz.XYZ_D50_to_OKLCH(e.channels);break;case exports.ColorNotation.OKLab:n.colorNotation=exports.ColorNotation.OKLab,n.channels=a.xyz.XYZ_D50_to_OKLab(e.channels);break;case exports.ColorNotation.XYZ_D50:n.colorNotation=exports.ColorNotation.XYZ_D50,n.channels=a.xyz.XYZ_D50_to_XYZ_D50(e.channels);break;case exports.ColorNotation.XYZ_D65:n.colorNotation=exports.ColorNotation.XYZ_D65,n.channels=a.xyz.XYZ_D50_to_XYZ_D65(e.channels);break;default:throw new Error("Unsupported color notation")}}else n.channels=e.channels.map((e=>Number.isNaN(e)?0:e));if(o===e.colorNotation)n.channels=carryForwardMissingComponents(e.channels,[0,1,2],n.channels,[0,1,2]);else if(s.has(o)&&s.has(e.colorNotation))n.channels=carryForwardMissingComponents(e.channels,[0,1,2],n.channels,[0,1,2]);else switch(o){case exports.ColorNotation.HSL:switch(e.colorNotation){case exports.ColorNotation.HWB:n.channels=carryForwardMissingComponents(e.channels,[0],n.channels,[0]);break;case exports.ColorNotation.Lab:case exports.ColorNotation.OKLab:n.channels=carryForwardMissingComponents(e.channels,[2],n.channels,[0]);break;case exports.ColorNotation.LCH:case exports.ColorNotation.OKLCH:n.channels=carryForwardMissingComponents(e.channels,[0,1,2],n.channels,[2,1,0])}break;case exports.ColorNotation.HWB:switch(e.colorNotation){case exports.ColorNotation.HSL:n.channels=carryForwardMissingComponents(e.channels,[0],n.channels,[0]);break;case exports.ColorNotation.LCH:case exports.ColorNotation.OKLCH:n.channels=carryForwardMissingComponents(e.channels,[0],n.channels,[2])}break;case exports.ColorNotation.Lab:case exports.ColorNotation.OKLab:switch(e.colorNotation){case exports.ColorNotation.HSL:n.channels=carryForwardMissingComponents(e.channels,[0],n.channels,[2]);break;case exports.ColorNotation.Lab:case exports.ColorNotation.OKLab:n.channels=carryForwardMissingComponents(e.channels,[0,1,2],n.channels,[0,1,2]);break;case exports.ColorNotation.LCH:case exports.ColorNotation.OKLCH:n.channels=carryForwardMissingComponents(e.channels,[0],n.channels,[0])}break;case exports.ColorNotation.LCH:case exports.ColorNotation.OKLCH:switch(e.colorNotation){case exports.ColorNotation.HSL:n.channels=carryForwardMissingComponents(e.channels,[0,1,2],n.channels,[2,1,0]);break;case exports.ColorNotation.HWB:n.channels=carryForwardMissingComponents(e.channels,[0],n.channels,[2]);break;case exports.ColorNotation.Lab:case exports.ColorNotation.OKLab:n.channels=carryForwardMissingComponents(e.channels,[0],n.channels,[0]);break;case exports.ColorNotation.LCH:case exports.ColorNotation.OKLCH:n.channels=carryForwardMissingComponents(e.channels,[0,1,2],n.channels,[0,1,2])}}return n.channels=convertPowerlessComponentsToMissingComponents(n.channels,o),n}function convertPowerlessComponentsToMissingComponents(e,o){const n=[...e];switch(o){case exports.ColorNotation.HSL:reducePrecision(n[1],4)<=0&&(n[0]=NaN);break;case exports.ColorNotation.HWB:Math.max(0,reducePrecision(n[1],4))+Math.max(0,reducePrecision(n[2],4))>=100&&(n[0]=NaN);break;case exports.ColorNotation.LCH:reducePrecision(n[1],4)<=0&&(n[2]=NaN);break;case exports.ColorNotation.OKLCH:reducePrecision(n[1],6)<=0&&(n[2]=NaN)}return n}function convertPowerlessComponentsToZeroValuesForDisplay(e,o){const n=[...e];switch(o){case exports.ColorNotation.HSL:(reducePrecision(n[2])<=0||reducePrecision(n[2])>=100)&&(n[0]=NaN,n[1]=NaN),reducePrecision(n[1])<=0&&(n[0]=NaN);break;case exports.ColorNotation.HWB:Math.max(0,reducePrecision(n[1]))+Math.max(0,reducePrecision(n[2]))>=100&&(n[0]=NaN);break;case exports.ColorNotation.Lab:(reducePrecision(n[0])<=0||reducePrecision(n[0])>=100)&&(n[1]=NaN,n[2]=NaN);break;case exports.ColorNotation.LCH:reducePrecision(n[1])<=0&&(n[2]=NaN),(reducePrecision(n[0])<=0||reducePrecision(n[0])>=100)&&(n[1]=NaN,n[2]=NaN);break;case exports.ColorNotation.OKLab:(reducePrecision(n[0])<=0||reducePrecision(n[0])>=1)&&(n[1]=NaN,n[2]=NaN);break;case exports.ColorNotation.OKLCH:reducePrecision(n[1])<=0&&(n[2]=NaN),(reducePrecision(n[0])<=0||reducePrecision(n[0])>=1)&&(n[1]=NaN,n[2]=NaN)}return n}function carryForwardMissingComponents(e,o,n,a){const t=[...n];for(const n of o)Number.isNaN(e[o[n]])&&(t[a[n]]=NaN);return t}function normalizeRelativeColorDataChannels(e){const o=new Map;switch(e.colorNotation){case exports.ColorNotation.RGB:case exports.ColorNotation.HEX:o.set("r",dummyNumberToken(255*e.channels[0])),o.set("g",dummyNumberToken(255*e.channels[1])),o.set("b",dummyNumberToken(255*e.channels[2])),"number"==typeof e.alpha&&o.set("alpha",dummyNumberToken(e.alpha));break;case exports.ColorNotation.HSL:o.set("h",dummyNumberToken(e.channels[0])),o.set("s",dummyNumberToken(e.channels[1])),o.set("l",dummyNumberToken(e.channels[2])),"number"==typeof e.alpha&&o.set("alpha",dummyNumberToken(e.alpha));break;case exports.ColorNotation.HWB:o.set("h",dummyNumberToken(e.channels[0])),o.set("w",dummyNumberToken(e.channels[1])),o.set("b",dummyNumberToken(e.channels[2])),"number"==typeof e.alpha&&o.set("alpha",dummyNumberToken(e.alpha));break;case exports.ColorNotation.Lab:case exports.ColorNotation.OKLab:o.set("l",dummyNumberToken(e.channels[0])),o.set("a",dummyNumberToken(e.channels[1])),o.set("b",dummyNumberToken(e.channels[2])),"number"==typeof e.alpha&&o.set("alpha",dummyNumberToken(e.alpha));break;case exports.ColorNotation.LCH:case exports.ColorNotation.OKLCH:o.set("l",dummyNumberToken(e.channels[0])),o.set("c",dummyNumberToken(e.channels[1])),o.set("h",dummyNumberToken(e.channels[2])),"number"==typeof e.alpha&&o.set("alpha",dummyNumberToken(e.alpha));break;case exports.ColorNotation.sRGB:case exports.ColorNotation.A98_RGB:case exports.ColorNotation.Display_P3:case exports.ColorNotation.Rec2020:case exports.ColorNotation.Linear_sRGB:case exports.ColorNotation.ProPhoto_RGB:o.set("r",dummyNumberToken(e.channels[0])),o.set("g",dummyNumberToken(e.channels[1])),o.set("b",dummyNumberToken(e.channels[2])),"number"==typeof e.alpha&&o.set("alpha",dummyNumberToken(e.alpha));break;case exports.ColorNotation.XYZ_D50:case exports.ColorNotation.XYZ_D65:o.set("x",dummyNumberToken(e.channels[0])),o.set("y",dummyNumberToken(e.channels[1])),o.set("z",dummyNumberToken(e.channels[2])),"number"==typeof e.alpha&&o.set("alpha",dummyNumberToken(e.alpha))}return o}function noneToZeroInRelativeColorDataChannels(e){const o=new Map(e);for(const[n,a]of e)Number.isNaN(a[4].value)&&o.set(n,dummyNumberToken(0));return o}function dummyNumberToken(e){return[n.TokenType.Number,e.toString(),-1,-1,{value:e,type:n.NumberType.Number}]}function reducePrecision(e,o=7){if(Number.isNaN(e))return 0;const n=Math.pow(10,o);return Math.round(e*n)/n}function normalize(e,o,n,a){return Math.min(Math.max(e/o,n),a)}const l=/[A-Z]/g;function toLowerCaseAZ(e){return e.replace(l,(e=>String.fromCharCode(e.charCodeAt(0)+32)))}function normalize_Color_ChannelValues(e,o,a){if(e[0]===n.TokenType.Ident&&"none"===toLowerCaseAZ(e[4].value))return a.syntaxFlags.add(exports.SyntaxFlag.HasNoneKeywords),[n.TokenType.Number,"none",e[2],e[3],{value:NaN,type:n.NumberType.Number}];if(e[0]===n.TokenType.Percentage){3!==o&&a.syntaxFlags.add(exports.SyntaxFlag.HasPercentageValues);let t=normalize(e[4].value,100,-1/0,1/0);return 3===o&&(t=normalize(e[4].value,100,0,1)),[n.TokenType.Number,t.toString(),e[2],e[3],{value:t,type:n.NumberType.Number}]}if(e[0]===n.TokenType.Number){3!==o&&a.syntaxFlags.add(exports.SyntaxFlag.HasNumberValues);let t=normalize(e[4].value,1,-1/0,1/0);return 3===o&&(t=normalize(e[4].value,1,0,1)),[n.TokenType.Number,t.toString(),e[2],e[3],{value:t,type:n.NumberType.Number}]}return!1}const i=new Set(["srgb","srgb-linear","display-p3","a98-rgb","prophoto-rgb","rec2020","xyz","xyz-d50","xyz-d65"]);function color$1(e,o){const a=[],s=[],l=[],u=[];let c,p,N=!1,m=!1;const h={colorNotation:exports.ColorNotation.sRGB,channels:[0,0,0],alpha:1,syntaxFlags:new Set([])};let y=a;for(let x=0;x=0){i=u.value[4].value;continue}}return!1}if(!l)return!1;a.push({color:l,percentage:i}),l=!1,i=!1}}if(l&&a.push({color:l,percentage:i}),2!==a.length)return!1;let u=a[0].percentage,c=a[1].percentage;return(!1===u||!(u<0||u>100))&&((!1===c||!(c<0||c>100))&&(!1===u&&!1===c?(u=50,c=50):!1!==u&&!1===c?c=100-u:!1===u&&!1!==c&&(u=100-c),(0!==u||0!==c)&&(!1!==u&&!1!==c&&(u+c>100&&(u=u/(u+c)*100,c=c/(u+c)*100),u+c<100&&(s=(u+c)/100,u=u/(u+c)*100,c=c/(u+c)*100),{a:{color:a[0].color,percentage:u},b:{color:a[1].color,percentage:c},alphaMultiplier:s}))))}function colorMixRectangular(e,o){if(!o)return!1;const n=o.a.color,a=o.b.color,t=o.a.percentage/100;let r=n.channels,s=a.channels,l=exports.ColorNotation.RGB,i=n.alpha;if("number"!=typeof i)return!1;let u=a.alpha;if("number"!=typeof u)return!1;switch(i=Number.isNaN(i)?u:i,u=Number.isNaN(u)?i:u,e){case"srgb":l=exports.ColorNotation.RGB;break;case"srgb-linear":l=exports.ColorNotation.Linear_sRGB;break;case"lab":l=exports.ColorNotation.Lab;break;case"oklab":l=exports.ColorNotation.OKLab;break;case"xyz-d50":l=exports.ColorNotation.XYZ_D50;break;case"xyz":case"xyz-d65":l=exports.ColorNotation.XYZ_D65}r=colorDataTo(n,l).channels,s=colorDataTo(a,l).channels,r[0]=fillInMissingComponent(r[0],s[0]),s[0]=fillInMissingComponent(s[0],r[0]),r[1]=fillInMissingComponent(r[1],s[1]),s[1]=fillInMissingComponent(s[1],r[1]),r[2]=fillInMissingComponent(r[2],s[2]),s[2]=fillInMissingComponent(s[2],r[2]),r[0]=premultiply(r[0],i),r[1]=premultiply(r[1],i),r[2]=premultiply(r[2],i),s[0]=premultiply(s[0],u),s[1]=premultiply(s[1],u),s[2]=premultiply(s[2],u);const c=interpolate(i,u,t),p={colorNotation:l,channels:[un_premultiply(interpolate(r[0],s[0],t),c),un_premultiply(interpolate(r[1],s[1],t),c),un_premultiply(interpolate(r[2],s[2],t),c)],alpha:c*o.alphaMultiplier,syntaxFlags:new Set([exports.SyntaxFlag.ColorMix])};return(o.a.color.syntaxFlags.has(exports.SyntaxFlag.Experimental)||o.b.color.syntaxFlags.has(exports.SyntaxFlag.Experimental))&&p.syntaxFlags.add(exports.SyntaxFlag.Experimental),p}function colorMixPolar(e,o,n){if(!n)return!1;const a=n.a.color,t=n.b.color,r=n.a.percentage/100;let s=a.channels,l=t.channels,i=0,u=0,c=0,p=0,N=0,m=0,h=exports.ColorNotation.RGB,y=a.alpha;if("number"!=typeof y)return!1;let x=t.alpha;if("number"!=typeof x)return!1;switch(y=Number.isNaN(y)?x:y,x=Number.isNaN(x)?y:x,e){case"hsl":h=exports.ColorNotation.HSL;break;case"hwb":h=exports.ColorNotation.HWB;break;case"lch":h=exports.ColorNotation.LCH;break;case"oklch":h=exports.ColorNotation.OKLCH}switch(s=colorDataTo(a,h).channels,l=colorDataTo(t,h).channels,e){case"hsl":case"hwb":i=s[0],u=l[0],c=s[1],p=l[1],N=s[2],m=l[2];break;case"lch":case"oklch":c=s[0],p=l[0],N=s[1],m=l[1],i=s[2],u=l[2]}i=fillInMissingComponent(i,u),Number.isNaN(i)&&(i=0),u=fillInMissingComponent(u,i),Number.isNaN(u)&&(u=0),c=fillInMissingComponent(c,p),p=fillInMissingComponent(p,c),N=fillInMissingComponent(N,m),m=fillInMissingComponent(m,N);const T=u-i;switch(o){case"shorter":T>180?i+=360:T<-180&&(u+=360);break;case"longer":-1800?i+=360:u+=360);break;case"increasing":T<0&&(u+=360);break;case"decreasing":T>0&&(i+=360);break;default:throw new Error("Unknown hue interpolation method")}c=premultiply(c,y),N=premultiply(N,y),p=premultiply(p,x),m=premultiply(m,x);let b=[0,0,0];const C=interpolate(y,x,r);switch(e){case"hsl":case"hwb":b=[interpolate(i,u,r),un_premultiply(interpolate(c,p,r),C),un_premultiply(interpolate(N,m,r),C)];break;case"lch":case"oklch":b=[un_premultiply(interpolate(c,p,r),C),un_premultiply(interpolate(N,m,r),C),interpolate(i,u,r)]}const d={colorNotation:h,channels:b,alpha:C*n.alphaMultiplier,syntaxFlags:new Set([exports.SyntaxFlag.ColorMix])};return(n.a.color.syntaxFlags.has(exports.SyntaxFlag.Experimental)||n.b.color.syntaxFlags.has(exports.SyntaxFlag.Experimental))&&d.syntaxFlags.add(exports.SyntaxFlag.Experimental),d}function fillInMissingComponent(e,o){return Number.isNaN(e)?o:e}function interpolate(e,o,n){return e*n+o*(1-n)}function premultiply(e,o){return Number.isNaN(o)?e:Number.isNaN(e)?NaN:e*o}function un_premultiply(e,o){return 0===o||Number.isNaN(o)?e:Number.isNaN(e)?NaN:e/o}function hex(e){const o=toLowerCaseAZ(e[4].value);if(o.match(/[^a-f0-9]/))return!1;const n={colorNotation:exports.ColorNotation.HEX,channels:[0,0,0],alpha:1,syntaxFlags:new Set([exports.SyntaxFlag.Hex])},a=o.length;if(3===a){const e=o[0],a=o[1],t=o[2];return n.channels=[parseInt(e+e,16)/255,parseInt(a+a,16)/255,parseInt(t+t,16)/255],n}if(6===a){const e=o[0]+o[1],a=o[2]+o[3],t=o[4]+o[5];return n.channels=[parseInt(e,16)/255,parseInt(a,16)/255,parseInt(t,16)/255],n}if(4===a){const e=o[0],a=o[1],t=o[2],r=o[3];return n.channels=[parseInt(e+e,16)/255,parseInt(a+a,16)/255,parseInt(t+t,16)/255],n.alpha=parseInt(r+r,16)/255,n.syntaxFlags.add(exports.SyntaxFlag.HasAlpha),n}if(8===a){const e=o[0]+o[1],a=o[2]+o[3],t=o[4]+o[5],r=o[6]+o[7];return n.channels=[parseInt(e,16)/255,parseInt(a,16)/255,parseInt(t,16)/255],n.alpha=parseInt(r,16)/255,n.syntaxFlags.add(exports.SyntaxFlag.HasAlpha),n}return!1}function normalizeHue(e){if(e[0]===n.TokenType.Number)return e[4].value=e[4].value%360,e[1]=e[4].value.toString(),e;if(e[0]===n.TokenType.Dimension){let o=e[4].value;switch(toLowerCaseAZ(e[4].unit)){case"deg":break;case"rad":o=180*e[4].value/Math.PI;break;case"grad":o=.9*e[4].value;break;case"turn":o=360*e[4].value;break;default:return!1}return o%=360,[n.TokenType.Number,o.toString(),e[2],e[3],{value:o,type:n.NumberType.Number}]}return!1}function normalize_legacy_HSL_ChannelValues(e,o,a){if(0===o){const o=normalizeHue(e);return!1!==o&&(e[0]===n.TokenType.Dimension&&a.syntaxFlags.add(exports.SyntaxFlag.HasDimensionValues),o)}if(e[0]===n.TokenType.Percentage){3===o?a.syntaxFlags.add(exports.SyntaxFlag.HasPercentageAlpha):a.syntaxFlags.add(exports.SyntaxFlag.HasPercentageValues);let t=normalize(e[4].value,1,0,100);return 3===o&&(t=normalize(e[4].value,100,0,1)),[n.TokenType.Number,t.toString(),e[2],e[3],{value:t,type:n.NumberType.Number}]}if(e[0]===n.TokenType.Number){if(3!==o)return!1;let a=normalize(e[4].value,1,0,100);return 3===o&&(a=normalize(e[4].value,1,0,1)),[n.TokenType.Number,a.toString(),e[2],e[3],{value:a,type:n.NumberType.Number}]}return!1}function normalize_modern_HSL_ChannelValues(e,o,a){if(e[0]===n.TokenType.Ident&&"none"===toLowerCaseAZ(e[4].value))return a.syntaxFlags.add(exports.SyntaxFlag.HasNoneKeywords),[n.TokenType.Number,"none",e[2],e[3],{value:NaN,type:n.NumberType.Number}];if(0===o){const o=normalizeHue(e);return!1!==o&&(e[0]===n.TokenType.Dimension&&a.syntaxFlags.add(exports.SyntaxFlag.HasDimensionValues),o)}if(e[0]===n.TokenType.Percentage){3===o?a.syntaxFlags.add(exports.SyntaxFlag.HasPercentageAlpha):a.syntaxFlags.add(exports.SyntaxFlag.HasPercentageValues);let t=e[4].value;return 3===o&&(t=normalize(e[4].value,100,0,1)),[n.TokenType.Number,t.toString(),e[2],e[3],{value:t,type:n.NumberType.Number}]}if(e[0]===n.TokenType.Number){3!==o&&a.syntaxFlags.add(exports.SyntaxFlag.HasNumberValues);let t=e[4].value;return 3===o&&(t=normalize(e[4].value,1,0,1)),[n.TokenType.Number,t.toString(),e[2],e[3],{value:t,type:n.NumberType.Number}]}return!1}function threeChannelLegacySyntax(e,o,a,s){const l=[],i=[],u=[],c=[],p={colorNotation:a,channels:[0,0,0],alpha:1,syntaxFlags:new Set(s)};let N=l;for(let o=0;ot.isTokenNode(e)&&e.value[0]===n.TokenType.Comma))){const o=hslCommaSeparated(e);if(!1!==o)return o}{const n=hslSpaceSeparated(e,o);if(!1!==n)return n}return!1}function hslCommaSeparated(e){return threeChannelLegacySyntax(e,normalize_legacy_HSL_ChannelValues,exports.ColorNotation.HSL,[exports.SyntaxFlag.LegacyHSL])}function hslSpaceSeparated(e,o){return threeChannelSpaceSeparated(e,normalize_modern_HSL_ChannelValues,exports.ColorNotation.HSL,[],o)}function normalize_HWB_ChannelValues(e,o,a){if(e[0]===n.TokenType.Ident&&"none"===toLowerCaseAZ(e[4].value))return a.syntaxFlags.add(exports.SyntaxFlag.HasNoneKeywords),[n.TokenType.Number,"none",e[2],e[3],{value:NaN,type:n.NumberType.Number}];if(0===o){const o=normalizeHue(e);return!1!==o&&(e[0]===n.TokenType.Dimension&&a.syntaxFlags.add(exports.SyntaxFlag.HasDimensionValues),o)}if(e[0]===n.TokenType.Percentage){3===o?a.syntaxFlags.add(exports.SyntaxFlag.HasPercentageAlpha):a.syntaxFlags.add(exports.SyntaxFlag.HasPercentageValues);let t=e[4].value;return 3===o&&(t=normalize(e[4].value,100,0,1)),[n.TokenType.Number,t.toString(),e[2],e[3],{value:t,type:n.NumberType.Number}]}if(e[0]===n.TokenType.Number){3!==o&&a.syntaxFlags.add(exports.SyntaxFlag.HasNumberValues);let t=e[4].value;return 3===o&&(t=normalize(e[4].value,1,0,1)),[n.TokenType.Number,t.toString(),e[2],e[3],{value:t,type:n.NumberType.Number}]}return!1}function normalize_Lab_ChannelValues(e,o,a){if(e[0]===n.TokenType.Ident&&"none"===toLowerCaseAZ(e[4].value))return a.syntaxFlags.add(exports.SyntaxFlag.HasNoneKeywords),[n.TokenType.Number,"none",e[2],e[3],{value:NaN,type:n.NumberType.Number}];if(e[0]===n.TokenType.Percentage){3!==o&&a.syntaxFlags.add(exports.SyntaxFlag.HasPercentageValues);let t=normalize(e[4].value,1,0,100);return 1===o||2===o?t=normalize(e[4].value,.8,-1/0,1/0):3===o&&(t=normalize(e[4].value,100,0,1)),[n.TokenType.Number,t.toString(),e[2],e[3],{value:t,type:n.NumberType.Number}]}if(e[0]===n.TokenType.Number){3!==o&&a.syntaxFlags.add(exports.SyntaxFlag.HasNumberValues);let t=normalize(e[4].value,1,0,100);return 1===o||2===o?t=normalize(e[4].value,1,-1/0,1/0):3===o&&(t=normalize(e[4].value,1,0,1)),[n.TokenType.Number,t.toString(),e[2],e[3],{value:t,type:n.NumberType.Number}]}return!1}function lab(e,o){return threeChannelSpaceSeparated(e,normalize_Lab_ChannelValues,exports.ColorNotation.Lab,[],o)}function normalize_LCH_ChannelValues(e,o,a){if(e[0]===n.TokenType.Ident&&"none"===toLowerCaseAZ(e[4].value))return a.syntaxFlags.add(exports.SyntaxFlag.HasNoneKeywords),[n.TokenType.Number,"none",e[2],e[3],{value:NaN,type:n.NumberType.Number}];if(2===o){const o=normalizeHue(e);return!1!==o&&(e[0]===n.TokenType.Dimension&&a.syntaxFlags.add(exports.SyntaxFlag.HasDimensionValues),o)}if(e[0]===n.TokenType.Percentage){3!==o&&a.syntaxFlags.add(exports.SyntaxFlag.HasPercentageValues);let t=normalize(e[4].value,1,0,100);return 1===o?t=normalize(e[4].value,100/150,0,1/0):3===o&&(t=normalize(e[4].value,100,0,1)),[n.TokenType.Number,t.toString(),e[2],e[3],{value:t,type:n.NumberType.Number}]}if(e[0]===n.TokenType.Number){3!==o&&a.syntaxFlags.add(exports.SyntaxFlag.HasNumberValues);let t=normalize(e[4].value,1,0,100);return 1===o?t=normalize(e[4].value,1,0,1/0):3===o&&(t=normalize(e[4].value,1,0,1)),[n.TokenType.Number,t.toString(),e[2],e[3],{value:t,type:n.NumberType.Number}]}return!1}function lch(e,o){return threeChannelSpaceSeparated(e,normalize_LCH_ChannelValues,exports.ColorNotation.LCH,[],o)}const N=new Map;for(const[e,o]of Object.entries(a.namedColors))N.set(e,o);function namedColor(e){const o=N.get(toLowerCaseAZ(e));return!!o&&{colorNotation:exports.ColorNotation.RGB,channels:[o[0]/255,o[1]/255,o[2]/255],alpha:1,syntaxFlags:new Set([exports.SyntaxFlag.ColorKeyword,exports.SyntaxFlag.NamedColor])}}function normalize_OKLab_ChannelValues(e,o,a){if(e[0]===n.TokenType.Ident&&"none"===toLowerCaseAZ(e[4].value))return a.syntaxFlags.add(exports.SyntaxFlag.HasNoneKeywords),[n.TokenType.Number,"none",e[2],e[3],{value:NaN,type:n.NumberType.Number}];if(e[0]===n.TokenType.Percentage){3!==o&&a.syntaxFlags.add(exports.SyntaxFlag.HasPercentageValues);let t=normalize(e[4].value,100,0,1);return 1===o||2===o?t=normalize(e[4].value,250,-1/0,1/0):3===o&&(t=normalize(e[4].value,100,0,1)),[n.TokenType.Number,t.toString(),e[2],e[3],{value:t,type:n.NumberType.Number}]}if(e[0]===n.TokenType.Number){3!==o&&a.syntaxFlags.add(exports.SyntaxFlag.HasNumberValues);let t=normalize(e[4].value,1,0,1);return 1===o||2===o?t=normalize(e[4].value,1,-1/0,1/0):3===o&&(t=normalize(e[4].value,1,0,1)),[n.TokenType.Number,t.toString(),e[2],e[3],{value:t,type:n.NumberType.Number}]}return!1}function oklab(e,o){return threeChannelSpaceSeparated(e,normalize_OKLab_ChannelValues,exports.ColorNotation.OKLab,[],o)}function normalize_OKLCH_ChannelValues(e,o,a){if(e[0]===n.TokenType.Ident&&"none"===toLowerCaseAZ(e[4].value))return a.syntaxFlags.add(exports.SyntaxFlag.HasNoneKeywords),[n.TokenType.Number,"none",e[2],e[3],{value:NaN,type:n.NumberType.Number}];if(2===o){const o=normalizeHue(e);return!1!==o&&(e[0]===n.TokenType.Dimension&&a.syntaxFlags.add(exports.SyntaxFlag.HasDimensionValues),o)}if(e[0]===n.TokenType.Percentage){3!==o&&a.syntaxFlags.add(exports.SyntaxFlag.HasPercentageValues);let t=normalize(e[4].value,100,0,1);return 1===o?t=normalize(e[4].value,250,0,1/0):3===o&&(t=normalize(e[4].value,100,0,1)),[n.TokenType.Number,t.toString(),e[2],e[3],{value:t,type:n.NumberType.Number}]}if(e[0]===n.TokenType.Number){3!==o&&a.syntaxFlags.add(exports.SyntaxFlag.HasNumberValues);let t=normalize(e[4].value,1,0,1);return 1===o?t=normalize(e[4].value,1,0,1/0):3===o&&(t=normalize(e[4].value,1,0,1)),[n.TokenType.Number,t.toString(),e[2],e[3],{value:t,type:n.NumberType.Number}]}return!1}function oklch(e,o){return threeChannelSpaceSeparated(e,normalize_OKLCH_ChannelValues,exports.ColorNotation.OKLCH,[],o)}function normalize_legacy_sRGB_ChannelValues(e,o,a){if(e[0]===n.TokenType.Percentage){3===o?a.syntaxFlags.add(exports.SyntaxFlag.HasPercentageAlpha):a.syntaxFlags.add(exports.SyntaxFlag.HasPercentageValues);const t=normalize(e[4].value,100,0,1);return[n.TokenType.Number,t.toString(),e[2],e[3],{value:t,type:n.NumberType.Number}]}if(e[0]===n.TokenType.Number){3!==o&&a.syntaxFlags.add(exports.SyntaxFlag.HasNumberValues);let t=normalize(e[4].value,255,0,1);return 3===o&&(t=normalize(e[4].value,1,0,1)),[n.TokenType.Number,t.toString(),e[2],e[3],{value:t,type:n.NumberType.Number}]}return!1}function normalize_modern_sRGB_ChannelValues(e,o,a){if(e[0]===n.TokenType.Ident&&"none"===toLowerCaseAZ(e[4].value))return a.syntaxFlags.add(exports.SyntaxFlag.HasNoneKeywords),[n.TokenType.Number,"none",e[2],e[3],{value:NaN,type:n.NumberType.Number}];if(e[0]===n.TokenType.Percentage){3!==o&&a.syntaxFlags.add(exports.SyntaxFlag.HasPercentageValues);let t=normalize(e[4].value,100,-1/0,1/0);return 3===o&&(t=normalize(e[4].value,100,0,1)),[n.TokenType.Number,t.toString(),e[2],e[3],{value:t,type:n.NumberType.Number}]}if(e[0]===n.TokenType.Number){3!==o&&a.syntaxFlags.add(exports.SyntaxFlag.HasNumberValues);let t=normalize(e[4].value,255,-1/0,1/0);return 3===o&&(t=normalize(e[4].value,1,0,1)),[n.TokenType.Number,t.toString(),e[2],e[3],{value:t,type:n.NumberType.Number}]}return!1}function rgb(e,o){if(e.value.some((e=>t.isTokenNode(e)&&e.value[0]===n.TokenType.Comma))){const o=rgbCommaSeparated(e);if(!1!==o)return(!o.syntaxFlags.has(exports.SyntaxFlag.HasNumberValues)||!o.syntaxFlags.has(exports.SyntaxFlag.HasPercentageValues))&&o}else{const n=rgbSpaceSeparated(e,o);if(!1!==n)return n}return!1}function rgbCommaSeparated(e){return threeChannelLegacySyntax(e,normalize_legacy_sRGB_ChannelValues,exports.ColorNotation.RGB,[exports.SyntaxFlag.LegacyRGB])}function rgbSpaceSeparated(e,o){return threeChannelSpaceSeparated(e,normalize_modern_sRGB_ChannelValues,exports.ColorNotation.RGB,[],o)}function toPrecision(e,o=7){e=+e,o=+o;const n=(Math.floor(e)+"").length;if(o>n)return+e.toFixed(o-n);{const a=10**(n-o);return Math.round(e/a)*a}}function XYZ_D50_to_P3_Gamut(e){const o=a.xyz.XYZ_D50_to_P3(e);if(a.utils.inGamut(o))return a.utils.clip(o);let n=e.slice();return n=a.conversions.D50_to_D65(n),n=a.conversions.XYZ_to_OKLab(n),n=a.conversions.OKLab_to_OKLCH(n),n[0]<1e-6&&(n=[0,0,0]),n[0]>.999999&&(n=[1,0,0]),a.calculations.mapGamut(n,(e=>(e=a.conversions.OKLCH_to_OKLab(e),e=a.conversions.OKLab_to_XYZ(e),e=a.conversions.XYZ_to_lin_P3(e),a.conversions.gam_P3(e))),(e=>(e=a.conversions.lin_P3(e),e=a.conversions.lin_P3_to_XYZ(e),e=a.conversions.XYZ_to_OKLab(e),a.conversions.OKLab_to_OKLCH(e))))}function serializeWithAlpha(e,o,a,r){const s=[n.TokenType.CloseParen,")",-1,-1,void 0];if("number"==typeof e.alpha){const l=Math.min(1,Math.max(0,toPrecision(Number.isNaN(e.alpha)?0:e.alpha)));return 1===toPrecision(l,4)?new t.FunctionNode(o,s,r):new t.FunctionNode(o,s,[...r,new t.WhitespaceNode([a]),new t.TokenNode([n.TokenType.Delim,"/",-1,-1,{value:"/"}]),new t.WhitespaceNode([a]),new t.TokenNode([n.TokenType.Number,toPrecision(l,4).toString(),-1,-1,{value:e.alpha,type:n.NumberType.Integer}])])}return new t.FunctionNode(o,s,[...r,new t.WhitespaceNode([a]),new t.TokenNode([n.TokenType.Delim,"/",-1,-1,{value:"/"}]),new t.WhitespaceNode([a]),e.alpha])}function XYZ_D50_to_sRGB_Gamut(e){const o=a.xyz.XYZ_D50_to_sRGB(e);if(a.utils.inGamut(o))return a.utils.clip(o);let n=e.slice();return n=a.conversions.D50_to_D65(n),n=a.conversions.XYZ_to_OKLab(n),n=a.conversions.OKLab_to_OKLCH(n),n[0]<1e-6&&(n=[0,0,0]),n[0]>.999999&&(n=[1,0,0]),a.calculations.mapGamut(n,(e=>(e=a.conversions.OKLCH_to_OKLab(e),e=a.conversions.OKLab_to_XYZ(e),e=a.conversions.XYZ_to_lin_sRGB(e),a.conversions.gam_sRGB(e))),(e=>(e=a.conversions.lin_sRGB(e),e=a.conversions.lin_sRGB_to_XYZ(e),e=a.conversions.XYZ_to_OKLab(e),a.conversions.OKLab_to_OKLCH(e))))}exports.color=function color(e){if(t.isFunctionNode(e)){switch(toLowerCaseAZ(e.getName())){case"rgb":case"rgba":return rgb(e,color);case"hsl":case"hsla":return hsl(e,color);case"hwb":return o=color,threeChannelSpaceSeparated(e,normalize_HWB_ChannelValues,exports.ColorNotation.HWB,[],o);case"lab":return lab(e,color);case"lch":return lch(e,color);case"oklab":return oklab(e,color);case"oklch":return oklch(e,color);case"color":return color$1(e,color);case"color-mix":return colorMix(e,color)}}var o;if(t.isTokenNode(e)){if(e.value[0]===n.TokenType.Hash)return hex(e.value);if(e.value[0]===n.TokenType.Ident){const o=namedColor(e.value[4].value);return!1!==o?o:"transparent"===toLowerCaseAZ(e.value[4].value)&&{colorNotation:exports.ColorNotation.RGB,channels:[0,0,0],alpha:0,syntaxFlags:new Set([exports.SyntaxFlag.ColorKeyword])}}}return!1},exports.colorDataFitsDisplayP3_Gamut=function colorDataFitsDisplayP3_Gamut(e){const o={...e,channels:[...e.channels]};return o.channels=convertPowerlessComponentsToZeroValuesForDisplay(o.channels,o.colorNotation),!colorDataTo(o,exports.ColorNotation.Display_P3).channels.find((e=>e<-1e-5||e>1.00001))},exports.colorDataFitsRGB_Gamut=function colorDataFitsRGB_Gamut(e){const o={...e,channels:[...e.channels]};return o.channels=convertPowerlessComponentsToZeroValuesForDisplay(o.channels,o.colorNotation),!colorDataTo(o,exports.ColorNotation.RGB).channels.find((e=>e<-1e-5||e>1.00001))},exports.colorDataTo=colorDataTo,exports.serializeHSL=function serializeHSL(e,o=!0){e.channels=convertPowerlessComponentsToZeroValuesForDisplay(e.channels,e.colorNotation);let r=e.channels.map((e=>Number.isNaN(e)?0:e));r=o?a.xyz.XYZ_D50_to_HSL(a.xyz.sRGB_to_XYZ_D50(XYZ_D50_to_sRGB_Gamut(colorData_to_XYZ_D50(e).channels))):a.xyz.XYZ_D50_to_HSL(colorData_to_XYZ_D50(e).channels),r=r.map((e=>Number.isNaN(e)?0:e));const s=Math.min(360,Math.max(0,Math.round(toPrecision(r[0])))),l=Math.min(100,Math.max(0,Math.round(toPrecision(r[1])))),i=Math.min(100,Math.max(0,Math.round(toPrecision(r[2])))),u=[n.TokenType.CloseParen,")",-1,-1,void 0],c=[n.TokenType.Whitespace," ",-1,-1,void 0],p=[n.TokenType.Comma,",",-1,-1,void 0],N=[new t.TokenNode([n.TokenType.Number,s.toString(),-1,-1,{value:r[0],type:n.NumberType.Integer}]),new t.TokenNode(p),new t.WhitespaceNode([c]),new t.TokenNode([n.TokenType.Percentage,l.toString()+"%",-1,-1,{value:r[1]}]),new t.TokenNode(p),new t.WhitespaceNode([c]),new t.TokenNode([n.TokenType.Percentage,i.toString()+"%",-1,-1,{value:r[2]}])];if("number"==typeof e.alpha){const o=Math.min(1,Math.max(0,toPrecision(Number.isNaN(e.alpha)?0:e.alpha)));return 1===toPrecision(o,4)?new t.FunctionNode([n.TokenType.Function,"hsl(",-1,-1,{value:"hsl"}],u,N):new t.FunctionNode([n.TokenType.Function,"hsla(",-1,-1,{value:"hsla"}],u,[...N,new t.TokenNode(p),new t.WhitespaceNode([c]),new t.TokenNode([n.TokenType.Number,toPrecision(o,4).toString(),-1,-1,{value:e.alpha,type:n.NumberType.Number}])])}return new t.FunctionNode([n.TokenType.Function,"hsla(",-1,-1,{value:"hsla"}],u,[...N,new t.TokenNode(p),new t.WhitespaceNode([c]),e.alpha])},exports.serializeOKLCH=function serializeOKLCH(e){e.channels=convertPowerlessComponentsToZeroValuesForDisplay(e.channels,e.colorNotation);let o=e.channels.map((e=>Number.isNaN(e)?0:e));e.colorNotation!==exports.ColorNotation.OKLCH&&(o=a.xyz.XYZ_D50_to_OKLCH(colorData_to_XYZ_D50(e).channels));const r=toPrecision(o[0],6),s=toPrecision(o[1],6),l=toPrecision(o[2],6),i=[n.TokenType.Function,"oklch(",-1,-1,{value:"oklch"}],u=[n.TokenType.Whitespace," ",-1,-1,void 0];return serializeWithAlpha(e,i,u,[new t.TokenNode([n.TokenType.Number,r.toString(),-1,-1,{value:o[0],type:n.NumberType.Number}]),new t.WhitespaceNode([u]),new t.TokenNode([n.TokenType.Number,s.toString(),-1,-1,{value:o[1],type:n.NumberType.Number}]),new t.WhitespaceNode([u]),new t.TokenNode([n.TokenType.Number,l.toString(),-1,-1,{value:o[2],type:n.NumberType.Number}])])},exports.serializeP3=function serializeP3(e,o=!0){e.channels=convertPowerlessComponentsToZeroValuesForDisplay(e.channels,e.colorNotation);let r=e.channels.map((e=>Number.isNaN(e)?0:e));e.colorNotation!==exports.ColorNotation.Display_P3&&(r=o?XYZ_D50_to_P3_Gamut(colorData_to_XYZ_D50(e).channels):a.xyz.XYZ_D50_to_P3(colorData_to_XYZ_D50(e).channels));const s=toPrecision(r[0],6),l=toPrecision(r[1],6),i=toPrecision(r[2],6),u=[n.TokenType.Function,"color(",-1,-1,{value:"color"}],c=[n.TokenType.Whitespace," ",-1,-1,void 0];return serializeWithAlpha(e,u,c,[new t.TokenNode([n.TokenType.Ident,"display-p3",-1,-1,{value:"display-p3"}]),new t.WhitespaceNode([c]),new t.TokenNode([n.TokenType.Number,s.toString(),-1,-1,{value:r[0],type:n.NumberType.Number}]),new t.WhitespaceNode([c]),new t.TokenNode([n.TokenType.Number,l.toString(),-1,-1,{value:r[1],type:n.NumberType.Number}]),new t.WhitespaceNode([c]),new t.TokenNode([n.TokenType.Number,i.toString(),-1,-1,{value:r[2],type:n.NumberType.Number}])])},exports.serializeRGB=function serializeRGB(e,o=!0){e.channels=convertPowerlessComponentsToZeroValuesForDisplay(e.channels,e.colorNotation);let r=e.channels.map((e=>Number.isNaN(e)?0:e));r=o?XYZ_D50_to_sRGB_Gamut(colorData_to_XYZ_D50(e).channels):a.xyz.XYZ_D50_to_sRGB(colorData_to_XYZ_D50(e).channels);const s=Math.min(255,Math.max(0,Math.round(255*toPrecision(r[0])))),l=Math.min(255,Math.max(0,Math.round(255*toPrecision(r[1])))),i=Math.min(255,Math.max(0,Math.round(255*toPrecision(r[2])))),u=[n.TokenType.CloseParen,")",-1,-1,void 0],c=[n.TokenType.Whitespace," ",-1,-1,void 0],p=[n.TokenType.Comma,",",-1,-1,void 0],N=[new t.TokenNode([n.TokenType.Number,s.toString(),-1,-1,{value:r[0],type:n.NumberType.Integer}]),new t.TokenNode(p),new t.WhitespaceNode([c]),new t.TokenNode([n.TokenType.Number,l.toString(),-1,-1,{value:r[1],type:n.NumberType.Integer}]),new t.TokenNode(p),new t.WhitespaceNode([c]),new t.TokenNode([n.TokenType.Number,i.toString(),-1,-1,{value:r[2],type:n.NumberType.Integer}])];if("number"==typeof e.alpha){const o=Math.min(1,Math.max(0,toPrecision(Number.isNaN(e.alpha)?0:e.alpha)));return 1===toPrecision(o,4)?new t.FunctionNode([n.TokenType.Function,"rgb(",-1,-1,{value:"rgb"}],u,N):new t.FunctionNode([n.TokenType.Function,"rgba(",-1,-1,{value:"rgba"}],u,[...N,new t.TokenNode(p),new t.WhitespaceNode([c]),new t.TokenNode([n.TokenType.Number,toPrecision(o,4).toString(),-1,-1,{value:e.alpha,type:n.NumberType.Number}])])}return new t.FunctionNode([n.TokenType.Function,"rgba(",-1,-1,{value:"rgba"}],u,[...N,new t.TokenNode(p),new t.WhitespaceNode([c]),e.alpha])}; +"use strict";var e,o,a=require("@csstools/css-tokenizer"),n=require("@csstools/color-helpers"),t=require("@csstools/css-parser-algorithms"),r=require("@csstools/css-calc");function colorData_to_XYZ_D50(e){switch(e.colorNotation){case exports.ColorNotation.HEX:case exports.ColorNotation.RGB:case exports.ColorNotation.sRGB:return{...e,colorNotation:exports.ColorNotation.XYZ_D50,channels:n.sRGB_to_XYZ_D50(e.channels.map((e=>Number.isNaN(e)?0:e)))};case exports.ColorNotation.Linear_sRGB:return{...e,colorNotation:exports.ColorNotation.XYZ_D50,channels:n.lin_sRGB_to_XYZ_D50(e.channels.map((e=>Number.isNaN(e)?0:e)))};case exports.ColorNotation.Display_P3:return{...e,colorNotation:exports.ColorNotation.XYZ_D50,channels:n.P3_to_XYZ_D50(e.channels.map((e=>Number.isNaN(e)?0:e)))};case exports.ColorNotation.Rec2020:return{...e,colorNotation:exports.ColorNotation.XYZ_D50,channels:n.rec_2020_to_XYZ_D50(e.channels.map((e=>Number.isNaN(e)?0:e)))};case exports.ColorNotation.A98_RGB:return{...e,colorNotation:exports.ColorNotation.XYZ_D50,channels:n.a98_RGB_to_XYZ_D50(e.channels.map((e=>Number.isNaN(e)?0:e)))};case exports.ColorNotation.ProPhoto_RGB:return{...e,colorNotation:exports.ColorNotation.XYZ_D50,channels:n.ProPhoto_RGB_to_XYZ_D50(e.channels.map((e=>Number.isNaN(e)?0:e)))};case exports.ColorNotation.HSL:return{...e,colorNotation:exports.ColorNotation.XYZ_D50,channels:n.HSL_to_XYZ_D50(e.channels.map((e=>Number.isNaN(e)?0:e)))};case exports.ColorNotation.HWB:return{...e,colorNotation:exports.ColorNotation.XYZ_D50,channels:n.HWB_to_XYZ_D50(e.channels.map((e=>Number.isNaN(e)?0:e)))};case exports.ColorNotation.Lab:return{...e,colorNotation:exports.ColorNotation.XYZ_D50,channels:n.Lab_to_XYZ_D50(e.channels.map((e=>Number.isNaN(e)?0:e)))};case exports.ColorNotation.OKLab:return{...e,colorNotation:exports.ColorNotation.XYZ_D50,channels:n.OKLab_to_XYZ_D50(e.channels.map((e=>Number.isNaN(e)?0:e)))};case exports.ColorNotation.LCH:return{...e,colorNotation:exports.ColorNotation.XYZ_D50,channels:n.LCH_to_XYZ_D50(e.channels.map((e=>Number.isNaN(e)?0:e)))};case exports.ColorNotation.OKLCH:return{...e,colorNotation:exports.ColorNotation.XYZ_D50,channels:n.OKLCH_to_XYZ_D50(e.channels.map((e=>Number.isNaN(e)?0:e)))};case exports.ColorNotation.XYZ_D50:return{...e,colorNotation:exports.ColorNotation.XYZ_D50,channels:n.XYZ_D50_to_XYZ_D50(e.channels.map((e=>Number.isNaN(e)?0:e)))};case exports.ColorNotation.XYZ_D65:return{...e,colorNotation:exports.ColorNotation.XYZ_D50,channels:n.XYZ_D65_to_XYZ_D50(e.channels.map((e=>Number.isNaN(e)?0:e)))};default:throw new Error("Unsupported color notation")}}exports.ColorNotation=void 0,(e=exports.ColorNotation||(exports.ColorNotation={})).A98_RGB="a98-rgb",e.Display_P3="display-p3",e.HEX="hex",e.HSL="hsl",e.HWB="hwb",e.LCH="lch",e.Lab="lab",e.Linear_sRGB="srgb-linear",e.OKLCH="oklch",e.OKLab="oklab",e.ProPhoto_RGB="prophoto-rgb",e.RGB="rgb",e.sRGB="srgb",e.Rec2020="rec2020",e.XYZ_D50="xyz-d50",e.XYZ_D65="xyz-d65",exports.SyntaxFlag=void 0,(o=exports.SyntaxFlag||(exports.SyntaxFlag={})).ColorKeyword="color-keyword",o.HasAlpha="has-alpha",o.HasDimensionValues="has-dimension-values",o.HasNoneKeywords="has-none-keywords",o.HasNumberValues="has-number-values",o.HasPercentageAlpha="has-percentage-alpha",o.HasPercentageValues="has-percentage-values",o.HasVariableAlpha="has-variable-alpha",o.Hex="hex",o.LegacyHSL="legacy-hsl",o.LegacyRGB="legacy-rgb",o.NamedColor="named-color",o.RelativeColorSyntax="relative-color-syntax",o.ColorMix="color-mix",o.Experimental="experimental";const l=new Set([exports.ColorNotation.A98_RGB,exports.ColorNotation.Display_P3,exports.ColorNotation.HEX,exports.ColorNotation.Linear_sRGB,exports.ColorNotation.ProPhoto_RGB,exports.ColorNotation.RGB,exports.ColorNotation.sRGB,exports.ColorNotation.Rec2020,exports.ColorNotation.XYZ_D50,exports.ColorNotation.XYZ_D65]);function colorDataTo(e,o){const a={...e};if(e.colorNotation!==o){const e=colorData_to_XYZ_D50(a);switch(o){case exports.ColorNotation.HEX:case exports.ColorNotation.RGB:a.colorNotation=exports.ColorNotation.RGB,a.channels=n.XYZ_D50_to_sRGB(e.channels);break;case exports.ColorNotation.sRGB:a.colorNotation=exports.ColorNotation.sRGB,a.channels=n.XYZ_D50_to_sRGB(e.channels);break;case exports.ColorNotation.Linear_sRGB:a.colorNotation=exports.ColorNotation.Linear_sRGB,a.channels=n.XYZ_D50_to_lin_sRGB(e.channels);break;case exports.ColorNotation.Display_P3:a.colorNotation=exports.ColorNotation.Display_P3,a.channels=n.XYZ_D50_to_P3(e.channels);break;case exports.ColorNotation.Rec2020:a.colorNotation=exports.ColorNotation.Rec2020,a.channels=n.XYZ_D50_to_rec_2020(e.channels);break;case exports.ColorNotation.ProPhoto_RGB:a.colorNotation=exports.ColorNotation.ProPhoto_RGB,a.channels=n.XYZ_D50_to_ProPhoto(e.channels);break;case exports.ColorNotation.A98_RGB:a.colorNotation=exports.ColorNotation.A98_RGB,a.channels=n.XYZ_D50_to_a98_RGB(e.channels);break;case exports.ColorNotation.HSL:a.colorNotation=exports.ColorNotation.HSL,a.channels=n.XYZ_D50_to_HSL(e.channels);break;case exports.ColorNotation.HWB:a.colorNotation=exports.ColorNotation.HWB,a.channels=n.XYZ_D50_to_HWB(e.channels);break;case exports.ColorNotation.Lab:a.colorNotation=exports.ColorNotation.Lab,a.channels=n.XYZ_D50_to_Lab(e.channels);break;case exports.ColorNotation.LCH:a.colorNotation=exports.ColorNotation.LCH,a.channels=n.XYZ_D50_to_LCH(e.channels);break;case exports.ColorNotation.OKLCH:a.colorNotation=exports.ColorNotation.OKLCH,a.channels=n.XYZ_D50_to_OKLCH(e.channels);break;case exports.ColorNotation.OKLab:a.colorNotation=exports.ColorNotation.OKLab,a.channels=n.XYZ_D50_to_OKLab(e.channels);break;case exports.ColorNotation.XYZ_D50:a.colorNotation=exports.ColorNotation.XYZ_D50,a.channels=n.XYZ_D50_to_XYZ_D50(e.channels);break;case exports.ColorNotation.XYZ_D65:a.colorNotation=exports.ColorNotation.XYZ_D65,a.channels=n.XYZ_D50_to_XYZ_D65(e.channels);break;default:throw new Error("Unsupported color notation")}}else a.channels=e.channels.map((e=>Number.isNaN(e)?0:e));if(o===e.colorNotation)a.channels=carryForwardMissingComponents(e.channels,[0,1,2],a.channels,[0,1,2]);else if(l.has(o)&&l.has(e.colorNotation))a.channels=carryForwardMissingComponents(e.channels,[0,1,2],a.channels,[0,1,2]);else switch(o){case exports.ColorNotation.HSL:switch(e.colorNotation){case exports.ColorNotation.HWB:a.channels=carryForwardMissingComponents(e.channels,[0],a.channels,[0]);break;case exports.ColorNotation.Lab:case exports.ColorNotation.OKLab:a.channels=carryForwardMissingComponents(e.channels,[2],a.channels,[0]);break;case exports.ColorNotation.LCH:case exports.ColorNotation.OKLCH:a.channels=carryForwardMissingComponents(e.channels,[0,1,2],a.channels,[2,1,0])}break;case exports.ColorNotation.HWB:switch(e.colorNotation){case exports.ColorNotation.HSL:a.channels=carryForwardMissingComponents(e.channels,[0],a.channels,[0]);break;case exports.ColorNotation.LCH:case exports.ColorNotation.OKLCH:a.channels=carryForwardMissingComponents(e.channels,[0],a.channels,[2])}break;case exports.ColorNotation.Lab:case exports.ColorNotation.OKLab:switch(e.colorNotation){case exports.ColorNotation.HSL:a.channels=carryForwardMissingComponents(e.channels,[0],a.channels,[2]);break;case exports.ColorNotation.Lab:case exports.ColorNotation.OKLab:a.channels=carryForwardMissingComponents(e.channels,[0,1,2],a.channels,[0,1,2]);break;case exports.ColorNotation.LCH:case exports.ColorNotation.OKLCH:a.channels=carryForwardMissingComponents(e.channels,[0],a.channels,[0])}break;case exports.ColorNotation.LCH:case exports.ColorNotation.OKLCH:switch(e.colorNotation){case exports.ColorNotation.HSL:a.channels=carryForwardMissingComponents(e.channels,[0,1,2],a.channels,[2,1,0]);break;case exports.ColorNotation.HWB:a.channels=carryForwardMissingComponents(e.channels,[0],a.channels,[2]);break;case exports.ColorNotation.Lab:case exports.ColorNotation.OKLab:a.channels=carryForwardMissingComponents(e.channels,[0],a.channels,[0]);break;case exports.ColorNotation.LCH:case exports.ColorNotation.OKLCH:a.channels=carryForwardMissingComponents(e.channels,[0,1,2],a.channels,[0,1,2])}}return a.channels=convertPowerlessComponentsToMissingComponents(a.channels,o),a}function convertPowerlessComponentsToMissingComponents(e,o){const a=[...e];switch(o){case exports.ColorNotation.HSL:reducePrecision(a[1],4)<=0&&(a[0]=NaN);break;case exports.ColorNotation.HWB:Math.max(0,reducePrecision(a[1],4))+Math.max(0,reducePrecision(a[2],4))>=100&&(a[0]=NaN);break;case exports.ColorNotation.LCH:reducePrecision(a[1],4)<=0&&(a[2]=NaN);break;case exports.ColorNotation.OKLCH:reducePrecision(a[1],6)<=0&&(a[2]=NaN)}return a}function convertPowerlessComponentsToZeroValuesForDisplay(e,o){const a=[...e];switch(o){case exports.ColorNotation.HSL:(reducePrecision(a[2])<=0||reducePrecision(a[2])>=100)&&(a[0]=NaN,a[1]=NaN),reducePrecision(a[1])<=0&&(a[0]=NaN);break;case exports.ColorNotation.HWB:Math.max(0,reducePrecision(a[1]))+Math.max(0,reducePrecision(a[2]))>=100&&(a[0]=NaN);break;case exports.ColorNotation.Lab:(reducePrecision(a[0])<=0||reducePrecision(a[0])>=100)&&(a[1]=NaN,a[2]=NaN);break;case exports.ColorNotation.LCH:reducePrecision(a[1])<=0&&(a[2]=NaN),(reducePrecision(a[0])<=0||reducePrecision(a[0])>=100)&&(a[1]=NaN,a[2]=NaN);break;case exports.ColorNotation.OKLab:(reducePrecision(a[0])<=0||reducePrecision(a[0])>=1)&&(a[1]=NaN,a[2]=NaN);break;case exports.ColorNotation.OKLCH:reducePrecision(a[1])<=0&&(a[2]=NaN),(reducePrecision(a[0])<=0||reducePrecision(a[0])>=1)&&(a[1]=NaN,a[2]=NaN)}return a}function carryForwardMissingComponents(e,o,a,n){const t=[...a];for(const a of o)Number.isNaN(e[o[a]])&&(t[n[a]]=NaN);return t}function normalizeRelativeColorDataChannels(e){const o=new Map;switch(e.colorNotation){case exports.ColorNotation.RGB:case exports.ColorNotation.HEX:o.set("r",dummyNumberToken(255*e.channels[0])),o.set("g",dummyNumberToken(255*e.channels[1])),o.set("b",dummyNumberToken(255*e.channels[2])),"number"==typeof e.alpha&&o.set("alpha",dummyNumberToken(e.alpha));break;case exports.ColorNotation.HSL:o.set("h",dummyNumberToken(e.channels[0])),o.set("s",dummyNumberToken(e.channels[1])),o.set("l",dummyNumberToken(e.channels[2])),"number"==typeof e.alpha&&o.set("alpha",dummyNumberToken(e.alpha));break;case exports.ColorNotation.HWB:o.set("h",dummyNumberToken(e.channels[0])),o.set("w",dummyNumberToken(e.channels[1])),o.set("b",dummyNumberToken(e.channels[2])),"number"==typeof e.alpha&&o.set("alpha",dummyNumberToken(e.alpha));break;case exports.ColorNotation.Lab:case exports.ColorNotation.OKLab:o.set("l",dummyNumberToken(e.channels[0])),o.set("a",dummyNumberToken(e.channels[1])),o.set("b",dummyNumberToken(e.channels[2])),"number"==typeof e.alpha&&o.set("alpha",dummyNumberToken(e.alpha));break;case exports.ColorNotation.LCH:case exports.ColorNotation.OKLCH:o.set("l",dummyNumberToken(e.channels[0])),o.set("c",dummyNumberToken(e.channels[1])),o.set("h",dummyNumberToken(e.channels[2])),"number"==typeof e.alpha&&o.set("alpha",dummyNumberToken(e.alpha));break;case exports.ColorNotation.sRGB:case exports.ColorNotation.A98_RGB:case exports.ColorNotation.Display_P3:case exports.ColorNotation.Rec2020:case exports.ColorNotation.Linear_sRGB:case exports.ColorNotation.ProPhoto_RGB:o.set("r",dummyNumberToken(e.channels[0])),o.set("g",dummyNumberToken(e.channels[1])),o.set("b",dummyNumberToken(e.channels[2])),"number"==typeof e.alpha&&o.set("alpha",dummyNumberToken(e.alpha));break;case exports.ColorNotation.XYZ_D50:case exports.ColorNotation.XYZ_D65:o.set("x",dummyNumberToken(e.channels[0])),o.set("y",dummyNumberToken(e.channels[1])),o.set("z",dummyNumberToken(e.channels[2])),"number"==typeof e.alpha&&o.set("alpha",dummyNumberToken(e.alpha))}return o}function noneToZeroInRelativeColorDataChannels(e){const o=new Map(e);for(const[a,n]of e)Number.isNaN(n[4].value)&&o.set(a,dummyNumberToken(0));return o}function dummyNumberToken(e){return[a.TokenType.Number,e.toString(),-1,-1,{value:e,type:a.NumberType.Number}]}function reducePrecision(e,o=7){if(Number.isNaN(e))return 0;const a=Math.pow(10,o);return Math.round(e*a)/a}function normalize(e,o,a,n){return Math.min(Math.max(e/o,a),n)}const s=/[A-Z]/g;function toLowerCaseAZ(e){return e.replace(s,(e=>String.fromCharCode(e.charCodeAt(0)+32)))}function normalize_Color_ChannelValues(e,o,n){if(e[0]===a.TokenType.Ident&&"none"===toLowerCaseAZ(e[4].value))return n.syntaxFlags.add(exports.SyntaxFlag.HasNoneKeywords),[a.TokenType.Number,"none",e[2],e[3],{value:NaN,type:a.NumberType.Number}];if(e[0]===a.TokenType.Percentage){3!==o&&n.syntaxFlags.add(exports.SyntaxFlag.HasPercentageValues);let t=normalize(e[4].value,100,-1/0,1/0);return 3===o&&(t=normalize(e[4].value,100,0,1)),[a.TokenType.Number,t.toString(),e[2],e[3],{value:t,type:a.NumberType.Number}]}if(e[0]===a.TokenType.Number){3!==o&&n.syntaxFlags.add(exports.SyntaxFlag.HasNumberValues);let t=normalize(e[4].value,1,-1/0,1/0);return 3===o&&(t=normalize(e[4].value,1,0,1)),[a.TokenType.Number,t.toString(),e[2],e[3],{value:t,type:a.NumberType.Number}]}return!1}const i=new Set(["srgb","srgb-linear","display-p3","a98-rgb","prophoto-rgb","rec2020","xyz","xyz-d50","xyz-d65"]);function color$1(e,o){const n=[],l=[],s=[],u=[];let c,p,N=!1,m=!1;const h={colorNotation:exports.ColorNotation.sRGB,channels:[0,0,0],alpha:1,syntaxFlags:new Set([])};let y=n;for(let x=0;x=0){i=u.value[4].value;continue}}return!1}if(!s)return!1;n.push({color:s,percentage:i}),s=!1,i=!1}}if(s&&n.push({color:s,percentage:i}),2!==n.length)return!1;let u=n[0].percentage,c=n[1].percentage;return(!1===u||!(u<0||u>100))&&((!1===c||!(c<0||c>100))&&(!1===u&&!1===c?(u=50,c=50):!1!==u&&!1===c?c=100-u:!1===u&&!1!==c&&(u=100-c),(0!==u||0!==c)&&(!1!==u&&!1!==c&&(u+c>100&&(u=u/(u+c)*100,c=c/(u+c)*100),u+c<100&&(l=(u+c)/100,u=u/(u+c)*100,c=c/(u+c)*100),{a:{color:n[0].color,percentage:u},b:{color:n[1].color,percentage:c},alphaMultiplier:l}))))}function colorMixRectangular(e,o){if(!o)return!1;const a=o.a.color,n=o.b.color,t=o.a.percentage/100;let r=a.channels,l=n.channels,s=exports.ColorNotation.RGB,i=a.alpha;if("number"!=typeof i)return!1;let u=n.alpha;if("number"!=typeof u)return!1;switch(i=Number.isNaN(i)?u:i,u=Number.isNaN(u)?i:u,e){case"srgb":s=exports.ColorNotation.RGB;break;case"srgb-linear":s=exports.ColorNotation.Linear_sRGB;break;case"lab":s=exports.ColorNotation.Lab;break;case"oklab":s=exports.ColorNotation.OKLab;break;case"xyz-d50":s=exports.ColorNotation.XYZ_D50;break;case"xyz":case"xyz-d65":s=exports.ColorNotation.XYZ_D65}r=colorDataTo(a,s).channels,l=colorDataTo(n,s).channels,r[0]=fillInMissingComponent(r[0],l[0]),l[0]=fillInMissingComponent(l[0],r[0]),r[1]=fillInMissingComponent(r[1],l[1]),l[1]=fillInMissingComponent(l[1],r[1]),r[2]=fillInMissingComponent(r[2],l[2]),l[2]=fillInMissingComponent(l[2],r[2]),r[0]=premultiply(r[0],i),r[1]=premultiply(r[1],i),r[2]=premultiply(r[2],i),l[0]=premultiply(l[0],u),l[1]=premultiply(l[1],u),l[2]=premultiply(l[2],u);const c=interpolate(i,u,t),p={colorNotation:s,channels:[un_premultiply(interpolate(r[0],l[0],t),c),un_premultiply(interpolate(r[1],l[1],t),c),un_premultiply(interpolate(r[2],l[2],t),c)],alpha:c*o.alphaMultiplier,syntaxFlags:new Set([exports.SyntaxFlag.ColorMix])};return(o.a.color.syntaxFlags.has(exports.SyntaxFlag.Experimental)||o.b.color.syntaxFlags.has(exports.SyntaxFlag.Experimental))&&p.syntaxFlags.add(exports.SyntaxFlag.Experimental),p}function colorMixPolar(e,o,a){if(!a)return!1;const n=a.a.color,t=a.b.color,r=a.a.percentage/100;let l=n.channels,s=t.channels,i=0,u=0,c=0,p=0,N=0,m=0,h=exports.ColorNotation.RGB,y=n.alpha;if("number"!=typeof y)return!1;let x=t.alpha;if("number"!=typeof x)return!1;switch(y=Number.isNaN(y)?x:y,x=Number.isNaN(x)?y:x,e){case"hsl":h=exports.ColorNotation.HSL;break;case"hwb":h=exports.ColorNotation.HWB;break;case"lch":h=exports.ColorNotation.LCH;break;case"oklch":h=exports.ColorNotation.OKLCH}switch(l=colorDataTo(n,h).channels,s=colorDataTo(t,h).channels,e){case"hsl":case"hwb":i=l[0],u=s[0],c=l[1],p=s[1],N=l[2],m=s[2];break;case"lch":case"oklch":c=l[0],p=s[0],N=l[1],m=s[1],i=l[2],u=s[2]}i=fillInMissingComponent(i,u),Number.isNaN(i)&&(i=0),u=fillInMissingComponent(u,i),Number.isNaN(u)&&(u=0),c=fillInMissingComponent(c,p),p=fillInMissingComponent(p,c),N=fillInMissingComponent(N,m),m=fillInMissingComponent(m,N);const T=u-i;switch(o){case"shorter":T>180?i+=360:T<-180&&(u+=360);break;case"longer":-1800?i+=360:u+=360);break;case"increasing":T<0&&(u+=360);break;case"decreasing":T>0&&(i+=360);break;default:throw new Error("Unknown hue interpolation method")}c=premultiply(c,y),N=premultiply(N,y),p=premultiply(p,x),m=premultiply(m,x);let b=[0,0,0];const C=interpolate(y,x,r);switch(e){case"hsl":case"hwb":b=[interpolate(i,u,r),un_premultiply(interpolate(c,p,r),C),un_premultiply(interpolate(N,m,r),C)];break;case"lch":case"oklch":b=[un_premultiply(interpolate(c,p,r),C),un_premultiply(interpolate(N,m,r),C),interpolate(i,u,r)]}const d={colorNotation:h,channels:b,alpha:C*a.alphaMultiplier,syntaxFlags:new Set([exports.SyntaxFlag.ColorMix])};return(a.a.color.syntaxFlags.has(exports.SyntaxFlag.Experimental)||a.b.color.syntaxFlags.has(exports.SyntaxFlag.Experimental))&&d.syntaxFlags.add(exports.SyntaxFlag.Experimental),d}function fillInMissingComponent(e,o){return Number.isNaN(e)?o:e}function interpolate(e,o,a){return e*a+o*(1-a)}function premultiply(e,o){return Number.isNaN(o)?e:Number.isNaN(e)?NaN:e*o}function un_premultiply(e,o){return 0===o||Number.isNaN(o)?e:Number.isNaN(e)?NaN:e/o}function hex(e){const o=toLowerCaseAZ(e[4].value);if(o.match(/[^a-f0-9]/))return!1;const a={colorNotation:exports.ColorNotation.HEX,channels:[0,0,0],alpha:1,syntaxFlags:new Set([exports.SyntaxFlag.Hex])},n=o.length;if(3===n){const e=o[0],n=o[1],t=o[2];return a.channels=[parseInt(e+e,16)/255,parseInt(n+n,16)/255,parseInt(t+t,16)/255],a}if(6===n){const e=o[0]+o[1],n=o[2]+o[3],t=o[4]+o[5];return a.channels=[parseInt(e,16)/255,parseInt(n,16)/255,parseInt(t,16)/255],a}if(4===n){const e=o[0],n=o[1],t=o[2],r=o[3];return a.channels=[parseInt(e+e,16)/255,parseInt(n+n,16)/255,parseInt(t+t,16)/255],a.alpha=parseInt(r+r,16)/255,a.syntaxFlags.add(exports.SyntaxFlag.HasAlpha),a}if(8===n){const e=o[0]+o[1],n=o[2]+o[3],t=o[4]+o[5],r=o[6]+o[7];return a.channels=[parseInt(e,16)/255,parseInt(n,16)/255,parseInt(t,16)/255],a.alpha=parseInt(r,16)/255,a.syntaxFlags.add(exports.SyntaxFlag.HasAlpha),a}return!1}function normalizeHue(e){if(e[0]===a.TokenType.Number)return e[4].value=e[4].value%360,e[1]=e[4].value.toString(),e;if(e[0]===a.TokenType.Dimension){let o=e[4].value;switch(toLowerCaseAZ(e[4].unit)){case"deg":break;case"rad":o=180*e[4].value/Math.PI;break;case"grad":o=.9*e[4].value;break;case"turn":o=360*e[4].value;break;default:return!1}return o%=360,[a.TokenType.Number,o.toString(),e[2],e[3],{value:o,type:a.NumberType.Number}]}return!1}function normalize_legacy_HSL_ChannelValues(e,o,n){if(0===o){const o=normalizeHue(e);return!1!==o&&(e[0]===a.TokenType.Dimension&&n.syntaxFlags.add(exports.SyntaxFlag.HasDimensionValues),o)}if(e[0]===a.TokenType.Percentage){3===o?n.syntaxFlags.add(exports.SyntaxFlag.HasPercentageAlpha):n.syntaxFlags.add(exports.SyntaxFlag.HasPercentageValues);let t=normalize(e[4].value,1,0,100);return 3===o&&(t=normalize(e[4].value,100,0,1)),[a.TokenType.Number,t.toString(),e[2],e[3],{value:t,type:a.NumberType.Number}]}if(e[0]===a.TokenType.Number){if(3!==o)return!1;let n=normalize(e[4].value,1,0,100);return 3===o&&(n=normalize(e[4].value,1,0,1)),[a.TokenType.Number,n.toString(),e[2],e[3],{value:n,type:a.NumberType.Number}]}return!1}function normalize_modern_HSL_ChannelValues(e,o,n){if(e[0]===a.TokenType.Ident&&"none"===toLowerCaseAZ(e[4].value))return n.syntaxFlags.add(exports.SyntaxFlag.HasNoneKeywords),[a.TokenType.Number,"none",e[2],e[3],{value:NaN,type:a.NumberType.Number}];if(0===o){const o=normalizeHue(e);return!1!==o&&(e[0]===a.TokenType.Dimension&&n.syntaxFlags.add(exports.SyntaxFlag.HasDimensionValues),o)}if(e[0]===a.TokenType.Percentage){3===o?n.syntaxFlags.add(exports.SyntaxFlag.HasPercentageAlpha):n.syntaxFlags.add(exports.SyntaxFlag.HasPercentageValues);let t=e[4].value;return 3===o&&(t=normalize(e[4].value,100,0,1)),[a.TokenType.Number,t.toString(),e[2],e[3],{value:t,type:a.NumberType.Number}]}if(e[0]===a.TokenType.Number){3!==o&&n.syntaxFlags.add(exports.SyntaxFlag.HasNumberValues);let t=e[4].value;return 3===o&&(t=normalize(e[4].value,1,0,1)),[a.TokenType.Number,t.toString(),e[2],e[3],{value:t,type:a.NumberType.Number}]}return!1}function threeChannelLegacySyntax(e,o,n,l){const s=[],i=[],u=[],c=[],p={colorNotation:n,channels:[0,0,0],alpha:1,syntaxFlags:new Set(l)};let N=s;for(let o=0;ot.isTokenNode(e)&&e.value[0]===a.TokenType.Comma))){const o=hslCommaSeparated(e);if(!1!==o)return o}{const a=hslSpaceSeparated(e,o);if(!1!==a)return a}return!1}function hslCommaSeparated(e){return threeChannelLegacySyntax(e,normalize_legacy_HSL_ChannelValues,exports.ColorNotation.HSL,[exports.SyntaxFlag.LegacyHSL])}function hslSpaceSeparated(e,o){return threeChannelSpaceSeparated(e,normalize_modern_HSL_ChannelValues,exports.ColorNotation.HSL,[],o)}function normalize_HWB_ChannelValues(e,o,n){if(e[0]===a.TokenType.Ident&&"none"===toLowerCaseAZ(e[4].value))return n.syntaxFlags.add(exports.SyntaxFlag.HasNoneKeywords),[a.TokenType.Number,"none",e[2],e[3],{value:NaN,type:a.NumberType.Number}];if(0===o){const o=normalizeHue(e);return!1!==o&&(e[0]===a.TokenType.Dimension&&n.syntaxFlags.add(exports.SyntaxFlag.HasDimensionValues),o)}if(e[0]===a.TokenType.Percentage){3===o?n.syntaxFlags.add(exports.SyntaxFlag.HasPercentageAlpha):n.syntaxFlags.add(exports.SyntaxFlag.HasPercentageValues);let t=e[4].value;return 3===o&&(t=normalize(e[4].value,100,0,1)),[a.TokenType.Number,t.toString(),e[2],e[3],{value:t,type:a.NumberType.Number}]}if(e[0]===a.TokenType.Number){3!==o&&n.syntaxFlags.add(exports.SyntaxFlag.HasNumberValues);let t=e[4].value;return 3===o&&(t=normalize(e[4].value,1,0,1)),[a.TokenType.Number,t.toString(),e[2],e[3],{value:t,type:a.NumberType.Number}]}return!1}function normalize_Lab_ChannelValues(e,o,n){if(e[0]===a.TokenType.Ident&&"none"===toLowerCaseAZ(e[4].value))return n.syntaxFlags.add(exports.SyntaxFlag.HasNoneKeywords),[a.TokenType.Number,"none",e[2],e[3],{value:NaN,type:a.NumberType.Number}];if(e[0]===a.TokenType.Percentage){3!==o&&n.syntaxFlags.add(exports.SyntaxFlag.HasPercentageValues);let t=normalize(e[4].value,1,0,100);return 1===o||2===o?t=normalize(e[4].value,.8,-1/0,1/0):3===o&&(t=normalize(e[4].value,100,0,1)),[a.TokenType.Number,t.toString(),e[2],e[3],{value:t,type:a.NumberType.Number}]}if(e[0]===a.TokenType.Number){3!==o&&n.syntaxFlags.add(exports.SyntaxFlag.HasNumberValues);let t=normalize(e[4].value,1,0,100);return 1===o||2===o?t=normalize(e[4].value,1,-1/0,1/0):3===o&&(t=normalize(e[4].value,1,0,1)),[a.TokenType.Number,t.toString(),e[2],e[3],{value:t,type:a.NumberType.Number}]}return!1}function lab(e,o){return threeChannelSpaceSeparated(e,normalize_Lab_ChannelValues,exports.ColorNotation.Lab,[],o)}function normalize_LCH_ChannelValues(e,o,n){if(e[0]===a.TokenType.Ident&&"none"===toLowerCaseAZ(e[4].value))return n.syntaxFlags.add(exports.SyntaxFlag.HasNoneKeywords),[a.TokenType.Number,"none",e[2],e[3],{value:NaN,type:a.NumberType.Number}];if(2===o){const o=normalizeHue(e);return!1!==o&&(e[0]===a.TokenType.Dimension&&n.syntaxFlags.add(exports.SyntaxFlag.HasDimensionValues),o)}if(e[0]===a.TokenType.Percentage){3!==o&&n.syntaxFlags.add(exports.SyntaxFlag.HasPercentageValues);let t=normalize(e[4].value,1,0,100);return 1===o?t=normalize(e[4].value,100/150,0,1/0):3===o&&(t=normalize(e[4].value,100,0,1)),[a.TokenType.Number,t.toString(),e[2],e[3],{value:t,type:a.NumberType.Number}]}if(e[0]===a.TokenType.Number){3!==o&&n.syntaxFlags.add(exports.SyntaxFlag.HasNumberValues);let t=normalize(e[4].value,1,0,100);return 1===o?t=normalize(e[4].value,1,0,1/0):3===o&&(t=normalize(e[4].value,1,0,1)),[a.TokenType.Number,t.toString(),e[2],e[3],{value:t,type:a.NumberType.Number}]}return!1}function lch(e,o){return threeChannelSpaceSeparated(e,normalize_LCH_ChannelValues,exports.ColorNotation.LCH,[],o)}const N=new Map;for(const[e,o]of Object.entries(n.namedColors))N.set(e,o);function namedColor(e){const o=N.get(toLowerCaseAZ(e));return!!o&&{colorNotation:exports.ColorNotation.RGB,channels:[o[0]/255,o[1]/255,o[2]/255],alpha:1,syntaxFlags:new Set([exports.SyntaxFlag.ColorKeyword,exports.SyntaxFlag.NamedColor])}}function normalize_OKLab_ChannelValues(e,o,n){if(e[0]===a.TokenType.Ident&&"none"===toLowerCaseAZ(e[4].value))return n.syntaxFlags.add(exports.SyntaxFlag.HasNoneKeywords),[a.TokenType.Number,"none",e[2],e[3],{value:NaN,type:a.NumberType.Number}];if(e[0]===a.TokenType.Percentage){3!==o&&n.syntaxFlags.add(exports.SyntaxFlag.HasPercentageValues);let t=normalize(e[4].value,100,0,1);return 1===o||2===o?t=normalize(e[4].value,250,-1/0,1/0):3===o&&(t=normalize(e[4].value,100,0,1)),[a.TokenType.Number,t.toString(),e[2],e[3],{value:t,type:a.NumberType.Number}]}if(e[0]===a.TokenType.Number){3!==o&&n.syntaxFlags.add(exports.SyntaxFlag.HasNumberValues);let t=normalize(e[4].value,1,0,1);return 1===o||2===o?t=normalize(e[4].value,1,-1/0,1/0):3===o&&(t=normalize(e[4].value,1,0,1)),[a.TokenType.Number,t.toString(),e[2],e[3],{value:t,type:a.NumberType.Number}]}return!1}function oklab(e,o){return threeChannelSpaceSeparated(e,normalize_OKLab_ChannelValues,exports.ColorNotation.OKLab,[],o)}function normalize_OKLCH_ChannelValues(e,o,n){if(e[0]===a.TokenType.Ident&&"none"===toLowerCaseAZ(e[4].value))return n.syntaxFlags.add(exports.SyntaxFlag.HasNoneKeywords),[a.TokenType.Number,"none",e[2],e[3],{value:NaN,type:a.NumberType.Number}];if(2===o){const o=normalizeHue(e);return!1!==o&&(e[0]===a.TokenType.Dimension&&n.syntaxFlags.add(exports.SyntaxFlag.HasDimensionValues),o)}if(e[0]===a.TokenType.Percentage){3!==o&&n.syntaxFlags.add(exports.SyntaxFlag.HasPercentageValues);let t=normalize(e[4].value,100,0,1);return 1===o?t=normalize(e[4].value,250,0,1/0):3===o&&(t=normalize(e[4].value,100,0,1)),[a.TokenType.Number,t.toString(),e[2],e[3],{value:t,type:a.NumberType.Number}]}if(e[0]===a.TokenType.Number){3!==o&&n.syntaxFlags.add(exports.SyntaxFlag.HasNumberValues);let t=normalize(e[4].value,1,0,1);return 1===o?t=normalize(e[4].value,1,0,1/0):3===o&&(t=normalize(e[4].value,1,0,1)),[a.TokenType.Number,t.toString(),e[2],e[3],{value:t,type:a.NumberType.Number}]}return!1}function oklch(e,o){return threeChannelSpaceSeparated(e,normalize_OKLCH_ChannelValues,exports.ColorNotation.OKLCH,[],o)}function normalize_legacy_sRGB_ChannelValues(e,o,n){if(e[0]===a.TokenType.Percentage){3===o?n.syntaxFlags.add(exports.SyntaxFlag.HasPercentageAlpha):n.syntaxFlags.add(exports.SyntaxFlag.HasPercentageValues);const t=normalize(e[4].value,100,0,1);return[a.TokenType.Number,t.toString(),e[2],e[3],{value:t,type:a.NumberType.Number}]}if(e[0]===a.TokenType.Number){3!==o&&n.syntaxFlags.add(exports.SyntaxFlag.HasNumberValues);let t=normalize(e[4].value,255,0,1);return 3===o&&(t=normalize(e[4].value,1,0,1)),[a.TokenType.Number,t.toString(),e[2],e[3],{value:t,type:a.NumberType.Number}]}return!1}function normalize_modern_sRGB_ChannelValues(e,o,n){if(e[0]===a.TokenType.Ident&&"none"===toLowerCaseAZ(e[4].value))return n.syntaxFlags.add(exports.SyntaxFlag.HasNoneKeywords),[a.TokenType.Number,"none",e[2],e[3],{value:NaN,type:a.NumberType.Number}];if(e[0]===a.TokenType.Percentage){3!==o&&n.syntaxFlags.add(exports.SyntaxFlag.HasPercentageValues);let t=normalize(e[4].value,100,-1/0,1/0);return 3===o&&(t=normalize(e[4].value,100,0,1)),[a.TokenType.Number,t.toString(),e[2],e[3],{value:t,type:a.NumberType.Number}]}if(e[0]===a.TokenType.Number){3!==o&&n.syntaxFlags.add(exports.SyntaxFlag.HasNumberValues);let t=normalize(e[4].value,255,-1/0,1/0);return 3===o&&(t=normalize(e[4].value,1,0,1)),[a.TokenType.Number,t.toString(),e[2],e[3],{value:t,type:a.NumberType.Number}]}return!1}function rgb(e,o){if(e.value.some((e=>t.isTokenNode(e)&&e.value[0]===a.TokenType.Comma))){const o=rgbCommaSeparated(e);if(!1!==o)return(!o.syntaxFlags.has(exports.SyntaxFlag.HasNumberValues)||!o.syntaxFlags.has(exports.SyntaxFlag.HasPercentageValues))&&o}else{const a=rgbSpaceSeparated(e,o);if(!1!==a)return a}return!1}function rgbCommaSeparated(e){return threeChannelLegacySyntax(e,normalize_legacy_sRGB_ChannelValues,exports.ColorNotation.RGB,[exports.SyntaxFlag.LegacyRGB])}function rgbSpaceSeparated(e,o){return threeChannelSpaceSeparated(e,normalize_modern_sRGB_ChannelValues,exports.ColorNotation.RGB,[],o)}function toPrecision(e,o=7){e=+e,o=+o;const a=(Math.floor(e)+"").length;if(o>a)return+e.toFixed(o-a);{const n=10**(a-o);return Math.round(e/n)*n}}function XYZ_D50_to_P3_Gamut(e){const o=n.XYZ_D50_to_P3(e);if(n.inGamut(o))return n.clip(o);let a=e.slice();return a=n.XYZ_D50_to_OKLCH(a),a[0]<1e-6&&(a=[0,0,0]),a[0]>.999999&&(a=[1,0,0]),n.mapGamut(a,(e=>(e=n.OKLCH_to_OKLab(e),e=n.OKLab_to_XYZ(e),e=n.XYZ_to_lin_P3(e),n.gam_P3(e))),(e=>(e=n.lin_P3(e),e=n.lin_P3_to_XYZ(e),e=n.XYZ_to_OKLab(e),n.OKLab_to_OKLCH(e))))}function serializeWithAlpha(e,o,n,r){const l=[a.TokenType.CloseParen,")",-1,-1,void 0];if("number"==typeof e.alpha){const s=Math.min(1,Math.max(0,toPrecision(Number.isNaN(e.alpha)?0:e.alpha)));return 1===toPrecision(s,4)?new t.FunctionNode(o,l,r):new t.FunctionNode(o,l,[...r,new t.WhitespaceNode([n]),new t.TokenNode([a.TokenType.Delim,"/",-1,-1,{value:"/"}]),new t.WhitespaceNode([n]),new t.TokenNode([a.TokenType.Number,toPrecision(s,4).toString(),-1,-1,{value:e.alpha,type:a.NumberType.Integer}])])}return new t.FunctionNode(o,l,[...r,new t.WhitespaceNode([n]),new t.TokenNode([a.TokenType.Delim,"/",-1,-1,{value:"/"}]),new t.WhitespaceNode([n]),e.alpha])}function XYZ_D50_to_sRGB_Gamut(e){const o=n.XYZ_D50_to_sRGB(e);if(n.inGamut(o))return n.clip(o);let a=e.slice();return a=n.XYZ_D50_to_OKLCH(a),a[0]<1e-6&&(a=[0,0,0]),a[0]>.999999&&(a=[1,0,0]),n.mapGamut(a,(e=>(e=n.OKLCH_to_OKLab(e),e=n.OKLab_to_XYZ(e),e=n.XYZ_to_lin_sRGB(e),n.gam_sRGB(e))),(e=>(e=n.lin_sRGB(e),e=n.lin_sRGB_to_XYZ(e),e=n.XYZ_to_OKLab(e),n.OKLab_to_OKLCH(e))))}exports.color=function color(e){if(t.isFunctionNode(e)){switch(toLowerCaseAZ(e.getName())){case"rgb":case"rgba":return rgb(e,color);case"hsl":case"hsla":return hsl(e,color);case"hwb":return o=color,threeChannelSpaceSeparated(e,normalize_HWB_ChannelValues,exports.ColorNotation.HWB,[],o);case"lab":return lab(e,color);case"lch":return lch(e,color);case"oklab":return oklab(e,color);case"oklch":return oklch(e,color);case"color":return color$1(e,color);case"color-mix":return colorMix(e,color)}}var o;if(t.isTokenNode(e)){if(e.value[0]===a.TokenType.Hash)return hex(e.value);if(e.value[0]===a.TokenType.Ident){const o=namedColor(e.value[4].value);return!1!==o?o:"transparent"===toLowerCaseAZ(e.value[4].value)&&{colorNotation:exports.ColorNotation.RGB,channels:[0,0,0],alpha:0,syntaxFlags:new Set([exports.SyntaxFlag.ColorKeyword])}}}return!1},exports.colorDataFitsDisplayP3_Gamut=function colorDataFitsDisplayP3_Gamut(e){const o={...e,channels:[...e.channels]};return o.channels=convertPowerlessComponentsToZeroValuesForDisplay(o.channels,o.colorNotation),!colorDataTo(o,exports.ColorNotation.Display_P3).channels.find((e=>e<-1e-5||e>1.00001))},exports.colorDataFitsRGB_Gamut=function colorDataFitsRGB_Gamut(e){const o={...e,channels:[...e.channels]};return o.channels=convertPowerlessComponentsToZeroValuesForDisplay(o.channels,o.colorNotation),!colorDataTo(o,exports.ColorNotation.RGB).channels.find((e=>e<-1e-5||e>1.00001))},exports.colorDataTo=colorDataTo,exports.serializeHSL=function serializeHSL(e,o=!0){e.channels=convertPowerlessComponentsToZeroValuesForDisplay(e.channels,e.colorNotation);let r=e.channels.map((e=>Number.isNaN(e)?0:e));r=o?n.XYZ_D50_to_HSL(n.sRGB_to_XYZ_D50(XYZ_D50_to_sRGB_Gamut(colorData_to_XYZ_D50(e).channels))):n.XYZ_D50_to_HSL(colorData_to_XYZ_D50(e).channels),r=r.map((e=>Number.isNaN(e)?0:e));const l=Math.min(360,Math.max(0,Math.round(toPrecision(r[0])))),s=Math.min(100,Math.max(0,Math.round(toPrecision(r[1])))),i=Math.min(100,Math.max(0,Math.round(toPrecision(r[2])))),u=[a.TokenType.CloseParen,")",-1,-1,void 0],c=[a.TokenType.Whitespace," ",-1,-1,void 0],p=[a.TokenType.Comma,",",-1,-1,void 0],N=[new t.TokenNode([a.TokenType.Number,l.toString(),-1,-1,{value:r[0],type:a.NumberType.Integer}]),new t.TokenNode(p),new t.WhitespaceNode([c]),new t.TokenNode([a.TokenType.Percentage,s.toString()+"%",-1,-1,{value:r[1]}]),new t.TokenNode(p),new t.WhitespaceNode([c]),new t.TokenNode([a.TokenType.Percentage,i.toString()+"%",-1,-1,{value:r[2]}])];if("number"==typeof e.alpha){const o=Math.min(1,Math.max(0,toPrecision(Number.isNaN(e.alpha)?0:e.alpha)));return 1===toPrecision(o,4)?new t.FunctionNode([a.TokenType.Function,"hsl(",-1,-1,{value:"hsl"}],u,N):new t.FunctionNode([a.TokenType.Function,"hsla(",-1,-1,{value:"hsla"}],u,[...N,new t.TokenNode(p),new t.WhitespaceNode([c]),new t.TokenNode([a.TokenType.Number,toPrecision(o,4).toString(),-1,-1,{value:e.alpha,type:a.NumberType.Number}])])}return new t.FunctionNode([a.TokenType.Function,"hsla(",-1,-1,{value:"hsla"}],u,[...N,new t.TokenNode(p),new t.WhitespaceNode([c]),e.alpha])},exports.serializeOKLCH=function serializeOKLCH(e){e.channels=convertPowerlessComponentsToZeroValuesForDisplay(e.channels,e.colorNotation);let o=e.channels.map((e=>Number.isNaN(e)?0:e));e.colorNotation!==exports.ColorNotation.OKLCH&&(o=n.XYZ_D50_to_OKLCH(colorData_to_XYZ_D50(e).channels));const r=toPrecision(o[0],6),l=toPrecision(o[1],6),s=toPrecision(o[2],6),i=[a.TokenType.Function,"oklch(",-1,-1,{value:"oklch"}],u=[a.TokenType.Whitespace," ",-1,-1,void 0];return serializeWithAlpha(e,i,u,[new t.TokenNode([a.TokenType.Number,r.toString(),-1,-1,{value:o[0],type:a.NumberType.Number}]),new t.WhitespaceNode([u]),new t.TokenNode([a.TokenType.Number,l.toString(),-1,-1,{value:o[1],type:a.NumberType.Number}]),new t.WhitespaceNode([u]),new t.TokenNode([a.TokenType.Number,s.toString(),-1,-1,{value:o[2],type:a.NumberType.Number}])])},exports.serializeP3=function serializeP3(e,o=!0){e.channels=convertPowerlessComponentsToZeroValuesForDisplay(e.channels,e.colorNotation);let r=e.channels.map((e=>Number.isNaN(e)?0:e));e.colorNotation!==exports.ColorNotation.Display_P3&&(r=o?XYZ_D50_to_P3_Gamut(colorData_to_XYZ_D50(e).channels):n.XYZ_D50_to_P3(colorData_to_XYZ_D50(e).channels));const l=toPrecision(r[0],6),s=toPrecision(r[1],6),i=toPrecision(r[2],6),u=[a.TokenType.Function,"color(",-1,-1,{value:"color"}],c=[a.TokenType.Whitespace," ",-1,-1,void 0];return serializeWithAlpha(e,u,c,[new t.TokenNode([a.TokenType.Ident,"display-p3",-1,-1,{value:"display-p3"}]),new t.WhitespaceNode([c]),new t.TokenNode([a.TokenType.Number,l.toString(),-1,-1,{value:r[0],type:a.NumberType.Number}]),new t.WhitespaceNode([c]),new t.TokenNode([a.TokenType.Number,s.toString(),-1,-1,{value:r[1],type:a.NumberType.Number}]),new t.WhitespaceNode([c]),new t.TokenNode([a.TokenType.Number,i.toString(),-1,-1,{value:r[2],type:a.NumberType.Number}])])},exports.serializeRGB=function serializeRGB(e,o=!0){e.channels=convertPowerlessComponentsToZeroValuesForDisplay(e.channels,e.colorNotation);let r=e.channels.map((e=>Number.isNaN(e)?0:e));r=o?XYZ_D50_to_sRGB_Gamut(colorData_to_XYZ_D50(e).channels):n.XYZ_D50_to_sRGB(colorData_to_XYZ_D50(e).channels);const l=Math.min(255,Math.max(0,Math.round(255*toPrecision(r[0])))),s=Math.min(255,Math.max(0,Math.round(255*toPrecision(r[1])))),i=Math.min(255,Math.max(0,Math.round(255*toPrecision(r[2])))),u=[a.TokenType.CloseParen,")",-1,-1,void 0],c=[a.TokenType.Whitespace," ",-1,-1,void 0],p=[a.TokenType.Comma,",",-1,-1,void 0],N=[new t.TokenNode([a.TokenType.Number,l.toString(),-1,-1,{value:r[0],type:a.NumberType.Integer}]),new t.TokenNode(p),new t.WhitespaceNode([c]),new t.TokenNode([a.TokenType.Number,s.toString(),-1,-1,{value:r[1],type:a.NumberType.Integer}]),new t.TokenNode(p),new t.WhitespaceNode([c]),new t.TokenNode([a.TokenType.Number,i.toString(),-1,-1,{value:r[2],type:a.NumberType.Integer}])];if("number"==typeof e.alpha){const o=Math.min(1,Math.max(0,toPrecision(Number.isNaN(e.alpha)?0:e.alpha)));return 1===toPrecision(o,4)?new t.FunctionNode([a.TokenType.Function,"rgb(",-1,-1,{value:"rgb"}],u,N):new t.FunctionNode([a.TokenType.Function,"rgba(",-1,-1,{value:"rgba"}],u,[...N,new t.TokenNode(p),new t.WhitespaceNode([c]),new t.TokenNode([a.TokenType.Number,toPrecision(o,4).toString(),-1,-1,{value:e.alpha,type:a.NumberType.Number}])])}return new t.FunctionNode([a.TokenType.Function,"rgba(",-1,-1,{value:"rgba"}],u,[...N,new t.TokenNode(p),new t.WhitespaceNode([c]),e.alpha])}; diff --git a/packages/css-color-parser/dist/index.d.ts b/packages/css-color-parser/dist/index.d.ts index 18c8e03c4..fa641ac5c 100644 --- a/packages/css-color-parser/dist/index.d.ts +++ b/packages/css-color-parser/dist/index.d.ts @@ -1,13 +1,7 @@ -import type { ColorData } from './color-data'; +import type { Color } from '@csstools/color-helpers'; import type { ComponentValue } from '@csstools/css-parser-algorithms'; -export type { ColorData } from './color-data'; -export { ColorNotation } from './color-notation'; -export { SyntaxFlag } from './color-data'; -export { colorDataTo, colorDataFitsRGB_Gamut, colorDataFitsDisplayP3_Gamut } from './color-data'; -export { serializeP3 } from './serialize/p3'; -export { serializeRGB } from './serialize/rgb'; -export { serializeHSL } from './serialize/hsl'; -export { serializeOKLCH } from './serialize/oklch'; +import { FunctionNode } from '@csstools/css-parser-algorithms'; + /** * Convert a color function to a `ColorData` object. * @@ -15,3 +9,129 @@ export { serializeOKLCH } from './serialize/oklch'; * @returns {ColorData|false} The color function as a `ColorData` object or `false` if it could not be converted. */ export declare function color(colorNode: ComponentValue): ColorData | false; + +export declare type ColorData = { + colorNotation: ColorNotation; + channels: Color; + alpha: number | ComponentValue; + syntaxFlags: Set; +}; + +/** + * Check if a color data object fits the `display-p3` gamut. + * + * @param {ColorData} x - The color data to be checked. + * @returns {boolean} Whether the color data fits the `display-p3` gamut. + */ +export declare function colorDataFitsDisplayP3_Gamut(x: ColorData): boolean; + +/** + * Check if a color data object fits the `sRGB` gamut. + * + * @param {ColorData} x - The color data to be checked. + * @returns {boolean} Whether the color data fits the `sRGB` gamut. + */ +export declare function colorDataFitsRGB_Gamut(x: ColorData): boolean; + +export declare function colorDataTo(colorData: ColorData, toNotation: ColorNotation): ColorData; + +export declare enum ColorNotation { + /** Adobe 1999, expressed through `color(a98-rgb 0 0 0)` */ + A98_RGB = "a98-rgb", + /** Display P3, expressed through `color(display-p3 0 0 0)` */ + Display_P3 = "display-p3", + /** Hex, expressed through `#000` */ + HEX = "hex", + /** HSL, expressed through `hsl(0 0% 0%)` */ + HSL = "hsl", + /** HWB, expressed through `hwb(0 0% 0%)` */ + HWB = "hwb", + /** LCH, expressed through `lch(0 0% 0deg)` */ + LCH = "lch", + /** Lab, expressed through `lab(0 0 0)` */ + Lab = "lab", + /** Linear sRGB, expressed through `color(linear-srgb 0 0 0)` */ + Linear_sRGB = "srgb-linear", + /** Oklch, expressed through `oklch(0 0% 0deg)` */ + OKLCH = "oklch", + /** Oklab, expressed through `oklab(0 0 0)` */ + OKLab = "oklab", + /** ProPhoto RGB, expressed through `color(prophoto-rgb 0 0 0)` */ + ProPhoto_RGB = "prophoto-rgb", + /** RGB, expressed through `rgb(0 0 0)` */ + RGB = "rgb", + /** sRGB, expressed through `color(srgb 0 0 0)` */ + sRGB = "srgb", + /** Rec. 2020, expressed through `color(rec2020 0 0 0)` */ + Rec2020 = "rec2020", + /** XYZ, expressed through `color(xyz-d50 0 0 0)` */ + XYZ_D50 = "xyz-d50", + /** XYZ, expressed through `color(xyz-d65 0 0 0)` */ + XYZ_D65 = "xyz-d65" +} + +export declare function serializeHSL(color: ColorData, gamutMapping?: boolean): FunctionNode; + +/** + * Convert color data to component values in the OKLCH color space. + * The return value can be converted to a string by calling `toString()` on it. + * + * @param {ColorData} color - The color data to be serialized. + * @returns {FunctionNode} The serialized color data as a FunctionNode object. + */ +export declare function serializeOKLCH(color: ColorData): FunctionNode; + +/** + * Convert color data to component values in the display-p3 color space. + * The return value can be converted to a string by calling `toString()` on it. + * + * @param {ColorData} color - The color data to be serialized. + * @param {boolean} gamutMapping - Whether to perform gamut mapping, defaults to `true`. + * @returns {FunctionNode} The serialized color data as a FunctionNode object. + */ +export declare function serializeP3(color: ColorData, gamutMapping?: boolean): FunctionNode; + +/** + * Convert color data to component values in the srgb color space. + * The return value can be converted to a string by calling `toString()` on it. + * + * @param {ColorData} color - The color data to be serialized. + * @param {boolean} gamutMapping - Whether to perform gamut mapping, defaults to `true`. + * @returns {FunctionNode} The serialized color data as a FunctionNode object. + */ +export declare function serializeRGB(color: ColorData, gamutMapping?: boolean): FunctionNode; + +export declare enum SyntaxFlag { + /** Is a color keyword, e.g. `transparent`, `currentColor`, ... */ + ColorKeyword = "color-keyword", + /** Has an explicit alpha channel */ + HasAlpha = "has-alpha", + /** Has a channel with a dimension value, e.g. `50deg` */ + HasDimensionValues = "has-dimension-values", + /** Has a channel with the `none` keyword */ + HasNoneKeywords = "has-none-keywords", + /** Has a channel with a number value */ + HasNumberValues = "has-number-values", + /** Has an alpha channel with a percentage value */ + HasPercentageAlpha = "has-percentage-alpha", + /** Has a channel with a percentage value */ + HasPercentageValues = "has-percentage-values", + /** Has an alpha channel with a `var()` function value */ + HasVariableAlpha = "has-variable-alpha", + /** Is Hex notation */ + Hex = "hex", + /** Is legacy HSL, e.g. `hsl(50deg, 0%, 0%)` */ + LegacyHSL = "legacy-hsl", + /** Is legacy RGB, e.g. `rgb(0, 0, 0)` */ + LegacyRGB = "legacy-rgb", + /** Is a named color, e.g. `red`, `blue` */ + NamedColor = "named-color", + /** Is a relative color syntax, e.g. `rgb(from purple r g b)` */ + RelativeColorSyntax = "relative-color-syntax", + /** Is a mixed color, e.g. `color-mix(in oklch, red, blue)` */ + ColorMix = "color-mix", + /** Is an experimental color syntax */ + Experimental = "experimental" +} + +export { } diff --git a/packages/css-color-parser/dist/index.mjs b/packages/css-color-parser/dist/index.mjs index b84e0b727..b3e7ae9b2 100644 --- a/packages/css-color-parser/dist/index.mjs +++ b/packages/css-color-parser/dist/index.mjs @@ -1 +1 @@ -import{TokenType as e,NumberType as a}from"@csstools/css-tokenizer";import{xyz as n,namedColors as r,utils as o,conversions as t,calculations as l}from"@csstools/color-helpers";import{isWhitespaceNode as s,isCommentNode as u,isTokenNode as i,isFunctionNode as c,TokenNode as m,FunctionNode as h,WhitespaceNode as N}from"@csstools/css-parser-algorithms";import{mathFunctionNames as p,calcFromComponentValues as b}from"@csstools/css-calc";var _,g;function colorData_to_XYZ_D50(e){switch(e.colorNotation){case _.HEX:case _.RGB:case _.sRGB:return{...e,colorNotation:_.XYZ_D50,channels:n.sRGB_to_XYZ_D50(e.channels.map((e=>Number.isNaN(e)?0:e)))};case _.Linear_sRGB:return{...e,colorNotation:_.XYZ_D50,channels:n.lin_sRGB_to_XYZ_D50(e.channels.map((e=>Number.isNaN(e)?0:e)))};case _.Display_P3:return{...e,colorNotation:_.XYZ_D50,channels:n.P3_to_XYZ_D50(e.channels.map((e=>Number.isNaN(e)?0:e)))};case _.Rec2020:return{...e,colorNotation:_.XYZ_D50,channels:n.rec_2020_to_XYZ_D50(e.channels.map((e=>Number.isNaN(e)?0:e)))};case _.A98_RGB:return{...e,colorNotation:_.XYZ_D50,channels:n.a98_RGB_to_XYZ_D50(e.channels.map((e=>Number.isNaN(e)?0:e)))};case _.ProPhoto_RGB:return{...e,colorNotation:_.XYZ_D50,channels:n.ProPhoto_RGB_to_XYZ_D50(e.channels.map((e=>Number.isNaN(e)?0:e)))};case _.HSL:return{...e,colorNotation:_.XYZ_D50,channels:n.HSL_to_XYZ_D50(e.channels.map((e=>Number.isNaN(e)?0:e)))};case _.HWB:return{...e,colorNotation:_.XYZ_D50,channels:n.HWB_to_XYZ_D50(e.channels.map((e=>Number.isNaN(e)?0:e)))};case _.Lab:return{...e,colorNotation:_.XYZ_D50,channels:n.Lab_to_XYZ_D50(e.channels.map((e=>Number.isNaN(e)?0:e)))};case _.OKLab:return{...e,colorNotation:_.XYZ_D50,channels:n.OKLab_to_XYZ_D50(e.channels.map((e=>Number.isNaN(e)?0:e)))};case _.LCH:return{...e,colorNotation:_.XYZ_D50,channels:n.LCH_to_XYZ_D50(e.channels.map((e=>Number.isNaN(e)?0:e)))};case _.OKLCH:return{...e,colorNotation:_.XYZ_D50,channels:n.OKLCH_to_XYZ_D50(e.channels.map((e=>Number.isNaN(e)?0:e)))};case _.XYZ_D50:return{...e,colorNotation:_.XYZ_D50,channels:n.XYZ_D50_to_XYZ_D50(e.channels.map((e=>Number.isNaN(e)?0:e)))};case _.XYZ_D65:return{...e,colorNotation:_.XYZ_D50,channels:n.XYZ_D65_to_XYZ_D50(e.channels.map((e=>Number.isNaN(e)?0:e)))};default:throw new Error("Unsupported color notation")}}!function(e){e.A98_RGB="a98-rgb",e.Display_P3="display-p3",e.HEX="hex",e.HSL="hsl",e.HWB="hwb",e.LCH="lch",e.Lab="lab",e.Linear_sRGB="srgb-linear",e.OKLCH="oklch",e.OKLab="oklab",e.ProPhoto_RGB="prophoto-rgb",e.RGB="rgb",e.sRGB="srgb",e.Rec2020="rec2020",e.XYZ_D50="xyz-d50",e.XYZ_D65="xyz-d65"}(_||(_={})),function(e){e.ColorKeyword="color-keyword",e.HasAlpha="has-alpha",e.HasDimensionValues="has-dimension-values",e.HasNoneKeywords="has-none-keywords",e.HasNumberValues="has-number-values",e.HasPercentageAlpha="has-percentage-alpha",e.HasPercentageValues="has-percentage-values",e.HasVariableAlpha="has-variable-alpha",e.Hex="hex",e.LegacyHSL="legacy-hsl",e.LegacyRGB="legacy-rgb",e.NamedColor="named-color",e.RelativeColorSyntax="relative-color-syntax",e.ColorMix="color-mix",e.Experimental="experimental"}(g||(g={}));const v=new Set([_.A98_RGB,_.Display_P3,_.HEX,_.Linear_sRGB,_.ProPhoto_RGB,_.RGB,_.sRGB,_.Rec2020,_.XYZ_D50,_.XYZ_D65]);function colorDataTo(e,a){const r={...e};if(e.colorNotation!==a){const e=colorData_to_XYZ_D50(r);switch(a){case _.HEX:case _.RGB:r.colorNotation=_.RGB,r.channels=n.XYZ_D50_to_sRGB(e.channels);break;case _.sRGB:r.colorNotation=_.sRGB,r.channels=n.XYZ_D50_to_sRGB(e.channels);break;case _.Linear_sRGB:r.colorNotation=_.Linear_sRGB,r.channels=n.XYZ_D50_to_lin_sRGB(e.channels);break;case _.Display_P3:r.colorNotation=_.Display_P3,r.channels=n.XYZ_D50_to_P3(e.channels);break;case _.Rec2020:r.colorNotation=_.Rec2020,r.channels=n.XYZ_D50_to_rec_2020(e.channels);break;case _.ProPhoto_RGB:r.colorNotation=_.ProPhoto_RGB,r.channels=n.XYZ_D50_to_ProPhoto(e.channels);break;case _.A98_RGB:r.colorNotation=_.A98_RGB,r.channels=n.XYZ_D50_to_a98_RGB(e.channels);break;case _.HSL:r.colorNotation=_.HSL,r.channels=n.XYZ_D50_to_HSL(e.channels);break;case _.HWB:r.colorNotation=_.HWB,r.channels=n.XYZ_D50_to_HWB(e.channels);break;case _.Lab:r.colorNotation=_.Lab,r.channels=n.XYZ_D50_to_Lab(e.channels);break;case _.LCH:r.colorNotation=_.LCH,r.channels=n.XYZ_D50_to_LCH(e.channels);break;case _.OKLCH:r.colorNotation=_.OKLCH,r.channels=n.XYZ_D50_to_OKLCH(e.channels);break;case _.OKLab:r.colorNotation=_.OKLab,r.channels=n.XYZ_D50_to_OKLab(e.channels);break;case _.XYZ_D50:r.colorNotation=_.XYZ_D50,r.channels=n.XYZ_D50_to_XYZ_D50(e.channels);break;case _.XYZ_D65:r.colorNotation=_.XYZ_D65,r.channels=n.XYZ_D50_to_XYZ_D65(e.channels);break;default:throw new Error("Unsupported color notation")}}else r.channels=e.channels.map((e=>Number.isNaN(e)?0:e));if(a===e.colorNotation)r.channels=carryForwardMissingComponents(e.channels,[0,1,2],r.channels,[0,1,2]);else if(v.has(a)&&v.has(e.colorNotation))r.channels=carryForwardMissingComponents(e.channels,[0,1,2],r.channels,[0,1,2]);else switch(a){case _.HSL:switch(e.colorNotation){case _.HWB:r.channels=carryForwardMissingComponents(e.channels,[0],r.channels,[0]);break;case _.Lab:case _.OKLab:r.channels=carryForwardMissingComponents(e.channels,[2],r.channels,[0]);break;case _.LCH:case _.OKLCH:r.channels=carryForwardMissingComponents(e.channels,[0,1,2],r.channels,[2,1,0])}break;case _.HWB:switch(e.colorNotation){case _.HSL:r.channels=carryForwardMissingComponents(e.channels,[0],r.channels,[0]);break;case _.LCH:case _.OKLCH:r.channels=carryForwardMissingComponents(e.channels,[0],r.channels,[2])}break;case _.Lab:case _.OKLab:switch(e.colorNotation){case _.HSL:r.channels=carryForwardMissingComponents(e.channels,[0],r.channels,[2]);break;case _.Lab:case _.OKLab:r.channels=carryForwardMissingComponents(e.channels,[0,1,2],r.channels,[0,1,2]);break;case _.LCH:case _.OKLCH:r.channels=carryForwardMissingComponents(e.channels,[0],r.channels,[0])}break;case _.LCH:case _.OKLCH:switch(e.colorNotation){case _.HSL:r.channels=carryForwardMissingComponents(e.channels,[0,1,2],r.channels,[2,1,0]);break;case _.HWB:r.channels=carryForwardMissingComponents(e.channels,[0],r.channels,[2]);break;case _.Lab:case _.OKLab:r.channels=carryForwardMissingComponents(e.channels,[0],r.channels,[0]);break;case _.LCH:case _.OKLCH:r.channels=carryForwardMissingComponents(e.channels,[0,1,2],r.channels,[0,1,2])}}return r.channels=convertPowerlessComponentsToMissingComponents(r.channels,a),r}function convertPowerlessComponentsToMissingComponents(e,a){const n=[...e];switch(a){case _.HSL:reducePrecision(n[1],4)<=0&&(n[0]=NaN);break;case _.HWB:Math.max(0,reducePrecision(n[1],4))+Math.max(0,reducePrecision(n[2],4))>=100&&(n[0]=NaN);break;case _.LCH:reducePrecision(n[1],4)<=0&&(n[2]=NaN);break;case _.OKLCH:reducePrecision(n[1],6)<=0&&(n[2]=NaN)}return n}function convertPowerlessComponentsToZeroValuesForDisplay(e,a){const n=[...e];switch(a){case _.HSL:(reducePrecision(n[2])<=0||reducePrecision(n[2])>=100)&&(n[0]=NaN,n[1]=NaN),reducePrecision(n[1])<=0&&(n[0]=NaN);break;case _.HWB:Math.max(0,reducePrecision(n[1]))+Math.max(0,reducePrecision(n[2]))>=100&&(n[0]=NaN);break;case _.Lab:(reducePrecision(n[0])<=0||reducePrecision(n[0])>=100)&&(n[1]=NaN,n[2]=NaN);break;case _.LCH:reducePrecision(n[1])<=0&&(n[2]=NaN),(reducePrecision(n[0])<=0||reducePrecision(n[0])>=100)&&(n[1]=NaN,n[2]=NaN);break;case _.OKLab:(reducePrecision(n[0])<=0||reducePrecision(n[0])>=1)&&(n[1]=NaN,n[2]=NaN);break;case _.OKLCH:reducePrecision(n[1])<=0&&(n[2]=NaN),(reducePrecision(n[0])<=0||reducePrecision(n[0])>=1)&&(n[1]=NaN,n[2]=NaN)}return n}function carryForwardMissingComponents(e,a,n,r){const o=[...n];for(const n of a)Number.isNaN(e[a[n]])&&(o[r[n]]=NaN);return o}function normalizeRelativeColorDataChannels(e){const a=new Map;switch(e.colorNotation){case _.RGB:case _.HEX:a.set("r",dummyNumberToken(255*e.channels[0])),a.set("g",dummyNumberToken(255*e.channels[1])),a.set("b",dummyNumberToken(255*e.channels[2])),"number"==typeof e.alpha&&a.set("alpha",dummyNumberToken(e.alpha));break;case _.HSL:a.set("h",dummyNumberToken(e.channels[0])),a.set("s",dummyNumberToken(e.channels[1])),a.set("l",dummyNumberToken(e.channels[2])),"number"==typeof e.alpha&&a.set("alpha",dummyNumberToken(e.alpha));break;case _.HWB:a.set("h",dummyNumberToken(e.channels[0])),a.set("w",dummyNumberToken(e.channels[1])),a.set("b",dummyNumberToken(e.channels[2])),"number"==typeof e.alpha&&a.set("alpha",dummyNumberToken(e.alpha));break;case _.Lab:case _.OKLab:a.set("l",dummyNumberToken(e.channels[0])),a.set("a",dummyNumberToken(e.channels[1])),a.set("b",dummyNumberToken(e.channels[2])),"number"==typeof e.alpha&&a.set("alpha",dummyNumberToken(e.alpha));break;case _.LCH:case _.OKLCH:a.set("l",dummyNumberToken(e.channels[0])),a.set("c",dummyNumberToken(e.channels[1])),a.set("h",dummyNumberToken(e.channels[2])),"number"==typeof e.alpha&&a.set("alpha",dummyNumberToken(e.alpha));break;case _.sRGB:case _.A98_RGB:case _.Display_P3:case _.Rec2020:case _.Linear_sRGB:case _.ProPhoto_RGB:a.set("r",dummyNumberToken(e.channels[0])),a.set("g",dummyNumberToken(e.channels[1])),a.set("b",dummyNumberToken(e.channels[2])),"number"==typeof e.alpha&&a.set("alpha",dummyNumberToken(e.alpha));break;case _.XYZ_D50:case _.XYZ_D65:a.set("x",dummyNumberToken(e.channels[0])),a.set("y",dummyNumberToken(e.channels[1])),a.set("z",dummyNumberToken(e.channels[2])),"number"==typeof e.alpha&&a.set("alpha",dummyNumberToken(e.alpha))}return a}function noneToZeroInRelativeColorDataChannels(e){const a=new Map(e);for(const[n,r]of e)Number.isNaN(r[4].value)&&a.set(n,dummyNumberToken(0));return a}function dummyNumberToken(n){return[e.Number,n.toString(),-1,-1,{value:n,type:a.Number}]}function reducePrecision(e,a=7){if(Number.isNaN(e))return 0;const n=Math.pow(10,a);return Math.round(e*n)/n}function colorDataFitsRGB_Gamut(e){const a={...e,channels:[...e.channels]};a.channels=convertPowerlessComponentsToZeroValuesForDisplay(a.channels,a.colorNotation);return!colorDataTo(a,_.RGB).channels.find((e=>e<-1e-5||e>1.00001))}function colorDataFitsDisplayP3_Gamut(e){const a={...e,channels:[...e.channels]};a.channels=convertPowerlessComponentsToZeroValuesForDisplay(a.channels,a.colorNotation);return!colorDataTo(a,_.Display_P3).channels.find((e=>e<-1e-5||e>1.00001))}function normalize(e,a,n,r){return Math.min(Math.max(e/a,n),r)}const d=/[A-Z]/g;function toLowerCaseAZ(e){return e.replace(d,(e=>String.fromCharCode(e.charCodeAt(0)+32)))}function normalize_Color_ChannelValues(n,r,o){if(n[0]===e.Ident&&"none"===toLowerCaseAZ(n[4].value))return o.syntaxFlags.add(g.HasNoneKeywords),[e.Number,"none",n[2],n[3],{value:NaN,type:a.Number}];if(n[0]===e.Percentage){3!==r&&o.syntaxFlags.add(g.HasPercentageValues);let t=normalize(n[4].value,100,-1/0,1/0);return 3===r&&(t=normalize(n[4].value,100,0,1)),[e.Number,t.toString(),n[2],n[3],{value:t,type:a.Number}]}if(n[0]===e.Number){3!==r&&o.syntaxFlags.add(g.HasNumberValues);let t=normalize(n[4].value,1,-1/0,1/0);return 3===r&&(t=normalize(n[4].value,1,0,1)),[e.Number,t.toString(),n[2],n[3],{value:t,type:a.Number}]}return!1}const f=new Set(["srgb","srgb-linear","display-p3","a98-rgb","prophoto-rgb","rec2020","xyz","xyz-d50","xyz-d65"]);function color$1(a,n){const r=[],o=[],t=[],l=[];let h,N,v=!1,d=!1;const y={colorNotation:_.sRGB,channels:[0,0,0],alpha:1,syntaxFlags:new Set([])};let C=r;for(let _=0;_=0){l=m.value[4].value;continue}}return!1}if(!t)return!1;r.push({color:t,percentage:l}),t=!1,l=!1}}if(t&&r.push({color:t,percentage:l}),2!==r.length)return!1;let m=r[0].percentage,h=r[1].percentage;return(!1===m||!(m<0||m>100))&&((!1===h||!(h<0||h>100))&&(!1===m&&!1===h?(m=50,h=50):!1!==m&&!1===h?h=100-m:!1===m&&!1!==h&&(m=100-h),(0!==m||0!==h)&&(!1!==m&&!1!==h&&(m+h>100&&(m=m/(m+h)*100,h=h/(m+h)*100),m+h<100&&(o=(m+h)/100,m=m/(m+h)*100,h=h/(m+h)*100),{a:{color:r[0].color,percentage:m},b:{color:r[1].color,percentage:h},alphaMultiplier:o}))))}function colorMixRectangular(e,a){if(!a)return!1;const n=a.a.color,r=a.b.color,o=a.a.percentage/100;let t=n.channels,l=r.channels,s=_.RGB,u=n.alpha;if("number"!=typeof u)return!1;let i=r.alpha;if("number"!=typeof i)return!1;switch(u=Number.isNaN(u)?i:u,i=Number.isNaN(i)?u:i,e){case"srgb":s=_.RGB;break;case"srgb-linear":s=_.Linear_sRGB;break;case"lab":s=_.Lab;break;case"oklab":s=_.OKLab;break;case"xyz-d50":s=_.XYZ_D50;break;case"xyz":case"xyz-d65":s=_.XYZ_D65}t=colorDataTo(n,s).channels,l=colorDataTo(r,s).channels,t[0]=fillInMissingComponent(t[0],l[0]),l[0]=fillInMissingComponent(l[0],t[0]),t[1]=fillInMissingComponent(t[1],l[1]),l[1]=fillInMissingComponent(l[1],t[1]),t[2]=fillInMissingComponent(t[2],l[2]),l[2]=fillInMissingComponent(l[2],t[2]),t[0]=premultiply(t[0],u),t[1]=premultiply(t[1],u),t[2]=premultiply(t[2],u),l[0]=premultiply(l[0],i),l[1]=premultiply(l[1],i),l[2]=premultiply(l[2],i);const c=interpolate(u,i,o),m={colorNotation:s,channels:[un_premultiply(interpolate(t[0],l[0],o),c),un_premultiply(interpolate(t[1],l[1],o),c),un_premultiply(interpolate(t[2],l[2],o),c)],alpha:c*a.alphaMultiplier,syntaxFlags:new Set([g.ColorMix])};return(a.a.color.syntaxFlags.has(g.Experimental)||a.b.color.syntaxFlags.has(g.Experimental))&&m.syntaxFlags.add(g.Experimental),m}function colorMixPolar(e,a,n){if(!n)return!1;const r=n.a.color,o=n.b.color,t=n.a.percentage/100;let l=r.channels,s=o.channels,u=0,i=0,c=0,m=0,h=0,N=0,p=_.RGB,b=r.alpha;if("number"!=typeof b)return!1;let v=o.alpha;if("number"!=typeof v)return!1;switch(b=Number.isNaN(b)?v:b,v=Number.isNaN(v)?b:v,e){case"hsl":p=_.HSL;break;case"hwb":p=_.HWB;break;case"lch":p=_.LCH;break;case"oklch":p=_.OKLCH}switch(l=colorDataTo(r,p).channels,s=colorDataTo(o,p).channels,e){case"hsl":case"hwb":u=l[0],i=s[0],c=l[1],m=s[1],h=l[2],N=s[2];break;case"lch":case"oklch":c=l[0],m=s[0],h=l[1],N=s[1],u=l[2],i=s[2]}u=fillInMissingComponent(u,i),Number.isNaN(u)&&(u=0),i=fillInMissingComponent(i,u),Number.isNaN(i)&&(i=0),c=fillInMissingComponent(c,m),m=fillInMissingComponent(m,c),h=fillInMissingComponent(h,N),N=fillInMissingComponent(N,h);const d=i-u;switch(a){case"shorter":d>180?u+=360:d<-180&&(i+=360);break;case"longer":-1800?u+=360:i+=360);break;case"increasing":d<0&&(i+=360);break;case"decreasing":d>0&&(u+=360);break;default:throw new Error("Unknown hue interpolation method")}c=premultiply(c,b),h=premultiply(h,b),m=premultiply(m,v),N=premultiply(N,v);let f=[0,0,0];const y=interpolate(b,v,t);switch(e){case"hsl":case"hwb":f=[interpolate(u,i,t),un_premultiply(interpolate(c,m,t),y),un_premultiply(interpolate(h,N,t),y)];break;case"lch":case"oklch":f=[un_premultiply(interpolate(c,m,t),y),un_premultiply(interpolate(h,N,t),y),interpolate(u,i,t)]}const C={colorNotation:p,channels:f,alpha:y*n.alphaMultiplier,syntaxFlags:new Set([g.ColorMix])};return(n.a.color.syntaxFlags.has(g.Experimental)||n.b.color.syntaxFlags.has(g.Experimental))&&C.syntaxFlags.add(g.Experimental),C}function fillInMissingComponent(e,a){return Number.isNaN(e)?a:e}function interpolate(e,a,n){return e*n+a*(1-n)}function premultiply(e,a){return Number.isNaN(a)?e:Number.isNaN(e)?NaN:e*a}function un_premultiply(e,a){return 0===a||Number.isNaN(a)?e:Number.isNaN(e)?NaN:e/a}function hex(e){const a=toLowerCaseAZ(e[4].value);if(a.match(/[^a-f0-9]/))return!1;const n={colorNotation:_.HEX,channels:[0,0,0],alpha:1,syntaxFlags:new Set([g.Hex])},r=a.length;if(3===r){const e=a[0],r=a[1],o=a[2];return n.channels=[parseInt(e+e,16)/255,parseInt(r+r,16)/255,parseInt(o+o,16)/255],n}if(6===r){const e=a[0]+a[1],r=a[2]+a[3],o=a[4]+a[5];return n.channels=[parseInt(e,16)/255,parseInt(r,16)/255,parseInt(o,16)/255],n}if(4===r){const e=a[0],r=a[1],o=a[2],t=a[3];return n.channels=[parseInt(e+e,16)/255,parseInt(r+r,16)/255,parseInt(o+o,16)/255],n.alpha=parseInt(t+t,16)/255,n.syntaxFlags.add(g.HasAlpha),n}if(8===r){const e=a[0]+a[1],r=a[2]+a[3],o=a[4]+a[5],t=a[6]+a[7];return n.channels=[parseInt(e,16)/255,parseInt(r,16)/255,parseInt(o,16)/255],n.alpha=parseInt(t,16)/255,n.syntaxFlags.add(g.HasAlpha),n}return!1}function normalizeHue(n){if(n[0]===e.Number)return n[4].value=n[4].value%360,n[1]=n[4].value.toString(),n;if(n[0]===e.Dimension){let r=n[4].value;switch(toLowerCaseAZ(n[4].unit)){case"deg":break;case"rad":r=180*n[4].value/Math.PI;break;case"grad":r=.9*n[4].value;break;case"turn":r=360*n[4].value;break;default:return!1}return r%=360,[e.Number,r.toString(),n[2],n[3],{value:r,type:a.Number}]}return!1}function normalize_legacy_HSL_ChannelValues(n,r,o){if(0===r){const a=normalizeHue(n);return!1!==a&&(n[0]===e.Dimension&&o.syntaxFlags.add(g.HasDimensionValues),a)}if(n[0]===e.Percentage){3===r?o.syntaxFlags.add(g.HasPercentageAlpha):o.syntaxFlags.add(g.HasPercentageValues);let t=normalize(n[4].value,1,0,100);return 3===r&&(t=normalize(n[4].value,100,0,1)),[e.Number,t.toString(),n[2],n[3],{value:t,type:a.Number}]}if(n[0]===e.Number){if(3!==r)return!1;let o=normalize(n[4].value,1,0,100);return 3===r&&(o=normalize(n[4].value,1,0,1)),[e.Number,o.toString(),n[2],n[3],{value:o,type:a.Number}]}return!1}function normalize_modern_HSL_ChannelValues(n,r,o){if(n[0]===e.Ident&&"none"===toLowerCaseAZ(n[4].value))return o.syntaxFlags.add(g.HasNoneKeywords),[e.Number,"none",n[2],n[3],{value:NaN,type:a.Number}];if(0===r){const a=normalizeHue(n);return!1!==a&&(n[0]===e.Dimension&&o.syntaxFlags.add(g.HasDimensionValues),a)}if(n[0]===e.Percentage){3===r?o.syntaxFlags.add(g.HasPercentageAlpha):o.syntaxFlags.add(g.HasPercentageValues);let t=n[4].value;return 3===r&&(t=normalize(n[4].value,100,0,1)),[e.Number,t.toString(),n[2],n[3],{value:t,type:a.Number}]}if(n[0]===e.Number){3!==r&&o.syntaxFlags.add(g.HasNumberValues);let t=n[4].value;return 3===r&&(t=normalize(n[4].value,1,0,1)),[e.Number,t.toString(),n[2],n[3],{value:t,type:a.Number}]}return!1}function threeChannelLegacySyntax(a,n,r,o){const t=[],l=[],m=[],h=[],N={colorNotation:r,channels:[0,0,0],alpha:1,syntaxFlags:new Set(o)};let _=t;for(let n=0;ni(a)&&a.value[0]===e.Comma))){const e=hslCommaSeparated(a);if(!1!==e)return e}{const e=hslSpaceSeparated(a,n);if(!1!==e)return e}return!1}function hslCommaSeparated(e){return threeChannelLegacySyntax(e,normalize_legacy_HSL_ChannelValues,_.HSL,[g.LegacyHSL])}function hslSpaceSeparated(e,a){return threeChannelSpaceSeparated(e,normalize_modern_HSL_ChannelValues,_.HSL,[],a)}function normalize_HWB_ChannelValues(n,r,o){if(n[0]===e.Ident&&"none"===toLowerCaseAZ(n[4].value))return o.syntaxFlags.add(g.HasNoneKeywords),[e.Number,"none",n[2],n[3],{value:NaN,type:a.Number}];if(0===r){const a=normalizeHue(n);return!1!==a&&(n[0]===e.Dimension&&o.syntaxFlags.add(g.HasDimensionValues),a)}if(n[0]===e.Percentage){3===r?o.syntaxFlags.add(g.HasPercentageAlpha):o.syntaxFlags.add(g.HasPercentageValues);let t=n[4].value;return 3===r&&(t=normalize(n[4].value,100,0,1)),[e.Number,t.toString(),n[2],n[3],{value:t,type:a.Number}]}if(n[0]===e.Number){3!==r&&o.syntaxFlags.add(g.HasNumberValues);let t=n[4].value;return 3===r&&(t=normalize(n[4].value,1,0,1)),[e.Number,t.toString(),n[2],n[3],{value:t,type:a.Number}]}return!1}function normalize_Lab_ChannelValues(n,r,o){if(n[0]===e.Ident&&"none"===toLowerCaseAZ(n[4].value))return o.syntaxFlags.add(g.HasNoneKeywords),[e.Number,"none",n[2],n[3],{value:NaN,type:a.Number}];if(n[0]===e.Percentage){3!==r&&o.syntaxFlags.add(g.HasPercentageValues);let t=normalize(n[4].value,1,0,100);return 1===r||2===r?t=normalize(n[4].value,.8,-1/0,1/0):3===r&&(t=normalize(n[4].value,100,0,1)),[e.Number,t.toString(),n[2],n[3],{value:t,type:a.Number}]}if(n[0]===e.Number){3!==r&&o.syntaxFlags.add(g.HasNumberValues);let t=normalize(n[4].value,1,0,100);return 1===r||2===r?t=normalize(n[4].value,1,-1/0,1/0):3===r&&(t=normalize(n[4].value,1,0,1)),[e.Number,t.toString(),n[2],n[3],{value:t,type:a.Number}]}return!1}function lab(e,a){return threeChannelSpaceSeparated(e,normalize_Lab_ChannelValues,_.Lab,[],a)}function normalize_LCH_ChannelValues(n,r,o){if(n[0]===e.Ident&&"none"===toLowerCaseAZ(n[4].value))return o.syntaxFlags.add(g.HasNoneKeywords),[e.Number,"none",n[2],n[3],{value:NaN,type:a.Number}];if(2===r){const a=normalizeHue(n);return!1!==a&&(n[0]===e.Dimension&&o.syntaxFlags.add(g.HasDimensionValues),a)}if(n[0]===e.Percentage){3!==r&&o.syntaxFlags.add(g.HasPercentageValues);let t=normalize(n[4].value,1,0,100);return 1===r?t=normalize(n[4].value,100/150,0,1/0):3===r&&(t=normalize(n[4].value,100,0,1)),[e.Number,t.toString(),n[2],n[3],{value:t,type:a.Number}]}if(n[0]===e.Number){3!==r&&o.syntaxFlags.add(g.HasNumberValues);let t=normalize(n[4].value,1,0,100);return 1===r?t=normalize(n[4].value,1,0,1/0):3===r&&(t=normalize(n[4].value,1,0,1)),[e.Number,t.toString(),n[2],n[3],{value:t,type:a.Number}]}return!1}function lch(e,a){return threeChannelSpaceSeparated(e,normalize_LCH_ChannelValues,_.LCH,[],a)}const L=new Map;for(const[e,a]of Object.entries(r))L.set(e,a);function namedColor(e){const a=L.get(toLowerCaseAZ(e));return!!a&&{colorNotation:_.RGB,channels:[a[0]/255,a[1]/255,a[2]/255],alpha:1,syntaxFlags:new Set([g.ColorKeyword,g.NamedColor])}}function normalize_OKLab_ChannelValues(n,r,o){if(n[0]===e.Ident&&"none"===toLowerCaseAZ(n[4].value))return o.syntaxFlags.add(g.HasNoneKeywords),[e.Number,"none",n[2],n[3],{value:NaN,type:a.Number}];if(n[0]===e.Percentage){3!==r&&o.syntaxFlags.add(g.HasPercentageValues);let t=normalize(n[4].value,100,0,1);return 1===r||2===r?t=normalize(n[4].value,250,-1/0,1/0):3===r&&(t=normalize(n[4].value,100,0,1)),[e.Number,t.toString(),n[2],n[3],{value:t,type:a.Number}]}if(n[0]===e.Number){3!==r&&o.syntaxFlags.add(g.HasNumberValues);let t=normalize(n[4].value,1,0,1);return 1===r||2===r?t=normalize(n[4].value,1,-1/0,1/0):3===r&&(t=normalize(n[4].value,1,0,1)),[e.Number,t.toString(),n[2],n[3],{value:t,type:a.Number}]}return!1}function oklab(e,a){return threeChannelSpaceSeparated(e,normalize_OKLab_ChannelValues,_.OKLab,[],a)}function normalize_OKLCH_ChannelValues(n,r,o){if(n[0]===e.Ident&&"none"===toLowerCaseAZ(n[4].value))return o.syntaxFlags.add(g.HasNoneKeywords),[e.Number,"none",n[2],n[3],{value:NaN,type:a.Number}];if(2===r){const a=normalizeHue(n);return!1!==a&&(n[0]===e.Dimension&&o.syntaxFlags.add(g.HasDimensionValues),a)}if(n[0]===e.Percentage){3!==r&&o.syntaxFlags.add(g.HasPercentageValues);let t=normalize(n[4].value,100,0,1);return 1===r?t=normalize(n[4].value,250,0,1/0):3===r&&(t=normalize(n[4].value,100,0,1)),[e.Number,t.toString(),n[2],n[3],{value:t,type:a.Number}]}if(n[0]===e.Number){3!==r&&o.syntaxFlags.add(g.HasNumberValues);let t=normalize(n[4].value,1,0,1);return 1===r?t=normalize(n[4].value,1,0,1/0):3===r&&(t=normalize(n[4].value,1,0,1)),[e.Number,t.toString(),n[2],n[3],{value:t,type:a.Number}]}return!1}function oklch(e,a){return threeChannelSpaceSeparated(e,normalize_OKLCH_ChannelValues,_.OKLCH,[],a)}function normalize_legacy_sRGB_ChannelValues(n,r,o){if(n[0]===e.Percentage){3===r?o.syntaxFlags.add(g.HasPercentageAlpha):o.syntaxFlags.add(g.HasPercentageValues);const t=normalize(n[4].value,100,0,1);return[e.Number,t.toString(),n[2],n[3],{value:t,type:a.Number}]}if(n[0]===e.Number){3!==r&&o.syntaxFlags.add(g.HasNumberValues);let t=normalize(n[4].value,255,0,1);return 3===r&&(t=normalize(n[4].value,1,0,1)),[e.Number,t.toString(),n[2],n[3],{value:t,type:a.Number}]}return!1}function normalize_modern_sRGB_ChannelValues(n,r,o){if(n[0]===e.Ident&&"none"===toLowerCaseAZ(n[4].value))return o.syntaxFlags.add(g.HasNoneKeywords),[e.Number,"none",n[2],n[3],{value:NaN,type:a.Number}];if(n[0]===e.Percentage){3!==r&&o.syntaxFlags.add(g.HasPercentageValues);let t=normalize(n[4].value,100,-1/0,1/0);return 3===r&&(t=normalize(n[4].value,100,0,1)),[e.Number,t.toString(),n[2],n[3],{value:t,type:a.Number}]}if(n[0]===e.Number){3!==r&&o.syntaxFlags.add(g.HasNumberValues);let t=normalize(n[4].value,255,-1/0,1/0);return 3===r&&(t=normalize(n[4].value,1,0,1)),[e.Number,t.toString(),n[2],n[3],{value:t,type:a.Number}]}return!1}function rgb(a,n){if(a.value.some((a=>i(a)&&a.value[0]===e.Comma))){const e=rgbCommaSeparated(a);if(!1!==e)return(!e.syntaxFlags.has(g.HasNumberValues)||!e.syntaxFlags.has(g.HasPercentageValues))&&e}else{const e=rgbSpaceSeparated(a,n);if(!1!==e)return e}return!1}function rgbCommaSeparated(e){return threeChannelLegacySyntax(e,normalize_legacy_sRGB_ChannelValues,_.RGB,[g.LegacyRGB])}function rgbSpaceSeparated(e,a){return threeChannelSpaceSeparated(e,normalize_modern_sRGB_ChannelValues,_.RGB,[],a)}function toPrecision(e,a=7){e=+e,a=+a;const n=(Math.floor(e)+"").length;if(a>n)return+e.toFixed(a-n);{const r=10**(n-a);return Math.round(e/r)*r}}function XYZ_D50_to_P3_Gamut(e){const a=n.XYZ_D50_to_P3(e);if(o.inGamut(a))return o.clip(a);let r=e.slice();return r=t.D50_to_D65(r),r=t.XYZ_to_OKLab(r),r=t.OKLab_to_OKLCH(r),r[0]<1e-6&&(r=[0,0,0]),r[0]>.999999&&(r=[1,0,0]),l.mapGamut(r,(e=>(e=t.OKLCH_to_OKLab(e),e=t.OKLab_to_XYZ(e),e=t.XYZ_to_lin_P3(e),t.gam_P3(e))),(e=>(e=t.lin_P3(e),e=t.lin_P3_to_XYZ(e),e=t.XYZ_to_OKLab(e),t.OKLab_to_OKLCH(e))))}function serializeWithAlpha(n,r,o,t){const l=[e.CloseParen,")",-1,-1,void 0];if("number"==typeof n.alpha){const s=Math.min(1,Math.max(0,toPrecision(Number.isNaN(n.alpha)?0:n.alpha)));return 1===toPrecision(s,4)?new h(r,l,t):new h(r,l,[...t,new N([o]),new m([e.Delim,"/",-1,-1,{value:"/"}]),new N([o]),new m([e.Number,toPrecision(s,4).toString(),-1,-1,{value:n.alpha,type:a.Integer}])])}return new h(r,l,[...t,new N([o]),new m([e.Delim,"/",-1,-1,{value:"/"}]),new N([o]),n.alpha])}function serializeP3(r,o=!0){r.channels=convertPowerlessComponentsToZeroValuesForDisplay(r.channels,r.colorNotation);let t=r.channels.map((e=>Number.isNaN(e)?0:e));r.colorNotation!==_.Display_P3&&(t=o?XYZ_D50_to_P3_Gamut(colorData_to_XYZ_D50(r).channels):n.XYZ_D50_to_P3(colorData_to_XYZ_D50(r).channels));const l=toPrecision(t[0],6),s=toPrecision(t[1],6),u=toPrecision(t[2],6),i=[e.Function,"color(",-1,-1,{value:"color"}],c=[e.Whitespace," ",-1,-1,void 0];return serializeWithAlpha(r,i,c,[new m([e.Ident,"display-p3",-1,-1,{value:"display-p3"}]),new N([c]),new m([e.Number,l.toString(),-1,-1,{value:t[0],type:a.Number}]),new N([c]),new m([e.Number,s.toString(),-1,-1,{value:t[1],type:a.Number}]),new N([c]),new m([e.Number,u.toString(),-1,-1,{value:t[2],type:a.Number}])])}function XYZ_D50_to_sRGB_Gamut(e){const a=n.XYZ_D50_to_sRGB(e);if(o.inGamut(a))return o.clip(a);let r=e.slice();return r=t.D50_to_D65(r),r=t.XYZ_to_OKLab(r),r=t.OKLab_to_OKLCH(r),r[0]<1e-6&&(r=[0,0,0]),r[0]>.999999&&(r=[1,0,0]),l.mapGamut(r,(e=>(e=t.OKLCH_to_OKLab(e),e=t.OKLab_to_XYZ(e),e=t.XYZ_to_lin_sRGB(e),t.gam_sRGB(e))),(e=>(e=t.lin_sRGB(e),e=t.lin_sRGB_to_XYZ(e),e=t.XYZ_to_OKLab(e),t.OKLab_to_OKLCH(e))))}function serializeRGB(r,o=!0){r.channels=convertPowerlessComponentsToZeroValuesForDisplay(r.channels,r.colorNotation);let t=r.channels.map((e=>Number.isNaN(e)?0:e));t=o?XYZ_D50_to_sRGB_Gamut(colorData_to_XYZ_D50(r).channels):n.XYZ_D50_to_sRGB(colorData_to_XYZ_D50(r).channels);const l=Math.min(255,Math.max(0,Math.round(255*toPrecision(t[0])))),s=Math.min(255,Math.max(0,Math.round(255*toPrecision(t[1])))),u=Math.min(255,Math.max(0,Math.round(255*toPrecision(t[2])))),i=[e.CloseParen,")",-1,-1,void 0],c=[e.Whitespace," ",-1,-1,void 0],p=[e.Comma,",",-1,-1,void 0],b=[new m([e.Number,l.toString(),-1,-1,{value:t[0],type:a.Integer}]),new m(p),new N([c]),new m([e.Number,s.toString(),-1,-1,{value:t[1],type:a.Integer}]),new m(p),new N([c]),new m([e.Number,u.toString(),-1,-1,{value:t[2],type:a.Integer}])];if("number"==typeof r.alpha){const n=Math.min(1,Math.max(0,toPrecision(Number.isNaN(r.alpha)?0:r.alpha)));return 1===toPrecision(n,4)?new h([e.Function,"rgb(",-1,-1,{value:"rgb"}],i,b):new h([e.Function,"rgba(",-1,-1,{value:"rgba"}],i,[...b,new m(p),new N([c]),new m([e.Number,toPrecision(n,4).toString(),-1,-1,{value:r.alpha,type:a.Number}])])}return new h([e.Function,"rgba(",-1,-1,{value:"rgba"}],i,[...b,new m(p),new N([c]),r.alpha])}function serializeHSL(r,o=!0){r.channels=convertPowerlessComponentsToZeroValuesForDisplay(r.channels,r.colorNotation);let t=r.channels.map((e=>Number.isNaN(e)?0:e));t=o?n.XYZ_D50_to_HSL(n.sRGB_to_XYZ_D50(XYZ_D50_to_sRGB_Gamut(colorData_to_XYZ_D50(r).channels))):n.XYZ_D50_to_HSL(colorData_to_XYZ_D50(r).channels),t=t.map((e=>Number.isNaN(e)?0:e));const l=Math.min(360,Math.max(0,Math.round(toPrecision(t[0])))),s=Math.min(100,Math.max(0,Math.round(toPrecision(t[1])))),u=Math.min(100,Math.max(0,Math.round(toPrecision(t[2])))),i=[e.CloseParen,")",-1,-1,void 0],c=[e.Whitespace," ",-1,-1,void 0],p=[e.Comma,",",-1,-1,void 0],b=[new m([e.Number,l.toString(),-1,-1,{value:t[0],type:a.Integer}]),new m(p),new N([c]),new m([e.Percentage,s.toString()+"%",-1,-1,{value:t[1]}]),new m(p),new N([c]),new m([e.Percentage,u.toString()+"%",-1,-1,{value:t[2]}])];if("number"==typeof r.alpha){const n=Math.min(1,Math.max(0,toPrecision(Number.isNaN(r.alpha)?0:r.alpha)));return 1===toPrecision(n,4)?new h([e.Function,"hsl(",-1,-1,{value:"hsl"}],i,b):new h([e.Function,"hsla(",-1,-1,{value:"hsla"}],i,[...b,new m(p),new N([c]),new m([e.Number,toPrecision(n,4).toString(),-1,-1,{value:r.alpha,type:a.Number}])])}return new h([e.Function,"hsla(",-1,-1,{value:"hsla"}],i,[...b,new m(p),new N([c]),r.alpha])}function serializeOKLCH(r){r.channels=convertPowerlessComponentsToZeroValuesForDisplay(r.channels,r.colorNotation);let o=r.channels.map((e=>Number.isNaN(e)?0:e));r.colorNotation!==_.OKLCH&&(o=n.XYZ_D50_to_OKLCH(colorData_to_XYZ_D50(r).channels));const t=toPrecision(o[0],6),l=toPrecision(o[1],6),s=toPrecision(o[2],6),u=[e.Function,"oklch(",-1,-1,{value:"oklch"}],i=[e.Whitespace," ",-1,-1,void 0];return serializeWithAlpha(r,u,i,[new m([e.Number,t.toString(),-1,-1,{value:o[0],type:a.Number}]),new N([i]),new m([e.Number,l.toString(),-1,-1,{value:o[1],type:a.Number}]),new N([i]),new m([e.Number,s.toString(),-1,-1,{value:o[2],type:a.Number}])])}function color(a){if(c(a)){switch(toLowerCaseAZ(a.getName())){case"rgb":case"rgba":return rgb(a,color);case"hsl":case"hsla":return hsl(a,color);case"hwb":return n=color,threeChannelSpaceSeparated(a,normalize_HWB_ChannelValues,_.HWB,[],n);case"lab":return lab(a,color);case"lch":return lch(a,color);case"oklab":return oklab(a,color);case"oklch":return oklch(a,color);case"color":return color$1(a,color);case"color-mix":return colorMix(a,color)}}var n;if(i(a)){if(a.value[0]===e.Hash)return hex(a.value);if(a.value[0]===e.Ident){const e=namedColor(a.value[4].value);return!1!==e?e:"transparent"===toLowerCaseAZ(a.value[4].value)&&{colorNotation:_.RGB,channels:[0,0,0],alpha:0,syntaxFlags:new Set([g.ColorKeyword])}}}return!1}export{_ as ColorNotation,g as SyntaxFlag,color,colorDataFitsDisplayP3_Gamut,colorDataFitsRGB_Gamut,colorDataTo,serializeHSL,serializeOKLCH,serializeP3,serializeRGB}; +import{TokenType as e,NumberType as a}from"@csstools/css-tokenizer";import{XYZ_D50_to_XYZ_D65 as n,XYZ_D50_to_XYZ_D50 as r,XYZ_D50_to_OKLab as o,XYZ_D50_to_OKLCH as t,XYZ_D50_to_LCH as l,XYZ_D50_to_Lab as s,XYZ_D50_to_HWB as u,XYZ_D50_to_HSL as i,XYZ_D50_to_a98_RGB as c,XYZ_D50_to_ProPhoto as m,XYZ_D50_to_rec_2020 as h,XYZ_D50_to_P3 as N,XYZ_D50_to_lin_sRGB as p,XYZ_D50_to_sRGB as b,XYZ_D65_to_XYZ_D50 as g,OKLCH_to_XYZ_D50 as v,LCH_to_XYZ_D50 as d,OKLab_to_XYZ_D50 as f,Lab_to_XYZ_D50 as y,HWB_to_XYZ_D50 as C,HSL_to_XYZ_D50 as w,ProPhoto_RGB_to_XYZ_D50 as _,a98_RGB_to_XYZ_D50 as H,rec_2020_to_XYZ_D50 as x,P3_to_XYZ_D50 as L,lin_sRGB_to_XYZ_D50 as P,sRGB_to_XYZ_D50 as D,namedColors as S,inGamut as k,clip as z,mapGamut as F,OKLCH_to_OKLab as Z,OKLab_to_XYZ as M,XYZ_to_lin_P3 as R,gam_P3 as B,lin_P3 as G,lin_P3_to_XYZ as V,XYZ_to_OKLab as A,OKLab_to_OKLCH as T,XYZ_to_lin_sRGB as I,gam_sRGB as X,lin_sRGB as K,lin_sRGB_to_XYZ as Y}from"@csstools/color-helpers";import{isWhitespaceNode as O,isCommentNode as E,isTokenNode as W,isFunctionNode as U,TokenNode as $,FunctionNode as j,WhitespaceNode as q}from"@csstools/css-parser-algorithms";import{mathFunctionNames as J,calcFromComponentValues as Q}from"@csstools/css-calc";var ee,ae;function colorData_to_XYZ_D50(e){switch(e.colorNotation){case ee.HEX:case ee.RGB:case ee.sRGB:return{...e,colorNotation:ee.XYZ_D50,channels:D(e.channels.map((e=>Number.isNaN(e)?0:e)))};case ee.Linear_sRGB:return{...e,colorNotation:ee.XYZ_D50,channels:P(e.channels.map((e=>Number.isNaN(e)?0:e)))};case ee.Display_P3:return{...e,colorNotation:ee.XYZ_D50,channels:L(e.channels.map((e=>Number.isNaN(e)?0:e)))};case ee.Rec2020:return{...e,colorNotation:ee.XYZ_D50,channels:x(e.channels.map((e=>Number.isNaN(e)?0:e)))};case ee.A98_RGB:return{...e,colorNotation:ee.XYZ_D50,channels:H(e.channels.map((e=>Number.isNaN(e)?0:e)))};case ee.ProPhoto_RGB:return{...e,colorNotation:ee.XYZ_D50,channels:_(e.channels.map((e=>Number.isNaN(e)?0:e)))};case ee.HSL:return{...e,colorNotation:ee.XYZ_D50,channels:w(e.channels.map((e=>Number.isNaN(e)?0:e)))};case ee.HWB:return{...e,colorNotation:ee.XYZ_D50,channels:C(e.channels.map((e=>Number.isNaN(e)?0:e)))};case ee.Lab:return{...e,colorNotation:ee.XYZ_D50,channels:y(e.channels.map((e=>Number.isNaN(e)?0:e)))};case ee.OKLab:return{...e,colorNotation:ee.XYZ_D50,channels:f(e.channels.map((e=>Number.isNaN(e)?0:e)))};case ee.LCH:return{...e,colorNotation:ee.XYZ_D50,channels:d(e.channels.map((e=>Number.isNaN(e)?0:e)))};case ee.OKLCH:return{...e,colorNotation:ee.XYZ_D50,channels:v(e.channels.map((e=>Number.isNaN(e)?0:e)))};case ee.XYZ_D50:return{...e,colorNotation:ee.XYZ_D50,channels:r(e.channels.map((e=>Number.isNaN(e)?0:e)))};case ee.XYZ_D65:return{...e,colorNotation:ee.XYZ_D50,channels:g(e.channels.map((e=>Number.isNaN(e)?0:e)))};default:throw new Error("Unsupported color notation")}}!function(e){e.A98_RGB="a98-rgb",e.Display_P3="display-p3",e.HEX="hex",e.HSL="hsl",e.HWB="hwb",e.LCH="lch",e.Lab="lab",e.Linear_sRGB="srgb-linear",e.OKLCH="oklch",e.OKLab="oklab",e.ProPhoto_RGB="prophoto-rgb",e.RGB="rgb",e.sRGB="srgb",e.Rec2020="rec2020",e.XYZ_D50="xyz-d50",e.XYZ_D65="xyz-d65"}(ee||(ee={})),function(e){e.ColorKeyword="color-keyword",e.HasAlpha="has-alpha",e.HasDimensionValues="has-dimension-values",e.HasNoneKeywords="has-none-keywords",e.HasNumberValues="has-number-values",e.HasPercentageAlpha="has-percentage-alpha",e.HasPercentageValues="has-percentage-values",e.HasVariableAlpha="has-variable-alpha",e.Hex="hex",e.LegacyHSL="legacy-hsl",e.LegacyRGB="legacy-rgb",e.NamedColor="named-color",e.RelativeColorSyntax="relative-color-syntax",e.ColorMix="color-mix",e.Experimental="experimental"}(ae||(ae={}));const ne=new Set([ee.A98_RGB,ee.Display_P3,ee.HEX,ee.Linear_sRGB,ee.ProPhoto_RGB,ee.RGB,ee.sRGB,ee.Rec2020,ee.XYZ_D50,ee.XYZ_D65]);function colorDataTo(e,a){const g={...e};if(e.colorNotation!==a){const e=colorData_to_XYZ_D50(g);switch(a){case ee.HEX:case ee.RGB:g.colorNotation=ee.RGB,g.channels=b(e.channels);break;case ee.sRGB:g.colorNotation=ee.sRGB,g.channels=b(e.channels);break;case ee.Linear_sRGB:g.colorNotation=ee.Linear_sRGB,g.channels=p(e.channels);break;case ee.Display_P3:g.colorNotation=ee.Display_P3,g.channels=N(e.channels);break;case ee.Rec2020:g.colorNotation=ee.Rec2020,g.channels=h(e.channels);break;case ee.ProPhoto_RGB:g.colorNotation=ee.ProPhoto_RGB,g.channels=m(e.channels);break;case ee.A98_RGB:g.colorNotation=ee.A98_RGB,g.channels=c(e.channels);break;case ee.HSL:g.colorNotation=ee.HSL,g.channels=i(e.channels);break;case ee.HWB:g.colorNotation=ee.HWB,g.channels=u(e.channels);break;case ee.Lab:g.colorNotation=ee.Lab,g.channels=s(e.channels);break;case ee.LCH:g.colorNotation=ee.LCH,g.channels=l(e.channels);break;case ee.OKLCH:g.colorNotation=ee.OKLCH,g.channels=t(e.channels);break;case ee.OKLab:g.colorNotation=ee.OKLab,g.channels=o(e.channels);break;case ee.XYZ_D50:g.colorNotation=ee.XYZ_D50,g.channels=r(e.channels);break;case ee.XYZ_D65:g.colorNotation=ee.XYZ_D65,g.channels=n(e.channels);break;default:throw new Error("Unsupported color notation")}}else g.channels=e.channels.map((e=>Number.isNaN(e)?0:e));if(a===e.colorNotation)g.channels=carryForwardMissingComponents(e.channels,[0,1,2],g.channels,[0,1,2]);else if(ne.has(a)&&ne.has(e.colorNotation))g.channels=carryForwardMissingComponents(e.channels,[0,1,2],g.channels,[0,1,2]);else switch(a){case ee.HSL:switch(e.colorNotation){case ee.HWB:g.channels=carryForwardMissingComponents(e.channels,[0],g.channels,[0]);break;case ee.Lab:case ee.OKLab:g.channels=carryForwardMissingComponents(e.channels,[2],g.channels,[0]);break;case ee.LCH:case ee.OKLCH:g.channels=carryForwardMissingComponents(e.channels,[0,1,2],g.channels,[2,1,0])}break;case ee.HWB:switch(e.colorNotation){case ee.HSL:g.channels=carryForwardMissingComponents(e.channels,[0],g.channels,[0]);break;case ee.LCH:case ee.OKLCH:g.channels=carryForwardMissingComponents(e.channels,[0],g.channels,[2])}break;case ee.Lab:case ee.OKLab:switch(e.colorNotation){case ee.HSL:g.channels=carryForwardMissingComponents(e.channels,[0],g.channels,[2]);break;case ee.Lab:case ee.OKLab:g.channels=carryForwardMissingComponents(e.channels,[0,1,2],g.channels,[0,1,2]);break;case ee.LCH:case ee.OKLCH:g.channels=carryForwardMissingComponents(e.channels,[0],g.channels,[0])}break;case ee.LCH:case ee.OKLCH:switch(e.colorNotation){case ee.HSL:g.channels=carryForwardMissingComponents(e.channels,[0,1,2],g.channels,[2,1,0]);break;case ee.HWB:g.channels=carryForwardMissingComponents(e.channels,[0],g.channels,[2]);break;case ee.Lab:case ee.OKLab:g.channels=carryForwardMissingComponents(e.channels,[0],g.channels,[0]);break;case ee.LCH:case ee.OKLCH:g.channels=carryForwardMissingComponents(e.channels,[0,1,2],g.channels,[0,1,2])}}return g.channels=convertPowerlessComponentsToMissingComponents(g.channels,a),g}function convertPowerlessComponentsToMissingComponents(e,a){const n=[...e];switch(a){case ee.HSL:reducePrecision(n[1],4)<=0&&(n[0]=NaN);break;case ee.HWB:Math.max(0,reducePrecision(n[1],4))+Math.max(0,reducePrecision(n[2],4))>=100&&(n[0]=NaN);break;case ee.LCH:reducePrecision(n[1],4)<=0&&(n[2]=NaN);break;case ee.OKLCH:reducePrecision(n[1],6)<=0&&(n[2]=NaN)}return n}function convertPowerlessComponentsToZeroValuesForDisplay(e,a){const n=[...e];switch(a){case ee.HSL:(reducePrecision(n[2])<=0||reducePrecision(n[2])>=100)&&(n[0]=NaN,n[1]=NaN),reducePrecision(n[1])<=0&&(n[0]=NaN);break;case ee.HWB:Math.max(0,reducePrecision(n[1]))+Math.max(0,reducePrecision(n[2]))>=100&&(n[0]=NaN);break;case ee.Lab:(reducePrecision(n[0])<=0||reducePrecision(n[0])>=100)&&(n[1]=NaN,n[2]=NaN);break;case ee.LCH:reducePrecision(n[1])<=0&&(n[2]=NaN),(reducePrecision(n[0])<=0||reducePrecision(n[0])>=100)&&(n[1]=NaN,n[2]=NaN);break;case ee.OKLab:(reducePrecision(n[0])<=0||reducePrecision(n[0])>=1)&&(n[1]=NaN,n[2]=NaN);break;case ee.OKLCH:reducePrecision(n[1])<=0&&(n[2]=NaN),(reducePrecision(n[0])<=0||reducePrecision(n[0])>=1)&&(n[1]=NaN,n[2]=NaN)}return n}function carryForwardMissingComponents(e,a,n,r){const o=[...n];for(const n of a)Number.isNaN(e[a[n]])&&(o[r[n]]=NaN);return o}function normalizeRelativeColorDataChannels(e){const a=new Map;switch(e.colorNotation){case ee.RGB:case ee.HEX:a.set("r",dummyNumberToken(255*e.channels[0])),a.set("g",dummyNumberToken(255*e.channels[1])),a.set("b",dummyNumberToken(255*e.channels[2])),"number"==typeof e.alpha&&a.set("alpha",dummyNumberToken(e.alpha));break;case ee.HSL:a.set("h",dummyNumberToken(e.channels[0])),a.set("s",dummyNumberToken(e.channels[1])),a.set("l",dummyNumberToken(e.channels[2])),"number"==typeof e.alpha&&a.set("alpha",dummyNumberToken(e.alpha));break;case ee.HWB:a.set("h",dummyNumberToken(e.channels[0])),a.set("w",dummyNumberToken(e.channels[1])),a.set("b",dummyNumberToken(e.channels[2])),"number"==typeof e.alpha&&a.set("alpha",dummyNumberToken(e.alpha));break;case ee.Lab:case ee.OKLab:a.set("l",dummyNumberToken(e.channels[0])),a.set("a",dummyNumberToken(e.channels[1])),a.set("b",dummyNumberToken(e.channels[2])),"number"==typeof e.alpha&&a.set("alpha",dummyNumberToken(e.alpha));break;case ee.LCH:case ee.OKLCH:a.set("l",dummyNumberToken(e.channels[0])),a.set("c",dummyNumberToken(e.channels[1])),a.set("h",dummyNumberToken(e.channels[2])),"number"==typeof e.alpha&&a.set("alpha",dummyNumberToken(e.alpha));break;case ee.sRGB:case ee.A98_RGB:case ee.Display_P3:case ee.Rec2020:case ee.Linear_sRGB:case ee.ProPhoto_RGB:a.set("r",dummyNumberToken(e.channels[0])),a.set("g",dummyNumberToken(e.channels[1])),a.set("b",dummyNumberToken(e.channels[2])),"number"==typeof e.alpha&&a.set("alpha",dummyNumberToken(e.alpha));break;case ee.XYZ_D50:case ee.XYZ_D65:a.set("x",dummyNumberToken(e.channels[0])),a.set("y",dummyNumberToken(e.channels[1])),a.set("z",dummyNumberToken(e.channels[2])),"number"==typeof e.alpha&&a.set("alpha",dummyNumberToken(e.alpha))}return a}function noneToZeroInRelativeColorDataChannels(e){const a=new Map(e);for(const[n,r]of e)Number.isNaN(r[4].value)&&a.set(n,dummyNumberToken(0));return a}function dummyNumberToken(n){return[e.Number,n.toString(),-1,-1,{value:n,type:a.Number}]}function reducePrecision(e,a=7){if(Number.isNaN(e))return 0;const n=Math.pow(10,a);return Math.round(e*n)/n}function colorDataFitsRGB_Gamut(e){const a={...e,channels:[...e.channels]};a.channels=convertPowerlessComponentsToZeroValuesForDisplay(a.channels,a.colorNotation);return!colorDataTo(a,ee.RGB).channels.find((e=>e<-1e-5||e>1.00001))}function colorDataFitsDisplayP3_Gamut(e){const a={...e,channels:[...e.channels]};a.channels=convertPowerlessComponentsToZeroValuesForDisplay(a.channels,a.colorNotation);return!colorDataTo(a,ee.Display_P3).channels.find((e=>e<-1e-5||e>1.00001))}function normalize(e,a,n,r){return Math.min(Math.max(e/a,n),r)}const re=/[A-Z]/g;function toLowerCaseAZ(e){return e.replace(re,(e=>String.fromCharCode(e.charCodeAt(0)+32)))}function normalize_Color_ChannelValues(n,r,o){if(n[0]===e.Ident&&"none"===toLowerCaseAZ(n[4].value))return o.syntaxFlags.add(ae.HasNoneKeywords),[e.Number,"none",n[2],n[3],{value:NaN,type:a.Number}];if(n[0]===e.Percentage){3!==r&&o.syntaxFlags.add(ae.HasPercentageValues);let t=normalize(n[4].value,100,-1/0,1/0);return 3===r&&(t=normalize(n[4].value,100,0,1)),[e.Number,t.toString(),n[2],n[3],{value:t,type:a.Number}]}if(n[0]===e.Number){3!==r&&o.syntaxFlags.add(ae.HasNumberValues);let t=normalize(n[4].value,1,-1/0,1/0);return 3===r&&(t=normalize(n[4].value,1,0,1)),[e.Number,t.toString(),n[2],n[3],{value:t,type:a.Number}]}return!1}const oe=new Set(["srgb","srgb-linear","display-p3","a98-rgb","prophoto-rgb","rec2020","xyz","xyz-d50","xyz-d65"]);function color$1(a,n){const r=[],o=[],t=[],l=[];let s,u,i=!1,c=!1;const m={colorNotation:ee.sRGB,channels:[0,0,0],alpha:1,syntaxFlags:new Set([])};let h=r;for(let N=0;N=0){l=s.value[4].value;continue}}return!1}if(!t)return!1;r.push({color:t,percentage:l}),t=!1,l=!1}}if(t&&r.push({color:t,percentage:l}),2!==r.length)return!1;let s=r[0].percentage,u=r[1].percentage;return(!1===s||!(s<0||s>100))&&((!1===u||!(u<0||u>100))&&(!1===s&&!1===u?(s=50,u=50):!1!==s&&!1===u?u=100-s:!1===s&&!1!==u&&(s=100-u),(0!==s||0!==u)&&(!1!==s&&!1!==u&&(s+u>100&&(s=s/(s+u)*100,u=u/(s+u)*100),s+u<100&&(o=(s+u)/100,s=s/(s+u)*100,u=u/(s+u)*100),{a:{color:r[0].color,percentage:s},b:{color:r[1].color,percentage:u},alphaMultiplier:o}))))}function colorMixRectangular(e,a){if(!a)return!1;const n=a.a.color,r=a.b.color,o=a.a.percentage/100;let t=n.channels,l=r.channels,s=ee.RGB,u=n.alpha;if("number"!=typeof u)return!1;let i=r.alpha;if("number"!=typeof i)return!1;switch(u=Number.isNaN(u)?i:u,i=Number.isNaN(i)?u:i,e){case"srgb":s=ee.RGB;break;case"srgb-linear":s=ee.Linear_sRGB;break;case"lab":s=ee.Lab;break;case"oklab":s=ee.OKLab;break;case"xyz-d50":s=ee.XYZ_D50;break;case"xyz":case"xyz-d65":s=ee.XYZ_D65}t=colorDataTo(n,s).channels,l=colorDataTo(r,s).channels,t[0]=fillInMissingComponent(t[0],l[0]),l[0]=fillInMissingComponent(l[0],t[0]),t[1]=fillInMissingComponent(t[1],l[1]),l[1]=fillInMissingComponent(l[1],t[1]),t[2]=fillInMissingComponent(t[2],l[2]),l[2]=fillInMissingComponent(l[2],t[2]),t[0]=premultiply(t[0],u),t[1]=premultiply(t[1],u),t[2]=premultiply(t[2],u),l[0]=premultiply(l[0],i),l[1]=premultiply(l[1],i),l[2]=premultiply(l[2],i);const c=interpolate(u,i,o),m={colorNotation:s,channels:[un_premultiply(interpolate(t[0],l[0],o),c),un_premultiply(interpolate(t[1],l[1],o),c),un_premultiply(interpolate(t[2],l[2],o),c)],alpha:c*a.alphaMultiplier,syntaxFlags:new Set([ae.ColorMix])};return(a.a.color.syntaxFlags.has(ae.Experimental)||a.b.color.syntaxFlags.has(ae.Experimental))&&m.syntaxFlags.add(ae.Experimental),m}function colorMixPolar(e,a,n){if(!n)return!1;const r=n.a.color,o=n.b.color,t=n.a.percentage/100;let l=r.channels,s=o.channels,u=0,i=0,c=0,m=0,h=0,N=0,p=ee.RGB,b=r.alpha;if("number"!=typeof b)return!1;let g=o.alpha;if("number"!=typeof g)return!1;switch(b=Number.isNaN(b)?g:b,g=Number.isNaN(g)?b:g,e){case"hsl":p=ee.HSL;break;case"hwb":p=ee.HWB;break;case"lch":p=ee.LCH;break;case"oklch":p=ee.OKLCH}switch(l=colorDataTo(r,p).channels,s=colorDataTo(o,p).channels,e){case"hsl":case"hwb":u=l[0],i=s[0],c=l[1],m=s[1],h=l[2],N=s[2];break;case"lch":case"oklch":c=l[0],m=s[0],h=l[1],N=s[1],u=l[2],i=s[2]}u=fillInMissingComponent(u,i),Number.isNaN(u)&&(u=0),i=fillInMissingComponent(i,u),Number.isNaN(i)&&(i=0),c=fillInMissingComponent(c,m),m=fillInMissingComponent(m,c),h=fillInMissingComponent(h,N),N=fillInMissingComponent(N,h);const v=i-u;switch(a){case"shorter":v>180?u+=360:v<-180&&(i+=360);break;case"longer":-1800?u+=360:i+=360);break;case"increasing":v<0&&(i+=360);break;case"decreasing":v>0&&(u+=360);break;default:throw new Error("Unknown hue interpolation method")}c=premultiply(c,b),h=premultiply(h,b),m=premultiply(m,g),N=premultiply(N,g);let d=[0,0,0];const f=interpolate(b,g,t);switch(e){case"hsl":case"hwb":d=[interpolate(u,i,t),un_premultiply(interpolate(c,m,t),f),un_premultiply(interpolate(h,N,t),f)];break;case"lch":case"oklch":d=[un_premultiply(interpolate(c,m,t),f),un_premultiply(interpolate(h,N,t),f),interpolate(u,i,t)]}const y={colorNotation:p,channels:d,alpha:f*n.alphaMultiplier,syntaxFlags:new Set([ae.ColorMix])};return(n.a.color.syntaxFlags.has(ae.Experimental)||n.b.color.syntaxFlags.has(ae.Experimental))&&y.syntaxFlags.add(ae.Experimental),y}function fillInMissingComponent(e,a){return Number.isNaN(e)?a:e}function interpolate(e,a,n){return e*n+a*(1-n)}function premultiply(e,a){return Number.isNaN(a)?e:Number.isNaN(e)?NaN:e*a}function un_premultiply(e,a){return 0===a||Number.isNaN(a)?e:Number.isNaN(e)?NaN:e/a}function hex(e){const a=toLowerCaseAZ(e[4].value);if(a.match(/[^a-f0-9]/))return!1;const n={colorNotation:ee.HEX,channels:[0,0,0],alpha:1,syntaxFlags:new Set([ae.Hex])},r=a.length;if(3===r){const e=a[0],r=a[1],o=a[2];return n.channels=[parseInt(e+e,16)/255,parseInt(r+r,16)/255,parseInt(o+o,16)/255],n}if(6===r){const e=a[0]+a[1],r=a[2]+a[3],o=a[4]+a[5];return n.channels=[parseInt(e,16)/255,parseInt(r,16)/255,parseInt(o,16)/255],n}if(4===r){const e=a[0],r=a[1],o=a[2],t=a[3];return n.channels=[parseInt(e+e,16)/255,parseInt(r+r,16)/255,parseInt(o+o,16)/255],n.alpha=parseInt(t+t,16)/255,n.syntaxFlags.add(ae.HasAlpha),n}if(8===r){const e=a[0]+a[1],r=a[2]+a[3],o=a[4]+a[5],t=a[6]+a[7];return n.channels=[parseInt(e,16)/255,parseInt(r,16)/255,parseInt(o,16)/255],n.alpha=parseInt(t,16)/255,n.syntaxFlags.add(ae.HasAlpha),n}return!1}function normalizeHue(n){if(n[0]===e.Number)return n[4].value=n[4].value%360,n[1]=n[4].value.toString(),n;if(n[0]===e.Dimension){let r=n[4].value;switch(toLowerCaseAZ(n[4].unit)){case"deg":break;case"rad":r=180*n[4].value/Math.PI;break;case"grad":r=.9*n[4].value;break;case"turn":r=360*n[4].value;break;default:return!1}return r%=360,[e.Number,r.toString(),n[2],n[3],{value:r,type:a.Number}]}return!1}function normalize_legacy_HSL_ChannelValues(n,r,o){if(0===r){const a=normalizeHue(n);return!1!==a&&(n[0]===e.Dimension&&o.syntaxFlags.add(ae.HasDimensionValues),a)}if(n[0]===e.Percentage){3===r?o.syntaxFlags.add(ae.HasPercentageAlpha):o.syntaxFlags.add(ae.HasPercentageValues);let t=normalize(n[4].value,1,0,100);return 3===r&&(t=normalize(n[4].value,100,0,1)),[e.Number,t.toString(),n[2],n[3],{value:t,type:a.Number}]}if(n[0]===e.Number){if(3!==r)return!1;let o=normalize(n[4].value,1,0,100);return 3===r&&(o=normalize(n[4].value,1,0,1)),[e.Number,o.toString(),n[2],n[3],{value:o,type:a.Number}]}return!1}function normalize_modern_HSL_ChannelValues(n,r,o){if(n[0]===e.Ident&&"none"===toLowerCaseAZ(n[4].value))return o.syntaxFlags.add(ae.HasNoneKeywords),[e.Number,"none",n[2],n[3],{value:NaN,type:a.Number}];if(0===r){const a=normalizeHue(n);return!1!==a&&(n[0]===e.Dimension&&o.syntaxFlags.add(ae.HasDimensionValues),a)}if(n[0]===e.Percentage){3===r?o.syntaxFlags.add(ae.HasPercentageAlpha):o.syntaxFlags.add(ae.HasPercentageValues);let t=n[4].value;return 3===r&&(t=normalize(n[4].value,100,0,1)),[e.Number,t.toString(),n[2],n[3],{value:t,type:a.Number}]}if(n[0]===e.Number){3!==r&&o.syntaxFlags.add(ae.HasNumberValues);let t=n[4].value;return 3===r&&(t=normalize(n[4].value,1,0,1)),[e.Number,t.toString(),n[2],n[3],{value:t,type:a.Number}]}return!1}function threeChannelLegacySyntax(a,n,r,o){const t=[],l=[],s=[],u=[],i={colorNotation:r,channels:[0,0,0],alpha:1,syntaxFlags:new Set(o)};let c=t;for(let n=0;nW(a)&&a.value[0]===e.Comma))){const e=hslCommaSeparated(a);if(!1!==e)return e}{const e=hslSpaceSeparated(a,n);if(!1!==e)return e}return!1}function hslCommaSeparated(e){return threeChannelLegacySyntax(e,normalize_legacy_HSL_ChannelValues,ee.HSL,[ae.LegacyHSL])}function hslSpaceSeparated(e,a){return threeChannelSpaceSeparated(e,normalize_modern_HSL_ChannelValues,ee.HSL,[],a)}function normalize_HWB_ChannelValues(n,r,o){if(n[0]===e.Ident&&"none"===toLowerCaseAZ(n[4].value))return o.syntaxFlags.add(ae.HasNoneKeywords),[e.Number,"none",n[2],n[3],{value:NaN,type:a.Number}];if(0===r){const a=normalizeHue(n);return!1!==a&&(n[0]===e.Dimension&&o.syntaxFlags.add(ae.HasDimensionValues),a)}if(n[0]===e.Percentage){3===r?o.syntaxFlags.add(ae.HasPercentageAlpha):o.syntaxFlags.add(ae.HasPercentageValues);let t=n[4].value;return 3===r&&(t=normalize(n[4].value,100,0,1)),[e.Number,t.toString(),n[2],n[3],{value:t,type:a.Number}]}if(n[0]===e.Number){3!==r&&o.syntaxFlags.add(ae.HasNumberValues);let t=n[4].value;return 3===r&&(t=normalize(n[4].value,1,0,1)),[e.Number,t.toString(),n[2],n[3],{value:t,type:a.Number}]}return!1}function normalize_Lab_ChannelValues(n,r,o){if(n[0]===e.Ident&&"none"===toLowerCaseAZ(n[4].value))return o.syntaxFlags.add(ae.HasNoneKeywords),[e.Number,"none",n[2],n[3],{value:NaN,type:a.Number}];if(n[0]===e.Percentage){3!==r&&o.syntaxFlags.add(ae.HasPercentageValues);let t=normalize(n[4].value,1,0,100);return 1===r||2===r?t=normalize(n[4].value,.8,-1/0,1/0):3===r&&(t=normalize(n[4].value,100,0,1)),[e.Number,t.toString(),n[2],n[3],{value:t,type:a.Number}]}if(n[0]===e.Number){3!==r&&o.syntaxFlags.add(ae.HasNumberValues);let t=normalize(n[4].value,1,0,100);return 1===r||2===r?t=normalize(n[4].value,1,-1/0,1/0):3===r&&(t=normalize(n[4].value,1,0,1)),[e.Number,t.toString(),n[2],n[3],{value:t,type:a.Number}]}return!1}function lab(e,a){return threeChannelSpaceSeparated(e,normalize_Lab_ChannelValues,ee.Lab,[],a)}function normalize_LCH_ChannelValues(n,r,o){if(n[0]===e.Ident&&"none"===toLowerCaseAZ(n[4].value))return o.syntaxFlags.add(ae.HasNoneKeywords),[e.Number,"none",n[2],n[3],{value:NaN,type:a.Number}];if(2===r){const a=normalizeHue(n);return!1!==a&&(n[0]===e.Dimension&&o.syntaxFlags.add(ae.HasDimensionValues),a)}if(n[0]===e.Percentage){3!==r&&o.syntaxFlags.add(ae.HasPercentageValues);let t=normalize(n[4].value,1,0,100);return 1===r?t=normalize(n[4].value,100/150,0,1/0):3===r&&(t=normalize(n[4].value,100,0,1)),[e.Number,t.toString(),n[2],n[3],{value:t,type:a.Number}]}if(n[0]===e.Number){3!==r&&o.syntaxFlags.add(ae.HasNumberValues);let t=normalize(n[4].value,1,0,100);return 1===r?t=normalize(n[4].value,1,0,1/0):3===r&&(t=normalize(n[4].value,1,0,1)),[e.Number,t.toString(),n[2],n[3],{value:t,type:a.Number}]}return!1}function lch(e,a){return threeChannelSpaceSeparated(e,normalize_LCH_ChannelValues,ee.LCH,[],a)}const ue=new Map;for(const[e,a]of Object.entries(S))ue.set(e,a);function namedColor(e){const a=ue.get(toLowerCaseAZ(e));return!!a&&{colorNotation:ee.RGB,channels:[a[0]/255,a[1]/255,a[2]/255],alpha:1,syntaxFlags:new Set([ae.ColorKeyword,ae.NamedColor])}}function normalize_OKLab_ChannelValues(n,r,o){if(n[0]===e.Ident&&"none"===toLowerCaseAZ(n[4].value))return o.syntaxFlags.add(ae.HasNoneKeywords),[e.Number,"none",n[2],n[3],{value:NaN,type:a.Number}];if(n[0]===e.Percentage){3!==r&&o.syntaxFlags.add(ae.HasPercentageValues);let t=normalize(n[4].value,100,0,1);return 1===r||2===r?t=normalize(n[4].value,250,-1/0,1/0):3===r&&(t=normalize(n[4].value,100,0,1)),[e.Number,t.toString(),n[2],n[3],{value:t,type:a.Number}]}if(n[0]===e.Number){3!==r&&o.syntaxFlags.add(ae.HasNumberValues);let t=normalize(n[4].value,1,0,1);return 1===r||2===r?t=normalize(n[4].value,1,-1/0,1/0):3===r&&(t=normalize(n[4].value,1,0,1)),[e.Number,t.toString(),n[2],n[3],{value:t,type:a.Number}]}return!1}function oklab(e,a){return threeChannelSpaceSeparated(e,normalize_OKLab_ChannelValues,ee.OKLab,[],a)}function normalize_OKLCH_ChannelValues(n,r,o){if(n[0]===e.Ident&&"none"===toLowerCaseAZ(n[4].value))return o.syntaxFlags.add(ae.HasNoneKeywords),[e.Number,"none",n[2],n[3],{value:NaN,type:a.Number}];if(2===r){const a=normalizeHue(n);return!1!==a&&(n[0]===e.Dimension&&o.syntaxFlags.add(ae.HasDimensionValues),a)}if(n[0]===e.Percentage){3!==r&&o.syntaxFlags.add(ae.HasPercentageValues);let t=normalize(n[4].value,100,0,1);return 1===r?t=normalize(n[4].value,250,0,1/0):3===r&&(t=normalize(n[4].value,100,0,1)),[e.Number,t.toString(),n[2],n[3],{value:t,type:a.Number}]}if(n[0]===e.Number){3!==r&&o.syntaxFlags.add(ae.HasNumberValues);let t=normalize(n[4].value,1,0,1);return 1===r?t=normalize(n[4].value,1,0,1/0):3===r&&(t=normalize(n[4].value,1,0,1)),[e.Number,t.toString(),n[2],n[3],{value:t,type:a.Number}]}return!1}function oklch(e,a){return threeChannelSpaceSeparated(e,normalize_OKLCH_ChannelValues,ee.OKLCH,[],a)}function normalize_legacy_sRGB_ChannelValues(n,r,o){if(n[0]===e.Percentage){3===r?o.syntaxFlags.add(ae.HasPercentageAlpha):o.syntaxFlags.add(ae.HasPercentageValues);const t=normalize(n[4].value,100,0,1);return[e.Number,t.toString(),n[2],n[3],{value:t,type:a.Number}]}if(n[0]===e.Number){3!==r&&o.syntaxFlags.add(ae.HasNumberValues);let t=normalize(n[4].value,255,0,1);return 3===r&&(t=normalize(n[4].value,1,0,1)),[e.Number,t.toString(),n[2],n[3],{value:t,type:a.Number}]}return!1}function normalize_modern_sRGB_ChannelValues(n,r,o){if(n[0]===e.Ident&&"none"===toLowerCaseAZ(n[4].value))return o.syntaxFlags.add(ae.HasNoneKeywords),[e.Number,"none",n[2],n[3],{value:NaN,type:a.Number}];if(n[0]===e.Percentage){3!==r&&o.syntaxFlags.add(ae.HasPercentageValues);let t=normalize(n[4].value,100,-1/0,1/0);return 3===r&&(t=normalize(n[4].value,100,0,1)),[e.Number,t.toString(),n[2],n[3],{value:t,type:a.Number}]}if(n[0]===e.Number){3!==r&&o.syntaxFlags.add(ae.HasNumberValues);let t=normalize(n[4].value,255,-1/0,1/0);return 3===r&&(t=normalize(n[4].value,1,0,1)),[e.Number,t.toString(),n[2],n[3],{value:t,type:a.Number}]}return!1}function rgb(a,n){if(a.value.some((a=>W(a)&&a.value[0]===e.Comma))){const e=rgbCommaSeparated(a);if(!1!==e)return(!e.syntaxFlags.has(ae.HasNumberValues)||!e.syntaxFlags.has(ae.HasPercentageValues))&&e}else{const e=rgbSpaceSeparated(a,n);if(!1!==e)return e}return!1}function rgbCommaSeparated(e){return threeChannelLegacySyntax(e,normalize_legacy_sRGB_ChannelValues,ee.RGB,[ae.LegacyRGB])}function rgbSpaceSeparated(e,a){return threeChannelSpaceSeparated(e,normalize_modern_sRGB_ChannelValues,ee.RGB,[],a)}function toPrecision(e,a=7){e=+e,a=+a;const n=(Math.floor(e)+"").length;if(a>n)return+e.toFixed(a-n);{const r=10**(n-a);return Math.round(e/r)*r}}function XYZ_D50_to_P3_Gamut(e){const a=N(e);if(k(a))return z(a);let n=e.slice();return n=t(n),n[0]<1e-6&&(n=[0,0,0]),n[0]>.999999&&(n=[1,0,0]),F(n,(e=>(e=Z(e),e=M(e),e=R(e),B(e))),(e=>(e=G(e),e=V(e),e=A(e),T(e))))}function serializeWithAlpha(n,r,o,t){const l=[e.CloseParen,")",-1,-1,void 0];if("number"==typeof n.alpha){const s=Math.min(1,Math.max(0,toPrecision(Number.isNaN(n.alpha)?0:n.alpha)));return 1===toPrecision(s,4)?new j(r,l,t):new j(r,l,[...t,new q([o]),new $([e.Delim,"/",-1,-1,{value:"/"}]),new q([o]),new $([e.Number,toPrecision(s,4).toString(),-1,-1,{value:n.alpha,type:a.Integer}])])}return new j(r,l,[...t,new q([o]),new $([e.Delim,"/",-1,-1,{value:"/"}]),new q([o]),n.alpha])}function serializeP3(n,r=!0){n.channels=convertPowerlessComponentsToZeroValuesForDisplay(n.channels,n.colorNotation);let o=n.channels.map((e=>Number.isNaN(e)?0:e));n.colorNotation!==ee.Display_P3&&(o=r?XYZ_D50_to_P3_Gamut(colorData_to_XYZ_D50(n).channels):N(colorData_to_XYZ_D50(n).channels));const t=toPrecision(o[0],6),l=toPrecision(o[1],6),s=toPrecision(o[2],6),u=[e.Function,"color(",-1,-1,{value:"color"}],i=[e.Whitespace," ",-1,-1,void 0];return serializeWithAlpha(n,u,i,[new $([e.Ident,"display-p3",-1,-1,{value:"display-p3"}]),new q([i]),new $([e.Number,t.toString(),-1,-1,{value:o[0],type:a.Number}]),new q([i]),new $([e.Number,l.toString(),-1,-1,{value:o[1],type:a.Number}]),new q([i]),new $([e.Number,s.toString(),-1,-1,{value:o[2],type:a.Number}])])}function XYZ_D50_to_sRGB_Gamut(e){const a=b(e);if(k(a))return z(a);let n=e.slice();return n=t(n),n[0]<1e-6&&(n=[0,0,0]),n[0]>.999999&&(n=[1,0,0]),F(n,(e=>(e=Z(e),e=M(e),e=I(e),X(e))),(e=>(e=K(e),e=Y(e),e=A(e),T(e))))}function serializeRGB(n,r=!0){n.channels=convertPowerlessComponentsToZeroValuesForDisplay(n.channels,n.colorNotation);let o=n.channels.map((e=>Number.isNaN(e)?0:e));o=r?XYZ_D50_to_sRGB_Gamut(colorData_to_XYZ_D50(n).channels):b(colorData_to_XYZ_D50(n).channels);const t=Math.min(255,Math.max(0,Math.round(255*toPrecision(o[0])))),l=Math.min(255,Math.max(0,Math.round(255*toPrecision(o[1])))),s=Math.min(255,Math.max(0,Math.round(255*toPrecision(o[2])))),u=[e.CloseParen,")",-1,-1,void 0],i=[e.Whitespace," ",-1,-1,void 0],c=[e.Comma,",",-1,-1,void 0],m=[new $([e.Number,t.toString(),-1,-1,{value:o[0],type:a.Integer}]),new $(c),new q([i]),new $([e.Number,l.toString(),-1,-1,{value:o[1],type:a.Integer}]),new $(c),new q([i]),new $([e.Number,s.toString(),-1,-1,{value:o[2],type:a.Integer}])];if("number"==typeof n.alpha){const r=Math.min(1,Math.max(0,toPrecision(Number.isNaN(n.alpha)?0:n.alpha)));return 1===toPrecision(r,4)?new j([e.Function,"rgb(",-1,-1,{value:"rgb"}],u,m):new j([e.Function,"rgba(",-1,-1,{value:"rgba"}],u,[...m,new $(c),new q([i]),new $([e.Number,toPrecision(r,4).toString(),-1,-1,{value:n.alpha,type:a.Number}])])}return new j([e.Function,"rgba(",-1,-1,{value:"rgba"}],u,[...m,new $(c),new q([i]),n.alpha])}function serializeHSL(n,r=!0){n.channels=convertPowerlessComponentsToZeroValuesForDisplay(n.channels,n.colorNotation);let o=n.channels.map((e=>Number.isNaN(e)?0:e));o=i(r?D(XYZ_D50_to_sRGB_Gamut(colorData_to_XYZ_D50(n).channels)):colorData_to_XYZ_D50(n).channels),o=o.map((e=>Number.isNaN(e)?0:e));const t=Math.min(360,Math.max(0,Math.round(toPrecision(o[0])))),l=Math.min(100,Math.max(0,Math.round(toPrecision(o[1])))),s=Math.min(100,Math.max(0,Math.round(toPrecision(o[2])))),u=[e.CloseParen,")",-1,-1,void 0],c=[e.Whitespace," ",-1,-1,void 0],m=[e.Comma,",",-1,-1,void 0],h=[new $([e.Number,t.toString(),-1,-1,{value:o[0],type:a.Integer}]),new $(m),new q([c]),new $([e.Percentage,l.toString()+"%",-1,-1,{value:o[1]}]),new $(m),new q([c]),new $([e.Percentage,s.toString()+"%",-1,-1,{value:o[2]}])];if("number"==typeof n.alpha){const r=Math.min(1,Math.max(0,toPrecision(Number.isNaN(n.alpha)?0:n.alpha)));return 1===toPrecision(r,4)?new j([e.Function,"hsl(",-1,-1,{value:"hsl"}],u,h):new j([e.Function,"hsla(",-1,-1,{value:"hsla"}],u,[...h,new $(m),new q([c]),new $([e.Number,toPrecision(r,4).toString(),-1,-1,{value:n.alpha,type:a.Number}])])}return new j([e.Function,"hsla(",-1,-1,{value:"hsla"}],u,[...h,new $(m),new q([c]),n.alpha])}function serializeOKLCH(n){n.channels=convertPowerlessComponentsToZeroValuesForDisplay(n.channels,n.colorNotation);let r=n.channels.map((e=>Number.isNaN(e)?0:e));n.colorNotation!==ee.OKLCH&&(r=t(colorData_to_XYZ_D50(n).channels));const o=toPrecision(r[0],6),l=toPrecision(r[1],6),s=toPrecision(r[2],6),u=[e.Function,"oklch(",-1,-1,{value:"oklch"}],i=[e.Whitespace," ",-1,-1,void 0];return serializeWithAlpha(n,u,i,[new $([e.Number,o.toString(),-1,-1,{value:r[0],type:a.Number}]),new q([i]),new $([e.Number,l.toString(),-1,-1,{value:r[1],type:a.Number}]),new q([i]),new $([e.Number,s.toString(),-1,-1,{value:r[2],type:a.Number}])])}function color(a){if(U(a)){switch(toLowerCaseAZ(a.getName())){case"rgb":case"rgba":return rgb(a,color);case"hsl":case"hsla":return hsl(a,color);case"hwb":return n=color,threeChannelSpaceSeparated(a,normalize_HWB_ChannelValues,ee.HWB,[],n);case"lab":return lab(a,color);case"lch":return lch(a,color);case"oklab":return oklab(a,color);case"oklch":return oklch(a,color);case"color":return color$1(a,color);case"color-mix":return colorMix(a,color)}}var n;if(W(a)){if(a.value[0]===e.Hash)return hex(a.value);if(a.value[0]===e.Ident){const e=namedColor(a.value[4].value);return!1!==e?e:"transparent"===toLowerCaseAZ(a.value[4].value)&&{colorNotation:ee.RGB,channels:[0,0,0],alpha:0,syntaxFlags:new Set([ae.ColorKeyword])}}}return!1}export{ee as ColorNotation,ae as SyntaxFlag,color,colorDataFitsDisplayP3_Gamut,colorDataFitsRGB_Gamut,colorDataTo,serializeHSL,serializeOKLCH,serializeP3,serializeRGB}; diff --git a/packages/css-color-parser/dist/serialize/hsl.d.ts b/packages/css-color-parser/dist/serialize/hsl.d.ts deleted file mode 100644 index cce037c95..000000000 --- a/packages/css-color-parser/dist/serialize/hsl.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -import { ColorData } from '../color-data'; -import { FunctionNode } from '@csstools/css-parser-algorithms'; -export declare function serializeHSL(color: ColorData, gamutMapping?: boolean): FunctionNode; diff --git a/packages/css-color-parser/dist/serialize/oklch.d.ts b/packages/css-color-parser/dist/serialize/oklch.d.ts deleted file mode 100644 index 97de044a3..000000000 --- a/packages/css-color-parser/dist/serialize/oklch.d.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { ColorData } from '../color-data'; -import { FunctionNode } from '@csstools/css-parser-algorithms'; -/** - * Convert color data to component values in the OKLCH color space. - * The return value can be converted to a string by calling `toString()` on it. - * - * @param {ColorData} color - The color data to be serialized. - * @returns {FunctionNode} The serialized color data as a FunctionNode object. - */ -export declare function serializeOKLCH(color: ColorData): FunctionNode; diff --git a/packages/css-color-parser/dist/serialize/p3.d.ts b/packages/css-color-parser/dist/serialize/p3.d.ts deleted file mode 100644 index c5a0ba9a1..000000000 --- a/packages/css-color-parser/dist/serialize/p3.d.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { ColorData } from '../color-data'; -import { FunctionNode } from '@csstools/css-parser-algorithms'; -/** - * Convert color data to component values in the display-p3 color space. - * The return value can be converted to a string by calling `toString()` on it. - * - * @param {ColorData} color - The color data to be serialized. - * @param {boolean} gamutMapping - Whether to perform gamut mapping, defaults to `true`. - * @returns {FunctionNode} The serialized color data as a FunctionNode object. - */ -export declare function serializeP3(color: ColorData, gamutMapping?: boolean): FunctionNode; diff --git a/packages/css-color-parser/dist/serialize/rgb.d.ts b/packages/css-color-parser/dist/serialize/rgb.d.ts deleted file mode 100644 index 1da6080b6..000000000 --- a/packages/css-color-parser/dist/serialize/rgb.d.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { ColorData } from '../color-data'; -import { FunctionNode } from '@csstools/css-parser-algorithms'; -/** - * Convert color data to component values in the srgb color space. - * The return value can be converted to a string by calling `toString()` on it. - * - * @param {ColorData} color - The color data to be serialized. - * @param {boolean} gamutMapping - Whether to perform gamut mapping, defaults to `true`. - * @returns {FunctionNode} The serialized color data as a FunctionNode object. - */ -export declare function serializeRGB(color: ColorData, gamutMapping?: boolean): FunctionNode; diff --git a/packages/css-color-parser/dist/serialize/to-precision.d.ts b/packages/css-color-parser/dist/serialize/to-precision.d.ts deleted file mode 100644 index 1bcc6b272..000000000 --- a/packages/css-color-parser/dist/serialize/to-precision.d.ts +++ /dev/null @@ -1 +0,0 @@ -export declare function toPrecision(n: number, precision?: number): number; diff --git a/packages/css-color-parser/dist/serialize/with-alpha.d.ts b/packages/css-color-parser/dist/serialize/with-alpha.d.ts deleted file mode 100644 index c214a9ccc..000000000 --- a/packages/css-color-parser/dist/serialize/with-alpha.d.ts +++ /dev/null @@ -1,4 +0,0 @@ -import { ColorData } from '../color-data'; -import type { TokenFunction, TokenWhitespace } from '@csstools/css-tokenizer'; -import { FunctionNode, TokenNode, WhitespaceNode } from '@csstools/css-parser-algorithms'; -export declare function serializeWithAlpha(color: ColorData, fn: TokenFunction, space: TokenWhitespace, channels: Array): FunctionNode; diff --git a/packages/css-color-parser/dist/util/to-lower-case-a-z.d.ts b/packages/css-color-parser/dist/util/to-lower-case-a-z.d.ts deleted file mode 100644 index 396b252e7..000000000 --- a/packages/css-color-parser/dist/util/to-lower-case-a-z.d.ts +++ /dev/null @@ -1 +0,0 @@ -export declare function toLowerCaseAZ(x: string): string; diff --git a/packages/css-color-parser/package.json b/packages/css-color-parser/package.json index 6ef632c92..a487adc75 100644 --- a/packages/css-color-parser/package.json +++ b/packages/css-color-parser/package.json @@ -27,15 +27,18 @@ "engines": { "node": "^14 || ^16 || >=18" }, + "type": "module", "main": "dist/index.cjs", "module": "dist/index.mjs", - "types": "dist/index.d.ts", "exports": { ".": { - "types": "./dist/index.d.ts", - "import": "./dist/index.mjs", - "require": "./dist/index.cjs", - "default": "./dist/index.mjs" + "import": { + "types": "./dist/index.d.ts", + "default": "./dist/index.mjs" + }, + "require": { + "default": "./dist/index.cjs" + } } }, "files": [ diff --git a/packages/css-color-parser/src/color-data.ts b/packages/css-color-parser/src/color-data.ts index 07e506fe5..b175a4a96 100644 --- a/packages/css-color-parser/src/color-data.ts +++ b/packages/css-color-parser/src/color-data.ts @@ -2,7 +2,7 @@ import type { Color } from '@csstools/color-helpers'; import type { ComponentValue } from '@csstools/css-parser-algorithms'; import { ColorNotation } from './color-notation'; import { NumberType, TokenNumber, TokenType } from '@csstools/css-tokenizer'; -import { xyz } from '@csstools/color-helpers'; +import { HSL_to_XYZ_D50, HWB_to_XYZ_D50, LCH_to_XYZ_D50, Lab_to_XYZ_D50, OKLCH_to_XYZ_D50, 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, a98_RGB_to_XYZ_D50, lin_sRGB_to_XYZ_D50, rec_2020_to_XYZ_D50, sRGB_to_XYZ_D50 } from '@csstools/color-helpers'; export type ColorData = { colorNotation: ColorNotation, @@ -52,85 +52,85 @@ export function colorData_to_XYZ_D50(colorData: ColorData): ColorData { return { ...colorData, colorNotation: ColorNotation.XYZ_D50, - channels: xyz.sRGB_to_XYZ_D50(colorData.channels.map((x) => Number.isNaN(x) ? 0 : x) as Color), + channels: sRGB_to_XYZ_D50(colorData.channels.map((x) => Number.isNaN(x) ? 0 : x) as Color), }; case ColorNotation.Linear_sRGB: return { ...colorData, colorNotation: ColorNotation.XYZ_D50, - channels: xyz.lin_sRGB_to_XYZ_D50(colorData.channels.map((x) => Number.isNaN(x) ? 0 : x) as Color), + channels: lin_sRGB_to_XYZ_D50(colorData.channels.map((x) => Number.isNaN(x) ? 0 : x) as Color), }; case ColorNotation.Display_P3: return { ...colorData, colorNotation: ColorNotation.XYZ_D50, - channels: xyz.P3_to_XYZ_D50(colorData.channels.map((x) => Number.isNaN(x) ? 0 : x) as Color), + channels: P3_to_XYZ_D50(colorData.channels.map((x) => Number.isNaN(x) ? 0 : x) as Color), }; case ColorNotation.Rec2020: return { ...colorData, colorNotation: ColorNotation.XYZ_D50, - channels: xyz.rec_2020_to_XYZ_D50(colorData.channels.map((x) => Number.isNaN(x) ? 0 : x) as Color), + channels: rec_2020_to_XYZ_D50(colorData.channels.map((x) => Number.isNaN(x) ? 0 : x) as Color), }; case ColorNotation.A98_RGB: return { ...colorData, colorNotation: ColorNotation.XYZ_D50, - channels: xyz.a98_RGB_to_XYZ_D50(colorData.channels.map((x) => Number.isNaN(x) ? 0 : x) as Color), + channels: a98_RGB_to_XYZ_D50(colorData.channels.map((x) => Number.isNaN(x) ? 0 : x) as Color), }; case ColorNotation.ProPhoto_RGB: return { ...colorData, colorNotation: ColorNotation.XYZ_D50, - channels: xyz.ProPhoto_RGB_to_XYZ_D50(colorData.channels.map((x) => Number.isNaN(x) ? 0 : x) as Color), + channels: ProPhoto_RGB_to_XYZ_D50(colorData.channels.map((x) => Number.isNaN(x) ? 0 : x) as Color), }; case ColorNotation.HSL: return { ...colorData, colorNotation: ColorNotation.XYZ_D50, - channels: xyz.HSL_to_XYZ_D50(colorData.channels.map((x) => Number.isNaN(x) ? 0 : x) as Color), + channels: HSL_to_XYZ_D50(colorData.channels.map((x) => Number.isNaN(x) ? 0 : x) as Color), }; case ColorNotation.HWB: return { ...colorData, colorNotation: ColorNotation.XYZ_D50, - channels: xyz.HWB_to_XYZ_D50(colorData.channels.map((x) => Number.isNaN(x) ? 0 : x) as Color), + channels: HWB_to_XYZ_D50(colorData.channels.map((x) => Number.isNaN(x) ? 0 : x) as Color), }; case ColorNotation.Lab: return { ...colorData, colorNotation: ColorNotation.XYZ_D50, - channels: xyz.Lab_to_XYZ_D50(colorData.channels.map((x) => Number.isNaN(x) ? 0 : x) as Color), + channels: Lab_to_XYZ_D50(colorData.channels.map((x) => Number.isNaN(x) ? 0 : x) as Color), }; case ColorNotation.OKLab: return { ...colorData, colorNotation: ColorNotation.XYZ_D50, - channels: xyz.OKLab_to_XYZ_D50(colorData.channels.map((x) => Number.isNaN(x) ? 0 : x) as Color), + channels: OKLab_to_XYZ_D50(colorData.channels.map((x) => Number.isNaN(x) ? 0 : x) as Color), }; case ColorNotation.LCH: return { ...colorData, colorNotation: ColorNotation.XYZ_D50, - channels: xyz.LCH_to_XYZ_D50(colorData.channels.map((x) => Number.isNaN(x) ? 0 : x) as Color), + channels: LCH_to_XYZ_D50(colorData.channels.map((x) => Number.isNaN(x) ? 0 : x) as Color), }; case ColorNotation.OKLCH: return { ...colorData, colorNotation: ColorNotation.XYZ_D50, - channels: xyz.OKLCH_to_XYZ_D50(colorData.channels.map((x) => Number.isNaN(x) ? 0 : x) as Color), + channels: OKLCH_to_XYZ_D50(colorData.channels.map((x) => Number.isNaN(x) ? 0 : x) as Color), }; case ColorNotation.XYZ_D50: return { ...colorData, colorNotation: ColorNotation.XYZ_D50, - channels: xyz.XYZ_D50_to_XYZ_D50(colorData.channels.map((x) => Number.isNaN(x) ? 0 : x) as Color), + channels: XYZ_D50_to_XYZ_D50(colorData.channels.map((x) => Number.isNaN(x) ? 0 : x) as Color), }; case ColorNotation.XYZ_D65: return { ...colorData, colorNotation: ColorNotation.XYZ_D50, - channels: xyz.XYZ_D65_to_XYZ_D50(colorData.channels.map((x) => Number.isNaN(x) ? 0 : x) as Color), + channels: XYZ_D65_to_XYZ_D50(colorData.channels.map((x) => Number.isNaN(x) ? 0 : x) as Color), }; default: throw new Error('Unsupported color notation'); @@ -163,63 +163,63 @@ export function colorDataTo(colorData: ColorData, toNotation: ColorNotation): Co case ColorNotation.HEX: case ColorNotation.RGB: outputColorData.colorNotation = ColorNotation.RGB; - outputColorData.channels = xyz.XYZ_D50_to_sRGB(xyzColorData.channels); + outputColorData.channels = XYZ_D50_to_sRGB(xyzColorData.channels); break; case ColorNotation.sRGB: outputColorData.colorNotation = ColorNotation.sRGB; - outputColorData.channels = xyz.XYZ_D50_to_sRGB(xyzColorData.channels); + outputColorData.channels = XYZ_D50_to_sRGB(xyzColorData.channels); break; case ColorNotation.Linear_sRGB: outputColorData.colorNotation = ColorNotation.Linear_sRGB; - outputColorData.channels = xyz.XYZ_D50_to_lin_sRGB(xyzColorData.channels); + outputColorData.channels = XYZ_D50_to_lin_sRGB(xyzColorData.channels); break; case ColorNotation.Display_P3: outputColorData.colorNotation = ColorNotation.Display_P3; - outputColorData.channels = xyz.XYZ_D50_to_P3(xyzColorData.channels); + outputColorData.channels = XYZ_D50_to_P3(xyzColorData.channels); break; case ColorNotation.Rec2020: outputColorData.colorNotation = ColorNotation.Rec2020; - outputColorData.channels = xyz.XYZ_D50_to_rec_2020(xyzColorData.channels); + outputColorData.channels = XYZ_D50_to_rec_2020(xyzColorData.channels); break; case ColorNotation.ProPhoto_RGB: outputColorData.colorNotation = ColorNotation.ProPhoto_RGB; - outputColorData.channels = xyz.XYZ_D50_to_ProPhoto(xyzColorData.channels); + outputColorData.channels = XYZ_D50_to_ProPhoto(xyzColorData.channels); break; case ColorNotation.A98_RGB: outputColorData.colorNotation = ColorNotation.A98_RGB; - outputColorData.channels = xyz.XYZ_D50_to_a98_RGB(xyzColorData.channels); + outputColorData.channels = XYZ_D50_to_a98_RGB(xyzColorData.channels); break; case ColorNotation.HSL: outputColorData.colorNotation = ColorNotation.HSL; - outputColorData.channels = xyz.XYZ_D50_to_HSL(xyzColorData.channels); + outputColorData.channels = XYZ_D50_to_HSL(xyzColorData.channels); break; case ColorNotation.HWB: outputColorData.colorNotation = ColorNotation.HWB; - outputColorData.channels = xyz.XYZ_D50_to_HWB(xyzColorData.channels); + outputColorData.channels = XYZ_D50_to_HWB(xyzColorData.channels); break; case ColorNotation.Lab: outputColorData.colorNotation = ColorNotation.Lab; - outputColorData.channels = xyz.XYZ_D50_to_Lab(xyzColorData.channels); + outputColorData.channels = XYZ_D50_to_Lab(xyzColorData.channels); break; case ColorNotation.LCH: outputColorData.colorNotation = ColorNotation.LCH; - outputColorData.channels = xyz.XYZ_D50_to_LCH(xyzColorData.channels); + outputColorData.channels = XYZ_D50_to_LCH(xyzColorData.channels); break; case ColorNotation.OKLCH: outputColorData.colorNotation = ColorNotation.OKLCH; - outputColorData.channels = xyz.XYZ_D50_to_OKLCH(xyzColorData.channels); + outputColorData.channels = XYZ_D50_to_OKLCH(xyzColorData.channels); break; case ColorNotation.OKLab: outputColorData.colorNotation = ColorNotation.OKLab; - outputColorData.channels = xyz.XYZ_D50_to_OKLab(xyzColorData.channels); + outputColorData.channels = XYZ_D50_to_OKLab(xyzColorData.channels); break; case ColorNotation.XYZ_D50: outputColorData.colorNotation = ColorNotation.XYZ_D50; - outputColorData.channels = xyz.XYZ_D50_to_XYZ_D50(xyzColorData.channels); + outputColorData.channels = XYZ_D50_to_XYZ_D50(xyzColorData.channels); break; case ColorNotation.XYZ_D65: outputColorData.colorNotation = ColorNotation.XYZ_D65; - outputColorData.channels = xyz.XYZ_D50_to_XYZ_D65(xyzColorData.channels); + outputColorData.channels = XYZ_D50_to_XYZ_D65(xyzColorData.channels); break; default: throw new Error('Unsupported color notation'); diff --git a/packages/css-color-parser/src/gamut-mapping/p3.ts b/packages/css-color-parser/src/gamut-mapping/p3.ts index 2977e150c..754c8c045 100644 --- a/packages/css-color-parser/src/gamut-mapping/p3.ts +++ b/packages/css-color-parser/src/gamut-mapping/p3.ts @@ -1,15 +1,13 @@ -import { calculations, Color, conversions, utils, xyz } from '@csstools/color-helpers'; +import { clip, XYZ_D50_to_OKLCH, OKLCH_to_OKLab, XYZ_to_lin_P3, gam_P3, XYZ_to_OKLab, OKLab_to_OKLCH, lin_P3_to_XYZ, lin_P3, OKLab_to_XYZ, mapGamut, XYZ_D50_to_P3, inGamut, Color } from '@csstools/color-helpers'; export function XYZ_D50_to_P3_Gamut(color: Color): Color { - const srgb = xyz.XYZ_D50_to_P3(color); - if (utils.inGamut(srgb)) { - return utils.clip(srgb); + const srgb = XYZ_D50_to_P3(color); + if (inGamut(srgb)) { + return clip(srgb); } let oklch = color.slice() as Color; - oklch = conversions.D50_to_D65(oklch); - oklch = conversions.XYZ_to_OKLab(oklch); - oklch = conversions.OKLab_to_OKLCH(oklch); + oklch = XYZ_D50_to_OKLCH(oklch); if (oklch[0] < 0.000001) { oklch = [0, 0, 0] as Color; } @@ -18,15 +16,15 @@ export function XYZ_D50_to_P3_Gamut(color: Color): Color { oklch = [1, 0, 0] as Color; } - return calculations.mapGamut(oklch, (x: Color) => { - x = conversions.OKLCH_to_OKLab(x); - x = conversions.OKLab_to_XYZ(x); - x = conversions.XYZ_to_lin_P3(x); - return conversions.gam_P3(x); + return mapGamut(oklch, (x: Color) => { + x = OKLCH_to_OKLab(x); + x = OKLab_to_XYZ(x); + x = XYZ_to_lin_P3(x); + return gam_P3(x); }, (x: Color) => { - x = conversions.lin_P3(x); - x = conversions.lin_P3_to_XYZ(x); - x = conversions.XYZ_to_OKLab(x); - return conversions.OKLab_to_OKLCH(x); + x = lin_P3(x); + x = lin_P3_to_XYZ(x); + x = XYZ_to_OKLab(x); + return OKLab_to_OKLCH(x); }); } diff --git a/packages/css-color-parser/src/gamut-mapping/srgb.ts b/packages/css-color-parser/src/gamut-mapping/srgb.ts index eb969be1d..ce1c61b70 100644 --- a/packages/css-color-parser/src/gamut-mapping/srgb.ts +++ b/packages/css-color-parser/src/gamut-mapping/srgb.ts @@ -1,15 +1,13 @@ -import { calculations, Color, conversions, utils, xyz } from '@csstools/color-helpers'; +import { clip, XYZ_D50_to_sRGB, OKLCH_to_OKLab, XYZ_to_lin_sRGB, XYZ_D50_to_OKLCH, XYZ_to_OKLab, OKLab_to_OKLCH, gam_sRGB, lin_sRGB, OKLab_to_XYZ, mapGamut, lin_sRGB_to_XYZ, inGamut, Color } from '@csstools/color-helpers'; export function XYZ_D50_to_sRGB_Gamut(color: Color): Color { - const srgb = xyz.XYZ_D50_to_sRGB(color); - if (utils.inGamut(srgb)) { - return utils.clip(srgb); + const srgb = XYZ_D50_to_sRGB(color); + if (inGamut(srgb)) { + return clip(srgb); } let oklch = color.slice() as Color; - oklch = conversions.D50_to_D65(oklch); - oklch = conversions.XYZ_to_OKLab(oklch); - oklch = conversions.OKLab_to_OKLCH(oklch); + oklch = XYZ_D50_to_OKLCH(oklch); if (oklch[0] < 0.000001) { oklch = [0, 0, 0] as Color; } @@ -18,15 +16,15 @@ export function XYZ_D50_to_sRGB_Gamut(color: Color): Color { oklch = [1, 0, 0] as Color; } - return calculations.mapGamut(oklch, (x: Color) => { - x = conversions.OKLCH_to_OKLab(x); - x = conversions.OKLab_to_XYZ(x); - x = conversions.XYZ_to_lin_sRGB(x); - return conversions.gam_sRGB(x); + return mapGamut(oklch, (x: Color) => { + x = OKLCH_to_OKLab(x); + x = OKLab_to_XYZ(x); + x = XYZ_to_lin_sRGB(x); + return gam_sRGB(x); }, (x: Color) => { - x = conversions.lin_sRGB(x); - x = conversions.lin_sRGB_to_XYZ(x); - x = conversions.XYZ_to_OKLab(x); - return conversions.OKLab_to_OKLCH(x); + x = lin_sRGB(x); + x = lin_sRGB_to_XYZ(x); + x = XYZ_to_OKLab(x); + return OKLab_to_OKLCH(x); }); } diff --git a/packages/css-color-parser/src/serialize/hsl.ts b/packages/css-color-parser/src/serialize/hsl.ts index 2790b34a5..6226c330c 100644 --- a/packages/css-color-parser/src/serialize/hsl.ts +++ b/packages/css-color-parser/src/serialize/hsl.ts @@ -2,7 +2,7 @@ import { ColorData, convertPowerlessComponentsToZeroValuesForDisplay } from '../ import type { TokenCloseParen, TokenComma, TokenWhitespace } from '@csstools/css-tokenizer'; import { FunctionNode, TokenNode, WhitespaceNode } from '@csstools/css-parser-algorithms'; import { NumberType, TokenType } from '@csstools/css-tokenizer'; -import { xyz } from '@csstools/color-helpers'; +import { XYZ_D50_to_HSL, sRGB_to_XYZ_D50 } from '@csstools/color-helpers'; import { colorData_to_XYZ_D50 } from '../color-data'; import { toPrecision } from './to-precision'; import { XYZ_D50_to_sRGB_Gamut } from '../gamut-mapping/srgb'; @@ -12,11 +12,11 @@ export function serializeHSL(color: ColorData, gamutMapping = true): FunctionNod let hsl = color.channels.map((x) => Number.isNaN(x) ? 0 : x); if (gamutMapping) { - hsl = xyz.XYZ_D50_to_HSL(xyz.sRGB_to_XYZ_D50( + hsl = XYZ_D50_to_HSL(sRGB_to_XYZ_D50( XYZ_D50_to_sRGB_Gamut(colorData_to_XYZ_D50(color).channels), )); } else { - hsl = xyz.XYZ_D50_to_HSL(colorData_to_XYZ_D50(color).channels); + hsl = XYZ_D50_to_HSL(colorData_to_XYZ_D50(color).channels); } // Needs to be done twice because `xyz.XYZ_D50_to_HSL` can return `NaN` values. diff --git a/packages/css-color-parser/src/serialize/oklch.ts b/packages/css-color-parser/src/serialize/oklch.ts index ed5e4f695..2b54f6577 100644 --- a/packages/css-color-parser/src/serialize/oklch.ts +++ b/packages/css-color-parser/src/serialize/oklch.ts @@ -4,7 +4,7 @@ import { colorData_to_XYZ_D50 } from '../color-data'; import { ColorNotation } from '../color-notation'; import { FunctionNode, TokenNode, WhitespaceNode } from '@csstools/css-parser-algorithms'; import { NumberType, TokenType } from '@csstools/css-tokenizer'; -import { xyz } from '@csstools/color-helpers'; +import { XYZ_D50_to_OKLCH } from '@csstools/color-helpers'; import { toPrecision } from './to-precision'; import { serializeWithAlpha } from './with-alpha'; @@ -22,7 +22,7 @@ export function serializeOKLCH(color: ColorData): FunctionNode { if ( color.colorNotation !== ColorNotation.OKLCH ) { - oklch = xyz.XYZ_D50_to_OKLCH(colorData_to_XYZ_D50(color).channels); + oklch = XYZ_D50_to_OKLCH(colorData_to_XYZ_D50(color).channels); } const l = toPrecision(oklch[0], 6); diff --git a/packages/css-color-parser/src/serialize/p3.ts b/packages/css-color-parser/src/serialize/p3.ts index 0f1bb3608..dca1fe8f1 100644 --- a/packages/css-color-parser/src/serialize/p3.ts +++ b/packages/css-color-parser/src/serialize/p3.ts @@ -4,7 +4,7 @@ import { colorData_to_XYZ_D50 } from '../color-data'; import { ColorNotation } from '../color-notation'; import { FunctionNode, TokenNode, WhitespaceNode } from '@csstools/css-parser-algorithms'; import { NumberType, TokenType } from '@csstools/css-tokenizer'; -import { xyz } from '@csstools/color-helpers'; +import { XYZ_D50_to_P3 } from '@csstools/color-helpers'; import { toPrecision } from './to-precision'; import { XYZ_D50_to_P3_Gamut } from '../gamut-mapping/p3'; import { serializeWithAlpha } from './with-alpha'; @@ -27,7 +27,7 @@ export function serializeP3(color: ColorData, gamutMapping = true): FunctionNode if (gamutMapping) { p3 = XYZ_D50_to_P3_Gamut(colorData_to_XYZ_D50(color).channels); } else { - p3 = xyz.XYZ_D50_to_P3(colorData_to_XYZ_D50(color).channels); + p3 = XYZ_D50_to_P3(colorData_to_XYZ_D50(color).channels); } } diff --git a/packages/css-color-parser/src/serialize/rgb.ts b/packages/css-color-parser/src/serialize/rgb.ts index 3db55316b..412d453a3 100644 --- a/packages/css-color-parser/src/serialize/rgb.ts +++ b/packages/css-color-parser/src/serialize/rgb.ts @@ -2,7 +2,7 @@ import { ColorData, convertPowerlessComponentsToZeroValuesForDisplay } from '../ import type { TokenCloseParen, TokenComma, TokenWhitespace } from '@csstools/css-tokenizer'; import { FunctionNode, TokenNode, WhitespaceNode } from '@csstools/css-parser-algorithms'; import { NumberType, TokenType } from '@csstools/css-tokenizer'; -import { xyz } from '@csstools/color-helpers'; +import { XYZ_D50_to_sRGB } from '@csstools/color-helpers'; import { colorData_to_XYZ_D50 } from '../color-data'; import { toPrecision } from './to-precision'; import { XYZ_D50_to_sRGB_Gamut } from '../gamut-mapping/srgb'; @@ -22,7 +22,7 @@ export function serializeRGB(color: ColorData, gamutMapping = true): FunctionNod if (gamutMapping) { srgb = XYZ_D50_to_sRGB_Gamut(colorData_to_XYZ_D50(color).channels); } else { - srgb = xyz.XYZ_D50_to_sRGB(colorData_to_XYZ_D50(color).channels); + srgb = XYZ_D50_to_sRGB(colorData_to_XYZ_D50(color).channels); } const r = Math.min(255, Math.max(0, Math.round(toPrecision(srgb[0]) * 255))); diff --git a/packages/css-parser-algorithms/CHANGELOG.md b/packages/css-parser-algorithms/CHANGELOG.md index 8801d8f99..141a519b3 100644 --- a/packages/css-parser-algorithms/CHANGELOG.md +++ b/packages/css-parser-algorithms/CHANGELOG.md @@ -2,7 +2,7 @@ ### Unreleased (minor) -- Small fixes in type definitions +- Fix type definitions - Only `walk` child nodes if they are still part of the current AST tree [#1202](https://github.com/csstools/postcss-plugins/issues/1202) - Make `walk` methods safe for mutations [#1204](https://github.com/csstools/postcss-plugins/issues/1204) - Add a `forEach` method to `FunctionNode` and `SimpleBlockNode` diff --git a/packages/css-parser-algorithms/api-extractor.json b/packages/css-parser-algorithms/api-extractor.json new file mode 100644 index 000000000..42058be51 --- /dev/null +++ b/packages/css-parser-algorithms/api-extractor.json @@ -0,0 +1,4 @@ +{ + "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json", + "extends": "../../api-extractor.json" +} diff --git a/packages/css-parser-algorithms/dist/consume/consume-component-block-function.d.ts b/packages/css-parser-algorithms/dist/consume/consume-component-block-function.d.ts deleted file mode 100644 index f8272d80f..000000000 --- a/packages/css-parser-algorithms/dist/consume/consume-component-block-function.d.ts +++ /dev/null @@ -1,203 +0,0 @@ -import { CSSToken, TokenFunction } from '@csstools/css-tokenizer'; -import { Context } from '../interfaces/context'; -import { ComponentValueType } from '../util/component-value-type'; -export type ContainerNode = FunctionNode | SimpleBlockNode; -export type ComponentValue = FunctionNode | SimpleBlockNode | WhitespaceNode | CommentNode | TokenNode; -export declare function consumeComponentValue(ctx: Context, tokens: Array): { - advance: number; - node: ComponentValue; -}; -declare abstract class ContainerNodeBaseClass { - /** - * The contents of the `Function` or `Simple Block`. - * This is a list of component values. - */ - value: Array; - /** - * Retrieve the index of the given item in the current node. - * For most node types this will be trivially implemented as `this.value.indexOf(item)`. - */ - indexOf(item: ComponentValue): number | string; - /** - * Retrieve the item at the given index in the current node. - * For most node types this will be trivially implemented as `this.value[index]`. - */ - at(index: number | string): ComponentValue | undefined; - /** - * Iterates over each item in the `value` array of the current node. - * - * @param cb - The callback function to execute for each item. - * The function receives an object containing the current node (`node`), its parent (`parent`), - * and an optional `state` object. - * A second parameter is the index of the current node. - * The function can return `false` to stop the iteration. - * - * @param state - An optional state object that can be used to pass additional information to the callback function. - * The state object is cloned for each iteration. This means that changes to the state object are not reflected in the next iteration. - * - * @returns `false` if the iteration was halted, `undefined` otherwise. - * - * @template T - The type of the `state` object. - * @template U - The type of the current node. - */ - forEach, U extends ContainerNode>(this: U, cb: (entry: { - node: ComponentValue; - parent: ContainerNode; - state?: T; - }, index: number | string) => boolean | void, state?: T): false | undefined; - /** - * Walks the current node and all its children. - * - * @param cb - The callback function to execute for each item. - * The function receives an object containing the current node (`node`), its parent (`parent`), - * and an optional `state` object. - * A second parameter is the index of the current node. - * The function can return `false` to stop the iteration. - * - * @param state - An optional state object that can be used to pass additional information to the callback function. - * The state object is cloned for each iteration. This means that changes to the state object are not reflected in the next iteration. - * However changes are passed down to child node iterations. - * - * @returns `false` if the iteration was halted, `undefined` otherwise. - * - * @template T - The type of the `state` object. - * @template U - The type of the current node. - */ - walk, U extends ContainerNode>(this: U, cb: (entry: { - node: ComponentValue; - parent: ContainerNode; - state?: T; - }, index: number | string) => boolean | void, state?: T): false | undefined; -} -export declare class FunctionNode extends ContainerNodeBaseClass { - /** - * The node type - * Always `ComponentValueType.Function` - */ - type: ComponentValueType; - /** - * The token for the name of the function. - */ - name: TokenFunction; - /** - * The token for the closing parenthesis of the function. - * If the function is unclosed, this will be an EOF token. - */ - endToken: CSSToken; - constructor(name: TokenFunction, endToken: CSSToken, value: Array); - /** - * Retrieve the name of the current Function. - * This is the parsed and unescaped name of the function. - */ - getName(): string; - /** - * Normalize the current Function: - * - if the "endToken" is EOF, replace with a ")-token" - */ - normalize(): void; - /** - * Retrieve the tokens for the current Function. - * This is the inverse of parsing from a list of tokens. - */ - tokens(): Array; - /** - * Convert the current Function to a string. - * This is not a true serialization. - * It is purely a concatenation of the string representation of the tokens. - */ - toString(): string; - /** - * A debug helper to convert the current object to a JSON representation. - * This is useful in asserts and to store large ASTs in files. - */ - toJSON(): unknown; - /** - * Check if the current object is a FunctionNode. - * This is a type guard to help with type narrowing. - */ - isFunctionNode(): this is FunctionNode; - /** - * Check if the given object is a FunctionNode. - * This is a type guard to help with type narrowing. - */ - static isFunctionNode(x: unknown): x is FunctionNode; -} -export declare function consumeFunction(ctx: Context, tokens: Array): { - advance: number; - node: FunctionNode; -}; -export declare class SimpleBlockNode extends ContainerNodeBaseClass { - type: ComponentValueType; - startToken: CSSToken; - endToken: CSSToken; - constructor(startToken: CSSToken, endToken: CSSToken, value: Array); - /** - * Normalize the current Simple Block: - * - if the "endToken" is EOF, replace with the mirror token of the "startToken" - */ - normalize(): void; - tokens(): Array; - toString(): string; - indexOf(item: ComponentValue): number | string; - at(index: number | string): ComponentValue | undefined; - toJSON(): unknown; - isSimpleBlockNode(): this is SimpleBlockNode; - static isSimpleBlockNode(x: unknown): x is SimpleBlockNode; -} -/** https://www.w3.org/TR/css-syntax-3/#consume-simple-block */ -export declare function consumeSimpleBlock(ctx: Context, tokens: Array): { - advance: number; - node: SimpleBlockNode; -}; -export declare class WhitespaceNode { - type: ComponentValueType; - value: Array; - constructor(value: Array); - tokens(): Array; - toString(): string; - toJSON(): { - type: ComponentValueType; - tokens: CSSToken[]; - }; - isWhitespaceNode(): this is WhitespaceNode; - static isWhitespaceNode(x: unknown): x is WhitespaceNode; -} -export declare function consumeWhitespace(ctx: Context, tokens: Array): { - advance: number; - node: WhitespaceNode; -}; -export declare class CommentNode { - type: ComponentValueType; - value: CSSToken; - constructor(value: CSSToken); - tokens(): Array; - toString(): string; - toJSON(): { - type: ComponentValueType; - tokens: CSSToken[]; - }; - isCommentNode(): this is CommentNode; - static isCommentNode(x: unknown): x is CommentNode; -} -export declare function consumeComment(ctx: Context, tokens: Array): { - advance: number; - node: CommentNode; -}; -export declare function consumeAllCommentsAndWhitespace(ctx: Context, tokens: Array): { - advance: number; - nodes: Array; -}; -export declare class TokenNode { - type: ComponentValueType; - value: CSSToken; - constructor(value: CSSToken); - tokens(): Array; - toString(): string; - toJSON(): { - type: ComponentValueType; - tokens: CSSToken[]; - }; - isTokenNode(): this is TokenNode; - static isTokenNode(x: unknown): x is TokenNode; -} -export {}; diff --git a/packages/css-parser-algorithms/dist/index.cjs b/packages/css-parser-algorithms/dist/index.cjs index a1eaf2076..eedf02936 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(t[0]===n.TokenType.OpenParen||t[0]===n.TokenType.OpenCurly||t[0]===n.TokenType.OpenSquare){const n=consumeSimpleBlock(e,o);return{advance:n.advance,node:n.node}}if(t[0]===n.TokenType.Function){const n=consumeFunction(e,o);return{advance:n.advance,node:n.node}}if(t[0]===n.TokenType.Whitespace){const n=consumeWhitespace(e,o);return{advance:n.advance,node:n.node}}if(t[0]===n.TokenType.Comment){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(){this.endToken[0]===n.TokenType.EOF&&(this.endToken=[n.TokenType.CloseParen,")",-1,-1,void 0])}tokens(){return this.endToken[0]===n.TokenType.EOF?[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||i[0]===n.TokenType.EOF)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(i[0]===n.TokenType.CloseParen)return{advance:s+1,node:new FunctionNode(o[0],i,t)};if(i[0]===n.TokenType.Comment||i[0]===n.TokenType.Whitespace){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(this.endToken[0]===n.TokenType.EOF){const e=n.mirrorVariant(this.startToken);e&&(this.endToken=e)}}tokens(){return this.endToken[0]===n.TokenType.EOF?[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)}indexOf(e){return this.value.indexOf(e)}at(e){if("number"==typeof e)return e<0&&(e=this.value.length+e),this.value[e]}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||r[0]===n.TokenType.EOF)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(r[0]===n.TokenType.Comment||r[0]===n.TokenType.Whitespace){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(;;){if(o[t][0]!==n.TokenType.Whitespace)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(o[s][0]!==n.TokenType.Whitespace){if(o[s][0]!==n.TokenType.Comment)return{advance:s,nodes:t};t.push(new CommentNode(o[s])),s++}else{const e=consumeWhitespace(0,o.slice(s));s+=e.advance,t.push(e.node)}}class TokenNode{type=exports.ComponentValueType.Token;value;constructor(e){this.value=e}tokens(){return[this.value]}toString(){return n.stringify(this.value)}toJSON(){return{type:this.type,tokens:this.tokens()}}isTokenNode(){return TokenNode.isTokenNode(this)}static isTokenNode(e){return!!e&&(e instanceof TokenNode&&e.type===exports.ComponentValueType.Token)}}function isSimpleBlockNode(e){return SimpleBlockNode.isSimpleBlockNode(e)}function isFunctionNode(e){return FunctionNode.isFunctionNode(e)}exports.CommentNode=CommentNode,exports.FunctionNode=FunctionNode,exports.SimpleBlockNode=SimpleBlockNode,exports.TokenNode=TokenNode,exports.WhitespaceNode=WhitespaceNode,exports.consumeAllCommentsAndWhitespace=consumeAllCommentsAndWhitespace,exports.consumeComment=consumeComment,exports.consumeComponentValue=consumeComponentValue,exports.consumeFunction=consumeFunction,exports.consumeSimpleBlock=consumeSimpleBlock,exports.consumeWhitespace=consumeWhitespace,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=isFunctionNode,exports.isSimpleBlockNode=isSimpleBlockNode,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:(null==o?void 0:o.onParseError)??(()=>{})},s=[...e];if(0===e.length)return[];s[s.length-1][0]!==n.TokenType.EOF&&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]||s[a][0]===n.TokenType.EOF)return r.length&&i.push(r),i;if(s[a][0]===n.TokenType.Comma){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:(null==o?void 0:o.onParseError)??(()=>{})},s=[...e];s[s.length-1][0]!==n.TokenType.EOF&&s.push([n.TokenType.EOF,"",s[s.length-1][2],s[s.length-1][3],void 0]);const i=consumeComponentValue(t,s);if(s[Math.min(i.advance,s.length-1)][0]===n.TokenType.EOF)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:(null==o?void 0:o.onParseError)??(()=>{})},s=[...e];s[s.length-1][0]!==n.TokenType.EOF&&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]||s[r][0]===n.TokenType.EOF)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=e.node,s=n(t);s&&e.parent.value.splice(o,1,s)}))}}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.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(t[0]===n.TokenType.OpenParen||t[0]===n.TokenType.OpenCurly||t[0]===n.TokenType.OpenSquare){const n=consumeSimpleBlock(e,o);return{advance:n.advance,node:n.node}}if(t[0]===n.TokenType.Function){const n=consumeFunction(e,o);return{advance:n.advance,node:n.node}}if(t[0]===n.TokenType.Whitespace){const n=consumeWhitespace(e,o);return{advance:n.advance,node:n.node}}if(t[0]===n.TokenType.Comment){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(){this.endToken[0]===n.TokenType.EOF&&(this.endToken=[n.TokenType.CloseParen,")",-1,-1,void 0])}tokens(){return this.endToken[0]===n.TokenType.EOF?[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||i[0]===n.TokenType.EOF)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(i[0]===n.TokenType.CloseParen)return{advance:s+1,node:new FunctionNode(o[0],i,t)};if(i[0]===n.TokenType.Comment||i[0]===n.TokenType.Whitespace){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(this.endToken[0]===n.TokenType.EOF){const e=n.mirrorVariant(this.startToken);e&&(this.endToken=e)}}tokens(){return this.endToken[0]===n.TokenType.EOF?[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)}indexOf(e){return this.value.indexOf(e)}at(e){if("number"==typeof e)return e<0&&(e=this.value.length+e),this.value[e]}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||r[0]===n.TokenType.EOF)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(r[0]===n.TokenType.Comment||r[0]===n.TokenType.Whitespace){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(;;){if(o[t][0]!==n.TokenType.Whitespace)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(o[s][0]!==n.TokenType.Whitespace){if(o[s][0]!==n.TokenType.Comment)return{advance:s,nodes:t};t.push(new CommentNode(o[s])),s++}else{const e=consumeWhitespace(0,o.slice(s));s+=e.advance,t.push(e.node)}}class TokenNode{type=exports.ComponentValueType.Token;value;constructor(e){this.value=e}tokens(){return[this.value]}toString(){return n.stringify(this.value)}toJSON(){return{type:this.type,tokens:this.tokens()}}isTokenNode(){return TokenNode.isTokenNode(this)}static isTokenNode(e){return!!e&&(e instanceof TokenNode&&e.type===exports.ComponentValueType.Token)}}function isSimpleBlockNode(e){return SimpleBlockNode.isSimpleBlockNode(e)}function isFunctionNode(e){return FunctionNode.isFunctionNode(e)}exports.CommentNode=CommentNode,exports.ContainerNodeBaseClass=ContainerNodeBaseClass,exports.FunctionNode=FunctionNode,exports.SimpleBlockNode=SimpleBlockNode,exports.TokenNode=TokenNode,exports.WhitespaceNode=WhitespaceNode,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=isFunctionNode,exports.isSimpleBlockNode=isSimpleBlockNode,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[];s[s.length-1][0]!==n.TokenType.EOF&&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]||s[a][0]===n.TokenType.EOF)return r.length&&i.push(r),i;if(s[a][0]===n.TokenType.Comma){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];s[s.length-1][0]!==n.TokenType.EOF&&s.push([n.TokenType.EOF,"",s[s.length-1][2],s[s.length-1][3],void 0]);const i=consumeComponentValue(t,s);if(s[Math.min(i.advance,s.length-1)][0]===n.TokenType.EOF)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];s[s.length-1][0]!==n.TokenType.EOF&&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]||s[r][0]===n.TokenType.EOF)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=e.node,s=n(t);s&&e.parent.value.splice(o,1,s)}))}}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.walkerIndexGenerator=walkerIndexGenerator; diff --git a/packages/css-parser-algorithms/dist/index.d.ts b/packages/css-parser-algorithms/dist/index.d.ts index a219a756a..7df6e14cc 100644 --- a/packages/css-parser-algorithms/dist/index.d.ts +++ b/packages/css-parser-algorithms/dist/index.d.ts @@ -1,11 +1,249 @@ -export * from './consume/consume-component-block-function'; -export { parseComponentValue } from './parse/parse-component-value'; -export { parseListOfComponentValues } from './parse/parse-list-of-component-values'; -export { parseCommaSeparatedListOfComponentValues } from './parse/parse-comma-separated-list-of-component-values'; -export { gatherNodeAncestry } from './util/node-ancestry'; -export { replaceComponentValues } from './util/replace-component-values'; -export { stringify } from './util/stringify'; -export { walkerIndexGenerator } from './util/walker-index-generator'; -export { ComponentValueType } from './util/component-value-type'; -export { isCommentNode, isFunctionNode, isSimpleBlockNode, isTokenNode, isWhitespaceNode, } from './util/type-predicates'; -export { sourceIndices } from './util/source-indices'; +import { CSSToken } from '@csstools/css-tokenizer'; +import { ParseError } from '@csstools/css-tokenizer'; +import { TokenFunction } from '@csstools/css-tokenizer'; + +export declare class CommentNode { + type: ComponentValueType; + value: CSSToken; + constructor(value: CSSToken); + tokens(): Array; + toString(): string; + toJSON(): { + type: ComponentValueType; + tokens: CSSToken[]; + }; + isCommentNode(): this is CommentNode; + static isCommentNode(x: unknown): x is CommentNode; +} + +export declare type ComponentValue = FunctionNode | SimpleBlockNode | WhitespaceNode | CommentNode | TokenNode; + +export declare enum ComponentValueType { + Function = "function", + SimpleBlock = "simple-block", + Whitespace = "whitespace", + Comment = "comment", + Token = "token" +} + +export declare type ContainerNode = FunctionNode | SimpleBlockNode; + +export declare abstract class ContainerNodeBaseClass { + /** + * The contents of the `Function` or `Simple Block`. + * This is a list of component values. + */ + value: Array; + /** + * Retrieve the index of the given item in the current node. + * For most node types this will be trivially implemented as `this.value.indexOf(item)`. + */ + indexOf(item: ComponentValue): number | string; + /** + * Retrieve the item at the given index in the current node. + * For most node types this will be trivially implemented as `this.value[index]`. + */ + at(index: number | string): ComponentValue | undefined; + /** + * Iterates over each item in the `value` array of the current node. + * + * @param cb - The callback function to execute for each item. + * The function receives an object containing the current node (`node`), its parent (`parent`), + * and an optional `state` object. + * A second parameter is the index of the current node. + * The function can return `false` to stop the iteration. + * + * @param state - An optional state object that can be used to pass additional information to the callback function. + * The state object is cloned for each iteration. This means that changes to the state object are not reflected in the next iteration. + * + * @returns `false` if the iteration was halted, `undefined` otherwise. + * + * @template T - The type of the `state` object. + * @template U - The type of the current node. + */ + forEach, U extends ContainerNode>(this: U, cb: (entry: { + node: ComponentValue; + parent: ContainerNode; + state?: T; + }, index: number | string) => boolean | void, state?: T): false | undefined; + /** + * Walks the current node and all its children. + * + * @param cb - The callback function to execute for each item. + * The function receives an object containing the current node (`node`), its parent (`parent`), + * and an optional `state` object. + * A second parameter is the index of the current node. + * The function can return `false` to stop the iteration. + * + * @param state - An optional state object that can be used to pass additional information to the callback function. + * The state object is cloned for each iteration. This means that changes to the state object are not reflected in the next iteration. + * However changes are passed down to child node iterations. + * + * @returns `false` if the iteration was halted, `undefined` otherwise. + * + * @template T - The type of the `state` object. + * @template U - The type of the current node. + */ + walk, U extends ContainerNode>(this: U, cb: (entry: { + node: ComponentValue; + parent: ContainerNode; + state?: T; + }, index: number | string) => boolean | void, state?: T): false | undefined; +} + +export declare class FunctionNode extends ContainerNodeBaseClass { + /** + * The node type + * Always `ComponentValueType.Function` + */ + type: ComponentValueType; + /** + * The token for the name of the function. + */ + name: TokenFunction; + /** + * The token for the closing parenthesis of the function. + * If the function is unclosed, this will be an EOF token. + */ + endToken: CSSToken; + constructor(name: TokenFunction, endToken: CSSToken, value: Array); + /** + * Retrieve the name of the current Function. + * This is the parsed and unescaped name of the function. + */ + getName(): string; + /** + * Normalize the current Function: + * - if the "endToken" is EOF, replace with a ")-token" + */ + normalize(): void; + /** + * Retrieve the tokens for the current Function. + * This is the inverse of parsing from a list of tokens. + */ + tokens(): Array; + /** + * Convert the current Function to a string. + * This is not a true serialization. + * It is purely a concatenation of the string representation of the tokens. + */ + toString(): string; + /** + * A debug helper to convert the current object to a JSON representation. + * This is useful in asserts and to store large ASTs in files. + */ + toJSON(): unknown; + /** + * Check if the current object is a FunctionNode. + * This is a type guard to help with type narrowing. + */ + isFunctionNode(): this is FunctionNode; + /** + * Check if the given object is a FunctionNode. + * This is a type guard to help with type narrowing. + */ + static isFunctionNode(x: unknown): x is FunctionNode; +} + +export declare function gatherNodeAncestry(node: { + walk(cb: (entry: { + node: Array | unknown; + parent: unknown; + }, index: number | string) => boolean | void): false | undefined; +}): Map; + +export declare function isCommentNode(x: unknown): x is CommentNode; + +export declare function isFunctionNode(x: unknown): x is FunctionNode; + +export declare function isSimpleBlockNode(x: unknown): x is SimpleBlockNode; + +export declare function isTokenNode(x: unknown): x is TokenNode; + +export declare function isWhitespaceNode(x: unknown): x is WhitespaceNode; + +export declare function parseCommaSeparatedListOfComponentValues(tokens: Array, options?: { + onParseError?: (error: ParseError) => void; +}): ComponentValue[][]; + +export declare function parseComponentValue(tokens: Array, options?: { + onParseError?: (error: ParseError) => void; +}): ComponentValue | undefined; + +export declare function parseListOfComponentValues(tokens: Array, options?: { + onParseError?: (error: ParseError) => void; +}): ComponentValue[]; + +export declare function replaceComponentValues(componentValuesList: Array>, replaceWith: (componentValue: ComponentValue) => ComponentValue | void): ComponentValue[][]; + +export declare class SimpleBlockNode extends ContainerNodeBaseClass { + type: ComponentValueType; + startToken: CSSToken; + endToken: CSSToken; + constructor(startToken: CSSToken, endToken: CSSToken, value: Array); + /** + * Normalize the current Simple Block: + * - if the "endToken" is EOF, replace with the mirror token of the "startToken" + */ + normalize(): void; + tokens(): Array; + toString(): string; + indexOf(item: ComponentValue): number | string; + at(index: number | string): ComponentValue | undefined; + toJSON(): unknown; + isSimpleBlockNode(): this is SimpleBlockNode; + static isSimpleBlockNode(x: unknown): x is SimpleBlockNode; +} + +/** + * Returns the start and end index of a node in the CSS source string. + */ +export declare function sourceIndices(x: { + tokens(): Array; +} | Array<{ + tokens(): Array; +}>): [number, number]; + +export declare function stringify(componentValueLists: Array>): string; + +export declare class TokenNode { + type: ComponentValueType; + value: CSSToken; + constructor(value: CSSToken); + tokens(): Array; + toString(): string; + toJSON(): { + type: ComponentValueType; + tokens: CSSToken[]; + }; + isTokenNode(): this is TokenNode; + static isTokenNode(x: unknown): x is TokenNode; +} + +/** + * Generate a function that finds the next element that should be visited when walking an AST. + * Rules : + * - the previous iteration is used as a reference, so any checks are relative to the start of the current iteration. + * - the next element always appears after the current index. + * - the next element always exists in the list. + * - replacing an element does not cause the replaced element to be visited. + * - removing an element does not cause elements to be skipped. + * - an element added later in the list will be visited. + */ +export declare function walkerIndexGenerator(initialList: Array): (list: Array, child: T, index: number) => number; + +export declare class WhitespaceNode { + type: ComponentValueType; + value: Array; + constructor(value: Array); + tokens(): Array; + toString(): string; + toJSON(): { + type: ComponentValueType; + tokens: CSSToken[]; + }; + isWhitespaceNode(): this is WhitespaceNode; + static isWhitespaceNode(x: unknown): x is WhitespaceNode; +} + +export { } diff --git a/packages/css-parser-algorithms/dist/index.mjs b/packages/css-parser-algorithms/dist/index.mjs index 2dcec4f1d..63b5ace36 100644 --- a/packages/css-parser-algorithms/dist/index.mjs +++ b/packages/css-parser-algorithms/dist/index.mjs @@ -1 +1 @@ -import{TokenType as e,isToken as n,stringify as t,ParseError as o,mirrorVariant as s,mirrorVariantType as i}from"@csstools/css-tokenizer";var r;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(n,t){const o=t[0];if(o[0]===e.OpenParen||o[0]===e.OpenCurly||o[0]===e.OpenSquare){const e=consumeSimpleBlock(n,t);return{advance:e.advance,node:e.node}}if(o[0]===e.Function){const e=consumeFunction(n,t);return{advance:e.advance,node:e.node}}if(o[0]===e.Whitespace){const e=consumeWhitespace(n,t);return{advance:e.advance,node:e.node}}if(o[0]===e.Comment){const e=consumeComment(n,t);return{advance:e.advance,node:e.node}}return{advance:1,node:new TokenNode(o)}}!function(e){e.Function="function",e.SimpleBlock="simple-block",e.Whitespace="whitespace",e.Comment="comment",e.Token="token"}(r||(r={}));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=r.Function;name;endToken;constructor(e,n,t){super(),this.name=e,this.endToken=n,this.value=t}getName(){return this.name[4].value}normalize(){this.endToken[0]===e.EOF&&(this.endToken=[e.CloseParen,")",-1,-1,void 0])}tokens(){return this.endToken[0]===e.EOF?[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(e)?t(e):e.toString())).join("");return t(this.name)+e+t(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===r.Function)}}function consumeFunction(n,t){const s=[];let i=1;for(;;){const r=t[i];if(!r||r[0]===e.EOF)return n.onParseError(new o("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],r,s)};if(r[0]===e.CloseParen)return{advance:i+1,node:new FunctionNode(t[0],r,s)};if(r[0]===e.Comment||r[0]===e.Whitespace){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 SimpleBlockNode extends ContainerNodeBaseClass{type=r.SimpleBlock;startToken;endToken;constructor(e,n,t){super(),this.startToken=e,this.endToken=n,this.value=t}normalize(){if(this.endToken[0]===e.EOF){const e=s(this.startToken);e&&(this.endToken=e)}}tokens(){return this.endToken[0]===e.EOF?[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(e)?t(e):e.toString())).join("");return t(this.startToken)+e+t(this.endToken)}indexOf(e){return this.value.indexOf(e)}at(e){if("number"==typeof e)return e<0&&(e=this.value.length+e),this.value[e]}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===r.SimpleBlock)}}function consumeSimpleBlock(n,t){const s=i(t[0][0]);if(!s)throw new Error("Failed to parse, a mirror variant must exist for all block open tokens.");const r=[];let a=1;for(;;){const i=t[a];if(!i||i[0]===e.EOF)return n.onParseError(new o("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],i,r)};if(i[0]===s)return{advance:a+1,node:new SimpleBlockNode(t[0],i,r)};if(i[0]===e.Comment||i[0]===e.Whitespace){const e=consumeAllCommentsAndWhitespace(n,t.slice(a));a+=e.advance,r.push(...e.nodes);continue}const c=consumeComponentValue(n,t.slice(a));a+=c.advance,r.push(c.node)}}class WhitespaceNode{type=r.Whitespace;value;constructor(e){this.value=e}tokens(){return this.value}toString(){return t(...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===r.Whitespace)}}function consumeWhitespace(n,t){let o=0;for(;;){if(t[o][0]!==e.Whitespace)return{advance:o,node:new WhitespaceNode(t.slice(0,o))};o++}}class CommentNode{type=r.Comment;value;constructor(e){this.value=e}tokens(){return[this.value]}toString(){return t(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===r.Comment)}}function consumeComment(e,n){return{advance:1,node:new CommentNode(n[0])}}function consumeAllCommentsAndWhitespace(n,t){const o=[];let s=0;for(;;)if(t[s][0]!==e.Whitespace){if(t[s][0]!==e.Comment)return{advance:s,nodes:o};o.push(new CommentNode(t[s])),s++}else{const e=consumeWhitespace(0,t.slice(s));s+=e.advance,o.push(e.node)}}class TokenNode{type=r.Token;value;constructor(e){this.value=e}tokens(){return[this.value]}toString(){return t(this.value)}toJSON(){return{type:this.type,tokens:this.tokens()}}isTokenNode(){return TokenNode.isTokenNode(this)}static isTokenNode(e){return!!e&&(e instanceof TokenNode&&e.type===r.Token)}}function parseComponentValue(n,t){const s={onParseError:(null==t?void 0:t.onParseError)??(()=>{})},i=[...n];i[i.length-1][0]!==e.EOF&&i.push([e.EOF,"",i[i.length-1][2],i[i.length-1][3],void 0]);const r=consumeComponentValue(s,i);if(i[Math.min(r.advance,i.length-1)][0]===e.EOF)return r.node;s.onParseError(new o("Expected EOF after parsing a component value.",n[0][2],n[n.length-1][3],["5.3.9. Parse a component value","Expected EOF"]))}function parseListOfComponentValues(n,t){const o={onParseError:(null==t?void 0:t.onParseError)??(()=>{})},s=[...n];s[s.length-1][0]!==e.EOF&&s.push([e.EOF,"",s[s.length-1][2],s[s.length-1][3],void 0]);const i=[];let r=0;for(;;){if(!s[r]||s[r][0]===e.EOF)return i;const n=consumeComponentValue(o,s.slice(r));i.push(n.node),r+=n.advance}}function parseCommaSeparatedListOfComponentValues(n,t){const o={onParseError:(null==t?void 0:t.onParseError)??(()=>{})},s=[...n];if(0===n.length)return[];s[s.length-1][0]!==e.EOF&&s.push([e.EOF,"",s[s.length-1][2],s[s.length-1][3],void 0]);const i=[];let r=[],a=0;for(;;){if(!s[a]||s[a][0]===e.EOF)return r.length&&i.push(r),i;if(s[a][0]===e.Comma){i.push(r),r=[],a++;continue}const t=consumeComponentValue(o,n.slice(a));r.push(t.node),a+=t.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 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 replaceComponentValues(e,n){for(let t=0;t{if("number"!=typeof t)return;const o=e.node,s=n(o);s&&e.parent.value.splice(t,1,s)}))}}return e}function stringify(e){return e.map((e=>e.map((e=>t(...e.tokens()))).join(""))).join(",")}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,r as ComponentValueType,FunctionNode,SimpleBlockNode,TokenNode,WhitespaceNode,consumeAllCommentsAndWhitespace,consumeComment,consumeComponentValue,consumeFunction,consumeSimpleBlock,consumeWhitespace,gatherNodeAncestry,isCommentNode,isFunctionNode,isSimpleBlockNode,isTokenNode,isWhitespaceNode,parseCommaSeparatedListOfComponentValues,parseComponentValue,parseListOfComponentValues,replaceComponentValues,sourceIndices,stringify,walkerIndexGenerator}; +import{TokenType as e,isToken as n,stringify as t,mirrorVariant as o,ParseError as s,mirrorVariantType as i}from"@csstools/css-tokenizer";var r;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(n,t){const o=t[0];if(o[0]===e.OpenParen||o[0]===e.OpenCurly||o[0]===e.OpenSquare){const e=consumeSimpleBlock(n,t);return{advance:e.advance,node:e.node}}if(o[0]===e.Function){const e=consumeFunction(n,t);return{advance:e.advance,node:e.node}}if(o[0]===e.Whitespace){const e=consumeWhitespace(n,t);return{advance:e.advance,node:e.node}}if(o[0]===e.Comment){const e=consumeComment(n,t);return{advance:e.advance,node:e.node}}return{advance:1,node:new TokenNode(o)}}!function(e){e.Function="function",e.SimpleBlock="simple-block",e.Whitespace="whitespace",e.Comment="comment",e.Token="token"}(r||(r={}));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=r.Function;name;endToken;constructor(e,n,t){super(),this.name=e,this.endToken=n,this.value=t}getName(){return this.name[4].value}normalize(){this.endToken[0]===e.EOF&&(this.endToken=[e.CloseParen,")",-1,-1,void 0])}tokens(){return this.endToken[0]===e.EOF?[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(e)?t(e):e.toString())).join("");return t(this.name)+e+t(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===r.Function)}}function consumeFunction(n,t){const o=[];let i=1;for(;;){const r=t[i];if(!r||r[0]===e.EOF)return n.onParseError(new s("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],r,o)};if(r[0]===e.CloseParen)return{advance:i+1,node:new FunctionNode(t[0],r,o)};if(r[0]===e.Comment||r[0]===e.Whitespace){const e=consumeAllCommentsAndWhitespace(n,t.slice(i));i+=e.advance,o.push(...e.nodes);continue}const a=consumeComponentValue(n,t.slice(i));i+=a.advance,o.push(a.node)}}class SimpleBlockNode extends ContainerNodeBaseClass{type=r.SimpleBlock;startToken;endToken;constructor(e,n,t){super(),this.startToken=e,this.endToken=n,this.value=t}normalize(){if(this.endToken[0]===e.EOF){const e=o(this.startToken);e&&(this.endToken=e)}}tokens(){return this.endToken[0]===e.EOF?[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(e)?t(e):e.toString())).join("");return t(this.startToken)+e+t(this.endToken)}indexOf(e){return this.value.indexOf(e)}at(e){if("number"==typeof e)return e<0&&(e=this.value.length+e),this.value[e]}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===r.SimpleBlock)}}function consumeSimpleBlock(n,t){const o=i(t[0][0]);if(!o)throw new Error("Failed to parse, a mirror variant must exist for all block open tokens.");const r=[];let a=1;for(;;){const i=t[a];if(!i||i[0]===e.EOF)return n.onParseError(new s("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],i,r)};if(i[0]===o)return{advance:a+1,node:new SimpleBlockNode(t[0],i,r)};if(i[0]===e.Comment||i[0]===e.Whitespace){const e=consumeAllCommentsAndWhitespace(n,t.slice(a));a+=e.advance,r.push(...e.nodes);continue}const c=consumeComponentValue(n,t.slice(a));a+=c.advance,r.push(c.node)}}class WhitespaceNode{type=r.Whitespace;value;constructor(e){this.value=e}tokens(){return this.value}toString(){return t(...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===r.Whitespace)}}function consumeWhitespace(n,t){let o=0;for(;;){if(t[o][0]!==e.Whitespace)return{advance:o,node:new WhitespaceNode(t.slice(0,o))};o++}}class CommentNode{type=r.Comment;value;constructor(e){this.value=e}tokens(){return[this.value]}toString(){return t(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===r.Comment)}}function consumeComment(e,n){return{advance:1,node:new CommentNode(n[0])}}function consumeAllCommentsAndWhitespace(n,t){const o=[];let s=0;for(;;)if(t[s][0]!==e.Whitespace){if(t[s][0]!==e.Comment)return{advance:s,nodes:o};o.push(new CommentNode(t[s])),s++}else{const e=consumeWhitespace(0,t.slice(s));s+=e.advance,o.push(e.node)}}class TokenNode{type=r.Token;value;constructor(e){this.value=e}tokens(){return[this.value]}toString(){return t(this.value)}toJSON(){return{type:this.type,tokens:this.tokens()}}isTokenNode(){return TokenNode.isTokenNode(this)}static isTokenNode(e){return!!e&&(e instanceof TokenNode&&e.type===r.Token)}}function parseComponentValue(n,t){const o={onParseError:t?.onParseError??(()=>{})},i=[...n];i[i.length-1][0]!==e.EOF&&i.push([e.EOF,"",i[i.length-1][2],i[i.length-1][3],void 0]);const r=consumeComponentValue(o,i);if(i[Math.min(r.advance,i.length-1)][0]===e.EOF)return r.node;o.onParseError(new s("Expected EOF after parsing a component value.",n[0][2],n[n.length-1][3],["5.3.9. Parse a component value","Expected EOF"]))}function parseListOfComponentValues(n,t){const o={onParseError:t?.onParseError??(()=>{})},s=[...n];s[s.length-1][0]!==e.EOF&&s.push([e.EOF,"",s[s.length-1][2],s[s.length-1][3],void 0]);const i=[];let r=0;for(;;){if(!s[r]||s[r][0]===e.EOF)return i;const n=consumeComponentValue(o,s.slice(r));i.push(n.node),r+=n.advance}}function parseCommaSeparatedListOfComponentValues(n,t){const o={onParseError:t?.onParseError??(()=>{})},s=[...n];if(0===n.length)return[];s[s.length-1][0]!==e.EOF&&s.push([e.EOF,"",s[s.length-1][2],s[s.length-1][3],void 0]);const i=[];let r=[],a=0;for(;;){if(!s[a]||s[a][0]===e.EOF)return r.length&&i.push(r),i;if(s[a][0]===e.Comma){i.push(r),r=[],a++;continue}const t=consumeComponentValue(o,n.slice(a));r.push(t.node),a+=t.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 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 replaceComponentValues(e,n){for(let t=0;t{if("number"!=typeof t)return;const o=e.node,s=n(o);s&&e.parent.value.splice(t,1,s)}))}}return e}function stringify(e){return e.map((e=>e.map((e=>t(...e.tokens()))).join(""))).join(",")}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,r as ComponentValueType,ContainerNodeBaseClass,FunctionNode,SimpleBlockNode,TokenNode,WhitespaceNode,gatherNodeAncestry,isCommentNode,isFunctionNode,isSimpleBlockNode,isTokenNode,isWhitespaceNode,parseCommaSeparatedListOfComponentValues,parseComponentValue,parseListOfComponentValues,replaceComponentValues,sourceIndices,stringify,walkerIndexGenerator}; diff --git a/packages/css-parser-algorithms/dist/interfaces/context.d.ts b/packages/css-parser-algorithms/dist/interfaces/context.d.ts deleted file mode 100644 index dc246e000..000000000 --- a/packages/css-parser-algorithms/dist/interfaces/context.d.ts +++ /dev/null @@ -1,4 +0,0 @@ -import { ParseError } from '@csstools/css-tokenizer'; -export type Context = { - onParseError: (error: ParseError) => void; -}; diff --git a/packages/css-parser-algorithms/dist/parse/parse-comma-separated-list-of-component-values.d.ts b/packages/css-parser-algorithms/dist/parse/parse-comma-separated-list-of-component-values.d.ts deleted file mode 100644 index 67dff1d04..000000000 --- a/packages/css-parser-algorithms/dist/parse/parse-comma-separated-list-of-component-values.d.ts +++ /dev/null @@ -1,5 +0,0 @@ -import { CSSToken, ParseError } from '@csstools/css-tokenizer'; -import { ComponentValue } from '../consume/consume-component-block-function'; -export declare function parseCommaSeparatedListOfComponentValues(tokens: Array, options?: { - onParseError?: (error: ParseError) => void; -}): ComponentValue[][]; diff --git a/packages/css-parser-algorithms/dist/parse/parse-component-value.d.ts b/packages/css-parser-algorithms/dist/parse/parse-component-value.d.ts deleted file mode 100644 index 2961290f9..000000000 --- a/packages/css-parser-algorithms/dist/parse/parse-component-value.d.ts +++ /dev/null @@ -1,4 +0,0 @@ -import { CSSToken, ParseError } from '@csstools/css-tokenizer'; -export declare function parseComponentValue(tokens: Array, options?: { - onParseError?: (error: ParseError) => void; -}): import("../consume/consume-component-block-function").ComponentValue | undefined; diff --git a/packages/css-parser-algorithms/dist/parse/parse-list-of-component-values.d.ts b/packages/css-parser-algorithms/dist/parse/parse-list-of-component-values.d.ts deleted file mode 100644 index 737f554d2..000000000 --- a/packages/css-parser-algorithms/dist/parse/parse-list-of-component-values.d.ts +++ /dev/null @@ -1,5 +0,0 @@ -import { CSSToken, ParseError } from '@csstools/css-tokenizer'; -import { ComponentValue } from '../consume/consume-component-block-function'; -export declare function parseListOfComponentValues(tokens: Array, options?: { - onParseError?: (error: ParseError) => void; -}): ComponentValue[]; diff --git a/packages/css-parser-algorithms/dist/util/component-value-type.d.ts b/packages/css-parser-algorithms/dist/util/component-value-type.d.ts deleted file mode 100644 index eda7ee93c..000000000 --- a/packages/css-parser-algorithms/dist/util/component-value-type.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -export declare enum ComponentValueType { - Function = "function", - SimpleBlock = "simple-block", - Whitespace = "whitespace", - Comment = "comment", - Token = "token" -} diff --git a/packages/css-parser-algorithms/dist/util/node-ancestry.d.ts b/packages/css-parser-algorithms/dist/util/node-ancestry.d.ts deleted file mode 100644 index a6a63303f..000000000 --- a/packages/css-parser-algorithms/dist/util/node-ancestry.d.ts +++ /dev/null @@ -1,8 +0,0 @@ -interface walkable { - walk(cb: (entry: { - node: Array | unknown; - parent: unknown; - }, index: number | string) => boolean | void): false | undefined; -} -export declare function gatherNodeAncestry(node: walkable): Map; -export {}; diff --git a/packages/css-parser-algorithms/dist/util/replace-component-values.d.ts b/packages/css-parser-algorithms/dist/util/replace-component-values.d.ts deleted file mode 100644 index 774051c6d..000000000 --- a/packages/css-parser-algorithms/dist/util/replace-component-values.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import type { ComponentValue } from '../consume/consume-component-block-function'; -export declare function replaceComponentValues(componentValuesList: Array>, replaceWith: (componentValue: ComponentValue) => ComponentValue | void): ComponentValue[][]; diff --git a/packages/css-parser-algorithms/dist/util/source-indices.d.ts b/packages/css-parser-algorithms/dist/util/source-indices.d.ts deleted file mode 100644 index 92d124bef..000000000 --- a/packages/css-parser-algorithms/dist/util/source-indices.d.ts +++ /dev/null @@ -1,9 +0,0 @@ -import { CSSToken } from '@csstools/css-tokenizer'; -interface TokenConvertible { - tokens(): Array; -} -/** - * Returns the start and end index of a node in the CSS source string. - */ -export declare function sourceIndices(x: TokenConvertible | Array): [number, number]; -export {}; diff --git a/packages/css-parser-algorithms/dist/util/stringify.d.ts b/packages/css-parser-algorithms/dist/util/stringify.d.ts deleted file mode 100644 index 6ab4140cf..000000000 --- a/packages/css-parser-algorithms/dist/util/stringify.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import type { ComponentValue } from '../consume/consume-component-block-function'; -export declare function stringify(componentValueLists: Array>): string; diff --git a/packages/css-parser-algorithms/dist/util/type-predicates.d.ts b/packages/css-parser-algorithms/dist/util/type-predicates.d.ts deleted file mode 100644 index 896d3036b..000000000 --- a/packages/css-parser-algorithms/dist/util/type-predicates.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { CommentNode, FunctionNode, SimpleBlockNode, TokenNode, WhitespaceNode } from '../consume/consume-component-block-function'; -export declare function isSimpleBlockNode(x: unknown): x is SimpleBlockNode; -export declare function isFunctionNode(x: unknown): x is FunctionNode; -export declare function isWhitespaceNode(x: unknown): x is WhitespaceNode; -export declare function isCommentNode(x: unknown): x is CommentNode; -export declare function isTokenNode(x: unknown): x is TokenNode; diff --git a/packages/css-parser-algorithms/dist/util/walker-index-generator.d.ts b/packages/css-parser-algorithms/dist/util/walker-index-generator.d.ts deleted file mode 100644 index 2fffc0c69..000000000 --- a/packages/css-parser-algorithms/dist/util/walker-index-generator.d.ts +++ /dev/null @@ -1,11 +0,0 @@ -/** - * Generate a function that finds the next element that should be visited when walking an AST. - * Rules : - * - the previous iteration is used as a reference, so any checks are relative to the start of the current iteration. - * - the next element always appears after the current index. - * - the next element always exists in the list. - * - replacing an element does not cause the replaced element to be visited. - * - removing an element does not cause elements to be skipped. - * - an element added later in the list will be visited. - */ -export declare function walkerIndexGenerator(initialList: Array): (list: Array, child: T, index: number) => number; diff --git a/packages/css-parser-algorithms/package.json b/packages/css-parser-algorithms/package.json index 009c0560d..d70fbe807 100644 --- a/packages/css-parser-algorithms/package.json +++ b/packages/css-parser-algorithms/package.json @@ -27,15 +27,18 @@ "engines": { "node": "^14 || ^16 || >=18" }, + "type": "module", "main": "dist/index.cjs", "module": "dist/index.mjs", - "types": "dist/index.d.ts", "exports": { ".": { - "types": "./dist/index.d.ts", - "import": "./dist/index.mjs", - "require": "./dist/index.cjs", - "default": "./dist/index.mjs" + "import": { + "types": "./dist/index.d.ts", + "default": "./dist/index.mjs" + }, + "require": { + "default": "./dist/index.cjs" + } } }, "files": [ diff --git a/packages/css-parser-algorithms/src/consume/consume-component-block-function.ts b/packages/css-parser-algorithms/src/consume/consume-component-block-function.ts index cf51e4694..968c307c8 100644 --- a/packages/css-parser-algorithms/src/consume/consume-component-block-function.ts +++ b/packages/css-parser-algorithms/src/consume/consume-component-block-function.ts @@ -52,7 +52,7 @@ export function consumeComponentValue(ctx: Context, tokens: Array): { }; } -abstract class ContainerNodeBaseClass { +export abstract class ContainerNodeBaseClass { /** * The contents of the `Function` or `Simple Block`. * This is a list of component values. @@ -286,7 +286,7 @@ export class FunctionNode extends ContainerNodeBaseClass { } // https://www.w3.org/TR/css-syntax-3/#consume-function -export function consumeFunction(ctx: Context, tokens: Array): { advance: number, node: FunctionNode } { +function consumeFunction(ctx: Context, tokens: Array): { advance: number, node: FunctionNode } { const value: Array = []; let i = 1; @@ -429,7 +429,7 @@ export class SimpleBlockNode extends ContainerNodeBaseClass { } /** https://www.w3.org/TR/css-syntax-3/#consume-simple-block */ -export function consumeSimpleBlock(ctx: Context, tokens: Array): { advance: number, node: SimpleBlockNode } { +function consumeSimpleBlock(ctx: Context, tokens: Array): { advance: number, node: SimpleBlockNode } { const endingTokenType = mirrorVariantType(tokens[0][0]); if (!endingTokenType) { throw new Error('Failed to parse, a mirror variant must exist for all block open tokens.'); @@ -520,7 +520,7 @@ export class WhitespaceNode { } } -export function consumeWhitespace(ctx: Context, tokens: Array): { advance: number, node: WhitespaceNode } { +function consumeWhitespace(ctx: Context, tokens: Array): { advance: number, node: WhitespaceNode } { let i = 0; // eslint-disable-next-line no-constant-condition @@ -580,14 +580,14 @@ export class CommentNode { } } -export function consumeComment(ctx: Context, tokens: Array): { advance: number, node: CommentNode } { +function consumeComment(ctx: Context, tokens: Array): { advance: number, node: CommentNode } { return { advance: 1, node: new CommentNode(tokens[0]), }; } -export function consumeAllCommentsAndWhitespace(ctx: Context, tokens: Array): { advance: number, nodes: Array } { +function consumeAllCommentsAndWhitespace(ctx: Context, tokens: Array): { advance: number, nodes: Array } { const nodes: Array = []; let i = 0; diff --git a/packages/css-parser-algorithms/src/index.ts b/packages/css-parser-algorithms/src/index.ts index b636b057e..7ff8c2462 100644 --- a/packages/css-parser-algorithms/src/index.ts +++ b/packages/css-parser-algorithms/src/index.ts @@ -1,4 +1,15 @@ -export * from './consume/consume-component-block-function'; +export type { + ContainerNode, + ComponentValue, +} from './consume/consume-component-block-function'; +export { + ContainerNodeBaseClass, + FunctionNode, + SimpleBlockNode, + WhitespaceNode, + CommentNode, + TokenNode, +} from './consume/consume-component-block-function'; export { parseComponentValue } from './parse/parse-component-value'; export { parseListOfComponentValues } from './parse/parse-list-of-component-values'; export { parseCommaSeparatedListOfComponentValues } from './parse/parse-comma-separated-list-of-component-values'; diff --git a/packages/css-parser-algorithms/src/util/node-ancestry.ts b/packages/css-parser-algorithms/src/util/node-ancestry.ts index 671d6c6f9..2a6d347f9 100644 --- a/packages/css-parser-algorithms/src/util/node-ancestry.ts +++ b/packages/css-parser-algorithms/src/util/node-ancestry.ts @@ -1,8 +1,4 @@ -interface walkable { - walk(cb: (entry: { node: Array | unknown, parent: unknown }, index: number | string) => boolean | void): false | undefined -} - -export function gatherNodeAncestry(node: walkable) { +export function gatherNodeAncestry(node: { walk(cb: (entry: { node: Array | unknown, parent: unknown }, index: number | string) => boolean | void): false | undefined }) { const ancestry: Map = new Map(); node.walk((entry) => { diff --git a/packages/css-parser-algorithms/src/util/source-indices.ts b/packages/css-parser-algorithms/src/util/source-indices.ts index 26e8073ff..6621481a2 100644 --- a/packages/css-parser-algorithms/src/util/source-indices.ts +++ b/packages/css-parser-algorithms/src/util/source-indices.ts @@ -1,13 +1,9 @@ import { CSSToken } from '@csstools/css-tokenizer'; -interface TokenConvertible { - tokens(): Array -} - /** * Returns the start and end index of a node in the CSS source string. */ -export function sourceIndices(x: TokenConvertible | Array): [number, number] { +export function sourceIndices(x: { tokens(): Array } | Array<{ tokens(): Array }>): [number, number] { if (Array.isArray(x)) { const firstNode = x[0]; diff --git a/packages/css-tokenizer/CHANGELOG.md b/packages/css-tokenizer/CHANGELOG.md index 2ccc9748e..1ba9edc80 100644 --- a/packages/css-tokenizer/CHANGELOG.md +++ b/packages/css-tokenizer/CHANGELOG.md @@ -2,7 +2,7 @@ ### Unreleased (patch) -- Small fixes in type definitions +- Fix type definitions ### 2.2.1 diff --git a/packages/css-tokenizer/api-extractor.json b/packages/css-tokenizer/api-extractor.json new file mode 100644 index 000000000..42058be51 --- /dev/null +++ b/packages/css-tokenizer/api-extractor.json @@ -0,0 +1,4 @@ +{ + "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json", + "extends": "../../api-extractor.json" +} diff --git a/packages/css-tokenizer/dist/checks/four-code-points-would-start-cdo.d.ts b/packages/css-tokenizer/dist/checks/four-code-points-would-start-cdo.d.ts deleted file mode 100644 index a9243f63a..000000000 --- a/packages/css-tokenizer/dist/checks/four-code-points-would-start-cdo.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import { CodePointReader } from '../interfaces/code-point-reader'; -export declare function checkIfFourCodePointsWouldStartCDO(reader: CodePointReader): boolean; diff --git a/packages/css-tokenizer/dist/checks/matches-url-ident.d.ts b/packages/css-tokenizer/dist/checks/matches-url-ident.d.ts deleted file mode 100644 index 6af31e4e6..000000000 --- a/packages/css-tokenizer/dist/checks/matches-url-ident.d.ts +++ /dev/null @@ -1 +0,0 @@ -export declare function checkIfCodePointsMatchURLIdent(codePoints: Array): boolean; diff --git a/packages/css-tokenizer/dist/checks/three-code-points-would-start-cdc.d.ts b/packages/css-tokenizer/dist/checks/three-code-points-would-start-cdc.d.ts deleted file mode 100644 index 09bd23237..000000000 --- a/packages/css-tokenizer/dist/checks/three-code-points-would-start-cdc.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import { CodePointReader } from '../interfaces/code-point-reader'; -export declare function checkIfThreeCodePointsWouldStartCDC(reader: CodePointReader): boolean; diff --git a/packages/css-tokenizer/dist/checks/three-code-points-would-start-ident-sequence.d.ts b/packages/css-tokenizer/dist/checks/three-code-points-would-start-ident-sequence.d.ts deleted file mode 100644 index d48323bb9..000000000 --- a/packages/css-tokenizer/dist/checks/three-code-points-would-start-ident-sequence.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -import { CodePointReader } from '../interfaces/code-point-reader'; -import { Context } from '../interfaces/context'; -export declare function checkIfThreeCodePointsWouldStartAnIdentSequence(ctx: Context, reader: CodePointReader): boolean; diff --git a/packages/css-tokenizer/dist/checks/three-code-points-would-start-number.d.ts b/packages/css-tokenizer/dist/checks/three-code-points-would-start-number.d.ts deleted file mode 100644 index 9c428a459..000000000 --- a/packages/css-tokenizer/dist/checks/three-code-points-would-start-number.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import { CodePointReader } from '../interfaces/code-point-reader'; -export declare function checkIfThreeCodePointsWouldStartANumber(reader: CodePointReader): boolean; diff --git a/packages/css-tokenizer/dist/checks/three-code-points-would-start-unicode-range.d.ts b/packages/css-tokenizer/dist/checks/three-code-points-would-start-unicode-range.d.ts deleted file mode 100644 index 46c91076a..000000000 --- a/packages/css-tokenizer/dist/checks/three-code-points-would-start-unicode-range.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import { CodePointReader } from '../interfaces/code-point-reader'; -export declare function checkIfThreeCodePointsWouldStartAUnicodeRange(reader: CodePointReader): boolean; diff --git a/packages/css-tokenizer/dist/checks/two-code-points-are-valid-escape.d.ts b/packages/css-tokenizer/dist/checks/two-code-points-are-valid-escape.d.ts deleted file mode 100644 index 99d954fde..000000000 --- a/packages/css-tokenizer/dist/checks/two-code-points-are-valid-escape.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import { CodePointReader } from '../interfaces/code-point-reader'; -export declare function checkIfTwoCodePointsAreAValidEscape(reader: CodePointReader): boolean; diff --git a/packages/css-tokenizer/dist/checks/two-code-points-start-comment.d.ts b/packages/css-tokenizer/dist/checks/two-code-points-start-comment.d.ts deleted file mode 100644 index 9d9fd4957..000000000 --- a/packages/css-tokenizer/dist/checks/two-code-points-start-comment.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import { CodePointReader } from '../interfaces/code-point-reader'; -export declare function checkIfTwoCodePointsStartAComment(reader: CodePointReader): boolean; diff --git a/packages/css-tokenizer/dist/code-points/code-points.d.ts b/packages/css-tokenizer/dist/code-points/code-points.d.ts deleted file mode 100644 index 3dcc47784..000000000 --- a/packages/css-tokenizer/dist/code-points/code-points.d.ts +++ /dev/null @@ -1,96 +0,0 @@ -/** ' */ -export declare const APOSTROPHE = 39; -/** * */ -export declare const ASTERISK = 42; -/** \b */ -export declare const BACKSPACE = 8; -/** \r */ -export declare const CARRIAGE_RETURN = 13; -/** \t */ -export declare const CHARACTER_TABULATION = 9; -/** : */ -export declare const COLON = 58; -/** , */ -export declare const COMMA = 44; -/** @ */ -export declare const COMMERCIAL_AT = 64; -/** \x7F */ -export declare const DELETE = 127; -/** ! */ -export declare const EXCLAMATION_MARK = 33; -/** \f */ -export declare const FORM_FEED = 12; -/** . */ -export declare const FULL_STOP = 46; -/** > */ -export declare const GREATER_THAN_SIGN = 62; -/** - */ -export declare const HYPHEN_MINUS = 45; -/** \x1F */ -export declare const INFORMATION_SEPARATOR_ONE = 31; -/** E */ -export declare const LATIN_CAPITAL_LETTER_E = 69; -/** e */ -export declare const LATIN_SMALL_LETTER_E = 101; -/** { */ -export declare const LEFT_CURLY_BRACKET = 123; -/** ( */ -export declare const LEFT_PARENTHESIS = 40; -/** [ */ -export declare const LEFT_SQUARE_BRACKET = 91; -/** < */ -export declare const LESS_THAN_SIGN = 60; -/** \n */ -export declare const LINE_FEED = 10; -/** \v */ -export declare const LINE_TABULATION = 11; -/** _ */ -export declare const LOW_LINE = 95; -/** \x10FFFF */ -export declare const MAXIMUM_ALLOWED_CODEPOINT = 1114111; -/** \x00 */ -export declare const NULL = 0; -/** # */ -export declare const NUMBER_SIGN = 35; -/** % */ -export declare const PERCENTAGE_SIGN = 37; -/** + */ -export declare const PLUS_SIGN = 43; -/** " */ -export declare const QUOTATION_MARK = 34; -/** � */ -export declare const REPLACEMENT_CHARACTER = 65533; -/** \ */ -export declare const REVERSE_SOLIDUS = 92; -/** } */ -export declare const RIGHT_CURLY_BRACKET = 125; -/** ) */ -export declare const RIGHT_PARENTHESIS = 41; -/** ] */ -export declare const RIGHT_SQUARE_BRACKET = 93; -/** ; */ -export declare const SEMICOLON = 59; -/** \u0E */ -export declare const SHIFT_OUT = 14; -/** / */ -export declare const SOLIDUS = 47; -/** \u20 */ -export declare const SPACE = 32; -/** u */ -export declare const LATIN_SMALL_LETTER_U = 117; -/** U */ -export declare const LATIN_CAPITAL_LETTER_U = 85; -/** r */ -export declare const LATIN_SMALL_LETTER_R = 114; -/** R */ -export declare const LATIN_CAPITAL_LETTER_R = 82; -/** l */ -export declare const LATIN_SMALL_LETTER_L = 108; -/** L */ -export declare const LATIN_CAPITAL_LETTER_L = 76; -/** ? */ -export declare const QUESTION_MARK = 63; -/** 0 */ -export declare const DIGIT_ZERO = 48; -/** F */ -export declare const LATIN_CAPITAL_LETTER_F = 70; diff --git a/packages/css-tokenizer/dist/code-points/ranges.d.ts b/packages/css-tokenizer/dist/code-points/ranges.d.ts deleted file mode 100644 index a1c442430..000000000 --- a/packages/css-tokenizer/dist/code-points/ranges.d.ts +++ /dev/null @@ -1,8 +0,0 @@ -export declare function isDigitCodePoint(search: number): boolean; -export declare function isHexDigitCodePoint(search: number): boolean; -export declare function isIdentStartCodePoint(search: number): boolean; -export declare function isIdentCodePoint(search: number): boolean; -export declare function isNonPrintableCodePoint(search: number): boolean; -export declare function isNewLine(search: number): boolean; -export declare function isWhitespace(search: number): boolean; -export declare function isSurrogate(search: number): boolean; diff --git a/packages/css-tokenizer/dist/consume/bad-url.d.ts b/packages/css-tokenizer/dist/consume/bad-url.d.ts deleted file mode 100644 index 4b18d0e8d..000000000 --- a/packages/css-tokenizer/dist/consume/bad-url.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -import { CodePointReader } from '../interfaces/code-point-reader'; -import { Context } from '../interfaces/context'; -export declare function consumeBadURL(ctx: Context, reader: CodePointReader): void; diff --git a/packages/css-tokenizer/dist/consume/comment.d.ts b/packages/css-tokenizer/dist/consume/comment.d.ts deleted file mode 100644 index d4ba2211d..000000000 --- a/packages/css-tokenizer/dist/consume/comment.d.ts +++ /dev/null @@ -1,4 +0,0 @@ -import { CodePointReader } from '../interfaces/code-point-reader'; -import { Context } from '../interfaces/context'; -import { TokenComment } from '../interfaces/token'; -export declare function consumeComment(ctx: Context, reader: CodePointReader): TokenComment; diff --git a/packages/css-tokenizer/dist/consume/escaped-code-point.d.ts b/packages/css-tokenizer/dist/consume/escaped-code-point.d.ts deleted file mode 100644 index a6f8dc2e6..000000000 --- a/packages/css-tokenizer/dist/consume/escaped-code-point.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -import { CodePointReader } from '../interfaces/code-point-reader'; -import { Context } from '../interfaces/context'; -export declare function consumeEscapedCodePoint(ctx: Context, reader: CodePointReader): number; diff --git a/packages/css-tokenizer/dist/consume/hash-token.d.ts b/packages/css-tokenizer/dist/consume/hash-token.d.ts deleted file mode 100644 index ac061a84c..000000000 --- a/packages/css-tokenizer/dist/consume/hash-token.d.ts +++ /dev/null @@ -1,4 +0,0 @@ -import { CodePointReader } from '../interfaces/code-point-reader'; -import { Context } from '../interfaces/context'; -import { TokenDelim, TokenHash } from '../interfaces/token'; -export declare function consumeHashToken(ctx: Context, reader: CodePointReader): TokenDelim | TokenHash; diff --git a/packages/css-tokenizer/dist/consume/ident-like-token.d.ts b/packages/css-tokenizer/dist/consume/ident-like-token.d.ts deleted file mode 100644 index 6be737627..000000000 --- a/packages/css-tokenizer/dist/consume/ident-like-token.d.ts +++ /dev/null @@ -1,4 +0,0 @@ -import { CodePointReader } from '../interfaces/code-point-reader'; -import { Context } from '../interfaces/context'; -import { TokenBadURL, TokenFunction, TokenIdent, TokenURL } from '../interfaces/token'; -export declare function consumeIdentLikeToken(ctx: Context, reader: CodePointReader): TokenIdent | TokenFunction | TokenURL | TokenBadURL; diff --git a/packages/css-tokenizer/dist/consume/ident-sequence.d.ts b/packages/css-tokenizer/dist/consume/ident-sequence.d.ts deleted file mode 100644 index 992520e2d..000000000 --- a/packages/css-tokenizer/dist/consume/ident-sequence.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -import { CodePointReader } from '../interfaces/code-point-reader'; -import { Context } from '../interfaces/context'; -export declare function consumeIdentSequence(ctx: Context, reader: CodePointReader): Array; diff --git a/packages/css-tokenizer/dist/consume/number.d.ts b/packages/css-tokenizer/dist/consume/number.d.ts deleted file mode 100644 index 18f1704f3..000000000 --- a/packages/css-tokenizer/dist/consume/number.d.ts +++ /dev/null @@ -1,4 +0,0 @@ -import { CodePointReader } from '../interfaces/code-point-reader'; -import { Context } from '../interfaces/context'; -import { NumberType } from '../interfaces/token'; -export declare function consumeNumber(ctx: Context, reader: CodePointReader): NumberType; diff --git a/packages/css-tokenizer/dist/consume/numeric-token.d.ts b/packages/css-tokenizer/dist/consume/numeric-token.d.ts deleted file mode 100644 index 1217bb0aa..000000000 --- a/packages/css-tokenizer/dist/consume/numeric-token.d.ts +++ /dev/null @@ -1,4 +0,0 @@ -import { CodePointReader } from '../interfaces/code-point-reader'; -import { Context } from '../interfaces/context'; -import { TokenDimension, TokenNumber, TokenPercentage } from '../interfaces/token'; -export declare function consumeNumericToken(ctx: Context, reader: CodePointReader): TokenPercentage | TokenNumber | TokenDimension; diff --git a/packages/css-tokenizer/dist/consume/string-token.d.ts b/packages/css-tokenizer/dist/consume/string-token.d.ts deleted file mode 100644 index 31f6448f7..000000000 --- a/packages/css-tokenizer/dist/consume/string-token.d.ts +++ /dev/null @@ -1,4 +0,0 @@ -import { CodePointReader } from '../interfaces/code-point-reader'; -import { Context } from '../interfaces/context'; -import { TokenBadString, TokenString } from '../interfaces/token'; -export declare function consumeStringToken(ctx: Context, reader: CodePointReader): TokenBadString | TokenString; diff --git a/packages/css-tokenizer/dist/consume/unicode-range-token.d.ts b/packages/css-tokenizer/dist/consume/unicode-range-token.d.ts deleted file mode 100644 index 526bcfe18..000000000 --- a/packages/css-tokenizer/dist/consume/unicode-range-token.d.ts +++ /dev/null @@ -1,4 +0,0 @@ -import { CodePointReader } from '../interfaces/code-point-reader'; -import { Context } from '../interfaces/context'; -import { TokenUnicodeRange } from '../interfaces/token'; -export declare function consumeUnicodeRangeToken(ctx: Context, reader: CodePointReader): TokenUnicodeRange; diff --git a/packages/css-tokenizer/dist/consume/url-token.d.ts b/packages/css-tokenizer/dist/consume/url-token.d.ts deleted file mode 100644 index 9140be704..000000000 --- a/packages/css-tokenizer/dist/consume/url-token.d.ts +++ /dev/null @@ -1,4 +0,0 @@ -import { CodePointReader } from '../interfaces/code-point-reader'; -import { Context } from '../interfaces/context'; -import { TokenBadURL, TokenURL } from '../interfaces/token'; -export declare function consumeUrlToken(ctx: Context, reader: CodePointReader): TokenURL | TokenBadURL; diff --git a/packages/css-tokenizer/dist/consume/whitespace-token.d.ts b/packages/css-tokenizer/dist/consume/whitespace-token.d.ts deleted file mode 100644 index 4584dc9a1..000000000 --- a/packages/css-tokenizer/dist/consume/whitespace-token.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -import { CodePointReader } from '../interfaces/code-point-reader'; -import { TokenWhitespace } from '../interfaces/token'; -export declare function consumeWhiteSpace(reader: CodePointReader): TokenWhitespace; diff --git a/packages/css-tokenizer/dist/index.cjs b/packages/css-tokenizer/dist/index.cjs index 915afc280..499ca5f81 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}}var e,o,n;exports.TokenType=void 0,(e=exports.TokenType||(exports.TokenType={})).Comment="comment",e.AtKeyword="at-keyword-token",e.BadString="bad-string-token",e.BadURL="bad-url-token",e.CDC="CDC-token",e.CDO="CDO-token",e.Colon="colon-token",e.Comma="comma-token",e.Delim="delim-token",e.Dimension="dimension-token",e.EOF="EOF-token",e.Function="function-token",e.Hash="hash-token",e.Ident="ident-token",e.Number="number-token",e.Percentage="percentage-token",e.Semicolon="semicolon-token",e.String="string-token",e.URL="url-token",e.Whitespace="whitespace-token",e.OpenParen="(-token",e.CloseParen=")-token",e.OpenSquare="[-token",e.CloseSquare="]-token",e.OpenCurly="{-token",e.CloseCurly="}-token",e.UnicodeRange="unicode-range-token",exports.NumberType=void 0,(o=exports.NumberType||(exports.NumberType={})).Integer="integer",o.Number="number",function(e){e.Unrestricted="unrestricted",e.ID="id"}(n||(n={}));const r=Object.values(exports.TokenType);const t=39,i=42,s=8,c=13,a=9,u=58,d=44,p=64,P=127,S=33,C=12,T=46,l=62,k=45,f=31,m=69,h=101,E=123,v=40,x=91,y=60,g=10,I=11,O=95,U=1114111,w=0,D=35,R=37,A=43,L=34,N=65533,b=92,q=125,W=41,F=93,H=59,V=14,B=47,z=32,K=117,M=85,$=114,J=82,_=108,j=76,Q=63,G=48,X=70;function checkIfFourCodePointsWouldStartCDO(e){return e.codePointSource[e.cursor]===y&&e.codePointSource[e.cursor+1]===S&&e.codePointSource[e.cursor+2]===k&&e.codePointSource[e.cursor+3]===k}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===O}function isIdentCodePoint(e){return isIdentStartCodePoint(e)||isDigitCodePoint(e)||e===k}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]===b&&!isNewLine(e.codePointSource[e.cursor+1])}function checkIfThreeCodePointsWouldStartAnIdentSequence(e,o){return o.codePointSource[o.cursor]===k?o.codePointSource[o.cursor+1]===k||(!!isIdentStartCodePoint(o.codePointSource[o.cursor+1])||o.codePointSource[o.cursor+1]===b&&!isNewLine(o.codePointSource[o.cursor+2])):!!isIdentStartCodePoint(o.codePointSource[o.cursor])||checkIfTwoCodePointsAreAValidEscape(o)}function checkIfThreeCodePointsWouldStartANumber(e){return e.codePointSource[e.cursor]===A||e.codePointSource[e.cursor]===k?!!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]===B&&e.codePointSource[e.cursor+1]===i}function checkIfThreeCodePointsWouldStartCDC(e){return e.codePointSource[e.cursor]===k&&e.codePointSource[e.cursor+1]===k&&e.codePointSource[e.cursor+2]===l}function consumeComment(e,o){for(o.advanceCodePoint(2);;){const n=o.readCodePoint();if(!1===n){e.onParseError(new ParseError("Unexpected EOF while consuming a comment.",o.representationStart,o.representationEnd,["4.3.2. Consume comments","Unexpected EOF"]));break}if(n===i&&(void 0!==o.codePointSource[o.cursor]&&o.codePointSource[o.cursor]===B)){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"])),N;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?N:(r=t)>=55296&&r<=57343||t>U?N: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 r=n.Unrestricted;checkIfThreeCodePointsWouldStartAnIdentSequence(0,o)&&(r=n.ID);const t=consumeIdentSequence(e,o);return[exports.TokenType.Hash,o.source.slice(o.representationStart,o.representationEnd+1),o.representationStart,o.representationEnd,{value:String.fromCodePoint(...t),type:r}]}return[exports.TokenType.Delim,"#",o.representationStart,o.representationEnd,{value:"#"}]}function consumeNumber(e,o){let n=exports.NumberType.Integer;for(o.codePointSource[o.cursor]!==A&&o.codePointSource[o.cursor]!==k||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]===h||o.codePointSource[o.cursor]===m){if(isDigitCodePoint(o.codePointSource[o.cursor+1]))o.advanceCodePoint(2);else{if(o.codePointSource[o.cursor+1]!==k&&o.codePointSource[o.cursor+1]!==A||!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===k?n="-":e===A&&(n="+")}const r=consumeNumber(0,o),t=parseFloat(o.source.slice(o.representationStart,o.representationEnd+1))||0;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]===R?(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!==b)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]!==K&&e[0]!==M||e[1]!==$&&e[1]!==J||e[2]!==_&&e[2]!==j)}function consumeBadURL(e,o){for(;;){if(void 0===o.codePointSource[o.cursor])return;if(o.codePointSource[o.cursor]===W)return void o.advanceCodePoint();checkIfTwoCodePointsAreAValidEscape(o)?(o.advanceCodePoint(),consumeEscapedCodePoint(e,o)):o.advanceCodePoint()}}function consumeUrlToken(e,o){for(;isWhitespace(o.codePointSource[o.cursor]);)o.advanceCodePoint();let n="";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"])),[exports.TokenType.URL,o.source.slice(o.representationStart,o.representationEnd+1),o.representationStart,o.representationEnd,{value:n}];if(o.codePointSource[o.cursor]===W)return o.advanceCodePoint(),[exports.TokenType.URL,o.source.slice(o.representationStart,o.representationEnd+1),o.representationStart,o.representationEnd,{value:n}];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"])),[exports.TokenType.URL,o.source.slice(o.representationStart,o.representationEnd+1),o.representationStart,o.representationEnd,{value:n}]):o.codePointSource[o.cursor]===W?(o.advanceCodePoint(),[exports.TokenType.URL,o.source.slice(o.representationStart,o.representationEnd+1),o.representationStart,o.representationEnd,{value:n}]):(consumeBadURL(e,o),[exports.TokenType.BadURL,o.source.slice(o.representationStart,o.representationEnd+1),o.representationStart,o.representationEnd,void 0])}if(o.codePointSource[o.cursor]===L||o.codePointSource[o.cursor]===t||o.codePointSource[o.cursor]===v||((r=o.codePointSource[o.cursor])===I||r===P||w<=r&&r<=s||V<=r&&r<=f))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"])),[exports.TokenType.BadURL,o.source.slice(o.representationStart,o.representationEnd+1),o.representationStart,o.representationEnd,void 0];if(o.codePointSource[o.cursor]===b){if(checkIfTwoCodePointsAreAValidEscape(o)){o.advanceCodePoint(),n+=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"])),[exports.TokenType.BadURL,o.source.slice(o.representationStart,o.representationEnd+1),o.representationStart,o.representationEnd,void 0]}n+=String.fromCodePoint(o.codePointSource[o.cursor]),o.advanceCodePoint()}var r}function consumeIdentLikeToken(e,o){const n=consumeIdentSequence(e,o);if(o.codePointSource[o.cursor]!==v)return[exports.TokenType.Ident,o.source.slice(o.representationStart,o.representationEnd+1),o.representationStart,o.representationEnd,{value:String.fromCodePoint(...n)}];if(checkIfCodePointsMatchURLIdent(n)){o.advanceCodePoint();let r=0;for(;;){const e=isWhitespace(o.codePointSource[o.cursor]),i=isWhitespace(o.codePointSource[o.cursor+1]);if(e&&i){r+=1,o.advanceCodePoint(1);continue}const s=e?o.codePointSource[o.cursor+1]:o.codePointSource[o.cursor];if(s===L||s===t)return r>0&&o.unreadCodePoint(r),[exports.TokenType.Function,o.source.slice(o.representationStart,o.representationEnd+1),o.representationStart,o.representationEnd,{value:String.fromCodePoint(...n)}];break}return consumeUrlToken(e,o)}return o.advanceCodePoint(),[exports.TokenType.Function,o.source.slice(o.representationStart,o.representationEnd+1),o.representationStart,o.representationEnd,{value:String.fromCodePoint(...n)}]}function checkIfThreeCodePointsWouldStartAUnicodeRange(e){return!(e.codePointSource[e.cursor]!==K&&e.codePointSource[e.cursor]!==M||e.codePointSource[e.cursor+1]!==A||e.codePointSource[e.cursor+2]!==Q&&!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]===Q;)0===r.length&&r.push(...n),n.push(G),r.push(X),o.advanceCodePoint();if(!r.length&&o.codePointSource[o.cursor]===k&&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,o){const n=e.css.valueOf(),r=e.unicodeRangesAllowed??!1,i=new Reader(n),s={onParseError:(null==o?void 0:o.onParseError)??(()=>{})};return{nextToken:function nextToken(){i.resetRepresentation();const e=i.codePointSource[i.cursor];if(void 0===e)return[exports.TokenType.EOF,"",-1,-1,void 0];if(e===B&&checkIfTwoCodePointsStartAComment(i))return consumeComment(s,i);if(r&&(e===K||e===M)&&checkIfThreeCodePointsWouldStartAUnicodeRange(i))return consumeUnicodeRangeToken(0,i);if(isIdentStartCodePoint(e))return consumeIdentLikeToken(s,i);if(isDigitCodePoint(e))return consumeNumericToken(s,i);switch(e){case d:return i.advanceCodePoint(),[exports.TokenType.Comma,",",i.representationStart,i.representationEnd,void 0];case u:return i.advanceCodePoint(),[exports.TokenType.Colon,":",i.representationStart,i.representationEnd,void 0];case H:return i.advanceCodePoint(),[exports.TokenType.Semicolon,";",i.representationStart,i.representationEnd,void 0];case v:return i.advanceCodePoint(),[exports.TokenType.OpenParen,"(",i.representationStart,i.representationEnd,void 0];case W:return i.advanceCodePoint(),[exports.TokenType.CloseParen,")",i.representationStart,i.representationEnd,void 0];case x:return i.advanceCodePoint(),[exports.TokenType.OpenSquare,"[",i.representationStart,i.representationEnd,void 0];case F:return i.advanceCodePoint(),[exports.TokenType.CloseSquare,"]",i.representationStart,i.representationEnd,void 0];case E:return i.advanceCodePoint(),[exports.TokenType.OpenCurly,"{",i.representationStart,i.representationEnd,void 0];case q:return i.advanceCodePoint(),[exports.TokenType.CloseCurly,"}",i.representationStart,i.representationEnd,void 0];case t:case L:return consumeStringToken(s,i);case D:return consumeHashToken(s,i);case A:case T:return checkIfThreeCodePointsWouldStartANumber(i)?consumeNumericToken(s,i):(i.advanceCodePoint(),[exports.TokenType.Delim,i.source[i.representationStart],i.representationStart,i.representationEnd,{value:i.source[i.representationStart]}]);case g:case c:case C:case a:case z:return consumeWhiteSpace(i);case k:return checkIfThreeCodePointsWouldStartANumber(i)?consumeNumericToken(s,i):checkIfThreeCodePointsWouldStartCDC(i)?(i.advanceCodePoint(3),[exports.TokenType.CDC,"--\x3e",i.representationStart,i.representationEnd,void 0]):checkIfThreeCodePointsWouldStartAnIdentSequence(0,i)?consumeIdentLikeToken(s,i):(i.advanceCodePoint(),[exports.TokenType.Delim,"-",i.representationStart,i.representationEnd,{value:"-"}]);case y:return checkIfFourCodePointsWouldStartCDO(i)?(i.advanceCodePoint(4),[exports.TokenType.CDO,"\x3c!--",i.representationStart,i.representationEnd,void 0]):(i.advanceCodePoint(),[exports.TokenType.Delim,"<",i.representationStart,i.representationEnd,{value:"<"}]);case p:if(i.advanceCodePoint(),checkIfThreeCodePointsWouldStartAnIdentSequence(0,i)){const e=consumeIdentSequence(s,i);return[exports.TokenType.AtKeyword,i.source.slice(i.representationStart,i.representationEnd+1),i.representationStart,i.representationEnd,{value:String.fromCodePoint(...e)}]}return[exports.TokenType.Delim,"@",i.representationStart,i.representationEnd,{value:"@"}];case b:return checkIfTwoCodePointsAreAValidEscape(i)?consumeIdentLikeToken(s,i):(i.advanceCodePoint(),s.onParseError(new ParseError('Invalid escape sequence after "\\"',i.representationStart,i.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,"\\",i.representationStart,i.representationEnd,{value:"\\"}])}return i.advanceCodePoint(),[exports.TokenType.Delim,i.source[i.representationStart],i.representationStart,i.representationEnd,{value:i.source[i.representationStart]}]},endOfFile:function endOfFile(){return void 0===i.codePointSource[i.cursor]}}}exports.ParseError=ParseError,exports.Reader=Reader,exports.cloneTokens=function cloneTokens(e){return"undefined"!=typeof globalThis&&"structuredClone"in globalThis?structuredClone(e):JSON.parse(JSON.stringify(e))},exports.isToken=function isToken(e){return!!Array.isArray(e)&&(!(e.length<4)&&(!!r.includes(e[0])&&("string"==typeof e[1]&&("number"==typeof e[2]&&"number"==typeof e[3]))))},exports.mirrorVariant=function mirrorVariant(e){switch(e[0]){case exports.TokenType.OpenParen:return[exports.TokenType.CloseParen,")",-1,-1,void 0];case exports.TokenType.CloseParen:return[exports.TokenType.OpenParen,"(",-1,-1,void 0];case exports.TokenType.OpenCurly:return[exports.TokenType.CloseCurly,"}",-1,-1,void 0];case exports.TokenType.CloseCurly:return[exports.TokenType.OpenCurly,"{",-1,-1,void 0];case exports.TokenType.OpenSquare:return[exports.TokenType.CloseSquare,"]",-1,-1,void 0];case exports.TokenType.CloseSquare:return[exports.TokenType.OpenSquare,"[",-1,-1,void 0];default:return null}},exports.mirrorVariantType=function mirrorVariantType(e){switch(e){case exports.TokenType.OpenParen:return exports.TokenType.CloseParen;case exports.TokenType.CloseParen:return exports.TokenType.OpenParen;case exports.TokenType.OpenCurly:return exports.TokenType.CloseCurly;case exports.TokenType.CloseCurly:return exports.TokenType.OpenCurly;case exports.TokenType.OpenSquare:return exports.TokenType.CloseSquare;case exports.TokenType.CloseSquare:return exports.TokenType.OpenSquare;default:return null}},exports.mutateIdent=function mutateIdent(e,o){let n="";const r=[];{let e="";for(e of o)r.push(e.codePointAt(0))}let t=0;r[0]===k&&r[1]===k?(n="--",t=2):r[0]===k&&r[1]?(n="-",t=2,isIdentStartCodePoint(r[1])?n+=o[1]:n+=`\\${r[1].toString(16)} `):isIdentStartCodePoint(r[0])?(n=o[0],t=1):(n=`\\${r[0].toString(16)} `,t=1);for(let e=t;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===O}function isIdentCodePoint(e){return isIdentStartCodePoint(e)||isDigitCodePoint(e)||e===k}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]===b&&!isNewLine(e.codePointSource[e.cursor+1])}function checkIfThreeCodePointsWouldStartAnIdentSequence(e,o){return o.codePointSource[o.cursor]===k?o.codePointSource[o.cursor+1]===k||(!!isIdentStartCodePoint(o.codePointSource[o.cursor+1])||o.codePointSource[o.cursor+1]===b&&!isNewLine(o.codePointSource[o.cursor+2])):!!isIdentStartCodePoint(o.codePointSource[o.cursor])||checkIfTwoCodePointsAreAValidEscape(o)}function checkIfThreeCodePointsWouldStartANumber(e){return e.codePointSource[e.cursor]===A||e.codePointSource[e.cursor]===k?!!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]===B&&e.codePointSource[e.cursor+1]===i}function checkIfThreeCodePointsWouldStartCDC(e){return e.codePointSource[e.cursor]===k&&e.codePointSource[e.cursor+1]===k&&e.codePointSource[e.cursor+2]===l}function consumeComment(e,o){for(o.advanceCodePoint(2);;){const n=o.readCodePoint();if(!1===n){e.onParseError(new ParseError("Unexpected EOF while consuming a comment.",o.representationStart,o.representationEnd,["4.3.2. Consume comments","Unexpected EOF"]));break}if(n===i&&(void 0!==o.codePointSource[o.cursor]&&o.codePointSource[o.cursor]===B)){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"])),N;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?N:(r=t)>=55296&&r<=57343||t>U?N: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 r=n.Unrestricted;checkIfThreeCodePointsWouldStartAnIdentSequence(0,o)&&(r=n.ID);const t=consumeIdentSequence(e,o);return[exports.TokenType.Hash,o.source.slice(o.representationStart,o.representationEnd+1),o.representationStart,o.representationEnd,{value:String.fromCodePoint(...t),type:r}]}return[exports.TokenType.Delim,"#",o.representationStart,o.representationEnd,{value:"#"}]}function consumeNumber(e,o){let n=exports.NumberType.Integer;for(o.codePointSource[o.cursor]!==A&&o.codePointSource[o.cursor]!==k||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]===h||o.codePointSource[o.cursor]===m){if(isDigitCodePoint(o.codePointSource[o.cursor+1]))o.advanceCodePoint(2);else{if(o.codePointSource[o.cursor+1]!==k&&o.codePointSource[o.cursor+1]!==A||!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===k?n="-":e===A&&(n="+")}const r=consumeNumber(0,o),t=parseFloat(o.source.slice(o.representationStart,o.representationEnd+1))||0;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]===R?(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!==b)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]!==K&&e[0]!==M||e[1]!==$&&e[1]!==J||e[2]!==_&&e[2]!==j)}function consumeBadURL(e,o){for(;;){if(void 0===o.codePointSource[o.cursor])return;if(o.codePointSource[o.cursor]===W)return void o.advanceCodePoint();checkIfTwoCodePointsAreAValidEscape(o)?(o.advanceCodePoint(),consumeEscapedCodePoint(e,o)):o.advanceCodePoint()}}function consumeUrlToken(e,o){for(;isWhitespace(o.codePointSource[o.cursor]);)o.advanceCodePoint();let n="";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"])),[exports.TokenType.URL,o.source.slice(o.representationStart,o.representationEnd+1),o.representationStart,o.representationEnd,{value:n}];if(o.codePointSource[o.cursor]===W)return o.advanceCodePoint(),[exports.TokenType.URL,o.source.slice(o.representationStart,o.representationEnd+1),o.representationStart,o.representationEnd,{value:n}];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"])),[exports.TokenType.URL,o.source.slice(o.representationStart,o.representationEnd+1),o.representationStart,o.representationEnd,{value:n}]):o.codePointSource[o.cursor]===W?(o.advanceCodePoint(),[exports.TokenType.URL,o.source.slice(o.representationStart,o.representationEnd+1),o.representationStart,o.representationEnd,{value:n}]):(consumeBadURL(e,o),[exports.TokenType.BadURL,o.source.slice(o.representationStart,o.representationEnd+1),o.representationStart,o.representationEnd,void 0])}if(o.codePointSource[o.cursor]===L||o.codePointSource[o.cursor]===t||o.codePointSource[o.cursor]===v||((r=o.codePointSource[o.cursor])===I||r===P||w<=r&&r<=s||V<=r&&r<=f))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"])),[exports.TokenType.BadURL,o.source.slice(o.representationStart,o.representationEnd+1),o.representationStart,o.representationEnd,void 0];if(o.codePointSource[o.cursor]===b){if(checkIfTwoCodePointsAreAValidEscape(o)){o.advanceCodePoint(),n+=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"])),[exports.TokenType.BadURL,o.source.slice(o.representationStart,o.representationEnd+1),o.representationStart,o.representationEnd,void 0]}n+=String.fromCodePoint(o.codePointSource[o.cursor]),o.advanceCodePoint()}var r}function consumeIdentLikeToken(e,o){const n=consumeIdentSequence(e,o);if(o.codePointSource[o.cursor]!==v)return[exports.TokenType.Ident,o.source.slice(o.representationStart,o.representationEnd+1),o.representationStart,o.representationEnd,{value:String.fromCodePoint(...n)}];if(checkIfCodePointsMatchURLIdent(n)){o.advanceCodePoint();let r=0;for(;;){const e=isWhitespace(o.codePointSource[o.cursor]),i=isWhitespace(o.codePointSource[o.cursor+1]);if(e&&i){r+=1,o.advanceCodePoint(1);continue}const s=e?o.codePointSource[o.cursor+1]:o.codePointSource[o.cursor];if(s===L||s===t)return r>0&&o.unreadCodePoint(r),[exports.TokenType.Function,o.source.slice(o.representationStart,o.representationEnd+1),o.representationStart,o.representationEnd,{value:String.fromCodePoint(...n)}];break}return consumeUrlToken(e,o)}return o.advanceCodePoint(),[exports.TokenType.Function,o.source.slice(o.representationStart,o.representationEnd+1),o.representationStart,o.representationEnd,{value:String.fromCodePoint(...n)}]}function checkIfThreeCodePointsWouldStartAUnicodeRange(e){return!(e.codePointSource[e.cursor]!==K&&e.codePointSource[e.cursor]!==M||e.codePointSource[e.cursor+1]!==A||e.codePointSource[e.cursor+2]!==Q&&!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]===Q;)0===r.length&&r.push(...n),n.push(G),r.push(X),o.advanceCodePoint();if(!r.length&&o.codePointSource[o.cursor]===k&&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,o){const n=e.css.valueOf(),r=e.unicodeRangesAllowed??!1,i=new Reader(n),s={onParseError:o?.onParseError??(()=>{})};return{nextToken:function nextToken(){i.resetRepresentation();const e=i.codePointSource[i.cursor];if(void 0===e)return[exports.TokenType.EOF,"",-1,-1,void 0];if(e===B&&checkIfTwoCodePointsStartAComment(i))return consumeComment(s,i);if(r&&(e===K||e===M)&&checkIfThreeCodePointsWouldStartAUnicodeRange(i))return consumeUnicodeRangeToken(0,i);if(isIdentStartCodePoint(e))return consumeIdentLikeToken(s,i);if(isDigitCodePoint(e))return consumeNumericToken(s,i);switch(e){case d:return i.advanceCodePoint(),[exports.TokenType.Comma,",",i.representationStart,i.representationEnd,void 0];case u:return i.advanceCodePoint(),[exports.TokenType.Colon,":",i.representationStart,i.representationEnd,void 0];case H:return i.advanceCodePoint(),[exports.TokenType.Semicolon,";",i.representationStart,i.representationEnd,void 0];case v:return i.advanceCodePoint(),[exports.TokenType.OpenParen,"(",i.representationStart,i.representationEnd,void 0];case W:return i.advanceCodePoint(),[exports.TokenType.CloseParen,")",i.representationStart,i.representationEnd,void 0];case x:return i.advanceCodePoint(),[exports.TokenType.OpenSquare,"[",i.representationStart,i.representationEnd,void 0];case F:return i.advanceCodePoint(),[exports.TokenType.CloseSquare,"]",i.representationStart,i.representationEnd,void 0];case E:return i.advanceCodePoint(),[exports.TokenType.OpenCurly,"{",i.representationStart,i.representationEnd,void 0];case q:return i.advanceCodePoint(),[exports.TokenType.CloseCurly,"}",i.representationStart,i.representationEnd,void 0];case t:case L:return consumeStringToken(s,i);case D:return consumeHashToken(s,i);case A:case T:return checkIfThreeCodePointsWouldStartANumber(i)?consumeNumericToken(s,i):(i.advanceCodePoint(),[exports.TokenType.Delim,i.source[i.representationStart],i.representationStart,i.representationEnd,{value:i.source[i.representationStart]}]);case g:case c:case C:case a:case z:return consumeWhiteSpace(i);case k:return checkIfThreeCodePointsWouldStartANumber(i)?consumeNumericToken(s,i):checkIfThreeCodePointsWouldStartCDC(i)?(i.advanceCodePoint(3),[exports.TokenType.CDC,"--\x3e",i.representationStart,i.representationEnd,void 0]):checkIfThreeCodePointsWouldStartAnIdentSequence(0,i)?consumeIdentLikeToken(s,i):(i.advanceCodePoint(),[exports.TokenType.Delim,"-",i.representationStart,i.representationEnd,{value:"-"}]);case y:return checkIfFourCodePointsWouldStartCDO(i)?(i.advanceCodePoint(4),[exports.TokenType.CDO,"\x3c!--",i.representationStart,i.representationEnd,void 0]):(i.advanceCodePoint(),[exports.TokenType.Delim,"<",i.representationStart,i.representationEnd,{value:"<"}]);case p:if(i.advanceCodePoint(),checkIfThreeCodePointsWouldStartAnIdentSequence(0,i)){const e=consumeIdentSequence(s,i);return[exports.TokenType.AtKeyword,i.source.slice(i.representationStart,i.representationEnd+1),i.representationStart,i.representationEnd,{value:String.fromCodePoint(...e)}]}return[exports.TokenType.Delim,"@",i.representationStart,i.representationEnd,{value:"@"}];case b:return checkIfTwoCodePointsAreAValidEscape(i)?consumeIdentLikeToken(s,i):(i.advanceCodePoint(),s.onParseError(new ParseError('Invalid escape sequence after "\\"',i.representationStart,i.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,"\\",i.representationStart,i.representationEnd,{value:"\\"}])}return i.advanceCodePoint(),[exports.TokenType.Delim,i.source[i.representationStart],i.representationStart,i.representationEnd,{value:i.source[i.representationStart]}]},endOfFile:function endOfFile(){return void 0===i.codePointSource[i.cursor]}}}exports.ParseError=ParseError,exports.Reader=Reader,exports.cloneTokens=function cloneTokens(e){return"undefined"!=typeof globalThis&&"structuredClone"in globalThis?structuredClone(e):JSON.parse(JSON.stringify(e))},exports.isToken=function isToken(e){return!!Array.isArray(e)&&(!(e.length<4)&&(!!r.includes(e[0])&&("string"==typeof e[1]&&("number"==typeof e[2]&&"number"==typeof e[3]))))},exports.mirrorVariant=function mirrorVariant(e){switch(e[0]){case exports.TokenType.OpenParen:return[exports.TokenType.CloseParen,")",-1,-1,void 0];case exports.TokenType.CloseParen:return[exports.TokenType.OpenParen,"(",-1,-1,void 0];case exports.TokenType.OpenCurly:return[exports.TokenType.CloseCurly,"}",-1,-1,void 0];case exports.TokenType.CloseCurly:return[exports.TokenType.OpenCurly,"{",-1,-1,void 0];case exports.TokenType.OpenSquare:return[exports.TokenType.CloseSquare,"]",-1,-1,void 0];case exports.TokenType.CloseSquare:return[exports.TokenType.OpenSquare,"[",-1,-1,void 0];default:return null}},exports.mirrorVariantType=function mirrorVariantType(e){switch(e){case exports.TokenType.OpenParen:return exports.TokenType.CloseParen;case exports.TokenType.CloseParen:return exports.TokenType.OpenParen;case exports.TokenType.OpenCurly:return exports.TokenType.CloseCurly;case exports.TokenType.CloseCurly:return exports.TokenType.OpenCurly;case exports.TokenType.OpenSquare:return exports.TokenType.CloseSquare;case exports.TokenType.CloseSquare:return exports.TokenType.OpenSquare;default:return null}},exports.mutateIdent=function mutateIdent(e,o){let n="";const r=[];{let e="";for(e of o)r.push(e.codePointAt(0))}let t=0;r[0]===k&&r[1]===k?(n="--",t=2):r[0]===k&&r[1]?(n="-",t=2,isIdentStartCodePoint(r[1])?n+=o[1]:n+=`\\${r[1].toString(16)} `):isIdentStartCodePoint(r[0])?(n=o[0],t=1):(n=`\\${r[0].toString(16)} `,t=1);for(let e=t;e): Array; + +export declare type CodePointReader = { + representationStart: number; + representationEnd: number; + cursor: number; + codePointSource: Array; + representationIndices: Array; + source: string; + advanceCodePoint(n?: number): void; + readCodePoint(n?: number): number | false; + unreadCodePoint(n?: number): void; + resetRepresentation(): void; +}; + +export declare type CSSToken = TokenAtKeyword | TokenBadString | TokenBadURL | TokenCDC | TokenCDO | TokenColon | TokenComma | TokenComment | TokenDelim | TokenDimension | TokenEOF | TokenFunction | TokenHash | TokenIdent | TokenNumber | TokenPercentage | TokenSemicolon | TokenString | TokenURL | TokenWhitespace | TokenOpenParen | TokenCloseParen | TokenOpenSquare | TokenCloseSquare | TokenOpenCurly | TokenCloseCurly | TokenUnicodeRange; + +export declare enum HashType { + Unrestricted = "unrestricted", + ID = "id" +} + +export declare function isToken(x: any): x is CSSToken; + +export declare function mirrorVariant(token: CSSToken): CSSToken | null; + +export declare function mirrorVariantType(type: TokenType): TokenType | null; + +export declare function mutateIdent(ident: TokenIdent, newValue: string): void; + +export declare enum NumberType { + Integer = "integer", + Number = "number" +} + +export declare class ParseError extends Error { + /** The index of the start character of the current token. */ + sourceStart: number; + /** The index of the end character of the current token. */ + sourceEnd: number; + /** The parser steps that preceded the error. */ + parserState: Array; + constructor(message: string, sourceStart: number, sourceEnd: number, parserState: Array); +} + +export declare class Reader implements CodePointReader { + cursor: number; + source: string; + codePointSource: Array; + representationIndices: Array; + length: number; + representationStart: number; + representationEnd: number; + constructor(source: string); + advanceCodePoint(n?: number): void; + readCodePoint(n?: number): number | false; + unreadCodePoint(n?: number): void; + resetRepresentation(): void; +} + +export declare function stringify(...tokens: Array): string; + +export declare type Token = [ +/** The type of token */ +T, +/** The token representation */ +string, +/** Start position of representation */ +number, +/** End position of representation */ +number, +/** Extra data */ +U +]; + +export declare type TokenAtKeyword = Token; + +export declare type TokenBadString = Token; + +export declare type TokenBadURL = Token; + +export declare type TokenCDC = Token; + +export declare type TokenCDO = Token; + +export declare type TokenCloseCurly = Token; + +export declare type TokenCloseParen = Token; + +export declare type TokenCloseSquare = Token; + +export declare type TokenColon = Token; + +export declare type TokenComma = Token; + +export declare type TokenComment = Token; + +export declare type TokenDelim = Token; + +export declare type TokenDimension = Token; + +export declare type TokenEOF = Token; + +export declare type TokenFunction = Token; + +export declare type TokenHash = Token; + +export declare type TokenIdent = Token; + +export declare function tokenize(input: { + css: { + valueOf(): string; + }; + unicodeRangesAllowed?: boolean; +}, options?: { + onParseError?: (error: ParseError) => void; +}): Array; + +export declare function tokenizer(input: { + css: { + valueOf(): string; + }; + unicodeRangesAllowed?: boolean; +}, options?: { + onParseError?: (error: ParseError) => void; +}): { + nextToken: () => CSSToken | undefined; + endOfFile: () => boolean; +}; + +export declare type TokenNumber = Token; + +export declare type TokenOpenCurly = Token; + +export declare type TokenOpenParen = Token; + +export declare type TokenOpenSquare = Token; + +export declare type TokenPercentage = Token; + +export declare type TokenSemicolon = Token; + +export declare type TokenString = Token; + +export declare enum TokenType { + /** https://www.w3.org/TR/2021/CRD-css-syntax-3-20211224/#comment-diagram */ + Comment = "comment", + /** https://www.w3.org/TR/2021/CRD-css-syntax-3-20211224/#typedef-at-keyword-token */ + AtKeyword = "at-keyword-token", + /** https://www.w3.org/TR/2021/CRD-css-syntax-3-20211224/#typedef-bad-string-token */ + BadString = "bad-string-token", + /** https://www.w3.org/TR/2021/CRD-css-syntax-3-20211224/#typedef-bad-url-token */ + BadURL = "bad-url-token", + /** https://www.w3.org/TR/2021/CRD-css-syntax-3-20211224/#typedef-cdc-token */ + CDC = "CDC-token", + /** https://www.w3.org/TR/2021/CRD-css-syntax-3-20211224/#typedef-cdo-token */ + CDO = "CDO-token", + /** https://www.w3.org/TR/2021/CRD-css-syntax-3-20211224/#typedef-colon-token */ + Colon = "colon-token", + /** https://www.w3.org/TR/2021/CRD-css-syntax-3-20211224/#typedef-comma-token */ + Comma = "comma-token", + /** https://www.w3.org/TR/2021/CRD-css-syntax-3-20211224/#typedef-delim-token */ + Delim = "delim-token", + /** https://www.w3.org/TR/2021/CRD-css-syntax-3-20211224/#typedef-dimension-token */ + Dimension = "dimension-token", + /** https://www.w3.org/TR/2021/CRD-css-syntax-3-20211224/#typedef-eof-token */ + EOF = "EOF-token", + /** https://www.w3.org/TR/2021/CRD-css-syntax-3-20211224/#typedef-function-token */ + Function = "function-token", + /** https://www.w3.org/TR/2021/CRD-css-syntax-3-20211224/#typedef-hash-token */ + Hash = "hash-token", + /** https://www.w3.org/TR/2021/CRD-css-syntax-3-20211224/#typedef-ident-token */ + Ident = "ident-token", + /** https://www.w3.org/TR/2021/CRD-css-syntax-3-20211224/#typedef-percentage-token */ + Number = "number-token", + /** https://www.w3.org/TR/2021/CRD-css-syntax-3-20211224/#typedef-percentage-token */ + Percentage = "percentage-token", + /** https://www.w3.org/TR/2021/CRD-css-syntax-3-20211224/#typedef-semicolon-token */ + Semicolon = "semicolon-token", + /** https://www.w3.org/TR/2021/CRD-css-syntax-3-20211224/#typedef-string-token */ + String = "string-token", + /** https://www.w3.org/TR/2021/CRD-css-syntax-3-20211224/#typedef-url-token */ + URL = "url-token", + /** https://www.w3.org/TR/2021/CRD-css-syntax-3-20211224/#typedef-whitespace-token */ + Whitespace = "whitespace-token", + /** https://www.w3.org/TR/2021/CRD-css-syntax-3-20211224/#tokendef-open-paren */ + OpenParen = "(-token", + /** https://www.w3.org/TR/2021/CRD-css-syntax-3-20211224/#tokendef-close-paren */ + CloseParen = ")-token", + /** https://www.w3.org/TR/2021/CRD-css-syntax-3-20211224/#tokendef-open-square */ + OpenSquare = "[-token", + /** https://www.w3.org/TR/2021/CRD-css-syntax-3-20211224/#tokendef-close-square */ + CloseSquare = "]-token", + /** https://www.w3.org/TR/2021/CRD-css-syntax-3-20211224/#tokendef-open-curly */ + OpenCurly = "{-token", + /** https://www.w3.org/TR/2021/CRD-css-syntax-3-20211224/#tokendef-close-curly */ + CloseCurly = "}-token", + /** https://drafts.csswg.org/css-syntax/#typedef-unicode-range-token */ + UnicodeRange = "unicode-range-token" +} + +export declare type TokenUnicodeRange = Token; + +export declare type TokenURL = Token; + +export declare type TokenWhitespace = Token; + +export { } diff --git a/packages/css-tokenizer/dist/index.mjs b/packages/css-tokenizer/dist/index.mjs index bfd7b0fb0..855a54205 100644 --- a/packages/css-tokenizer/dist/index.mjs +++ b/packages/css-tokenizer/dist/index.mjs @@ -1 +1 @@ -class ParseError extends Error{sourceStart;sourceEnd;parserState;constructor(e,n,o,r){super(e),this.name="ParseError",this.sourceStart=n,this.sourceEnd=o,this.parserState=r}}class Reader{cursor=0;source="";codePointSource=[];representationIndices=[-1];length=0;representationStart=0;representationEnd=-1;constructor(e){this.source=e;{let n=-1,o="";for(o of e)n+=o.length,this.codePointSource.push(o.codePointAt(0)),this.representationIndices.push(n)}this.length=this.codePointSource.length}advanceCodePoint(e=1){this.cursor=this.cursor+e,this.representationEnd=this.representationIndices[this.cursor]}readCodePoint(e=1){const n=this.codePointSource[this.cursor];return void 0!==n&&(this.cursor=this.cursor+e,this.representationEnd=this.representationIndices[this.cursor],n)}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}}var e,n,o;function mirrorVariantType(n){switch(n){case e.OpenParen:return e.CloseParen;case e.CloseParen:return e.OpenParen;case e.OpenCurly:return e.CloseCurly;case e.CloseCurly:return e.OpenCurly;case e.OpenSquare:return e.CloseSquare;case e.CloseSquare:return e.OpenSquare;default:return null}}function mirrorVariant(n){switch(n[0]){case e.OpenParen:return[e.CloseParen,")",-1,-1,void 0];case e.CloseParen:return[e.OpenParen,"(",-1,-1,void 0];case e.OpenCurly:return[e.CloseCurly,"}",-1,-1,void 0];case e.CloseCurly:return[e.OpenCurly,"{",-1,-1,void 0];case e.OpenSquare:return[e.CloseSquare,"]",-1,-1,void 0];case e.CloseSquare:return[e.OpenSquare,"[",-1,-1,void 0];default:return null}}!function(e){e.Comment="comment",e.AtKeyword="at-keyword-token",e.BadString="bad-string-token",e.BadURL="bad-url-token",e.CDC="CDC-token",e.CDO="CDO-token",e.Colon="colon-token",e.Comma="comma-token",e.Delim="delim-token",e.Dimension="dimension-token",e.EOF="EOF-token",e.Function="function-token",e.Hash="hash-token",e.Ident="ident-token",e.Number="number-token",e.Percentage="percentage-token",e.Semicolon="semicolon-token",e.String="string-token",e.URL="url-token",e.Whitespace="whitespace-token",e.OpenParen="(-token",e.CloseParen=")-token",e.OpenSquare="[-token",e.CloseSquare="]-token",e.OpenCurly="{-token",e.CloseCurly="}-token",e.UnicodeRange="unicode-range-token"}(e||(e={})),function(e){e.Integer="integer",e.Number="number"}(n||(n={})),function(e){e.Unrestricted="unrestricted",e.ID="id"}(o||(o={}));const r=Object.values(e);function isToken(e){return!!Array.isArray(e)&&(!(e.length<4)&&(!!r.includes(e[0])&&("string"==typeof e[1]&&("number"==typeof e[2]&&"number"==typeof e[3]))))}function cloneTokens(e){return"undefined"!=typeof globalThis&&"structuredClone"in globalThis?structuredClone(e):JSON.parse(JSON.stringify(e))}function stringify(...e){let n="";for(let o=0;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===w}function isIdentCodePoint(e){return isIdentStartCodePoint(e)||isDigitCodePoint(e)||e===h}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]===W&&!isNewLine(e.codePointSource[e.cursor+1])}function checkIfThreeCodePointsWouldStartAnIdentSequence(e,n){return n.codePointSource[n.cursor]===h?n.codePointSource[n.cursor+1]===h||(!!isIdentStartCodePoint(n.codePointSource[n.cursor+1])||n.codePointSource[n.cursor+1]===W&&!isNewLine(n.codePointSource[n.cursor+2])):!!isIdentStartCodePoint(n.codePointSource[n.cursor])||checkIfTwoCodePointsAreAValidEscape(n)}function checkIfThreeCodePointsWouldStartANumber(e){return e.codePointSource[e.cursor]===x||e.codePointSource[e.cursor]===h?!!isDigitCodePoint(e.codePointSource[e.cursor+1])||e.codePointSource[e.cursor+1]===l&&isDigitCodePoint(e.codePointSource[e.cursor+2]):e.codePointSource[e.cursor]===l?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]===i}function checkIfThreeCodePointsWouldStartCDC(e){return e.codePointSource[e.cursor]===h&&e.codePointSource[e.cursor+1]===h&&e.codePointSource[e.cursor+2]===f}function consumeComment(n,o){for(o.advanceCodePoint(2);;){const e=o.readCodePoint();if(!1===e){n.onParseError(new ParseError("Unexpected EOF while consuming a comment.",o.representationStart,o.representationEnd,["4.3.2. Consume comments","Unexpected EOF"]));break}if(e===i&&(void 0!==o.codePointSource[o.cursor]&&o.codePointSource[o.cursor]===B)){o.advanceCodePoint();break}}return[e.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"])),q;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?q:(r=t)>=55296&&r<=57343||t>D?q: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(n,r){if(r.advanceCodePoint(),void 0!==r.codePointSource[r.cursor]&&(isIdentCodePoint(r.codePointSource[r.cursor])||checkIfTwoCodePointsAreAValidEscape(r))){let t=o.Unrestricted;checkIfThreeCodePointsWouldStartAnIdentSequence(0,r)&&(t=o.ID);const i=consumeIdentSequence(n,r);return[e.Hash,r.source.slice(r.representationStart,r.representationEnd+1),r.representationStart,r.representationEnd,{value:String.fromCodePoint(...i),type:t}]}return[e.Delim,"#",r.representationStart,r.representationEnd,{value:"#"}]}function consumeNumber(e,o){let r=n.Integer;for(o.codePointSource[o.cursor]!==x&&o.codePointSource[o.cursor]!==h||o.advanceCodePoint();isDigitCodePoint(o.codePointSource[o.cursor]);)o.advanceCodePoint();if(o.codePointSource[o.cursor]===l&&isDigitCodePoint(o.codePointSource[o.cursor+1]))for(o.advanceCodePoint(2),r=n.Number;isDigitCodePoint(o.codePointSource[o.cursor]);)o.advanceCodePoint();if(o.codePointSource[o.cursor]===v||o.codePointSource[o.cursor]===m){if(isDigitCodePoint(o.codePointSource[o.cursor+1]))o.advanceCodePoint(2);else{if(o.codePointSource[o.cursor+1]!==h&&o.codePointSource[o.cursor+1]!==x||!isDigitCodePoint(o.codePointSource[o.cursor+2]))return r;o.advanceCodePoint(3)}for(r=n.Number;isDigitCodePoint(o.codePointSource[o.cursor]);)o.advanceCodePoint()}return r}function consumeNumericToken(n,o){let r;{const e=o.codePointSource[o.cursor];e===h?r="-":e===x&&(r="+")}const t=consumeNumber(0,o),i=parseFloat(o.source.slice(o.representationStart,o.representationEnd+1))||0;if(checkIfThreeCodePointsWouldStartAnIdentSequence(0,o)){const c=consumeIdentSequence(n,o);return[e.Dimension,o.source.slice(o.representationStart,o.representationEnd+1),o.representationStart,o.representationEnd,{value:i,signCharacter:r,type:t,unit:String.fromCodePoint(...c)}]}return o.codePointSource[o.cursor]===L?(o.advanceCodePoint(),[e.Percentage,o.source.slice(o.representationStart,o.representationEnd+1),o.representationStart,o.representationEnd,{value:i,signCharacter:r}]):[e.Number,o.source.slice(o.representationStart,o.representationEnd+1),o.representationStart,o.representationEnd,{value:i,signCharacter:r,type:t}]}function consumeWhiteSpace(n){for(;isWhitespace(n.codePointSource[n.cursor]);)n.advanceCodePoint();return[e.Whitespace,n.source.slice(n.representationStart,n.representationEnd+1),n.representationStart,n.representationEnd,void 0]}function consumeStringToken(n,o){let r="";const t=o.readCodePoint();for(;;){const i=o.readCodePoint();if(!1===i)return n.onParseError(new ParseError("Unexpected EOF while consuming a string token.",o.representationStart,o.representationEnd,["4.3.5. Consume a string token","Unexpected EOF"])),[e.String,o.source.slice(o.representationStart,o.representationEnd+1),o.representationStart,o.representationEnd,{value:r}];if(isNewLine(i))return n.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(),[e.BadString,o.source.slice(o.representationStart,o.representationEnd+1),o.representationStart,o.representationEnd,void 0];if(i===t)return[e.String,o.source.slice(o.representationStart,o.representationEnd+1),o.representationStart,o.representationEnd,{value:r}];if(i!==W)r+=String.fromCodePoint(i);else{if(void 0===o.codePointSource[o.cursor])continue;if(isNewLine(o.codePointSource[o.cursor])){o.advanceCodePoint();continue}r+=String.fromCodePoint(consumeEscapedCodePoint(n,o))}}}function checkIfCodePointsMatchURLIdent(e){return!(3!==e.length||e[0]!==K&&e[0]!==M||e[1]!==$&&e[1]!==J||e[2]!==_&&e[2]!==j)}function consumeBadURL(e,n){for(;;){if(void 0===n.codePointSource[n.cursor])return;if(n.codePointSource[n.cursor]===b)return void n.advanceCodePoint();checkIfTwoCodePointsAreAValidEscape(n)?(n.advanceCodePoint(),consumeEscapedCodePoint(e,n)):n.advanceCodePoint()}}function consumeUrlToken(n,o){for(;isWhitespace(o.codePointSource[o.cursor]);)o.advanceCodePoint();let r="";for(;;){if(void 0===o.codePointSource[o.cursor])return n.onParseError(new ParseError("Unexpected EOF while consuming a url token.",o.representationStart,o.representationEnd,["4.3.6. Consume a url token","Unexpected EOF"])),[e.URL,o.source.slice(o.representationStart,o.representationEnd+1),o.representationStart,o.representationEnd,{value:r}];if(o.codePointSource[o.cursor]===b)return o.advanceCodePoint(),[e.URL,o.source.slice(o.representationStart,o.representationEnd+1),o.representationStart,o.representationEnd,{value:r}];if(isWhitespace(o.codePointSource[o.cursor])){for(o.advanceCodePoint();isWhitespace(o.codePointSource[o.cursor]);)o.advanceCodePoint();return void 0===o.codePointSource[o.cursor]?(n.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"])),[e.URL,o.source.slice(o.representationStart,o.representationEnd+1),o.representationStart,o.representationEnd,{value:r}]):o.codePointSource[o.cursor]===b?(o.advanceCodePoint(),[e.URL,o.source.slice(o.representationStart,o.representationEnd+1),o.representationStart,o.representationEnd,{value:r}]):(consumeBadURL(n,o),[e.BadURL,o.source.slice(o.representationStart,o.representationEnd+1),o.representationStart,o.representationEnd,void 0])}if(o.codePointSource[o.cursor]===y||o.codePointSource[o.cursor]===t||o.codePointSource[o.cursor]===k||((i=o.codePointSource[o.cursor])===U||i===p||A<=i&&i<=c||V<=i&&i<=E))return consumeBadURL(n,o),n.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"])),[e.BadURL,o.source.slice(o.representationStart,o.representationEnd+1),o.representationStart,o.representationEnd,void 0];if(o.codePointSource[o.cursor]===W){if(checkIfTwoCodePointsAreAValidEscape(o)){o.advanceCodePoint(),r+=String.fromCodePoint(consumeEscapedCodePoint(n,o));continue}return consumeBadURL(n,o),n.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"])),[e.BadURL,o.source.slice(o.representationStart,o.representationEnd+1),o.representationStart,o.representationEnd,void 0]}r+=String.fromCodePoint(o.codePointSource[o.cursor]),o.advanceCodePoint()}var i}function consumeIdentLikeToken(n,o){const r=consumeIdentSequence(n,o);if(o.codePointSource[o.cursor]!==k)return[e.Ident,o.source.slice(o.representationStart,o.representationEnd+1),o.representationStart,o.representationEnd,{value:String.fromCodePoint(...r)}];if(checkIfCodePointsMatchURLIdent(r)){o.advanceCodePoint();let i=0;for(;;){const n=isWhitespace(o.codePointSource[o.cursor]),c=isWhitespace(o.codePointSource[o.cursor+1]);if(n&&c){i+=1,o.advanceCodePoint(1);continue}const s=n?o.codePointSource[o.cursor+1]:o.codePointSource[o.cursor];if(s===y||s===t)return i>0&&o.unreadCodePoint(i),[e.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(),[e.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]!==K&&e.codePointSource[e.cursor]!==M||e.codePointSource[e.cursor+1]!==x||e.codePointSource[e.cursor+2]!==Q&&!isHexDigitCodePoint(e.codePointSource[e.cursor+2]))}function consumeUnicodeRangeToken(n,o){o.advanceCodePoint(2);const r=[],t=[];for(;void 0!==o.codePointSource[o.cursor]&&r.length<6&&isHexDigitCodePoint(o.codePointSource[o.cursor]);)r.push(o.codePointSource[o.cursor]),o.advanceCodePoint();for(;void 0!==o.codePointSource[o.cursor]&&r.length<6&&o.codePointSource[o.cursor]===Q;)0===t.length&&t.push(...r),r.push(G),t.push(X),o.advanceCodePoint();if(!t.length&&o.codePointSource[o.cursor]===h&&isHexDigitCodePoint(o.codePointSource[o.cursor+1]))for(o.advanceCodePoint();void 0!==o.codePointSource[o.cursor]&&t.length<6&&isHexDigitCodePoint(o.codePointSource[o.cursor]);)t.push(o.codePointSource[o.cursor]),o.advanceCodePoint();if(!t.length){const n=parseInt(String.fromCodePoint(...r),16);return[e.UnicodeRange,o.source.slice(o.representationStart,o.representationEnd+1),o.representationStart,o.representationEnd,{startOfRange:n,endOfRange:n}]}const i=parseInt(String.fromCodePoint(...r),16),c=parseInt(String.fromCodePoint(...t),16);return[e.UnicodeRange,o.source.slice(o.representationStart,o.representationEnd+1),o.representationStart,o.representationEnd,{startOfRange:i,endOfRange:c}]}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 r=n.css.valueOf(),i=n.unicodeRangesAllowed??!1,c=new Reader(r),p={onParseError:(null==o?void 0:o.onParseError)??(()=>{})};return{nextToken:function nextToken(){c.resetRepresentation();const n=c.codePointSource[c.cursor];if(void 0===n)return[e.EOF,"",-1,-1,void 0];if(n===B&&checkIfTwoCodePointsStartAComment(c))return consumeComment(p,c);if(i&&(n===K||n===M)&&checkIfThreeCodePointsWouldStartAUnicodeRange(c))return consumeUnicodeRangeToken(0,c);if(isIdentStartCodePoint(n))return consumeIdentLikeToken(p,c);if(isDigitCodePoint(n))return consumeNumericToken(p,c);switch(n){case d:return c.advanceCodePoint(),[e.Comma,",",c.representationStart,c.representationEnd,void 0];case u:return c.advanceCodePoint(),[e.Colon,":",c.representationStart,c.representationEnd,void 0];case H:return c.advanceCodePoint(),[e.Semicolon,";",c.representationStart,c.representationEnd,void 0];case k:return c.advanceCodePoint(),[e.OpenParen,"(",c.representationStart,c.representationEnd,void 0];case b:return c.advanceCodePoint(),[e.CloseParen,")",c.representationStart,c.representationEnd,void 0];case I:return c.advanceCodePoint(),[e.OpenSquare,"[",c.representationStart,c.representationEnd,void 0];case F:return c.advanceCodePoint(),[e.CloseSquare,"]",c.representationStart,c.representationEnd,void 0];case g:return c.advanceCodePoint(),[e.OpenCurly,"{",c.representationStart,c.representationEnd,void 0];case N:return c.advanceCodePoint(),[e.CloseCurly,"}",c.representationStart,c.representationEnd,void 0];case t:case y:return consumeStringToken(p,c);case R:return consumeHashToken(p,c);case x:case l:return checkIfThreeCodePointsWouldStartANumber(c)?consumeNumericToken(p,c):(c.advanceCodePoint(),[e.Delim,c.source[c.representationStart],c.representationStart,c.representationEnd,{value:c.source[c.representationStart]}]);case O:case s:case C:case a:case z:return consumeWhiteSpace(c);case h:return checkIfThreeCodePointsWouldStartANumber(c)?consumeNumericToken(p,c):checkIfThreeCodePointsWouldStartCDC(c)?(c.advanceCodePoint(3),[e.CDC,"--\x3e",c.representationStart,c.representationEnd,void 0]):checkIfThreeCodePointsWouldStartAnIdentSequence(0,c)?consumeIdentLikeToken(p,c):(c.advanceCodePoint(),[e.Delim,"-",c.representationStart,c.representationEnd,{value:"-"}]);case T:return checkIfFourCodePointsWouldStartCDO(c)?(c.advanceCodePoint(4),[e.CDO,"\x3c!--",c.representationStart,c.representationEnd,void 0]):(c.advanceCodePoint(),[e.Delim,"<",c.representationStart,c.representationEnd,{value:"<"}]);case P:if(c.advanceCodePoint(),checkIfThreeCodePointsWouldStartAnIdentSequence(0,c)){const n=consumeIdentSequence(p,c);return[e.AtKeyword,c.source.slice(c.representationStart,c.representationEnd+1),c.representationStart,c.representationEnd,{value:String.fromCodePoint(...n)}]}return[e.Delim,"@",c.representationStart,c.representationEnd,{value:"@"}];case W:return checkIfTwoCodePointsAreAValidEscape(c)?consumeIdentLikeToken(p,c):(c.advanceCodePoint(),p.onParseError(new ParseError('Invalid escape sequence after "\\"',c.representationStart,c.representationEnd,["4.3.1. Consume a token","U+005C REVERSE SOLIDUS (\\)","The input stream does not start with a valid escape sequence"])),[e.Delim,"\\",c.representationStart,c.representationEnd,{value:"\\"}])}return c.advanceCodePoint(),[e.Delim,c.source[c.representationStart],c.representationStart,c.representationEnd,{value:c.source[c.representationStart]}]},endOfFile:function endOfFile(){return void 0===c.codePointSource[c.cursor]}}}function mutateIdent(e,n){let o="";const r=[];{let e="";for(e of n)r.push(e.codePointAt(0))}let t=0;r[0]===h&&r[1]===h?(o="--",t=2):r[0]===h&&r[1]?(o="-",t=2,isIdentStartCodePoint(r[1])?o+=n[1]:o+=`\\${r[1].toString(16)} `):isIdentStartCodePoint(r[0])?(o=n[0],t=1):(o=`\\${r[0].toString(16)} `,t=1);for(let e=t;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===w}function isIdentCodePoint(e){return isIdentStartCodePoint(e)||isDigitCodePoint(e)||e===h}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]===W&&!isNewLine(e.codePointSource[e.cursor+1])}function checkIfThreeCodePointsWouldStartAnIdentSequence(e,n){return n.codePointSource[n.cursor]===h?n.codePointSource[n.cursor+1]===h||(!!isIdentStartCodePoint(n.codePointSource[n.cursor+1])||n.codePointSource[n.cursor+1]===W&&!isNewLine(n.codePointSource[n.cursor+2])):!!isIdentStartCodePoint(n.codePointSource[n.cursor])||checkIfTwoCodePointsAreAValidEscape(n)}function checkIfThreeCodePointsWouldStartANumber(e){return e.codePointSource[e.cursor]===x||e.codePointSource[e.cursor]===h?!!isDigitCodePoint(e.codePointSource[e.cursor+1])||e.codePointSource[e.cursor+1]===l&&isDigitCodePoint(e.codePointSource[e.cursor+2]):e.codePointSource[e.cursor]===l?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]===i}function checkIfThreeCodePointsWouldStartCDC(e){return e.codePointSource[e.cursor]===h&&e.codePointSource[e.cursor+1]===h&&e.codePointSource[e.cursor+2]===f}function consumeComment(n,o){for(o.advanceCodePoint(2);;){const e=o.readCodePoint();if(!1===e){n.onParseError(new ParseError("Unexpected EOF while consuming a comment.",o.representationStart,o.representationEnd,["4.3.2. Consume comments","Unexpected EOF"]));break}if(e===i&&(void 0!==o.codePointSource[o.cursor]&&o.codePointSource[o.cursor]===B)){o.advanceCodePoint();break}}return[e.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"])),q;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?q:(r=t)>=55296&&r<=57343||t>D?q: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(n,r){if(r.advanceCodePoint(),void 0!==r.codePointSource[r.cursor]&&(isIdentCodePoint(r.codePointSource[r.cursor])||checkIfTwoCodePointsAreAValidEscape(r))){let t=o.Unrestricted;checkIfThreeCodePointsWouldStartAnIdentSequence(0,r)&&(t=o.ID);const i=consumeIdentSequence(n,r);return[e.Hash,r.source.slice(r.representationStart,r.representationEnd+1),r.representationStart,r.representationEnd,{value:String.fromCodePoint(...i),type:t}]}return[e.Delim,"#",r.representationStart,r.representationEnd,{value:"#"}]}function consumeNumber(e,o){let r=n.Integer;for(o.codePointSource[o.cursor]!==x&&o.codePointSource[o.cursor]!==h||o.advanceCodePoint();isDigitCodePoint(o.codePointSource[o.cursor]);)o.advanceCodePoint();if(o.codePointSource[o.cursor]===l&&isDigitCodePoint(o.codePointSource[o.cursor+1]))for(o.advanceCodePoint(2),r=n.Number;isDigitCodePoint(o.codePointSource[o.cursor]);)o.advanceCodePoint();if(o.codePointSource[o.cursor]===v||o.codePointSource[o.cursor]===m){if(isDigitCodePoint(o.codePointSource[o.cursor+1]))o.advanceCodePoint(2);else{if(o.codePointSource[o.cursor+1]!==h&&o.codePointSource[o.cursor+1]!==x||!isDigitCodePoint(o.codePointSource[o.cursor+2]))return r;o.advanceCodePoint(3)}for(r=n.Number;isDigitCodePoint(o.codePointSource[o.cursor]);)o.advanceCodePoint()}return r}function consumeNumericToken(n,o){let r;{const e=o.codePointSource[o.cursor];e===h?r="-":e===x&&(r="+")}const t=consumeNumber(0,o),i=parseFloat(o.source.slice(o.representationStart,o.representationEnd+1))||0;if(checkIfThreeCodePointsWouldStartAnIdentSequence(0,o)){const c=consumeIdentSequence(n,o);return[e.Dimension,o.source.slice(o.representationStart,o.representationEnd+1),o.representationStart,o.representationEnd,{value:i,signCharacter:r,type:t,unit:String.fromCodePoint(...c)}]}return o.codePointSource[o.cursor]===L?(o.advanceCodePoint(),[e.Percentage,o.source.slice(o.representationStart,o.representationEnd+1),o.representationStart,o.representationEnd,{value:i,signCharacter:r}]):[e.Number,o.source.slice(o.representationStart,o.representationEnd+1),o.representationStart,o.representationEnd,{value:i,signCharacter:r,type:t}]}function consumeWhiteSpace(n){for(;isWhitespace(n.codePointSource[n.cursor]);)n.advanceCodePoint();return[e.Whitespace,n.source.slice(n.representationStart,n.representationEnd+1),n.representationStart,n.representationEnd,void 0]}function consumeStringToken(n,o){let r="";const t=o.readCodePoint();for(;;){const i=o.readCodePoint();if(!1===i)return n.onParseError(new ParseError("Unexpected EOF while consuming a string token.",o.representationStart,o.representationEnd,["4.3.5. Consume a string token","Unexpected EOF"])),[e.String,o.source.slice(o.representationStart,o.representationEnd+1),o.representationStart,o.representationEnd,{value:r}];if(isNewLine(i))return n.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(),[e.BadString,o.source.slice(o.representationStart,o.representationEnd+1),o.representationStart,o.representationEnd,void 0];if(i===t)return[e.String,o.source.slice(o.representationStart,o.representationEnd+1),o.representationStart,o.representationEnd,{value:r}];if(i!==W)r+=String.fromCodePoint(i);else{if(void 0===o.codePointSource[o.cursor])continue;if(isNewLine(o.codePointSource[o.cursor])){o.advanceCodePoint();continue}r+=String.fromCodePoint(consumeEscapedCodePoint(n,o))}}}function checkIfCodePointsMatchURLIdent(e){return!(3!==e.length||e[0]!==K&&e[0]!==M||e[1]!==$&&e[1]!==J||e[2]!==_&&e[2]!==j)}function consumeBadURL(e,n){for(;;){if(void 0===n.codePointSource[n.cursor])return;if(n.codePointSource[n.cursor]===b)return void n.advanceCodePoint();checkIfTwoCodePointsAreAValidEscape(n)?(n.advanceCodePoint(),consumeEscapedCodePoint(e,n)):n.advanceCodePoint()}}function consumeUrlToken(n,o){for(;isWhitespace(o.codePointSource[o.cursor]);)o.advanceCodePoint();let r="";for(;;){if(void 0===o.codePointSource[o.cursor])return n.onParseError(new ParseError("Unexpected EOF while consuming a url token.",o.representationStart,o.representationEnd,["4.3.6. Consume a url token","Unexpected EOF"])),[e.URL,o.source.slice(o.representationStart,o.representationEnd+1),o.representationStart,o.representationEnd,{value:r}];if(o.codePointSource[o.cursor]===b)return o.advanceCodePoint(),[e.URL,o.source.slice(o.representationStart,o.representationEnd+1),o.representationStart,o.representationEnd,{value:r}];if(isWhitespace(o.codePointSource[o.cursor])){for(o.advanceCodePoint();isWhitespace(o.codePointSource[o.cursor]);)o.advanceCodePoint();return void 0===o.codePointSource[o.cursor]?(n.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"])),[e.URL,o.source.slice(o.representationStart,o.representationEnd+1),o.representationStart,o.representationEnd,{value:r}]):o.codePointSource[o.cursor]===b?(o.advanceCodePoint(),[e.URL,o.source.slice(o.representationStart,o.representationEnd+1),o.representationStart,o.representationEnd,{value:r}]):(consumeBadURL(n,o),[e.BadURL,o.source.slice(o.representationStart,o.representationEnd+1),o.representationStart,o.representationEnd,void 0])}if(o.codePointSource[o.cursor]===y||o.codePointSource[o.cursor]===t||o.codePointSource[o.cursor]===k||((i=o.codePointSource[o.cursor])===U||i===p||A<=i&&i<=c||V<=i&&i<=E))return consumeBadURL(n,o),n.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"])),[e.BadURL,o.source.slice(o.representationStart,o.representationEnd+1),o.representationStart,o.representationEnd,void 0];if(o.codePointSource[o.cursor]===W){if(checkIfTwoCodePointsAreAValidEscape(o)){o.advanceCodePoint(),r+=String.fromCodePoint(consumeEscapedCodePoint(n,o));continue}return consumeBadURL(n,o),n.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"])),[e.BadURL,o.source.slice(o.representationStart,o.representationEnd+1),o.representationStart,o.representationEnd,void 0]}r+=String.fromCodePoint(o.codePointSource[o.cursor]),o.advanceCodePoint()}var i}function consumeIdentLikeToken(n,o){const r=consumeIdentSequence(n,o);if(o.codePointSource[o.cursor]!==k)return[e.Ident,o.source.slice(o.representationStart,o.representationEnd+1),o.representationStart,o.representationEnd,{value:String.fromCodePoint(...r)}];if(checkIfCodePointsMatchURLIdent(r)){o.advanceCodePoint();let i=0;for(;;){const n=isWhitespace(o.codePointSource[o.cursor]),c=isWhitespace(o.codePointSource[o.cursor+1]);if(n&&c){i+=1,o.advanceCodePoint(1);continue}const s=n?o.codePointSource[o.cursor+1]:o.codePointSource[o.cursor];if(s===y||s===t)return i>0&&o.unreadCodePoint(i),[e.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(),[e.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]!==K&&e.codePointSource[e.cursor]!==M||e.codePointSource[e.cursor+1]!==x||e.codePointSource[e.cursor+2]!==Q&&!isHexDigitCodePoint(e.codePointSource[e.cursor+2]))}function consumeUnicodeRangeToken(n,o){o.advanceCodePoint(2);const r=[],t=[];for(;void 0!==o.codePointSource[o.cursor]&&r.length<6&&isHexDigitCodePoint(o.codePointSource[o.cursor]);)r.push(o.codePointSource[o.cursor]),o.advanceCodePoint();for(;void 0!==o.codePointSource[o.cursor]&&r.length<6&&o.codePointSource[o.cursor]===Q;)0===t.length&&t.push(...r),r.push(G),t.push(X),o.advanceCodePoint();if(!t.length&&o.codePointSource[o.cursor]===h&&isHexDigitCodePoint(o.codePointSource[o.cursor+1]))for(o.advanceCodePoint();void 0!==o.codePointSource[o.cursor]&&t.length<6&&isHexDigitCodePoint(o.codePointSource[o.cursor]);)t.push(o.codePointSource[o.cursor]),o.advanceCodePoint();if(!t.length){const n=parseInt(String.fromCodePoint(...r),16);return[e.UnicodeRange,o.source.slice(o.representationStart,o.representationEnd+1),o.representationStart,o.representationEnd,{startOfRange:n,endOfRange:n}]}const i=parseInt(String.fromCodePoint(...r),16),c=parseInt(String.fromCodePoint(...t),16);return[e.UnicodeRange,o.source.slice(o.representationStart,o.representationEnd+1),o.representationStart,o.representationEnd,{startOfRange:i,endOfRange:c}]}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 r=n.css.valueOf(),i=n.unicodeRangesAllowed??!1,c=new Reader(r),p={onParseError:o?.onParseError??(()=>{})};return{nextToken:function nextToken(){c.resetRepresentation();const n=c.codePointSource[c.cursor];if(void 0===n)return[e.EOF,"",-1,-1,void 0];if(n===B&&checkIfTwoCodePointsStartAComment(c))return consumeComment(p,c);if(i&&(n===K||n===M)&&checkIfThreeCodePointsWouldStartAUnicodeRange(c))return consumeUnicodeRangeToken(0,c);if(isIdentStartCodePoint(n))return consumeIdentLikeToken(p,c);if(isDigitCodePoint(n))return consumeNumericToken(p,c);switch(n){case d:return c.advanceCodePoint(),[e.Comma,",",c.representationStart,c.representationEnd,void 0];case u:return c.advanceCodePoint(),[e.Colon,":",c.representationStart,c.representationEnd,void 0];case H:return c.advanceCodePoint(),[e.Semicolon,";",c.representationStart,c.representationEnd,void 0];case k:return c.advanceCodePoint(),[e.OpenParen,"(",c.representationStart,c.representationEnd,void 0];case b:return c.advanceCodePoint(),[e.CloseParen,")",c.representationStart,c.representationEnd,void 0];case I:return c.advanceCodePoint(),[e.OpenSquare,"[",c.representationStart,c.representationEnd,void 0];case F:return c.advanceCodePoint(),[e.CloseSquare,"]",c.representationStart,c.representationEnd,void 0];case g:return c.advanceCodePoint(),[e.OpenCurly,"{",c.representationStart,c.representationEnd,void 0];case N:return c.advanceCodePoint(),[e.CloseCurly,"}",c.representationStart,c.representationEnd,void 0];case t:case y:return consumeStringToken(p,c);case R:return consumeHashToken(p,c);case x:case l:return checkIfThreeCodePointsWouldStartANumber(c)?consumeNumericToken(p,c):(c.advanceCodePoint(),[e.Delim,c.source[c.representationStart],c.representationStart,c.representationEnd,{value:c.source[c.representationStart]}]);case O:case s:case C:case a:case z:return consumeWhiteSpace(c);case h:return checkIfThreeCodePointsWouldStartANumber(c)?consumeNumericToken(p,c):checkIfThreeCodePointsWouldStartCDC(c)?(c.advanceCodePoint(3),[e.CDC,"--\x3e",c.representationStart,c.representationEnd,void 0]):checkIfThreeCodePointsWouldStartAnIdentSequence(0,c)?consumeIdentLikeToken(p,c):(c.advanceCodePoint(),[e.Delim,"-",c.representationStart,c.representationEnd,{value:"-"}]);case T:return checkIfFourCodePointsWouldStartCDO(c)?(c.advanceCodePoint(4),[e.CDO,"\x3c!--",c.representationStart,c.representationEnd,void 0]):(c.advanceCodePoint(),[e.Delim,"<",c.representationStart,c.representationEnd,{value:"<"}]);case P:if(c.advanceCodePoint(),checkIfThreeCodePointsWouldStartAnIdentSequence(0,c)){const n=consumeIdentSequence(p,c);return[e.AtKeyword,c.source.slice(c.representationStart,c.representationEnd+1),c.representationStart,c.representationEnd,{value:String.fromCodePoint(...n)}]}return[e.Delim,"@",c.representationStart,c.representationEnd,{value:"@"}];case W:return checkIfTwoCodePointsAreAValidEscape(c)?consumeIdentLikeToken(p,c):(c.advanceCodePoint(),p.onParseError(new ParseError('Invalid escape sequence after "\\"',c.representationStart,c.representationEnd,["4.3.1. Consume a token","U+005C REVERSE SOLIDUS (\\)","The input stream does not start with a valid escape sequence"])),[e.Delim,"\\",c.representationStart,c.representationEnd,{value:"\\"}])}return c.advanceCodePoint(),[e.Delim,c.source[c.representationStart],c.representationStart,c.representationEnd,{value:c.source[c.representationStart]}]},endOfFile:function endOfFile(){return void 0===c.codePointSource[c.cursor]}}}function mutateIdent(e,n){let o="";const r=[];{let e="";for(e of n)r.push(e.codePointAt(0))}let t=0;r[0]===h&&r[1]===h?(o="--",t=2):r[0]===h&&r[1]?(o="-",t=2,isIdentStartCodePoint(r[1])?o+=n[1]:o+=`\\${r[1].toString(16)} `):isIdentStartCodePoint(r[0])?(o=n[0],t=1):(o=`\\${r[0].toString(16)} `,t=1);for(let e=t;e; - representationIndices: Array; - source: string; - advanceCodePoint(n?: number): void; - readCodePoint(n?: number): number | false; - unreadCodePoint(n?: number): void; - resetRepresentation(): void; -}; diff --git a/packages/css-tokenizer/dist/interfaces/context.d.ts b/packages/css-tokenizer/dist/interfaces/context.d.ts deleted file mode 100644 index 339bfe4e4..000000000 --- a/packages/css-tokenizer/dist/interfaces/context.d.ts +++ /dev/null @@ -1,4 +0,0 @@ -import { ParseError } from './error'; -export type Context = { - onParseError: (error: ParseError) => void; -}; diff --git a/packages/css-tokenizer/dist/interfaces/error.d.ts b/packages/css-tokenizer/dist/interfaces/error.d.ts deleted file mode 100644 index dc47e1d69..000000000 --- a/packages/css-tokenizer/dist/interfaces/error.d.ts +++ /dev/null @@ -1,9 +0,0 @@ -export declare class ParseError extends Error { - /** The index of the start character of the current token. */ - sourceStart: number; - /** The index of the end character of the current token. */ - sourceEnd: number; - /** The parser steps that preceded the error. */ - parserState: Array; - constructor(message: string, sourceStart: number, sourceEnd: number, parserState: Array); -} diff --git a/packages/css-tokenizer/dist/interfaces/token.d.ts b/packages/css-tokenizer/dist/interfaces/token.d.ts deleted file mode 100644 index c4f2f4e3e..000000000 --- a/packages/css-tokenizer/dist/interfaces/token.d.ts +++ /dev/null @@ -1,137 +0,0 @@ -export declare enum TokenType { - /** https://www.w3.org/TR/2021/CRD-css-syntax-3-20211224/#comment-diagram */ - Comment = "comment", - /** https://www.w3.org/TR/2021/CRD-css-syntax-3-20211224/#typedef-at-keyword-token */ - AtKeyword = "at-keyword-token", - /** https://www.w3.org/TR/2021/CRD-css-syntax-3-20211224/#typedef-bad-string-token */ - BadString = "bad-string-token", - /** https://www.w3.org/TR/2021/CRD-css-syntax-3-20211224/#typedef-bad-url-token */ - BadURL = "bad-url-token", - /** https://www.w3.org/TR/2021/CRD-css-syntax-3-20211224/#typedef-cdc-token */ - CDC = "CDC-token", - /** https://www.w3.org/TR/2021/CRD-css-syntax-3-20211224/#typedef-cdo-token */ - CDO = "CDO-token", - /** https://www.w3.org/TR/2021/CRD-css-syntax-3-20211224/#typedef-colon-token */ - Colon = "colon-token", - /** https://www.w3.org/TR/2021/CRD-css-syntax-3-20211224/#typedef-comma-token */ - Comma = "comma-token", - /** https://www.w3.org/TR/2021/CRD-css-syntax-3-20211224/#typedef-delim-token */ - Delim = "delim-token", - /** https://www.w3.org/TR/2021/CRD-css-syntax-3-20211224/#typedef-dimension-token */ - Dimension = "dimension-token", - /** https://www.w3.org/TR/2021/CRD-css-syntax-3-20211224/#typedef-eof-token */ - EOF = "EOF-token", - /** https://www.w3.org/TR/2021/CRD-css-syntax-3-20211224/#typedef-function-token */ - Function = "function-token", - /** https://www.w3.org/TR/2021/CRD-css-syntax-3-20211224/#typedef-hash-token */ - Hash = "hash-token", - /** https://www.w3.org/TR/2021/CRD-css-syntax-3-20211224/#typedef-ident-token */ - Ident = "ident-token", - /** https://www.w3.org/TR/2021/CRD-css-syntax-3-20211224/#typedef-percentage-token */ - Number = "number-token", - /** https://www.w3.org/TR/2021/CRD-css-syntax-3-20211224/#typedef-percentage-token */ - Percentage = "percentage-token", - /** https://www.w3.org/TR/2021/CRD-css-syntax-3-20211224/#typedef-semicolon-token */ - Semicolon = "semicolon-token", - /** https://www.w3.org/TR/2021/CRD-css-syntax-3-20211224/#typedef-string-token */ - String = "string-token", - /** https://www.w3.org/TR/2021/CRD-css-syntax-3-20211224/#typedef-url-token */ - URL = "url-token", - /** https://www.w3.org/TR/2021/CRD-css-syntax-3-20211224/#typedef-whitespace-token */ - Whitespace = "whitespace-token", - /** https://www.w3.org/TR/2021/CRD-css-syntax-3-20211224/#tokendef-open-paren */ - OpenParen = "(-token", - /** https://www.w3.org/TR/2021/CRD-css-syntax-3-20211224/#tokendef-close-paren */ - CloseParen = ")-token", - /** https://www.w3.org/TR/2021/CRD-css-syntax-3-20211224/#tokendef-open-square */ - OpenSquare = "[-token", - /** https://www.w3.org/TR/2021/CRD-css-syntax-3-20211224/#tokendef-close-square */ - CloseSquare = "]-token", - /** https://www.w3.org/TR/2021/CRD-css-syntax-3-20211224/#tokendef-open-curly */ - OpenCurly = "{-token", - /** https://www.w3.org/TR/2021/CRD-css-syntax-3-20211224/#tokendef-close-curly */ - CloseCurly = "}-token", - /** https://drafts.csswg.org/css-syntax/#typedef-unicode-range-token */ - UnicodeRange = "unicode-range-token" -} -export declare enum NumberType { - Integer = "integer", - Number = "number" -} -export declare enum HashType { - Unrestricted = "unrestricted", - ID = "id" -} -export type TokenAtKeyword = Token; -export type TokenBadString = Token; -export type TokenBadURL = Token; -export type TokenCDC = Token; -export type TokenCDO = Token; -export type TokenColon = Token; -export type TokenComma = Token; -export type TokenComment = Token; -export type TokenDelim = Token; -export type TokenDimension = Token; -export type TokenEOF = Token; -export type TokenFunction = Token; -export type TokenHash = Token; -export type TokenIdent = Token; -export type TokenNumber = Token; -export type TokenPercentage = Token; -export type TokenSemicolon = Token; -export type TokenString = Token; -export type TokenURL = Token; -export type TokenWhitespace = Token; -export type TokenOpenParen = Token; -export type TokenCloseParen = Token; -export type TokenOpenSquare = Token; -export type TokenCloseSquare = Token; -export type TokenOpenCurly = Token; -export type TokenCloseCurly = Token; -export type TokenUnicodeRange = Token; -export type CSSToken = TokenAtKeyword | TokenBadString | TokenBadURL | TokenCDC | TokenCDO | TokenColon | TokenComma | TokenComment | TokenDelim | TokenDimension | TokenEOF | TokenFunction | TokenHash | TokenIdent | TokenNumber | TokenPercentage | TokenSemicolon | TokenString | TokenURL | TokenWhitespace | TokenOpenParen | TokenCloseParen | TokenOpenSquare | TokenCloseSquare | TokenOpenCurly | TokenCloseCurly | TokenUnicodeRange; -export type Token = [ - /** The type of token */ - T, - /** The token representation */ - string, - /** Start position of representation */ - number, - /** End position of representation */ - number, - /** Extra data */ - U -]; -export declare function mirrorVariantType(type: TokenType): TokenType | null; -export declare function mirrorVariant(token: CSSToken): CSSToken | null; -export declare function isToken(x: any): x is CSSToken; diff --git a/packages/css-tokenizer/dist/reader.d.ts b/packages/css-tokenizer/dist/reader.d.ts deleted file mode 100644 index fc798c58d..000000000 --- a/packages/css-tokenizer/dist/reader.d.ts +++ /dev/null @@ -1,15 +0,0 @@ -import { CodePointReader } from './interfaces/code-point-reader'; -export declare class Reader implements CodePointReader { - cursor: number; - source: string; - codePointSource: Array; - representationIndices: Array; - length: number; - representationStart: number; - representationEnd: number; - constructor(source: string); - advanceCodePoint(n?: number): void; - readCodePoint(n?: number): number | false; - unreadCodePoint(n?: number): void; - resetRepresentation(): void; -} diff --git a/packages/css-tokenizer/dist/stringify.d.ts b/packages/css-tokenizer/dist/stringify.d.ts deleted file mode 100644 index 574d2043e..000000000 --- a/packages/css-tokenizer/dist/stringify.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import type { CSSToken } from './interfaces/token'; -export declare function stringify(...tokens: Array): string; diff --git a/packages/css-tokenizer/dist/tokenizer.d.ts b/packages/css-tokenizer/dist/tokenizer.d.ts deleted file mode 100644 index 318a16bbb..000000000 --- a/packages/css-tokenizer/dist/tokenizer.d.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { CSSToken } from './interfaces/token'; -import { ParseError } from './interfaces/error'; -interface Stringer { - valueOf(): string; -} -export declare function tokenize(input: { - css: Stringer; - unicodeRangesAllowed?: boolean; -}, options?: { - onParseError?: (error: ParseError) => void; -}): Array; -export declare function tokenizer(input: { - css: Stringer; - unicodeRangesAllowed?: boolean; -}, options?: { - onParseError?: (error: ParseError) => void; -}): { - nextToken: () => CSSToken | undefined; - endOfFile: () => boolean; -}; -export {}; diff --git a/packages/css-tokenizer/dist/util/clone-tokens.d.ts b/packages/css-tokenizer/dist/util/clone-tokens.d.ts deleted file mode 100644 index 1db05d036..000000000 --- a/packages/css-tokenizer/dist/util/clone-tokens.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import { CSSToken } from '../interfaces/token'; -export declare function cloneTokens(tokens: Array): Array; diff --git a/packages/css-tokenizer/dist/util/mutations.d.ts b/packages/css-tokenizer/dist/util/mutations.d.ts deleted file mode 100644 index 37f23cd29..000000000 --- a/packages/css-tokenizer/dist/util/mutations.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import { TokenIdent } from '../interfaces/token'; -export declare function mutateIdent(ident: TokenIdent, newValue: string): void; diff --git a/packages/css-tokenizer/package.json b/packages/css-tokenizer/package.json index d99e30d85..5572f827c 100644 --- a/packages/css-tokenizer/package.json +++ b/packages/css-tokenizer/package.json @@ -27,15 +27,18 @@ "engines": { "node": "^14 || ^16 || >=18" }, + "type": "module", "main": "dist/index.cjs", "module": "dist/index.mjs", - "types": "dist/index.d.ts", "exports": { ".": { - "types": "./dist/index.d.ts", - "import": "./dist/index.mjs", - "require": "./dist/index.cjs", - "default": "./dist/index.mjs" + "import": { + "types": "./dist/index.d.ts", + "default": "./dist/index.mjs" + }, + "require": { + "default": "./dist/index.cjs" + } } }, "files": [ diff --git a/packages/css-tokenizer/src/index.ts b/packages/css-tokenizer/src/index.ts index 04d52a3cf..5f29d011b 100644 --- a/packages/css-tokenizer/src/index.ts +++ b/packages/css-tokenizer/src/index.ts @@ -1,4 +1,5 @@ export type { CSSToken } from './interfaces/token'; +export type { CodePointReader } from './interfaces/code-point-reader'; export type { Token } from './interfaces/token'; export { ParseError } from './interfaces/error'; export { Reader } from './reader'; @@ -8,11 +9,15 @@ export { stringify } from './stringify'; export { tokenize, tokenizer } from './tokenizer'; export type { + HashType, TokenAtKeyword, TokenBadString, TokenBadURL, TokenCDC, TokenCDO, + TokenCloseCurly, + TokenCloseParen, + TokenCloseSquare, TokenColon, TokenComma, TokenComment, @@ -23,17 +28,15 @@ export type { TokenHash, TokenIdent, TokenNumber, + TokenOpenCurly, + TokenOpenParen, + TokenOpenSquare, TokenPercentage, TokenSemicolon, TokenString, TokenURL, + TokenUnicodeRange, TokenWhitespace, - TokenOpenParen, - TokenCloseParen, - TokenOpenSquare, - TokenCloseSquare, - TokenOpenCurly, - TokenCloseCurly, } from './interfaces/token'; export { diff --git a/packages/css-tokenizer/src/tokenizer.ts b/packages/css-tokenizer/src/tokenizer.ts index e93b9607a..45408d444 100644 --- a/packages/css-tokenizer/src/tokenizer.ts +++ b/packages/css-tokenizer/src/tokenizer.ts @@ -19,11 +19,7 @@ import { ParseError } from './interfaces/error'; import { checkIfThreeCodePointsWouldStartAUnicodeRange } from './checks/three-code-points-would-start-unicode-range'; import { consumeUnicodeRangeToken } from './consume/unicode-range-token'; -interface Stringer { - valueOf(): string -} - -export function tokenize(input: { css: Stringer, unicodeRangesAllowed?: boolean }, options?: { onParseError?: (error: ParseError) => void }): Array { +export function tokenize(input: { css: { valueOf(): string }, unicodeRangesAllowed?: boolean }, options?: { onParseError?: (error: ParseError) => void }): Array { const t = tokenizer(input, options); const tokens: Array = []; @@ -45,7 +41,7 @@ export function tokenize(input: { css: Stringer, unicodeRangesAllowed?: boolean return tokens; } -export function tokenizer(input: { css: Stringer, unicodeRangesAllowed?: boolean }, options?: { onParseError?: (error: ParseError) => void }) { +export function tokenizer(input: { css: { valueOf(): string }, unicodeRangesAllowed?: boolean }, options?: { onParseError?: (error: ParseError) => void }) { const css = input.css.valueOf(); const unicodeRangesAllowed = input.unicodeRangesAllowed ?? false; diff --git a/packages/media-query-list-parser/CHANGELOG.md b/packages/media-query-list-parser/CHANGELOG.md index 053bb70ee..14e99cc43 100644 --- a/packages/media-query-list-parser/CHANGELOG.md +++ b/packages/media-query-list-parser/CHANGELOG.md @@ -2,7 +2,7 @@ ### Unreleased (patch) -- Small fixes in type definitions +- Fix type definitions - Only `walk` child nodes if they are still part of the current AST tree [#1202](https://github.com/csstools/postcss-plugins/issues/1202) - Make `walk` methods safe for mutations [#1204](https://github.com/csstools/postcss-plugins/issues/1204) diff --git a/packages/media-query-list-parser/api-extractor.json b/packages/media-query-list-parser/api-extractor.json new file mode 100644 index 000000000..42058be51 --- /dev/null +++ b/packages/media-query-list-parser/api-extractor.json @@ -0,0 +1,4 @@ +{ + "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json", + "extends": "../../api-extractor.json" +} diff --git a/packages/media-query-list-parser/dist/index.cjs b/packages/media-query-list-parser/dist/index.cjs index 2603d9206..8d3e5aea9 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";const a=/[A-Z]/g;function toLowerCaseAZ(e){return e.replace(a,(e=>String.fromCharCode(e.charCodeAt(0)+32)))}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!!(e.type===t.ComponentValueType.Token&&e.value[0]===i.TokenType.Number||e.type===t.ComponentValueType.Function&&r.has(toLowerCaseAZ(e.name[4].value)))}const r=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 e.type===t.ComponentValueType.Token&&e.value[0]===i.TokenType.Dimension}function isIdent(e){return e.type===t.ComponentValueType.Token&&e.value[0]===i.TokenType.Ident}function isEnvironmentVariable(e){return e.type===t.ComponentValueType.Function&&"env"===toLowerCaseAZ(e.name[4].value)}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(e[0][0]!==i.TokenType.Delim)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(e[1][0]!==i.TokenType.Delim)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,(n=exports.MediaFeatureLT||(exports.MediaFeatureLT={})).LT="<",n.LT_OR_EQ="<=",exports.MediaFeatureGT=void 0,(s=exports.MediaFeatureGT||(exports.MediaFeatureGT={})).GT=">",s.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(e.startToken[0]!==i.TokenType.OpenParen)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))}function parseMediaNot(e){let i=!1,a=null;for(let r=0;re.tokens())),t)}}}return a||!1}function parseMediaOr(e){let i=!1;for(let a=0;ae.tokens())),t)}}return!1}}return!1}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:null==i?void 0:i.onParseError});return a.map(((e,t)=>{const r=parseMediaQuery(e);return 0==r&&!0===(null==i?void 0:i.preserveInvalidMediaQueries)?new MediaQueryInvalid(a[t]):r})).filter((e=>!!e))}exports.MediaQueryModifier=void 0,(o=exports.MediaQueryModifier||(exports.MediaQueryModifier={})).Not="not",o.Only="only";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;tString.fromCharCode(e.charCodeAt(0)+32)))}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!!(e.type===t.ComponentValueType.Token&&e.value[0]===i.TokenType.Number||e.type===t.ComponentValueType.Function&&r.has(toLowerCaseAZ(e.name[4].value)))}const r=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 e.type===t.ComponentValueType.Token&&e.value[0]===i.TokenType.Dimension}function isIdent(e){return e.type===t.ComponentValueType.Token&&e.value[0]===i.TokenType.Ident}function isEnvironmentVariable(e){return e.type===t.ComponentValueType.Function&&"env"===toLowerCaseAZ(e.name[4].value)}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(e[0][0]!==i.TokenType.Delim)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(e[1][0]!==i.TokenType.Delim)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,(n=exports.MediaFeatureLT||(exports.MediaFeatureLT={})).LT="<",n.LT_OR_EQ="<=",exports.MediaFeatureGT=void 0,(s=exports.MediaFeatureGT||(exports.MediaFeatureGT={})).GT=">",s.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(e.startToken[0]!==i.TokenType.OpenParen)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))}function parseMediaNot(e){let i=!1,a=null;for(let r=0;re.tokens())),t)}}}return a||!1}function parseMediaOr(e){let i=!1;for(let a=0;ae.tokens())),t)}}return!1}}return!1}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 0==r&&!0===i?.preserveInvalidMediaQueries?new MediaQueryInvalid(a[t]):r})).filter((e=>!!e))}exports.MediaQueryModifier=void 0,(o=exports.MediaQueryModifier||(exports.MediaQueryModifier={})).Not="not",o.Only="only";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;t(x: T): T; + +export declare function comparisonFromTokens(tokens: [TokenDelim, TokenDelim] | [TokenDelim]): MediaFeatureComparison | false; + +export declare class CustomMedia { + type: NodeType; + name: Array; + mediaQueryList: Array | null; + trueOrFalseKeyword: Array | null; + constructor(name: Array, mediaQueryList: Array | null, trueOrFalseKeyword?: Array); + getName(): string; + getNameToken(): CSSToken | null; + hasMediaQueryList(): boolean; + hasTrueKeyword(): boolean; + hasFalseKeyword(): boolean; + tokens(): Array; + toString(): string; + toJSON(): { + type: NodeType; + string: string; + nameValue: string; + name: CSSToken[]; + hasFalseKeyword: boolean; + hasTrueKeyword: boolean; + trueOrFalseKeyword: CSSToken[] | null; + mediaQueryList: ({ + type: NodeType; + string: string; + modifier: CSSToken[]; + mediaType: CSSToken[]; + and: CSSToken[] | undefined; + media: MediaCondition | undefined; + } | { + type: NodeType; + string: string; + media: MediaCondition; + } | { + type: NodeType; + string: string; + media: ComponentValue[]; + })[] | undefined; + }; + isCustomMedia(): this is CustomMedia; + static isCustomMedia(x: unknown): x is CustomMedia; +} + +export declare class GeneralEnclosed { + type: NodeType; + value: ComponentValue; + constructor(value: ComponentValue); + tokens(): Array; + toString(): string; + indexOf(item: ComponentValue): number | string; + at(index: number | string): ComponentValue | undefined; + walk>(cb: (entry: { + node: GeneralEnclosedWalkerEntry; + parent: GeneralEnclosedWalkerParent; + state?: T; + }, index: number | string) => boolean | void, state?: T): false | undefined; + toJSON(): { + type: NodeType; + tokens: CSSToken[]; + }; + isGeneralEnclosed(): this is GeneralEnclosed; + static isGeneralEnclosed(x: unknown): x is GeneralEnclosed; +} + +export declare type GeneralEnclosedWalkerEntry = ComponentValue; + +export declare type GeneralEnclosedWalkerParent = ContainerNode | GeneralEnclosed; + +export declare function invertComparison(operator: MediaFeatureComparison): MediaFeatureComparison | false; + +export declare function isCustomMedia(x: unknown): x is GeneralEnclosed; + +export declare function isGeneralEnclosed(x: unknown): x is GeneralEnclosed; + +export declare function isMediaAnd(x: unknown): x is MediaAnd; + +export declare function isMediaCondition(x: unknown): x is MediaCondition; + +export declare function isMediaConditionList(x: unknown): x is MediaConditionList; + +export declare function isMediaConditionListWithAnd(x: unknown): x is MediaConditionListWithAnd; + +export declare function isMediaConditionListWithOr(x: unknown): x is MediaConditionListWithOr; + +export declare function isMediaFeature(x: unknown): x is MediaFeature; + +export declare function isMediaFeatureBoolean(x: unknown): x is MediaFeatureBoolean; + +export declare function isMediaFeatureName(x: unknown): x is MediaFeatureName; + +export declare function isMediaFeaturePlain(x: unknown): x is MediaFeaturePlain; + +export declare function isMediaFeatureRange(x: unknown): x is MediaFeatureRange; + +export declare function isMediaFeatureRangeNameValue(x: unknown): x is MediaFeatureRangeNameValue; + +export declare function isMediaFeatureRangeValueName(x: unknown): x is MediaFeatureRangeValueName; + +export declare function isMediaFeatureRangeValueNameValue(x: unknown): x is MediaFeatureRangeValueNameValue; + +export declare function isMediaFeatureValue(x: unknown): x is MediaFeatureValue; + +export declare function isMediaInParens(x: unknown): x is MediaInParens; + +export declare function isMediaNot(x: unknown): x is MediaNot; + +export declare function isMediaOr(x: unknown): x is MediaOr; + +export declare function isMediaQuery(x: unknown): x is MediaQuery; + +export declare function isMediaQueryInvalid(x: unknown): x is MediaQueryInvalid; + +export declare function isMediaQueryWithoutType(x: unknown): x is MediaQueryWithoutType; + +export declare function isMediaQueryWithType(x: unknown): x is MediaQueryWithType; + +export declare function matchesComparison(componentValues: Array): false | [number, number]; + +export declare function matchesRatio(componentValues: Array): number[] | -1; + +export declare function matchesRatioExactly(componentValues: Array): number[] | -1; + +export declare class MediaAnd { + type: NodeType; + modifier: Array; + media: MediaInParens; + constructor(modifier: Array, media: MediaInParens); + tokens(): Array; + toString(): string; + indexOf(item: MediaInParens): number | string; + at(index: number | string): MediaInParens | null; + walk>(cb: (entry: { + node: MediaAndWalkerEntry; + parent: MediaAndWalkerParent; + state?: T; + }, index: number | string) => boolean | void, state?: T): false | undefined; + toJSON(): unknown; + isMediaAnd(): this is MediaAnd; + static isMediaAnd(x: unknown): x is MediaAnd; +} + +export declare type MediaAndWalkerEntry = MediaInParensWalkerEntry | MediaInParens; + +export declare type MediaAndWalkerParent = MediaInParensWalkerParent | MediaAnd; + +export declare class MediaCondition { + type: NodeType; + media: MediaNot | MediaInParens | MediaConditionListWithAnd | MediaConditionListWithOr; + constructor(media: MediaNot | MediaInParens | MediaConditionListWithAnd | MediaConditionListWithOr); + tokens(): Array; + toString(): string; + indexOf(item: MediaNot | MediaInParens | MediaConditionListWithAnd | MediaConditionListWithOr): number | string; + at(index: number | string): MediaNot | MediaInParens | MediaConditionListWithAnd | MediaConditionListWithOr | undefined; + walk>(cb: (entry: { + node: MediaConditionWalkerEntry; + parent: MediaConditionWalkerParent; + state?: T; + }, index: number | string) => boolean | void, state?: T): false | undefined; + toJSON(): unknown; + isMediaCondition(): this is MediaCondition; + static isMediaCondition(x: unknown): x is MediaCondition; +} + +export declare type MediaConditionList = MediaConditionListWithAnd | MediaConditionListWithOr; + +export declare class MediaConditionListWithAnd { + type: NodeType; + leading: MediaInParens; + list: Array; + before: Array; + after: Array; + constructor(leading: MediaInParens, list: Array, before?: Array, after?: Array); + tokens(): Array; + toString(): string; + indexOf(item: MediaInParens | MediaAnd): number | string; + at(index: number | string): MediaInParens | MediaAnd | undefined; + walk>(cb: (entry: { + node: MediaConditionListWithAndWalkerEntry; + parent: MediaConditionListWithAndWalkerParent; + state?: T; + }, index: number | string) => boolean | void, state?: T): false | undefined; + toJSON(): unknown; + isMediaConditionListWithAnd(): this is MediaConditionListWithAnd; + static isMediaConditionListWithAnd(x: unknown): x is MediaConditionListWithAnd; +} + +export declare type MediaConditionListWithAndWalkerEntry = MediaAndWalkerEntry | MediaAnd; + +export declare type MediaConditionListWithAndWalkerParent = MediaAndWalkerParent | MediaConditionListWithAnd; + +export declare class MediaConditionListWithOr { + type: NodeType; + leading: MediaInParens; + list: Array; + before: Array; + after: Array; + constructor(leading: MediaInParens, list: Array, before?: Array, after?: Array); + tokens(): Array; + toString(): string; + indexOf(item: MediaInParens | MediaOr): number | string; + at(index: number | string): MediaInParens | MediaOr | undefined; + walk>(cb: (entry: { + node: MediaConditionListWithOrWalkerEntry; + parent: MediaConditionListWithOrWalkerParent; + state?: T; + }, index: number | string) => boolean | void, state?: T): false | undefined; + toJSON(): unknown; + isMediaConditionListWithOr(): this is MediaConditionListWithOr; + static isMediaConditionListWithOr(x: unknown): x is MediaConditionListWithOr; +} + +export declare type MediaConditionListWithOrWalkerEntry = MediaOrWalkerEntry | MediaOr; + +export declare type MediaConditionListWithOrWalkerParent = MediaOrWalkerParent | MediaConditionListWithOr; + +export declare type MediaConditionWalkerEntry = MediaNotWalkerEntry | MediaConditionListWithAndWalkerEntry | MediaConditionListWithOrWalkerEntry | MediaNot | MediaConditionListWithAnd | MediaConditionListWithOr; + +export declare type MediaConditionWalkerParent = MediaNotWalkerParent | MediaConditionListWithAndWalkerParent | MediaConditionListWithOrWalkerParent | MediaCondition; + +export declare class MediaFeature { + type: NodeType; + feature: MediaFeaturePlain | MediaFeatureBoolean | MediaFeatureRange; + before: Array; + after: Array; + constructor(feature: MediaFeaturePlain | MediaFeatureBoolean | MediaFeatureRange, before?: Array, after?: Array); + getName(): string; + getNameToken(): CSSToken; + tokens(): Array; + toString(): string; + indexOf(item: MediaFeaturePlain | MediaFeatureBoolean | MediaFeatureRange): number | string; + at(index: number | string): MediaFeatureBoolean | MediaFeaturePlain | MediaFeatureRange | undefined; + walk>(cb: (entry: { + node: MediaFeatureWalkerEntry; + parent: MediaFeatureWalkerParent; + state?: T; + }, index: number | string) => boolean | void, state?: T): false | undefined; + toJSON(): { + type: NodeType; + feature: { + type: NodeType; + name: { + type: NodeType; + name: string; + tokens: CSSToken[]; + }; + tokens: CSSToken[]; + }; + before: CSSToken[]; + after: CSSToken[]; + }; + isMediaFeature(): this is MediaFeature; + static isMediaFeature(x: unknown): x is MediaFeature; +} + +export declare class MediaFeatureBoolean { + type: NodeType; + name: MediaFeatureName; + constructor(name: MediaFeatureName); + getName(): string; + getNameToken(): CSSToken; + tokens(): Array; + toString(): string; + indexOf(item: MediaFeatureName): number | string; + at(index: number | string): MediaFeatureName | undefined; + toJSON(): { + type: NodeType; + name: { + type: NodeType; + name: string; + tokens: CSSToken[]; + }; + tokens: CSSToken[]; + }; + isMediaFeatureBoolean(): this is MediaFeatureBoolean; + static isMediaFeatureBoolean(x: unknown): x is MediaFeatureBoolean; +} + +export declare type MediaFeatureComparison = MediaFeatureLT | MediaFeatureGT | MediaFeatureEQ; + +export declare enum MediaFeatureEQ { + EQ = "=" +} + +export declare enum MediaFeatureGT { + GT = ">", + GT_OR_EQ = ">=" +} + +export declare enum MediaFeatureLT { + LT = "<", + LT_OR_EQ = "<=" +} + +export declare class MediaFeatureName { + type: NodeType; + name: ComponentValue; + before: Array; + after: Array; + constructor(name: ComponentValue, before?: Array, after?: Array); + getName(): string; + getNameToken(): CSSToken; + tokens(): Array; + toString(): string; + indexOf(item: ComponentValue): number | string; + at(index: number | string): ComponentValue | undefined; + toJSON(): { + type: NodeType; + name: string; + tokens: CSSToken[]; + }; + isMediaFeatureName(): this is MediaFeatureName; + static isMediaFeatureName(x: unknown): x is MediaFeatureName; +} + +export declare class MediaFeaturePlain { + type: NodeType; + name: MediaFeatureName; + colon: TokenColon; + value: MediaFeatureValue; + constructor(name: MediaFeatureName, colon: TokenColon, value: MediaFeatureValue); + getName(): string; + getNameToken(): CSSToken; + tokens(): Array; + toString(): string; + indexOf(item: MediaFeatureName | MediaFeatureValue): number | string; + at(index: number | string): MediaFeatureName | MediaFeatureValue | undefined; + walk>(cb: (entry: { + node: MediaFeaturePlainWalkerEntry; + parent: MediaFeaturePlainWalkerParent; + state?: T; + }, index: number | string) => boolean | void, state?: T): false | undefined; + toJSON(): { + type: NodeType; + name: { + type: NodeType; + name: string; + tokens: CSSToken[]; + }; + value: { + type: NodeType; + value: unknown; + tokens: CSSToken[]; + }; + tokens: CSSToken[]; + }; + isMediaFeaturePlain(): this is MediaFeaturePlain; + static isMediaFeaturePlain(x: unknown): x is MediaFeaturePlain; +} + +export declare type MediaFeaturePlainWalkerEntry = MediaFeatureValueWalkerEntry | MediaFeatureValue; + +export declare type MediaFeaturePlainWalkerParent = MediaFeatureValueWalkerParent | MediaFeaturePlain; + +export declare type MediaFeatureRange = MediaFeatureRangeNameValue | MediaFeatureRangeValueName | MediaFeatureRangeValueNameValue; + +export declare class MediaFeatureRangeNameValue { + type: NodeType; + name: MediaFeatureName; + operator: [TokenDelim, TokenDelim] | [TokenDelim]; + value: MediaFeatureValue; + constructor(name: MediaFeatureName, operator: [TokenDelim, TokenDelim] | [TokenDelim], value: MediaFeatureValue); + operatorKind(): MediaFeatureComparison | false; + getName(): string; + getNameToken(): CSSToken; + tokens(): Array; + toString(): string; + indexOf(item: MediaFeatureName | MediaFeatureValue): number | string; + at(index: number | string): MediaFeatureName | MediaFeatureValue | undefined; + walk>(cb: (entry: { + node: MediaFeatureRangeWalkerEntry; + parent: MediaFeatureRangeWalkerParent; + state?: T; + }, index: number | string) => boolean | void, state?: T): false | undefined; + toJSON(): { + type: NodeType; + name: { + type: NodeType; + name: string; + tokens: CSSToken[]; + }; + value: { + type: NodeType; + value: unknown; + tokens: CSSToken[]; + }; + tokens: CSSToken[]; + }; + isMediaFeatureRangeNameValue(): this is MediaFeatureRangeNameValue; + static isMediaFeatureRangeNameValue(x: unknown): x is MediaFeatureRangeNameValue; +} + +export declare class MediaFeatureRangeValueName { + type: NodeType; + name: MediaFeatureName; + operator: [TokenDelim, TokenDelim] | [TokenDelim]; + value: MediaFeatureValue; + constructor(name: MediaFeatureName, operator: [TokenDelim, TokenDelim] | [TokenDelim], value: MediaFeatureValue); + operatorKind(): MediaFeatureComparison | false; + getName(): string; + getNameToken(): CSSToken; + tokens(): Array; + toString(): string; + indexOf(item: MediaFeatureName | MediaFeatureValue): number | string; + at(index: number | string): MediaFeatureName | MediaFeatureValue | undefined; + walk>(cb: (entry: { + node: MediaFeatureRangeWalkerEntry; + parent: MediaFeatureRangeWalkerParent; + state?: T; + }, index: number | string) => boolean | void, state?: T): false | undefined; + toJSON(): { + type: NodeType; + name: { + type: NodeType; + name: string; + tokens: CSSToken[]; + }; + value: { + type: NodeType; + value: unknown; + tokens: CSSToken[]; + }; + tokens: CSSToken[]; + }; + isMediaFeatureRangeValueName(): this is MediaFeatureRangeValueName; + static isMediaFeatureRangeValueName(x: unknown): x is MediaFeatureRangeValueName; +} + +export declare class MediaFeatureRangeValueNameValue { + type: NodeType; + name: MediaFeatureName; + valueOne: MediaFeatureValue; + valueOneOperator: [TokenDelim, TokenDelim] | [TokenDelim]; + valueTwo: MediaFeatureValue; + valueTwoOperator: [TokenDelim, TokenDelim] | [TokenDelim]; + constructor(name: MediaFeatureName, valueOne: MediaFeatureValue, valueOneOperator: [TokenDelim, TokenDelim] | [TokenDelim], valueTwo: MediaFeatureValue, valueTwoOperator: [TokenDelim, TokenDelim] | [TokenDelim]); + valueOneOperatorKind(): MediaFeatureComparison | false; + valueTwoOperatorKind(): MediaFeatureComparison | false; + getName(): string; + getNameToken(): CSSToken; + tokens(): Array; + toString(): string; + indexOf(item: MediaFeatureName | MediaFeatureValue): number | string; + at(index: number | string): MediaFeatureName | MediaFeatureValue | undefined; + walk>(cb: (entry: { + node: MediaFeatureRangeWalkerEntry; + parent: MediaFeatureRangeWalkerParent; + state?: T; + }, index: number | string) => boolean | void, state?: T): false | undefined; + toJSON(): { + type: NodeType; + name: { + type: NodeType; + name: string; + tokens: CSSToken[]; + }; + valueOne: { + type: NodeType; + value: unknown; + tokens: CSSToken[]; + }; + valueTwo: { + type: NodeType; + value: unknown; + tokens: CSSToken[]; + }; + tokens: CSSToken[]; + }; + isMediaFeatureRangeValueNameValue(): this is MediaFeatureRangeValueNameValue; + static isMediaFeatureRangeValueNameValue(x: unknown): x is MediaFeatureRangeValueNameValue; +} + +export declare type MediaFeatureRangeWalkerEntry = MediaFeatureValueWalkerEntry | MediaFeatureValue; + +export declare type MediaFeatureRangeWalkerParent = MediaFeatureValueWalkerParent | MediaFeatureRange; + +export declare class MediaFeatureValue { + type: NodeType; + value: ComponentValue | Array; + before: Array; + after: Array; + constructor(value: ComponentValue | Array, before?: Array, after?: Array); + tokens(): Array; + toString(): string; + indexOf(item: ComponentValue): number | string; + at(index: number | string): ComponentValue | Array | undefined; + walk>(cb: (entry: { + node: MediaFeatureValueWalkerEntry; + parent: MediaFeatureValueWalkerParent; + state?: T; + }, index: number | string) => boolean | void, state?: T): false | undefined; + toJSON(): { + type: NodeType; + value: unknown; + tokens: CSSToken[]; + }; + isMediaFeatureValue(): this is MediaFeatureValue; + static isMediaFeatureValue(x: unknown): x is MediaFeatureValue; +} + +export declare type MediaFeatureValueWalkerEntry = ComponentValue; + +export declare type MediaFeatureValueWalkerParent = ContainerNode | MediaFeatureValue; + +export declare type MediaFeatureWalkerEntry = MediaFeaturePlainWalkerEntry | MediaFeatureRangeWalkerEntry | MediaFeaturePlain | MediaFeatureBoolean | MediaFeatureRange; + +export declare type MediaFeatureWalkerParent = MediaFeaturePlainWalkerParent | MediaFeatureRangeWalkerParent | MediaFeature; + +export declare class MediaInParens { + type: NodeType; + media: MediaCondition | MediaFeature | GeneralEnclosed; + before: Array; + after: Array; + constructor(media: MediaCondition | MediaFeature | GeneralEnclosed, before?: Array, after?: Array); + tokens(): Array; + toString(): string; + indexOf(item: MediaCondition | MediaFeature | GeneralEnclosed): number | string; + at(index: number | string): MediaCondition | MediaFeature | GeneralEnclosed | undefined; + walk>(cb: (entry: { + node: MediaInParensWalkerEntry; + parent: MediaInParensWalkerParent; + state?: T; + }, index: number | string) => boolean | void, state?: T): false | undefined; + toJSON(): { + type: NodeType; + media: unknown; + before: CSSToken[]; + after: CSSToken[]; + }; + isMediaInParens(): this is MediaInParens; + static isMediaInParens(x: unknown): x is MediaInParens; +} + +export declare type MediaInParensWalkerEntry = ComponentValue | GeneralEnclosed | MediaAnd | MediaNot | MediaOr | MediaConditionList | MediaCondition | MediaFeatureBoolean | MediaFeatureName | MediaFeaturePlain | MediaFeatureRange | MediaFeatureValue | MediaFeature | GeneralEnclosed | MediaInParens; + +export declare type MediaInParensWalkerParent = ContainerNode | GeneralEnclosed | MediaAnd | MediaNot | MediaOr | MediaConditionList | MediaCondition | MediaFeatureBoolean | MediaFeatureName | MediaFeaturePlain | MediaFeatureRange | MediaFeatureValue | MediaFeature | GeneralEnclosed | MediaInParens; + +export declare class MediaNot { + type: NodeType; + modifier: Array; + media: MediaInParens; + constructor(modifier: Array, media: MediaInParens); + tokens(): Array; + toString(): string; + indexOf(item: MediaInParens): number | string; + at(index: number | string): MediaInParens | undefined; + walk>(cb: (entry: { + node: MediaNotWalkerEntry; + parent: MediaNotWalkerParent; + state?: T; + }, index: number | string) => boolean | void, state?: T): false | undefined; + toJSON(): { + type: NodeType; + modifier: CSSToken[]; + media: { + type: NodeType; + media: unknown; + before: CSSToken[]; + after: CSSToken[]; + }; + }; + isMediaNot(): this is MediaNot; + static isMediaNot(x: unknown): x is MediaNot; +} + +export declare type MediaNotWalkerEntry = MediaInParensWalkerEntry | MediaInParens; + +export declare type MediaNotWalkerParent = MediaInParensWalkerParent | MediaNot; + +export declare class MediaOr { + type: NodeType; + modifier: Array; + media: MediaInParens; + constructor(modifier: Array, media: MediaInParens); + tokens(): Array; + toString(): string; + indexOf(item: MediaInParens): number | string; + at(index: number | string): MediaInParens | undefined; + walk>(cb: (entry: { + node: MediaOrWalkerEntry; + parent: MediaOrWalkerParent; + state?: T; + }, index: number | string) => boolean | void, state?: T): false | undefined; + toJSON(): { + type: NodeType; + modifier: CSSToken[]; + media: { + type: NodeType; + media: unknown; + before: CSSToken[]; + after: CSSToken[]; + }; + }; + isMediaOr(): this is MediaOr; + static isMediaOr(x: unknown): x is MediaOr; +} + +export declare type MediaOrWalkerEntry = MediaInParensWalkerEntry | MediaInParens; + +export declare type MediaOrWalkerParent = MediaInParensWalkerParent | MediaOr; + +export declare type MediaQuery = MediaQueryWithType | MediaQueryWithoutType | MediaQueryInvalid; + +export declare class MediaQueryInvalid { + type: NodeType; + media: Array; + constructor(media: Array); + negateQuery(): MediaQuery; + tokens(): Array; + toString(): string; + walk>(cb: (entry: { + node: MediaQueryInvalidWalkerEntry; + parent: MediaQueryInvalidWalkerParent; + state?: T; + }, index: number | string) => boolean | void, state?: T): false | undefined; + toJSON(): { + type: NodeType; + string: string; + media: ComponentValue[]; + }; + isMediaQueryInvalid(): this is MediaQueryInvalid; + static isMediaQueryInvalid(x: unknown): x is MediaQueryInvalid; +} + +export declare type MediaQueryInvalidWalkerEntry = ComponentValue; + +export declare type MediaQueryInvalidWalkerParent = ComponentValue | MediaQueryInvalid; + +export declare enum MediaQueryModifier { + Not = "not", + Only = "only" +} + +export declare class MediaQueryWithoutType { + type: NodeType; + media: MediaCondition; + constructor(media: MediaCondition); + negateQuery(): MediaQuery; + tokens(): Array; + toString(): string; + indexOf(item: MediaCondition): number | string; + at(index: number | string): MediaCondition | undefined; + walk>(cb: (entry: { + node: MediaQueryWithoutTypeWalkerEntry; + parent: MediaQueryWithoutTypeWalkerParent; + state?: T; + }, index: number | string) => boolean | void, state?: T): false | undefined; + toJSON(): { + type: NodeType; + string: string; + media: MediaCondition; + }; + isMediaQueryWithoutType(): this is MediaQueryWithoutType; + static isMediaQueryWithoutType(x: unknown): x is MediaQueryWithoutType; +} + +export declare type MediaQueryWithoutTypeWalkerEntry = MediaConditionWalkerEntry | MediaCondition; + +export declare type MediaQueryWithoutTypeWalkerParent = MediaConditionWalkerParent | MediaQueryWithoutType; + +export declare class MediaQueryWithType { + type: NodeType; + modifier: Array; + mediaType: Array; + and: Array | undefined; + media: MediaCondition | undefined; + constructor(modifier: Array, mediaType: Array, and?: Array | undefined, media?: MediaCondition | undefined); + getModifier(): string; + negateQuery(): MediaQuery; + getMediaType(): string; + tokens(): Array; + toString(): string; + indexOf(item: MediaCondition): number | string; + at(index: number | string): MediaCondition | undefined; + walk>(cb: (entry: { + node: MediaQueryWithTypeWalkerEntry; + parent: MediaQueryWithTypeWalkerParent; + state?: T; + }, index: number | string) => boolean | void, state?: T): false | undefined; + toJSON(): { + type: NodeType; + string: string; + modifier: CSSToken[]; + mediaType: CSSToken[]; + and: CSSToken[] | undefined; + media: MediaCondition | undefined; + }; + isMediaQueryWithType(): this is MediaQueryWithType; + static isMediaQueryWithType(x: unknown): x is MediaQueryWithType; +} + +export declare type MediaQueryWithTypeWalkerEntry = MediaConditionWalkerEntry | MediaCondition; + +export declare type MediaQueryWithTypeWalkerParent = MediaConditionWalkerParent | MediaQueryWithType; + +export declare enum MediaType { + /** Always matches */ + All = "all", + Print = "print", + Screen = "screen", + /** Never matches */ + Tty = "tty", + /** Never matches */ + Tv = "tv", + /** Never matches */ + Projection = "projection", + /** Never matches */ + Handheld = "handheld", + /** Never matches */ + Braille = "braille", + /** Never matches */ + Embossed = "embossed", + /** Never matches */ + Aural = "aural", + /** Never matches */ + Speech = "speech" +} + +export declare function modifierFromToken(token: TokenIdent): MediaQueryModifier | false; + +export declare function newMediaFeatureBoolean(name: string): MediaFeature; + +export declare function newMediaFeaturePlain(name: string, ...value: Array): MediaFeature; + +export declare enum NodeType { + CustomMedia = "custom-media", + GeneralEnclosed = "general-enclosed", + MediaAnd = "media-and", + MediaCondition = "media-condition", + MediaConditionListWithAnd = "media-condition-list-and", + MediaConditionListWithOr = "media-condition-list-or", + MediaFeature = "media-feature", + MediaFeatureBoolean = "mf-boolean", + MediaFeatureName = "mf-name", + MediaFeaturePlain = "mf-plain", + MediaFeatureRangeNameValue = "mf-range-name-value", + MediaFeatureRangeValueName = "mf-range-value-name", + MediaFeatureRangeValueNameValue = "mf-range-value-name-value", + MediaFeatureValue = "mf-value", + MediaInParens = "media-in-parens", + MediaNot = "media-not", + MediaOr = "media-or", + MediaQueryWithType = "media-query-with-type", + MediaQueryWithoutType = "media-query-without-type", + MediaQueryInvalid = "media-query-invalid" +} + +export declare function parse(source: string, options?: { + preserveInvalidMediaQueries?: boolean; + onParseError?: (error: ParseError) => void; +}): MediaQuery[]; + +export declare function parseCustomMedia(source: string, options?: { + preserveInvalidMediaQueries?: boolean; + onParseError?: (error: ParseError) => void; +}): CustomMedia | false; + +export declare function parseCustomMediaFromTokens(tokens: Array, options?: { + preserveInvalidMediaQueries?: boolean; + onParseError?: (error: ParseError) => void; +}): CustomMedia | false; + +export declare function parseFromTokens(tokens: Array, options?: { + preserveInvalidMediaQueries?: boolean; + onParseError?: (error: ParseError) => void; +}): MediaQuery[]; + +export declare function typeFromToken(token: TokenIdent): MediaType | false; + +export { } diff --git a/packages/media-query-list-parser/dist/index.mjs b/packages/media-query-list-parser/dist/index.mjs index fd26b563b..6a84592c1 100644 --- a/packages/media-query-list-parser/dist/index.mjs +++ b/packages/media-query-list-parser/dist/index.mjs @@ -1 +1 @@ -import{walkerIndexGenerator as e,ComponentValueType as t,TokenNode as i,parseListOfComponentValues as a,isWhitespaceNode as n,isCommentNode as r,isTokenNode as s,isSimpleBlockNode as o,parseCommaSeparatedListOfComponentValues as u}from"@csstools/css-parser-algorithms";import{stringify as d,TokenType as l,mutateIdent as h,tokenizer as m,cloneTokens as f}from"@csstools/css-tokenizer";var c;!function(e){e.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"}(c||(c={}));const M=/[A-Z]/g;function toLowerCaseAZ(e){return e.replace(M,(e=>String.fromCharCode(e.charCodeAt(0)+32)))}class MediaCondition{type=c.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===c.MediaCondition)}}class MediaInParens{type=c.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 d(...this.before)+this.media.toString()+d(...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===c.MediaInParens)}}class MediaQueryWithType{type=c.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(t,i){if(0===this.media.length)return;const a=e(this.media);let n=0;for(;ne.tokens())),...this.after]}toString(){return d(...this.before)+this.leading.toString()+this.list.map((e=>e.toString())).join("")+d(...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===c.MediaConditionListWithAnd)}}class MediaConditionListWithOr{type=c.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 d(...this.before)+this.leading.toString()+this.list.map((e=>e.toString())).join("")+d(...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===c.MediaConditionListWithOr)}}function isNumber(e){return!!(e.type===t.Token&&e.value[0]===l.Number||e.type===t.Function&&p.has(toLowerCaseAZ(e.name[4].value)))}const p=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 e.type===t.Token&&e.value[0]===l.Dimension}function isIdent(e){return e.type===t.Token&&e.value[0]===l.Ident}function isEnvironmentVariable(e){return e.type===t.Function&&"env"===toLowerCaseAZ(e.name[4].value)}class MediaFeatureName{type=c.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 d(...this.before)+this.name.toString()+d(...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===c.MediaFeatureName)}}function parseMediaFeatureName(e){let i=-1;for(let a=0;ae.tokens())),e.slice(i+1).flatMap((e=>e.tokens())))}class MediaFeatureBoolean{type=c.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===c.MediaFeatureBoolean)}}function parseMediaFeatureBoolean(e){const t=parseMediaFeatureName(e);return!1===t?t:new MediaFeatureBoolean(t)}class MediaFeatureValue{type=c.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)?d(...this.before)+this.value.map((e=>e.toString())).join("")+d(...this.after):d(...this.before)+this.value.toString()+d(...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===c.MediaFeatureValue)}}function parseMediaFeatureValue(e,i=!1){let a=-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(e[0][0]!==l.Delim)return!1;if(1===e.length)switch(e[0][4].value){case g.EQ:return g.EQ;case y.LT:return y.LT;case v.GT:return v.GT;default:return!1}if(e[1][0]!==l.Delim)return!1;if(e[1][4].value!==g.EQ)return!1;switch(e[0][4].value){case y.LT:return y.LT_OR_EQ;case v.GT:return v.GT_OR_EQ;default:return!1}}function invertComparison(e){switch(e){case g.EQ:return g.EQ;case y.LT:return v.GT;case y.LT_OR_EQ:return v.GT_OR_EQ;case v.GT:return y.LT;case v.GT_OR_EQ:return y.LT_OR_EQ;default:return!1}}!function(e){e.LT="<",e.LT_OR_EQ="<="}(y||(y={})),function(e){e.GT=">",e.GT_OR_EQ=">="}(v||(v={})),function(e){e.EQ="="}(g||(g={}));class MediaFeatureRangeNameValue{type=c.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()+d(...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===c.MediaFeatureRangeNameValue)}}class MediaFeatureRangeValueName{type=c.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()+d(...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===c.MediaFeatureRangeValueName)}}class MediaFeatureRangeValueNameValue{type=c.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()+d(...this.valueOneOperator)+this.name.toString()+d(...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===c.MediaFeatureRangeValueNameValue)}}function parseMediaFeatureRange(e){let i=!1,a=!1;for(let n=0;ne.tokens())),-1!==i&&(u=e.slice(t+1,i+1).flatMap((e=>e.tokens())))):-1!==i&&(u=e.slice(0,i+1).flatMap((e=>e.tokens())));const d=parseMediaConditionWithoutOr(e.slice(Math.max(t,i,a)+1));return!1===d?new MediaQueryWithType(o,[...u,...e.slice(i+1).flatMap((e=>e.tokens()))]):new MediaQueryWithType(o,u,e.slice(i+1,a+1).flatMap((e=>e.tokens())),d)}}function parseMediaConditionListWithOr(e){let i=!1;const a=[];let n=-1,r=-1;for(let s=0;se.tokens())),e.slice(r+1).flatMap((e=>e.tokens())))}function parseMediaConditionListWithAnd(e){let i=!1;const a=[];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 i=-1;for(let a=0;ae.tokens())),a.startToken],r=[a.endToken,...e.slice(i+1).flatMap((e=>e.tokens()))],s=parseMediaFeature(a,n,r);if(!1!==s)return new MediaInParens(s);const u=parseMediaCondition(a.value);return!1!==u?new MediaInParens(u,n,r):new MediaInParens(new GeneralEnclosed(a),e.slice(0,i).flatMap((e=>e.tokens())),e.slice(i+1).flatMap((e=>e.tokens())))}function parseMediaInParensFromSimpleBlock(e){if(e.startToken[0]!==l.OpenParen)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 parseMediaNot(e){let i=!1,a=null;for(let n=0;ne.tokens())),t)}}}return a||!1}function parseMediaOr(e){let i=!1;for(let a=0;ae.tokens())),t)}}return!1}}return!1}function parseMediaAnd(e){let i=!1;for(let a=0;ae.tokens())),t)}}return!1}}return!1}function parseFromTokens(e,t){const i=u(e,{onParseError:null==t?void 0:t.onParseError});return i.map(((e,a)=>{const n=parseMediaQuery(e);return 0==n&&!0===(null==t?void 0:t.preserveInvalidMediaQueries)?new MediaQueryInvalid(i[a]):n})).filter((e=>!!e))}function parse(e,t){const i=m({css:e},{onParseError:null==t?void 0:t.onParseError}),a=[];for(;!i.endOfFile();)a.push(i.nextToken());return a.push(i.nextToken()),parseFromTokens(a,t)}!function(e){e.Not="not",e.Only="only"}(k||(k={}));class CustomMedia{type=c.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===c.CustomMedia)}}function parseCustomMediaFromTokens(e,t){let i=[],a=e;for(let t=0;tString.fromCharCode(e.charCodeAt(0)+32)))}class MediaCondition{type=c.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===c.MediaCondition)}}class MediaInParens{type=c.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 d(...this.before)+this.media.toString()+d(...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===c.MediaInParens)}}class MediaQueryWithType{type=c.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(t,i){if(0===this.media.length)return;const a=e(this.media);let n=0;for(;ne.tokens())),...this.after]}toString(){return d(...this.before)+this.leading.toString()+this.list.map((e=>e.toString())).join("")+d(...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===c.MediaConditionListWithAnd)}}class MediaConditionListWithOr{type=c.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 d(...this.before)+this.leading.toString()+this.list.map((e=>e.toString())).join("")+d(...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===c.MediaConditionListWithOr)}}function isNumber(e){return!!(e.type===t.Token&&e.value[0]===l.Number||e.type===t.Function&&p.has(toLowerCaseAZ(e.name[4].value)))}const p=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 e.type===t.Token&&e.value[0]===l.Dimension}function isIdent(e){return e.type===t.Token&&e.value[0]===l.Ident}function isEnvironmentVariable(e){return e.type===t.Function&&"env"===toLowerCaseAZ(e.name[4].value)}class MediaFeatureName{type=c.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 d(...this.before)+this.name.toString()+d(...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===c.MediaFeatureName)}}function parseMediaFeatureName(e){let i=-1;for(let a=0;ae.tokens())),e.slice(i+1).flatMap((e=>e.tokens())))}class MediaFeatureBoolean{type=c.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===c.MediaFeatureBoolean)}}function parseMediaFeatureBoolean(e){const t=parseMediaFeatureName(e);return!1===t?t:new MediaFeatureBoolean(t)}class MediaFeatureValue{type=c.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)?d(...this.before)+this.value.map((e=>e.toString())).join("")+d(...this.after):d(...this.before)+this.value.toString()+d(...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===c.MediaFeatureValue)}}function parseMediaFeatureValue(e,i=!1){let a=-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(e[0][0]!==l.Delim)return!1;if(1===e.length)switch(e[0][4].value){case g.EQ:return g.EQ;case y.LT:return y.LT;case v.GT:return v.GT;default:return!1}if(e[1][0]!==l.Delim)return!1;if(e[1][4].value!==g.EQ)return!1;switch(e[0][4].value){case y.LT:return y.LT_OR_EQ;case v.GT:return v.GT_OR_EQ;default:return!1}}function invertComparison(e){switch(e){case g.EQ:return g.EQ;case y.LT:return v.GT;case y.LT_OR_EQ:return v.GT_OR_EQ;case v.GT:return y.LT;case v.GT_OR_EQ:return y.LT_OR_EQ;default:return!1}}!function(e){e.LT="<",e.LT_OR_EQ="<="}(y||(y={})),function(e){e.GT=">",e.GT_OR_EQ=">="}(v||(v={})),function(e){e.EQ="="}(g||(g={}));class MediaFeatureRangeNameValue{type=c.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()+d(...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===c.MediaFeatureRangeNameValue)}}class MediaFeatureRangeValueName{type=c.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()+d(...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===c.MediaFeatureRangeValueName)}}class MediaFeatureRangeValueNameValue{type=c.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()+d(...this.valueOneOperator)+this.name.toString()+d(...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===c.MediaFeatureRangeValueNameValue)}}function parseMediaFeatureRange(e){let i=!1,a=!1;for(let n=0;ne.tokens())),-1!==i&&(u=e.slice(t+1,i+1).flatMap((e=>e.tokens())))):-1!==i&&(u=e.slice(0,i+1).flatMap((e=>e.tokens())));const d=parseMediaConditionWithoutOr(e.slice(Math.max(t,i,a)+1));return!1===d?new MediaQueryWithType(o,[...u,...e.slice(i+1).flatMap((e=>e.tokens()))]):new MediaQueryWithType(o,u,e.slice(i+1,a+1).flatMap((e=>e.tokens())),d)}}function parseMediaConditionListWithOr(e){let i=!1;const a=[];let n=-1,r=-1;for(let s=0;se.tokens())),e.slice(r+1).flatMap((e=>e.tokens())))}function parseMediaConditionListWithAnd(e){let i=!1;const a=[];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 i=-1;for(let a=0;ae.tokens())),a.startToken],r=[a.endToken,...e.slice(i+1).flatMap((e=>e.tokens()))],s=parseMediaFeature(a,n,r);if(!1!==s)return new MediaInParens(s);const u=parseMediaCondition(a.value);return!1!==u?new MediaInParens(u,n,r):new MediaInParens(new GeneralEnclosed(a),e.slice(0,i).flatMap((e=>e.tokens())),e.slice(i+1).flatMap((e=>e.tokens())))}function parseMediaInParensFromSimpleBlock(e){if(e.startToken[0]!==l.OpenParen)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 parseMediaNot(e){let i=!1,a=null;for(let n=0;ne.tokens())),t)}}}return a||!1}function parseMediaOr(e){let i=!1;for(let a=0;ae.tokens())),t)}}return!1}}return!1}function parseMediaAnd(e){let i=!1;for(let a=0;ae.tokens())),t)}}return!1}}return!1}function parseFromTokens(e,t){const i=u(e,{onParseError:t?.onParseError});return i.map(((e,a)=>{const n=parseMediaQuery(e);return 0==n&&!0===t?.preserveInvalidMediaQueries?new MediaQueryInvalid(i[a]):n})).filter((e=>!!e))}function parse(e,t){const i=m({css:e},{onParseError:t?.onParseError}),a=[];for(;!i.endOfFile();)a.push(i.nextToken());return a.push(i.nextToken()),parseFromTokens(a,t)}!function(e){e.Not="not",e.Only="only"}(k||(k={}));class CustomMedia{type=c.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===c.CustomMedia)}}function parseCustomMediaFromTokens(e,t){let i=[],a=e;for(let t=0;t; - mediaQueryList: Array | null; - trueOrFalseKeyword: Array | null; - constructor(name: Array, mediaQueryList: Array | null, trueOrFalseKeyword?: Array); - getName(): string; - getNameToken(): CSSToken | null; - hasMediaQueryList(): boolean; - hasTrueKeyword(): boolean; - hasFalseKeyword(): boolean; - tokens(): Array; - toString(): string; - toJSON(): { - type: NodeType; - string: string; - nameValue: string; - name: CSSToken[]; - hasFalseKeyword: boolean; - hasTrueKeyword: boolean; - trueOrFalseKeyword: CSSToken[] | null; - mediaQueryList: ({ - type: NodeType; - string: string; - modifier: CSSToken[]; - mediaType: CSSToken[]; - and: CSSToken[] | undefined; - media: import("./media-condition").MediaCondition | undefined; - } | { - type: NodeType; - string: string; - media: import("./media-condition").MediaCondition; - } | { - type: NodeType; - string: string; - media: import("@csstools/css-parser-algorithms").ComponentValue[]; - })[] | undefined; - }; - isCustomMedia(): this is CustomMedia; - static isCustomMedia(x: unknown): x is CustomMedia; -} diff --git a/packages/media-query-list-parser/dist/nodes/general-enclosed.d.ts b/packages/media-query-list-parser/dist/nodes/general-enclosed.d.ts deleted file mode 100644 index 71a5f3704..000000000 --- a/packages/media-query-list-parser/dist/nodes/general-enclosed.d.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { ComponentValue, ContainerNode } from '@csstools/css-parser-algorithms'; -import { CSSToken } from '@csstools/css-tokenizer'; -import { NodeType } from '../util/node-type'; -export declare class GeneralEnclosed { - type: NodeType; - value: ComponentValue; - constructor(value: ComponentValue); - tokens(): Array; - toString(): string; - indexOf(item: ComponentValue): number | string; - at(index: number | string): ComponentValue | undefined; - walk>(cb: (entry: { - node: GeneralEnclosedWalkerEntry; - parent: GeneralEnclosedWalkerParent; - state?: T; - }, index: number | string) => boolean | void, state?: T): false | undefined; - toJSON(): { - type: NodeType; - tokens: CSSToken[]; - }; - isGeneralEnclosed(): this is GeneralEnclosed; - static isGeneralEnclosed(x: unknown): x is GeneralEnclosed; -} -type GeneralEnclosedWalkerEntry = ComponentValue; -type GeneralEnclosedWalkerParent = ContainerNode | GeneralEnclosed; -export {}; diff --git a/packages/media-query-list-parser/dist/nodes/media-and.d.ts b/packages/media-query-list-parser/dist/nodes/media-and.d.ts deleted file mode 100644 index ddd73d539..000000000 --- a/packages/media-query-list-parser/dist/nodes/media-and.d.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { CSSToken } from '@csstools/css-tokenizer'; -import { MediaInParens, MediaInParensWalkerEntry, MediaInParensWalkerParent } from './media-in-parens'; -import { NodeType } from '../util/node-type'; -export declare class MediaAnd { - type: NodeType; - modifier: Array; - media: MediaInParens; - constructor(modifier: Array, media: MediaInParens); - tokens(): Array; - toString(): string; - indexOf(item: MediaInParens): number | string; - at(index: number | string): MediaInParens | null; - walk>(cb: (entry: { - node: MediaAndWalkerEntry; - parent: MediaAndWalkerParent; - state?: T; - }, index: number | string) => boolean | void, state?: T): false | undefined; - toJSON(): unknown; - isMediaAnd(): this is MediaAnd; - static isMediaAnd(x: unknown): x is MediaAnd; -} -export type MediaAndWalkerEntry = MediaInParensWalkerEntry | MediaInParens; -export type MediaAndWalkerParent = MediaInParensWalkerParent | MediaAnd; diff --git a/packages/media-query-list-parser/dist/nodes/media-condition-list.d.ts b/packages/media-query-list-parser/dist/nodes/media-condition-list.d.ts deleted file mode 100644 index ddc51062d..000000000 --- a/packages/media-query-list-parser/dist/nodes/media-condition-list.d.ts +++ /dev/null @@ -1,50 +0,0 @@ -import { CSSToken } from '@csstools/css-tokenizer'; -import { MediaAnd, MediaAndWalkerEntry, MediaAndWalkerParent } from './media-and'; -import { MediaInParens } from './media-in-parens'; -import { MediaOr, MediaOrWalkerEntry, MediaOrWalkerParent } from './media-or'; -import { NodeType } from '../util/node-type'; -export type MediaConditionList = MediaConditionListWithAnd | MediaConditionListWithOr; -export declare class MediaConditionListWithAnd { - type: NodeType; - leading: MediaInParens; - list: Array; - before: Array; - after: Array; - constructor(leading: MediaInParens, list: Array, before?: Array, after?: Array); - tokens(): Array; - toString(): string; - indexOf(item: MediaInParens | MediaAnd): number | string; - at(index: number | string): MediaInParens | MediaAnd | undefined; - walk>(cb: (entry: { - node: MediaConditionListWithAndWalkerEntry; - parent: MediaConditionListWithAndWalkerParent; - state?: T; - }, index: number | string) => boolean | void, state?: T): false | undefined; - toJSON(): unknown; - isMediaConditionListWithAnd(): this is MediaConditionListWithAnd; - static isMediaConditionListWithAnd(x: unknown): x is MediaConditionListWithAnd; -} -export type MediaConditionListWithAndWalkerEntry = MediaAndWalkerEntry | MediaAnd; -export type MediaConditionListWithAndWalkerParent = MediaAndWalkerParent | MediaConditionListWithAnd; -export declare class MediaConditionListWithOr { - type: NodeType; - leading: MediaInParens; - list: Array; - before: Array; - after: Array; - constructor(leading: MediaInParens, list: Array, before?: Array, after?: Array); - tokens(): Array; - toString(): string; - indexOf(item: MediaInParens | MediaOr): number | string; - at(index: number | string): MediaInParens | MediaOr | undefined; - walk>(cb: (entry: { - node: MediaConditionListWithOrWalkerEntry; - parent: MediaConditionListWithOrWalkerParent; - state?: T; - }, index: number | string) => boolean | void, state?: T): false | undefined; - toJSON(): unknown; - isMediaConditionListWithOr(): this is MediaConditionListWithOr; - static isMediaConditionListWithOr(x: unknown): x is MediaConditionListWithOr; -} -export type MediaConditionListWithOrWalkerEntry = MediaOrWalkerEntry | MediaOr; -export type MediaConditionListWithOrWalkerParent = MediaOrWalkerParent | MediaConditionListWithOr; diff --git a/packages/media-query-list-parser/dist/nodes/media-condition.d.ts b/packages/media-query-list-parser/dist/nodes/media-condition.d.ts deleted file mode 100644 index faf2b49d2..000000000 --- a/packages/media-query-list-parser/dist/nodes/media-condition.d.ts +++ /dev/null @@ -1,24 +0,0 @@ -import { CSSToken } from '@csstools/css-tokenizer'; -import { MediaConditionListWithAnd, MediaConditionListWithAndWalkerEntry, MediaConditionListWithAndWalkerParent, MediaConditionListWithOr, MediaConditionListWithOrWalkerEntry, MediaConditionListWithOrWalkerParent } from './media-condition-list'; -import { MediaInParens } from './media-in-parens'; -import { MediaNot, MediaNotWalkerEntry, MediaNotWalkerParent } from './media-not'; -import { NodeType } from '../util/node-type'; -export declare class MediaCondition { - type: NodeType; - media: MediaNot | MediaInParens | MediaConditionListWithAnd | MediaConditionListWithOr; - constructor(media: MediaNot | MediaInParens | MediaConditionListWithAnd | MediaConditionListWithOr); - tokens(): Array; - toString(): string; - indexOf(item: MediaNot | MediaInParens | MediaConditionListWithAnd | MediaConditionListWithOr): number | string; - at(index: number | string): MediaNot | MediaInParens | MediaConditionListWithAnd | MediaConditionListWithOr | undefined; - walk>(cb: (entry: { - node: MediaConditionWalkerEntry; - parent: MediaConditionWalkerParent; - state?: T; - }, index: number | string) => boolean | void, state?: T): false | undefined; - toJSON(): unknown; - isMediaCondition(): this is MediaCondition; - static isMediaCondition(x: unknown): x is MediaCondition; -} -export type MediaConditionWalkerEntry = MediaNotWalkerEntry | MediaConditionListWithAndWalkerEntry | MediaConditionListWithOrWalkerEntry | MediaNot | MediaConditionListWithAnd | MediaConditionListWithOr; -export type MediaConditionWalkerParent = MediaNotWalkerParent | MediaConditionListWithAndWalkerParent | MediaConditionListWithOrWalkerParent | MediaCondition; diff --git a/packages/media-query-list-parser/dist/nodes/media-feature-boolean.d.ts b/packages/media-query-list-parser/dist/nodes/media-feature-boolean.d.ts deleted file mode 100644 index a5c64ec1f..000000000 --- a/packages/media-query-list-parser/dist/nodes/media-feature-boolean.d.ts +++ /dev/null @@ -1,27 +0,0 @@ -import { ComponentValue } from '@csstools/css-parser-algorithms'; -import { MediaFeatureName } from './media-feature-name'; -import { NodeType } from '../util/node-type'; -import { CSSToken } from '@csstools/css-tokenizer'; -export declare class MediaFeatureBoolean { - type: NodeType; - name: MediaFeatureName; - constructor(name: MediaFeatureName); - getName(): string; - getNameToken(): CSSToken; - tokens(): Array; - toString(): string; - indexOf(item: MediaFeatureName): number | string; - at(index: number | string): MediaFeatureName | undefined; - toJSON(): { - type: NodeType; - name: { - type: NodeType; - name: string; - tokens: CSSToken[]; - }; - tokens: CSSToken[]; - }; - isMediaFeatureBoolean(): this is MediaFeatureBoolean; - static isMediaFeatureBoolean(x: unknown): x is MediaFeatureBoolean; -} -export declare function parseMediaFeatureBoolean(componentValues: Array): false | MediaFeatureBoolean; diff --git a/packages/media-query-list-parser/dist/nodes/media-feature-comparison.d.ts b/packages/media-query-list-parser/dist/nodes/media-feature-comparison.d.ts deleted file mode 100644 index 377696577..000000000 --- a/packages/media-query-list-parser/dist/nodes/media-feature-comparison.d.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { ComponentValue } from '@csstools/css-parser-algorithms'; -import { TokenDelim } from '@csstools/css-tokenizer'; -export declare enum MediaFeatureLT { - LT = "<", - LT_OR_EQ = "<=" -} -export declare enum MediaFeatureGT { - GT = ">", - GT_OR_EQ = ">=" -} -export declare enum MediaFeatureEQ { - EQ = "=" -} -export type MediaFeatureComparison = MediaFeatureLT | MediaFeatureGT | MediaFeatureEQ; -export declare function matchesComparison(componentValues: Array): false | [number, number]; -export declare function comparisonFromTokens(tokens: [TokenDelim, TokenDelim] | [TokenDelim]): MediaFeatureComparison | false; -export declare function invertComparison(operator: MediaFeatureComparison): MediaFeatureComparison | false; diff --git a/packages/media-query-list-parser/dist/nodes/media-feature-name.d.ts b/packages/media-query-list-parser/dist/nodes/media-feature-name.d.ts deleted file mode 100644 index 332b421a1..000000000 --- a/packages/media-query-list-parser/dist/nodes/media-feature-name.d.ts +++ /dev/null @@ -1,24 +0,0 @@ -import { ComponentValue } from '@csstools/css-parser-algorithms'; -import { CSSToken } from '@csstools/css-tokenizer'; -import { NodeType } from '../util/node-type'; -export declare class MediaFeatureName { - type: NodeType; - name: ComponentValue; - before: Array; - after: Array; - constructor(name: ComponentValue, before?: Array, after?: Array); - getName(): string; - getNameToken(): CSSToken; - tokens(): Array; - toString(): string; - indexOf(item: ComponentValue): number | string; - at(index: number | string): ComponentValue | undefined; - toJSON(): { - type: NodeType; - name: string; - tokens: CSSToken[]; - }; - isMediaFeatureName(): this is MediaFeatureName; - static isMediaFeatureName(x: unknown): x is MediaFeatureName; -} -export declare function parseMediaFeatureName(componentValues: Array): MediaFeatureName | false; diff --git a/packages/media-query-list-parser/dist/nodes/media-feature-plain.d.ts b/packages/media-query-list-parser/dist/nodes/media-feature-plain.d.ts deleted file mode 100644 index 32f22c401..000000000 --- a/packages/media-query-list-parser/dist/nodes/media-feature-plain.d.ts +++ /dev/null @@ -1,42 +0,0 @@ -import { ComponentValue } from '@csstools/css-parser-algorithms'; -import { CSSToken, TokenColon } from '@csstools/css-tokenizer'; -import { MediaFeatureName } from './media-feature-name'; -import { MediaFeatureValue, MediaFeatureValueWalkerEntry, MediaFeatureValueWalkerParent } from './media-feature-value'; -import { NodeType } from '../util/node-type'; -export declare class MediaFeaturePlain { - type: NodeType; - name: MediaFeatureName; - colon: TokenColon; - value: MediaFeatureValue; - constructor(name: MediaFeatureName, colon: TokenColon, value: MediaFeatureValue); - getName(): string; - getNameToken(): CSSToken; - tokens(): Array; - toString(): string; - indexOf(item: MediaFeatureName | MediaFeatureValue): number | string; - at(index: number | string): MediaFeatureName | MediaFeatureValue | undefined; - walk>(cb: (entry: { - node: MediaFeaturePlainWalkerEntry; - parent: MediaFeaturePlainWalkerParent; - state?: T; - }, index: number | string) => boolean | void, state?: T): false | undefined; - toJSON(): { - type: NodeType; - name: { - type: NodeType; - name: string; - tokens: CSSToken[]; - }; - value: { - type: NodeType; - value: unknown; - tokens: CSSToken[]; - }; - tokens: CSSToken[]; - }; - isMediaFeaturePlain(): this is MediaFeaturePlain; - static isMediaFeaturePlain(x: unknown): x is MediaFeaturePlain; -} -export type MediaFeaturePlainWalkerEntry = MediaFeatureValueWalkerEntry | MediaFeatureValue; -export type MediaFeaturePlainWalkerParent = MediaFeatureValueWalkerParent | MediaFeaturePlain; -export declare function parseMediaFeaturePlain(componentValues: Array): MediaFeaturePlain | false; diff --git a/packages/media-query-list-parser/dist/nodes/media-feature-range.d.ts b/packages/media-query-list-parser/dist/nodes/media-feature-range.d.ts deleted file mode 100644 index afe322aeb..000000000 --- a/packages/media-query-list-parser/dist/nodes/media-feature-range.d.ts +++ /dev/null @@ -1,123 +0,0 @@ -import { ComponentValue } from '@csstools/css-parser-algorithms'; -import { CSSToken, TokenDelim } from '@csstools/css-tokenizer'; -import { MediaFeatureComparison } from './media-feature-comparison'; -import { MediaFeatureName } from './media-feature-name'; -import { MediaFeatureValue, MediaFeatureValueWalkerEntry, MediaFeatureValueWalkerParent } from './media-feature-value'; -import { NodeType } from '../util/node-type'; -export type MediaFeatureRange = MediaFeatureRangeNameValue | MediaFeatureRangeValueName | MediaFeatureRangeValueNameValue; -export declare class MediaFeatureRangeNameValue { - type: NodeType; - name: MediaFeatureName; - operator: [TokenDelim, TokenDelim] | [TokenDelim]; - value: MediaFeatureValue; - constructor(name: MediaFeatureName, operator: [TokenDelim, TokenDelim] | [TokenDelim], value: MediaFeatureValue); - operatorKind(): MediaFeatureComparison | false; - getName(): string; - getNameToken(): CSSToken; - tokens(): Array; - toString(): string; - indexOf(item: MediaFeatureName | MediaFeatureValue): number | string; - at(index: number | string): MediaFeatureName | MediaFeatureValue | undefined; - walk>(cb: (entry: { - node: MediaFeatureRangeWalkerEntry; - parent: MediaFeatureRangeWalkerParent; - state?: T; - }, index: number | string) => boolean | void, state?: T): false | undefined; - toJSON(): { - type: NodeType; - name: { - type: NodeType; - name: string; - tokens: CSSToken[]; - }; - value: { - type: NodeType; - value: unknown; - tokens: CSSToken[]; - }; - tokens: CSSToken[]; - }; - isMediaFeatureRangeNameValue(): this is MediaFeatureRangeNameValue; - static isMediaFeatureRangeNameValue(x: unknown): x is MediaFeatureRangeNameValue; -} -export declare class MediaFeatureRangeValueName { - type: NodeType; - name: MediaFeatureName; - operator: [TokenDelim, TokenDelim] | [TokenDelim]; - value: MediaFeatureValue; - constructor(name: MediaFeatureName, operator: [TokenDelim, TokenDelim] | [TokenDelim], value: MediaFeatureValue); - operatorKind(): MediaFeatureComparison | false; - getName(): string; - getNameToken(): CSSToken; - tokens(): Array; - toString(): string; - indexOf(item: MediaFeatureName | MediaFeatureValue): number | string; - at(index: number | string): MediaFeatureName | MediaFeatureValue | undefined; - walk>(cb: (entry: { - node: MediaFeatureRangeWalkerEntry; - parent: MediaFeatureRangeWalkerParent; - state?: T; - }, index: number | string) => boolean | void, state?: T): false | undefined; - toJSON(): { - type: NodeType; - name: { - type: NodeType; - name: string; - tokens: CSSToken[]; - }; - value: { - type: NodeType; - value: unknown; - tokens: CSSToken[]; - }; - tokens: CSSToken[]; - }; - isMediaFeatureRangeValueName(): this is MediaFeatureRangeValueName; - static isMediaFeatureRangeValueName(x: unknown): x is MediaFeatureRangeValueName; -} -export declare class MediaFeatureRangeValueNameValue { - type: NodeType; - name: MediaFeatureName; - valueOne: MediaFeatureValue; - valueOneOperator: [TokenDelim, TokenDelim] | [TokenDelim]; - valueTwo: MediaFeatureValue; - valueTwoOperator: [TokenDelim, TokenDelim] | [TokenDelim]; - constructor(name: MediaFeatureName, valueOne: MediaFeatureValue, valueOneOperator: [TokenDelim, TokenDelim] | [TokenDelim], valueTwo: MediaFeatureValue, valueTwoOperator: [TokenDelim, TokenDelim] | [TokenDelim]); - valueOneOperatorKind(): MediaFeatureComparison | false; - valueTwoOperatorKind(): MediaFeatureComparison | false; - getName(): string; - getNameToken(): CSSToken; - tokens(): Array; - toString(): string; - indexOf(item: MediaFeatureName | MediaFeatureValue): number | string; - at(index: number | string): MediaFeatureName | MediaFeatureValue | undefined; - walk>(cb: (entry: { - node: MediaFeatureRangeWalkerEntry; - parent: MediaFeatureRangeWalkerParent; - state?: T; - }, index: number | string) => boolean | void, state?: T): false | undefined; - toJSON(): { - type: NodeType; - name: { - type: NodeType; - name: string; - tokens: CSSToken[]; - }; - valueOne: { - type: NodeType; - value: unknown; - tokens: CSSToken[]; - }; - valueTwo: { - type: NodeType; - value: unknown; - tokens: CSSToken[]; - }; - tokens: CSSToken[]; - }; - isMediaFeatureRangeValueNameValue(): this is MediaFeatureRangeValueNameValue; - static isMediaFeatureRangeValueNameValue(x: unknown): x is MediaFeatureRangeValueNameValue; -} -export type MediaFeatureRangeWalkerEntry = MediaFeatureValueWalkerEntry | MediaFeatureValue; -export type MediaFeatureRangeWalkerParent = MediaFeatureValueWalkerParent | MediaFeatureRange; -export declare function parseMediaFeatureRange(componentValues: Array): MediaFeatureRange | false; diff --git a/packages/media-query-list-parser/dist/nodes/media-feature-value.d.ts b/packages/media-query-list-parser/dist/nodes/media-feature-value.d.ts deleted file mode 100644 index dda072bb1..000000000 --- a/packages/media-query-list-parser/dist/nodes/media-feature-value.d.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { ComponentValue, ContainerNode } from '@csstools/css-parser-algorithms'; -import { CSSToken } from '@csstools/css-tokenizer'; -import { NodeType } from '../util/node-type'; -export declare class MediaFeatureValue { - type: NodeType; - value: ComponentValue | Array; - before: Array; - after: Array; - constructor(value: ComponentValue | Array, before?: Array, after?: Array); - tokens(): Array; - toString(): string; - indexOf(item: ComponentValue): number | string; - at(index: number | string): ComponentValue | Array | undefined; - walk>(cb: (entry: { - node: MediaFeatureValueWalkerEntry; - parent: MediaFeatureValueWalkerParent; - state?: T; - }, index: number | string) => boolean | void, state?: T): false | undefined; - toJSON(): { - type: NodeType; - value: unknown; - tokens: CSSToken[]; - }; - isMediaFeatureValue(): this is MediaFeatureValue; - static isMediaFeatureValue(x: unknown): x is MediaFeatureValue; -} -export type MediaFeatureValueWalkerEntry = ComponentValue; -export type MediaFeatureValueWalkerParent = ContainerNode | MediaFeatureValue; -export declare function parseMediaFeatureValue(componentValues: Array, inRangeContext?: boolean): MediaFeatureValue | false; -export declare function matchesRatioExactly(componentValues: Array): number[] | -1; -export declare function matchesRatio(componentValues: Array): number[] | -1; diff --git a/packages/media-query-list-parser/dist/nodes/media-feature.d.ts b/packages/media-query-list-parser/dist/nodes/media-feature.d.ts deleted file mode 100644 index 9c0ab852b..000000000 --- a/packages/media-query-list-parser/dist/nodes/media-feature.d.ts +++ /dev/null @@ -1,46 +0,0 @@ -import { SimpleBlockNode } from '@csstools/css-parser-algorithms'; -import { CSSToken } from '@csstools/css-tokenizer'; -import { MediaFeatureBoolean } from './media-feature-boolean'; -import { MediaFeaturePlain, MediaFeaturePlainWalkerEntry, MediaFeaturePlainWalkerParent } from './media-feature-plain'; -import { MediaFeatureRange, MediaFeatureRangeWalkerEntry, MediaFeatureRangeWalkerParent } from './media-feature-range'; -import { NodeType } from '../util/node-type'; -export declare class MediaFeature { - type: NodeType; - feature: MediaFeaturePlain | MediaFeatureBoolean | MediaFeatureRange; - before: Array; - after: Array; - constructor(feature: MediaFeaturePlain | MediaFeatureBoolean | MediaFeatureRange, before?: Array, after?: Array); - getName(): string; - getNameToken(): CSSToken; - tokens(): Array; - toString(): string; - indexOf(item: MediaFeaturePlain | MediaFeatureBoolean | MediaFeatureRange): number | string; - at(index: number | string): MediaFeatureBoolean | MediaFeaturePlain | MediaFeatureRange | undefined; - walk>(cb: (entry: { - node: MediaFeatureWalkerEntry; - parent: MediaFeatureWalkerParent; - state?: T; - }, index: number | string) => boolean | void, state?: T): false | undefined; - toJSON(): { - type: NodeType; - feature: { - type: NodeType; - name: { - type: NodeType; - name: string; - tokens: CSSToken[]; - }; - tokens: CSSToken[]; - }; - before: CSSToken[]; - after: CSSToken[]; - }; - isMediaFeature(): this is MediaFeature; - static isMediaFeature(x: unknown): x is MediaFeature; -} -type MediaFeatureWalkerEntry = MediaFeaturePlainWalkerEntry | MediaFeatureRangeWalkerEntry | MediaFeaturePlain | MediaFeatureBoolean | MediaFeatureRange; -type MediaFeatureWalkerParent = MediaFeaturePlainWalkerParent | MediaFeatureRangeWalkerParent | MediaFeature; -export declare function parseMediaFeature(simpleBlock: SimpleBlockNode, before?: Array, after?: Array): false | MediaFeature; -export declare function newMediaFeatureBoolean(name: string): MediaFeature; -export declare function newMediaFeaturePlain(name: string, ...value: Array): MediaFeature; -export {}; diff --git a/packages/media-query-list-parser/dist/nodes/media-in-parens.d.ts b/packages/media-query-list-parser/dist/nodes/media-in-parens.d.ts deleted file mode 100644 index 904a0725e..000000000 --- a/packages/media-query-list-parser/dist/nodes/media-in-parens.d.ts +++ /dev/null @@ -1,41 +0,0 @@ -import { ComponentValue, ContainerNode } from '@csstools/css-parser-algorithms'; -import { CSSToken } from '@csstools/css-tokenizer'; -import { GeneralEnclosed } from './general-enclosed'; -import { MediaAnd } from './media-and'; -import { MediaCondition } from './media-condition'; -import { MediaConditionList } from './media-condition-list'; -import { MediaFeature } from './media-feature'; -import { MediaFeatureBoolean } from './media-feature-boolean'; -import { MediaFeatureName } from './media-feature-name'; -import { MediaFeaturePlain } from './media-feature-plain'; -import { MediaFeatureRange } from './media-feature-range'; -import { MediaFeatureValue } from './media-feature-value'; -import { NodeType } from '../util/node-type'; -import { MediaNot } from './media-not'; -import { MediaOr } from './media-or'; -export declare class MediaInParens { - type: NodeType; - media: MediaCondition | MediaFeature | GeneralEnclosed; - before: Array; - after: Array; - constructor(media: MediaCondition | MediaFeature | GeneralEnclosed, before?: Array, after?: Array); - tokens(): Array; - toString(): string; - indexOf(item: MediaCondition | MediaFeature | GeneralEnclosed): number | string; - at(index: number | string): MediaCondition | MediaFeature | GeneralEnclosed | undefined; - walk>(cb: (entry: { - node: MediaInParensWalkerEntry; - parent: MediaInParensWalkerParent; - state?: T; - }, index: number | string) => boolean | void, state?: T): false | undefined; - toJSON(): { - type: NodeType; - media: unknown; - before: CSSToken[]; - after: CSSToken[]; - }; - isMediaInParens(): this is MediaInParens; - static isMediaInParens(x: unknown): x is 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; diff --git a/packages/media-query-list-parser/dist/nodes/media-not.d.ts b/packages/media-query-list-parser/dist/nodes/media-not.d.ts deleted file mode 100644 index 2bedcaa31..000000000 --- a/packages/media-query-list-parser/dist/nodes/media-not.d.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { CSSToken } from '@csstools/css-tokenizer'; -import { MediaInParens, MediaInParensWalkerEntry, MediaInParensWalkerParent } from './media-in-parens'; -import { NodeType } from '../util/node-type'; -export declare class MediaNot { - type: NodeType; - modifier: Array; - media: MediaInParens; - constructor(modifier: Array, media: MediaInParens); - tokens(): Array; - toString(): string; - indexOf(item: MediaInParens): number | string; - at(index: number | string): MediaInParens | undefined; - walk>(cb: (entry: { - node: MediaNotWalkerEntry; - parent: MediaNotWalkerParent; - state?: T; - }, index: number | string) => boolean | void, state?: T): false | undefined; - toJSON(): { - type: NodeType; - modifier: CSSToken[]; - media: { - type: NodeType; - media: unknown; - before: CSSToken[]; - after: CSSToken[]; - }; - }; - isMediaNot(): this is MediaNot; - static isMediaNot(x: unknown): x is MediaNot; -} -export type MediaNotWalkerEntry = MediaInParensWalkerEntry | MediaInParens; -export type MediaNotWalkerParent = MediaInParensWalkerParent | MediaNot; diff --git a/packages/media-query-list-parser/dist/nodes/media-or.d.ts b/packages/media-query-list-parser/dist/nodes/media-or.d.ts deleted file mode 100644 index 4459412d4..000000000 --- a/packages/media-query-list-parser/dist/nodes/media-or.d.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { CSSToken } from '@csstools/css-tokenizer'; -import { MediaInParens, MediaInParensWalkerEntry, MediaInParensWalkerParent } from './media-in-parens'; -import { NodeType } from '../util/node-type'; -export declare class MediaOr { - type: NodeType; - modifier: Array; - media: MediaInParens; - constructor(modifier: Array, media: MediaInParens); - tokens(): Array; - toString(): string; - indexOf(item: MediaInParens): number | string; - at(index: number | string): MediaInParens | undefined; - walk>(cb: (entry: { - node: MediaOrWalkerEntry; - parent: MediaOrWalkerParent; - state?: T; - }, index: number | string) => boolean | void, state?: T): false | undefined; - toJSON(): { - type: NodeType; - modifier: CSSToken[]; - media: { - type: NodeType; - media: unknown; - before: CSSToken[]; - after: CSSToken[]; - }; - }; - isMediaOr(): this is MediaOr; - static isMediaOr(x: unknown): x is MediaOr; -} -export type MediaOrWalkerEntry = MediaInParensWalkerEntry | MediaInParens; -export type MediaOrWalkerParent = MediaInParensWalkerParent | MediaOr; diff --git a/packages/media-query-list-parser/dist/nodes/media-query-modifier.d.ts b/packages/media-query-list-parser/dist/nodes/media-query-modifier.d.ts deleted file mode 100644 index df9733cb5..000000000 --- a/packages/media-query-list-parser/dist/nodes/media-query-modifier.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { TokenIdent } from '@csstools/css-tokenizer'; -export declare enum MediaQueryModifier { - Not = "not", - Only = "only" -} -export declare function modifierFromToken(token: TokenIdent): MediaQueryModifier | false; diff --git a/packages/media-query-list-parser/dist/nodes/media-query.d.ts b/packages/media-query-list-parser/dist/nodes/media-query.d.ts deleted file mode 100644 index ad1e32fa4..000000000 --- a/packages/media-query-list-parser/dist/nodes/media-query.d.ts +++ /dev/null @@ -1,84 +0,0 @@ -import { ComponentValue } from '@csstools/css-parser-algorithms'; -import { CSSToken } from '@csstools/css-tokenizer'; -import { NodeType } from '../util/node-type'; -import { MediaCondition, MediaConditionWalkerEntry, MediaConditionWalkerParent } from './media-condition'; -export type MediaQuery = MediaQueryWithType | MediaQueryWithoutType | MediaQueryInvalid; -export declare class MediaQueryWithType { - type: NodeType; - modifier: Array; - mediaType: Array; - and: Array | undefined; - media: MediaCondition | undefined; - constructor(modifier: Array, mediaType: Array, and?: Array | undefined, media?: MediaCondition | undefined); - getModifier(): string; - negateQuery(): MediaQuery; - getMediaType(): string; - tokens(): Array; - toString(): string; - indexOf(item: MediaCondition): number | string; - at(index: number | string): MediaCondition | undefined; - walk>(cb: (entry: { - node: MediaQueryWithTypeWalkerEntry; - parent: MediaQueryWithTypeWalkerParent; - state?: T; - }, index: number | string) => boolean | void, state?: T): false | undefined; - toJSON(): { - type: NodeType; - string: string; - modifier: CSSToken[]; - mediaType: CSSToken[]; - and: CSSToken[] | undefined; - media: MediaCondition | undefined; - }; - isMediaQueryWithType(): this is MediaQueryWithType; - static isMediaQueryWithType(x: unknown): x is MediaQueryWithType; -} -type MediaQueryWithTypeWalkerEntry = MediaConditionWalkerEntry | MediaCondition; -type MediaQueryWithTypeWalkerParent = MediaConditionWalkerParent | MediaQueryWithType; -export declare class MediaQueryWithoutType { - type: NodeType; - media: MediaCondition; - constructor(media: MediaCondition); - negateQuery(): MediaQuery; - tokens(): Array; - toString(): string; - indexOf(item: MediaCondition): number | string; - at(index: number | string): MediaCondition | undefined; - walk>(cb: (entry: { - node: MediaQueryWithoutTypeWalkerEntry; - parent: MediaQueryWithoutTypeWalkerParent; - state?: T; - }, index: number | string) => boolean | void, state?: T): false | undefined; - toJSON(): { - type: NodeType; - string: string; - media: MediaCondition; - }; - isMediaQueryWithoutType(): this is MediaQueryWithoutType; - static isMediaQueryWithoutType(x: unknown): x is MediaQueryWithoutType; -} -type MediaQueryWithoutTypeWalkerEntry = MediaConditionWalkerEntry | MediaCondition; -type MediaQueryWithoutTypeWalkerParent = MediaConditionWalkerParent | MediaQueryWithoutType; -export declare class MediaQueryInvalid { - type: NodeType; - media: Array; - constructor(media: Array); - negateQuery(): MediaQuery; - tokens(): Array; - toString(): string; - walk>(cb: (entry: { - node: MediaQueryInvalidWalkerEntry; - parent: MediaQueryInvalidWalkerParent; - state?: T; - }, index: number | string) => boolean | void, state?: T): false | undefined; - toJSON(): { - type: NodeType; - string: string; - media: ComponentValue[]; - }; - isMediaQueryInvalid(): this is MediaQueryInvalid; - static isMediaQueryInvalid(x: unknown): x is MediaQueryInvalid; -} -type MediaQueryInvalidWalkerEntry = ComponentValue; -type MediaQueryInvalidWalkerParent = ComponentValue | MediaQueryInvalid; -export {}; diff --git a/packages/media-query-list-parser/dist/nodes/media-type.d.ts b/packages/media-query-list-parser/dist/nodes/media-type.d.ts deleted file mode 100644 index b7924b760..000000000 --- a/packages/media-query-list-parser/dist/nodes/media-type.d.ts +++ /dev/null @@ -1,24 +0,0 @@ -import { TokenIdent } from '@csstools/css-tokenizer'; -export declare enum MediaType { - /** Always matches */ - All = "all", - Print = "print", - Screen = "screen", - /** Never matches */ - Tty = "tty", - /** Never matches */ - Tv = "tv", - /** Never matches */ - Projection = "projection", - /** Never matches */ - Handheld = "handheld", - /** Never matches */ - Braille = "braille", - /** Never matches */ - Embossed = "embossed", - /** Never matches */ - Aural = "aural", - /** Never matches */ - Speech = "speech" -} -export declare function typeFromToken(token: TokenIdent): MediaType | false; diff --git a/packages/media-query-list-parser/dist/parser/parse-custom-media.d.ts b/packages/media-query-list-parser/dist/parser/parse-custom-media.d.ts deleted file mode 100644 index 1f747f8e1..000000000 --- a/packages/media-query-list-parser/dist/parser/parse-custom-media.d.ts +++ /dev/null @@ -1,9 +0,0 @@ -import { CSSToken, ParseError } from '@csstools/css-tokenizer'; -import { CustomMedia } from '../nodes/custom-media'; -type Options = { - preserveInvalidMediaQueries?: boolean; - onParseError?: (error: ParseError) => void; -}; -export declare function parseCustomMediaFromTokens(tokens: Array, options?: Options): CustomMedia | false; -export declare function parseCustomMedia(source: string, options?: Options): CustomMedia | false; -export {}; diff --git a/packages/media-query-list-parser/dist/parser/parse-media-query.d.ts b/packages/media-query-list-parser/dist/parser/parse-media-query.d.ts deleted file mode 100644 index 4c00cb76a..000000000 --- a/packages/media-query-list-parser/dist/parser/parse-media-query.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -import { ComponentValue } from '@csstools/css-parser-algorithms'; -import { MediaQuery } from '../nodes/media-query'; -export declare function parseMediaQuery(componentValues: Array): MediaQuery | false; diff --git a/packages/media-query-list-parser/dist/parser/parse.d.ts b/packages/media-query-list-parser/dist/parser/parse.d.ts deleted file mode 100644 index b208e00a3..000000000 --- a/packages/media-query-list-parser/dist/parser/parse.d.ts +++ /dev/null @@ -1,9 +0,0 @@ -import { CSSToken, ParseError } from '@csstools/css-tokenizer'; -import { MediaQuery } from '../nodes/media-query'; -type Options = { - preserveInvalidMediaQueries?: boolean; - onParseError?: (error: ParseError) => void; -}; -export declare function parseFromTokens(tokens: Array, options?: Options): MediaQuery[]; -export declare function parse(source: string, options?: Options): MediaQuery[]; -export {}; diff --git a/packages/media-query-list-parser/dist/util/clone-media-query.d.ts b/packages/media-query-list-parser/dist/util/clone-media-query.d.ts deleted file mode 100644 index e0702c235..000000000 --- a/packages/media-query-list-parser/dist/util/clone-media-query.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import { MediaQueryInvalid, MediaQueryWithoutType, MediaQueryWithType } from '../nodes/media-query'; -export declare function cloneMediaQuery(x: T): T; diff --git a/packages/media-query-list-parser/dist/util/component-value-is.d.ts b/packages/media-query-list-parser/dist/util/component-value-is.d.ts deleted file mode 100644 index f0763807b..000000000 --- a/packages/media-query-list-parser/dist/util/component-value-is.d.ts +++ /dev/null @@ -1,5 +0,0 @@ -import { ComponentValue } from '@csstools/css-parser-algorithms'; -export declare function isNumber(componentValue: ComponentValue): boolean; -export declare function isDimension(componentValue: ComponentValue): boolean; -export declare function isIdent(componentValue: ComponentValue): boolean; -export declare function isEnvironmentVariable(componentValue: ComponentValue): boolean; diff --git a/packages/media-query-list-parser/dist/util/node-type.d.ts b/packages/media-query-list-parser/dist/util/node-type.d.ts deleted file mode 100644 index 935e6eb54..000000000 --- a/packages/media-query-list-parser/dist/util/node-type.d.ts +++ /dev/null @@ -1,22 +0,0 @@ -export declare enum NodeType { - CustomMedia = "custom-media", - GeneralEnclosed = "general-enclosed", - MediaAnd = "media-and", - MediaCondition = "media-condition", - MediaConditionListWithAnd = "media-condition-list-and", - MediaConditionListWithOr = "media-condition-list-or", - MediaFeature = "media-feature", - MediaFeatureBoolean = "mf-boolean", - MediaFeatureName = "mf-name", - MediaFeaturePlain = "mf-plain", - MediaFeatureRangeNameValue = "mf-range-name-value", - MediaFeatureRangeValueName = "mf-range-value-name", - MediaFeatureRangeValueNameValue = "mf-range-value-name-value", - MediaFeatureValue = "mf-value", - MediaInParens = "media-in-parens", - MediaNot = "media-not", - MediaOr = "media-or", - MediaQueryWithType = "media-query-with-type", - MediaQueryWithoutType = "media-query-without-type", - MediaQueryInvalid = "media-query-invalid" -} diff --git a/packages/media-query-list-parser/dist/util/to-lower-case-a-z.d.ts b/packages/media-query-list-parser/dist/util/to-lower-case-a-z.d.ts deleted file mode 100644 index 396b252e7..000000000 --- a/packages/media-query-list-parser/dist/util/to-lower-case-a-z.d.ts +++ /dev/null @@ -1 +0,0 @@ -export declare function toLowerCaseAZ(x: string): string; diff --git a/packages/media-query-list-parser/dist/util/type-predicates.d.ts b/packages/media-query-list-parser/dist/util/type-predicates.d.ts deleted file mode 100644 index 2313f29b0..000000000 --- a/packages/media-query-list-parser/dist/util/type-predicates.d.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { GeneralEnclosed } from '../nodes/general-enclosed'; -import { MediaAnd } from '../nodes/media-and'; -import { MediaCondition } from '../nodes/media-condition'; -import { MediaConditionList, MediaConditionListWithAnd, MediaConditionListWithOr } from '../nodes/media-condition-list'; -import { MediaFeature } from '../nodes/media-feature'; -import { MediaFeatureBoolean } from '../nodes/media-feature-boolean'; -import { MediaFeatureName } from '../nodes/media-feature-name'; -import { MediaFeaturePlain } from '../nodes/media-feature-plain'; -import { MediaFeatureRange, MediaFeatureRangeNameValue, MediaFeatureRangeValueName, MediaFeatureRangeValueNameValue } from '../nodes/media-feature-range'; -import { MediaFeatureValue } from '../nodes/media-feature-value'; -import { MediaInParens } from '../nodes/media-in-parens'; -import { MediaNot } from '../nodes/media-not'; -import { MediaOr } from '../nodes/media-or'; -import { MediaQuery, MediaQueryInvalid, MediaQueryWithoutType, MediaQueryWithType } from '../nodes/media-query'; -export declare function isCustomMedia(x: unknown): x is GeneralEnclosed; -export declare function isGeneralEnclosed(x: unknown): x is GeneralEnclosed; -export declare function isMediaAnd(x: unknown): x is MediaAnd; -export declare function isMediaConditionList(x: unknown): x is MediaConditionList; -export declare function isMediaConditionListWithAnd(x: unknown): x is MediaConditionListWithAnd; -export declare function isMediaConditionListWithOr(x: unknown): x is MediaConditionListWithOr; -export declare function isMediaCondition(x: unknown): x is MediaCondition; -export declare function isMediaFeatureBoolean(x: unknown): x is MediaFeatureBoolean; -export declare function isMediaFeatureName(x: unknown): x is MediaFeatureName; -export declare function isMediaFeatureValue(x: unknown): x is MediaFeatureValue; -export declare function isMediaFeaturePlain(x: unknown): x is MediaFeaturePlain; -export declare function isMediaFeatureRange(x: unknown): x is MediaFeatureRange; -export declare function isMediaFeatureRangeNameValue(x: unknown): x is MediaFeatureRangeNameValue; -export declare function isMediaFeatureRangeValueName(x: unknown): x is MediaFeatureRangeValueName; -export declare function isMediaFeatureRangeValueNameValue(x: unknown): x is MediaFeatureRangeValueNameValue; -export declare function isMediaFeature(x: unknown): x is MediaFeature; -export declare function isMediaInParens(x: unknown): x is MediaInParens; -export declare function isMediaNot(x: unknown): x is MediaNot; -export declare function isMediaOr(x: unknown): x is MediaOr; -export declare function isMediaQuery(x: unknown): x is MediaQuery; -export declare function isMediaQueryWithType(x: unknown): x is MediaQueryWithType; -export declare function isMediaQueryWithoutType(x: unknown): x is MediaQueryWithoutType; -export declare function isMediaQueryInvalid(x: unknown): x is MediaQueryInvalid; diff --git a/packages/media-query-list-parser/package.json b/packages/media-query-list-parser/package.json index d9037c742..1cb40a3e7 100644 --- a/packages/media-query-list-parser/package.json +++ b/packages/media-query-list-parser/package.json @@ -27,15 +27,18 @@ "engines": { "node": "^14 || ^16 || >=18" }, + "type": "module", "main": "dist/index.cjs", "module": "dist/index.mjs", - "types": "dist/index.d.ts", "exports": { ".": { - "types": "./dist/index.d.ts", - "import": "./dist/index.mjs", - "require": "./dist/index.cjs", - "default": "./dist/index.mjs" + "import": { + "types": "./dist/index.d.ts", + "default": "./dist/index.mjs" + }, + "require": { + "default": "./dist/index.cjs" + } } }, "files": [ diff --git a/packages/media-query-list-parser/src/index.ts b/packages/media-query-list-parser/src/index.ts index 58bb55f0a..7b88c108f 100644 --- a/packages/media-query-list-parser/src/index.ts +++ b/packages/media-query-list-parser/src/index.ts @@ -1,6 +1,9 @@ export { parse, parseFromTokens } from './parser/parse'; export { parseCustomMedia, parseCustomMediaFromTokens } from './parser/parse-custom-media'; + export { NodeType } from './util/node-type'; +export { cloneMediaQuery } from './util/clone-media-query'; + export { isCustomMedia, isGeneralEnclosed, @@ -27,26 +30,50 @@ export { isMediaQueryWithoutType, } from './util/type-predicates'; -export type { MediaConditionList } from './nodes/media-condition-list'; +export type { MediaConditionList, MediaConditionListWithAndWalkerEntry, MediaConditionListWithAndWalkerParent, MediaConditionListWithOrWalkerEntry, MediaConditionListWithOrWalkerParent } from './nodes/media-condition-list'; +export { MediaConditionListWithAnd, MediaConditionListWithOr } from './nodes/media-condition-list'; + export type { MediaFeatureComparison } from './nodes/media-feature-comparison'; export type { MediaFeatureRange } from './nodes/media-feature-range'; export type { MediaQuery } from './nodes/media-query'; export { CustomMedia } from './nodes/custom-media'; + +export type { GeneralEnclosedWalkerEntry, GeneralEnclosedWalkerParent } from './nodes/general-enclosed'; export { GeneralEnclosed } from './nodes/general-enclosed'; + +export type { MediaAndWalkerEntry, MediaAndWalkerParent } from './nodes/media-and'; export { MediaAnd } from './nodes/media-and'; + +export type { MediaConditionWalkerEntry, MediaConditionWalkerParent } from './nodes/media-condition'; export { MediaCondition } from './nodes/media-condition'; -export { MediaConditionListWithAnd, MediaConditionListWithOr } from './nodes/media-condition-list'; + +export type { MediaFeatureWalkerEntry, MediaFeatureWalkerParent } from './nodes/media-feature'; export { MediaFeature, newMediaFeatureBoolean, newMediaFeaturePlain } from './nodes/media-feature'; -export { MediaFeatureBoolean } from './nodes/media-feature-boolean'; -export { MediaFeatureEQ, MediaFeatureGT, MediaFeatureLT, invertComparison, matchesComparison, comparisonFromTokens } from './nodes/media-feature-comparison'; -export { MediaFeatureName } from './nodes/media-feature-name'; + +export type { MediaFeaturePlainWalkerEntry, MediaFeaturePlainWalkerParent } from './nodes/media-feature-plain'; export { MediaFeaturePlain } from './nodes/media-feature-plain'; + +export type { MediaFeatureRangeWalkerEntry, MediaFeatureRangeWalkerParent } from './nodes/media-feature-range'; export { MediaFeatureRangeNameValue, MediaFeatureRangeValueName, MediaFeatureRangeValueNameValue } from './nodes/media-feature-range'; + +export type { MediaFeatureValueWalkerEntry, MediaFeatureValueWalkerParent } from './nodes/media-feature-value'; export { MediaFeatureValue, matchesRatio, matchesRatioExactly } from './nodes/media-feature-value'; + +export type { MediaInParensWalkerEntry, MediaInParensWalkerParent } from './nodes/media-in-parens'; export { MediaInParens } from './nodes/media-in-parens'; + +export type { MediaNotWalkerEntry, MediaNotWalkerParent } from './nodes/media-not'; export { MediaNot } from './nodes/media-not'; -export { MediaOr } from './nodes/media-or'; -export { MediaQueryModifier, modifierFromToken } from './nodes/media-query-modifier'; + +export type { MediaOrWalkerEntry, MediaOrWalkerParent } from './nodes/media-or'; +export { MediaOr } from './nodes/media-or'; + +export type { MediaQueryInvalidWalkerEntry, MediaQueryInvalidWalkerParent, MediaQueryWithTypeWalkerEntry, MediaQueryWithTypeWalkerParent, MediaQueryWithoutTypeWalkerEntry, MediaQueryWithoutTypeWalkerParent } from './nodes/media-query'; export { MediaQueryWithType, MediaQueryWithoutType, MediaQueryInvalid } from './nodes/media-query'; + +export { MediaFeatureBoolean } from './nodes/media-feature-boolean'; +export { MediaFeatureEQ, MediaFeatureGT, MediaFeatureLT, invertComparison, matchesComparison, comparisonFromTokens } from './nodes/media-feature-comparison'; +export { MediaFeatureName } from './nodes/media-feature-name'; +export { MediaQueryModifier, modifierFromToken } from './nodes/media-query-modifier'; + export { MediaType, typeFromToken } from './nodes/media-type'; -export { cloneMediaQuery } from './util/clone-media-query'; diff --git a/packages/media-query-list-parser/src/nodes/general-enclosed.ts b/packages/media-query-list-parser/src/nodes/general-enclosed.ts index b0ceb67de..e55672f11 100644 --- a/packages/media-query-list-parser/src/nodes/general-enclosed.ts +++ b/packages/media-query-list-parser/src/nodes/general-enclosed.ts @@ -74,5 +74,5 @@ export class GeneralEnclosed { } } -type GeneralEnclosedWalkerEntry = ComponentValue; -type GeneralEnclosedWalkerParent = ContainerNode | GeneralEnclosed; +export type GeneralEnclosedWalkerEntry = ComponentValue; +export type GeneralEnclosedWalkerParent = ContainerNode | GeneralEnclosed; diff --git a/packages/media-query-list-parser/src/nodes/media-feature.ts b/packages/media-query-list-parser/src/nodes/media-feature.ts index 28b433fbf..0caf57005 100644 --- a/packages/media-query-list-parser/src/nodes/media-feature.ts +++ b/packages/media-query-list-parser/src/nodes/media-feature.ts @@ -97,8 +97,8 @@ export class MediaFeature { } } -type MediaFeatureWalkerEntry = MediaFeaturePlainWalkerEntry | MediaFeatureRangeWalkerEntry | MediaFeaturePlain | MediaFeatureBoolean | MediaFeatureRange; -type MediaFeatureWalkerParent = MediaFeaturePlainWalkerParent | MediaFeatureRangeWalkerParent | MediaFeature; +export type MediaFeatureWalkerEntry = MediaFeaturePlainWalkerEntry | MediaFeatureRangeWalkerEntry | MediaFeaturePlain | MediaFeatureBoolean | MediaFeatureRange; +export type MediaFeatureWalkerParent = MediaFeaturePlainWalkerParent | MediaFeatureRangeWalkerParent | MediaFeature; export function parseMediaFeature(simpleBlock: SimpleBlockNode, before: Array = [], after: Array = []) { if (simpleBlock.startToken[0] !== TokenType.OpenParen) { diff --git a/packages/media-query-list-parser/src/nodes/media-query.ts b/packages/media-query-list-parser/src/nodes/media-query.ts index 9d034f5b3..46e1f8ebb 100644 --- a/packages/media-query-list-parser/src/nodes/media-query.ts +++ b/packages/media-query-list-parser/src/nodes/media-query.ts @@ -169,8 +169,8 @@ export class MediaQueryWithType { } } -type MediaQueryWithTypeWalkerEntry = MediaConditionWalkerEntry | MediaCondition; -type MediaQueryWithTypeWalkerParent = MediaConditionWalkerParent | MediaQueryWithType; +export type MediaQueryWithTypeWalkerEntry = MediaConditionWalkerEntry | MediaCondition; +export type MediaQueryWithTypeWalkerParent = MediaConditionWalkerParent | MediaQueryWithType; export class MediaQueryWithoutType { type = NodeType.MediaQueryWithoutType; @@ -286,8 +286,8 @@ export class MediaQueryWithoutType { } } -type MediaQueryWithoutTypeWalkerEntry = MediaConditionWalkerEntry | MediaCondition; -type MediaQueryWithoutTypeWalkerParent = MediaConditionWalkerParent | MediaQueryWithoutType; +export type MediaQueryWithoutTypeWalkerEntry = MediaConditionWalkerEntry | MediaCondition; +export type MediaQueryWithoutTypeWalkerParent = MediaConditionWalkerParent | MediaQueryWithoutType; export class MediaQueryInvalid { type = NodeType.MediaQueryInvalid; @@ -370,5 +370,5 @@ export class MediaQueryInvalid { } } -type MediaQueryInvalidWalkerEntry = ComponentValue; -type MediaQueryInvalidWalkerParent = ComponentValue | MediaQueryInvalid; +export type MediaQueryInvalidWalkerEntry = ComponentValue; +export type MediaQueryInvalidWalkerParent = ComponentValue | MediaQueryInvalid; diff --git a/packages/media-query-list-parser/src/parser/parse-custom-media.ts b/packages/media-query-list-parser/src/parser/parse-custom-media.ts index dc4bdd4a2..3858bf160 100644 --- a/packages/media-query-list-parser/src/parser/parse-custom-media.ts +++ b/packages/media-query-list-parser/src/parser/parse-custom-media.ts @@ -3,12 +3,13 @@ import { CustomMedia } from '../nodes/custom-media'; import { toLowerCaseAZ } from '../util/to-lower-case-a-z'; import { parseFromTokens } from './parse'; -type Options = { - preserveInvalidMediaQueries?: boolean, - onParseError?: (error: ParseError) => void -} - -export function parseCustomMediaFromTokens(tokens: Array, options?: Options): CustomMedia | false { +export function parseCustomMediaFromTokens( + tokens: Array, + options?: { + preserveInvalidMediaQueries?: boolean, + onParseError?: (error: ParseError) => void + }, +): CustomMedia | false { let name: Array = []; let remainder = tokens; for (let i = 0; i < tokens.length; i++) { @@ -66,7 +67,13 @@ export function parseCustomMediaFromTokens(tokens: Array, options?: Op return new CustomMedia(name, parseFromTokens(cloneTokens(remainder), options)); } -export function parseCustomMedia(source: string, options?: Options): CustomMedia | false { +export function parseCustomMedia( + source: string, + options?: { + preserveInvalidMediaQueries?: boolean, + onParseError?: (error: ParseError) => void + }, +): CustomMedia | false { const t = tokenizer({ css: source }, { onParseError: options?.onParseError, }); diff --git a/packages/media-query-list-parser/src/parser/parse.ts b/packages/media-query-list-parser/src/parser/parse.ts index 056667eb2..55088b7f2 100644 --- a/packages/media-query-list-parser/src/parser/parse.ts +++ b/packages/media-query-list-parser/src/parser/parse.ts @@ -3,12 +3,13 @@ import { CSSToken, tokenizer, ParseError } from '@csstools/css-tokenizer'; import { MediaQuery, MediaQueryInvalid } from '../nodes/media-query'; import { parseMediaQuery } from './parse-media-query'; -type Options = { - preserveInvalidMediaQueries?: boolean, - onParseError?: (error: ParseError) => void -} - -export function parseFromTokens(tokens: Array, options?: Options) { +export function parseFromTokens( + tokens: Array, + options?: { + preserveInvalidMediaQueries?: boolean, + onParseError?: (error: ParseError) => void + }, +) { const componentValuesLists = parseCommaSeparatedListOfComponentValues(tokens, { onParseError: options?.onParseError, }); @@ -23,7 +24,13 @@ export function parseFromTokens(tokens: Array, options?: Options) { }).filter((x) => !!x) as Array; } -export function parse(source: string, options?: Options) { +export function parse( + source: string, + options?: { + preserveInvalidMediaQueries?: boolean, + onParseError?: (error: ParseError) => void + }, +) { const t = tokenizer({ css: source }, { onParseError: options?.onParseError, }); diff --git a/packages/postcss-tape/CHANGELOG.md b/packages/postcss-tape/CHANGELOG.md index 5912b4b0a..5f6af4b4d 100644 --- a/packages/postcss-tape/CHANGELOG.md +++ b/packages/postcss-tape/CHANGELOG.md @@ -1,5 +1,9 @@ # Changes to PostCSS Tape +### Unreleased (patch) + +- Fix type definitions + ### 3.0.1 _August 28, 2023_ diff --git a/packages/postcss-tape/api-extractor.json b/packages/postcss-tape/api-extractor.json new file mode 100644 index 000000000..42058be51 --- /dev/null +++ b/packages/postcss-tape/api-extractor.json @@ -0,0 +1,4 @@ +{ + "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json", + "extends": "../../api-extractor.json" +} diff --git a/packages/postcss-tape/dist/format-asserts.d.ts b/packages/postcss-tape/dist/format-asserts.d.ts deleted file mode 100644 index 6750e2ce8..000000000 --- a/packages/postcss-tape/dist/format-asserts.d.ts +++ /dev/null @@ -1,5 +0,0 @@ -import type { Warning } from 'postcss'; -import type { TestCaseOptions } from './test-case-options'; -export declare const dashesSeparator = "----------------------------------------"; -export declare function formatCSSAssertError(testCaseLabel: string, testCaseOptions: TestCaseOptions, err: Error, forGithubAnnotation?: boolean): string; -export declare function formatWarningsAssertError(testCaseLabel: string, testCaseOptions: TestCaseOptions, actual: Array, expected: number, forGithubAnnotation?: boolean): string; diff --git a/packages/postcss-tape/dist/github-annotations.d.ts b/packages/postcss-tape/dist/github-annotations.d.ts deleted file mode 100644 index 48161dab9..000000000 --- a/packages/postcss-tape/dist/github-annotations.d.ts +++ /dev/null @@ -1 +0,0 @@ -export declare function formatGitHubActionAnnotation(message: string, level?: string, options?: Record): string; diff --git a/packages/postcss-tape/dist/index.d.ts b/packages/postcss-tape/dist/index.d.ts index 25e66c357..2e4ad86eb 100644 --- a/packages/postcss-tape/dist/index.d.ts +++ b/packages/postcss-tape/dist/index.d.ts @@ -1,20 +1,52 @@ -import type { AtRule, Declaration, Rule } from 'postcss'; +import type { AtRule } from 'postcss'; +import type { Declaration } from 'postcss'; +import type { Plugin } from 'postcss'; import type { PluginCreator } from 'postcss'; -import type { TestCaseOptions } from './test-case-options'; -export declare function postcssTape(currentPlugin: PluginCreator): (options: Record) => Promise; +import type { Rule } from 'postcss'; + +export declare const atRuleClonerPlugin: { + postcssPlugin: string; + prepare(): { + AtRuleExit(atRule: AtRule): void; + }; +}; + export declare const declarationClonerPlugin: { postcssPlugin: string; Declaration(decl: Declaration): void; }; + +export declare function postcssTape(currentPlugin: PluginCreator): (options: Record) => Promise; + export declare const ruleClonerPlugin: { postcssPlugin: string; prepare(): { RuleExit(rule: Rule): void; }; }; -export declare const atRuleClonerPlugin: { - postcssPlugin: string; - prepare(): { - AtRuleExit(atRule: AtRule): void; - }; + +export declare type TestCaseOptions = { + /** Debug message */ + message?: string; + /** Plugin options. Only used if `plugins` is not specified. */ + options?: unknown; + /** Plugins to use. When specified the original plugin is not used. */ + plugins?: Array; + /** The expected number of warnings. */ + warnings?: number; + /** Expected exception */ + /** NOTE: plugins should not throw exceptions, this goes against best practices. Use `errors` instead. */ + exception?: RegExp; + /** Override the file name of the "expect" file. */ + expect?: string; + /** Override the file name of the "result" file. */ + result?: string; + /** Do something before the test is run. */ + before?: () => void; + /** Do something after the test is run. */ + after?: () => void | Promise; + /** Process the test cases with "postcss-html" as the syntax */ + postcssSyntaxHTML?: boolean; }; + +export { } diff --git a/packages/postcss-tape/dist/noop-plugin.d.ts b/packages/postcss-tape/dist/noop-plugin.d.ts deleted file mode 100644 index 458abbc03..000000000 --- a/packages/postcss-tape/dist/noop-plugin.d.ts +++ /dev/null @@ -1,8 +0,0 @@ -declare const noopPlugin: { - (): { - postcssPlugin: string; - Rule(): void; - }; - postcss: boolean; -}; -export default noopPlugin; diff --git a/packages/postcss-tape/dist/reduce-css-syntax-error.d.ts b/packages/postcss-tape/dist/reduce-css-syntax-error.d.ts deleted file mode 100644 index 0786db68e..000000000 --- a/packages/postcss-tape/dist/reduce-css-syntax-error.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import type { CssSyntaxError } from 'postcss'; -export declare function reduceInformationInCssSyntaxError(err: CssSyntaxError | TypeError): void; diff --git a/packages/postcss-tape/dist/test-case-options.d.ts b/packages/postcss-tape/dist/test-case-options.d.ts deleted file mode 100644 index c1dd65223..000000000 --- a/packages/postcss-tape/dist/test-case-options.d.ts +++ /dev/null @@ -1,24 +0,0 @@ -import type { Plugin } from 'postcss'; -export type TestCaseOptions = { - /** Debug message */ - message?: string; - /** Plugin options. Only used if `plugins` is not specified. */ - options?: unknown; - /** Plugins to use. When specified the original plugin is not used. */ - plugins?: Array; - /** The expected number of warnings. */ - warnings?: number; - /** Expected exception */ - /** NOTE: plugins should not throw exceptions, this goes against best practices. Use `errors` instead. */ - exception?: RegExp; - /** Override the file name of the "expect" file. */ - expect?: string; - /** Override the file name of the "result" file. */ - result?: string; - /** Do something before the test is run. */ - before?: () => void; - /** Do something after the test is run. */ - after?: () => void | Promise; - /** Process the test cases with "postcss-html" as the syntax */ - postcssSyntaxHTML?: boolean; -}; diff --git a/packages/postcss-tape/package.json b/packages/postcss-tape/package.json index a6d32c5bb..d1fdda04a 100644 --- a/packages/postcss-tape/package.json +++ b/packages/postcss-tape/package.json @@ -31,14 +31,18 @@ "engines": { "node": "^14 || ^16 || >=18" }, + "type": "module", "main": "dist/index.cjs", "module": "dist/index.mjs", - "types": "dist/index.d.ts", "exports": { ".": { - "import": "./dist/index.mjs", - "require": "./dist/index.cjs", - "default": "./dist/index.mjs" + "import": { + "types": "./dist/index.d.ts", + "default": "./dist/index.mjs" + }, + "require": { + "default": "./dist/index.cjs" + } } }, "files": [ diff --git a/packages/postcss-tape/src/index.ts b/packages/postcss-tape/src/index.ts index b687ae1a5..2fcf7a056 100644 --- a/packages/postcss-tape/src/index.ts +++ b/packages/postcss-tape/src/index.ts @@ -11,6 +11,7 @@ import { dashesSeparator, formatCSSAssertError, formatWarningsAssertError } from import { formatGitHubActionAnnotation } from './github-annotations'; import { reduceInformationInCssSyntaxError } from './reduce-css-syntax-error'; import { strict as assert } from 'assert'; +export type { TestCaseOptions } from './test-case-options'; const emitGitHubAnnotations = process.env.GITHUB_ACTIONS && process.env.ENABLE_ANNOTATIONS_FOR_NODE === 'true' && process.env.ENABLE_ANNOTATIONS_FOR_OS === 'true'; diff --git a/packages/postcss-tape/tsconfig.json b/packages/postcss-tape/tsconfig.json index aa6ec7ec0..fbc026620 100644 --- a/packages/postcss-tape/tsconfig.json +++ b/packages/postcss-tape/tsconfig.json @@ -2,6 +2,9 @@ "extends": "../../tsconfig.json", "compilerOptions": { "outDir": "dist", + "declarationDir": ".", + "skipLibCheck": true, }, "include": ["./src/**/*"], + "exclude": ["dist"], } diff --git a/packages/selector-specificity/api-extractor.json b/packages/selector-specificity/api-extractor.json new file mode 100644 index 000000000..42058be51 --- /dev/null +++ b/packages/selector-specificity/api-extractor.json @@ -0,0 +1,4 @@ +{ + "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json", + "extends": "../../api-extractor.json" +} diff --git a/packages/selector-specificity/dist/index.d.ts b/packages/selector-specificity/dist/index.d.ts index f92ce6d84..90606de18 100644 --- a/packages/selector-specificity/dist/index.d.ts +++ b/packages/selector-specificity/dist/index.d.ts @@ -1,8 +1,13 @@ import type { Node } from 'postcss-selector-parser'; -export type Specificity = { + +export declare function compare(s1: Specificity, s2: Specificity): number; + +export declare function selectorSpecificity(node: Node): Specificity; + +export declare type Specificity = { a: number; b: number; c: number; }; -export declare function compare(s1: Specificity, s2: Specificity): number; -export declare function selectorSpecificity(node: Node): Specificity; + +export { } diff --git a/packages/selector-specificity/dist/to-lower-case-a-z.d.ts b/packages/selector-specificity/dist/to-lower-case-a-z.d.ts deleted file mode 100644 index 396b252e7..000000000 --- a/packages/selector-specificity/dist/to-lower-case-a-z.d.ts +++ /dev/null @@ -1 +0,0 @@ -export declare function toLowerCaseAZ(x: string): string; diff --git a/packages/selector-specificity/package.json b/packages/selector-specificity/package.json index 36e083896..87174aa33 100644 --- a/packages/selector-specificity/package.json +++ b/packages/selector-specificity/package.json @@ -27,15 +27,18 @@ "engines": { "node": "^14 || ^16 || >=18" }, + "type": "module", "main": "dist/index.cjs", "module": "dist/index.mjs", - "types": "dist/index.d.ts", "exports": { ".": { - "types": "./dist/index.d.ts", - "import": "./dist/index.mjs", - "require": "./dist/index.cjs", - "default": "./dist/index.mjs" + "import": { + "types": "./dist/index.d.ts", + "default": "./dist/index.mjs" + }, + "require": { + "default": "./dist/index.cjs" + } } }, "files": [ diff --git a/plugin-packs/postcss-bundler/CHANGELOG.md b/plugin-packs/postcss-bundler/CHANGELOG.md index 740ede4a5..bb5a3ee34 100644 --- a/plugin-packs/postcss-bundler/CHANGELOG.md +++ b/plugin-packs/postcss-bundler/CHANGELOG.md @@ -2,7 +2,7 @@ ### Unreleased (patch) -- Small fixes in type definitions +- Fix type definitions ### 1.0.7 diff --git a/plugin-packs/postcss-bundler/api-extractor.json b/plugin-packs/postcss-bundler/api-extractor.json new file mode 100644 index 000000000..42058be51 --- /dev/null +++ b/plugin-packs/postcss-bundler/api-extractor.json @@ -0,0 +1,4 @@ +{ + "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json", + "extends": "../../api-extractor.json" +} diff --git a/plugin-packs/postcss-bundler/dist/index.cjs b/plugin-packs/postcss-bundler/dist/index.cjs index f5245dab4..358696f2d 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 l=/^charset$/i,u=/^import$/i,p=/^url$/i,m=/^layer$/i,d=/^supports$/i;function parseAtImport(s){const o=t.tokenize({css:s});if(2===o.length&&(o[0][0]===t.TokenType.String||o[0][0]===t.TokenType.URL)){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="",l="";for(let s=0;s{const i=parseStylesheet(e,t,s,o,n);var a,c;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 ${null==(a=i.charset.source)?void 0:a.input.file}\n ${r.charset.params} specified in ${null==(c=r.charset.source)?void 0:c.input.file}`);!r.charset&&i.charset&&(r.charset=i.charset),r.statements.push(...i.statements)})),r;let i,a,c=[],p=[];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{var n;if(isWarning(s)||isPreImportStatement(s)||null==(n=s.conditions)||!n.length)return;if(isImportStatement(s))return void(s.node.params=base64EncodedConditionalImport(s.fullUri,s.conditions));const r=s.nodes;if(!r.length)return;const i=r[0].parent;if(!i)return;const a=[];for(const e of s.conditions){if(void 0!==e.media){var c;const o=t({name:"media",params:e.media,source:(null==(c=s.importingNode)?void 0:c.source)??i.source});a.push(o)}if(void 0!==e.supports){var l;const o=t({name:"supports",params:"("+e.supports+")",source:(null==(l=s.importingNode)?void 0:l.source)??i.source});a.push(o)}if(void 0!==e.layer){var u;const o=t({name:"layer",params:e.layer,source:(null==(u=s.importingNode)?void 0:u.source)??i.source});a.push(o)}}const p=a[0];if(!p)return;for(let e=0;e{e.parent=void 0})),m.append(r),e.statements[o]={type:"nodes",nodes:[p],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&&(o[0][0]===t.TokenType.String||o[0][0]===t.TokenType.URL)){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.d.ts b/plugin-packs/postcss-bundler/dist/index.d.ts index 4ea42dfa5..38635f8f5 100644 --- a/plugin-packs/postcss-bundler/dist/index.d.ts +++ b/plugin-packs/postcss-bundler/dist/index.d.ts @@ -1,5 +1,9 @@ import type { PluginCreator } from 'postcss'; -/** postcss-bundler plugin options */ -export type pluginOptions = never; + declare const creator: PluginCreator; export default creator; + +/** postcss-bundler plugin options */ +export declare type pluginOptions = never; + +export { } diff --git a/plugin-packs/postcss-bundler/dist/index.mjs b/plugin-packs/postcss-bundler/dist/index.mjs index 21eec07af..2189a3f82 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 n,stringify as r}from"@csstools/css-parser-algorithms";import{tokenize as i,TokenType as a}from"@csstools/css-tokenizer";import c from"path";import l from"module";import p from"fs/promises";import u 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 m=/^data:text\/css(?:;(base64|plain))?,/i,d=/^data:text\/css;base64,/i,f=/^data:text\/css;plain,/i;function isValidDataURL(e){return!!e&&m.test(e)}const h=/^charset$/i,y=/^import$/i,g=/^url$/i,v=/^layer$/i,I=/^supports$/i;function parseAtImport(c){const l=i({css:c});if(2===l.length&&(l[0][0]===a.String||l[0][0]===a.URL)){let e=l[0][4].value;return e=stripHash(e),!!e&&{uri:e,fullUri:l[0][1]}}const p=e(l);let u,m,d,f="",h="";for(let e=0;e{const i=parseStylesheet(e,t,s,o,n);var a,c;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 ${null==(a=i.charset.source)?void 0:a.input.file}\n ${r.charset.params} specified in ${null==(c=r.charset.source)?void 0:c.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{var n;if(isWarning(s)||isPreImportStatement(s)||null==(n=s.conditions)||!n.length)return;if(isImportStatement(s))return void(s.node.params=base64EncodedConditionalImport(s.fullUri,s.conditions));const r=s.nodes;if(!r.length)return;const i=r[0].parent;if(!i)return;const a=[];for(const e of s.conditions){if(void 0!==e.media){var c;const o=t({name:"media",params:e.media,source:(null==(c=s.importingNode)?void 0:c.source)??i.source});a.push(o)}if(void 0!==e.supports){var l;const o=t({name:"supports",params:"("+e.supports+")",source:(null==(l=s.importingNode)?void 0:l.source)??i.source});a.push(o)}if(void 0!==e.layer){var p;const o=t({name:"layer",params:e.layer,source:(null==(p=s.importingNode)?void 0:p.source)??i.source});a.push(o)}}const u=a[0];if(!u)return;for(let e=0;e{e.parent=void 0})),m.append(r),e.statements[o]={type:"nodes",nodes:[u],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(),u()]});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,TokenType as a}from"@csstools/css-tokenizer";import c from"path";import p from"module";import u from"fs/promises";import l 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 m=/^data:text\/css(?:;(base64|plain))?,/i,d=/^data:text\/css;base64,/i,f=/^data:text\/css;plain,/i;function isValidDataURL(e){return!!e&&m.test(e)}const h=/^charset$/i,y=/^import$/i,g=/^url$/i,v=/^layer$/i,I=/^supports$/i;function parseAtImport(c){const p=i({css:c});if(2===p.length&&(p[0][0]===a.String||p[0][0]===a.URL)){let e=p[0][4].value;return e=stripHash(e),!!e&&{uri:e,fullUri:p[0][1]}}const u=e(p);let l,m,d,f="",h="";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(),l()]});creator.postcss=!0;export{creator as default}; diff --git a/plugin-packs/postcss-bundler/dist/postcss-import/index.d.ts b/plugin-packs/postcss-bundler/dist/postcss-import/index.d.ts deleted file mode 100644 index 89d75c8fd..000000000 --- a/plugin-packs/postcss-bundler/dist/postcss-import/index.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -import type { PluginCreator } from 'postcss'; -declare const creator: PluginCreator; -export default creator; diff --git a/plugin-packs/postcss-bundler/dist/postcss-import/lib/apply-conditions.d.ts b/plugin-packs/postcss-bundler/dist/postcss-import/lib/apply-conditions.d.ts deleted file mode 100644 index 76feb6286..000000000 --- a/plugin-packs/postcss-bundler/dist/postcss-import/lib/apply-conditions.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -import type { AtRule, AtRuleProps } from 'postcss'; -import { Stylesheet } from './statement'; -export declare function applyConditions(stylesheet: Stylesheet, atRule: (defaults?: AtRuleProps) => AtRule): void; diff --git a/plugin-packs/postcss-bundler/dist/postcss-import/lib/apply-styles.d.ts b/plugin-packs/postcss-bundler/dist/postcss-import/lib/apply-styles.d.ts deleted file mode 100644 index 24534276e..000000000 --- a/plugin-packs/postcss-bundler/dist/postcss-import/lib/apply-styles.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -import type { Document, Root } from 'postcss'; -import { Stylesheet } from './statement'; -export declare function applyStyles(stylesheet: Stylesheet, styles: Root | Document): void; diff --git a/plugin-packs/postcss-bundler/dist/postcss-import/lib/base64-encoded-import.d.ts b/plugin-packs/postcss-bundler/dist/postcss-import/lib/base64-encoded-import.d.ts deleted file mode 100644 index 8e8284439..000000000 --- a/plugin-packs/postcss-bundler/dist/postcss-import/lib/base64-encoded-import.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import { Condition } from './conditions'; -export declare function base64EncodedConditionalImport(prelude: string, conditions: Array): string; diff --git a/plugin-packs/postcss-bundler/dist/postcss-import/lib/conditions.d.ts b/plugin-packs/postcss-bundler/dist/postcss-import/lib/conditions.d.ts deleted file mode 100644 index ce1378ac2..000000000 --- a/plugin-packs/postcss-bundler/dist/postcss-import/lib/conditions.d.ts +++ /dev/null @@ -1,5 +0,0 @@ -export type Condition = { - layer?: string; - media?: string; - supports?: string; -}; diff --git a/plugin-packs/postcss-bundler/dist/postcss-import/lib/data-url.d.ts b/plugin-packs/postcss-bundler/dist/postcss-import/lib/data-url.d.ts deleted file mode 100644 index 54aa5ba4c..000000000 --- a/plugin-packs/postcss-bundler/dist/postcss-import/lib/data-url.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -export declare function isValidDataURL(url?: string): boolean; -export declare function dataURLContents(url: string): string; diff --git a/plugin-packs/postcss-bundler/dist/postcss-import/lib/format-import-prelude.d.ts b/plugin-packs/postcss-bundler/dist/postcss-import/lib/format-import-prelude.d.ts deleted file mode 100644 index 257b3fb06..000000000 --- a/plugin-packs/postcss-bundler/dist/postcss-import/lib/format-import-prelude.d.ts +++ /dev/null @@ -1 +0,0 @@ -export declare function formatImportPrelude(layer: string | undefined, media: string | undefined, supports: string | undefined): string; diff --git a/plugin-packs/postcss-bundler/dist/postcss-import/lib/load-content.d.ts b/plugin-packs/postcss-bundler/dist/postcss-import/lib/load-content.d.ts deleted file mode 100644 index 30257103e..000000000 --- a/plugin-packs/postcss-bundler/dist/postcss-import/lib/load-content.d.ts +++ /dev/null @@ -1 +0,0 @@ -export declare function loadContent(filename: string): Promise; diff --git a/plugin-packs/postcss-bundler/dist/postcss-import/lib/names.d.ts b/plugin-packs/postcss-bundler/dist/postcss-import/lib/names.d.ts deleted file mode 100644 index 94f8376a3..000000000 --- a/plugin-packs/postcss-bundler/dist/postcss-import/lib/names.d.ts +++ /dev/null @@ -1,5 +0,0 @@ -export declare const IS_CHARSET: RegExp; -export declare const IS_IMPORT: RegExp; -export declare const IS_URL: RegExp; -export declare const IS_LAYER: RegExp; -export declare const IS_SUPPORTS: RegExp; diff --git a/plugin-packs/postcss-bundler/dist/postcss-import/lib/noop-plugin.d.ts b/plugin-packs/postcss-bundler/dist/postcss-import/lib/noop-plugin.d.ts deleted file mode 100644 index 44b4ea068..000000000 --- a/plugin-packs/postcss-bundler/dist/postcss-import/lib/noop-plugin.d.ts +++ /dev/null @@ -1,8 +0,0 @@ -declare const noopPlugin: { - (): { - postcssPlugin: string; - Once(): void; - }; - postcss: boolean; -}; -export default noopPlugin; diff --git a/plugin-packs/postcss-bundler/dist/postcss-import/lib/parse-at-import.d.ts b/plugin-packs/postcss-bundler/dist/postcss-import/lib/parse-at-import.d.ts deleted file mode 100644 index 99a6bd2dd..000000000 --- a/plugin-packs/postcss-bundler/dist/postcss-import/lib/parse-at-import.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -export declare function parseAtImport(params: string): false | { - uri: string; - fullUri: string; - layer?: string; - media?: string; - supports?: string; -}; diff --git a/plugin-packs/postcss-bundler/dist/postcss-import/lib/parse-styles.d.ts b/plugin-packs/postcss-bundler/dist/postcss-import/lib/parse-styles.d.ts deleted file mode 100644 index 4ff88c005..000000000 --- a/plugin-packs/postcss-bundler/dist/postcss-import/lib/parse-styles.d.ts +++ /dev/null @@ -1,4 +0,0 @@ -import type { Document, Postcss, Result, Root, AtRule } from 'postcss'; -import { Stylesheet } from './statement'; -import { Condition } from './conditions'; -export declare function parseStyles(result: Result, styles: Root | Document, importingNode: AtRule | null, conditions: Array, from: Array, postcss: Postcss): Promise; diff --git a/plugin-packs/postcss-bundler/dist/postcss-import/lib/parse-stylesheet.d.ts b/plugin-packs/postcss-bundler/dist/postcss-import/lib/parse-stylesheet.d.ts deleted file mode 100644 index 55813909a..000000000 --- a/plugin-packs/postcss-bundler/dist/postcss-import/lib/parse-stylesheet.d.ts +++ /dev/null @@ -1,4 +0,0 @@ -import type { AtRule, Document, Result, Root } from 'postcss'; -import { Condition } from './conditions'; -import { Stylesheet } from './statement'; -export declare function parseStylesheet(result: Result, styles: Root | Document, importingNode: AtRule | null, conditions: Array, from: Array): Stylesheet; diff --git a/plugin-packs/postcss-bundler/dist/postcss-import/lib/post-process.d.ts b/plugin-packs/postcss-bundler/dist/postcss-import/lib/post-process.d.ts deleted file mode 100644 index 68c59c20b..000000000 --- a/plugin-packs/postcss-bundler/dist/postcss-import/lib/post-process.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -import type { AtRule, AtRuleProps } from 'postcss'; -import { Stylesheet } from './statement'; -export declare function postProcess(stylesheet: Stylesheet, atRule: (defaults?: AtRuleProps) => AtRule): void; diff --git a/plugin-packs/postcss-bundler/dist/postcss-import/lib/resolve-id.d.ts b/plugin-packs/postcss-bundler/dist/postcss-import/lib/resolve-id.d.ts deleted file mode 100644 index 09c13df9d..000000000 --- a/plugin-packs/postcss-bundler/dist/postcss-import/lib/resolve-id.d.ts +++ /dev/null @@ -1,4 +0,0 @@ -/// -import type { Node, Result } from 'postcss'; -export declare function resolveId(node: Node, require: NodeRequire, id: string, base: string): string; -export declare function createRequire(node: Node, result: Result): [NodeRequire, string, string] | []; diff --git a/plugin-packs/postcss-bundler/dist/postcss-import/lib/statement.d.ts b/plugin-packs/postcss-bundler/dist/postcss-import/lib/statement.d.ts deleted file mode 100644 index 0ce12e518..000000000 --- a/plugin-packs/postcss-bundler/dist/postcss-import/lib/statement.d.ts +++ /dev/null @@ -1,39 +0,0 @@ -import type { AtRule, ChildNode, Warning } from 'postcss'; -import { Condition } from './conditions'; -export type Stylesheet = { - charset?: AtRule; - statements: Array; -}; -export type Statement = ImportStatement | PreImportStatement | NodesStatement | Warning; -export type NodesStatement = { - type: 'nodes'; - nodes: Array; - conditions: Array; - from: Array; - parent?: Statement; - importingNode: AtRule | null; -}; -export type ImportStatement = { - type: 'import'; - uri: string; - fullUri: string; - node: AtRule; - conditions: Array; - from: Array; - parent?: Statement; - stylesheet?: Stylesheet; - importingNode: AtRule | null; -}; -type PreImportStatement = { - type: 'pre-import'; - node: ChildNode; - conditions: Array; - from: Array; - parent?: Statement; - importingNode: AtRule | null; -}; -export declare function isWarning(stmt: Statement): stmt is Warning; -export declare function isNodesStatement(stmt: Statement): stmt is NodesStatement; -export declare function isImportStatement(stmt: Statement): stmt is ImportStatement; -export declare function isPreImportStatement(stmt: Statement): stmt is PreImportStatement; -export {}; diff --git a/plugin-packs/postcss-bundler/package.json b/plugin-packs/postcss-bundler/package.json index 2a0fe48fc..f1efcabea 100644 --- a/plugin-packs/postcss-bundler/package.json +++ b/plugin-packs/postcss-bundler/package.json @@ -27,15 +27,18 @@ "engines": { "node": "^14 || ^16 || >=18" }, + "type": "module", "main": "dist/index.cjs", "module": "dist/index.mjs", - "types": "dist/index.d.ts", "exports": { ".": { - "types": "./dist/index.d.ts", - "import": "./dist/index.mjs", - "require": "./dist/index.cjs", - "default": "./dist/index.mjs" + "import": { + "types": "./dist/index.d.ts", + "default": "./dist/index.mjs" + }, + "require": { + "default": "./dist/index.cjs" + } } }, "files": [ diff --git a/plugin-packs/postcss-preset-env/CHANGELOG.md b/plugin-packs/postcss-preset-env/CHANGELOG.md index 84bc123de..449ab7c29 100644 --- a/plugin-packs/postcss-preset-env/CHANGELOG.md +++ b/plugin-packs/postcss-preset-env/CHANGELOG.md @@ -2,7 +2,7 @@ ### Unreleased (patch) -- Small fixes in type definitions +- Fix type definitions - Remove extraneous dependency on `postcss-value-parser` - Updated [`cssdb`](https://github.com/csstools/cssdb) to [`7.9.1`](https://github.com/csstools/cssdb/blob/main/CHANGELOG.md#791-december-11-2023) (patch) diff --git a/plugin-packs/postcss-preset-env/api-extractor.json b/plugin-packs/postcss-preset-env/api-extractor.json new file mode 100644 index 000000000..42058be51 --- /dev/null +++ b/plugin-packs/postcss-preset-env/api-extractor.json @@ -0,0 +1,4 @@ +{ + "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json", + "extends": "../../api-extractor.json" +} diff --git a/plugin-packs/postcss-preset-env/dist/index.d.ts b/plugin-packs/postcss-preset-env/dist/index.d.ts index 8ffa75d06..14c2a4f73 100644 --- a/plugin-packs/postcss-preset-env/dist/index.d.ts +++ b/plugin-packs/postcss-preset-env/dist/index.d.ts @@ -1,5 +1,296 @@ -import type { pluginOptions } from './options'; +import type autoprefixer from 'autoprefixer'; import type { PluginCreator } from 'postcss'; -export type { pluginOptions } from './options'; +import type { pluginOptions as pluginOptions_10 } from 'postcss-custom-media'; +import type { pluginOptions as pluginOptions_11 } from 'postcss-custom-properties'; +import type { pluginOptions as pluginOptions_12 } from 'postcss-custom-selectors'; +import type { pluginOptions as pluginOptions_13 } from 'postcss-dir-pseudo-class'; +import type { pluginOptions as pluginOptions_14 } from '@csstools/postcss-normalize-display-values'; +import type { pluginOptions as pluginOptions_15 } from 'postcss-double-position-gradients'; +import type { pluginOptions as pluginOptions_16 } from '@csstools/postcss-exponential-functions'; +import type { pluginOptions as pluginOptions_17 } from '@csstools/postcss-logical-float-and-clear'; +import type { pluginOptions as pluginOptions_18 } from 'postcss-focus-visible'; +import type { pluginOptions as pluginOptions_19 } from 'postcss-focus-within'; +import type { pluginOptions as pluginOptions_2 } from '@csstools/postcss-initial'; +import type { pluginOptions as pluginOptions_20 } from '@csstools/postcss-font-format-keywords'; +import type { pluginOptions as pluginOptions_21 } from '@csstools/postcss-gamut-mapping'; +import type { pluginOptions as pluginOptions_22 } from 'postcss-gap-properties'; +import type { pluginOptions as pluginOptions_23 } from '@csstools/postcss-gradients-interpolation-method'; +import type { pluginOptions as pluginOptions_24 } from 'css-has-pseudo'; +import type { pluginOptions as pluginOptions_25 } from 'postcss-color-hex-alpha'; +import type { pluginOptions as pluginOptions_26 } from '@csstools/postcss-hwb-function'; +import type { pluginOptions as pluginOptions_27 } from '@csstools/postcss-ic-unit'; +import type { pluginOptions as pluginOptions_28 } from 'postcss-image-set-function'; +import type { pluginOptions as pluginOptions_29 } from '@csstools/postcss-is-pseudo-class'; +import type { pluginOptions as pluginOptions_3 } from 'postcss-pseudo-class-any-link'; +import type { pluginOptions as pluginOptions_30 } from 'postcss-lab-function'; +import type { pluginOptions as pluginOptions_31 } from '@csstools/postcss-logical-overflow'; +import type { pluginOptions as pluginOptions_32 } from '@csstools/postcss-logical-overscroll-behavior'; +import type { pluginOptions as pluginOptions_33 } from 'postcss-logical'; +import type { pluginOptions as pluginOptions_34 } from '@csstools/postcss-logical-resize'; +import type { pluginOptions as pluginOptions_35 } from '@csstools/postcss-logical-viewport-units'; +import type { pluginOptions as pluginOptions_36 } from '@csstools/postcss-media-queries-aspect-ratio-number-values'; +import type { pluginOptions as pluginOptions_37 } from '@csstools/postcss-media-minmax'; +import type { pluginOptions as pluginOptions_38 } from '@csstools/postcss-nested-calc'; +import type { pluginOptions as pluginOptions_39 } from 'postcss-nesting'; +import type { pluginOptions as pluginOptions_4 } from 'css-blank-pseudo'; +import type { pluginOptions as pluginOptions_40 } from 'postcss-selector-not'; +import type { pluginOptions as pluginOptions_41 } from '@csstools/postcss-oklab-function'; +import type { pluginOptions as pluginOptions_42 } from 'postcss-overflow-shorthand'; +import type { pluginOptions as pluginOptions_43 } from 'postcss-place'; +import type { pluginOptions as pluginOptions_44 } from 'css-prefers-color-scheme'; +import type { pluginOptions as pluginOptions_45 } from 'postcss-color-rebeccapurple'; +import type { pluginOptions as pluginOptions_46 } from '@csstools/postcss-relative-color-syntax'; +import type { pluginOptions as pluginOptions_47 } from '@csstools/postcss-scope-pseudo-class'; +import type { pluginOptions as pluginOptions_48 } from '@csstools/postcss-stepped-value-functions'; +import type { pluginOptions as pluginOptions_49 } from '@csstools/postcss-text-decoration-shorthand'; +import type { pluginOptions as pluginOptions_5 } from '@csstools/postcss-cascade-layers'; +import type { pluginOptions as pluginOptions_50 } from '@csstools/postcss-trigonometric-functions'; +import type { pluginOptions as pluginOptions_51 } from '@csstools/postcss-unset-value'; +import type { pluginOptions as pluginOptions_6 } from 'postcss-attribute-case-insensitive'; +import type { pluginOptions as pluginOptions_7 } from '@csstools/postcss-color-function'; +import type { pluginOptions as pluginOptions_8 } from 'postcss-color-functional-notation'; +import type { pluginOptions as pluginOptions_9 } from '@csstools/postcss-color-mix-function'; + declare const creator: PluginCreator; export default creator; + +export declare enum DirectionFlow { + TopToBottom = "top-to-bottom", + BottomToTop = "bottom-to-top", + RightToLeft = "right-to-left", + LeftToRight = "left-to-right" +} + +export declare type pluginOptions = { + /** + * Determine which CSS features to polyfill, + * based upon their process in becoming web standards. + * default: 2 + */ + stage?: number | false; + /** + * Determine which CSS features to polyfill, + * based their implementation status. + * default: 0 + */ + minimumVendorImplementations?: number; + /** + * Enable any feature that would need an extra browser library to be loaded into the page for it to work. + * default: false + */ + enableClientSidePolyfills?: boolean; + /** + * PostCSS Preset Env supports any standard browserslist configuration, + * which can be a `.browserslistrc` file, + * a `browserslist` key in `package.json`, + * or `browserslist` environment variables. + * + * The `env` option is used to select a specific browserslist environment in the event that you have more than one. + */ + env?: string; + /** + * PostCSS Preset Env supports any standard browserslist configuration, + * which can be a `.browserslistrc` file, + * a `browserslist` key in `package.json`, + * or `browserslist` environment variables. + * + * The `browsers` option should only be used when a standard browserslist configuration is not available. + * When the `browsers` option is used the `env` option is ignored. + */ + browsers?: string | Array | null; + /** + * Determine whether all plugins should receive a `preserve` option, + * which may preserve or remove the original and now polyfilled CSS. + * Each plugin has it's own default, some true, others false. + * default: _not set_ + */ + preserve?: boolean; + /** + * [Configure autoprefixer](https://github.com/postcss/autoprefixer#options) + */ + autoprefixer?: autoprefixer.Options; + /** + * Enable or disable specific polyfills by ID. + * Passing `true` to a specific [feature ID](https://github.com/csstools/postcss-plugins/blob/main/plugin-packs/postcss-preset-env/FEATURES.md) will enable its polyfill, + * while passing `false` will disable it. + * + * Passing an object to a specific feature ID will both enable and configure it. + */ + features?: pluginsOptions; + /** + * The `insertBefore` key allows you to insert other PostCSS plugins into the chain. + * This is only useful if you are also using sugary PostCSS plugins that must execute before certain polyfills. + * `insertBefore` supports chaining one or multiple plugins. + */ + insertBefore?: Record; + /** + * The `insertAfter` key allows you to insert other PostCSS plugins into the chain. + * This is only useful if you are also using sugary PostCSS plugins that must execute after certain polyfills. + * `insertAfter` supports chaining one or multiple plugins. + */ + insertAfter?: Record; + /** + * Enable debugging messages to stdout giving insights into which features have been enabled/disabled and why. + * default: false + */ + debug?: boolean; + /** + * The `logical` object allows to configure all plugins related to logical document flow at once. + * It accepts the same options as each plugin: `inlineDirection` and `blockDirection`. + */ + logical?: { + /** Set the inline flow direction. default: left-to-right */ + inlineDirection?: DirectionFlow; + /** Set the block flow direction. default: top-to-bottom */ + blockDirection?: DirectionFlow; + }; +}; + +export declare type pluginsOptions = { + /** plugin options for "@csstools/postcss-initial" */ + 'all-property'?: pluginOptions_2 | boolean; + /** plugin options for "postcss-pseudo-class-any-link" */ + 'any-link-pseudo-class'?: pluginOptions_3 | boolean; + /** plugin options for "css-blank-pseudo" */ + 'blank-pseudo-class'?: pluginOptions_4 | boolean; + /** plugin options for "postcss-page-break" */ + 'break-properties'?: postcssPageBreakOptions | boolean; + /** plugin options for "@csstools/postcss-cascade-layers" */ + 'cascade-layers'?: pluginOptions_5 | boolean; + /** plugin options for "postcss-attribute-case-insensitive" */ + 'case-insensitive-attributes'?: pluginOptions_6 | boolean; + /** plugin options for "postcss-clamp" */ + 'clamp'?: postcssClampOptions | boolean; + /** plugin options for "@csstools/postcss-color-function" */ + 'color-function'?: pluginOptions_7 | boolean; + /** plugin options for "postcss-color-functional-notation" */ + 'color-functional-notation'?: pluginOptions_8 | boolean; + /** plugin options for "@csstools/postcss-color-mix-function" */ + 'color-mix'?: pluginOptions_9 | boolean; + /** plugin options for "postcss-custom-media" */ + 'custom-media-queries'?: pluginOptions_10 | boolean; + /** plugin options for "postcss-custom-properties" */ + 'custom-properties'?: pluginOptions_11 | boolean; + /** plugin options for "postcss-custom-selectors" */ + 'custom-selectors'?: pluginOptions_12 | boolean; + /** plugin options for "postcss-dir-pseudo-class" */ + 'dir-pseudo-class'?: pluginOptions_13 | boolean; + /** plugin options for "@csstools/postcss-normalize-display-values" */ + 'display-two-values'?: pluginOptions_14 | boolean; + /** plugin options for "postcss-double-position-gradients" */ + 'double-position-gradients'?: pluginOptions_15 | boolean; + /** plugin options for "@csstools/postcss-exponential-functions" */ + 'exponential-functions'?: pluginOptions_16 | boolean; + /** plugin options for "@csstools/postcss-logical-float-and-clear" */ + 'float-clear-logical-values'?: pluginOptions_17 | boolean; + /** plugin options for "postcss-focus-visible" */ + 'focus-visible-pseudo-class'?: pluginOptions_18 | boolean; + /** plugin options for "postcss-focus-within" */ + 'focus-within-pseudo-class'?: pluginOptions_19 | boolean; + /** plugin options for "@csstools/postcss-font-format-keywords" */ + 'font-format-keywords'?: pluginOptions_20 | boolean; + /** plugin options for "postcss-font-variant" */ + 'font-variant-property'?: postcssFontVariantOptions | boolean; + /** plugin options for "@csstools/postcss-gamut-mapping" */ + 'gamut-mapping'?: pluginOptions_21 | boolean; + /** plugin options for "postcss-gap-properties" */ + 'gap-properties'?: pluginOptions_22 | boolean; + /** plugin options for "@csstools/postcss-gradients-interpolation-method" */ + 'gradients-interpolation-method'?: pluginOptions_23 | boolean; + /** plugin options for "css-has-pseudo" */ + 'has-pseudo-class'?: pluginOptions_24 | boolean; + /** plugin options for "postcss-color-hex-alpha" */ + 'hexadecimal-alpha-notation'?: pluginOptions_25 | boolean; + /** plugin options for "@csstools/postcss-hwb-function" */ + 'hwb-function'?: pluginOptions_26 | boolean; + /** plugin options for "@csstools/postcss-ic-unit" */ + 'ic-unit'?: pluginOptions_27 | boolean; + /** plugin options for "postcss-image-set-function" */ + 'image-set-function'?: pluginOptions_28 | boolean; + /** plugin options for "@csstools/postcss-is-pseudo-class" */ + 'is-pseudo-class'?: pluginOptions_29 | boolean; + /** plugin options for "postcss-lab-function" */ + 'lab-function'?: pluginOptions_30 | boolean; + /** plugin options for "@csstools/postcss-logical-overflow" */ + 'logical-overflow'?: pluginOptions_31 | boolean; + /** plugin options for "@csstools/postcss-logical-overscroll-behavior" */ + 'logical-overscroll-behavior'?: pluginOptions_32 | boolean; + /** plugin options for "postcss-logical" */ + 'logical-properties-and-values'?: pluginOptions_33 | boolean; + /** plugin options for "@csstools/postcss-logical-resize" */ + 'logical-resize'?: pluginOptions_34 | boolean; + /** plugin options for "@csstools/postcss-logical-viewport-units" */ + 'logical-viewport-units'?: pluginOptions_35 | boolean; + /** plugin options for "@csstools/postcss-media-queries-aspect-ratio-number-values" */ + 'media-queries-aspect-ratio-number-values'?: pluginOptions_36 | boolean; + /** plugin options for "@csstools/postcss-media-minmax" */ + 'media-query-ranges'?: pluginOptions_37 | boolean; + /** plugin options for "@csstools/postcss-nested-calc" */ + 'nested-calc'?: pluginOptions_38 | boolean; + /** plugin options for "postcss-nesting" */ + 'nesting-rules'?: pluginOptions_39 | boolean; + /** plugin options for "postcss-selector-not" */ + 'not-pseudo-class'?: pluginOptions_40 | boolean; + /** plugin options for "@csstools/postcss-oklab-function" */ + 'oklab-function'?: pluginOptions_41 | boolean; + /** plugin options for "postcss-opacity-percentage" */ + 'opacity-percentage'?: postcssOpacityPercentageOptions | boolean; + /** plugin options for "postcss-overflow-shorthand" */ + 'overflow-property'?: pluginOptions_42 | boolean; + /** plugin options for "postcss-replace-overflow-wrap" */ + 'overflow-wrap-property'?: postcssReplaceOverflowWrapOptions | boolean; + /** plugin options for "postcss-place" */ + 'place-properties'?: pluginOptions_43 | boolean; + /** plugin options for "css-prefers-color-scheme" */ + 'prefers-color-scheme-query'?: pluginOptions_44 | boolean; + /** plugin options for "postcss-color-rebeccapurple" */ + 'rebeccapurple-color'?: pluginOptions_45 | boolean; + /** plugin options for "@csstools/postcss-relative-color-syntax" */ + 'relative-color-syntax'?: pluginOptions_46 | boolean; + /** plugin options for "@csstools/postcss-scope-pseudo-class" */ + 'scope-pseudo-class'?: pluginOptions_47 | boolean; + /** plugin options for "@csstools/postcss-stepped-value-functions" */ + 'stepped-value-functions'?: pluginOptions_48 | boolean; + /** plugin options for "postcss-system-ui-font-family" */ + 'system-ui-font-family'?: postcssFontFamilySystemUIOptions | boolean; + /** plugin options for "@csstools/postcss-text-decoration-shorthand" */ + 'text-decoration-shorthand'?: pluginOptions_49 | boolean; + /** plugin options for "@csstools/postcss-trigonometric-functions" */ + 'trigonometric-functions'?: pluginOptions_50 | boolean; + /** plugin options for "@csstools/postcss-unset-value" */ + 'unset-value'?: pluginOptions_51 | boolean; +}; + +/** postcss-clamp plugin options */ +export declare type postcssClampOptions = { + /** Preserve the original notation. default: false */ + preserve?: boolean; + /** + * The precalculate option determines whether values with the same unit should be precalculated. + * default: false + */ + precalculate?: boolean; +}; + +/** postcss-system-ui-font-family plugin options */ +export declare type postcssFontFamilySystemUIOptions = Record; + +/** postcss-font-variant plugin options */ +export declare type postcssFontVariantOptions = Record; + +/** postcss-opacity-percentage plugin options */ +export declare type postcssOpacityPercentageOptions = { + /** Preserve the original notation. default: false */ + preserve?: boolean; +}; + +/** postcss-page-break plugin options */ +export declare type postcssPageBreakOptions = Record; + +/** postcss-replace-overflow-wrap plugin options */ +export declare type postcssReplaceOverflowWrapOptions = { + /** Preserve the original notation. default: false */ + preserve?: boolean; +}; + +export { } diff --git a/plugin-packs/postcss-preset-env/dist/options.d.ts b/plugin-packs/postcss-preset-env/dist/options.d.ts deleted file mode 100644 index 8522d1d8e..000000000 --- a/plugin-packs/postcss-preset-env/dist/options.d.ts +++ /dev/null @@ -1,93 +0,0 @@ -import type autoprefixer from 'autoprefixer'; -import { pluginsOptions } from './plugins/plugins-options'; -declare enum DirectionFlow { - TopToBottom = "top-to-bottom", - BottomToTop = "bottom-to-top", - RightToLeft = "right-to-left", - LeftToRight = "left-to-right" -} -export type pluginOptions = { - /** - * Determine which CSS features to polyfill, - * based upon their process in becoming web standards. - * default: 2 - */ - stage?: number | false; - /** - * Determine which CSS features to polyfill, - * based their implementation status. - * default: 0 - */ - minimumVendorImplementations?: number; - /** - * Enable any feature that would need an extra browser library to be loaded into the page for it to work. - * default: false - */ - enableClientSidePolyfills?: boolean; - /** - * PostCSS Preset Env supports any standard browserslist configuration, - * which can be a `.browserslistrc` file, - * a `browserslist` key in `package.json`, - * or `browserslist` environment variables. - * - * The `env` option is used to select a specific browserslist environment in the event that you have more than one. - */ - env?: string; - /** - * PostCSS Preset Env supports any standard browserslist configuration, - * which can be a `.browserslistrc` file, - * a `browserslist` key in `package.json`, - * or `browserslist` environment variables. - * - * The `browsers` option should only be used when a standard browserslist configuration is not available. - * When the `browsers` option is used the `env` option is ignored. - */ - browsers?: string | Array | null; - /** - * Determine whether all plugins should receive a `preserve` option, - * which may preserve or remove the original and now polyfilled CSS. - * Each plugin has it's own default, some true, others false. - * default: _not set_ - */ - preserve?: boolean; - /** - * [Configure autoprefixer](https://github.com/postcss/autoprefixer#options) - */ - autoprefixer?: autoprefixer.Options; - /** - * Enable or disable specific polyfills by ID. - * Passing `true` to a specific [feature ID](https://github.com/csstools/postcss-plugins/blob/main/plugin-packs/postcss-preset-env/FEATURES.md) will enable its polyfill, - * while passing `false` will disable it. - * - * Passing an object to a specific feature ID will both enable and configure it. - */ - features?: pluginsOptions; - /** - * The `insertBefore` key allows you to insert other PostCSS plugins into the chain. - * This is only useful if you are also using sugary PostCSS plugins that must execute before certain polyfills. - * `insertBefore` supports chaining one or multiple plugins. - */ - insertBefore?: Record; - /** - * The `insertAfter` key allows you to insert other PostCSS plugins into the chain. - * This is only useful if you are also using sugary PostCSS plugins that must execute after certain polyfills. - * `insertAfter` supports chaining one or multiple plugins. - */ - insertAfter?: Record; - /** - * Enable debugging messages to stdout giving insights into which features have been enabled/disabled and why. - * default: false - */ - debug?: boolean; - /** - * The `logical` object allows to configure all plugins related to logical document flow at once. - * It accepts the same options as each plugin: `inlineDirection` and `blockDirection`. - */ - logical?: { - /** Set the inline flow direction. default: left-to-right */ - inlineDirection?: DirectionFlow; - /** Set the block flow direction. default: top-to-bottom */ - blockDirection?: DirectionFlow; - }; -}; -export {}; diff --git a/plugin-packs/postcss-preset-env/dist/plugins/plugins-options.d.ts b/plugin-packs/postcss-preset-env/dist/plugins/plugins-options.d.ts deleted file mode 100644 index 4d67f35d2..000000000 --- a/plugin-packs/postcss-preset-env/dist/plugins/plugins-options.d.ts +++ /dev/null @@ -1,170 +0,0 @@ -import type { pluginOptions as postcssInitial } from '@csstools/postcss-initial'; -import type { pluginOptions as postcssPseudoClassAnyLink } from 'postcss-pseudo-class-any-link'; -import type { pluginOptions as postcssBlankPseudo } from 'css-blank-pseudo'; -import type { pluginOptions as postcssPageBreak } from '../types/postcss-page-break/plugin-options'; -import type { pluginOptions as postcssCascadeLayers } from '@csstools/postcss-cascade-layers'; -import type { pluginOptions as postcssAttributeCaseInsensitive } from 'postcss-attribute-case-insensitive'; -import type { pluginOptions as postcssClamp } from '../types/postcss-clamp/plugin-options'; -import type { pluginOptions as postcssColorFunction } from '@csstools/postcss-color-function'; -import type { pluginOptions as postcssColorFunctionalNotation } from 'postcss-color-functional-notation'; -import type { pluginOptions as postcssColorMixFunction } from '@csstools/postcss-color-mix-function'; -import type { pluginOptions as postcssCustomMedia } from 'postcss-custom-media'; -import type { pluginOptions as postcssCustomProperties } from 'postcss-custom-properties'; -import type { pluginOptions as postcssCustomSelectors } from 'postcss-custom-selectors'; -import type { pluginOptions as postcssDirPseudoClass } from 'postcss-dir-pseudo-class'; -import type { pluginOptions as postcssNormalizeDisplayValues } from '@csstools/postcss-normalize-display-values'; -import type { pluginOptions as postcssDoublePositionGradients } from 'postcss-double-position-gradients'; -import type { pluginOptions as postcssExponentialFunctions } from '@csstools/postcss-exponential-functions'; -import type { pluginOptions as postcssLogicalFloatAndClear } from '@csstools/postcss-logical-float-and-clear'; -import type { pluginOptions as postcssFocusVisible } from 'postcss-focus-visible'; -import type { pluginOptions as postcssFocusWithin } from 'postcss-focus-within'; -import type { pluginOptions as postcssFontFormatKeywords } from '@csstools/postcss-font-format-keywords'; -import type { pluginOptions as postcssFontVariant } from '../types/postcss-font-variant/plugin-options'; -import type { pluginOptions as postcssGamutMapping } from '@csstools/postcss-gamut-mapping'; -import type { pluginOptions as postcssGapProperties } from 'postcss-gap-properties'; -import type { pluginOptions as postcssGradientsInterpolationMethod } from '@csstools/postcss-gradients-interpolation-method'; -import type { pluginOptions as postcssHasPseudo } from 'css-has-pseudo'; -import type { pluginOptions as postcssColorHexAlpha } from 'postcss-color-hex-alpha'; -import type { pluginOptions as postcssHWBFunction } from '@csstools/postcss-hwb-function'; -import type { pluginOptions as postcssICUnit } from '@csstools/postcss-ic-unit'; -import type { pluginOptions as postcssImageSetFunction } from 'postcss-image-set-function'; -import type { pluginOptions as postcssIsPseudoClass } from '@csstools/postcss-is-pseudo-class'; -import type { pluginOptions as postcssLabFunction } from 'postcss-lab-function'; -import type { pluginOptions as postcssLogicalOverflow } from '@csstools/postcss-logical-overflow'; -import type { pluginOptions as postcssLogicalOverscrollBehavor } from '@csstools/postcss-logical-overscroll-behavior'; -import type { pluginOptions as postcssLogical } from 'postcss-logical'; -import type { pluginOptions as postcssLogicalResize } from '@csstools/postcss-logical-resize'; -import type { pluginOptions as postcssLogicalViewportUnits } from '@csstools/postcss-logical-viewport-units'; -import type { pluginOptions as postcssMediaQueriesAspectRatioNumberValues } from '@csstools/postcss-media-queries-aspect-ratio-number-values'; -import type { pluginOptions as postcssMediaMinmax } from '@csstools/postcss-media-minmax'; -import type { pluginOptions as postcssNestedCalc } from '@csstools/postcss-nested-calc'; -import type { pluginOptions as postcssNesting } from 'postcss-nesting'; -import type { pluginOptions as postcssSelectorNot } from 'postcss-selector-not'; -import type { pluginOptions as postcssOKLabFunction } from '@csstools/postcss-oklab-function'; -import type { pluginOptions as postcssOpacityPercentage } from '../types/postcss-opacity-percentage/plugin-options'; -import type { pluginOptions as postcssOverflowShorthand } from 'postcss-overflow-shorthand'; -import type { pluginOptions as postcssReplaceOverflowWrap } from '../types/postcss-replace-overflow-wrap/plugin-options'; -import type { pluginOptions as postcssPlace } from 'postcss-place'; -import type { pluginOptions as postcssPrefersColorScheme } from 'css-prefers-color-scheme'; -import type { pluginOptions as postcssColorRebeccapurple } from 'postcss-color-rebeccapurple'; -import type { pluginOptions as postcssRelativeColorSyntax } from '@csstools/postcss-relative-color-syntax'; -import type { pluginOptions as postcssScopePseudoClass } from '@csstools/postcss-scope-pseudo-class'; -import type { pluginOptions as postcssSteppedValueFunctions } from '@csstools/postcss-stepped-value-functions'; -import type { pluginOptions as postcssFontFamilySystemUI } from '../types/postcss-system-ui-font-family/plugin-options'; -import type { pluginOptions as postcssTextDecorationShorthand } from '@csstools/postcss-text-decoration-shorthand'; -import type { pluginOptions as postcssTrigonometricFunctions } from '@csstools/postcss-trigonometric-functions'; -import type { pluginOptions as postcssUnsetValue } from '@csstools/postcss-unset-value'; -export type pluginsOptions = { - /** plugin options for "@csstools/postcss-initial" */ - 'all-property'?: postcssInitial | boolean; - /** plugin options for "postcss-pseudo-class-any-link" */ - 'any-link-pseudo-class'?: postcssPseudoClassAnyLink | boolean; - /** plugin options for "css-blank-pseudo" */ - 'blank-pseudo-class'?: postcssBlankPseudo | boolean; - /** plugin options for "postcss-page-break" */ - 'break-properties'?: postcssPageBreak | boolean; - /** plugin options for "@csstools/postcss-cascade-layers" */ - 'cascade-layers'?: postcssCascadeLayers | boolean; - /** plugin options for "postcss-attribute-case-insensitive" */ - 'case-insensitive-attributes'?: postcssAttributeCaseInsensitive | boolean; - /** plugin options for "postcss-clamp" */ - 'clamp'?: postcssClamp | boolean; - /** plugin options for "@csstools/postcss-color-function" */ - 'color-function'?: postcssColorFunction | boolean; - /** plugin options for "postcss-color-functional-notation" */ - 'color-functional-notation'?: postcssColorFunctionalNotation | boolean; - /** plugin options for "@csstools/postcss-color-mix-function" */ - 'color-mix'?: postcssColorMixFunction | boolean; - /** plugin options for "postcss-custom-media" */ - 'custom-media-queries'?: postcssCustomMedia | boolean; - /** plugin options for "postcss-custom-properties" */ - 'custom-properties'?: postcssCustomProperties | boolean; - /** plugin options for "postcss-custom-selectors" */ - 'custom-selectors'?: postcssCustomSelectors | boolean; - /** plugin options for "postcss-dir-pseudo-class" */ - 'dir-pseudo-class'?: postcssDirPseudoClass | boolean; - /** plugin options for "@csstools/postcss-normalize-display-values" */ - 'display-two-values'?: postcssNormalizeDisplayValues | boolean; - /** plugin options for "postcss-double-position-gradients" */ - 'double-position-gradients'?: postcssDoublePositionGradients | boolean; - /** plugin options for "@csstools/postcss-exponential-functions" */ - 'exponential-functions'?: postcssExponentialFunctions | boolean; - /** plugin options for "@csstools/postcss-logical-float-and-clear" */ - 'float-clear-logical-values'?: postcssLogicalFloatAndClear | boolean; - /** plugin options for "postcss-focus-visible" */ - 'focus-visible-pseudo-class'?: postcssFocusVisible | boolean; - /** plugin options for "postcss-focus-within" */ - 'focus-within-pseudo-class'?: postcssFocusWithin | boolean; - /** plugin options for "@csstools/postcss-font-format-keywords" */ - 'font-format-keywords'?: postcssFontFormatKeywords | boolean; - /** plugin options for "postcss-font-variant" */ - 'font-variant-property'?: postcssFontVariant | boolean; - /** plugin options for "@csstools/postcss-gamut-mapping" */ - 'gamut-mapping'?: postcssGamutMapping | boolean; - /** plugin options for "postcss-gap-properties" */ - 'gap-properties'?: postcssGapProperties | boolean; - /** plugin options for "@csstools/postcss-gradients-interpolation-method" */ - 'gradients-interpolation-method'?: postcssGradientsInterpolationMethod | boolean; - /** plugin options for "css-has-pseudo" */ - 'has-pseudo-class'?: postcssHasPseudo | boolean; - /** plugin options for "postcss-color-hex-alpha" */ - 'hexadecimal-alpha-notation'?: postcssColorHexAlpha | boolean; - /** plugin options for "@csstools/postcss-hwb-function" */ - 'hwb-function'?: postcssHWBFunction | boolean; - /** plugin options for "@csstools/postcss-ic-unit" */ - 'ic-unit'?: postcssICUnit | boolean; - /** plugin options for "postcss-image-set-function" */ - 'image-set-function'?: postcssImageSetFunction | boolean; - /** plugin options for "@csstools/postcss-is-pseudo-class" */ - 'is-pseudo-class'?: postcssIsPseudoClass | boolean; - /** plugin options for "postcss-lab-function" */ - 'lab-function'?: postcssLabFunction | boolean; - /** plugin options for "@csstools/postcss-logical-overflow" */ - 'logical-overflow'?: postcssLogicalOverflow | boolean; - /** plugin options for "@csstools/postcss-logical-overscroll-behavior" */ - 'logical-overscroll-behavior'?: postcssLogicalOverscrollBehavor | boolean; - /** plugin options for "postcss-logical" */ - 'logical-properties-and-values'?: postcssLogical | boolean; - /** plugin options for "@csstools/postcss-logical-resize" */ - 'logical-resize'?: postcssLogicalResize | boolean; - /** plugin options for "@csstools/postcss-logical-viewport-units" */ - 'logical-viewport-units'?: postcssLogicalViewportUnits | boolean; - /** plugin options for "@csstools/postcss-media-queries-aspect-ratio-number-values" */ - 'media-queries-aspect-ratio-number-values'?: postcssMediaQueriesAspectRatioNumberValues | boolean; - /** plugin options for "@csstools/postcss-media-minmax" */ - 'media-query-ranges'?: postcssMediaMinmax | boolean; - /** plugin options for "@csstools/postcss-nested-calc" */ - 'nested-calc'?: postcssNestedCalc | boolean; - /** plugin options for "postcss-nesting" */ - 'nesting-rules'?: postcssNesting | boolean; - /** plugin options for "postcss-selector-not" */ - 'not-pseudo-class'?: postcssSelectorNot | boolean; - /** plugin options for "@csstools/postcss-oklab-function" */ - 'oklab-function'?: postcssOKLabFunction | boolean; - /** plugin options for "postcss-opacity-percentage" */ - 'opacity-percentage'?: postcssOpacityPercentage | boolean; - /** plugin options for "postcss-overflow-shorthand" */ - 'overflow-property'?: postcssOverflowShorthand | boolean; - /** plugin options for "postcss-replace-overflow-wrap" */ - 'overflow-wrap-property'?: postcssReplaceOverflowWrap | boolean; - /** plugin options for "postcss-place" */ - 'place-properties'?: postcssPlace | boolean; - /** plugin options for "css-prefers-color-scheme" */ - 'prefers-color-scheme-query'?: postcssPrefersColorScheme | boolean; - /** plugin options for "postcss-color-rebeccapurple" */ - 'rebeccapurple-color'?: postcssColorRebeccapurple | boolean; - /** plugin options for "@csstools/postcss-relative-color-syntax" */ - 'relative-color-syntax'?: postcssRelativeColorSyntax | boolean; - /** plugin options for "@csstools/postcss-scope-pseudo-class" */ - 'scope-pseudo-class'?: postcssScopePseudoClass | boolean; - /** plugin options for "@csstools/postcss-stepped-value-functions" */ - 'stepped-value-functions'?: postcssSteppedValueFunctions | boolean; - /** plugin options for "postcss-system-ui-font-family" */ - 'system-ui-font-family'?: postcssFontFamilySystemUI | boolean; - /** plugin options for "@csstools/postcss-text-decoration-shorthand" */ - 'text-decoration-shorthand'?: postcssTextDecorationShorthand | boolean; - /** plugin options for "@csstools/postcss-trigonometric-functions" */ - 'trigonometric-functions'?: postcssTrigonometricFunctions | boolean; - /** plugin options for "@csstools/postcss-unset-value" */ - 'unset-value'?: postcssUnsetValue | boolean; -}; diff --git a/plugin-packs/postcss-preset-env/dist/types/postcss-clamp/plugin-options.d.ts b/plugin-packs/postcss-preset-env/dist/types/postcss-clamp/plugin-options.d.ts deleted file mode 100644 index c3ed79450..000000000 --- a/plugin-packs/postcss-preset-env/dist/types/postcss-clamp/plugin-options.d.ts +++ /dev/null @@ -1,10 +0,0 @@ -/** postcss-clamp plugin options */ -export type pluginOptions = { - /** Preserve the original notation. default: false */ - preserve?: boolean; - /** - * The precalculate option determines whether values with the same unit should be precalculated. - * default: false - */ - precalculate?: boolean; -}; diff --git a/plugin-packs/postcss-preset-env/dist/types/postcss-font-variant/plugin-options.d.ts b/plugin-packs/postcss-preset-env/dist/types/postcss-font-variant/plugin-options.d.ts deleted file mode 100644 index b539e77b2..000000000 --- a/plugin-packs/postcss-preset-env/dist/types/postcss-font-variant/plugin-options.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -/** postcss-font-variant plugin options */ -export type pluginOptions = Record; diff --git a/plugin-packs/postcss-preset-env/dist/types/postcss-opacity-percentage/plugin-options.d.ts b/plugin-packs/postcss-preset-env/dist/types/postcss-opacity-percentage/plugin-options.d.ts deleted file mode 100644 index 81306fbba..000000000 --- a/plugin-packs/postcss-preset-env/dist/types/postcss-opacity-percentage/plugin-options.d.ts +++ /dev/null @@ -1,5 +0,0 @@ -/** postcss-opacity-percentage plugin options */ -export type pluginOptions = { - /** Preserve the original notation. default: false */ - preserve?: boolean; -}; diff --git a/plugin-packs/postcss-preset-env/dist/types/postcss-page-break/plugin-options.d.ts b/plugin-packs/postcss-preset-env/dist/types/postcss-page-break/plugin-options.d.ts deleted file mode 100644 index 05d36d940..000000000 --- a/plugin-packs/postcss-preset-env/dist/types/postcss-page-break/plugin-options.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -/** postcss-page-break plugin options */ -export type pluginOptions = Record; diff --git a/plugin-packs/postcss-preset-env/dist/types/postcss-replace-overflow-wrap/plugin-options.d.ts b/plugin-packs/postcss-preset-env/dist/types/postcss-replace-overflow-wrap/plugin-options.d.ts deleted file mode 100644 index 5b9a3bfe3..000000000 --- a/plugin-packs/postcss-preset-env/dist/types/postcss-replace-overflow-wrap/plugin-options.d.ts +++ /dev/null @@ -1,5 +0,0 @@ -/** postcss-replace-overflow-wrap plugin options */ -export type pluginOptions = { - /** Preserve the original notation. default: false */ - preserve?: boolean; -}; diff --git a/plugin-packs/postcss-preset-env/dist/types/postcss-system-ui-font-family/plugin-options.d.ts b/plugin-packs/postcss-preset-env/dist/types/postcss-system-ui-font-family/plugin-options.d.ts deleted file mode 100644 index 6a5f429da..000000000 --- a/plugin-packs/postcss-preset-env/dist/types/postcss-system-ui-font-family/plugin-options.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -/** postcss-system-ui-font-family plugin options */ -export type pluginOptions = Record; diff --git a/plugin-packs/postcss-preset-env/package.json b/plugin-packs/postcss-preset-env/package.json index 264a87fc0..a8b96b557 100644 --- a/plugin-packs/postcss-preset-env/package.json +++ b/plugin-packs/postcss-preset-env/package.json @@ -31,15 +31,18 @@ "engines": { "node": "^14 || ^16 || >=18" }, + "type": "module", "main": "dist/index.cjs", "module": "dist/index.mjs", - "types": "dist/index.d.ts", "exports": { ".": { - "types": "./dist/index.d.ts", - "import": "./dist/index.mjs", - "require": "./dist/index.cjs", - "default": "./dist/index.mjs" + "import": { + "types": "./dist/index.d.ts", + "default": "./dist/index.mjs" + }, + "require": { + "default": "./dist/index.cjs" + } } }, "files": [ diff --git a/plugin-packs/postcss-preset-env/scripts/generate-plugins-data.mjs b/plugin-packs/postcss-preset-env/scripts/generate-plugins-data.mjs index 9ffb2e3a2..bec51fd71 100644 --- a/plugin-packs/postcss-preset-env/scripts/generate-plugins-data.mjs +++ b/plugin-packs/postcss-preset-env/scripts/generate-plugins-data.mjs @@ -38,9 +38,9 @@ function generatePluginOptions(data) { const plugin = plugins[i]; if (existsSync(path.join('./src/types/', plugin.packageName, 'plugin-options.ts'))) { - result += `import type { pluginOptions as ${plugin.importName} } from '${path.posix.join('../types/', plugin.packageName, 'plugin-options')}';\n`; + result += `import type { ${plugin.importName}Options } from '${path.posix.join('../types/', plugin.packageName, 'plugin-options')}';\n`; } else { - result += `import type { pluginOptions as ${plugin.importName} } from '${plugin.packageName}';\n`; + result += `import type { pluginOptions as ${plugin.importName}Options } from '${plugin.packageName}';\n`; } } @@ -49,7 +49,7 @@ function generatePluginOptions(data) { for (let i = 0; i < plugins.length; i++) { const plugin = plugins[i]; result += `\t/** plugin options for "${plugin.packageName}" */\n`; - result += `\t'${plugin.id}'?: ${plugin.importName} | boolean\n`; + result += `\t'${plugin.id}'?: ${plugin.importName}Options | boolean\n`; } result += '};\n'; diff --git a/plugin-packs/postcss-preset-env/src/index.ts b/plugin-packs/postcss-preset-env/src/index.ts index a23b65703..045f02a83 100644 --- a/plugin-packs/postcss-preset-env/src/index.ts +++ b/plugin-packs/postcss-preset-env/src/index.ts @@ -7,7 +7,14 @@ import { newLogger } from './log/helper.mjs'; import { pluginIdHelp } from './plugins/plugin-id-help.mjs'; import type { pluginOptions } from './options'; import type { PluginCreator } from 'postcss'; -export type { pluginOptions } from './options'; +export type { pluginOptions, DirectionFlow } from './options'; +export type { pluginsOptions } from './plugins/plugins-options'; +export type { postcssClampOptions } from './types/postcss-clamp/plugin-options'; +export type { postcssFontFamilySystemUIOptions } from './types/postcss-system-ui-font-family/plugin-options'; +export type { postcssFontVariantOptions } from './types/postcss-font-variant/plugin-options'; +export type { postcssOpacityPercentageOptions } from './types/postcss-opacity-percentage/plugin-options'; +export type { postcssPageBreakOptions } from './types/postcss-page-break/plugin-options'; +export type { postcssReplaceOverflowWrapOptions } from './types/postcss-replace-overflow-wrap/plugin-options'; const creator: PluginCreator = (opts?: pluginOptions) => { const logger = newLogger(); diff --git a/plugin-packs/postcss-preset-env/src/options.ts b/plugin-packs/postcss-preset-env/src/options.ts index a08d23f42..af98f5db4 100644 --- a/plugin-packs/postcss-preset-env/src/options.ts +++ b/plugin-packs/postcss-preset-env/src/options.ts @@ -1,7 +1,7 @@ import type autoprefixer from 'autoprefixer'; import { pluginsOptions } from './plugins/plugins-options'; -enum DirectionFlow { +export enum DirectionFlow { TopToBottom = 'top-to-bottom', BottomToTop = 'bottom-to-top', RightToLeft = 'right-to-left', diff --git a/plugin-packs/postcss-preset-env/src/plugins/plugins-options.ts b/plugin-packs/postcss-preset-env/src/plugins/plugins-options.ts index 19a69f00a..614e83f98 100644 --- a/plugin-packs/postcss-preset-env/src/plugins/plugins-options.ts +++ b/plugin-packs/postcss-preset-env/src/plugins/plugins-options.ts @@ -1,171 +1,171 @@ -import type { pluginOptions as postcssInitial } from '@csstools/postcss-initial'; -import type { pluginOptions as postcssPseudoClassAnyLink } from 'postcss-pseudo-class-any-link'; -import type { pluginOptions as postcssBlankPseudo } from 'css-blank-pseudo'; -import type { pluginOptions as postcssPageBreak } from '../types/postcss-page-break/plugin-options'; -import type { pluginOptions as postcssCascadeLayers } from '@csstools/postcss-cascade-layers'; -import type { pluginOptions as postcssAttributeCaseInsensitive } from 'postcss-attribute-case-insensitive'; -import type { pluginOptions as postcssClamp } from '../types/postcss-clamp/plugin-options'; -import type { pluginOptions as postcssColorFunction } from '@csstools/postcss-color-function'; -import type { pluginOptions as postcssColorFunctionalNotation } from 'postcss-color-functional-notation'; -import type { pluginOptions as postcssColorMixFunction } from '@csstools/postcss-color-mix-function'; -import type { pluginOptions as postcssCustomMedia } from 'postcss-custom-media'; -import type { pluginOptions as postcssCustomProperties } from 'postcss-custom-properties'; -import type { pluginOptions as postcssCustomSelectors } from 'postcss-custom-selectors'; -import type { pluginOptions as postcssDirPseudoClass } from 'postcss-dir-pseudo-class'; -import type { pluginOptions as postcssNormalizeDisplayValues } from '@csstools/postcss-normalize-display-values'; -import type { pluginOptions as postcssDoublePositionGradients } from 'postcss-double-position-gradients'; -import type { pluginOptions as postcssExponentialFunctions } from '@csstools/postcss-exponential-functions'; -import type { pluginOptions as postcssLogicalFloatAndClear } from '@csstools/postcss-logical-float-and-clear'; -import type { pluginOptions as postcssFocusVisible } from 'postcss-focus-visible'; -import type { pluginOptions as postcssFocusWithin } from 'postcss-focus-within'; -import type { pluginOptions as postcssFontFormatKeywords } from '@csstools/postcss-font-format-keywords'; -import type { pluginOptions as postcssFontVariant } from '../types/postcss-font-variant/plugin-options'; -import type { pluginOptions as postcssGamutMapping } from '@csstools/postcss-gamut-mapping'; -import type { pluginOptions as postcssGapProperties } from 'postcss-gap-properties'; -import type { pluginOptions as postcssGradientsInterpolationMethod } from '@csstools/postcss-gradients-interpolation-method'; -import type { pluginOptions as postcssHasPseudo } from 'css-has-pseudo'; -import type { pluginOptions as postcssColorHexAlpha } from 'postcss-color-hex-alpha'; -import type { pluginOptions as postcssHWBFunction } from '@csstools/postcss-hwb-function'; -import type { pluginOptions as postcssICUnit } from '@csstools/postcss-ic-unit'; -import type { pluginOptions as postcssImageSetFunction } from 'postcss-image-set-function'; -import type { pluginOptions as postcssIsPseudoClass } from '@csstools/postcss-is-pseudo-class'; -import type { pluginOptions as postcssLabFunction } from 'postcss-lab-function'; -import type { pluginOptions as postcssLogicalOverflow } from '@csstools/postcss-logical-overflow'; -import type { pluginOptions as postcssLogicalOverscrollBehavor } from '@csstools/postcss-logical-overscroll-behavior'; -import type { pluginOptions as postcssLogical } from 'postcss-logical'; -import type { pluginOptions as postcssLogicalResize } from '@csstools/postcss-logical-resize'; -import type { pluginOptions as postcssLogicalViewportUnits } from '@csstools/postcss-logical-viewport-units'; -import type { pluginOptions as postcssMediaQueriesAspectRatioNumberValues } from '@csstools/postcss-media-queries-aspect-ratio-number-values'; -import type { pluginOptions as postcssMediaMinmax } from '@csstools/postcss-media-minmax'; -import type { pluginOptions as postcssNestedCalc } from '@csstools/postcss-nested-calc'; -import type { pluginOptions as postcssNesting } from 'postcss-nesting'; -import type { pluginOptions as postcssSelectorNot } from 'postcss-selector-not'; -import type { pluginOptions as postcssOKLabFunction } from '@csstools/postcss-oklab-function'; -import type { pluginOptions as postcssOpacityPercentage } from '../types/postcss-opacity-percentage/plugin-options'; -import type { pluginOptions as postcssOverflowShorthand } from 'postcss-overflow-shorthand'; -import type { pluginOptions as postcssReplaceOverflowWrap } from '../types/postcss-replace-overflow-wrap/plugin-options'; -import type { pluginOptions as postcssPlace } from 'postcss-place'; -import type { pluginOptions as postcssPrefersColorScheme } from 'css-prefers-color-scheme'; -import type { pluginOptions as postcssColorRebeccapurple } from 'postcss-color-rebeccapurple'; -import type { pluginOptions as postcssRelativeColorSyntax } from '@csstools/postcss-relative-color-syntax'; -import type { pluginOptions as postcssScopePseudoClass } from '@csstools/postcss-scope-pseudo-class'; -import type { pluginOptions as postcssSteppedValueFunctions } from '@csstools/postcss-stepped-value-functions'; -import type { pluginOptions as postcssFontFamilySystemUI } from '../types/postcss-system-ui-font-family/plugin-options'; -import type { pluginOptions as postcssTextDecorationShorthand } from '@csstools/postcss-text-decoration-shorthand'; -import type { pluginOptions as postcssTrigonometricFunctions } from '@csstools/postcss-trigonometric-functions'; -import type { pluginOptions as postcssUnsetValue } from '@csstools/postcss-unset-value'; +import type { pluginOptions as postcssInitialOptions } from '@csstools/postcss-initial'; +import type { pluginOptions as postcssPseudoClassAnyLinkOptions } from 'postcss-pseudo-class-any-link'; +import type { pluginOptions as postcssBlankPseudoOptions } from 'css-blank-pseudo'; +import type { postcssPageBreakOptions } from '../types/postcss-page-break/plugin-options'; +import type { pluginOptions as postcssCascadeLayersOptions } from '@csstools/postcss-cascade-layers'; +import type { pluginOptions as postcssAttributeCaseInsensitiveOptions } from 'postcss-attribute-case-insensitive'; +import type { postcssClampOptions } from '../types/postcss-clamp/plugin-options'; +import type { pluginOptions as postcssColorFunctionOptions } from '@csstools/postcss-color-function'; +import type { pluginOptions as postcssColorFunctionalNotationOptions } from 'postcss-color-functional-notation'; +import type { pluginOptions as postcssColorMixFunctionOptions } from '@csstools/postcss-color-mix-function'; +import type { pluginOptions as postcssCustomMediaOptions } from 'postcss-custom-media'; +import type { pluginOptions as postcssCustomPropertiesOptions } from 'postcss-custom-properties'; +import type { pluginOptions as postcssCustomSelectorsOptions } from 'postcss-custom-selectors'; +import type { pluginOptions as postcssDirPseudoClassOptions } from 'postcss-dir-pseudo-class'; +import type { pluginOptions as postcssNormalizeDisplayValuesOptions } from '@csstools/postcss-normalize-display-values'; +import type { pluginOptions as postcssDoublePositionGradientsOptions } from 'postcss-double-position-gradients'; +import type { pluginOptions as postcssExponentialFunctionsOptions } from '@csstools/postcss-exponential-functions'; +import type { pluginOptions as postcssLogicalFloatAndClearOptions } from '@csstools/postcss-logical-float-and-clear'; +import type { pluginOptions as postcssFocusVisibleOptions } from 'postcss-focus-visible'; +import type { pluginOptions as postcssFocusWithinOptions } from 'postcss-focus-within'; +import type { pluginOptions as postcssFontFormatKeywordsOptions } from '@csstools/postcss-font-format-keywords'; +import type { postcssFontVariantOptions } from '../types/postcss-font-variant/plugin-options'; +import type { pluginOptions as postcssGamutMappingOptions } from '@csstools/postcss-gamut-mapping'; +import type { pluginOptions as postcssGapPropertiesOptions } from 'postcss-gap-properties'; +import type { pluginOptions as postcssGradientsInterpolationMethodOptions } from '@csstools/postcss-gradients-interpolation-method'; +import type { pluginOptions as postcssHasPseudoOptions } from 'css-has-pseudo'; +import type { pluginOptions as postcssColorHexAlphaOptions } from 'postcss-color-hex-alpha'; +import type { pluginOptions as postcssHWBFunctionOptions } from '@csstools/postcss-hwb-function'; +import type { pluginOptions as postcssICUnitOptions } from '@csstools/postcss-ic-unit'; +import type { pluginOptions as postcssImageSetFunctionOptions } from 'postcss-image-set-function'; +import type { pluginOptions as postcssIsPseudoClassOptions } from '@csstools/postcss-is-pseudo-class'; +import type { pluginOptions as postcssLabFunctionOptions } from 'postcss-lab-function'; +import type { pluginOptions as postcssLogicalOverflowOptions } from '@csstools/postcss-logical-overflow'; +import type { pluginOptions as postcssLogicalOverscrollBehavorOptions } from '@csstools/postcss-logical-overscroll-behavior'; +import type { pluginOptions as postcssLogicalOptions } from 'postcss-logical'; +import type { pluginOptions as postcssLogicalResizeOptions } from '@csstools/postcss-logical-resize'; +import type { pluginOptions as postcssLogicalViewportUnitsOptions } from '@csstools/postcss-logical-viewport-units'; +import type { pluginOptions as postcssMediaQueriesAspectRatioNumberValuesOptions } from '@csstools/postcss-media-queries-aspect-ratio-number-values'; +import type { pluginOptions as postcssMediaMinmaxOptions } from '@csstools/postcss-media-minmax'; +import type { pluginOptions as postcssNestedCalcOptions } from '@csstools/postcss-nested-calc'; +import type { pluginOptions as postcssNestingOptions } from 'postcss-nesting'; +import type { pluginOptions as postcssSelectorNotOptions } from 'postcss-selector-not'; +import type { pluginOptions as postcssOKLabFunctionOptions } from '@csstools/postcss-oklab-function'; +import type { postcssOpacityPercentageOptions } from '../types/postcss-opacity-percentage/plugin-options'; +import type { pluginOptions as postcssOverflowShorthandOptions } from 'postcss-overflow-shorthand'; +import type { postcssReplaceOverflowWrapOptions } from '../types/postcss-replace-overflow-wrap/plugin-options'; +import type { pluginOptions as postcssPlaceOptions } from 'postcss-place'; +import type { pluginOptions as postcssPrefersColorSchemeOptions } from 'css-prefers-color-scheme'; +import type { pluginOptions as postcssColorRebeccapurpleOptions } from 'postcss-color-rebeccapurple'; +import type { pluginOptions as postcssRelativeColorSyntaxOptions } from '@csstools/postcss-relative-color-syntax'; +import type { pluginOptions as postcssScopePseudoClassOptions } from '@csstools/postcss-scope-pseudo-class'; +import type { pluginOptions as postcssSteppedValueFunctionsOptions } from '@csstools/postcss-stepped-value-functions'; +import type { postcssFontFamilySystemUIOptions } from '../types/postcss-system-ui-font-family/plugin-options'; +import type { pluginOptions as postcssTextDecorationShorthandOptions } from '@csstools/postcss-text-decoration-shorthand'; +import type { pluginOptions as postcssTrigonometricFunctionsOptions } from '@csstools/postcss-trigonometric-functions'; +import type { pluginOptions as postcssUnsetValueOptions } from '@csstools/postcss-unset-value'; export type pluginsOptions = { /** plugin options for "@csstools/postcss-initial" */ - 'all-property'?: postcssInitial | boolean + 'all-property'?: postcssInitialOptions | boolean /** plugin options for "postcss-pseudo-class-any-link" */ - 'any-link-pseudo-class'?: postcssPseudoClassAnyLink | boolean + 'any-link-pseudo-class'?: postcssPseudoClassAnyLinkOptions | boolean /** plugin options for "css-blank-pseudo" */ - 'blank-pseudo-class'?: postcssBlankPseudo | boolean + 'blank-pseudo-class'?: postcssBlankPseudoOptions | boolean /** plugin options for "postcss-page-break" */ - 'break-properties'?: postcssPageBreak | boolean + 'break-properties'?: postcssPageBreakOptions | boolean /** plugin options for "@csstools/postcss-cascade-layers" */ - 'cascade-layers'?: postcssCascadeLayers | boolean + 'cascade-layers'?: postcssCascadeLayersOptions | boolean /** plugin options for "postcss-attribute-case-insensitive" */ - 'case-insensitive-attributes'?: postcssAttributeCaseInsensitive | boolean + 'case-insensitive-attributes'?: postcssAttributeCaseInsensitiveOptions | boolean /** plugin options for "postcss-clamp" */ - 'clamp'?: postcssClamp | boolean + 'clamp'?: postcssClampOptions | boolean /** plugin options for "@csstools/postcss-color-function" */ - 'color-function'?: postcssColorFunction | boolean + 'color-function'?: postcssColorFunctionOptions | boolean /** plugin options for "postcss-color-functional-notation" */ - 'color-functional-notation'?: postcssColorFunctionalNotation | boolean + 'color-functional-notation'?: postcssColorFunctionalNotationOptions | boolean /** plugin options for "@csstools/postcss-color-mix-function" */ - 'color-mix'?: postcssColorMixFunction | boolean + 'color-mix'?: postcssColorMixFunctionOptions | boolean /** plugin options for "postcss-custom-media" */ - 'custom-media-queries'?: postcssCustomMedia | boolean + 'custom-media-queries'?: postcssCustomMediaOptions | boolean /** plugin options for "postcss-custom-properties" */ - 'custom-properties'?: postcssCustomProperties | boolean + 'custom-properties'?: postcssCustomPropertiesOptions | boolean /** plugin options for "postcss-custom-selectors" */ - 'custom-selectors'?: postcssCustomSelectors | boolean + 'custom-selectors'?: postcssCustomSelectorsOptions | boolean /** plugin options for "postcss-dir-pseudo-class" */ - 'dir-pseudo-class'?: postcssDirPseudoClass | boolean + 'dir-pseudo-class'?: postcssDirPseudoClassOptions | boolean /** plugin options for "@csstools/postcss-normalize-display-values" */ - 'display-two-values'?: postcssNormalizeDisplayValues | boolean + 'display-two-values'?: postcssNormalizeDisplayValuesOptions | boolean /** plugin options for "postcss-double-position-gradients" */ - 'double-position-gradients'?: postcssDoublePositionGradients | boolean + 'double-position-gradients'?: postcssDoublePositionGradientsOptions | boolean /** plugin options for "@csstools/postcss-exponential-functions" */ - 'exponential-functions'?: postcssExponentialFunctions | boolean + 'exponential-functions'?: postcssExponentialFunctionsOptions | boolean /** plugin options for "@csstools/postcss-logical-float-and-clear" */ - 'float-clear-logical-values'?: postcssLogicalFloatAndClear | boolean + 'float-clear-logical-values'?: postcssLogicalFloatAndClearOptions | boolean /** plugin options for "postcss-focus-visible" */ - 'focus-visible-pseudo-class'?: postcssFocusVisible | boolean + 'focus-visible-pseudo-class'?: postcssFocusVisibleOptions | boolean /** plugin options for "postcss-focus-within" */ - 'focus-within-pseudo-class'?: postcssFocusWithin | boolean + 'focus-within-pseudo-class'?: postcssFocusWithinOptions | boolean /** plugin options for "@csstools/postcss-font-format-keywords" */ - 'font-format-keywords'?: postcssFontFormatKeywords | boolean + 'font-format-keywords'?: postcssFontFormatKeywordsOptions | boolean /** plugin options for "postcss-font-variant" */ - 'font-variant-property'?: postcssFontVariant | boolean + 'font-variant-property'?: postcssFontVariantOptions | boolean /** plugin options for "@csstools/postcss-gamut-mapping" */ - 'gamut-mapping'?: postcssGamutMapping | boolean + 'gamut-mapping'?: postcssGamutMappingOptions | boolean /** plugin options for "postcss-gap-properties" */ - 'gap-properties'?: postcssGapProperties | boolean + 'gap-properties'?: postcssGapPropertiesOptions | boolean /** plugin options for "@csstools/postcss-gradients-interpolation-method" */ - 'gradients-interpolation-method'?: postcssGradientsInterpolationMethod | boolean + 'gradients-interpolation-method'?: postcssGradientsInterpolationMethodOptions | boolean /** plugin options for "css-has-pseudo" */ - 'has-pseudo-class'?: postcssHasPseudo | boolean + 'has-pseudo-class'?: postcssHasPseudoOptions | boolean /** plugin options for "postcss-color-hex-alpha" */ - 'hexadecimal-alpha-notation'?: postcssColorHexAlpha | boolean + 'hexadecimal-alpha-notation'?: postcssColorHexAlphaOptions | boolean /** plugin options for "@csstools/postcss-hwb-function" */ - 'hwb-function'?: postcssHWBFunction | boolean + 'hwb-function'?: postcssHWBFunctionOptions | boolean /** plugin options for "@csstools/postcss-ic-unit" */ - 'ic-unit'?: postcssICUnit | boolean + 'ic-unit'?: postcssICUnitOptions | boolean /** plugin options for "postcss-image-set-function" */ - 'image-set-function'?: postcssImageSetFunction | boolean + 'image-set-function'?: postcssImageSetFunctionOptions | boolean /** plugin options for "@csstools/postcss-is-pseudo-class" */ - 'is-pseudo-class'?: postcssIsPseudoClass | boolean + 'is-pseudo-class'?: postcssIsPseudoClassOptions | boolean /** plugin options for "postcss-lab-function" */ - 'lab-function'?: postcssLabFunction | boolean + 'lab-function'?: postcssLabFunctionOptions | boolean /** plugin options for "@csstools/postcss-logical-overflow" */ - 'logical-overflow'?: postcssLogicalOverflow | boolean + 'logical-overflow'?: postcssLogicalOverflowOptions | boolean /** plugin options for "@csstools/postcss-logical-overscroll-behavior" */ - 'logical-overscroll-behavior'?: postcssLogicalOverscrollBehavor | boolean + 'logical-overscroll-behavior'?: postcssLogicalOverscrollBehavorOptions | boolean /** plugin options for "postcss-logical" */ - 'logical-properties-and-values'?: postcssLogical | boolean + 'logical-properties-and-values'?: postcssLogicalOptions | boolean /** plugin options for "@csstools/postcss-logical-resize" */ - 'logical-resize'?: postcssLogicalResize | boolean + 'logical-resize'?: postcssLogicalResizeOptions | boolean /** plugin options for "@csstools/postcss-logical-viewport-units" */ - 'logical-viewport-units'?: postcssLogicalViewportUnits | boolean + 'logical-viewport-units'?: postcssLogicalViewportUnitsOptions | boolean /** plugin options for "@csstools/postcss-media-queries-aspect-ratio-number-values" */ - 'media-queries-aspect-ratio-number-values'?: postcssMediaQueriesAspectRatioNumberValues | boolean + 'media-queries-aspect-ratio-number-values'?: postcssMediaQueriesAspectRatioNumberValuesOptions | boolean /** plugin options for "@csstools/postcss-media-minmax" */ - 'media-query-ranges'?: postcssMediaMinmax | boolean + 'media-query-ranges'?: postcssMediaMinmaxOptions | boolean /** plugin options for "@csstools/postcss-nested-calc" */ - 'nested-calc'?: postcssNestedCalc | boolean + 'nested-calc'?: postcssNestedCalcOptions | boolean /** plugin options for "postcss-nesting" */ - 'nesting-rules'?: postcssNesting | boolean + 'nesting-rules'?: postcssNestingOptions | boolean /** plugin options for "postcss-selector-not" */ - 'not-pseudo-class'?: postcssSelectorNot | boolean + 'not-pseudo-class'?: postcssSelectorNotOptions | boolean /** plugin options for "@csstools/postcss-oklab-function" */ - 'oklab-function'?: postcssOKLabFunction | boolean + 'oklab-function'?: postcssOKLabFunctionOptions | boolean /** plugin options for "postcss-opacity-percentage" */ - 'opacity-percentage'?: postcssOpacityPercentage | boolean + 'opacity-percentage'?: postcssOpacityPercentageOptions | boolean /** plugin options for "postcss-overflow-shorthand" */ - 'overflow-property'?: postcssOverflowShorthand | boolean + 'overflow-property'?: postcssOverflowShorthandOptions | boolean /** plugin options for "postcss-replace-overflow-wrap" */ - 'overflow-wrap-property'?: postcssReplaceOverflowWrap | boolean + 'overflow-wrap-property'?: postcssReplaceOverflowWrapOptions | boolean /** plugin options for "postcss-place" */ - 'place-properties'?: postcssPlace | boolean + 'place-properties'?: postcssPlaceOptions | boolean /** plugin options for "css-prefers-color-scheme" */ - 'prefers-color-scheme-query'?: postcssPrefersColorScheme | boolean + 'prefers-color-scheme-query'?: postcssPrefersColorSchemeOptions | boolean /** plugin options for "postcss-color-rebeccapurple" */ - 'rebeccapurple-color'?: postcssColorRebeccapurple | boolean + 'rebeccapurple-color'?: postcssColorRebeccapurpleOptions | boolean /** plugin options for "@csstools/postcss-relative-color-syntax" */ - 'relative-color-syntax'?: postcssRelativeColorSyntax | boolean + 'relative-color-syntax'?: postcssRelativeColorSyntaxOptions | boolean /** plugin options for "@csstools/postcss-scope-pseudo-class" */ - 'scope-pseudo-class'?: postcssScopePseudoClass | boolean + 'scope-pseudo-class'?: postcssScopePseudoClassOptions | boolean /** plugin options for "@csstools/postcss-stepped-value-functions" */ - 'stepped-value-functions'?: postcssSteppedValueFunctions | boolean + 'stepped-value-functions'?: postcssSteppedValueFunctionsOptions | boolean /** plugin options for "postcss-system-ui-font-family" */ - 'system-ui-font-family'?: postcssFontFamilySystemUI | boolean + 'system-ui-font-family'?: postcssFontFamilySystemUIOptions | boolean /** plugin options for "@csstools/postcss-text-decoration-shorthand" */ - 'text-decoration-shorthand'?: postcssTextDecorationShorthand | boolean + 'text-decoration-shorthand'?: postcssTextDecorationShorthandOptions | boolean /** plugin options for "@csstools/postcss-trigonometric-functions" */ - 'trigonometric-functions'?: postcssTrigonometricFunctions | boolean + 'trigonometric-functions'?: postcssTrigonometricFunctionsOptions | boolean /** plugin options for "@csstools/postcss-unset-value" */ - 'unset-value'?: postcssUnsetValue | boolean + 'unset-value'?: postcssUnsetValueOptions | boolean }; diff --git a/plugin-packs/postcss-preset-env/src/types/postcss-clamp/plugin-options.ts b/plugin-packs/postcss-preset-env/src/types/postcss-clamp/plugin-options.ts index d1e433440..4923e497a 100644 --- a/plugin-packs/postcss-preset-env/src/types/postcss-clamp/plugin-options.ts +++ b/plugin-packs/postcss-preset-env/src/types/postcss-clamp/plugin-options.ts @@ -1,5 +1,5 @@ /** postcss-clamp plugin options */ -export type pluginOptions = { +export type postcssClampOptions = { /** Preserve the original notation. default: false */ preserve?: boolean, /** diff --git a/plugin-packs/postcss-preset-env/src/types/postcss-font-variant/plugin-options.ts b/plugin-packs/postcss-preset-env/src/types/postcss-font-variant/plugin-options.ts index b539e77b2..dc65dae3e 100644 --- a/plugin-packs/postcss-preset-env/src/types/postcss-font-variant/plugin-options.ts +++ b/plugin-packs/postcss-preset-env/src/types/postcss-font-variant/plugin-options.ts @@ -1,2 +1,2 @@ /** postcss-font-variant plugin options */ -export type pluginOptions = Record; +export type postcssFontVariantOptions = Record; diff --git a/plugin-packs/postcss-preset-env/src/types/postcss-opacity-percentage/plugin-options.ts b/plugin-packs/postcss-preset-env/src/types/postcss-opacity-percentage/plugin-options.ts index 53ece950a..55756841d 100644 --- a/plugin-packs/postcss-preset-env/src/types/postcss-opacity-percentage/plugin-options.ts +++ b/plugin-packs/postcss-preset-env/src/types/postcss-opacity-percentage/plugin-options.ts @@ -1,5 +1,5 @@ /** postcss-opacity-percentage plugin options */ -export type pluginOptions = { +export type postcssOpacityPercentageOptions = { /** Preserve the original notation. default: false */ preserve?: boolean, }; diff --git a/plugin-packs/postcss-preset-env/src/types/postcss-page-break/plugin-options.ts b/plugin-packs/postcss-preset-env/src/types/postcss-page-break/plugin-options.ts index 05d36d940..176971042 100644 --- a/plugin-packs/postcss-preset-env/src/types/postcss-page-break/plugin-options.ts +++ b/plugin-packs/postcss-preset-env/src/types/postcss-page-break/plugin-options.ts @@ -1,2 +1,2 @@ /** postcss-page-break plugin options */ -export type pluginOptions = Record; +export type postcssPageBreakOptions = Record; diff --git a/plugin-packs/postcss-preset-env/src/types/postcss-replace-overflow-wrap/plugin-options.ts b/plugin-packs/postcss-preset-env/src/types/postcss-replace-overflow-wrap/plugin-options.ts index d3e75c54d..25dafa819 100644 --- a/plugin-packs/postcss-preset-env/src/types/postcss-replace-overflow-wrap/plugin-options.ts +++ b/plugin-packs/postcss-preset-env/src/types/postcss-replace-overflow-wrap/plugin-options.ts @@ -1,5 +1,5 @@ /** postcss-replace-overflow-wrap plugin options */ -export type pluginOptions = { +export type postcssReplaceOverflowWrapOptions = { /** Preserve the original notation. default: false */ preserve?: boolean, }; diff --git a/plugin-packs/postcss-preset-env/src/types/postcss-system-ui-font-family/plugin-options.ts b/plugin-packs/postcss-preset-env/src/types/postcss-system-ui-font-family/plugin-options.ts index 6a5f429da..5aa4f5c18 100644 --- a/plugin-packs/postcss-preset-env/src/types/postcss-system-ui-font-family/plugin-options.ts +++ b/plugin-packs/postcss-preset-env/src/types/postcss-system-ui-font-family/plugin-options.ts @@ -1,2 +1,2 @@ /** postcss-system-ui-font-family plugin options */ -export type pluginOptions = Record; +export type postcssFontFamilySystemUIOptions = Record; diff --git a/plugins/css-blank-pseudo/CHANGELOG.md b/plugins/css-blank-pseudo/CHANGELOG.md index 1091212d6..62d9497f4 100644 --- a/plugins/css-blank-pseudo/CHANGELOG.md +++ b/plugins/css-blank-pseudo/CHANGELOG.md @@ -1,5 +1,9 @@ # Changes to CSS Blank Pseudo +### Unreleased (patch) + +- Fix type definitions + ### 6.0.0 _July 3, 2023_ diff --git a/plugins/css-blank-pseudo/api-extractor.json b/plugins/css-blank-pseudo/api-extractor.json new file mode 100644 index 000000000..42058be51 --- /dev/null +++ b/plugins/css-blank-pseudo/api-extractor.json @@ -0,0 +1,4 @@ +{ + "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json", + "extends": "../../api-extractor.json" +} diff --git a/plugins/css-blank-pseudo/dist/index.cjs b/plugins/css-blank-pseudo/dist/index.cjs index 7a62f4dad..e4fcf78d5 100644 --- a/plugins/css-blank-pseudo/dist/index.cjs +++ b/plugins/css-blank-pseudo/dist/index.cjs @@ -1 +1 @@ -"use strict";var e=require("postcss-selector-parser");const s=[" ",">","~",":","+","@","#","(",")"];function isValidReplacement(e){let n=!0;for(let t=0,l=s.length;t-1&&(n=!1);return n}const n="js-blank-pseudo",t=":blank",creator=s=>{const l=Object.assign({preserve:!0,replaceWith:"[blank]",disablePolyfillReadyClass:!1},s),r=e().astSync(l.replaceWith);return isValidReplacement(l.replaceWith)?{postcssPlugin:"css-blank-pseudo",prepare(){const s=new WeakSet;return{Rule(o,{result:a}){if(s.has(o))return;if(!o.selector.toLowerCase().includes(t))return;const i=o.selectors.flatMap((s=>{if(!s.toLowerCase().includes(t))return[s];let i;try{i=e().astSync(s)}catch(e){return o.warn(a,`Failed to parse selector : "${s}" with message: "${e instanceof Error?e.message:e}"`),[s]}if(void 0===i)return[s];let c=!1;if(i.walkPseudos((e=>{e.value.toLowerCase()===t&&(e.nodes&&e.nodes.length||(c=!0,e.replaceWith(r.clone({}))))})),!c)return[s];const d=i.clone();if(!l.disablePolyfillReadyClass){var u,p;if(null!=(u=i.nodes)&&null!=(u=u[0])&&null!=(u=u.nodes)&&u.length)for(let s=0;s{e.warn(s,`${l.replaceWith} is not a valid replacement since it can't be applied to single elements.`)}}};creator.postcss=!0,module.exports=creator; +"use strict";var e=require("postcss-selector-parser");const s=[" ",">","~",":","+","@","#","(",")"];function isValidReplacement(e){let n=!0;for(let t=0,r=s.length;t-1&&(n=!1);return n}const n="js-blank-pseudo",t=":blank",creator=s=>{const r=Object.assign({preserve:!0,replaceWith:"[blank]",disablePolyfillReadyClass:!1},s),o=e().astSync(r.replaceWith);return isValidReplacement(r.replaceWith)?{postcssPlugin:"css-blank-pseudo",prepare(){const s=new WeakSet;return{Rule(l,{result:a}){if(s.has(l))return;if(!l.selector.toLowerCase().includes(t))return;const i=l.selectors.flatMap((s=>{if(!s.toLowerCase().includes(t))return[s];let i;try{i=e().astSync(s)}catch(e){return l.warn(a,`Failed to parse selector : "${s}" with message: "${e instanceof Error?e.message:e}"`),[s]}if(void 0===i)return[s];let c=!1;if(i.walkPseudos((e=>{e.value.toLowerCase()===t&&(e.nodes&&e.nodes.length||(c=!0,e.replaceWith(o.clone({}))))})),!c)return[s];const d=i.clone();if(!r.disablePolyfillReadyClass){if(i.nodes?.[0]?.nodes?.length)for(let s=0;s{e.warn(s,`${r.replaceWith} is not a valid replacement since it can't be applied to single elements.`)}}};creator.postcss=!0,module.exports=creator; diff --git a/plugins/css-blank-pseudo/dist/index.d.ts b/plugins/css-blank-pseudo/dist/index.d.ts index 488c813e6..d19920638 100644 --- a/plugins/css-blank-pseudo/dist/index.d.ts +++ b/plugins/css-blank-pseudo/dist/index.d.ts @@ -1,6 +1,10 @@ import type { PluginCreator } from 'postcss'; + +declare const creator: PluginCreator; +export default creator; + /** css-blank-pseudo plugin options */ -export type pluginOptions = { +export declare type pluginOptions = { /** Preserve the original notation. default: true */ preserve?: boolean; /** Replacement for ":blank". default: "[blank]" */ @@ -8,5 +12,5 @@ export type pluginOptions = { /** Do not inject "js-blank-pseudo" before each selector with "[blank]". default: false */ disablePolyfillReadyClass?: boolean; }; -declare const creator: PluginCreator; -export default creator; + +export { } diff --git a/plugins/css-blank-pseudo/dist/index.mjs b/plugins/css-blank-pseudo/dist/index.mjs index 2f258574f..2e579041e 100644 --- a/plugins/css-blank-pseudo/dist/index.mjs +++ b/plugins/css-blank-pseudo/dist/index.mjs @@ -1 +1 @@ -import e from"postcss-selector-parser";const s=[" ",">","~",":","+","@","#","(",")"];function isValidReplacement(e){let n=!0;for(let t=0,l=s.length;t-1&&(n=!1);return n}const n="js-blank-pseudo",t=":blank",creator=s=>{const l=Object.assign({preserve:!0,replaceWith:"[blank]",disablePolyfillReadyClass:!1},s),o=e().astSync(l.replaceWith);return isValidReplacement(l.replaceWith)?{postcssPlugin:"css-blank-pseudo",prepare(){const s=new WeakSet;return{Rule(r,{result:a}){if(s.has(r))return;if(!r.selector.toLowerCase().includes(t))return;const i=r.selectors.flatMap((s=>{if(!s.toLowerCase().includes(t))return[s];let i;try{i=e().astSync(s)}catch(e){return r.warn(a,`Failed to parse selector : "${s}" with message: "${e instanceof Error?e.message:e}"`),[s]}if(void 0===i)return[s];let c=!1;if(i.walkPseudos((e=>{e.value.toLowerCase()===t&&(e.nodes&&e.nodes.length||(c=!0,e.replaceWith(o.clone({}))))})),!c)return[s];const d=i.clone();if(!l.disablePolyfillReadyClass){var u,p;if(null!=(u=i.nodes)&&null!=(u=u[0])&&null!=(u=u.nodes)&&u.length)for(let s=0;s{e.warn(s,`${l.replaceWith} is not a valid replacement since it can't be applied to single elements.`)}}};creator.postcss=!0;export{creator as default}; +import e from"postcss-selector-parser";const s=[" ",">","~",":","+","@","#","(",")"];function isValidReplacement(e){let n=!0;for(let t=0,o=s.length;t-1&&(n=!1);return n}const n="js-blank-pseudo",t=":blank",creator=s=>{const o=Object.assign({preserve:!0,replaceWith:"[blank]",disablePolyfillReadyClass:!1},s),r=e().astSync(o.replaceWith);return isValidReplacement(o.replaceWith)?{postcssPlugin:"css-blank-pseudo",prepare(){const s=new WeakSet;return{Rule(l,{result:a}){if(s.has(l))return;if(!l.selector.toLowerCase().includes(t))return;const i=l.selectors.flatMap((s=>{if(!s.toLowerCase().includes(t))return[s];let i;try{i=e().astSync(s)}catch(e){return l.warn(a,`Failed to parse selector : "${s}" with message: "${e instanceof Error?e.message:e}"`),[s]}if(void 0===i)return[s];let c=!1;if(i.walkPseudos((e=>{e.value.toLowerCase()===t&&(e.nodes&&e.nodes.length||(c=!0,e.replaceWith(r.clone({}))))})),!c)return[s];const d=i.clone();if(!o.disablePolyfillReadyClass){if(i.nodes?.[0]?.nodes?.length)for(let s=0;s{e.warn(s,`${o.replaceWith} is not a valid replacement since it can't be applied to single elements.`)}}};creator.postcss=!0;export{creator as default}; diff --git a/plugins/css-blank-pseudo/package.json b/plugins/css-blank-pseudo/package.json index 85362002b..0c4ef87fc 100644 --- a/plugins/css-blank-pseudo/package.json +++ b/plugins/css-blank-pseudo/package.json @@ -31,15 +31,18 @@ "engines": { "node": "^14 || ^16 || >=18" }, + "type": "module", "main": "dist/index.cjs", "module": "dist/index.mjs", - "types": "dist/index.d.ts", "exports": { ".": { - "types": "./dist/index.d.ts", - "import": "./dist/index.mjs", - "require": "./dist/index.cjs", - "default": "./dist/index.mjs" + "import": { + "types": "./dist/index.d.ts", + "default": "./dist/index.mjs" + }, + "require": { + "default": "./dist/index.cjs" + } }, "./browser": { "import": "./dist/browser.mjs", diff --git a/plugins/css-blank-pseudo/src/index.ts b/plugins/css-blank-pseudo/src/index.ts index 875798615..8477b848f 100644 --- a/plugins/css-blank-pseudo/src/index.ts +++ b/plugins/css-blank-pseudo/src/index.ts @@ -109,6 +109,7 @@ const creator: PluginCreator = (opts?: pluginOptions) => { if (i === selectorAST.nodes[0].nodes.length - 1) { // Append the class to the end of the selector if no combinator or pseudo element was found. + // @ts-expect-error https://github.com/postcss/postcss-selector-parser/pull/284 selectorAST.nodes[0].append(parser.className({ value: POLYFILL_READY_CLASSNAME })); break; } @@ -117,7 +118,9 @@ const creator: PluginCreator = (opts?: pluginOptions) => { if (selectorAST.nodes?.[0]?.nodes) { // Prepend a space combinator and the class to the beginning of the selector. + // @ts-expect-error https://github.com/postcss/postcss-selector-parser/pull/284 selectorASTClone.nodes[0].prepend(parser.combinator({ value: ' ' })); + // @ts-expect-error https://github.com/postcss/postcss-selector-parser/pull/284 selectorASTClone.nodes[0].prepend(parser.className({ value: POLYFILL_READY_CLASSNAME })); } diff --git a/plugins/css-has-pseudo/CHANGELOG.md b/plugins/css-has-pseudo/CHANGELOG.md index a6c0b6668..e8c95c5d9 100644 --- a/plugins/css-has-pseudo/CHANGELOG.md +++ b/plugins/css-has-pseudo/CHANGELOG.md @@ -2,7 +2,7 @@ ### Unreleased (patch) -- Small fixes in type definitions +- Fix type definitions ### 6.0.0 diff --git a/plugins/css-has-pseudo/api-extractor.json b/plugins/css-has-pseudo/api-extractor.json new file mode 100644 index 000000000..42058be51 --- /dev/null +++ b/plugins/css-has-pseudo/api-extractor.json @@ -0,0 +1,4 @@ +{ + "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json", + "extends": "../../api-extractor.json" +} diff --git a/plugins/css-has-pseudo/dist/index.d.ts b/plugins/css-has-pseudo/dist/index.d.ts index 2f29343ac..fa7b73629 100644 --- a/plugins/css-has-pseudo/dist/index.d.ts +++ b/plugins/css-has-pseudo/dist/index.d.ts @@ -1,10 +1,14 @@ import type { PluginCreator } from 'postcss'; + +declare const creator: PluginCreator; +export default creator; + /** css-has-pseudo plugin options */ -export type pluginOptions = { +export declare type pluginOptions = { /** Preserve the original notation. default: true */ preserve?: boolean; /** Change the selector that is used to adjust specificity. default: "does-not-exist" */ specificityMatchingName?: string; }; -declare const creator: PluginCreator; -export default creator; + +export { } diff --git a/plugins/css-has-pseudo/dist/is-guarded-by-at-supports.d.ts b/plugins/css-has-pseudo/dist/is-guarded-by-at-supports.d.ts deleted file mode 100644 index 6cc9d4d69..000000000 --- a/plugins/css-has-pseudo/dist/is-guarded-by-at-supports.d.ts +++ /dev/null @@ -1 +0,0 @@ -export declare function isGuardedByAtSupportsFromAtRuleParams(atSupportsParams: string): boolean; diff --git a/plugins/css-has-pseudo/package.json b/plugins/css-has-pseudo/package.json index 0592dac22..f01d12b6a 100644 --- a/plugins/css-has-pseudo/package.json +++ b/plugins/css-has-pseudo/package.json @@ -31,15 +31,18 @@ "engines": { "node": "^14 || ^16 || >=18" }, + "type": "module", "main": "dist/index.cjs", "module": "dist/index.mjs", - "types": "dist/index.d.ts", "exports": { ".": { - "types": "./dist/index.d.ts", - "import": "./dist/index.mjs", - "require": "./dist/index.cjs", - "default": "./dist/index.mjs" + "import": { + "types": "./dist/index.d.ts", + "default": "./dist/index.mjs" + }, + "require": { + "default": "./dist/index.cjs" + } }, "./browser": { "import": "./dist/browser.mjs", diff --git a/plugins/css-has-pseudo/src/index.ts b/plugins/css-has-pseudo/src/index.ts index 0f866cfd7..6476ae9cd 100644 --- a/plugins/css-has-pseudo/src/index.ts +++ b/plugins/css-has-pseudo/src/index.ts @@ -136,10 +136,12 @@ const creator: PluginCreator = (opts?: pluginOptions) => { if (x.type === 'selector') { x.nodes.forEach((y) => { delete y.parent; + // @ts-expect-error https://github.com/postcss/postcss-selector-parser/pull/284 hasContainingSelector.append(y); }); } else { delete x.parent; + // @ts-expect-error https://github.com/postcss/postcss-selector-parser/pull/284 hasContainingSelector.append(x); } }); @@ -165,6 +167,7 @@ const creator: PluginCreator = (opts?: pluginOptions) => { const replacementNodes = encodedSelectorAST.nodes[0].nodes; for (let i = replacementNodes.length - 1; i >= 0; i--) { + // @ts-expect-error https://github.com/postcss/postcss-selector-parser/pull/284 container.prepend(replacementNodes[i]); } }); diff --git a/plugins/css-prefers-color-scheme/CHANGELOG.md b/plugins/css-prefers-color-scheme/CHANGELOG.md index d27db4888..5a8fe6451 100644 --- a/plugins/css-prefers-color-scheme/CHANGELOG.md +++ b/plugins/css-prefers-color-scheme/CHANGELOG.md @@ -1,5 +1,9 @@ # Changes to Prefers Color Scheme +### Unreleased (patch) + +- Fix type definitions + ### 9.0.0 _July 3, 2023_ diff --git a/plugins/css-prefers-color-scheme/api-extractor.json b/plugins/css-prefers-color-scheme/api-extractor.json new file mode 100644 index 000000000..42058be51 --- /dev/null +++ b/plugins/css-prefers-color-scheme/api-extractor.json @@ -0,0 +1,4 @@ +{ + "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json", + "extends": "../../api-extractor.json" +} diff --git a/plugins/css-prefers-color-scheme/dist/index.d.ts b/plugins/css-prefers-color-scheme/dist/index.d.ts index e7060b756..c401d2a20 100644 --- a/plugins/css-prefers-color-scheme/dist/index.d.ts +++ b/plugins/css-prefers-color-scheme/dist/index.d.ts @@ -1,8 +1,12 @@ import type { PluginCreator } from 'postcss'; + +declare const creator: PluginCreator; +export default creator; + /** postcss-prefers-color-scheme plugin options */ -export type pluginOptions = { +export declare type pluginOptions = { /** Preserve the original notation. default: true */ preserve?: boolean; }; -declare const creator: PluginCreator; -export default creator; + +export { } diff --git a/plugins/css-prefers-color-scheme/package.json b/plugins/css-prefers-color-scheme/package.json index 611398df6..55818d1bb 100644 --- a/plugins/css-prefers-color-scheme/package.json +++ b/plugins/css-prefers-color-scheme/package.json @@ -31,15 +31,18 @@ "engines": { "node": "^14 || ^16 || >=18" }, + "type": "module", "main": "dist/index.cjs", "module": "dist/index.mjs", - "types": "dist/index.d.ts", "exports": { ".": { - "types": "./dist/index.d.ts", - "import": "./dist/index.mjs", - "require": "./dist/index.cjs", - "default": "./dist/index.mjs" + "import": { + "types": "./dist/index.d.ts", + "default": "./dist/index.mjs" + }, + "require": { + "default": "./dist/index.cjs" + } }, "./browser": { "import": "./dist/browser.mjs", diff --git a/plugins/postcss-attribute-case-insensitive/CHANGELOG.md b/plugins/postcss-attribute-case-insensitive/CHANGELOG.md index 48fa74eba..b954edbeb 100644 --- a/plugins/postcss-attribute-case-insensitive/CHANGELOG.md +++ b/plugins/postcss-attribute-case-insensitive/CHANGELOG.md @@ -2,7 +2,7 @@ ### Unreleased (patch) -- Small fixes in type definitions +- Fix type definitions - Fix an infinite loop when a pseudo selector function contains a case insensitive attribute selector ### 6.0.2 diff --git a/plugins/postcss-attribute-case-insensitive/api-extractor.json b/plugins/postcss-attribute-case-insensitive/api-extractor.json new file mode 100644 index 000000000..42058be51 --- /dev/null +++ b/plugins/postcss-attribute-case-insensitive/api-extractor.json @@ -0,0 +1,4 @@ +{ + "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json", + "extends": "../../api-extractor.json" +} diff --git a/plugins/postcss-attribute-case-insensitive/dist/index.d.ts b/plugins/postcss-attribute-case-insensitive/dist/index.d.ts index c3aecebb7..ba9565d22 100644 --- a/plugins/postcss-attribute-case-insensitive/dist/index.d.ts +++ b/plugins/postcss-attribute-case-insensitive/dist/index.d.ts @@ -1,8 +1,12 @@ import type { PluginCreator } from 'postcss'; + +declare const creator: PluginCreator; +export default creator; + /** postcss-prefers-color-scheme plugin options */ -export type pluginOptions = { +export declare type pluginOptions = { /** Preserve the original notation. default: false */ preserve?: boolean; }; -declare const creator: PluginCreator; -export default creator; + +export { } diff --git a/plugins/postcss-attribute-case-insensitive/package.json b/plugins/postcss-attribute-case-insensitive/package.json index 30dd578a2..403e001fe 100644 --- a/plugins/postcss-attribute-case-insensitive/package.json +++ b/plugins/postcss-attribute-case-insensitive/package.json @@ -30,15 +30,18 @@ "engines": { "node": "^14 || ^16 || >=18" }, + "type": "module", "main": "dist/index.cjs", "module": "dist/index.mjs", - "types": "dist/index.d.ts", "exports": { ".": { - "types": "./dist/index.d.ts", - "import": "./dist/index.mjs", - "require": "./dist/index.cjs", - "default": "./dist/index.mjs" + "import": { + "types": "./dist/index.d.ts", + "default": "./dist/index.mjs" + }, + "require": { + "default": "./dist/index.cjs" + } } }, "files": [ diff --git a/plugins/postcss-attribute-case-insensitive/src/index.ts b/plugins/postcss-attribute-case-insensitive/src/index.ts index 73794546a..7a6813599 100644 --- a/plugins/postcss-attribute-case-insensitive/src/index.ts +++ b/plugins/postcss-attribute-case-insensitive/src/index.ts @@ -36,6 +36,7 @@ function createSensitiveAttributes(attribute: selectorParser.Attribute) { insensitive: false, }); + // @ts-expect-error https://github.com/postcss/postcss-selector-parser/pull/284 newAttribute.setValue(x); return newAttribute; @@ -48,6 +49,7 @@ function createNewSelectors(selector: selectorParser.Selector) { selector.each((node) => { if (!nodeIsInsensitiveAttribute(node)) { newSelectors.forEach(newSelector => { + // @ts-expect-error https://github.com/postcss/postcss-selector-parser/pull/284 newSelector.append(node.clone()); }); return; @@ -59,7 +61,9 @@ function createNewSelectors(selector: selectorParser.Selector) { sensitiveAttributes.forEach(newNode => { newSelectors.forEach(newSelector => { const newSelectorWithNewNode = newSelector.clone({}); + // @ts-expect-error https://github.com/postcss/postcss-selector-parser/pull/284 newSelectorWithNewNode.append(newNode); + // @ts-expect-error https://github.com/postcss/postcss-selector-parser/pull/284 newSelectorsWithSensitiveAttributes.push(newSelectorWithNewNode); }); }); diff --git a/plugins/postcss-base-plugin/api-extractor.json b/plugins/postcss-base-plugin/api-extractor.json new file mode 100644 index 000000000..42058be51 --- /dev/null +++ b/plugins/postcss-base-plugin/api-extractor.json @@ -0,0 +1,4 @@ +{ + "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json", + "extends": "../../api-extractor.json" +} diff --git a/plugins/postcss-base-plugin/dist/index.d.ts b/plugins/postcss-base-plugin/dist/index.d.ts index e76bf4523..be70ff742 100644 --- a/plugins/postcss-base-plugin/dist/index.d.ts +++ b/plugins/postcss-base-plugin/dist/index.d.ts @@ -1,10 +1,14 @@ import type { PluginCreator } from 'postcss'; + +declare const creator: PluginCreator; +export default creator; + /** postcss-base-plugin plugin options */ -export type pluginOptions = { +export declare type pluginOptions = { /** Preserve the original notation. default: false */ preserve?: boolean; /** Replacement color */ color?: string; }; -declare const creator: PluginCreator; -export default creator; + +export { } diff --git a/plugins/postcss-base-plugin/package.json b/plugins/postcss-base-plugin/package.json index ab161175b..e04bfb38d 100644 --- a/plugins/postcss-base-plugin/package.json +++ b/plugins/postcss-base-plugin/package.json @@ -28,15 +28,18 @@ "engines": { "node": "^14 || ^16 || >=18" }, + "type": "module", "main": "dist/index.cjs", "module": "dist/index.mjs", - "types": "dist/index.d.ts", "exports": { ".": { - "types": "./dist/index.d.ts", - "import": "./dist/index.mjs", - "require": "./dist/index.cjs", - "default": "./dist/index.mjs" + "import": { + "types": "./dist/index.d.ts", + "default": "./dist/index.mjs" + }, + "require": { + "default": "./dist/index.cjs" + } } }, "files": [ diff --git a/plugins/postcss-cascade-layers/CHANGELOG.md b/plugins/postcss-cascade-layers/CHANGELOG.md index 46533e390..86978a704 100644 --- a/plugins/postcss-cascade-layers/CHANGELOG.md +++ b/plugins/postcss-cascade-layers/CHANGELOG.md @@ -1,5 +1,9 @@ # Changes to PostCSS Cascade Layers +### Unreleased (patch) + +- Fix type definitions + ### 4.0.1 _October 31, 2023_ diff --git a/plugins/postcss-cascade-layers/api-extractor.json b/plugins/postcss-cascade-layers/api-extractor.json new file mode 100644 index 000000000..42058be51 --- /dev/null +++ b/plugins/postcss-cascade-layers/api-extractor.json @@ -0,0 +1,4 @@ +{ + "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json", + "extends": "../../api-extractor.json" +} diff --git a/plugins/postcss-cascade-layers/dist/adjust-selector-specificity.d.ts b/plugins/postcss-cascade-layers/dist/adjust-selector-specificity.d.ts deleted file mode 100644 index af7b5e19e..000000000 --- a/plugins/postcss-cascade-layers/dist/adjust-selector-specificity.d.ts +++ /dev/null @@ -1 +0,0 @@ -export declare function adjustSelectorSpecificity(selector: string, amount: number): string; diff --git a/plugins/postcss-cascade-layers/dist/clean-blocks.d.ts b/plugins/postcss-cascade-layers/dist/clean-blocks.d.ts deleted file mode 100644 index b9f2a5647..000000000 --- a/plugins/postcss-cascade-layers/dist/clean-blocks.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -import type { Container } from 'postcss'; -export declare function removeEmptyDescendantBlocks(block: Container | undefined): void; -export declare function removeEmptyAncestorBlocks(block: Container | undefined): void; diff --git a/plugins/postcss-cascade-layers/dist/constants.d.ts b/plugins/postcss-cascade-layers/dist/constants.d.ts deleted file mode 100644 index a2393c35e..000000000 --- a/plugins/postcss-cascade-layers/dist/constants.d.ts +++ /dev/null @@ -1,12 +0,0 @@ -/** @constant {string} INVALID_LAYER_NAME Used to replace "layer" temporarily when an invalid layer is detected. This allows us to ignore this rule in further processing. */ -export declare const INVALID_LAYER_NAME = "csstools-invalid-layer"; -/** @constant {string} WITH_SELECTORS_LAYER_NAME Used to replace "layer" temporarily for any layer at rules that contain selectors. This allows us to sort these differently from other layer at rules. */ -export declare const WITH_SELECTORS_LAYER_NAME = "csstools-layer-with-selector-rules"; -export declare const ANONYMOUS_LAYER_SUFFIX = "6efdb677-bb05-44e5-840f-29d2175862fd"; -export declare const IMPLICIT_LAYER_SUFFIX = "b147acf6-11a6-4338-a4d0-80aef4cd1a2f"; -export declare const CONDITIONAL_ATRULES: string[]; -export declare const ATRULES_WITH_NON_SELECTOR_BLOCK_LISTS: string[]; -export declare const IS_REVERT_LAYER: RegExp; -export declare const IS_IMPORT: RegExp; -export declare const IS_LAYER: RegExp; -export declare const HAS_LAYER: RegExp; diff --git a/plugins/postcss-cascade-layers/dist/desugar-and-parse-layer-names.d.ts b/plugins/postcss-cascade-layers/dist/desugar-and-parse-layer-names.d.ts deleted file mode 100644 index d44fd4545..000000000 --- a/plugins/postcss-cascade-layers/dist/desugar-and-parse-layer-names.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -import type { Container } from 'postcss'; -import type { Model } from './model'; -export declare function desugarAndParseLayerNames(root: Container, model: Model): void; diff --git a/plugins/postcss-cascade-layers/dist/desugar-nested-layers.d.ts b/plugins/postcss-cascade-layers/dist/desugar-nested-layers.d.ts deleted file mode 100644 index e15d3bfba..000000000 --- a/plugins/postcss-cascade-layers/dist/desugar-nested-layers.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -import type { Container, ChildNode } from 'postcss'; -import type { Model } from './model'; -export declare function desugarNestedLayers(root: Container, model: Model): void; diff --git a/plugins/postcss-cascade-layers/dist/get-conditional-atrule-ancestor.d.ts b/plugins/postcss-cascade-layers/dist/get-conditional-atrule-ancestor.d.ts deleted file mode 100644 index 25a6756ac..000000000 --- a/plugins/postcss-cascade-layers/dist/get-conditional-atrule-ancestor.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import type { AtRule } from 'postcss'; -export declare function getConditionalAtRuleAncestor(layerRule: AtRule): AtRule | null; diff --git a/plugins/postcss-cascade-layers/dist/get-layer-atrule-ancestor.d.ts b/plugins/postcss-cascade-layers/dist/get-layer-atrule-ancestor.d.ts deleted file mode 100644 index b59be340a..000000000 --- a/plugins/postcss-cascade-layers/dist/get-layer-atrule-ancestor.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import type { AtRule, Node } from 'postcss'; -export declare function getLayerAtRuleAncestor(node: Node): AtRule | null; diff --git a/plugins/postcss-cascade-layers/dist/index.cjs b/plugins/postcss-cascade-layers/dist/index.cjs index 78ea4800d..a679b6888 100644 --- a/plugins/postcss-cascade-layers/dist/index.cjs +++ b/plugins/postcss-cascade-layers/dist/index.cjs @@ -1 +1 @@ -"use strict";var e=require("postcss-selector-parser"),r=require("@csstools/selector-specificity");const t="csstools-invalid-layer",a="csstools-layer-with-selector-rules",s="6efdb677-bb05-44e5-840f-29d2175862fd",n="b147acf6-11a6-4338-a4d0-80aef4cd1a2f",o=["media","supports"],l=["keyframes"],i=/^revert-layer$/i,c=/^import$/i,u=/^layer$/i,y=/layer/i,m=new Set(["layer","supports","media","container","scope"]);function isProcessableLayerRule(e){if("atrule"!==e.type)return!1;if(!u.test(e.name))return!1;let r=e.parent;for(;r;){if("rule"===r.type)return!1;if("atrule"===r.type&&!m.has(r.name.toLowerCase()))return!1;r=r.parent}return!0}class Model{anonymousLayerCount=0;layerCount=0;layerOrder;layerParamsParsed;layerNameParts;constructor(){this.anonymousLayerCount=0,this.layerCount=0,this.layerOrder=new Map,this.layerParamsParsed=new Map,this.layerNameParts=new Map}createAnonymousLayerName(){const e=`anonymous-${this.anonymousLayerCount}-${s}`;return this.addLayerNameParts(e),this.layerParamsParsed.set(e,[e]),this.anonymousLayerCount++,e}createImplicitLayerName(e){const r=this.layerNameParts.get(e)??[],t=`implicit-${r[r.length-1]}-${n}`;return this.addLayerNameParts([...r,t]),this.layerParamsParsed.set(t,[t]),t}addLayerParams(e,r){r?"string"!=typeof r?this.layerParamsParsed.set(e,r):this.layerParamsParsed.set(e,[r]):this.layerParamsParsed.set(e,[e])}addLayerNameParts(e){"string"!=typeof e?this.layerNameParts.set(e.join("."),e):this.layerNameParts.set(e,[e])}getLayerParams(e){const r=[...this.layerParamsParsed.get(e.params)??[]];let t=e.parent;for(;t;)"atrule"===t.type?(isProcessableLayerRule(t)&&r.push(...this.layerParamsParsed.get(t.params)??[]),t=t.parent):t=t.parent;return r.reverse(),r.flatMap((e=>this.layerNameParts.get(e)??[]))}getLayerNameList(e){const r=this.layerNameParts.get(e)??[],t=[];for(let e=0;e{const t=this.layerNameParts.get(e[0])??[],a=this.layerNameParts.get(r[0])??[];if(t[0]!==a[0])return(this.layerOrder.get(t[0])??0)-(this.layerOrder.get(a[0])??0);const s=Math.max(t.length,a.length);for(let e=0;e{this.layerOrder.set(e[0],r)}))}}function adjustSelectorSpecificity(r,t){const a=e().astSync(r),s=e().astSync(generateNot(t));let n=!1;for(let r=0;r{if(r(e))return t=!0,!1})),t}function someAtRuleInTree(e,r){let t=!1;return e.walkAtRules((e=>{if(r(e))return t=!0,!1})),t}function getLayerAtRuleAncestor(e){let r=e.parent;for(;r;)if("atrule"===r.type){if(isProcessableLayerRule(r))return r;r=r.parent}else r=r.parent;return null}function removeEmptyDescendantBlocks(e){var r;e&&(e.walk((e=>{var r;("rule"===e.type||"atrule"===e.type&&["layer",...o].includes(e.name.toLowerCase()))&&(0===(null==(r=e.nodes)?void 0:r.length)&&e.remove())})),0===(null==(r=e.nodes)?void 0:r.length)&&e.remove())}function removeEmptyAncestorBlocks(e){if(!e)return;let r=e;for(;r;){if(void 0===r.nodes)return;if(r.nodes.length>0)return;const e=r.parent;r.remove(),r=e}}function desugarAndParseLayerNames(r,a){r.walkAtRules((r=>{if(!isProcessableLayerRule(r))return;if(r.params){const s=[];let n=!1;if(e().astSync(r.params).each((e=>{const r=[];e.walk((e=>{switch(e.type){case"class":case"tag":r.push(e.value);break;default:n=!0}})),n||(s.push(r.join(".")),a.addLayerNameParts(r))})),a.addLayerParams(r.params,s),r.nodes&&s.length>1&&(n=!0),n)return void(r.name=t);if(!r.nodes||0===r.nodes.length){if(s.length<=1)return;return s.slice(0,-1).forEach((e=>{a.addLayerParams(e,e),r.cloneBefore({params:e})})),a.addLayerParams(s[s.length-1],s[s.length-1]),void(r.params=s[s.length-1])}}r.params||(r.raws.afterName=" ",r.params=a.createAnonymousLayerName());const s=someAtRuleInTree(r,(e=>isProcessableLayerRule(e))),n=someInTree(r,(e=>{if("rule"!==e.type)return!1;return getLayerAtRuleAncestor(e)===r}));if(s&&n){const e=a.createImplicitLayerName(r.params),t=r.clone({params:e});t.walkAtRules((e=>{isProcessableLayerRule(e)&&e.remove()})),r.walk((e=>{if("atrule"===e.type&&isProcessableLayerRule(e))return;if("atrule"===e.type&&o.includes(e.name.toLowerCase()))return;getLayerAtRuleAncestor(e)===r&&e.remove()})),r.append(t),removeEmptyDescendantBlocks(r),removeEmptyAncestorBlocks(r)}}))}function desugarNestedLayers(e,r){for(;someAtRuleInTree(e,(e=>e.nodes&&someAtRuleInTree(e,(e=>isProcessableLayerRule(e)))));){let t=!1;if(e.walkAtRules((a=>{var s,n;if(isProcessableLayerRule(a)&&a.parent!==e){if("atrule"===(null==(s=a.parent)?void 0:s.type)&&isProcessableLayerRule(a.parent)){const e=a.parent;{const t=r.layerNameParts.get(e.params),s=r.layerNameParts.get(a.params);if(!t||!s)return;r.layerNameParts.set(`${e.params}.${a.params}`,[...t,...s]),r.layerParamsParsed.set(`${e.params}.${a.params}`,[`${e.params}.${a.params}`])}return a.params=`${e.params}.${a.params}`,e.before(a),removeEmptyDescendantBlocks(e),void removeEmptyAncestorBlocks(e)}if("atrule"===(null==(n=a.parent)?void 0:n.type)){const e=a.parent,r=e.clone(),t=a.clone();return r.removeAll(),t.removeAll(),r.append(a.nodes),t.append(r),e.before(t),a.remove(),removeEmptyDescendantBlocks(e),void removeEmptyAncestorBlocks(e)}t=!0}})),t)break}}function sortRootNodes(e,r){e.walkAtRules((e=>{if(!isProcessableLayerRule(e))return;const r=e.clone(),t=e.clone();r.walkAtRules((e=>{if(l.includes(e.name.toLowerCase())){const r=e.parent;return e.remove(),removeEmptyDescendantBlocks(r),void removeEmptyAncestorBlocks(r)}if(someInTree(e,(e=>"rule"===e.type)))return;const r=e.parent;e.remove(),removeEmptyDescendantBlocks(r),removeEmptyAncestorBlocks(r)})),t.walkRules((e=>{if(e.parent&&"atrule"===e.parent.type&&l.includes(e.parent.name.toLowerCase()))return;const r=e.parent;e.remove(),removeEmptyDescendantBlocks(r),removeEmptyAncestorBlocks(r)})),t.walkAtRules((e=>{if(o.includes(e.name.toLowerCase()))return removeEmptyDescendantBlocks(e),void removeEmptyAncestorBlocks(e)})),r.name=a,e.replaceWith(r,t),0===r.nodes.length&&r.remove(),0===t.nodes.length&&t.remove()})),e.nodes.sort(((e,t)=>{const a="atrule"===e.type&&u.test(e.name),s="atrule"===t.type&&u.test(t.name);if(a&&s){return(r.layerOrder.get(e.params)??0)-(r.layerOrder.get(t.params)??0)}return a!==s?a?-1:1:0})),e.walkAtRules(a,(e=>{e.name="layer"}))}function getConditionalAtRuleAncestor(e){let r=e.parent;for(;r;)if("atrule"===r.type){if(o.includes(r.name.toLowerCase()))return r;r=r.parent}else r=r.parent;return null}function recordLayerOrder(e,r,{result:t,options:a}){e.walkAtRules((e=>{if(!isProcessableLayerRule(e))return;const o=r.getLayerParams(e),l=o.join(".");r.layerOrder.has(l)||(a.onConditionalRulesChangingLayerOrder&&getConditionalAtRuleAncestor(e)&&!e.params.endsWith(n)&&!e.params.endsWith(s)&&e.warn(t,"handling different layer orders in conditional rules is unsupported by this plugin and will cause style differences between browser versions."),r.layerParamsParsed.has(l)||r.layerParamsParsed.set(l,[l]),r.layerNameParts.has(l)||r.layerNameParts.set(l,[...o]),r.getLayerNameList(l).forEach((e=>{r.layerOrder.has(e)||(r.layerOrder.set(e,r.layerCount),r.layerCount+=1)}))),e.nodes&&0!==e.nodes.length||e.remove()}))}function splitImportantStyles(e){e.walkDecls((e=>{var r;if(!e.important)return;const t=e.parent;if(!t)return;if("atrule"===(null==t||null==(r=t.parent)?void 0:r.type)&&l.includes(t.parent.name.toLowerCase()))return;const a=t.clone();a.each((e=>{"decl"===e.type&&e.important||e.remove()})),t.each((e=>{"decl"===e.type&&e.important&&e.remove()})),t.before(a),removeEmptyDescendantBlocks(t)}))}const creator=a=>{const s=Object.assign({onRevertLayerKeyword:"warn",onConditionalRulesChangingLayerOrder:"warn",onImportLayerRule:"warn"},a);return{postcssPlugin:"postcss-cascade-layers",OnceExit(a,{result:n}){let o=!1;if((s.onRevertLayerKeyword||s.onImportLayerRule)&&a.walk((e=>"decl"===e.type?i.test(e.value)?void e.warn(n,'handling "revert-layer" is unsupported by this plugin and will cause style differences between browser versions.'):void 0:"atrule"===e.type?c.test(e.name)&&y.test(e.params)?void e.warn(n,"To use @import with layers, the postcss-import plugin is also required. This plugin alone will not support using the @import at-rule."):u.test(e.name)?void(o=!0):void 0:void 0)),!o)return;splitImportantStyles(a);const m=new Model;if(desugarAndParseLayerNames(a,m),recordLayerOrder(a,m,{result:n,options:s}),!m.layerCount)return void a.walkAtRules(t,(e=>{e.name="layer"}));let d=0;for(a.walkRules((t=>{t.selectors.forEach((a=>{try{const t=r.selectorSpecificity(e().astSync(a));d=Math.max(d,t.a+1)}catch(e){t.warn(n,`Failed to parse selector : "${a}" with message: "${e instanceof Error?e.message:e}"`)}}))})),a.walkRules((e=>{e.parent&&"atrule"===e.parent.type&&l.includes(e.parent.name.toLowerCase())||getLayerAtRuleAncestor(e)||e.some((e=>"decl"===e.type&&e.important))||(e.selectors=e.selectors.map((r=>{try{return adjustSelectorSpecificity(r,m.layerCount*d)}catch(t){e.warn(n,`Failed to parse selector : "${r}" with message: "${t instanceof Error?t.message:t}"`)}return r})))})),m.sortLayerNames(),desugarNestedLayers(a,m),sortRootNodes(a,m),a.walkRules((e=>{if(e.parent&&"atrule"===e.parent.type&&l.includes(e.parent.name.toLowerCase()))return;const r=getLayerAtRuleAncestor(e);if(!r)return;const t=m.getLayerParams(r).join(".");let a=(m.layerOrder.get(t)??0)*d;e.some((e=>"decl"===e.type&&e.important))&&(a=m.layerCount-a),e.selectors=e.selectors.map((e=>adjustSelectorSpecificity(e,a)))}));someAtRuleInTree(a,(e=>isProcessableLayerRule(e)));)a.walkAtRules((e=>{isProcessableLayerRule(e)&&e.replaceWith(e.nodes)}));a.walkAtRules(t,(e=>{e.name="layer"}))}}};creator.postcss=!0,module.exports=creator; +"use strict";var e=require("postcss-selector-parser"),r=require("@csstools/selector-specificity");const t="csstools-invalid-layer",a="csstools-layer-with-selector-rules",s="6efdb677-bb05-44e5-840f-29d2175862fd",n="b147acf6-11a6-4338-a4d0-80aef4cd1a2f",o=["media","supports"],l=["keyframes"],i=/^revert-layer$/i,c=/^import$/i,u=/^layer$/i,y=/layer/i,m=new Set(["layer","supports","media","container","scope"]);function isProcessableLayerRule(e){if("atrule"!==e.type)return!1;if(!u.test(e.name))return!1;let r=e.parent;for(;r;){if("rule"===r.type)return!1;if("atrule"===r.type&&!m.has(r.name.toLowerCase()))return!1;r=r.parent}return!0}class Model{anonymousLayerCount=0;layerCount=0;layerOrder;layerParamsParsed;layerNameParts;constructor(){this.anonymousLayerCount=0,this.layerCount=0,this.layerOrder=new Map,this.layerParamsParsed=new Map,this.layerNameParts=new Map}createAnonymousLayerName(){const e=`anonymous-${this.anonymousLayerCount}-${s}`;return this.addLayerNameParts(e),this.layerParamsParsed.set(e,[e]),this.anonymousLayerCount++,e}createImplicitLayerName(e){const r=this.layerNameParts.get(e)??[],t=`implicit-${r[r.length-1]}-${n}`;return this.addLayerNameParts([...r,t]),this.layerParamsParsed.set(t,[t]),t}addLayerParams(e,r){r?"string"!=typeof r?this.layerParamsParsed.set(e,r):this.layerParamsParsed.set(e,[r]):this.layerParamsParsed.set(e,[e])}addLayerNameParts(e){"string"!=typeof e?this.layerNameParts.set(e.join("."),e):this.layerNameParts.set(e,[e])}getLayerParams(e){const r=[...this.layerParamsParsed.get(e.params)??[]];let t=e.parent;for(;t;)"atrule"===t.type?(isProcessableLayerRule(t)&&r.push(...this.layerParamsParsed.get(t.params)??[]),t=t.parent):t=t.parent;return r.reverse(),r.flatMap((e=>this.layerNameParts.get(e)??[]))}getLayerNameList(e){const r=this.layerNameParts.get(e)??[],t=[];for(let e=0;e{const t=this.layerNameParts.get(e[0])??[],a=this.layerNameParts.get(r[0])??[];if(t[0]!==a[0])return(this.layerOrder.get(t[0])??0)-(this.layerOrder.get(a[0])??0);const s=Math.max(t.length,a.length);for(let e=0;e{this.layerOrder.set(e[0],r)}))}}function adjustSelectorSpecificity(r,t){const a=e().astSync(r),s=e().astSync(generateNot(t));let n=!1;for(let r=0;r{if(r(e))return t=!0,!1})),t}function someAtRuleInTree(e,r){let t=!1;return e.walkAtRules((e=>{if(r(e))return t=!0,!1})),t}function getLayerAtRuleAncestor(e){let r=e.parent;for(;r;)if("atrule"===r.type){if(isProcessableLayerRule(r))return r;r=r.parent}else r=r.parent;return null}function removeEmptyDescendantBlocks(e){e&&(e.walk((e=>{("rule"===e.type||"atrule"===e.type&&["layer",...o].includes(e.name.toLowerCase()))&&0===e.nodes?.length&&e.remove()})),0===e.nodes?.length&&e.remove())}function removeEmptyAncestorBlocks(e){if(!e)return;let r=e;for(;r;){if(void 0===r.nodes)return;if(r.nodes.length>0)return;const e=r.parent;r.remove(),r=e}}function desugarAndParseLayerNames(r,a){r.walkAtRules((r=>{if(!isProcessableLayerRule(r))return;if(r.params){const s=[];let n=!1;if(e().astSync(r.params).each((e=>{const r=[];e.walk((e=>{switch(e.type){case"class":case"tag":r.push(e.value);break;default:n=!0}})),n||(s.push(r.join(".")),a.addLayerNameParts(r))})),a.addLayerParams(r.params,s),r.nodes&&s.length>1&&(n=!0),n)return void(r.name=t);if(!r.nodes||0===r.nodes.length){if(s.length<=1)return;return s.slice(0,-1).forEach((e=>{a.addLayerParams(e,e),r.cloneBefore({params:e})})),a.addLayerParams(s[s.length-1],s[s.length-1]),void(r.params=s[s.length-1])}}r.params||(r.raws.afterName=" ",r.params=a.createAnonymousLayerName());const s=someAtRuleInTree(r,(e=>isProcessableLayerRule(e))),n=someInTree(r,(e=>{if("rule"!==e.type)return!1;return getLayerAtRuleAncestor(e)===r}));if(s&&n){const e=a.createImplicitLayerName(r.params),t=r.clone({params:e});t.walkAtRules((e=>{isProcessableLayerRule(e)&&e.remove()})),r.walk((e=>{if("atrule"===e.type&&isProcessableLayerRule(e))return;if("atrule"===e.type&&o.includes(e.name.toLowerCase()))return;getLayerAtRuleAncestor(e)===r&&e.remove()})),r.append(t),removeEmptyDescendantBlocks(r),removeEmptyAncestorBlocks(r)}}))}function desugarNestedLayers(e,r){for(;someAtRuleInTree(e,(e=>e.nodes&&someAtRuleInTree(e,(e=>isProcessableLayerRule(e)))));){let t=!1;if(e.walkAtRules((a=>{if(isProcessableLayerRule(a)&&a.parent!==e){if("atrule"===a.parent?.type&&isProcessableLayerRule(a.parent)){const e=a.parent;{const t=r.layerNameParts.get(e.params),s=r.layerNameParts.get(a.params);if(!t||!s)return;r.layerNameParts.set(`${e.params}.${a.params}`,[...t,...s]),r.layerParamsParsed.set(`${e.params}.${a.params}`,[`${e.params}.${a.params}`])}return a.params=`${e.params}.${a.params}`,e.before(a),removeEmptyDescendantBlocks(e),void removeEmptyAncestorBlocks(e)}if("atrule"===a.parent?.type){const e=a.parent,r=e.clone(),t=a.clone();return r.removeAll(),t.removeAll(),r.append(a.nodes),t.append(r),e.before(t),a.remove(),removeEmptyDescendantBlocks(e),void removeEmptyAncestorBlocks(e)}t=!0}})),t)break}}function sortRootNodes(e,r){e.walkAtRules((e=>{if(!isProcessableLayerRule(e))return;const r=e.clone(),t=e.clone();r.walkAtRules((e=>{if(l.includes(e.name.toLowerCase())){const r=e.parent;return e.remove(),removeEmptyDescendantBlocks(r),void removeEmptyAncestorBlocks(r)}if(someInTree(e,(e=>"rule"===e.type)))return;const r=e.parent;e.remove(),removeEmptyDescendantBlocks(r),removeEmptyAncestorBlocks(r)})),t.walkRules((e=>{if(e.parent&&"atrule"===e.parent.type&&l.includes(e.parent.name.toLowerCase()))return;const r=e.parent;e.remove(),removeEmptyDescendantBlocks(r),removeEmptyAncestorBlocks(r)})),t.walkAtRules((e=>{if(o.includes(e.name.toLowerCase()))return removeEmptyDescendantBlocks(e),void removeEmptyAncestorBlocks(e)})),r.name=a,e.replaceWith(r,t),0===r.nodes.length&&r.remove(),0===t.nodes.length&&t.remove()})),e.nodes.sort(((e,t)=>{const a="atrule"===e.type&&u.test(e.name),s="atrule"===t.type&&u.test(t.name);if(a&&s){return(r.layerOrder.get(e.params)??0)-(r.layerOrder.get(t.params)??0)}return a!==s?a?-1:1:0})),e.walkAtRules(a,(e=>{e.name="layer"}))}function getConditionalAtRuleAncestor(e){let r=e.parent;for(;r;)if("atrule"===r.type){if(o.includes(r.name.toLowerCase()))return r;r=r.parent}else r=r.parent;return null}function recordLayerOrder(e,r,{result:t,options:a}){e.walkAtRules((e=>{if(!isProcessableLayerRule(e))return;const o=r.getLayerParams(e),l=o.join(".");r.layerOrder.has(l)||(a.onConditionalRulesChangingLayerOrder&&getConditionalAtRuleAncestor(e)&&!e.params.endsWith(n)&&!e.params.endsWith(s)&&e.warn(t,"handling different layer orders in conditional rules is unsupported by this plugin and will cause style differences between browser versions."),r.layerParamsParsed.has(l)||r.layerParamsParsed.set(l,[l]),r.layerNameParts.has(l)||r.layerNameParts.set(l,[...o]),r.getLayerNameList(l).forEach((e=>{r.layerOrder.has(e)||(r.layerOrder.set(e,r.layerCount),r.layerCount+=1)}))),e.nodes&&0!==e.nodes.length||e.remove()}))}function splitImportantStyles(e){e.walkDecls((e=>{if(!e.important)return;const r=e.parent;if(!r)return;if("atrule"===r?.parent?.type&&l.includes(r.parent.name.toLowerCase()))return;const t=r.clone();t.each((e=>{"decl"===e.type&&e.important||e.remove()})),r.each((e=>{"decl"===e.type&&e.important&&e.remove()})),r.before(t),removeEmptyDescendantBlocks(r)}))}const creator=a=>{const s=Object.assign({onRevertLayerKeyword:"warn",onConditionalRulesChangingLayerOrder:"warn",onImportLayerRule:"warn"},a);return{postcssPlugin:"postcss-cascade-layers",OnceExit(a,{result:n}){let o=!1;if((s.onRevertLayerKeyword||s.onImportLayerRule)&&a.walk((e=>"decl"===e.type?i.test(e.value)?void e.warn(n,'handling "revert-layer" is unsupported by this plugin and will cause style differences between browser versions.'):void 0:"atrule"===e.type?c.test(e.name)&&y.test(e.params)?void e.warn(n,"To use @import with layers, the postcss-import plugin is also required. This plugin alone will not support using the @import at-rule."):u.test(e.name)?void(o=!0):void 0:void 0)),!o)return;splitImportantStyles(a);const m=new Model;if(desugarAndParseLayerNames(a,m),recordLayerOrder(a,m,{result:n,options:s}),!m.layerCount)return void a.walkAtRules(t,(e=>{e.name="layer"}));let p=0;for(a.walkRules((t=>{t.selectors.forEach((a=>{try{const t=r.selectorSpecificity(e().astSync(a));p=Math.max(p,t.a+1)}catch(e){t.warn(n,`Failed to parse selector : "${a}" with message: "${e instanceof Error?e.message:e}"`)}}))})),a.walkRules((e=>{e.parent&&"atrule"===e.parent.type&&l.includes(e.parent.name.toLowerCase())||getLayerAtRuleAncestor(e)||e.some((e=>"decl"===e.type&&e.important))||(e.selectors=e.selectors.map((r=>{try{return adjustSelectorSpecificity(r,m.layerCount*p)}catch(t){e.warn(n,`Failed to parse selector : "${r}" with message: "${t instanceof Error?t.message:t}"`)}return r})))})),m.sortLayerNames(),desugarNestedLayers(a,m),sortRootNodes(a,m),a.walkRules((e=>{if(e.parent&&"atrule"===e.parent.type&&l.includes(e.parent.name.toLowerCase()))return;const r=getLayerAtRuleAncestor(e);if(!r)return;const t=m.getLayerParams(r).join(".");let a=(m.layerOrder.get(t)??0)*p;e.some((e=>"decl"===e.type&&e.important))&&(a=m.layerCount-a),e.selectors=e.selectors.map((e=>adjustSelectorSpecificity(e,a)))}));someAtRuleInTree(a,(e=>isProcessableLayerRule(e)));)a.walkAtRules((e=>{isProcessableLayerRule(e)&&e.replaceWith(e.nodes)}));a.walkAtRules(t,(e=>{e.name="layer"}))}}};creator.postcss=!0,module.exports=creator; diff --git a/plugins/postcss-cascade-layers/dist/index.d.ts b/plugins/postcss-cascade-layers/dist/index.d.ts index 9f366fbb9..da46b302d 100644 --- a/plugins/postcss-cascade-layers/dist/index.d.ts +++ b/plugins/postcss-cascade-layers/dist/index.d.ts @@ -1,5 +1,16 @@ import type { PluginCreator } from 'postcss'; -import type { pluginOptions } from './options'; -export type { pluginOptions } from './options'; + declare const creator: PluginCreator; export default creator; + +/** postcss-cascasde-layers plugin options */ +export declare type pluginOptions = { + /** Emit a warning when the "revert" keyword is found in your CSS. default: "warn" */ + onRevertLayerKeyword?: 'warn' | false; + /** Emit a warning when conditional rules could change the layer order. default: "warn" */ + onConditionalRulesChangingLayerOrder?: 'warn' | false; + /** Emit a warning when "layer" is used in "@import". default: "warn" */ + onImportLayerRule?: 'warn' | false; +}; + +export { } diff --git a/plugins/postcss-cascade-layers/dist/index.mjs b/plugins/postcss-cascade-layers/dist/index.mjs index db1186ee4..f28cd9e94 100644 --- a/plugins/postcss-cascade-layers/dist/index.mjs +++ b/plugins/postcss-cascade-layers/dist/index.mjs @@ -1 +1 @@ -import e from"postcss-selector-parser";import{selectorSpecificity as r}from"@csstools/selector-specificity";const t="csstools-invalid-layer",a="csstools-layer-with-selector-rules",s="6efdb677-bb05-44e5-840f-29d2175862fd",n="b147acf6-11a6-4338-a4d0-80aef4cd1a2f",o=["media","supports"],l=["keyframes"],i=/^revert-layer$/i,c=/^import$/i,u=/^layer$/i,m=/layer/i,y=new Set(["layer","supports","media","container","scope"]);function isProcessableLayerRule(e){if("atrule"!==e.type)return!1;if(!u.test(e.name))return!1;let r=e.parent;for(;r;){if("rule"===r.type)return!1;if("atrule"===r.type&&!y.has(r.name.toLowerCase()))return!1;r=r.parent}return!0}class Model{anonymousLayerCount=0;layerCount=0;layerOrder;layerParamsParsed;layerNameParts;constructor(){this.anonymousLayerCount=0,this.layerCount=0,this.layerOrder=new Map,this.layerParamsParsed=new Map,this.layerNameParts=new Map}createAnonymousLayerName(){const e=`anonymous-${this.anonymousLayerCount}-${s}`;return this.addLayerNameParts(e),this.layerParamsParsed.set(e,[e]),this.anonymousLayerCount++,e}createImplicitLayerName(e){const r=this.layerNameParts.get(e)??[],t=`implicit-${r[r.length-1]}-${n}`;return this.addLayerNameParts([...r,t]),this.layerParamsParsed.set(t,[t]),t}addLayerParams(e,r){r?"string"!=typeof r?this.layerParamsParsed.set(e,r):this.layerParamsParsed.set(e,[r]):this.layerParamsParsed.set(e,[e])}addLayerNameParts(e){"string"!=typeof e?this.layerNameParts.set(e.join("."),e):this.layerNameParts.set(e,[e])}getLayerParams(e){const r=[...this.layerParamsParsed.get(e.params)??[]];let t=e.parent;for(;t;)"atrule"===t.type?(isProcessableLayerRule(t)&&r.push(...this.layerParamsParsed.get(t.params)??[]),t=t.parent):t=t.parent;return r.reverse(),r.flatMap((e=>this.layerNameParts.get(e)??[]))}getLayerNameList(e){const r=this.layerNameParts.get(e)??[],t=[];for(let e=0;e{const t=this.layerNameParts.get(e[0])??[],a=this.layerNameParts.get(r[0])??[];if(t[0]!==a[0])return(this.layerOrder.get(t[0])??0)-(this.layerOrder.get(a[0])??0);const s=Math.max(t.length,a.length);for(let e=0;e{this.layerOrder.set(e[0],r)}))}}function adjustSelectorSpecificity(r,t){const a=e().astSync(r),s=e().astSync(generateNot(t));let n=!1;for(let r=0;r{if(r(e))return t=!0,!1})),t}function someAtRuleInTree(e,r){let t=!1;return e.walkAtRules((e=>{if(r(e))return t=!0,!1})),t}function getLayerAtRuleAncestor(e){let r=e.parent;for(;r;)if("atrule"===r.type){if(isProcessableLayerRule(r))return r;r=r.parent}else r=r.parent;return null}function removeEmptyDescendantBlocks(e){var r;e&&(e.walk((e=>{var r;("rule"===e.type||"atrule"===e.type&&["layer",...o].includes(e.name.toLowerCase()))&&(0===(null==(r=e.nodes)?void 0:r.length)&&e.remove())})),0===(null==(r=e.nodes)?void 0:r.length)&&e.remove())}function removeEmptyAncestorBlocks(e){if(!e)return;let r=e;for(;r;){if(void 0===r.nodes)return;if(r.nodes.length>0)return;const e=r.parent;r.remove(),r=e}}function desugarAndParseLayerNames(r,a){r.walkAtRules((r=>{if(!isProcessableLayerRule(r))return;if(r.params){const s=[];let n=!1;if(e().astSync(r.params).each((e=>{const r=[];e.walk((e=>{switch(e.type){case"class":case"tag":r.push(e.value);break;default:n=!0}})),n||(s.push(r.join(".")),a.addLayerNameParts(r))})),a.addLayerParams(r.params,s),r.nodes&&s.length>1&&(n=!0),n)return void(r.name=t);if(!r.nodes||0===r.nodes.length){if(s.length<=1)return;return s.slice(0,-1).forEach((e=>{a.addLayerParams(e,e),r.cloneBefore({params:e})})),a.addLayerParams(s[s.length-1],s[s.length-1]),void(r.params=s[s.length-1])}}r.params||(r.raws.afterName=" ",r.params=a.createAnonymousLayerName());const s=someAtRuleInTree(r,(e=>isProcessableLayerRule(e))),n=someInTree(r,(e=>{if("rule"!==e.type)return!1;return getLayerAtRuleAncestor(e)===r}));if(s&&n){const e=a.createImplicitLayerName(r.params),t=r.clone({params:e});t.walkAtRules((e=>{isProcessableLayerRule(e)&&e.remove()})),r.walk((e=>{if("atrule"===e.type&&isProcessableLayerRule(e))return;if("atrule"===e.type&&o.includes(e.name.toLowerCase()))return;getLayerAtRuleAncestor(e)===r&&e.remove()})),r.append(t),removeEmptyDescendantBlocks(r),removeEmptyAncestorBlocks(r)}}))}function desugarNestedLayers(e,r){for(;someAtRuleInTree(e,(e=>e.nodes&&someAtRuleInTree(e,(e=>isProcessableLayerRule(e)))));){let t=!1;if(e.walkAtRules((a=>{var s,n;if(isProcessableLayerRule(a)&&a.parent!==e){if("atrule"===(null==(s=a.parent)?void 0:s.type)&&isProcessableLayerRule(a.parent)){const e=a.parent;{const t=r.layerNameParts.get(e.params),s=r.layerNameParts.get(a.params);if(!t||!s)return;r.layerNameParts.set(`${e.params}.${a.params}`,[...t,...s]),r.layerParamsParsed.set(`${e.params}.${a.params}`,[`${e.params}.${a.params}`])}return a.params=`${e.params}.${a.params}`,e.before(a),removeEmptyDescendantBlocks(e),void removeEmptyAncestorBlocks(e)}if("atrule"===(null==(n=a.parent)?void 0:n.type)){const e=a.parent,r=e.clone(),t=a.clone();return r.removeAll(),t.removeAll(),r.append(a.nodes),t.append(r),e.before(t),a.remove(),removeEmptyDescendantBlocks(e),void removeEmptyAncestorBlocks(e)}t=!0}})),t)break}}function sortRootNodes(e,r){e.walkAtRules((e=>{if(!isProcessableLayerRule(e))return;const r=e.clone(),t=e.clone();r.walkAtRules((e=>{if(l.includes(e.name.toLowerCase())){const r=e.parent;return e.remove(),removeEmptyDescendantBlocks(r),void removeEmptyAncestorBlocks(r)}if(someInTree(e,(e=>"rule"===e.type)))return;const r=e.parent;e.remove(),removeEmptyDescendantBlocks(r),removeEmptyAncestorBlocks(r)})),t.walkRules((e=>{if(e.parent&&"atrule"===e.parent.type&&l.includes(e.parent.name.toLowerCase()))return;const r=e.parent;e.remove(),removeEmptyDescendantBlocks(r),removeEmptyAncestorBlocks(r)})),t.walkAtRules((e=>{if(o.includes(e.name.toLowerCase()))return removeEmptyDescendantBlocks(e),void removeEmptyAncestorBlocks(e)})),r.name=a,e.replaceWith(r,t),0===r.nodes.length&&r.remove(),0===t.nodes.length&&t.remove()})),e.nodes.sort(((e,t)=>{const a="atrule"===e.type&&u.test(e.name),s="atrule"===t.type&&u.test(t.name);if(a&&s){return(r.layerOrder.get(e.params)??0)-(r.layerOrder.get(t.params)??0)}return a!==s?a?-1:1:0})),e.walkAtRules(a,(e=>{e.name="layer"}))}function getConditionalAtRuleAncestor(e){let r=e.parent;for(;r;)if("atrule"===r.type){if(o.includes(r.name.toLowerCase()))return r;r=r.parent}else r=r.parent;return null}function recordLayerOrder(e,r,{result:t,options:a}){e.walkAtRules((e=>{if(!isProcessableLayerRule(e))return;const o=r.getLayerParams(e),l=o.join(".");r.layerOrder.has(l)||(a.onConditionalRulesChangingLayerOrder&&getConditionalAtRuleAncestor(e)&&!e.params.endsWith(n)&&!e.params.endsWith(s)&&e.warn(t,"handling different layer orders in conditional rules is unsupported by this plugin and will cause style differences between browser versions."),r.layerParamsParsed.has(l)||r.layerParamsParsed.set(l,[l]),r.layerNameParts.has(l)||r.layerNameParts.set(l,[...o]),r.getLayerNameList(l).forEach((e=>{r.layerOrder.has(e)||(r.layerOrder.set(e,r.layerCount),r.layerCount+=1)}))),e.nodes&&0!==e.nodes.length||e.remove()}))}function splitImportantStyles(e){e.walkDecls((e=>{var r;if(!e.important)return;const t=e.parent;if(!t)return;if("atrule"===(null==t||null==(r=t.parent)?void 0:r.type)&&l.includes(t.parent.name.toLowerCase()))return;const a=t.clone();a.each((e=>{"decl"===e.type&&e.important||e.remove()})),t.each((e=>{"decl"===e.type&&e.important&&e.remove()})),t.before(a),removeEmptyDescendantBlocks(t)}))}const creator=a=>{const s=Object.assign({onRevertLayerKeyword:"warn",onConditionalRulesChangingLayerOrder:"warn",onImportLayerRule:"warn"},a);return{postcssPlugin:"postcss-cascade-layers",OnceExit(a,{result:n}){let o=!1;if((s.onRevertLayerKeyword||s.onImportLayerRule)&&a.walk((e=>"decl"===e.type?i.test(e.value)?void e.warn(n,'handling "revert-layer" is unsupported by this plugin and will cause style differences between browser versions.'):void 0:"atrule"===e.type?c.test(e.name)&&m.test(e.params)?void e.warn(n,"To use @import with layers, the postcss-import plugin is also required. This plugin alone will not support using the @import at-rule."):u.test(e.name)?void(o=!0):void 0:void 0)),!o)return;splitImportantStyles(a);const y=new Model;if(desugarAndParseLayerNames(a,y),recordLayerOrder(a,y,{result:n,options:s}),!y.layerCount)return void a.walkAtRules(t,(e=>{e.name="layer"}));let d=0;for(a.walkRules((t=>{t.selectors.forEach((a=>{try{const t=r(e().astSync(a));d=Math.max(d,t.a+1)}catch(e){t.warn(n,`Failed to parse selector : "${a}" with message: "${e instanceof Error?e.message:e}"`)}}))})),a.walkRules((e=>{e.parent&&"atrule"===e.parent.type&&l.includes(e.parent.name.toLowerCase())||getLayerAtRuleAncestor(e)||e.some((e=>"decl"===e.type&&e.important))||(e.selectors=e.selectors.map((r=>{try{return adjustSelectorSpecificity(r,y.layerCount*d)}catch(t){e.warn(n,`Failed to parse selector : "${r}" with message: "${t instanceof Error?t.message:t}"`)}return r})))})),y.sortLayerNames(),desugarNestedLayers(a,y),sortRootNodes(a,y),a.walkRules((e=>{if(e.parent&&"atrule"===e.parent.type&&l.includes(e.parent.name.toLowerCase()))return;const r=getLayerAtRuleAncestor(e);if(!r)return;const t=y.getLayerParams(r).join(".");let a=(y.layerOrder.get(t)??0)*d;e.some((e=>"decl"===e.type&&e.important))&&(a=y.layerCount-a),e.selectors=e.selectors.map((e=>adjustSelectorSpecificity(e,a)))}));someAtRuleInTree(a,(e=>isProcessableLayerRule(e)));)a.walkAtRules((e=>{isProcessableLayerRule(e)&&e.replaceWith(e.nodes)}));a.walkAtRules(t,(e=>{e.name="layer"}))}}};creator.postcss=!0;export{creator as default}; +import e from"postcss-selector-parser";import{selectorSpecificity as r}from"@csstools/selector-specificity";const t="csstools-invalid-layer",a="csstools-layer-with-selector-rules",s="6efdb677-bb05-44e5-840f-29d2175862fd",n="b147acf6-11a6-4338-a4d0-80aef4cd1a2f",o=["media","supports"],l=["keyframes"],i=/^revert-layer$/i,c=/^import$/i,u=/^layer$/i,m=/layer/i,y=new Set(["layer","supports","media","container","scope"]);function isProcessableLayerRule(e){if("atrule"!==e.type)return!1;if(!u.test(e.name))return!1;let r=e.parent;for(;r;){if("rule"===r.type)return!1;if("atrule"===r.type&&!y.has(r.name.toLowerCase()))return!1;r=r.parent}return!0}class Model{anonymousLayerCount=0;layerCount=0;layerOrder;layerParamsParsed;layerNameParts;constructor(){this.anonymousLayerCount=0,this.layerCount=0,this.layerOrder=new Map,this.layerParamsParsed=new Map,this.layerNameParts=new Map}createAnonymousLayerName(){const e=`anonymous-${this.anonymousLayerCount}-${s}`;return this.addLayerNameParts(e),this.layerParamsParsed.set(e,[e]),this.anonymousLayerCount++,e}createImplicitLayerName(e){const r=this.layerNameParts.get(e)??[],t=`implicit-${r[r.length-1]}-${n}`;return this.addLayerNameParts([...r,t]),this.layerParamsParsed.set(t,[t]),t}addLayerParams(e,r){r?"string"!=typeof r?this.layerParamsParsed.set(e,r):this.layerParamsParsed.set(e,[r]):this.layerParamsParsed.set(e,[e])}addLayerNameParts(e){"string"!=typeof e?this.layerNameParts.set(e.join("."),e):this.layerNameParts.set(e,[e])}getLayerParams(e){const r=[...this.layerParamsParsed.get(e.params)??[]];let t=e.parent;for(;t;)"atrule"===t.type?(isProcessableLayerRule(t)&&r.push(...this.layerParamsParsed.get(t.params)??[]),t=t.parent):t=t.parent;return r.reverse(),r.flatMap((e=>this.layerNameParts.get(e)??[]))}getLayerNameList(e){const r=this.layerNameParts.get(e)??[],t=[];for(let e=0;e{const t=this.layerNameParts.get(e[0])??[],a=this.layerNameParts.get(r[0])??[];if(t[0]!==a[0])return(this.layerOrder.get(t[0])??0)-(this.layerOrder.get(a[0])??0);const s=Math.max(t.length,a.length);for(let e=0;e{this.layerOrder.set(e[0],r)}))}}function adjustSelectorSpecificity(r,t){const a=e().astSync(r),s=e().astSync(generateNot(t));let n=!1;for(let r=0;r{if(r(e))return t=!0,!1})),t}function someAtRuleInTree(e,r){let t=!1;return e.walkAtRules((e=>{if(r(e))return t=!0,!1})),t}function getLayerAtRuleAncestor(e){let r=e.parent;for(;r;)if("atrule"===r.type){if(isProcessableLayerRule(r))return r;r=r.parent}else r=r.parent;return null}function removeEmptyDescendantBlocks(e){e&&(e.walk((e=>{("rule"===e.type||"atrule"===e.type&&["layer",...o].includes(e.name.toLowerCase()))&&0===e.nodes?.length&&e.remove()})),0===e.nodes?.length&&e.remove())}function removeEmptyAncestorBlocks(e){if(!e)return;let r=e;for(;r;){if(void 0===r.nodes)return;if(r.nodes.length>0)return;const e=r.parent;r.remove(),r=e}}function desugarAndParseLayerNames(r,a){r.walkAtRules((r=>{if(!isProcessableLayerRule(r))return;if(r.params){const s=[];let n=!1;if(e().astSync(r.params).each((e=>{const r=[];e.walk((e=>{switch(e.type){case"class":case"tag":r.push(e.value);break;default:n=!0}})),n||(s.push(r.join(".")),a.addLayerNameParts(r))})),a.addLayerParams(r.params,s),r.nodes&&s.length>1&&(n=!0),n)return void(r.name=t);if(!r.nodes||0===r.nodes.length){if(s.length<=1)return;return s.slice(0,-1).forEach((e=>{a.addLayerParams(e,e),r.cloneBefore({params:e})})),a.addLayerParams(s[s.length-1],s[s.length-1]),void(r.params=s[s.length-1])}}r.params||(r.raws.afterName=" ",r.params=a.createAnonymousLayerName());const s=someAtRuleInTree(r,(e=>isProcessableLayerRule(e))),n=someInTree(r,(e=>{if("rule"!==e.type)return!1;return getLayerAtRuleAncestor(e)===r}));if(s&&n){const e=a.createImplicitLayerName(r.params),t=r.clone({params:e});t.walkAtRules((e=>{isProcessableLayerRule(e)&&e.remove()})),r.walk((e=>{if("atrule"===e.type&&isProcessableLayerRule(e))return;if("atrule"===e.type&&o.includes(e.name.toLowerCase()))return;getLayerAtRuleAncestor(e)===r&&e.remove()})),r.append(t),removeEmptyDescendantBlocks(r),removeEmptyAncestorBlocks(r)}}))}function desugarNestedLayers(e,r){for(;someAtRuleInTree(e,(e=>e.nodes&&someAtRuleInTree(e,(e=>isProcessableLayerRule(e)))));){let t=!1;if(e.walkAtRules((a=>{if(isProcessableLayerRule(a)&&a.parent!==e){if("atrule"===a.parent?.type&&isProcessableLayerRule(a.parent)){const e=a.parent;{const t=r.layerNameParts.get(e.params),s=r.layerNameParts.get(a.params);if(!t||!s)return;r.layerNameParts.set(`${e.params}.${a.params}`,[...t,...s]),r.layerParamsParsed.set(`${e.params}.${a.params}`,[`${e.params}.${a.params}`])}return a.params=`${e.params}.${a.params}`,e.before(a),removeEmptyDescendantBlocks(e),void removeEmptyAncestorBlocks(e)}if("atrule"===a.parent?.type){const e=a.parent,r=e.clone(),t=a.clone();return r.removeAll(),t.removeAll(),r.append(a.nodes),t.append(r),e.before(t),a.remove(),removeEmptyDescendantBlocks(e),void removeEmptyAncestorBlocks(e)}t=!0}})),t)break}}function sortRootNodes(e,r){e.walkAtRules((e=>{if(!isProcessableLayerRule(e))return;const r=e.clone(),t=e.clone();r.walkAtRules((e=>{if(l.includes(e.name.toLowerCase())){const r=e.parent;return e.remove(),removeEmptyDescendantBlocks(r),void removeEmptyAncestorBlocks(r)}if(someInTree(e,(e=>"rule"===e.type)))return;const r=e.parent;e.remove(),removeEmptyDescendantBlocks(r),removeEmptyAncestorBlocks(r)})),t.walkRules((e=>{if(e.parent&&"atrule"===e.parent.type&&l.includes(e.parent.name.toLowerCase()))return;const r=e.parent;e.remove(),removeEmptyDescendantBlocks(r),removeEmptyAncestorBlocks(r)})),t.walkAtRules((e=>{if(o.includes(e.name.toLowerCase()))return removeEmptyDescendantBlocks(e),void removeEmptyAncestorBlocks(e)})),r.name=a,e.replaceWith(r,t),0===r.nodes.length&&r.remove(),0===t.nodes.length&&t.remove()})),e.nodes.sort(((e,t)=>{const a="atrule"===e.type&&u.test(e.name),s="atrule"===t.type&&u.test(t.name);if(a&&s){return(r.layerOrder.get(e.params)??0)-(r.layerOrder.get(t.params)??0)}return a!==s?a?-1:1:0})),e.walkAtRules(a,(e=>{e.name="layer"}))}function getConditionalAtRuleAncestor(e){let r=e.parent;for(;r;)if("atrule"===r.type){if(o.includes(r.name.toLowerCase()))return r;r=r.parent}else r=r.parent;return null}function recordLayerOrder(e,r,{result:t,options:a}){e.walkAtRules((e=>{if(!isProcessableLayerRule(e))return;const o=r.getLayerParams(e),l=o.join(".");r.layerOrder.has(l)||(a.onConditionalRulesChangingLayerOrder&&getConditionalAtRuleAncestor(e)&&!e.params.endsWith(n)&&!e.params.endsWith(s)&&e.warn(t,"handling different layer orders in conditional rules is unsupported by this plugin and will cause style differences between browser versions."),r.layerParamsParsed.has(l)||r.layerParamsParsed.set(l,[l]),r.layerNameParts.has(l)||r.layerNameParts.set(l,[...o]),r.getLayerNameList(l).forEach((e=>{r.layerOrder.has(e)||(r.layerOrder.set(e,r.layerCount),r.layerCount+=1)}))),e.nodes&&0!==e.nodes.length||e.remove()}))}function splitImportantStyles(e){e.walkDecls((e=>{if(!e.important)return;const r=e.parent;if(!r)return;if("atrule"===r?.parent?.type&&l.includes(r.parent.name.toLowerCase()))return;const t=r.clone();t.each((e=>{"decl"===e.type&&e.important||e.remove()})),r.each((e=>{"decl"===e.type&&e.important&&e.remove()})),r.before(t),removeEmptyDescendantBlocks(r)}))}const creator=a=>{const s=Object.assign({onRevertLayerKeyword:"warn",onConditionalRulesChangingLayerOrder:"warn",onImportLayerRule:"warn"},a);return{postcssPlugin:"postcss-cascade-layers",OnceExit(a,{result:n}){let o=!1;if((s.onRevertLayerKeyword||s.onImportLayerRule)&&a.walk((e=>"decl"===e.type?i.test(e.value)?void e.warn(n,'handling "revert-layer" is unsupported by this plugin and will cause style differences between browser versions.'):void 0:"atrule"===e.type?c.test(e.name)&&m.test(e.params)?void e.warn(n,"To use @import with layers, the postcss-import plugin is also required. This plugin alone will not support using the @import at-rule."):u.test(e.name)?void(o=!0):void 0:void 0)),!o)return;splitImportantStyles(a);const y=new Model;if(desugarAndParseLayerNames(a,y),recordLayerOrder(a,y,{result:n,options:s}),!y.layerCount)return void a.walkAtRules(t,(e=>{e.name="layer"}));let p=0;for(a.walkRules((t=>{t.selectors.forEach((a=>{try{const t=r(e().astSync(a));p=Math.max(p,t.a+1)}catch(e){t.warn(n,`Failed to parse selector : "${a}" with message: "${e instanceof Error?e.message:e}"`)}}))})),a.walkRules((e=>{e.parent&&"atrule"===e.parent.type&&l.includes(e.parent.name.toLowerCase())||getLayerAtRuleAncestor(e)||e.some((e=>"decl"===e.type&&e.important))||(e.selectors=e.selectors.map((r=>{try{return adjustSelectorSpecificity(r,y.layerCount*p)}catch(t){e.warn(n,`Failed to parse selector : "${r}" with message: "${t instanceof Error?t.message:t}"`)}return r})))})),y.sortLayerNames(),desugarNestedLayers(a,y),sortRootNodes(a,y),a.walkRules((e=>{if(e.parent&&"atrule"===e.parent.type&&l.includes(e.parent.name.toLowerCase()))return;const r=getLayerAtRuleAncestor(e);if(!r)return;const t=y.getLayerParams(r).join(".");let a=(y.layerOrder.get(t)??0)*p;e.some((e=>"decl"===e.type&&e.important))&&(a=y.layerCount-a),e.selectors=e.selectors.map((e=>adjustSelectorSpecificity(e,a)))}));someAtRuleInTree(a,(e=>isProcessableLayerRule(e)));)a.walkAtRules((e=>{isProcessableLayerRule(e)&&e.replaceWith(e.nodes)}));a.walkAtRules(t,(e=>{e.name="layer"}))}}};creator.postcss=!0;export{creator as default}; diff --git a/plugins/postcss-cascade-layers/dist/is-processable-layer-rule.d.ts b/plugins/postcss-cascade-layers/dist/is-processable-layer-rule.d.ts deleted file mode 100644 index 115b5dbad..000000000 --- a/plugins/postcss-cascade-layers/dist/is-processable-layer-rule.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import type { AtRule } from 'postcss'; -export declare function isProcessableLayerRule(atRule: AtRule): boolean; diff --git a/plugins/postcss-cascade-layers/dist/model.d.ts b/plugins/postcss-cascade-layers/dist/model.d.ts deleted file mode 100644 index 38a268e45..000000000 --- a/plugins/postcss-cascade-layers/dist/model.d.ts +++ /dev/null @@ -1,18 +0,0 @@ -import type { AtRule } from 'postcss'; -export declare class Model { - anonymousLayerCount: number; - layerCount: number; - layerOrder: Map; - layerParamsParsed: Map>; - layerNameParts: Map>; - constructor(); - createAnonymousLayerName(): string; - createImplicitLayerName(layerName: string): string; - addLayerParams(key: string, parts?: string): void; - addLayerParams(key: string, parts: Array): void; - addLayerNameParts(parts: string): void; - addLayerNameParts(parts: Array): void; - getLayerParams(layer: AtRule): Array; - getLayerNameList(layerName: string): Array; - sortLayerNames(): void; -} diff --git a/plugins/postcss-cascade-layers/dist/options.d.ts b/plugins/postcss-cascade-layers/dist/options.d.ts deleted file mode 100644 index e3a1943d5..000000000 --- a/plugins/postcss-cascade-layers/dist/options.d.ts +++ /dev/null @@ -1,9 +0,0 @@ -/** postcss-cascasde-layers plugin options */ -export type pluginOptions = { - /** Emit a warning when the "revert" keyword is found in your CSS. default: "warn" */ - onRevertLayerKeyword?: 'warn' | false; - /** Emit a warning when conditional rules could change the layer order. default: "warn" */ - onConditionalRulesChangingLayerOrder?: 'warn' | false; - /** Emit a warning when "layer" is used in "@import". default: "warn" */ - onImportLayerRule?: 'warn' | false; -}; diff --git a/plugins/postcss-cascade-layers/dist/record-layer-order.d.ts b/plugins/postcss-cascade-layers/dist/record-layer-order.d.ts deleted file mode 100644 index 05d6ac7df..000000000 --- a/plugins/postcss-cascade-layers/dist/record-layer-order.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -import type { Container, Result } from 'postcss'; -import type { Model } from './model'; -import { pluginOptions } from './options'; -export declare function recordLayerOrder(root: Container, model: Model, { result, options }: { - result: Result; - options: pluginOptions; -}): void; diff --git a/plugins/postcss-cascade-layers/dist/some-in-tree.d.ts b/plugins/postcss-cascade-layers/dist/some-in-tree.d.ts deleted file mode 100644 index 8c416c593..000000000 --- a/plugins/postcss-cascade-layers/dist/some-in-tree.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -import type { Container, ChildNode, AtRule } from 'postcss'; -export declare function someInTree(container: Container, predicate: (node: ChildNode) => boolean): boolean; -export declare function someAtRuleInTree(container: Container, predicate: (node: AtRule) => boolean): boolean; diff --git a/plugins/postcss-cascade-layers/dist/sort-root-nodes.d.ts b/plugins/postcss-cascade-layers/dist/sort-root-nodes.d.ts deleted file mode 100644 index 8eb479edb..000000000 --- a/plugins/postcss-cascade-layers/dist/sort-root-nodes.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -import type { Container } from 'postcss'; -import type { Model } from './model'; -export declare function sortRootNodes(root: Container, model: Model): void; diff --git a/plugins/postcss-cascade-layers/dist/split-important-styles.d.ts b/plugins/postcss-cascade-layers/dist/split-important-styles.d.ts deleted file mode 100644 index 270c69a98..000000000 --- a/plugins/postcss-cascade-layers/dist/split-important-styles.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import type { Container } from 'postcss'; -export declare function splitImportantStyles(root: Container): void; diff --git a/plugins/postcss-cascade-layers/package.json b/plugins/postcss-cascade-layers/package.json index abf67b75c..79d89f219 100644 --- a/plugins/postcss-cascade-layers/package.json +++ b/plugins/postcss-cascade-layers/package.json @@ -35,15 +35,18 @@ "engines": { "node": "^14 || ^16 || >=18" }, + "type": "module", "main": "dist/index.cjs", "module": "dist/index.mjs", - "types": "dist/index.d.ts", "exports": { ".": { - "types": "./dist/index.d.ts", - "import": "./dist/index.mjs", - "require": "./dist/index.cjs", - "default": "./dist/index.mjs" + "import": { + "types": "./dist/index.d.ts", + "default": "./dist/index.mjs" + }, + "require": { + "default": "./dist/index.cjs" + } } }, "files": [ diff --git a/plugins/postcss-color-function/api-extractor.json b/plugins/postcss-color-function/api-extractor.json new file mode 100644 index 000000000..42058be51 --- /dev/null +++ b/plugins/postcss-color-function/api-extractor.json @@ -0,0 +1,4 @@ +{ + "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json", + "extends": "../../api-extractor.json" +} diff --git a/plugins/postcss-color-function/dist/has-fallback-decl.d.ts b/plugins/postcss-color-function/dist/has-fallback-decl.d.ts deleted file mode 100644 index d7ae8d890..000000000 --- a/plugins/postcss-color-function/dist/has-fallback-decl.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import type { Declaration } from 'postcss'; -export declare function hasFallback(node: Declaration): boolean; diff --git a/plugins/postcss-color-function/dist/has-supports-at-rule-ancestor.d.ts b/plugins/postcss-color-function/dist/has-supports-at-rule-ancestor.d.ts deleted file mode 100644 index a46009ecc..000000000 --- a/plugins/postcss-color-function/dist/has-supports-at-rule-ancestor.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import type { Node } from 'postcss'; -export declare function hasSupportsAtRuleAncestor(node: Node): boolean; diff --git a/plugins/postcss-color-function/dist/index.cjs b/plugins/postcss-color-function/dist/index.cjs index 031ddeea3..9e08190c1 100644 --- a/plugins/postcss-color-function/dist/index.cjs +++ b/plugins/postcss-color-function/dist/index.cjs @@ -1 +1 @@ -"use strict";var e=require("@csstools/postcss-progressive-custom-properties"),s=require("@csstools/css-tokenizer"),r=require("@csstools/css-color-parser"),t=require("@csstools/css-parser-algorithms");function hasFallback(e){const s=e.parent;if(!s)return!1;const r=e.prop.toLowerCase(),t=s.index(e);for(let e=0;e({postcssPlugin:"postcss-color-function",Declaration:a=>{const i=a.value;if(!o.test(i))return;if(hasFallback(a))return;if(hasSupportsAtRuleAncestor(a))return;const l=s.tokenize({css:i}),c=t.replaceComponentValues(t.parseCommaSeparatedListOfComponentValues(l),(e=>{if(t.isFunctionNode(e)&&n.test(e.getName())){const s=r.color(e);if(!s)return;if(s.syntaxFlags.has(r.SyntaxFlag.Experimental))return;if(s.syntaxFlags.has(r.SyntaxFlag.HasNoneKeywords))return;if(s.syntaxFlags.has(r.SyntaxFlag.RelativeColorSyntax))return;return r.serializeRGB(s)}})),p=t.stringify(c);p!==i&&(a.cloneBefore({value:p}),null!=e&&e.preserve||a.remove())}});basePlugin.postcss=!0;const postcssPlugin=s=>{const r=Object.assign({preserve:!1,enableProgressiveCustomProperties:!0},s);return r.enableProgressiveCustomProperties&&r.preserve?{postcssPlugin:"postcss-color-function",plugins:[e(),basePlugin(r)]}:basePlugin(r)};postcssPlugin.postcss=!0,module.exports=postcssPlugin; +"use strict";var e=require("@csstools/postcss-progressive-custom-properties"),s=require("@csstools/css-tokenizer"),r=require("@csstools/css-color-parser"),t=require("@csstools/css-parser-algorithms");function hasFallback(e){const s=e.parent;if(!s)return!1;const r=e.prop.toLowerCase(),t=s.index(e);for(let e=0;e({postcssPlugin:"postcss-color-function",Declaration:a=>{const i=a.value;if(!o.test(i))return;if(hasFallback(a))return;if(hasSupportsAtRuleAncestor(a))return;const c=s.tokenize({css:i}),l=t.replaceComponentValues(t.parseCommaSeparatedListOfComponentValues(c),(e=>{if(t.isFunctionNode(e)&&n.test(e.getName())){const s=r.color(e);if(!s)return;if(s.syntaxFlags.has(r.SyntaxFlag.Experimental))return;if(s.syntaxFlags.has(r.SyntaxFlag.HasNoneKeywords))return;if(s.syntaxFlags.has(r.SyntaxFlag.RelativeColorSyntax))return;return r.serializeRGB(s)}})),p=t.stringify(l);p!==i&&(a.cloneBefore({value:p}),e?.preserve||a.remove())}});basePlugin.postcss=!0;const postcssPlugin=s=>{const r=Object.assign({preserve:!1,enableProgressiveCustomProperties:!0},s);return r.enableProgressiveCustomProperties&&r.preserve?{postcssPlugin:"postcss-color-function",plugins:[e(),basePlugin(r)]}:basePlugin(r)};postcssPlugin.postcss=!0,module.exports=postcssPlugin; diff --git a/plugins/postcss-color-function/dist/index.d.ts b/plugins/postcss-color-function/dist/index.d.ts index 616abbd78..358de7ea3 100644 --- a/plugins/postcss-color-function/dist/index.d.ts +++ b/plugins/postcss-color-function/dist/index.d.ts @@ -1,10 +1,14 @@ import type { PluginCreator } from 'postcss'; + /** postcss-color-function plugin options */ -export type pluginOptions = { +export declare type pluginOptions = { /** Preserve the original notation. default: false */ preserve?: boolean; /** Enable "@csstools/postcss-progressive-custom-properties". default: true */ enableProgressiveCustomProperties?: boolean; }; + declare const postcssPlugin: PluginCreator; export default postcssPlugin; + +export { } diff --git a/plugins/postcss-color-function/dist/index.mjs b/plugins/postcss-color-function/dist/index.mjs index f3e23f3c4..49c7c6204 100644 --- a/plugins/postcss-color-function/dist/index.mjs +++ b/plugins/postcss-color-function/dist/index.mjs @@ -1 +1 @@ -import s from"@csstools/postcss-progressive-custom-properties";import{tokenize as r}from"@csstools/css-tokenizer";import{color as e,SyntaxFlag as t,serializeRGB as o}from"@csstools/css-color-parser";import{replaceComponentValues as n,parseCommaSeparatedListOfComponentValues as a,isFunctionNode as c,stringify as p}from"@csstools/css-parser-algorithms";function hasFallback(s){const r=s.parent;if(!r)return!1;const e=s.prop.toLowerCase(),t=r.index(s);for(let s=0;s({postcssPlugin:"postcss-color-function",Declaration:u=>{const f=u.value;if(!l.test(f))return;if(hasFallback(u))return;if(hasSupportsAtRuleAncestor(u))return;const m=r({css:f}),g=n(a(m),(s=>{if(c(s)&&i.test(s.getName())){const r=e(s);if(!r)return;if(r.syntaxFlags.has(t.Experimental))return;if(r.syntaxFlags.has(t.HasNoneKeywords))return;if(r.syntaxFlags.has(t.RelativeColorSyntax))return;return o(r)}})),v=p(g);v!==f&&(u.cloneBefore({value:v}),null!=s&&s.preserve||u.remove())}});basePlugin.postcss=!0;const postcssPlugin=r=>{const e=Object.assign({preserve:!1,enableProgressiveCustomProperties:!0},r);return e.enableProgressiveCustomProperties&&e.preserve?{postcssPlugin:"postcss-color-function",plugins:[s(),basePlugin(e)]}:basePlugin(e)};postcssPlugin.postcss=!0;export{postcssPlugin as default}; +import s from"@csstools/postcss-progressive-custom-properties";import{tokenize as r}from"@csstools/css-tokenizer";import{color as e,SyntaxFlag as t,serializeRGB as o}from"@csstools/css-color-parser";import{replaceComponentValues as n,parseCommaSeparatedListOfComponentValues as a,isFunctionNode as c,stringify as p}from"@csstools/css-parser-algorithms";function hasFallback(s){const r=s.parent;if(!r)return!1;const e=s.prop.toLowerCase(),t=r.index(s);for(let s=0;s({postcssPlugin:"postcss-color-function",Declaration:u=>{const f=u.value;if(!i.test(f))return;if(hasFallback(u))return;if(hasSupportsAtRuleAncestor(u))return;const m=r({css:f}),g=n(a(m),(s=>{if(c(s)&&l.test(s.getName())){const r=e(s);if(!r)return;if(r.syntaxFlags.has(t.Experimental))return;if(r.syntaxFlags.has(t.HasNoneKeywords))return;if(r.syntaxFlags.has(t.RelativeColorSyntax))return;return o(r)}})),v=p(g);v!==f&&(u.cloneBefore({value:v}),s?.preserve||u.remove())}});basePlugin.postcss=!0;const postcssPlugin=r=>{const e=Object.assign({preserve:!1,enableProgressiveCustomProperties:!0},r);return e.enableProgressiveCustomProperties&&e.preserve?{postcssPlugin:"postcss-color-function",plugins:[s(),basePlugin(e)]}:basePlugin(e)};postcssPlugin.postcss=!0;export{postcssPlugin as default}; diff --git a/plugins/postcss-color-function/package.json b/plugins/postcss-color-function/package.json index a2b330a46..e560c0102 100644 --- a/plugins/postcss-color-function/package.json +++ b/plugins/postcss-color-function/package.json @@ -17,15 +17,18 @@ "engines": { "node": "^14 || ^16 || >=18" }, + "type": "module", "main": "dist/index.cjs", "module": "dist/index.mjs", - "types": "./dist/index.d.ts", "exports": { ".": { - "types": "./dist/index.d.ts", - "import": "./dist/index.mjs", - "require": "./dist/index.cjs", - "default": "./dist/index.mjs" + "import": { + "types": "./dist/index.d.ts", + "default": "./dist/index.mjs" + }, + "require": { + "default": "./dist/index.cjs" + } } }, "files": [ diff --git a/plugins/postcss-color-functional-notation/api-extractor.json b/plugins/postcss-color-functional-notation/api-extractor.json new file mode 100644 index 000000000..42058be51 --- /dev/null +++ b/plugins/postcss-color-functional-notation/api-extractor.json @@ -0,0 +1,4 @@ +{ + "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json", + "extends": "../../api-extractor.json" +} diff --git a/plugins/postcss-color-functional-notation/dist/has-fallback-decl.d.ts b/plugins/postcss-color-functional-notation/dist/has-fallback-decl.d.ts deleted file mode 100644 index d7ae8d890..000000000 --- a/plugins/postcss-color-functional-notation/dist/has-fallback-decl.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import type { Declaration } from 'postcss'; -export declare function hasFallback(node: Declaration): boolean; diff --git a/plugins/postcss-color-functional-notation/dist/has-supports-at-rule-ancestor.d.ts b/plugins/postcss-color-functional-notation/dist/has-supports-at-rule-ancestor.d.ts deleted file mode 100644 index 95f67a105..000000000 --- a/plugins/postcss-color-functional-notation/dist/has-supports-at-rule-ancestor.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -import type { Node } from 'postcss'; -export declare const rgb_hsl_functionRegex: RegExp; -export declare function hasSupportsAtRuleAncestor(node: Node): boolean; diff --git a/plugins/postcss-color-functional-notation/dist/index.cjs b/plugins/postcss-color-functional-notation/dist/index.cjs index bba165455..45316a198 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-tokenizer"),t=require("@csstools/css-color-parser"),r=require("@csstools/css-parser-algorithms");function hasFallback(s){const e=s.parent;if(!e)return!1;const t=s.prop.toLowerCase(),r=e.index(s);for(let s=0;s({postcssPlugin:"postcss-color-functional-notation",Declaration:n=>{const l=n.value;if(!o.test(l))return;if(hasFallback(n))return;if(hasSupportsAtRuleAncestor(n))return;const i=r.replaceComponentValues(r.parseCommaSeparatedListOfComponentValues(e.tokenize({css:l})),(s=>{if(r.isFunctionNode(s)&&a.test(s.getName())){const e=t.color(s);if(!e)return;if(e.syntaxFlags.has(t.SyntaxFlag.Experimental))return;if(e.syntaxFlags.has(t.SyntaxFlag.HasNoneKeywords))return;if(e.syntaxFlags.has(t.SyntaxFlag.RelativeColorSyntax))return;if((e.syntaxFlags.has(t.SyntaxFlag.LegacyRGB)||e.syntaxFlags.has(t.SyntaxFlag.LegacyHSL))&&!e.syntaxFlags.has(t.SyntaxFlag.HasPercentageAlpha))return;return"hsl"===e.colorNotation?t.serializeHSL(e):t.serializeRGB(e)}})),c=r.stringify(i);c!==l&&(n.cloneBefore({value:c}),null!=s&&s.preserve||n.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-tokenizer"),t=require("@csstools/css-color-parser"),r=require("@csstools/css-parser-algorithms");function hasFallback(s){const e=s.parent;if(!e)return!1;const t=s.prop.toLowerCase(),r=e.index(s);for(let s=0;s({postcssPlugin:"postcss-color-functional-notation",Declaration:n=>{const l=n.value;if(!o.test(l))return;if(hasFallback(n))return;if(hasSupportsAtRuleAncestor(n))return;const i=r.replaceComponentValues(r.parseCommaSeparatedListOfComponentValues(e.tokenize({css:l})),(s=>{if(r.isFunctionNode(s)&&a.test(s.getName())){const e=t.color(s);if(!e)return;if(e.syntaxFlags.has(t.SyntaxFlag.Experimental))return;if(e.syntaxFlags.has(t.SyntaxFlag.HasNoneKeywords))return;if(e.syntaxFlags.has(t.SyntaxFlag.RelativeColorSyntax))return;if((e.syntaxFlags.has(t.SyntaxFlag.LegacyRGB)||e.syntaxFlags.has(t.SyntaxFlag.LegacyHSL))&&!e.syntaxFlags.has(t.SyntaxFlag.HasPercentageAlpha))return;return"hsl"===e.colorNotation?t.serializeHSL(e):t.serializeRGB(e)}})),c=r.stringify(i);c!==l&&(n.cloneBefore({value:c}),s?.preserve||n.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.d.ts b/plugins/postcss-color-functional-notation/dist/index.d.ts index 7ed2f388e..096f1f4f7 100644 --- a/plugins/postcss-color-functional-notation/dist/index.d.ts +++ b/plugins/postcss-color-functional-notation/dist/index.d.ts @@ -1,10 +1,14 @@ import type { PluginCreator } from 'postcss'; + /** postcss-color-functional-notation plugin options */ -export type pluginOptions = { +export declare type pluginOptions = { /** Preserve the original notation. default: false */ preserve?: boolean; /** Enable "@csstools/postcss-progressive-custom-properties". default: true */ enableProgressiveCustomProperties?: boolean; }; + declare const postcssPlugin: PluginCreator; export default postcssPlugin; + +export { } diff --git a/plugins/postcss-color-functional-notation/dist/index.mjs b/plugins/postcss-color-functional-notation/dist/index.mjs index 0bec2f119..261f1b9d2 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{tokenize as t}from"@csstools/css-tokenizer";import{color as e,SyntaxFlag as r,serializeHSL as o,serializeRGB as n}from"@csstools/css-color-parser";import{replaceComponentValues as a,parseCommaSeparatedListOfComponentValues as l,isFunctionNode as c,stringify as i}from"@csstools/css-parser-algorithms";function hasFallback(s){const t=s.parent;if(!t)return!1;const e=s.prop.toLowerCase(),r=t.index(s);for(let s=0;s({postcssPlugin:"postcss-color-functional-notation",Declaration:f=>{const g=f.value;if(!p.test(g))return;if(hasFallback(f))return;if(hasSupportsAtRuleAncestor(f))return;const m=a(l(t({css:g})),(s=>{if(c(s)&&u.test(s.getName())){const t=e(s);if(!t)return;if(t.syntaxFlags.has(r.Experimental))return;if(t.syntaxFlags.has(r.HasNoneKeywords))return;if(t.syntaxFlags.has(r.RelativeColorSyntax))return;if((t.syntaxFlags.has(r.LegacyRGB)||t.syntaxFlags.has(r.LegacyHSL))&&!t.syntaxFlags.has(r.HasPercentageAlpha))return;return"hsl"===t.colorNotation?o(t):n(t)}})),h=i(m);h!==g&&(f.cloneBefore({value:h}),null!=s&&s.preserve||f.remove())}});basePlugin.postcss=!0;const postcssPlugin=t=>{const e=Object.assign({preserve:!1,enableProgressiveCustomProperties:!0},t);return e.enableProgressiveCustomProperties&&e.preserve?{postcssPlugin:"postcss-color-functional-notation",plugins:[s(),basePlugin(e)]}:basePlugin(e)};postcssPlugin.postcss=!0;export{postcssPlugin as default}; +import s from"@csstools/postcss-progressive-custom-properties";import{tokenize as t}from"@csstools/css-tokenizer";import{color as e,SyntaxFlag as r,serializeHSL as o,serializeRGB as a}from"@csstools/css-color-parser";import{replaceComponentValues as n,parseCommaSeparatedListOfComponentValues as c,isFunctionNode as l,stringify as i}from"@csstools/css-parser-algorithms";function hasFallback(s){const t=s.parent;if(!t)return!1;const e=s.prop.toLowerCase(),r=t.index(s);for(let s=0;s({postcssPlugin:"postcss-color-functional-notation",Declaration:f=>{const g=f.value;if(!p.test(g))return;if(hasFallback(f))return;if(hasSupportsAtRuleAncestor(f))return;const m=n(c(t({css:g})),(s=>{if(l(s)&&u.test(s.getName())){const t=e(s);if(!t)return;if(t.syntaxFlags.has(r.Experimental))return;if(t.syntaxFlags.has(r.HasNoneKeywords))return;if(t.syntaxFlags.has(r.RelativeColorSyntax))return;if((t.syntaxFlags.has(r.LegacyRGB)||t.syntaxFlags.has(r.LegacyHSL))&&!t.syntaxFlags.has(r.HasPercentageAlpha))return;return"hsl"===t.colorNotation?o(t):a(t)}})),h=i(m);h!==g&&(f.cloneBefore({value:h}),s?.preserve||f.remove())}});basePlugin.postcss=!0;const postcssPlugin=t=>{const e=Object.assign({preserve:!1,enableProgressiveCustomProperties:!0},t);return e.enableProgressiveCustomProperties&&e.preserve?{postcssPlugin:"postcss-color-functional-notation",plugins:[s(),basePlugin(e)]}:basePlugin(e)};postcssPlugin.postcss=!0;export{postcssPlugin as default}; diff --git a/plugins/postcss-color-functional-notation/package.json b/plugins/postcss-color-functional-notation/package.json index 6b986b423..cc879b710 100644 --- a/plugins/postcss-color-functional-notation/package.json +++ b/plugins/postcss-color-functional-notation/package.json @@ -17,15 +17,18 @@ "engines": { "node": "^14 || ^16 || >=18" }, + "type": "module", "main": "dist/index.cjs", "module": "dist/index.mjs", - "types": "./dist/index.d.ts", "exports": { ".": { - "types": "./dist/index.d.ts", - "import": "./dist/index.mjs", - "require": "./dist/index.cjs", - "default": "./dist/index.mjs" + "import": { + "types": "./dist/index.d.ts", + "default": "./dist/index.mjs" + }, + "require": { + "default": "./dist/index.cjs" + } } }, "files": [ diff --git a/plugins/postcss-color-hex-alpha/CHANGELOG.md b/plugins/postcss-color-hex-alpha/CHANGELOG.md index 1874b99fa..453d79c88 100644 --- a/plugins/postcss-color-hex-alpha/CHANGELOG.md +++ b/plugins/postcss-color-hex-alpha/CHANGELOG.md @@ -1,5 +1,9 @@ # Changes to PostCSS Color Hex Alpha +### Unreleased (patch) + +- Fix type definitions + ### 9.0.2 _February 6, 2023_ diff --git a/plugins/postcss-color-hex-alpha/api-extractor.json b/plugins/postcss-color-hex-alpha/api-extractor.json new file mode 100644 index 000000000..42058be51 --- /dev/null +++ b/plugins/postcss-color-hex-alpha/api-extractor.json @@ -0,0 +1,4 @@ +{ + "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json", + "extends": "../../api-extractor.json" +} diff --git a/plugins/postcss-color-hex-alpha/dist/has-fallback-decl.d.ts b/plugins/postcss-color-hex-alpha/dist/has-fallback-decl.d.ts deleted file mode 100644 index d7ae8d890..000000000 --- a/plugins/postcss-color-hex-alpha/dist/has-fallback-decl.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import type { Declaration } from 'postcss'; -export declare function hasFallback(node: Declaration): boolean; diff --git a/plugins/postcss-color-hex-alpha/dist/index.d.ts b/plugins/postcss-color-hex-alpha/dist/index.d.ts index 10220232f..ce39d2bcd 100644 --- a/plugins/postcss-color-hex-alpha/dist/index.d.ts +++ b/plugins/postcss-color-hex-alpha/dist/index.d.ts @@ -1,8 +1,12 @@ import type { PluginCreator } from 'postcss'; + +declare const creator: PluginCreator; +export default creator; + /** postcss-color-hex-alpha plugin options */ -export type pluginOptions = { +export declare type pluginOptions = { /** Preserve the original notation. default: false */ preserve?: boolean; }; -declare const creator: PluginCreator; -export default creator; + +export { } diff --git a/plugins/postcss-color-hex-alpha/package.json b/plugins/postcss-color-hex-alpha/package.json index e19d3e54a..8fb99681d 100644 --- a/plugins/postcss-color-hex-alpha/package.json +++ b/plugins/postcss-color-hex-alpha/package.json @@ -34,15 +34,18 @@ "engines": { "node": "^14 || ^16 || >=18" }, + "type": "module", "main": "dist/index.cjs", "module": "dist/index.mjs", - "types": "dist/index.d.ts", "exports": { ".": { - "types": "./dist/index.d.ts", - "import": "./dist/index.mjs", - "require": "./dist/index.cjs", - "default": "./dist/index.mjs" + "import": { + "types": "./dist/index.d.ts", + "default": "./dist/index.mjs" + }, + "require": { + "default": "./dist/index.cjs" + } } }, "files": [ diff --git a/plugins/postcss-color-mix-function/api-extractor.json b/plugins/postcss-color-mix-function/api-extractor.json new file mode 100644 index 000000000..42058be51 --- /dev/null +++ b/plugins/postcss-color-mix-function/api-extractor.json @@ -0,0 +1,4 @@ +{ + "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json", + "extends": "../../api-extractor.json" +} diff --git a/plugins/postcss-color-mix-function/dist/has-fallback-decl.d.ts b/plugins/postcss-color-mix-function/dist/has-fallback-decl.d.ts deleted file mode 100644 index d7ae8d890..000000000 --- a/plugins/postcss-color-mix-function/dist/has-fallback-decl.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import type { Declaration } from 'postcss'; -export declare function hasFallback(node: Declaration): boolean; diff --git a/plugins/postcss-color-mix-function/dist/has-supports-at-rule-ancestor.d.ts b/plugins/postcss-color-mix-function/dist/has-supports-at-rule-ancestor.d.ts deleted file mode 100644 index a46009ecc..000000000 --- a/plugins/postcss-color-mix-function/dist/has-supports-at-rule-ancestor.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import type { Node } from 'postcss'; -export declare function hasSupportsAtRuleAncestor(node: Node): boolean; diff --git a/plugins/postcss-color-mix-function/dist/index.cjs b/plugins/postcss-color-mix-function/dist/index.cjs index f1c26e4af..8e43b99b7 100644 --- a/plugins/postcss-color-mix-function/dist/index.cjs +++ b/plugins/postcss-color-mix-function/dist/index.cjs @@ -1 +1 @@ -"use strict";var e=require("@csstools/postcss-progressive-custom-properties"),s=require("@csstools/css-tokenizer"),r=require("@csstools/css-color-parser"),t=require("@csstools/css-parser-algorithms");function hasFallback(e){const s=e.parent;if(!s)return!1;const r=e.prop.toLowerCase(),t=s.index(e);for(let e=0;e({postcssPlugin:"postcss-color-mix-function",Declaration:a=>{const i=a.value;if(!o.test(i))return;if(hasFallback(a))return;if(hasSupportsAtRuleAncestor(a))return;const u=s.tokenize({css:i}),l=t.replaceComponentValues(t.parseCommaSeparatedListOfComponentValues(u),(e=>{if(t.isFunctionNode(e)&&n.test(e.getName())){const s=r.color(e);if(!s)return;if(s.syntaxFlags.has(r.SyntaxFlag.Experimental))return;return r.serializeRGB(s)}})),c=t.stringify(l);if(c===i)return;let p=c;null!=e&&e.subFeatures.displayP3&&(p=t.stringify(t.replaceComponentValues(t.parseCommaSeparatedListOfComponentValues(u),(e=>{if(t.isFunctionNode(e)&&n.test(e.getName())){const s=r.color(e);if(!s)return;return r.colorDataFitsRGB_Gamut(s)?r.serializeRGB(s):r.serializeP3(s)}})))),a.cloneBefore({value:c}),null!=e&&e.subFeatures.displayP3&&p!==c&&a.cloneBefore({value:p}),null!=e&&e.preserve||a.remove()}});basePlugin.postcss=!0;const postcssPlugin=s=>{const r=Object.assign({enableProgressiveCustomProperties:!0,preserve:!1,subFeatures:{displayP3:!0}},s);return r.subFeatures=Object.assign({displayP3:!0},r.subFeatures),r.enableProgressiveCustomProperties&&(r.preserve||r.subFeatures.displayP3)?{postcssPlugin:"postcss-color-mix-function",plugins:[e(),basePlugin(r)]}:basePlugin(r)};postcssPlugin.postcss=!0,module.exports=postcssPlugin; +"use strict";var e=require("@csstools/postcss-progressive-custom-properties"),s=require("@csstools/css-tokenizer"),r=require("@csstools/css-color-parser"),t=require("@csstools/css-parser-algorithms");function hasFallback(e){const s=e.parent;if(!s)return!1;const r=e.prop.toLowerCase(),t=s.index(e);for(let e=0;e({postcssPlugin:"postcss-color-mix-function",Declaration:n=>{const i=n.value;if(!o.test(i))return;if(hasFallback(n))return;if(hasSupportsAtRuleAncestor(n))return;const u=s.tokenize({css:i}),l=t.replaceComponentValues(t.parseCommaSeparatedListOfComponentValues(u),(e=>{if(t.isFunctionNode(e)&&a.test(e.getName())){const s=r.color(e);if(!s)return;if(s.syntaxFlags.has(r.SyntaxFlag.Experimental))return;return r.serializeRGB(s)}})),c=t.stringify(l);if(c===i)return;let p=c;e?.subFeatures.displayP3&&(p=t.stringify(t.replaceComponentValues(t.parseCommaSeparatedListOfComponentValues(u),(e=>{if(t.isFunctionNode(e)&&a.test(e.getName())){const s=r.color(e);if(!s)return;return r.colorDataFitsRGB_Gamut(s)?r.serializeRGB(s):r.serializeP3(s)}})))),n.cloneBefore({value:c}),e?.subFeatures.displayP3&&p!==c&&n.cloneBefore({value:p}),e?.preserve||n.remove()}});basePlugin.postcss=!0;const postcssPlugin=s=>{const r=Object.assign({enableProgressiveCustomProperties:!0,preserve:!1,subFeatures:{displayP3:!0}},s);return r.subFeatures=Object.assign({displayP3:!0},r.subFeatures),r.enableProgressiveCustomProperties&&(r.preserve||r.subFeatures.displayP3)?{postcssPlugin:"postcss-color-mix-function",plugins:[e(),basePlugin(r)]}:basePlugin(r)};postcssPlugin.postcss=!0,module.exports=postcssPlugin; diff --git a/plugins/postcss-color-mix-function/dist/index.d.ts b/plugins/postcss-color-mix-function/dist/index.d.ts index 22a656f08..0cae0a44b 100644 --- a/plugins/postcss-color-mix-function/dist/index.d.ts +++ b/plugins/postcss-color-mix-function/dist/index.d.ts @@ -1,6 +1,7 @@ import type { PluginCreator } from 'postcss'; + /** postcss-color-mix-function plugin options */ -export type pluginOptions = { +export declare type pluginOptions = { /** Preserve the original notation. default: false */ preserve?: boolean; /** Enable "@csstools/postcss-progressive-custom-properties". default: true */ @@ -11,5 +12,8 @@ export type pluginOptions = { displayP3?: boolean; }; }; + declare const postcssPlugin: PluginCreator; export default postcssPlugin; + +export { } diff --git a/plugins/postcss-color-mix-function/dist/index.mjs b/plugins/postcss-color-mix-function/dist/index.mjs index 90a2ede20..146902691 100644 --- a/plugins/postcss-color-mix-function/dist/index.mjs +++ b/plugins/postcss-color-mix-function/dist/index.mjs @@ -1 +1 @@ -import s from"@csstools/postcss-progressive-custom-properties";import{tokenize as e}from"@csstools/css-tokenizer";import{color as r,SyntaxFlag as t,serializeRGB as o,colorDataFitsRGB_Gamut as n,serializeP3 as a}from"@csstools/css-color-parser";import{replaceComponentValues as i,parseCommaSeparatedListOfComponentValues as u,isFunctionNode as l,stringify as c}from"@csstools/css-parser-algorithms";function hasFallback(s){const e=s.parent;if(!e)return!1;const r=s.prop.toLowerCase(),t=e.index(s);for(let s=0;s({postcssPlugin:"postcss-color-mix-function",Declaration:m=>{const b=m.value;if(!p.test(b))return;if(hasFallback(m))return;if(hasSupportsAtRuleAncestor(m))return;const g=e({css:b}),P=i(u(g),(s=>{if(l(s)&&f.test(s.getName())){const e=r(s);if(!e)return;if(e.syntaxFlags.has(t.Experimental))return;return o(e)}})),d=c(P);if(d===b)return;let v=d;null!=s&&s.subFeatures.displayP3&&(v=c(i(u(g),(s=>{if(l(s)&&f.test(s.getName())){const e=r(s);if(!e)return;return n(e)?o(e):a(e)}})))),m.cloneBefore({value:d}),null!=s&&s.subFeatures.displayP3&&v!==d&&m.cloneBefore({value:v}),null!=s&&s.preserve||m.remove()}});basePlugin.postcss=!0;const postcssPlugin=e=>{const r=Object.assign({enableProgressiveCustomProperties:!0,preserve:!1,subFeatures:{displayP3:!0}},e);return r.subFeatures=Object.assign({displayP3:!0},r.subFeatures),r.enableProgressiveCustomProperties&&(r.preserve||r.subFeatures.displayP3)?{postcssPlugin:"postcss-color-mix-function",plugins:[s(),basePlugin(r)]}:basePlugin(r)};postcssPlugin.postcss=!0;export{postcssPlugin as default}; +import s from"@csstools/postcss-progressive-custom-properties";import{tokenize as e}from"@csstools/css-tokenizer";import{color as r,SyntaxFlag as t,serializeRGB as o,colorDataFitsRGB_Gamut as n,serializeP3 as a}from"@csstools/css-color-parser";import{replaceComponentValues as i,parseCommaSeparatedListOfComponentValues as u,isFunctionNode as c,stringify as p}from"@csstools/css-parser-algorithms";function hasFallback(s){const e=s.parent;if(!e)return!1;const r=s.prop.toLowerCase(),t=e.index(s);for(let s=0;s({postcssPlugin:"postcss-color-mix-function",Declaration:m=>{const b=m.value;if(!l.test(b))return;if(hasFallback(m))return;if(hasSupportsAtRuleAncestor(m))return;const g=e({css:b}),P=i(u(g),(s=>{if(c(s)&&f.test(s.getName())){const e=r(s);if(!e)return;if(e.syntaxFlags.has(t.Experimental))return;return o(e)}})),d=p(P);if(d===b)return;let v=d;s?.subFeatures.displayP3&&(v=p(i(u(g),(s=>{if(c(s)&&f.test(s.getName())){const e=r(s);if(!e)return;return n(e)?o(e):a(e)}})))),m.cloneBefore({value:d}),s?.subFeatures.displayP3&&v!==d&&m.cloneBefore({value:v}),s?.preserve||m.remove()}});basePlugin.postcss=!0;const postcssPlugin=e=>{const r=Object.assign({enableProgressiveCustomProperties:!0,preserve:!1,subFeatures:{displayP3:!0}},e);return r.subFeatures=Object.assign({displayP3:!0},r.subFeatures),r.enableProgressiveCustomProperties&&(r.preserve||r.subFeatures.displayP3)?{postcssPlugin:"postcss-color-mix-function",plugins:[s(),basePlugin(r)]}:basePlugin(r)};postcssPlugin.postcss=!0;export{postcssPlugin as default}; diff --git a/plugins/postcss-color-mix-function/package.json b/plugins/postcss-color-mix-function/package.json index 1636ac7f4..5e10aa361 100644 --- a/plugins/postcss-color-mix-function/package.json +++ b/plugins/postcss-color-mix-function/package.json @@ -27,15 +27,18 @@ "engines": { "node": "^14 || ^16 || >=18" }, + "type": "module", "main": "dist/index.cjs", "module": "dist/index.mjs", - "types": "dist/index.d.ts", "exports": { ".": { - "types": "./dist/index.d.ts", - "import": "./dist/index.mjs", - "require": "./dist/index.cjs", - "default": "./dist/index.mjs" + "import": { + "types": "./dist/index.d.ts", + "default": "./dist/index.mjs" + }, + "require": { + "default": "./dist/index.cjs" + } } }, "files": [ diff --git a/plugins/postcss-color-rebeccapurple/CHANGELOG.md b/plugins/postcss-color-rebeccapurple/CHANGELOG.md index 0662b6158..fef189d70 100644 --- a/plugins/postcss-color-rebeccapurple/CHANGELOG.md +++ b/plugins/postcss-color-rebeccapurple/CHANGELOG.md @@ -1,5 +1,9 @@ # Changes to PostCSS RebeccaPurple +### Unreleased (patch) + +- Fix type definitions + ### 9.0.1 _September 18, 2023_ diff --git a/plugins/postcss-color-rebeccapurple/api-extractor.json b/plugins/postcss-color-rebeccapurple/api-extractor.json new file mode 100644 index 000000000..42058be51 --- /dev/null +++ b/plugins/postcss-color-rebeccapurple/api-extractor.json @@ -0,0 +1,4 @@ +{ + "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json", + "extends": "../../api-extractor.json" +} diff --git a/plugins/postcss-color-rebeccapurple/dist/has-fallback-decl.d.ts b/plugins/postcss-color-rebeccapurple/dist/has-fallback-decl.d.ts deleted file mode 100644 index d7ae8d890..000000000 --- a/plugins/postcss-color-rebeccapurple/dist/has-fallback-decl.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import type { Declaration } from 'postcss'; -export declare function hasFallback(node: Declaration): boolean; diff --git a/plugins/postcss-color-rebeccapurple/dist/index.d.ts b/plugins/postcss-color-rebeccapurple/dist/index.d.ts index 2909bb928..fd19298ad 100644 --- a/plugins/postcss-color-rebeccapurple/dist/index.d.ts +++ b/plugins/postcss-color-rebeccapurple/dist/index.d.ts @@ -1,8 +1,12 @@ import type { PluginCreator } from 'postcss'; + +declare const creator: PluginCreator; +export default creator; + /** postcss-color-rebeccapurple plugin options */ -export type pluginOptions = { +export declare type pluginOptions = { /** Preserve the original notation. default: false */ preserve?: boolean; }; -declare const creator: PluginCreator; -export default creator; + +export { } diff --git a/plugins/postcss-color-rebeccapurple/package.json b/plugins/postcss-color-rebeccapurple/package.json index 67a793ad6..f5e81525d 100644 --- a/plugins/postcss-color-rebeccapurple/package.json +++ b/plugins/postcss-color-rebeccapurple/package.json @@ -34,15 +34,18 @@ "engines": { "node": "^14 || ^16 || >=18" }, + "type": "module", "main": "dist/index.cjs", "module": "dist/index.mjs", - "types": "dist/index.d.ts", "exports": { ".": { - "types": "./dist/index.d.ts", - "import": "./dist/index.mjs", - "require": "./dist/index.cjs", - "default": "./dist/index.mjs" + "import": { + "types": "./dist/index.d.ts", + "default": "./dist/index.mjs" + }, + "require": { + "default": "./dist/index.cjs" + } } }, "files": [ diff --git a/plugins/postcss-conditional-values/CHANGELOG.md b/plugins/postcss-conditional-values/CHANGELOG.md index 2f23004fa..315d46f5a 100644 --- a/plugins/postcss-conditional-values/CHANGELOG.md +++ b/plugins/postcss-conditional-values/CHANGELOG.md @@ -1,5 +1,9 @@ # Changes to PostCSS Conditional Values +### Unreleased (patch) + +- Fix type definitions + ### 3.0.0 _July 3, 2023_ diff --git a/plugins/postcss-conditional-values/api-extractor.json b/plugins/postcss-conditional-values/api-extractor.json new file mode 100644 index 000000000..42058be51 --- /dev/null +++ b/plugins/postcss-conditional-values/api-extractor.json @@ -0,0 +1,4 @@ +{ + "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json", + "extends": "../../api-extractor.json" +} diff --git a/plugins/postcss-conditional-values/dist/index.d.ts b/plugins/postcss-conditional-values/dist/index.d.ts index 7d41e514f..3cac06f72 100644 --- a/plugins/postcss-conditional-values/dist/index.d.ts +++ b/plugins/postcss-conditional-values/dist/index.d.ts @@ -1,6 +1,10 @@ import type { PluginCreator } from 'postcss'; -export type pluginOptions = { - functionName: string; -}; + declare const creator: PluginCreator; export default creator; + +export declare type pluginOptions = { + functionName: string; +}; + +export { } diff --git a/plugins/postcss-conditional-values/package.json b/plugins/postcss-conditional-values/package.json index 33f609abf..d5a064616 100644 --- a/plugins/postcss-conditional-values/package.json +++ b/plugins/postcss-conditional-values/package.json @@ -27,15 +27,18 @@ "engines": { "node": "^14 || ^16 || >=18" }, + "type": "module", "main": "dist/index.cjs", "module": "dist/index.mjs", - "types": "dist/index.d.ts", "exports": { ".": { - "types": "./dist/index.d.ts", - "import": "./dist/index.mjs", - "require": "./dist/index.cjs", - "default": "./dist/index.mjs" + "import": { + "types": "./dist/index.d.ts", + "default": "./dist/index.mjs" + }, + "require": { + "default": "./dist/index.cjs" + } } }, "files": [ diff --git a/plugins/postcss-custom-media/CHANGELOG.md b/plugins/postcss-custom-media/CHANGELOG.md index 645a1332b..ac8d28223 100644 --- a/plugins/postcss-custom-media/CHANGELOG.md +++ b/plugins/postcss-custom-media/CHANGELOG.md @@ -2,7 +2,7 @@ ### Unreleased (patch) -- Small fixes in type definitions +- Fix type definitions ### 10.0.2 diff --git a/plugins/postcss-custom-media/api-extractor.json b/plugins/postcss-custom-media/api-extractor.json new file mode 100644 index 000000000..42058be51 --- /dev/null +++ b/plugins/postcss-custom-media/api-extractor.json @@ -0,0 +1,4 @@ +{ + "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json", + "extends": "../../api-extractor.json" +} diff --git a/plugins/postcss-custom-media/dist/cascade-layers.d.ts b/plugins/postcss-custom-media/dist/cascade-layers.d.ts deleted file mode 100644 index b9891949e..000000000 --- a/plugins/postcss-custom-media/dist/cascade-layers.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -import type { Node, Root } from 'postcss'; -export declare function collectCascadeLayerOrder(root: Root): WeakMap; -export declare function cascadeLayerNumberForNode(node: Node, layers: WeakMap): number; diff --git a/plugins/postcss-custom-media/dist/custom-media-from-root.d.ts b/plugins/postcss-custom-media/dist/custom-media-from-root.d.ts deleted file mode 100644 index f248ed932..000000000 --- a/plugins/postcss-custom-media/dist/custom-media-from-root.d.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { MediaQuery } from '@csstools/media-query-list-parser'; -import type { Result, Root as PostCSSRoot } from 'postcss'; -export default function getCustomMedia(root: PostCSSRoot, result: Result, opts: { - preserve?: boolean; -}): Map; - falsy: Array; -}>; diff --git a/plugins/postcss-custom-media/dist/index.cjs b/plugins/postcss-custom-media/dist/index.cjs index af2499116..54186e432 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=>{var s;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.parse(i);if(null!=(s=l)&&s.length){{let e=r.parent;for(;e&&"atrule"===e.type&&"layer"===e.name.toLowerCase();){const r=o.get(e);r?(l=l.map((e=>r.concat(e))),e=e.parent):e=e.parent}}if(e.addLayerToModel(a,l),r.nodes){const e=l[0].concat(n);t.set(r,e),o.set(r,l[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;let n=r;for(;e.size>0;)try{toposort(Array.from(e.keys()),n);break}catch(r){if(!r._graphNode)throw r;e.delete(r._graphNode),t.add(r._graphNode),n=n.filter((e=>-1===e.indexOf(r._graphNode)))}return t}function toposort(e,r){let t=e.length;const n=new Array(t),o={};let a=t;const s=makeOutgoingEdges(r),i=makeNodesHash(e);for(;a--;)o[a]||visit(e[a],a,new Set);return n;function visit(e,r,a){if(a.has(e)){const r=new Error("Cyclic dependency"+JSON.stringify(e));throw r._graphNode=e,r}if(!i.has(e))return;if(o[r])return;o[r]=!0;let l=s.get(e)||new Set;if(l=Array.from(l),r=l.length){a.add(e);do{const e=l[--r];visit(e,i.get(e),a)}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[e,a]))}}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.dependsOn)),!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{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;let n=r;for(;e.size>0;)try{toposort(Array.from(e.keys()),n);break}catch(r){if(!r._graphNode)throw r;e.delete(r._graphNode),t.add(r._graphNode),n=n.filter((e=>-1===e.indexOf(r._graphNode)))}return t}function toposort(e,r){let t=e.length;const n=new Array(t),o={};let a=t;const s=makeOutgoingEdges(r),i=makeNodesHash(e);for(;a--;)o[a]||visit(e[a],a,new Set);return n;function visit(e,r,a){if(a.has(e)){const r=new Error("Cyclic dependency"+JSON.stringify(e));throw r._graphNode=e,r}if(!i.has(e))return;if(o[r])return;o[r]=!0;let l=s.get(e)||new Set;if(l=Array.from(l),r=l.length){a.add(e);do{const e=l[--r];visit(e,i.get(e),a)}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[e,a]))}}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.dependsOn)),!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{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.d.ts b/plugins/postcss-custom-media/dist/index.d.ts index 79f6f1e73..ff7d04217 100644 --- a/plugins/postcss-custom-media/dist/index.d.ts +++ b/plugins/postcss-custom-media/dist/index.d.ts @@ -1,8 +1,12 @@ import type { PluginCreator } from 'postcss'; + +declare const creator: PluginCreator; +export default creator; + /** postcss-custom-media plugin options */ -export type pluginOptions = { +export declare type pluginOptions = { /** Preserve the original notation. default: false */ preserve?: boolean; }; -declare const creator: PluginCreator; -export default creator; + +export { } diff --git a/plugins/postcss-custom-media/dist/index.mjs b/plugins/postcss-custom-media/dist/index.mjs index 2a5093145..0463fa6b8 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 a,cloneTokens as o,stringify as s}from"@csstools/css-tokenizer";import{parseFromTokens as i,parse as l,isMediaFeatureBoolean as u,isMediaFeature as c,newMediaFeaturePlain as p,isMediaQueryInvalid as f,isMediaQueryWithType as m,isMediaAnd as d,isMediaOr as h,isMediaNot as y,isMediaConditionList as g,isGeneralEnclosed as v}from"@csstools/media-query-list-parser";const w=e("csstools-implicit-layer")[0];function collectCascadeLayerOrder(t){const n=new Map,a=new Map,o=[];t.walkAtRules((t=>{var s;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 i;if(t.nodes)i=normalizeLayerName(t.params,1);else{if(!t.params.trim())return;i=t.params}let l=e(i);if(null!=(s=l)&&s.length){{let e=t.parent;for(;e&&"atrule"===e.type&&"layer"===e.name.toLowerCase();){const r=a.get(e);r?(l=l.map((e=>r.concat(e))),e=e.parent):e=e.parent}}if(r(o,l),t.nodes){const e=l[0].concat(w);n.set(t,e),a.set(t,l[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 C=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&&!C.has(r.name.toLowerCase()))return!1;r=r.parent}return!0}function removeCyclicReferences(e,r){const t=new Set;let n=r;for(;e.size>0;)try{toposort(Array.from(e.keys()),n);break}catch(r){if(!r._graphNode)throw r;e.delete(r._graphNode),t.add(r._graphNode),n=n.filter((e=>-1===e.indexOf(r._graphNode)))}return t}function toposort(e,r){let t=e.length;const n=new Array(t),a={};let o=t;const s=makeOutgoingEdges(r),i=makeNodesHash(e);for(;o--;)a[o]||visit(e[o],o,new Set);return n;function visit(e,r,o){if(o.has(e)){const r=new Error("Cyclic dependency"+JSON.stringify(e));throw r._graphNode=e,r}if(!i.has(e))return;if(a[r])return;a[r]=!0;let l=s.get(e)||new Set;if(l=Array.from(l),r=l.length){o.add(e);do{const e=l[--r];visit(e,i.get(e),o)}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}]],k=[[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 a=0;a{throw new Error(`Unable to parse media query "${s(...l)}"`)}}),c=i(o(l),{preserveInvalidMediaQueries:!0,onParseError:()=>{throw new Error(`Unable to parse media query "${s(...l)}"`)}});for(let e=0;e[e,a]))}}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.dependsOn)),!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=l(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(!u(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(!u(a))return;const o=n.parent;if(!c(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(c(e.node))return r=e.node,!1})),r&&r.feature)return o.feature=r.feature,t=[{replaceWith:e.toString()}],!1}const r=p(W[0][4].value,W[2]);o.feature=r.feature;const n=e.toString(),a=p(k[0][4].value,k[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(f(e))return!1;if(m(e))return!1;let r=!0;return e.walk((e=>{if(d(e.node)||h(e.node)||y(e.node)||g(e.node)||v(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{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}; +import{parse as e,addLayerToModel as r}from"@csstools/cascade-layer-name-parser";import{tokenizer as t,TokenType as n,NumberType as o,cloneTokens as a,stringify as s}from"@csstools/css-tokenizer";import{parseFromTokens as i,parse as l,isMediaFeatureBoolean as u,isMediaFeature as c,newMediaFeaturePlain as p,isMediaQueryInvalid as f,isMediaQueryWithType as m,isMediaAnd as d,isMediaOr as h,isMediaNot as y,isMediaConditionList as g,isGeneralEnclosed as v}from"@csstools/media-query-list-parser";const w=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(w);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 C=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&&!C.has(r.name.toLowerCase()))return!1;r=r.parent}return!0}function removeCyclicReferences(e,r){const t=new Set;let n=r;for(;e.size>0;)try{toposort(Array.from(e.keys()),n);break}catch(r){if(!r._graphNode)throw r;e.delete(r._graphNode),t.add(r._graphNode),n=n.filter((e=>-1===e.indexOf(r._graphNode)))}return t}function toposort(e,r){let t=e.length;const n=new Array(t),o={};let a=t;const s=makeOutgoingEdges(r),i=makeNodesHash(e);for(;a--;)o[a]||visit(e[a],a,new Set);return n;function visit(e,r,a){if(a.has(e)){const r=new Error("Cyclic dependency"+JSON.stringify(e));throw r._graphNode=e,r}if(!i.has(e))return;if(o[r])return;o[r]=!0;let l=s.get(e)||new Set;if(l=Array.from(l),r=l.length){a.add(e);do{const e=l[--r];visit(e,i.get(e),a)}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}]],k=[[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 o=0;o{throw new Error(`Unable to parse media query "${s(...l)}"`)}}),c=i(a(l),{preserveInvalidMediaQueries:!0,onParseError:()=>{throw new Error(`Unable to parse media query "${s(...l)}"`)}});for(let e=0;e[e,o]))}}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.dependsOn)),!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=l(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(!u(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(!u(o))return;const a=n.parent;if(!c(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(c(e.node))return r=e.node,!1})),r&&r.feature)return a.feature=r.feature,t=[{replaceWith:e.toString()}],!1}const r=p(W[0][4].value,W[2]);a.feature=r.feature;const n=e.toString(),o=p(k[0][4].value,k[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(f(e))return!1;if(m(e))return!1;let r=!0;return e.walk((e=>{if(d(e.node)||h(e.node)||y(e.node)||g(e.node)||v(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{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}; diff --git a/plugins/postcss-custom-media/dist/is-processable-custom-media-rule.d.ts b/plugins/postcss-custom-media/dist/is-processable-custom-media-rule.d.ts deleted file mode 100644 index 04c46a3d8..000000000 --- a/plugins/postcss-custom-media/dist/is-processable-custom-media-rule.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import type { AtRule } from 'postcss'; -export declare function isProcessableCustomMediaRule(atRule: AtRule): boolean; diff --git a/plugins/postcss-custom-media/dist/toposort.d.ts b/plugins/postcss-custom-media/dist/toposort.d.ts deleted file mode 100644 index ffb196fdd..000000000 --- a/plugins/postcss-custom-media/dist/toposort.d.ts +++ /dev/null @@ -1 +0,0 @@ -export declare function removeCyclicReferences(nodes: Map, edges: Array>): Set; diff --git a/plugins/postcss-custom-media/dist/transform-at-media/always-true-or-false.d.ts b/plugins/postcss-custom-media/dist/transform-at-media/always-true-or-false.d.ts deleted file mode 100644 index e37de5a34..000000000 --- a/plugins/postcss-custom-media/dist/transform-at-media/always-true-or-false.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -import type { TokenColon, TokenIdent, TokenNumber } from '@csstools/css-tokenizer'; -export declare const alwaysTrue: [TokenIdent, TokenColon, TokenNumber]; -export declare const neverTrue: [TokenIdent, TokenColon, TokenNumber]; diff --git a/plugins/postcss-custom-media/dist/transform-at-media/at-media-params-tokens.d.ts b/plugins/postcss-custom-media/dist/transform-at-media/at-media-params-tokens.d.ts deleted file mode 100644 index e9a831301..000000000 --- a/plugins/postcss-custom-media/dist/transform-at-media/at-media-params-tokens.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import type { CSSToken } from '@csstools/css-tokenizer'; -export declare function atMediaParamsTokens(params: string): Array; diff --git a/plugins/postcss-custom-media/dist/transform-at-media/custom-media.d.ts b/plugins/postcss-custom-media/dist/transform-at-media/custom-media.d.ts deleted file mode 100644 index 5ef92dc5f..000000000 --- a/plugins/postcss-custom-media/dist/transform-at-media/custom-media.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { MediaQuery } from '@csstools/media-query-list-parser'; -export declare function parseCustomMedia(params: string): { - name: string; - truthy: Array; - falsy: Array; - dependsOn: Array<[string, string]>; -} | false; diff --git a/plugins/postcss-custom-media/dist/transform-at-media/transform-at-media.d.ts b/plugins/postcss-custom-media/dist/transform-at-media/transform-at-media.d.ts deleted file mode 100644 index 065620ce6..000000000 --- a/plugins/postcss-custom-media/dist/transform-at-media/transform-at-media.d.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { MediaQuery } from '@csstools/media-query-list-parser'; -export declare function transformAtMediaListTokens(params: string, replacements: Map; - falsy: Array; -}>): Array<{ - replaceWith: string; - encapsulateWith?: string; -}>; diff --git a/plugins/postcss-custom-media/dist/transform-at-media/true-and-false.d.ts b/plugins/postcss-custom-media/dist/transform-at-media/true-and-false.d.ts deleted file mode 100644 index ba1fa3a9f..000000000 --- a/plugins/postcss-custom-media/dist/transform-at-media/true-and-false.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import type { CSSToken } from '@csstools/css-tokenizer'; -export declare function replaceTrueAndFalseTokens(tokens: Array): Array; diff --git a/plugins/postcss-custom-media/package.json b/plugins/postcss-custom-media/package.json index bdff6eb45..d77c946d1 100644 --- a/plugins/postcss-custom-media/package.json +++ b/plugins/postcss-custom-media/package.json @@ -34,15 +34,18 @@ "engines": { "node": "^14 || ^16 || >=18" }, + "type": "module", "main": "dist/index.cjs", "module": "dist/index.mjs", - "types": "dist/index.d.ts", "exports": { ".": { - "types": "./dist/index.d.ts", - "import": "./dist/index.mjs", - "require": "./dist/index.cjs", - "default": "./dist/index.mjs" + "import": { + "types": "./dist/index.d.ts", + "default": "./dist/index.mjs" + }, + "require": { + "default": "./dist/index.cjs" + } } }, "files": [ diff --git a/plugins/postcss-custom-properties/CHANGELOG.md b/plugins/postcss-custom-properties/CHANGELOG.md index 31bbc294c..8abc29538 100644 --- a/plugins/postcss-custom-properties/CHANGELOG.md +++ b/plugins/postcss-custom-properties/CHANGELOG.md @@ -1,5 +1,9 @@ # Changes to PostCSS Custom Properties +### Unreleased (patch) + +- Fix type definitions + ### 13.3.2 _September 24, 2023_ diff --git a/plugins/postcss-custom-properties/api-extractor.json b/plugins/postcss-custom-properties/api-extractor.json new file mode 100644 index 000000000..42058be51 --- /dev/null +++ b/plugins/postcss-custom-properties/api-extractor.json @@ -0,0 +1,4 @@ +{ + "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json", + "extends": "../../api-extractor.json" +} diff --git a/plugins/postcss-custom-properties/dist/cascade-layers.d.ts b/plugins/postcss-custom-properties/dist/cascade-layers.d.ts deleted file mode 100644 index b9891949e..000000000 --- a/plugins/postcss-custom-properties/dist/cascade-layers.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -import type { Node, Root } from 'postcss'; -export declare function collectCascadeLayerOrder(root: Root): WeakMap; -export declare function cascadeLayerNumberForNode(node: Node, layers: WeakMap): number; diff --git a/plugins/postcss-custom-properties/dist/get-custom-properties-from-root.d.ts b/plugins/postcss-custom-properties/dist/get-custom-properties-from-root.d.ts deleted file mode 100644 index 5a9c1547f..000000000 --- a/plugins/postcss-custom-properties/dist/get-custom-properties-from-root.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -import type { Root } from 'postcss'; -import valuesParser from 'postcss-value-parser'; -export default function getCustomPropertiesFromRoot(root: Root, parsedValuesCache: Map): Map; diff --git a/plugins/postcss-custom-properties/dist/has-supports-at-rule-ancestor.d.ts b/plugins/postcss-custom-properties/dist/has-supports-at-rule-ancestor.d.ts deleted file mode 100644 index a46009ecc..000000000 --- a/plugins/postcss-custom-properties/dist/has-supports-at-rule-ancestor.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import type { Node } from 'postcss'; -export declare function hasSupportsAtRuleAncestor(node: Node): boolean; diff --git a/plugins/postcss-custom-properties/dist/index.cjs b/plugins/postcss-custom-properties/dist/index.cjs index 5f0a23c57..24b50e03f 100644 --- a/plugins/postcss-custom-properties/dist/index.cjs +++ b/plugins/postcss-custom-properties/dist/index.cjs @@ -1 +1 @@ -"use strict";var e=require("postcss-value-parser"),r=require("@csstools/cascade-layer-name-parser");const t=r.parse("csstools-implicit-layer")[0];function collectCascadeLayerOrder(e){const n=new Map,o=new Map,s=[];e.walkAtRules((e=>{var a;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 l;if(e.nodes)l=normalizeLayerName(e.params,1);else{if(!e.params.trim())return;l=e.params}let i=r.parse(l);if(null!=(a=i)&&a.length){{let r=e.parent;for(;r&&"atrule"===r.type&&"layer"===r.name.toLowerCase();){const e=o.get(r);e?(i=i.map((r=>e.concat(r))),r=r.parent):r=r.parent}}if(r.addLayerToModel(s,i),e.nodes){const r=i[0].concat(t);n.set(e,r),o.set(e,i[0])}}}));for(const e of n.values())r.addLayerToModel(s,[e]);const a=new WeakMap;for(const[e,r]of n)a.set(e,s.findIndex((e=>r.equal(e))));return a}function normalizeLayerName(e,r){return e.trim()?e:"csstools-anon-layer--"+r++}const n=/(!\s*)?postcss-custom-properties:\s*off\b/i,o=new WeakMap;function isBlockIgnored(e){if(!e||!e.nodes)return!1;if(o.has(e))return o.get(e);const r=e.some((e=>isIgnoreComment(e,n)));return o.set(e,r),r}const s=/(!\s*)?postcss-custom-properties:\s*ignore\s+next\b/i;function isDeclarationIgnored(e){return!!e&&(!!isBlockIgnored(e.parent)||isIgnoreComment(e.prev(),s))}function isIgnoreComment(e,r){return!!e&&"comment"===e.type&&r.test(e.text)}const a=new Set(["layer"]);function isProcessableRule(e){let r=e.parent;for(;r;){if("atrule"===r.type&&!a.has(r.name.toLowerCase()))return!1;r=r.parent}return!0}const l=/^html$/i,i=/^:where\(html\)$/i,c=/^:root$/i,u=/^:where\(:root\)$/i,p=/(html|:root)/i,d=/^var$/i;function isVarFunction(e){return"function"===e.type&&d.test(e.value)&&Object(e.nodes).length>0}const f=/var\(/i;function removeCyclicReferences(e,r){const t=new Set;let n=r;for(;e.size>0;)try{toposort(Array.from(e.keys()),n);break}catch(r){if(!r._graphNode)throw r;e.delete(r._graphNode),t.add(r._graphNode),n=n.filter((e=>-1===e.indexOf(r._graphNode)))}return t}function toposort(e,r){let t=e.length;const n=new Array(t),o={};let s=t;const a=makeOutgoingEdges(r),l=makeNodesHash(e);for(;s--;)o[s]||visit(e[s],s,new Set);return n;function visit(e,r,s){if(s.has(e)){const r=new Error("Cyclic dependency"+JSON.stringify(e));throw r._graphNode=e,r}if(!l.has(e))return;if(o[r])return;o[r]=!0;let i=a.get(e)||new Set;if(i=Array.from(i),r=i.length){s.add(e);do{const e=i[--r];visit(e,l.get(e),s)}while(r);s.delete(e)}n[--t]=e}}function makeOutgoingEdges(e){const r=new Map;for(let t=0,n=e.length;t{var r;p.test(e.selector)&&null!=(r=e.nodes)&&r.length&&isProcessableRule(e)&&(isBlockIgnored(e)||e.selectors.forEach((r=>{let t=-1;if(i.test(r)||u.test(r))t=0;else if(l.test(r))t=1;else{if(!c.test(r))return;t=2}const a=(d=s,((p=e).parent&&"atrule"===p.parent.type&&"layer"===p.parent.name.toLowerCase()?d.has(p.parent)?d.get(p.parent)+1:0:1e7)+10+t);var p,d;e.each((e=>{if("decl"!==e.type)return;if(!e.variable||isDeclarationIgnored(e))return;if("initial"===e.value.toLowerCase().trim())return;const r=o.get(e.prop)??-1;a>=r&&(o.set(e.prop,a),n.set(e.prop,e.value))}))})))}));const a=[],d=new Map;for(const[r,o]of n.entries()){const n=parseOrCached(o,t);e.walk(n.nodes,(e=>{if(isVarFunction(e)){const[t]=e.nodes.filter((e=>"word"===e.type));a.push([t.value,r])}})),d.set(r,n)}return removeCyclicReferences(d,a),d}function transformValueAST(r,t,n){var o;if(null==(o=r.nodes)||!o.length)return"";const s=new Map;return r.nodes.forEach((e=>{s.set(e,r)})),e.walk(r.nodes,(e=>{"nodes"in e&&e.nodes.length&&e.nodes.forEach((r=>{s.set(r,e)}))})),e.walk(r.nodes,(r=>{var o,a;if(!isVarFunction(r))return;const[l,...i]=r.nodes.filter((e=>"div"!==e.type)),{value:c}=l,u=s.get(r);if(!u)return;const p=u.nodes.indexOf(r);if(-1===p)return;let d=!1;i&&e.walk(i,(e=>{if(isVarFunction(e)){const[r]=e.nodes.filter((e=>"word"===e.type));if(t.has(r.value)||n.has(r.value))return;return d=!0,!1}}));let f=(null==(o=n.get(c))?void 0:o.nodes)??(null==(a=t.get(c))?void 0:a.nodes);f||!i.length||d||(f=r.nodes.slice(r.nodes.indexOf(i[0]))),void 0!==f&&(f.length?(u.nodes.splice(p,1,...f),u.nodes.forEach((e=>s.set(e,u)))):(u.nodes.splice(p,1,{type:"comment",value:"",sourceIndex:r.sourceIndex,sourceEndIndex:r.sourceEndIndex}),u.nodes.forEach((e=>s.set(e,u)))))}),!0),e.stringify(r.nodes)}function transformProperties(r,t,n,o,s){if(isTransformableDecl(r)&&!isDeclarationIgnored(r)){const o=r.value;let i=transformValueAST(e(o),t,n);const c=new Set;for(;f.test(i)&&!c.has(i);){c.add(i);i=transformValueAST(e(i),t,n)}if(i!==o){if(parentHasExactFallback(r,i))return void(s.preserve||r.remove());if(s.preserve){var a;const e=r.cloneBefore({value:i});hasTrailingComment(e)&&null!=(a=e.raws)&&a.value&&(e.raws.value.value=e.value.replace(v,"$1"),e.raws.value.raw=e.raws.value.value+e.raws.value.raw.replace(v,"$2"))}else{var l;r.value=i,hasTrailingComment(r)&&null!=(l=r.raws)&&l.value&&(r.raws.value.value=r.value.replace(v,"$1"),r.raws.value.raw=r.raws.value.value+r.raws.value.raw.replace(v,"$2"))}}}}const isTransformableDecl=e=>!e.variable&&e.value.includes("--")&&e.value.toLowerCase().includes("var("),hasTrailingComment=e=>{var r,t;return"value"in Object(Object(e.raws).value)&&"raw"in((null==(r=e.raws)?void 0:r.value)??{})&&v.test((null==(t=e.raws.value)?void 0:t.raw)??"")},v=/^([\W\w]+)(\s*\/\*[\W\w]+?\*\/)$/;function parentHasExactFallback(e,r){if(!e||!e.parent)return!1;let t=!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===r&&(t=!0))))),t}function hasSupportsAtRuleAncestor(e){let r=e.parent;for(;r;)if("atrule"===r.type){if("supports"===r.name.toLowerCase()&&/([^\w]var\()|(\(top: var\(--f\))/i.test(r.params))return!0;r=r.parent}else r=r.parent;return!1}const w=/^initial$/i,creator=e=>{const r=!("preserve"in Object(e))||Boolean(null==e?void 0: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 t=new Map;return{Once:r=>{e=getCustomPropertiesFromRoot(r,t)},Declaration:n=>{if(!f.test(n.value))return;if(hasSupportsAtRuleAncestor(n))return;const o=new Map;r&&n.parent&&n.parent.each((e=>{"decl"===e.type&&e.variable&&n!==e&&(isDeclarationIgnored(e)||(w.test(e.value)?o.delete(e.prop):o.set(e.prop,parseOrCached(e.value,t))))})),transformProperties(n,e,o,0,{preserve:r})}}}}};creator.postcss=!0,module.exports=creator; +"use strict";var e=require("postcss-value-parser"),t=require("@csstools/cascade-layer-name-parser");const r=t.parse("csstools-implicit-layer")[0];function collectCascadeLayerOrder(e){const n=new Map,o=new Map,s=[];e.walkAtRules((e=>{if("layer"!==e.name.toLowerCase())return;{let t=e.parent;for(;t;){if("atrule"!==t.type||"layer"!==t.name.toLowerCase()){if(t===e.root())break;return}t=t.parent}}let a;if(e.nodes)a=normalizeLayerName(e.params,1);else{if(!e.params.trim())return;a=e.params}let i=t.parse(a);if(i?.length){{let t=e.parent;for(;t&&"atrule"===t.type&&"layer"===t.name.toLowerCase();){const e=o.get(t);e?(i=i.map((t=>e.concat(t))),t=t.parent):t=t.parent}}if(t.addLayerToModel(s,i),e.nodes){const t=i[0].concat(r);n.set(e,t),o.set(e,i[0])}}}));for(const e of n.values())t.addLayerToModel(s,[e]);const a=new WeakMap;for(const[e,t]of n)a.set(e,s.findIndex((e=>t.equal(e))));return a}function normalizeLayerName(e,t){return e.trim()?e:"csstools-anon-layer--"+t++}const n=/(!\s*)?postcss-custom-properties:\s*off\b/i,o=new WeakMap;function isBlockIgnored(e){if(!e||!e.nodes)return!1;if(o.has(e))return o.get(e);const t=e.some((e=>isIgnoreComment(e,n)));return o.set(e,t),t}const s=/(!\s*)?postcss-custom-properties:\s*ignore\s+next\b/i;function isDeclarationIgnored(e){return!!e&&(!!isBlockIgnored(e.parent)||isIgnoreComment(e.prev(),s))}function isIgnoreComment(e,t){return!!e&&"comment"===e.type&&t.test(e.text)}const a=new Set(["layer"]);function isProcessableRule(e){let t=e.parent;for(;t;){if("atrule"===t.type&&!a.has(t.name.toLowerCase()))return!1;t=t.parent}return!0}const i=/^html$/i,l=/^:where\(html\)$/i,c=/^:root$/i,u=/^:where\(:root\)$/i,p=/(html|:root)/i,f=/^var$/i;function isVarFunction(e){return"function"===e.type&&f.test(e.value)&&Object(e.nodes).length>0}const d=/var\(/i;function removeCyclicReferences(e,t){const r=new Set;let n=t;for(;e.size>0;)try{toposort(Array.from(e.keys()),n);break}catch(t){if(!t._graphNode)throw t;e.delete(t._graphNode),r.add(t._graphNode),n=n.filter((e=>-1===e.indexOf(t._graphNode)))}return r}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)){const t=new Error("Cyclic dependency"+JSON.stringify(e));throw t._graphNode=e,t}if(!i.has(e))return;if(o[t])return;o[t]=!0;let l=a.get(e)||new Set;if(l=Array.from(l),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 makeOutgoingEdges(e){const t=new Map;for(let r=0,n=e.length;r{p.test(e.selector)&&e.nodes?.length&&isProcessableRule(e)&&(isBlockIgnored(e)||e.selectors.forEach((t=>{let r=-1;if(l.test(t)||u.test(t))r=0;else if(i.test(t))r=1;else{if(!c.test(t))return;r=2}const a=(f=s,((p=e).parent&&"atrule"===p.parent.type&&"layer"===p.parent.name.toLowerCase()?f.has(p.parent)?f.get(p.parent)+1:0:1e7)+10+r);var p,f;e.each((e=>{if("decl"!==e.type)return;if(!e.variable||isDeclarationIgnored(e))return;if("initial"===e.value.toLowerCase().trim())return;const t=o.get(e.prop)??-1;a>=t&&(o.set(e.prop,a),n.set(e.prop,e.value))}))})))}));const a=[],f=new Map;for(const[t,o]of n.entries()){const n=parseOrCached(o,r);e.walk(n.nodes,(e=>{if(isVarFunction(e)){const[r]=e.nodes.filter((e=>"word"===e.type));a.push([r.value,t])}})),f.set(t,n)}return removeCyclicReferences(f,a),f}function transformValueAST(t,r,n){if(!t.nodes?.length)return"";const o=new Map;return t.nodes.forEach((e=>{o.set(e,t)})),e.walk(t.nodes,(e=>{"nodes"in e&&e.nodes.length&&e.nodes.forEach((t=>{o.set(t,e)}))})),e.walk(t.nodes,(t=>{if(!isVarFunction(t))return;const[s,...a]=t.nodes.filter((e=>"div"!==e.type)),{value:i}=s,l=o.get(t);if(!l)return;const c=l.nodes.indexOf(t);if(-1===c)return;let u=!1;a&&e.walk(a,(e=>{if(isVarFunction(e)){const[t]=e.nodes.filter((e=>"word"===e.type));if(r.has(t.value)||n.has(t.value))return;return u=!0,!1}}));let p=n.get(i)?.nodes??r.get(i)?.nodes;p||!a.length||u||(p=t.nodes.slice(t.nodes.indexOf(a[0]))),void 0!==p&&(p.length?(l.nodes.splice(c,1,...p),l.nodes.forEach((e=>o.set(e,l)))):(l.nodes.splice(c,1,{type:"comment",value:"",sourceIndex:t.sourceIndex,sourceEndIndex:t.sourceEndIndex}),l.nodes.forEach((e=>o.set(e,l)))))}),!0),e.stringify(t.nodes)}function transformProperties(t,r,n,o,s){if(isTransformableDecl(t)&&!isDeclarationIgnored(t)){const o=t.value;let a=transformValueAST(e(o),r,n);const i=new Set;for(;d.test(a)&&!i.has(a);){i.add(a);a=transformValueAST(e(a),r,n)}if(a!==o){if(parentHasExactFallback(t,a))return void(s.preserve||t.remove());if(s.preserve){const e=t.cloneBefore({value:a});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"))}else t.value=a,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"))}}}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}function hasSupportsAtRuleAncestor(e){let t=e.parent;for(;t;)if("atrule"===t.type){if("supports"===t.name.toLowerCase()&&/([^\w]var\()|(\(top: var\(--f\))/i.test(t.params))return!0;t=t.parent}else t=t.parent;return!1}const v=/^initial$/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 Map;return{Once:t=>{e=getCustomPropertiesFromRoot(t,r)},Declaration:n=>{if(!d.test(n.value))return;if(hasSupportsAtRuleAncestor(n))return;const o=new Map;t&&n.parent&&n.parent.each((e=>{"decl"===e.type&&e.variable&&n!==e&&(isDeclarationIgnored(e)||(v.test(e.value)?o.delete(e.prop):o.set(e.prop,parseOrCached(e.value,r))))})),transformProperties(n,e,o,0,{preserve:t})}}}}};creator.postcss=!0,module.exports=creator; diff --git a/plugins/postcss-custom-properties/dist/index.d.ts b/plugins/postcss-custom-properties/dist/index.d.ts index beebd186f..7e2b993e2 100644 --- a/plugins/postcss-custom-properties/dist/index.d.ts +++ b/plugins/postcss-custom-properties/dist/index.d.ts @@ -1,8 +1,12 @@ import type { PluginCreator } from 'postcss'; + +declare const creator: PluginCreator; +export default creator; + /** postcss-custom-properties plugin options */ -export type pluginOptions = { +export declare type pluginOptions = { /** Preserve the original notation. default: true */ preserve?: boolean; }; -declare const creator: PluginCreator; -export default creator; + +export { } diff --git a/plugins/postcss-custom-properties/dist/index.mjs b/plugins/postcss-custom-properties/dist/index.mjs index 6b5101538..a82df6d4e 100644 --- a/plugins/postcss-custom-properties/dist/index.mjs +++ b/plugins/postcss-custom-properties/dist/index.mjs @@ -1 +1 @@ -import e from"postcss-value-parser";import{parse as t,addLayerToModel as r}from"@csstools/cascade-layer-name-parser";const n=t("csstools-implicit-layer")[0];function collectCascadeLayerOrder(e){const o=new Map,s=new Map,a=[];e.walkAtRules((e=>{var l;if("layer"!==e.name.toLowerCase())return;{let t=e.parent;for(;t;){if("atrule"!==t.type||"layer"!==t.name.toLowerCase()){if(t===e.root())break;return}t=t.parent}}let i;if(e.nodes)i=normalizeLayerName(e.params,1);else{if(!e.params.trim())return;i=e.params}let c=t(i);if(null!=(l=c)&&l.length){{let t=e.parent;for(;t&&"atrule"===t.type&&"layer"===t.name.toLowerCase();){const e=s.get(t);e?(c=c.map((t=>e.concat(t))),t=t.parent):t=t.parent}}if(r(a,c),e.nodes){const t=c[0].concat(n);o.set(e,t),s.set(e,c[0])}}}));for(const e of o.values())r(a,[e]);const l=new WeakMap;for(const[e,t]of o)l.set(e,a.findIndex((e=>t.equal(e))));return l}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 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 i=/^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 v=/var\(/i;function removeCyclicReferences(e,t){const r=new Set;let n=t;for(;e.size>0;)try{toposort(Array.from(e.keys()),n);break}catch(t){if(!t._graphNode)throw t;e.delete(t._graphNode),r.add(t._graphNode),n=n.filter((e=>-1===e.indexOf(t._graphNode)))}return r}function toposort(e,t){let r=e.length;const n=new Array(r),o={};let s=r;const a=makeOutgoingEdges(t),l=makeNodesHash(e);for(;s--;)o[s]||visit(e[s],s,new Set);return n;function visit(e,t,s){if(s.has(e)){const t=new Error("Cyclic dependency"+JSON.stringify(e));throw t._graphNode=e,t}if(!l.has(e))return;if(o[t])return;o[t]=!0;let i=a.get(e)||new Set;if(i=Array.from(i),t=i.length){s.add(e);do{const e=i[--t];visit(e,l.get(e),s)}while(t);s.delete(e)}n[--r]=e}}function makeOutgoingEdges(e){const t=new Map;for(let r=0,n=e.length;r{var t;f.test(e.selector)&&null!=(t=e.nodes)&&t.length&&isProcessableRule(e)&&(isBlockIgnored(e)||e.selectors.forEach((t=>{let r=-1;if(c.test(t)||p.test(t))r=0;else if(i.test(t))r=1;else{if(!u.test(t))return;r=2}const a=(f=s,((l=e).parent&&"atrule"===l.parent.type&&"layer"===l.parent.name.toLowerCase()?f.has(l.parent)?f.get(l.parent)+1:0:1e7)+10+r);var l,f;e.each((e=>{if("decl"!==e.type)return;if(!e.variable||isDeclarationIgnored(e))return;if("initial"===e.value.toLowerCase().trim())return;const t=o.get(e.prop)??-1;a>=t&&(o.set(e.prop,a),n.set(e.prop,e.value))}))})))}));const a=[],l=new Map;for(const[t,o]of n.entries()){const n=parseOrCached(o,r);e.walk(n.nodes,(e=>{if(isVarFunction(e)){const[r]=e.nodes.filter((e=>"word"===e.type));a.push([r.value,t])}})),l.set(t,n)}return removeCyclicReferences(l,a),l}function transformValueAST(t,r,n){var o;if(null==(o=t.nodes)||!o.length)return"";const s=new Map;return t.nodes.forEach((e=>{s.set(e,t)})),e.walk(t.nodes,(e=>{"nodes"in e&&e.nodes.length&&e.nodes.forEach((t=>{s.set(t,e)}))})),e.walk(t.nodes,(t=>{var o,a;if(!isVarFunction(t))return;const[l,...i]=t.nodes.filter((e=>"div"!==e.type)),{value:c}=l,u=s.get(t);if(!u)return;const p=u.nodes.indexOf(t);if(-1===p)return;let f=!1;i&&e.walk(i,(e=>{if(isVarFunction(e)){const[t]=e.nodes.filter((e=>"word"===e.type));if(r.has(t.value)||n.has(t.value))return;return f=!0,!1}}));let d=(null==(o=n.get(c))?void 0:o.nodes)??(null==(a=r.get(c))?void 0:a.nodes);d||!i.length||f||(d=t.nodes.slice(t.nodes.indexOf(i[0]))),void 0!==d&&(d.length?(u.nodes.splice(p,1,...d),u.nodes.forEach((e=>s.set(e,u)))):(u.nodes.splice(p,1,{type:"comment",value:"",sourceIndex:t.sourceIndex,sourceEndIndex:t.sourceEndIndex}),u.nodes.forEach((e=>s.set(e,u)))))}),!0),e.stringify(t.nodes)}function transformProperties(t,r,n,o,s){if(isTransformableDecl(t)&&!isDeclarationIgnored(t)){const o=t.value;let i=transformValueAST(e(o),r,n);const c=new Set;for(;v.test(i)&&!c.has(i);){c.add(i);i=transformValueAST(e(i),r,n)}if(i!==o){if(parentHasExactFallback(t,i))return void(s.preserve||t.remove());if(s.preserve){var a;const e=t.cloneBefore({value:i});hasTrailingComment(e)&&null!=(a=e.raws)&&a.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"))}else{var l;t.value=i,hasTrailingComment(t)&&null!=(l=t.raws)&&l.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"))}}}}const isTransformableDecl=e=>!e.variable&&e.value.includes("--")&&e.value.toLowerCase().includes("var("),hasTrailingComment=e=>{var t,r;return"value"in Object(Object(e.raws).value)&&"raw"in((null==(t=e.raws)?void 0:t.value)??{})&&w.test((null==(r=e.raws.value)?void 0:r.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}function hasSupportsAtRuleAncestor(e){let t=e.parent;for(;t;)if("atrule"===t.type){if("supports"===t.name.toLowerCase()&&/([^\w]var\()|(\(top: var\(--f\))/i.test(t.params))return!0;t=t.parent}else t=t.parent;return!1}const m=/^initial$/i,creator=e=>{const t=!("preserve"in Object(e))||Boolean(null==e?void 0: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 Map;return{Once:t=>{e=getCustomPropertiesFromRoot(t,r)},Declaration:n=>{if(!v.test(n.value))return;if(hasSupportsAtRuleAncestor(n))return;const o=new Map;t&&n.parent&&n.parent.each((e=>{"decl"===e.type&&e.variable&&n!==e&&(isDeclarationIgnored(e)||(m.test(e.value)?o.delete(e.prop):o.set(e.prop,parseOrCached(e.value,r))))})),transformProperties(n,e,o,0,{preserve:t})}}}}};creator.postcss=!0;export{creator as default}; +import e from"postcss-value-parser";import{parse as t,addLayerToModel as r}from"@csstools/cascade-layer-name-parser";const n=t("csstools-implicit-layer")[0];function collectCascadeLayerOrder(e){const o=new Map,s=new Map,a=[];e.walkAtRules((e=>{if("layer"!==e.name.toLowerCase())return;{let t=e.parent;for(;t;){if("atrule"!==t.type||"layer"!==t.name.toLowerCase()){if(t===e.root())break;return}t=t.parent}}let i;if(e.nodes)i=normalizeLayerName(e.params,1);else{if(!e.params.trim())return;i=e.params}let l=t(i);if(l?.length){{let t=e.parent;for(;t&&"atrule"===t.type&&"layer"===t.name.toLowerCase();){const e=s.get(t);e?(l=l.map((t=>e.concat(t))),t=t.parent):t=t.parent}}if(r(a,l),e.nodes){const t=l[0].concat(n);o.set(e,t),s.set(e,l[0])}}}));for(const e of o.values())r(a,[e]);const i=new WeakMap;for(const[e,t]of o)i.set(e,a.findIndex((e=>t.equal(e))));return i}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 w=/var\(/i;function removeCyclicReferences(e,t){const r=new Set;let n=t;for(;e.size>0;)try{toposort(Array.from(e.keys()),n);break}catch(t){if(!t._graphNode)throw t;e.delete(t._graphNode),r.add(t._graphNode),n=n.filter((e=>-1===e.indexOf(t._graphNode)))}return r}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)){const t=new Error("Cyclic dependency"+JSON.stringify(e));throw t._graphNode=e,t}if(!i.has(e))return;if(o[t])return;o[t]=!0;let l=a.get(e)||new Set;if(l=Array.from(l),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 makeOutgoingEdges(e){const t=new Map;for(let r=0,n=e.length;r{f.test(e.selector)&&e.nodes?.length&&isProcessableRule(e)&&(isBlockIgnored(e)||e.selectors.forEach((t=>{let r=-1;if(c.test(t)||p.test(t))r=0;else if(l.test(t))r=1;else{if(!u.test(t))return;r=2}const a=(f=s,((i=e).parent&&"atrule"===i.parent.type&&"layer"===i.parent.name.toLowerCase()?f.has(i.parent)?f.get(i.parent)+1:0:1e7)+10+r);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=o.get(e.prop)??-1;a>=t&&(o.set(e.prop,a),n.set(e.prop,e.value))}))})))}));const a=[],i=new Map;for(const[t,o]of n.entries()){const n=parseOrCached(o,r);e.walk(n.nodes,(e=>{if(isVarFunction(e)){const[r]=e.nodes.filter((e=>"word"===e.type));a.push([r.value,t])}})),i.set(t,n)}return removeCyclicReferences(i,a),i}function transformValueAST(t,r,n){if(!t.nodes?.length)return"";const o=new Map;return t.nodes.forEach((e=>{o.set(e,t)})),e.walk(t.nodes,(e=>{"nodes"in e&&e.nodes.length&&e.nodes.forEach((t=>{o.set(t,e)}))})),e.walk(t.nodes,(t=>{if(!isVarFunction(t))return;const[s,...a]=t.nodes.filter((e=>"div"!==e.type)),{value:i}=s,l=o.get(t);if(!l)return;const c=l.nodes.indexOf(t);if(-1===c)return;let u=!1;a&&e.walk(a,(e=>{if(isVarFunction(e)){const[t]=e.nodes.filter((e=>"word"===e.type));if(r.has(t.value)||n.has(t.value))return;return u=!0,!1}}));let p=n.get(i)?.nodes??r.get(i)?.nodes;p||!a.length||u||(p=t.nodes.slice(t.nodes.indexOf(a[0]))),void 0!==p&&(p.length?(l.nodes.splice(c,1,...p),l.nodes.forEach((e=>o.set(e,l)))):(l.nodes.splice(c,1,{type:"comment",value:"",sourceIndex:t.sourceIndex,sourceEndIndex:t.sourceEndIndex}),l.nodes.forEach((e=>o.set(e,l)))))}),!0),e.stringify(t.nodes)}function transformProperties(t,r,n,o,s){if(isTransformableDecl(t)&&!isDeclarationIgnored(t)){const o=t.value;let a=transformValueAST(e(o),r,n);const i=new Set;for(;w.test(a)&&!i.has(a);){i.add(a);a=transformValueAST(e(a),r,n)}if(a!==o){if(parentHasExactFallback(t,a))return void(s.preserve||t.remove());if(s.preserve){const e=t.cloneBefore({value:a});hasTrailingComment(e)&&e.raws?.value&&(e.raws.value.value=e.value.replace(m,"$1"),e.raws.value.raw=e.raws.value.value+e.raws.value.raw.replace(m,"$2"))}else t.value=a,hasTrailingComment(t)&&t.raws?.value&&(t.raws.value.value=t.value.replace(m,"$1"),t.raws.value.raw=t.raws.value.value+t.raws.value.raw.replace(m,"$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??{})&&m.test(e.raws.value?.raw??""),m=/^([\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}function hasSupportsAtRuleAncestor(e){let t=e.parent;for(;t;)if("atrule"===t.type){if("supports"===t.name.toLowerCase()&&/([^\w]var\()|(\(top: var\(--f\))/i.test(t.params))return!0;t=t.parent}else t=t.parent;return!1}const v=/^initial$/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 Map;return{Once:t=>{e=getCustomPropertiesFromRoot(t,r)},Declaration:n=>{if(!w.test(n.value))return;if(hasSupportsAtRuleAncestor(n))return;const o=new Map;t&&n.parent&&n.parent.each((e=>{"decl"===e.type&&e.variable&&n!==e&&(isDeclarationIgnored(e)||(v.test(e.value)?o.delete(e.prop):o.set(e.prop,parseOrCached(e.value,r))))})),transformProperties(n,e,o,0,{preserve:t})}}}}};creator.postcss=!0;export{creator as default}; diff --git a/plugins/postcss-custom-properties/dist/is-ignored.d.ts b/plugins/postcss-custom-properties/dist/is-ignored.d.ts deleted file mode 100644 index 336cbebf9..000000000 --- a/plugins/postcss-custom-properties/dist/is-ignored.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -import type { Container, Declaration } from 'postcss'; -export declare function isBlockIgnored(container: Container | undefined): any; -export declare function isDeclarationIgnored(decl: Declaration | undefined): boolean; diff --git a/plugins/postcss-custom-properties/dist/is-processable-rule.d.ts b/plugins/postcss-custom-properties/dist/is-processable-rule.d.ts deleted file mode 100644 index 235ba67ed..000000000 --- a/plugins/postcss-custom-properties/dist/is-processable-rule.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -import type { Rule } from 'postcss'; -export declare function isProcessableRule(rule: Rule): boolean; -export declare const HTML_SELECTOR_REGEXP: RegExp; -export declare const HTML_WHERE_SELECTOR_REGEXP: RegExp; -export declare const ROOT_SELECTOR_REGEXP: RegExp; -export declare const ROOT_WHERE_SELECTOR_REGEXP: RegExp; -export declare const MAYBE_HTML_OR_ROOT_RULE_REGEXP: RegExp; diff --git a/plugins/postcss-custom-properties/dist/is-var-function.d.ts b/plugins/postcss-custom-properties/dist/is-var-function.d.ts deleted file mode 100644 index dd9ad6cc5..000000000 --- a/plugins/postcss-custom-properties/dist/is-var-function.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -import type { FunctionNode, Node } from 'postcss-value-parser'; -export declare function isVarFunction(node: Node): node is FunctionNode; -export declare const HAS_VAR_FUNCTION: RegExp; diff --git a/plugins/postcss-custom-properties/dist/parse-or-cached.d.ts b/plugins/postcss-custom-properties/dist/parse-or-cached.d.ts deleted file mode 100644 index c96e7b6c8..000000000 --- a/plugins/postcss-custom-properties/dist/parse-or-cached.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import valuesParser from 'postcss-value-parser'; -export declare function parseOrCached(value: string, parsedValuesCache: Map): valuesParser.ParsedValue; diff --git a/plugins/postcss-custom-properties/dist/toposort.d.ts b/plugins/postcss-custom-properties/dist/toposort.d.ts deleted file mode 100644 index ffb196fdd..000000000 --- a/plugins/postcss-custom-properties/dist/toposort.d.ts +++ /dev/null @@ -1 +0,0 @@ -export declare function removeCyclicReferences(nodes: Map, edges: Array>): Set; diff --git a/plugins/postcss-custom-properties/dist/transform-properties.d.ts b/plugins/postcss-custom-properties/dist/transform-properties.d.ts deleted file mode 100644 index da417cbd8..000000000 --- a/plugins/postcss-custom-properties/dist/transform-properties.d.ts +++ /dev/null @@ -1,5 +0,0 @@ -import valuesParser from 'postcss-value-parser'; -import type { Declaration } from 'postcss'; -export declare function transformProperties(decl: Declaration, customProperties: Map, localCustomProperties: Map, parsedValuesCache: Map, opts: { - preserve?: boolean; -}): void; diff --git a/plugins/postcss-custom-properties/dist/transform-value-ast.d.ts b/plugins/postcss-custom-properties/dist/transform-value-ast.d.ts deleted file mode 100644 index 91a52d186..000000000 --- a/plugins/postcss-custom-properties/dist/transform-value-ast.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import valuesParser from 'postcss-value-parser'; -export default function transformValueAST(root: valuesParser.ParsedValue, customProperties: Map, localCustomProperties: Map): string; diff --git a/plugins/postcss-custom-properties/package.json b/plugins/postcss-custom-properties/package.json index 99bd789b5..23c8074fb 100644 --- a/plugins/postcss-custom-properties/package.json +++ b/plugins/postcss-custom-properties/package.json @@ -20,15 +20,18 @@ "engines": { "node": "^14 || ^16 || >=18" }, + "type": "module", "main": "dist/index.cjs", "module": "dist/index.mjs", - "types": "dist/index.d.ts", "exports": { ".": { - "types": "./dist/index.d.ts", - "import": "./dist/index.mjs", - "require": "./dist/index.cjs", - "default": "./dist/index.mjs" + "import": { + "types": "./dist/index.d.ts", + "default": "./dist/index.mjs" + }, + "require": { + "default": "./dist/index.cjs" + } } }, "files": [ diff --git a/plugins/postcss-custom-selectors/CHANGELOG.md b/plugins/postcss-custom-selectors/CHANGELOG.md index b0b5e12bc..1646ec639 100644 --- a/plugins/postcss-custom-selectors/CHANGELOG.md +++ b/plugins/postcss-custom-selectors/CHANGELOG.md @@ -2,7 +2,7 @@ ### Unreleased (patch) -- Small fixes in type definitions +- Fix type definitions ### 7.1.6 diff --git a/plugins/postcss-custom-selectors/api-extractor.json b/plugins/postcss-custom-selectors/api-extractor.json new file mode 100644 index 000000000..42058be51 --- /dev/null +++ b/plugins/postcss-custom-selectors/api-extractor.json @@ -0,0 +1,4 @@ +{ + "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json", + "extends": "../../api-extractor.json" +} diff --git a/plugins/postcss-custom-selectors/dist/cascade-layers.d.ts b/plugins/postcss-custom-selectors/dist/cascade-layers.d.ts deleted file mode 100644 index b9891949e..000000000 --- a/plugins/postcss-custom-selectors/dist/cascade-layers.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -import type { Node, Root } from 'postcss'; -export declare function collectCascadeLayerOrder(root: Root): WeakMap; -export declare function cascadeLayerNumberForNode(node: Node, layers: WeakMap): number; diff --git a/plugins/postcss-custom-selectors/dist/custom-selectors-from-root.d.ts b/plugins/postcss-custom-selectors/dist/custom-selectors-from-root.d.ts deleted file mode 100644 index 346923e8f..000000000 --- a/plugins/postcss-custom-selectors/dist/custom-selectors-from-root.d.ts +++ /dev/null @@ -1,5 +0,0 @@ -import type { Result, Root as PostCSSRoot } from 'postcss'; -import type { Root as SelectorRoot } from 'postcss-selector-parser'; -export default function getCustomSelectors(root: PostCSSRoot, result: Result, opts: { - preserve?: boolean; -}): Map; diff --git a/plugins/postcss-custom-selectors/dist/index.cjs b/plugins/postcss-custom-selectors/dist/index.cjs index 083fe8c9c..6f5bacb0a 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=>{var a;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 l;if(e.nodes)l=normalizeLayerName(e.params,1);else{if(!e.params.trim())return;l=e.params}let c=r.parse(l);if(null!=(a=c)&&a.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 l,c;if(isProcessableCustomSelectorRule(r))try{var u;const t=r.params.trim(),p=e().astSync(t),i=null==p||null==(u=p.nodes)||null==(u=u[0])||null==(u=u.nodes)?void 0:u[0];if(!i||"pseudo"!==i.type||!i.value.startsWith(":--"))return;const m=i.toString(),f=(c=a,(l=r).parent&&"atrule"===l.parent.type&&"layer"===l.parent.name.toLowerCase()?c.has(l.parent)?c.get(l.parent)+1:0:1e7),d=n.get(m)??-1;if(f&&f>=d&&(n.set(m,f),o.set(m,e().astSync(t.slice(m.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{Once:(e,{result:s})=>{t=getCustomSelectors(e,s,{preserve:r})},Rule:(s,{result:o})=>{var n;if(e.has(s))return;if(null==(n=s.selector)||!n.includes(":--"))return;const a=transformRule(s,o,t);a!==s.selector&&(e.add(s),s.cloneBefore({selector:a}),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=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{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.d.ts b/plugins/postcss-custom-selectors/dist/index.d.ts index aa450f622..d745e5f7a 100644 --- a/plugins/postcss-custom-selectors/dist/index.d.ts +++ b/plugins/postcss-custom-selectors/dist/index.d.ts @@ -1,8 +1,12 @@ import type { PluginCreator } from 'postcss'; + +declare const creator: PluginCreator; +export default creator; + /** postcss-custom-selectors plugin options */ -export type pluginOptions = { +export declare type pluginOptions = { /** Preserve the original notation. default: false */ preserve?: boolean; }; -declare const creator: PluginCreator; -export default creator; + +export { } diff --git a/plugins/postcss-custom-selectors/dist/index.mjs b/plugins/postcss-custom-selectors/dist/index.mjs index 9e3ae4af9..963d91c8d 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=>{var l;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 u=r(c);if(null!=(l=u)&&l.length){{let r=e.parent;for(;r&&"atrule"===r.type&&"layer"===r.name.toLowerCase();){const e=n.get(r);e?(u=u.map((r=>e.concat(r))),r=r.parent):r=r.parent}}if(t(a,u),e.nodes){const r=u[0].concat(s);o.set(e,r),n.set(e,u[0])}}}));for(const e of o.values())t(a,[e]);const l=new WeakMap;for(const[e,r]of o)l.set(e,a.findIndex((e=>r.equal(e))));return l}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 l,c;if(isProcessableCustomSelectorRule(r))try{var u;const t=r.params.trim(),p=e().astSync(t),i=null==p||null==(u=p.nodes)||null==(u=u[0])||null==(u=u.nodes)?void 0:u[0];if(!i||"pseudo"!==i.type||!i.value.startsWith(":--"))return;const m=i.toString(),f=(c=a,(l=r).parent&&"atrule"===l.parent.type&&"layer"===l.parent.name.toLowerCase()?c.has(l.parent)?c.get(l.parent)+1:0:1e7),d=n.get(m)??-1;if(f&&f>=d&&(n.set(m,f),o.set(m,e().astSync(t.slice(m.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{Once:(e,{result:s})=>{t=getCustomSelectors(e,s,{preserve:r})},Rule:(s,{result:o})=>{var n;if(e.has(s))return;if(null==(n=s.selector)||!n.includes(":--"))return;const a=transformRule(s,o,t);a!==s.selector&&(e.add(s),s.cloneBefore({selector:a}),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=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{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/dist/is-processable-custom-selector-rule.d.ts b/plugins/postcss-custom-selectors/dist/is-processable-custom-selector-rule.d.ts deleted file mode 100644 index 2dd82837f..000000000 --- a/plugins/postcss-custom-selectors/dist/is-processable-custom-selector-rule.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import type { AtRule } from 'postcss'; -export declare function isProcessableCustomSelectorRule(atRule: AtRule): boolean; diff --git a/plugins/postcss-custom-selectors/dist/transform-rule.d.ts b/plugins/postcss-custom-selectors/dist/transform-rule.d.ts deleted file mode 100644 index deec52461..000000000 --- a/plugins/postcss-custom-selectors/dist/transform-rule.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -import type { Result, Rule } from 'postcss'; -import type { Root } from 'postcss-selector-parser'; -export declare function transformRule(rule: Rule, result: Result, customSelectors: Map): string; diff --git a/plugins/postcss-custom-selectors/package.json b/plugins/postcss-custom-selectors/package.json index 8bd7d7732..3024b1de2 100644 --- a/plugins/postcss-custom-selectors/package.json +++ b/plugins/postcss-custom-selectors/package.json @@ -37,15 +37,18 @@ "engines": { "node": "^14 || ^16 || >=18" }, + "type": "module", "main": "dist/index.cjs", "module": "dist/index.mjs", - "types": "dist/index.d.ts", "exports": { ".": { - "types": "./dist/index.d.ts", - "import": "./dist/index.mjs", - "require": "./dist/index.cjs", - "default": "./dist/index.mjs" + "import": { + "types": "./dist/index.d.ts", + "default": "./dist/index.mjs" + }, + "require": { + "default": "./dist/index.cjs" + } } }, "files": [ diff --git a/plugins/postcss-debug-logger/CHANGELOG.md b/plugins/postcss-debug-logger/CHANGELOG.md index 8f4065049..c8817becb 100644 --- a/plugins/postcss-debug-logger/CHANGELOG.md +++ b/plugins/postcss-debug-logger/CHANGELOG.md @@ -1,5 +1,9 @@ # Changes to PostCSS Debug Logger +### Unreleased (patch) + +- Fix type definitions + ### 2.0.0 _July 3, 2023_ diff --git a/plugins/postcss-debug-logger/api-extractor.json b/plugins/postcss-debug-logger/api-extractor.json new file mode 100644 index 000000000..42058be51 --- /dev/null +++ b/plugins/postcss-debug-logger/api-extractor.json @@ -0,0 +1,4 @@ +{ + "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json", + "extends": "../../api-extractor.json" +} diff --git a/plugins/postcss-debug-logger/dist/index.cjs b/plugins/postcss-debug-logger/dist/index.cjs index 249389523..184cdc937 100644 --- a/plugins/postcss-debug-logger/dist/index.cjs +++ b/plugins/postcss-debug-logger/dist/index.cjs @@ -1 +1 @@ -"use strict";var n=require("path");const creator=()=>{const onceHandler=e=>o=>{var l,t,i;let r=null==(l=o.source)||null==(l=l.input)?void 0:l.from;r&&(r=n.relative(process.cwd(),r));let u="";u+=e,u+=`\n index : ${(null==(t=o.parent)?void 0:t.index(o))??"N/A"}`,u+=`\n nodes : ${null==(i=o.nodes)?void 0:i.length}`,u+=`\n input.from : ${r??"N/A"}`,console.log(u+"\n")},documentHandler=e=>o=>{var l,t;let i=null==(l=o.source)||null==(l=l.input)?void 0:l.from;i&&(i=n.relative(process.cwd(),i));let r="";r+=e,r+=`\n nodes : ${null==(t=o.nodes)?void 0:t.length}`,r+=`\n input.from : ${i??"N/A"}`,console.log(r+"\n")},atRuleHandler=e=>o=>{var l,t,i;let r=null==(l=o.source)||null==(l=l.input)?void 0:l.from;r&&(r=n.relative(process.cwd(),r));let u="";u+=e,u+=`\n name : ${o.name}`,u+=`\n params : ${o.params}`,u+=`\n index : ${(null==(t=o.parent)?void 0:t.index(o))??"N/A"}`,u+=`\n nodes : ${null==(i=o.nodes)?void 0:i.length}`,u+=`\n raw : ${JSON.stringify(o.raws)}`,u+=`\n input.from : ${r??"N/A"}`,console.log(u+"\n")},ruleHandler=e=>o=>{var l,t,i;let r=null==(l=o.source)||null==(l=l.input)?void 0:l.from;r&&(r=n.relative(process.cwd(),r));let u="";u+=e,u+=`\n selector : ${o.selector}`,u+=`\n index : ${(null==(t=o.parent)?void 0:t.index(o))??"N/A"}`,u+=`\n nodes : ${null==(i=o.nodes)?void 0:i.length}`,u+=`\n raw : ${JSON.stringify(o.raws)}`,u+=`\n input.from : ${r??"N/A"}`,console.log(u+"\n")},commentHandler=e=>o=>{var l,t;let i=null==(l=o.source)||null==(l=l.input)?void 0:l.from;i&&(i=n.relative(process.cwd(),i));let r="";r+=e,r+=`\n text : ${o.text}`,r+=`\n index : ${(null==(t=o.parent)?void 0:t.index(o))??"N/A"}`,r+=`\n raw : ${JSON.stringify(o.raws)}`,r+=`\n input.from : ${i??"N/A"}`,console.log(r+"\n")},declHandler=e=>o=>{var l,t;let i=null==(l=o.source)||null==(l=l.input)?void 0:l.from;i&&(i=n.relative(process.cwd(),i));let r="";r+=e,r+=`\n prop : ${o.prop}`,r+=`\n value : ${o.value}`,r+=`\n index : ${(null==(t=o.parent)?void 0:t.index(o))??"N/A"}`,r+=`\n raw : ${JSON.stringify(o.raws)}`,r+=`\n input.from : ${i??"N/A"}`,console.log(r+"\n")};return{postcssPlugin:"postcss-debug-logger",AtRule:atRuleHandler("AtRule"),AtRuleExit:atRuleHandler("AtRuleExit"),Comment:commentHandler("Comment"),CommentExit:commentHandler("CommentExit"),Declaration:declHandler("Declaration"),DeclarationExit:declHandler("DeclarationExit"),Document:documentHandler("Document"),DocumentExit:documentHandler("DocumentExit"),Once:onceHandler("Once"),OnceExit:onceHandler("OnceExit"),Root:onceHandler("Root"),RootExit:onceHandler("RootExit"),Rule:ruleHandler("Rule"),RuleExit:ruleHandler("RuleExit")}};creator.postcss=!0,module.exports=creator; +"use strict";var e=require("path");const creator=()=>{const onceHandler=n=>t=>{let o=t.source?.input?.from;o&&(o=e.relative(process.cwd(),o));let r="";r+=n,r+=`\n index : ${t.parent?.index(t)??"N/A"}`,r+=`\n nodes : ${t.nodes?.length}`,r+=`\n input.from : ${o??"N/A"}`,console.log(r+"\n")},documentHandler=n=>t=>{let o=t.source?.input?.from;o&&(o=e.relative(process.cwd(),o));let r="";r+=n,r+=`\n nodes : ${t.nodes?.length}`,r+=`\n input.from : ${o??"N/A"}`,console.log(r+"\n")},atRuleHandler=n=>t=>{let o=t.source?.input?.from;o&&(o=e.relative(process.cwd(),o));let r="";r+=n,r+=`\n name : ${t.name}`,r+=`\n params : ${t.params}`,r+=`\n index : ${t.parent?.index(t)??"N/A"}`,r+=`\n nodes : ${t.nodes?.length}`,r+=`\n raw : ${JSON.stringify(t.raws)}`,r+=`\n input.from : ${o??"N/A"}`,console.log(r+"\n")},ruleHandler=n=>t=>{let o=t.source?.input?.from;o&&(o=e.relative(process.cwd(),o));let r="";r+=n,r+=`\n selector : ${t.selector}`,r+=`\n index : ${t.parent?.index(t)??"N/A"}`,r+=`\n nodes : ${t.nodes?.length}`,r+=`\n raw : ${JSON.stringify(t.raws)}`,r+=`\n input.from : ${o??"N/A"}`,console.log(r+"\n")},commentHandler=n=>t=>{let o=t.source?.input?.from;o&&(o=e.relative(process.cwd(),o));let r="";r+=n,r+=`\n text : ${t.text}`,r+=`\n index : ${t.parent?.index(t)??"N/A"}`,r+=`\n raw : ${JSON.stringify(t.raws)}`,r+=`\n input.from : ${o??"N/A"}`,console.log(r+"\n")},declHandler=n=>t=>{let o=t.source?.input?.from;o&&(o=e.relative(process.cwd(),o));let r="";r+=n,r+=`\n prop : ${t.prop}`,r+=`\n value : ${t.value}`,r+=`\n index : ${t.parent?.index(t)??"N/A"}`,r+=`\n raw : ${JSON.stringify(t.raws)}`,r+=`\n input.from : ${o??"N/A"}`,console.log(r+"\n")};return{postcssPlugin:"postcss-debug-logger",AtRule:atRuleHandler("AtRule"),AtRuleExit:atRuleHandler("AtRuleExit"),Comment:commentHandler("Comment"),CommentExit:commentHandler("CommentExit"),Declaration:declHandler("Declaration"),DeclarationExit:declHandler("DeclarationExit"),Document:documentHandler("Document"),DocumentExit:documentHandler("DocumentExit"),Once:onceHandler("Once"),OnceExit:onceHandler("OnceExit"),Root:onceHandler("Root"),RootExit:onceHandler("RootExit"),Rule:ruleHandler("Rule"),RuleExit:ruleHandler("RuleExit")}};creator.postcss=!0,module.exports=creator; diff --git a/plugins/postcss-debug-logger/dist/index.d.ts b/plugins/postcss-debug-logger/dist/index.d.ts index 89d75c8fd..73f8cdb79 100644 --- a/plugins/postcss-debug-logger/dist/index.d.ts +++ b/plugins/postcss-debug-logger/dist/index.d.ts @@ -1,3 +1,6 @@ import type { PluginCreator } from 'postcss'; + declare const creator: PluginCreator; export default creator; + +export { } diff --git a/plugins/postcss-debug-logger/dist/index.mjs b/plugins/postcss-debug-logger/dist/index.mjs index 2dc9f32c8..c1eb1b985 100644 --- a/plugins/postcss-debug-logger/dist/index.mjs +++ b/plugins/postcss-debug-logger/dist/index.mjs @@ -1 +1 @@ -import n from"path";const creator=()=>{const onceHandler=e=>o=>{var l,t,i;let r=null==(l=o.source)||null==(l=l.input)?void 0:l.from;r&&(r=n.relative(process.cwd(),r));let u="";u+=e,u+=`\n index : ${(null==(t=o.parent)?void 0:t.index(o))??"N/A"}`,u+=`\n nodes : ${null==(i=o.nodes)?void 0:i.length}`,u+=`\n input.from : ${r??"N/A"}`,console.log(u+"\n")},documentHandler=e=>o=>{var l,t;let i=null==(l=o.source)||null==(l=l.input)?void 0:l.from;i&&(i=n.relative(process.cwd(),i));let r="";r+=e,r+=`\n nodes : ${null==(t=o.nodes)?void 0:t.length}`,r+=`\n input.from : ${i??"N/A"}`,console.log(r+"\n")},atRuleHandler=e=>o=>{var l,t,i;let r=null==(l=o.source)||null==(l=l.input)?void 0:l.from;r&&(r=n.relative(process.cwd(),r));let u="";u+=e,u+=`\n name : ${o.name}`,u+=`\n params : ${o.params}`,u+=`\n index : ${(null==(t=o.parent)?void 0:t.index(o))??"N/A"}`,u+=`\n nodes : ${null==(i=o.nodes)?void 0:i.length}`,u+=`\n raw : ${JSON.stringify(o.raws)}`,u+=`\n input.from : ${r??"N/A"}`,console.log(u+"\n")},ruleHandler=e=>o=>{var l,t,i;let r=null==(l=o.source)||null==(l=l.input)?void 0:l.from;r&&(r=n.relative(process.cwd(),r));let u="";u+=e,u+=`\n selector : ${o.selector}`,u+=`\n index : ${(null==(t=o.parent)?void 0:t.index(o))??"N/A"}`,u+=`\n nodes : ${null==(i=o.nodes)?void 0:i.length}`,u+=`\n raw : ${JSON.stringify(o.raws)}`,u+=`\n input.from : ${r??"N/A"}`,console.log(u+"\n")},commentHandler=e=>o=>{var l,t;let i=null==(l=o.source)||null==(l=l.input)?void 0:l.from;i&&(i=n.relative(process.cwd(),i));let r="";r+=e,r+=`\n text : ${o.text}`,r+=`\n index : ${(null==(t=o.parent)?void 0:t.index(o))??"N/A"}`,r+=`\n raw : ${JSON.stringify(o.raws)}`,r+=`\n input.from : ${i??"N/A"}`,console.log(r+"\n")},declHandler=e=>o=>{var l,t;let i=null==(l=o.source)||null==(l=l.input)?void 0:l.from;i&&(i=n.relative(process.cwd(),i));let r="";r+=e,r+=`\n prop : ${o.prop}`,r+=`\n value : ${o.value}`,r+=`\n index : ${(null==(t=o.parent)?void 0:t.index(o))??"N/A"}`,r+=`\n raw : ${JSON.stringify(o.raws)}`,r+=`\n input.from : ${i??"N/A"}`,console.log(r+"\n")};return{postcssPlugin:"postcss-debug-logger",AtRule:atRuleHandler("AtRule"),AtRuleExit:atRuleHandler("AtRuleExit"),Comment:commentHandler("Comment"),CommentExit:commentHandler("CommentExit"),Declaration:declHandler("Declaration"),DeclarationExit:declHandler("DeclarationExit"),Document:documentHandler("Document"),DocumentExit:documentHandler("DocumentExit"),Once:onceHandler("Once"),OnceExit:onceHandler("OnceExit"),Root:onceHandler("Root"),RootExit:onceHandler("RootExit"),Rule:ruleHandler("Rule"),RuleExit:ruleHandler("RuleExit")}};creator.postcss=!0;export{creator as default}; +import e from"path";const creator=()=>{const onceHandler=n=>t=>{let o=t.source?.input?.from;o&&(o=e.relative(process.cwd(),o));let r="";r+=n,r+=`\n index : ${t.parent?.index(t)??"N/A"}`,r+=`\n nodes : ${t.nodes?.length}`,r+=`\n input.from : ${o??"N/A"}`,console.log(r+"\n")},documentHandler=n=>t=>{let o=t.source?.input?.from;o&&(o=e.relative(process.cwd(),o));let r="";r+=n,r+=`\n nodes : ${t.nodes?.length}`,r+=`\n input.from : ${o??"N/A"}`,console.log(r+"\n")},atRuleHandler=n=>t=>{let o=t.source?.input?.from;o&&(o=e.relative(process.cwd(),o));let r="";r+=n,r+=`\n name : ${t.name}`,r+=`\n params : ${t.params}`,r+=`\n index : ${t.parent?.index(t)??"N/A"}`,r+=`\n nodes : ${t.nodes?.length}`,r+=`\n raw : ${JSON.stringify(t.raws)}`,r+=`\n input.from : ${o??"N/A"}`,console.log(r+"\n")},ruleHandler=n=>t=>{let o=t.source?.input?.from;o&&(o=e.relative(process.cwd(),o));let r="";r+=n,r+=`\n selector : ${t.selector}`,r+=`\n index : ${t.parent?.index(t)??"N/A"}`,r+=`\n nodes : ${t.nodes?.length}`,r+=`\n raw : ${JSON.stringify(t.raws)}`,r+=`\n input.from : ${o??"N/A"}`,console.log(r+"\n")},commentHandler=n=>t=>{let o=t.source?.input?.from;o&&(o=e.relative(process.cwd(),o));let r="";r+=n,r+=`\n text : ${t.text}`,r+=`\n index : ${t.parent?.index(t)??"N/A"}`,r+=`\n raw : ${JSON.stringify(t.raws)}`,r+=`\n input.from : ${o??"N/A"}`,console.log(r+"\n")},declHandler=n=>t=>{let o=t.source?.input?.from;o&&(o=e.relative(process.cwd(),o));let r="";r+=n,r+=`\n prop : ${t.prop}`,r+=`\n value : ${t.value}`,r+=`\n index : ${t.parent?.index(t)??"N/A"}`,r+=`\n raw : ${JSON.stringify(t.raws)}`,r+=`\n input.from : ${o??"N/A"}`,console.log(r+"\n")};return{postcssPlugin:"postcss-debug-logger",AtRule:atRuleHandler("AtRule"),AtRuleExit:atRuleHandler("AtRuleExit"),Comment:commentHandler("Comment"),CommentExit:commentHandler("CommentExit"),Declaration:declHandler("Declaration"),DeclarationExit:declHandler("DeclarationExit"),Document:documentHandler("Document"),DocumentExit:documentHandler("DocumentExit"),Once:onceHandler("Once"),OnceExit:onceHandler("OnceExit"),Root:onceHandler("Root"),RootExit:onceHandler("RootExit"),Rule:ruleHandler("Rule"),RuleExit:ruleHandler("RuleExit")}};creator.postcss=!0;export{creator as default}; diff --git a/plugins/postcss-debug-logger/package.json b/plugins/postcss-debug-logger/package.json index 788645ff0..e682d356a 100644 --- a/plugins/postcss-debug-logger/package.json +++ b/plugins/postcss-debug-logger/package.json @@ -27,15 +27,18 @@ "engines": { "node": "^14 || ^16 || >=18" }, + "type": "module", "main": "dist/index.cjs", "module": "dist/index.mjs", - "types": "dist/index.d.ts", "exports": { ".": { - "types": "./dist/index.d.ts", - "import": "./dist/index.mjs", - "require": "./dist/index.cjs", - "default": "./dist/index.mjs" + "import": { + "types": "./dist/index.d.ts", + "default": "./dist/index.mjs" + }, + "require": { + "default": "./dist/index.cjs" + } } }, "files": [ diff --git a/plugins/postcss-design-tokens/CHANGELOG.md b/plugins/postcss-design-tokens/CHANGELOG.md index 337c5da03..b5879f6e7 100644 --- a/plugins/postcss-design-tokens/CHANGELOG.md +++ b/plugins/postcss-design-tokens/CHANGELOG.md @@ -2,7 +2,7 @@ ### Unreleased (patch) -- Small fixes in type definitions +- Fix type definitions ### 3.1.1 diff --git a/plugins/postcss-design-tokens/api-extractor.json b/plugins/postcss-design-tokens/api-extractor.json new file mode 100644 index 000000000..42058be51 --- /dev/null +++ b/plugins/postcss-design-tokens/api-extractor.json @@ -0,0 +1,4 @@ +{ + "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json", + "extends": "../../api-extractor.json" +} diff --git a/plugins/postcss-design-tokens/dist/constants.d.ts b/plugins/postcss-design-tokens/dist/constants.d.ts deleted file mode 100644 index 9f2732385..000000000 --- a/plugins/postcss-design-tokens/dist/constants.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -export declare const DEFAULT_CONDITION = "6b4e71e7-4787-42f7-a092-8684961895db"; -export declare const DEFAULT_VALUE_FUNCTION_NAME = "design-token"; -export declare const DEFAULT_IMPORT_AT_RULE_NAME = "design-tokens"; diff --git a/plugins/postcss-design-tokens/dist/data-formats/base/token.d.ts b/plugins/postcss-design-tokens/dist/data-formats/base/token.d.ts deleted file mode 100644 index b5d8b4f80..000000000 --- a/plugins/postcss-design-tokens/dist/data-formats/base/token.d.ts +++ /dev/null @@ -1,9 +0,0 @@ -export interface TokenTransformOptions { - pluginOptions: { - rootFontSize: number; - }; - toUnit?: string; -} -export interface Token { - cssValue(opts?: TokenTransformOptions): string; -} diff --git a/plugins/postcss-design-tokens/dist/data-formats/parse-import.d.ts b/plugins/postcss-design-tokens/dist/data-formats/parse-import.d.ts deleted file mode 100644 index 8f15f9703..000000000 --- a/plugins/postcss-design-tokens/dist/data-formats/parse-import.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { Token } from './base/token'; -import type { Helpers, Root } from 'postcss'; -export declare function tokensFromImport(root: Root, postcssHelpers: Helpers, buildIs: Array, sourceFilePath: string, statement: string, alreadyImported: Set): Promise<{ - filePath: string; - tokens: Map; -} | false>; diff --git a/plugins/postcss-design-tokens/dist/data-formats/style-dictionary/style-dictionary.d.ts b/plugins/postcss-design-tokens/dist/data-formats/style-dictionary/style-dictionary.d.ts deleted file mode 100644 index d4192cec2..000000000 --- a/plugins/postcss-design-tokens/dist/data-formats/style-dictionary/style-dictionary.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import { Token } from '../base/token'; -export declare function extractStyleDictionaryTokens(version: string, node: unknown, filePath: string): Map; diff --git a/plugins/postcss-design-tokens/dist/data-formats/style-dictionary/v3/dereference.d.ts b/plugins/postcss-design-tokens/dist/data-formats/style-dictionary/v3/dereference.d.ts deleted file mode 100644 index b933a9478..000000000 --- a/plugins/postcss-design-tokens/dist/data-formats/style-dictionary/v3/dereference.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import { StyleDictionaryV3TokenValue } from './value'; -export declare function dereferenceTokenValues(tokens: Map): Map; diff --git a/plugins/postcss-design-tokens/dist/data-formats/style-dictionary/v3/group.d.ts b/plugins/postcss-design-tokens/dist/data-formats/style-dictionary/v3/group.d.ts deleted file mode 100644 index fbaf531d7..000000000 --- a/plugins/postcss-design-tokens/dist/data-formats/style-dictionary/v3/group.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { Token } from '../../base/token'; -import { StyleDictionaryV3TokenValue } from './value'; -export type StyleDictionaryV3TokenGroup = { - [key: string]: StyleDictionaryV3TokenGroup | StyleDictionaryV3TokenValue; -}; -export declare function extractStyleDictionaryV3Tokens(node: StyleDictionaryV3TokenGroup, filePath: string): Map; diff --git a/plugins/postcss-design-tokens/dist/data-formats/style-dictionary/v3/value.d.ts b/plugins/postcss-design-tokens/dist/data-formats/style-dictionary/v3/value.d.ts deleted file mode 100644 index 2987abbd4..000000000 --- a/plugins/postcss-design-tokens/dist/data-formats/style-dictionary/v3/value.d.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { TokenTransformOptions } from '../../base/token'; -export type StyleDictionaryV3TokenValue = { - cssValue(transformOptions?: TokenTransformOptions): string; - value: unknown; - name?: string; - comment?: string; - themeable?: boolean; - attributes?: unknown; - metadata?: { - name?: string; - path: Array; - filePath: string; - isSource: boolean; - }; -}; -export declare function extractStyleDictionaryV3Token(node: Record, key: string, path: Array, filePath: string): StyleDictionaryV3TokenValue; -export declare function applyTransformsToValue(value: string | undefined | null, transformOptions?: TokenTransformOptions): string; diff --git a/plugins/postcss-design-tokens/dist/data-formats/token.d.ts b/plugins/postcss-design-tokens/dist/data-formats/token.d.ts deleted file mode 100644 index a25aec2a3..000000000 --- a/plugins/postcss-design-tokens/dist/data-formats/token.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import { Token } from './base/token'; -export declare function mergeTokens(a: Map, b: Map): Map; diff --git a/plugins/postcss-design-tokens/dist/data-formats/toposort/toposort.d.ts b/plugins/postcss-design-tokens/dist/data-formats/toposort/toposort.d.ts deleted file mode 100644 index 4d843c2f8..000000000 --- a/plugins/postcss-design-tokens/dist/data-formats/toposort/toposort.d.ts +++ /dev/null @@ -1 +0,0 @@ -export declare function toposort(nodes: Array, edges: Array>): Array; diff --git a/plugins/postcss-design-tokens/dist/index.cjs b/plugins/postcss-design-tokens/dist/index.cjs index 9536ab166..a3e6f9091 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;let u=a.get(e)||new Set;if(u=Array.from(u),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}"`)}var o,s;return"rem"===r.unit&&"px"===n.toUnit?remToPx(parseFloat(r.number),(null==(o=n.pluginOptions)?void 0:o.rootFontSize)??16):"px"===r.unit&&"rem"===n.toUnit?pxToRem(parseFloat(r.number),(null==(s=n.pluginOptions)?void 0:s.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){if("3"===e)return extractStyleDictionaryV3Tokens(t,n);throw new Error("Unsupported version: "+e)}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){var l;const{filePath:c,format:f,conditions:p}=parseImport(i);if(!p.every((e=>s.includes(e))))return!1;let d="";try{if(c.startsWith("node_modules://")){d=r.createRequire(t.dirname(a)).resolve(c.slice(15))}else if(c.startsWith("node_modules:")){d=r.createRequire(t.dirname(a)).resolve(c.slice(13))}else d=t.resolve(t.dirname(a),c)}catch(e){throw new Error(`Failed to read ${c} with error ${e instanceof Error?e.message:e}`)}if(u.has(d))return!1;o.result.messages.push({type:"dependency",plugin:"postcss-design-tokens",file:d,parent:null==(l=e.source)||null==(l=l.input)?void 0:l.file}),u.add(d);const m=await n.promises.readFile(d,"utf8"),w=JSON.parse(m);if("style-dictionary3"===f)return{filePath:t.resolve(c),tokens:extractStyleDictionaryTokens("3",w,d)};throw new Error("Unsupported format: "+f)}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{OnceExit(){e=new Map,n=new Set},Once:async(r,o)=>{const s=[];r.walkAtRules((e=>{var n;if(e.name.toLowerCase()!==t.importAtRuleName)return;if(null==e||null==(n=e.source)||null==(n=n.input)||!n.file)return;const r=e.source.input.file,o=e.params;e.remove(),s.push({filePath:r,params:o,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(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;let u=a.get(e)||new Set;if(u=Array.from(u),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){if("3"===e)return extractStyleDictionaryV3Tokens(t,n);throw new Error("Unsupported version: "+e)}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("3",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{OnceExit(){e=new Map,n=new Set},Once:async(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; diff --git a/plugins/postcss-design-tokens/dist/index.d.ts b/plugins/postcss-design-tokens/dist/index.d.ts index e009762a9..4042d30de 100644 --- a/plugins/postcss-design-tokens/dist/index.d.ts +++ b/plugins/postcss-design-tokens/dist/index.d.ts @@ -1,4 +1,15 @@ import type { PluginCreator } from 'postcss'; -import { pluginOptions } from './options'; + declare const creator: PluginCreator; export default creator; + +export declare type pluginOptions = { + importAtRuleName: string; + is?: Array; + unitsAndValues?: { + rootFontSize?: number; + }; + valueFunctionName: string; +}; + +export { } diff --git a/plugins/postcss-design-tokens/dist/index.mjs b/plugins/postcss-design-tokens/dist/index.mjs index 01fb881a1..66f63a9a7 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,TokenType as c}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;let u=a.get(e)||new Set;if(u=Array.from(u),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 f=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(f.has(n.toUnit)){if(f.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 f.set(n.toUnit,!0),`${t}${n.toUnit}`;f.set(n.toUnit,!1)}catch(e){f.set(n.toUnit,!1)}throw new Error(`Invalid unit "${n.toUnit}" for "${t}"`)}var o,s;return"rem"===r.unit&&"px"===n.toUnit?remToPx(parseFloat(r.number),(null==(o=n.pluginOptions)?void 0:o.rootFontSize)??16):"px"===r.unit&&"rem"===n.toUnit?pxToRem(parseFloat(r.number),(null==(s=n.pluginOptions)?void 0:s.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){if("3"===e)return extractStyleDictionaryV3Tokens(t,n);throw new Error("Unsupported version: "+e)}const p="6b4e71e7-4787-42f7-a092-8684961895db";function parseImport(t){const n=e(t),r={filePath:"",format:"standard",conditions:[p]};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=[p]),r}async function tokensFromImport(e,o,s,a,i,u){var l;const{filePath:c,format:f,conditions:p}=parseImport(i);if(!p.every((e=>s.includes(e))))return!1;let m="";try{if(c.startsWith("node_modules://")){m=r.createRequire(t.dirname(a)).resolve(c.slice(15))}else if(c.startsWith("node_modules:")){m=r.createRequire(t.dirname(a)).resolve(c.slice(13))}else m=t.resolve(t.dirname(a),c)}catch(e){throw new Error(`Failed to read ${c} with error ${e instanceof Error?e.message:e}`)}if(u.has(m))return!1;o.result.messages.push({type:"dependency",plugin:"postcss-design-tokens",file:m,parent:null==(l=e.source)||null==(l=l.input)?void 0:l.file}),u.add(m);const d=await n.readFile(m,"utf8"),w=JSON.parse(d);if("style-dictionary3"===f)return{filePath:t.resolve(c),tokens:extractStyleDictionaryTokens("3",w,m)};throw new Error("Unsupported format: "+f)}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:[p],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=[p]),"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="",f="",p="";for(let t=0;t{const t=parsePluginOptions(e);return{postcssPlugin:"postcss-design-tokens",prepare(){let e=new Map,n=new Set;return{OnceExit(){e=new Map,n=new Set},Once:async(r,o)=>{const s=[];r.walkAtRules((e=>{var n;if(e.name.toLowerCase()!==t.importAtRuleName)return;if(null==e||null==(n=e.source)||null==(n=n.input)||!n.file)return;const r=e.source.input.file,o=e.params;e.remove(),s.push({filePath:r,params:o,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,TokenType as c}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;let u=a.get(e)||new Set;if(u=Array.from(u),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 f=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(f.has(n.toUnit)){if(f.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 f.set(n.toUnit,!0),`${t}${n.toUnit}`;f.set(n.toUnit,!1)}catch(e){f.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){if("3"===e)return extractStyleDictionaryV3Tokens(t,n);throw new Error("Unsupported version: "+e)}const p="6b4e71e7-4787-42f7-a092-8684961895db";function parseImport(t){const n=e(t),r={filePath:"",format:"standard",conditions:[p]};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=[p]),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("3",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:[p],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=[p]),"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="",f="",p="";for(let t=0;t{const t=parsePluginOptions(e);return{postcssPlugin:"postcss-design-tokens",prepare(){let e=new Map,n=new Set;return{OnceExit(){e=new Map,n=new Set},Once:async(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}; diff --git a/plugins/postcss-design-tokens/dist/options.d.ts b/plugins/postcss-design-tokens/dist/options.d.ts deleted file mode 100644 index 8bdd0477a..000000000 --- a/plugins/postcss-design-tokens/dist/options.d.ts +++ /dev/null @@ -1,17 +0,0 @@ -export type pluginOptions = { - importAtRuleName: string; - is?: Array; - unitsAndValues?: { - rootFontSize?: number; - }; - valueFunctionName: string; -}; -export type parsedPluginOptions = { - importAtRuleName: string; - is: Array; - unitsAndValues: { - rootFontSize: number; - }; - valueFunctionName: string; -}; -export declare function parsePluginOptions(opts?: pluginOptions): parsedPluginOptions; diff --git a/plugins/postcss-design-tokens/dist/parse-component-values.d.ts b/plugins/postcss-design-tokens/dist/parse-component-values.d.ts deleted file mode 100644 index 9f19381c9..000000000 --- a/plugins/postcss-design-tokens/dist/parse-component-values.d.ts +++ /dev/null @@ -1 +0,0 @@ -export declare function parseComponentValues(source: string): import("@csstools/css-parser-algorithms").ComponentValue[]; diff --git a/plugins/postcss-design-tokens/dist/transform.d.ts b/plugins/postcss-design-tokens/dist/transform.d.ts deleted file mode 100644 index 341f554d1..000000000 --- a/plugins/postcss-design-tokens/dist/transform.d.ts +++ /dev/null @@ -1,4 +0,0 @@ -import type { Node, Result } from 'postcss'; -import { Token } from './data-formats/base/token'; -import { parsedPluginOptions } from './options'; -export declare function transform(tokens: Map, result: Result, postCSSNode: Node, source: string, opts: parsedPluginOptions): string; diff --git a/plugins/postcss-design-tokens/package.json b/plugins/postcss-design-tokens/package.json index 2730b899c..1ba71fb1a 100644 --- a/plugins/postcss-design-tokens/package.json +++ b/plugins/postcss-design-tokens/package.json @@ -27,15 +27,18 @@ "engines": { "node": "^14 || ^16 || >=18" }, + "type": "module", "main": "dist/index.cjs", "module": "dist/index.mjs", - "types": "dist/index.d.ts", "exports": { ".": { - "types": "./dist/index.d.ts", - "import": "./dist/index.mjs", - "require": "./dist/index.cjs", - "default": "./dist/index.mjs" + "import": { + "types": "./dist/index.d.ts", + "default": "./dist/index.mjs" + }, + "require": { + "default": "./dist/index.cjs" + } } }, "files": [ diff --git a/plugins/postcss-design-tokens/src/index.ts b/plugins/postcss-design-tokens/src/index.ts index e177264e1..40d74de3b 100644 --- a/plugins/postcss-design-tokens/src/index.ts +++ b/plugins/postcss-design-tokens/src/index.ts @@ -3,6 +3,7 @@ import { Token } from './data-formats/base/token'; import { tokensFromImport } from './data-formats/parse-import'; import { mergeTokens } from './data-formats/token'; import { parsePluginOptions, pluginOptions } from './options'; +export type { pluginOptions } from './options'; import { transform } from './transform'; const creator: PluginCreator = (opts?: pluginOptions) => { diff --git a/plugins/postcss-dir-pseudo-class/CHANGELOG.md b/plugins/postcss-dir-pseudo-class/CHANGELOG.md index 293b311ca..48a3c7035 100644 --- a/plugins/postcss-dir-pseudo-class/CHANGELOG.md +++ b/plugins/postcss-dir-pseudo-class/CHANGELOG.md @@ -2,7 +2,7 @@ ### Unreleased (patch) -- Small fixes in type definitions +- Fix type definitions ### 8.0.0 diff --git a/plugins/postcss-dir-pseudo-class/api-extractor.json b/plugins/postcss-dir-pseudo-class/api-extractor.json new file mode 100644 index 000000000..42058be51 --- /dev/null +++ b/plugins/postcss-dir-pseudo-class/api-extractor.json @@ -0,0 +1,4 @@ +{ + "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json", + "extends": "../../api-extractor.json" +} diff --git a/plugins/postcss-dir-pseudo-class/dist/index.d.ts b/plugins/postcss-dir-pseudo-class/dist/index.d.ts index 8e6f1148b..bcfe2c60d 100644 --- a/plugins/postcss-dir-pseudo-class/dist/index.d.ts +++ b/plugins/postcss-dir-pseudo-class/dist/index.d.ts @@ -1,6 +1,10 @@ import type { PluginCreator } from 'postcss'; + +declare const creator: PluginCreator; +export default creator; + /** postcss-dir-pseudo-class plugin options */ -export type pluginOptions = { +export declare type pluginOptions = { /** Preserve the original notation. default: true */ preserve?: boolean; /** Assume a direction for the document. default: null */ @@ -8,5 +12,5 @@ export type pluginOptions = { /** Assume that the CSS is intended to be used in Shadow DOM with Custom Elements. default: false */ shadow?: boolean; }; -declare const creator: PluginCreator; -export default creator; + +export { } diff --git a/plugins/postcss-dir-pseudo-class/package.json b/plugins/postcss-dir-pseudo-class/package.json index 8abca57e0..0d7e1617f 100644 --- a/plugins/postcss-dir-pseudo-class/package.json +++ b/plugins/postcss-dir-pseudo-class/package.json @@ -31,15 +31,18 @@ "engines": { "node": "^14 || ^16 || >=18" }, + "type": "module", "main": "dist/index.cjs", "module": "dist/index.mjs", - "types": "dist/index.d.ts", "exports": { ".": { - "types": "./dist/index.d.ts", - "import": "./dist/index.mjs", - "require": "./dist/index.cjs", - "default": "./dist/index.mjs" + "import": { + "types": "./dist/index.d.ts", + "default": "./dist/index.mjs" + }, + "require": { + "default": "./dist/index.cjs" + } } }, "files": [ diff --git a/plugins/postcss-dir-pseudo-class/src/index.ts b/plugins/postcss-dir-pseudo-class/src/index.ts index be26fb661..c73f0bf3f 100644 --- a/plugins/postcss-dir-pseudo-class/src/index.ts +++ b/plugins/postcss-dir-pseudo-class/src/index.ts @@ -114,6 +114,7 @@ const creator: PluginCreator = (opts?: pluginOptions) => { if (first && !firstIsHtml && !firstIsRoot && !firstIsSpaceCombinator) { parent.prepend( + // @ts-expect-error https://github.com/postcss/postcss-selector-parser/pull/284 selectorParser.combinator({ value: ' ', }), @@ -170,6 +171,7 @@ const creator: PluginCreator = (opts?: pluginOptions) => { parent.insertAfter(first, notDirAttr); } else { // prepend :root + // @ts-expect-error https://github.com/postcss/postcss-selector-parser/pull/284 parent.prepend(notDirAttr); } } else if (firstIsHtml) { @@ -177,9 +179,11 @@ const creator: PluginCreator = (opts?: pluginOptions) => { parent.insertAfter(first, dirAttr); } else if (options.shadow && !firstIsRoot) { // prepend :host-context([dir]) + // @ts-expect-error https://github.com/postcss/postcss-selector-parser/pull/284 parent.prepend(hostContextPseudo); } else { // otherwise, prepend the dir attribute + // @ts-expect-error https://github.com/postcss/postcss-selector-parser/pull/284 parent.prepend(dirAttr); } }); diff --git a/plugins/postcss-double-position-gradients/CHANGELOG.md b/plugins/postcss-double-position-gradients/CHANGELOG.md index 0d6567e76..5fa80b898 100644 --- a/plugins/postcss-double-position-gradients/CHANGELOG.md +++ b/plugins/postcss-double-position-gradients/CHANGELOG.md @@ -1,5 +1,9 @@ # Changes to PostCSS Double Position Gradients +### Unreleased (patch) + +- Fix type definitions + ### 5.0.2 _October 9, 2023_ diff --git a/plugins/postcss-double-position-gradients/api-extractor.json b/plugins/postcss-double-position-gradients/api-extractor.json new file mode 100644 index 000000000..42058be51 --- /dev/null +++ b/plugins/postcss-double-position-gradients/api-extractor.json @@ -0,0 +1,4 @@ +{ + "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json", + "extends": "../../api-extractor.json" +} diff --git a/plugins/postcss-double-position-gradients/dist/has-fallback-decl.d.ts b/plugins/postcss-double-position-gradients/dist/has-fallback-decl.d.ts deleted file mode 100644 index d7ae8d890..000000000 --- a/plugins/postcss-double-position-gradients/dist/has-fallback-decl.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import type { Declaration } from 'postcss'; -export declare function hasFallback(node: Declaration): boolean; diff --git a/plugins/postcss-double-position-gradients/dist/has-supports-at-rule-ancestor.d.ts b/plugins/postcss-double-position-gradients/dist/has-supports-at-rule-ancestor.d.ts deleted file mode 100644 index a46009ecc..000000000 --- a/plugins/postcss-double-position-gradients/dist/has-supports-at-rule-ancestor.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import type { Node } from 'postcss'; -export declare function hasSupportsAtRuleAncestor(node: Node): boolean; diff --git a/plugins/postcss-double-position-gradients/dist/index.cjs b/plugins/postcss-double-position-gradients/dist/index.cjs index 3c38b391e..d5a656fbf 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");function hasFallback(e){const t=e.parent;if(!t)return!1;const r=e.prop.toLowerCase(),s=t.index(e);for(let e=0;e"div"===e.type&&","===e.value;function isNumericNode(e){try{return!1!==t.unit(null==e?void 0:e.value)}catch(e){return!1}}const basePlugin=e=>({postcssPlugin:"postcss-double-position-gradients",Declaration(n,{result:i}){if(!r.test(n.value))return;if(hasFallback(n))return;if(hasSupportsAtRuleAncestor(n))return;let a;try{a=t(n.value)}catch(e){n.warn(i,`Failed to parse value '${n.value}' as a CSS gradient. Leaving the original value intact.`)}if(void 0===a)return;a.walk((e=>{if("function"!==e.type||!s.test(e.value))return;const t=e.nodes.filter((e=>"comment"!==e.type&&"space"!==e.type));let r=!1;t.forEach(((t,s,n)=>{if("word"===t.type&&o.includes(t.value.toLowerCase())&&(r=!0),"div"===t.type&&","===t.value&&(r=!1),r)return;const i=Object(n[s-1]),a=Object(n[s-2]),c=Object(n[s+1]);if(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 c=a.toString();c!==n.value&&(n.cloneBefore({value:c}),null!=e&&e.preserve||n.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,module.exports=postcssPlugin; +"use strict";var e=require("@csstools/postcss-progressive-custom-properties"),t=require("postcss-value-parser");function hasFallback(e){const t=e.parent;if(!t)return!1;const r=e.prop.toLowerCase(),s=t.index(e);for(let e=0;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:i}){if(!r.test(n.value))return;if(hasFallback(n))return;if(hasSupportsAtRuleAncestor(n))return;let a;try{a=t(n.value)}catch(e){n.warn(i,`Failed to parse value '${n.value}' as a CSS gradient. Leaving the original value intact.`)}if(void 0===a)return;a.walk((e=>{if("function"!==e.type||!s.test(e.value))return;const t=e.nodes.filter((e=>"comment"!==e.type&&"space"!==e.type));let r=!1;t.forEach(((t,s,n)=>{if("word"===t.type&&o.includes(t.value.toLowerCase())&&(r=!0),"div"===t.type&&","===t.value&&(r=!1),r)return;const i=Object(n[s-1]),a=Object(n[s-2]),c=Object(n[s+1]);if(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 c=a.toString();c!==n.value&&(n.cloneBefore({value:c}),e?.preserve||n.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,module.exports=postcssPlugin; diff --git a/plugins/postcss-double-position-gradients/dist/index.d.ts b/plugins/postcss-double-position-gradients/dist/index.d.ts index 75ff88fb7..b002dc64f 100644 --- a/plugins/postcss-double-position-gradients/dist/index.d.ts +++ b/plugins/postcss-double-position-gradients/dist/index.d.ts @@ -1,10 +1,14 @@ import type { PluginCreator } from 'postcss'; + /** postcss-double-position-gradients plugin options */ -export type pluginOptions = { +export declare type pluginOptions = { /** Preserve the original notation. default: true */ preserve?: boolean; /** Enable "@csstools/postcss-progressive-custom-properties". default: true */ enableProgressiveCustomProperties?: boolean; }; + declare const postcssPlugin: PluginCreator; export default postcssPlugin; + +export { } diff --git a/plugins/postcss-double-position-gradients/dist/index.mjs b/plugins/postcss-double-position-gradients/dist/index.mjs index f3fe49ec0..ed1d2c2ed 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";function hasFallback(e){const t=e.parent;if(!t)return!1;const r=e.prop.toLowerCase(),s=t.index(e);for(let e=0;e"div"===e.type&&","===e.value;function isNumericNode(e){try{return!1!==t.unit(null==e?void 0:e.value)}catch(e){return!1}}const basePlugin=e=>({postcssPlugin:"postcss-double-position-gradients",Declaration(n,{result:i}){if(!r.test(n.value))return;if(hasFallback(n))return;if(hasSupportsAtRuleAncestor(n))return;let a;try{a=t(n.value)}catch(e){n.warn(i,`Failed to parse value '${n.value}' as a CSS gradient. Leaving the original value intact.`)}if(void 0===a)return;a.walk((e=>{if("function"!==e.type||!s.test(e.value))return;const t=e.nodes.filter((e=>"comment"!==e.type&&"space"!==e.type));let r=!1;t.forEach(((t,s,n)=>{if("word"===t.type&&o.includes(t.value.toLowerCase())&&(r=!0),"div"===t.type&&","===t.value&&(r=!1),r)return;const i=Object(n[s-1]),a=Object(n[s-2]),c=Object(n[s+1]);if(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 c=a.toString();c!==n.value&&(n.cloneBefore({value:c}),null!=e&&e.preserve||n.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}; +import e from"@csstools/postcss-progressive-custom-properties";import t from"postcss-value-parser";function hasFallback(e){const t=e.parent;if(!t)return!1;const r=e.prop.toLowerCase(),s=t.index(e);for(let e=0;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:i}){if(!r.test(n.value))return;if(hasFallback(n))return;if(hasSupportsAtRuleAncestor(n))return;let a;try{a=t(n.value)}catch(e){n.warn(i,`Failed to parse value '${n.value}' as a CSS gradient. Leaving the original value intact.`)}if(void 0===a)return;a.walk((e=>{if("function"!==e.type||!s.test(e.value))return;const t=e.nodes.filter((e=>"comment"!==e.type&&"space"!==e.type));let r=!1;t.forEach(((t,s,n)=>{if("word"===t.type&&o.includes(t.value.toLowerCase())&&(r=!0),"div"===t.type&&","===t.value&&(r=!1),r)return;const i=Object(n[s-1]),a=Object(n[s-2]),c=Object(n[s+1]);if(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 c=a.toString();c!==n.value&&(n.cloneBefore({value:c}),e?.preserve||n.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/dist/is-gradient.d.ts b/plugins/postcss-double-position-gradients/dist/is-gradient.d.ts deleted file mode 100644 index 72378209e..000000000 --- a/plugins/postcss-double-position-gradients/dist/is-gradient.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -export declare const HAS_GRADIENT_FUNCTION: RegExp; -export declare const IS_GRADIENT_FUNCTION: RegExp; diff --git a/plugins/postcss-double-position-gradients/package.json b/plugins/postcss-double-position-gradients/package.json index a94cfc0d1..64779b2d2 100644 --- a/plugins/postcss-double-position-gradients/package.json +++ b/plugins/postcss-double-position-gradients/package.json @@ -17,15 +17,18 @@ "engines": { "node": "^14 || ^16 || >=18" }, + "type": "module", "main": "dist/index.cjs", "module": "dist/index.mjs", - "types": "dist/index.d.ts", "exports": { ".": { - "types": "./dist/index.d.ts", - "import": "./dist/index.mjs", - "require": "./dist/index.cjs", - "default": "./dist/index.mjs" + "import": { + "types": "./dist/index.d.ts", + "default": "./dist/index.mjs" + }, + "require": { + "default": "./dist/index.cjs" + } } }, "files": [ diff --git a/plugins/postcss-exponential-functions/CHANGELOG.md b/plugins/postcss-exponential-functions/CHANGELOG.md index 36fbadf9e..f4773f5ea 100644 --- a/plugins/postcss-exponential-functions/CHANGELOG.md +++ b/plugins/postcss-exponential-functions/CHANGELOG.md @@ -2,7 +2,7 @@ ### Unreleased (patch) -- Small fixes in type definitions +- Fix type definitions ### 1.0.1 diff --git a/plugins/postcss-exponential-functions/api-extractor.json b/plugins/postcss-exponential-functions/api-extractor.json new file mode 100644 index 000000000..42058be51 --- /dev/null +++ b/plugins/postcss-exponential-functions/api-extractor.json @@ -0,0 +1,4 @@ +{ + "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json", + "extends": "../../api-extractor.json" +} diff --git a/plugins/postcss-exponential-functions/dist/index.d.ts b/plugins/postcss-exponential-functions/dist/index.d.ts index d216e5787..44407b783 100644 --- a/plugins/postcss-exponential-functions/dist/index.d.ts +++ b/plugins/postcss-exponential-functions/dist/index.d.ts @@ -1,8 +1,12 @@ import type { PluginCreator } from 'postcss'; + +declare const creator: PluginCreator; +export default creator; + /** postcss-exponential-functions plugin options */ -export type pluginOptions = { +export declare type pluginOptions = { /** Preserve the original notation. default: false */ preserve?: boolean; }; -declare const creator: PluginCreator; -export default creator; + +export { } diff --git a/plugins/postcss-exponential-functions/package.json b/plugins/postcss-exponential-functions/package.json index 5b6fd6834..3eee81623 100644 --- a/plugins/postcss-exponential-functions/package.json +++ b/plugins/postcss-exponential-functions/package.json @@ -27,15 +27,18 @@ "engines": { "node": "^14 || ^16 || >=18" }, + "type": "module", "main": "dist/index.cjs", "module": "dist/index.mjs", - "types": "dist/index.d.ts", "exports": { ".": { - "types": "./dist/index.d.ts", - "import": "./dist/index.mjs", - "require": "./dist/index.cjs", - "default": "./dist/index.mjs" + "import": { + "types": "./dist/index.d.ts", + "default": "./dist/index.mjs" + }, + "require": { + "default": "./dist/index.cjs" + } } }, "files": [ diff --git a/plugins/postcss-extract/CHANGELOG.md b/plugins/postcss-extract/CHANGELOG.md index 9eddfab8a..6a8472f1c 100644 --- a/plugins/postcss-extract/CHANGELOG.md +++ b/plugins/postcss-extract/CHANGELOG.md @@ -2,7 +2,7 @@ ### Unreleased (patch) -- Small fixes in type definitions +- Fix type definitions ### 3.0.0 diff --git a/plugins/postcss-extract/api-extractor.json b/plugins/postcss-extract/api-extractor.json new file mode 100644 index 000000000..42058be51 --- /dev/null +++ b/plugins/postcss-extract/api-extractor.json @@ -0,0 +1,4 @@ +{ + "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json", + "extends": "../../api-extractor.json" +} diff --git a/plugins/postcss-extract/dist/index.cjs b/plugins/postcss-extract/dist/index.cjs index ea7fc22f5..969f81b9f 100644 --- a/plugins/postcss-extract/dist/index.cjs +++ b/plugins/postcss-extract/dist/index.cjs @@ -1 +1 @@ -"use strict";var e,t=require("postcss-selector-parser");function notPseudo(e,t){return e.filter((e=>!t.includes(e)))}function adjacentSiblingCombinator(e){return e.map((e=>e.prev())).filter((e=>!!e))}function childCombinator(e){return e.map((e=>e.parent)).filter((e=>!!e))}function descendantCombinator(e){return e.flatMap((t=>{const n=[];let r=t.parent;for(;r;)n.push(r),r=r.parent;return e.length?n:[]})).filter((e=>!!e))}function generalSiblingCombinator(e){return e.flatMap((t=>{const n=[];let r=t.prev();for(;r;)n.push(r),r=r.prev();return e.length?n:[]})).filter((e=>!!e))}function matchAttribute(t,n,r,a,s=!1){if(n.startsWith("__proto__")||null!=r&&r.startsWith("__proto__"))return[];let i=!1;r||""===r||(i=!0);let o="";i||(o=r.toString()),s&&(o=o.toLowerCase());return t.filter((t=>{let r="";if(r="variable"===n.toLowerCase()&&"decl"===t.type&&"variable"in t?"variable":Object.keys(t).find((e=>e.toLowerCase()===n.toLowerCase()&&Object.prototype.hasOwnProperty.call(t,e))),!r)return!1;if("boolean"==typeof t[r])return t[r];if(i)return!0;let u=[t[r].toString()];switch("rule"!==t.type||"selector"!==r&&"selectors"!==r||(u=t.selectors),s&&(u=u.map((e=>e.toLowerCase()))),a){case e.StartsWith:return!!u.find((e=>e.startsWith(o)));case e.EndsWith:return!!u.find((e=>e.endsWith(o)));case e.Contains:return!!u.find((e=>e.includes(o)));case e.Exact:default:return!!u.find((e=>e===o))}}))}function matchTagName(e,t){return e.filter((e=>e.type.toLowerCase()===t.toLowerCase()))}function simplifyASTNode(e){switch(e.type){case"decl":{const t=e;return cleanUndefinedValues({type:t.type,important:t.important,prop:t.prop,value:t.value,variable:t.variable})}case"rule":{const t=e;return cleanUndefinedValues({type:t.type,selectors:t.selectors})}case"atrule":{const t=e;return cleanUndefinedValues({type:t.type,name:t.name,params:t.params})}case"comment":{const t=e;return cleanUndefinedValues({type:t.type,text:t.text})}default:return{}}}function cleanUndefinedValues(e){return Object.keys(e).forEach((t=>{void 0===e[t]&&delete e[t]})),e}function extract(e,t){const n={};for(const[r,a]of t){let t=new Set;a.each((n=>{t=selectNodesForSingleQuery(e,n,t)})),n[r]=[];for(const e of t)n[r].push(simplifyASTNode(e))}return n}function selectNodesForSingleQuery(e,t,n){const r=buildQuery(t);if(!r)return new Set;const a=new Set(n);return e.walk((e=>{if(a.has(e))return;executeConditions(r,[e]).length>0&&a.add(e)})),a}function buildQuery(t){if(!t||!t.nodes)return;let n;return t.each((t=>{switch(t.type){case"universal":n={next:n,run:e=>e};break;case"combinator":switch(t.value){case" ":n={next:n,run:e=>descendantCombinator(e)};break;case">":n={next:n,run:e=>childCombinator(e)};break;case"+":n={next:n,run:e=>adjacentSiblingCombinator(e)};break;case"~":n={next:n,run:e=>generalSiblingCombinator(e)};break;default:n={next:n,run:()=>[]}}break;case"tag":n={next:n,run:e=>matchTagName(e,t.value)};break;case"pseudo":if(":not"===t.value)n={next:n,run:e=>{const n=t.nodes.map((e=>buildQuery(e))),r=e.filter((e=>n.flatMap((t=>t?executeConditions(t,[e]):[])).length>0));return notPseudo(e,r)}};else n={next:n,run:()=>[]};break;case"attribute":switch(t.operator){case"^=":n={next:n,run:n=>matchAttribute(n,t.attribute,t.value,e.StartsWith,t.insensitive)};break;case"$=":n={next:n,run:n=>matchAttribute(n,t.attribute,t.value,e.EndsWith,t.insensitive)};break;case"*=":n={next:n,run:n=>matchAttribute(n,t.attribute,t.value,e.Contains,t.insensitive)};break;default:n={next:n,run:n=>matchAttribute(n,t.attribute,t.value,e.Exact,t.insensitive)}}break;default:n={next:n,run:()=>[]}}})),n}function executeConditions(e,t){let n=e,r=t;for(;n&&r.length>0;)r=n.run(r),n=n.next;return r}!function(e){e.Exact="",e.StartsWith="^",e.EndsWith="$",e.Contains="*"}(e||(e={}));const creator=e=>{const n=Object(e),r=new Map;return Object.keys(n.queries??{}).forEach((e=>{r.set(e,t().astSync(n.queries[e]))})),n.results||(n.results=e=>{console.log(e)}),{postcssPlugin:"postcss-extract",prepare:()=>n.extractLate?{OnceExit:e=>{n.results(extract(e,r))}}:{Once:e=>{n.results(extract(e,r))}}}};creator.postcss=!0,module.exports=creator; +"use strict";var e,t=require("postcss-selector-parser");function notPseudo(e,t){return e.filter((e=>!t.includes(e)))}function adjacentSiblingCombinator(e){return e.map((e=>e.prev())).filter((e=>!!e))}function childCombinator(e){return e.map((e=>e.parent)).filter((e=>!!e))}function descendantCombinator(e){return e.flatMap((t=>{const n=[];let r=t.parent;for(;r;)n.push(r),r=r.parent;return e.length?n:[]})).filter((e=>!!e))}function generalSiblingCombinator(e){return e.flatMap((t=>{const n=[];let r=t.prev();for(;r;)n.push(r),r=r.prev();return e.length?n:[]})).filter((e=>!!e))}function matchAttribute(t,n,r,a,s=!1){if(n.startsWith("__proto__")||r?.startsWith("__proto__"))return[];let i=!1;r||""===r||(i=!0);let o="";i||(o=r.toString()),s&&(o=o.toLowerCase());return t.filter((t=>{let r="";if(r="variable"===n.toLowerCase()&&"decl"===t.type&&"variable"in t?"variable":Object.keys(t).find((e=>e.toLowerCase()===n.toLowerCase()&&Object.prototype.hasOwnProperty.call(t,e))),!r)return!1;if("boolean"==typeof t[r])return t[r];if(i)return!0;let u=[t[r].toString()];switch("rule"!==t.type||"selector"!==r&&"selectors"!==r||(u=t.selectors),s&&(u=u.map((e=>e.toLowerCase()))),a){case e.StartsWith:return!!u.find((e=>e.startsWith(o)));case e.EndsWith:return!!u.find((e=>e.endsWith(o)));case e.Contains:return!!u.find((e=>e.includes(o)));case e.Exact:default:return!!u.find((e=>e===o))}}))}function matchTagName(e,t){return e.filter((e=>e.type.toLowerCase()===t.toLowerCase()))}function simplifyASTNode(e){switch(e.type){case"decl":{const t=e;return cleanUndefinedValues({type:t.type,important:t.important,prop:t.prop,value:t.value,variable:t.variable})}case"rule":{const t=e;return cleanUndefinedValues({type:t.type,selectors:t.selectors})}case"atrule":{const t=e;return cleanUndefinedValues({type:t.type,name:t.name,params:t.params})}case"comment":{const t=e;return cleanUndefinedValues({type:t.type,text:t.text})}default:return{}}}function cleanUndefinedValues(e){return Object.keys(e).forEach((t=>{void 0===e[t]&&delete e[t]})),e}function extract(e,t){const n={};for(const[r,a]of t){let t=new Set;a.each((n=>{t=selectNodesForSingleQuery(e,n,t)})),n[r]=[];for(const e of t)n[r].push(simplifyASTNode(e))}return n}function selectNodesForSingleQuery(e,t,n){const r=buildQuery(t);if(!r)return new Set;const a=new Set(n);return e.walk((e=>{if(a.has(e))return;executeConditions(r,[e]).length>0&&a.add(e)})),a}function buildQuery(t){if(!t||!t.nodes)return;let n;return t.each((t=>{switch(t.type){case"universal":n={next:n,run:e=>e};break;case"combinator":switch(t.value){case" ":n={next:n,run:e=>descendantCombinator(e)};break;case">":n={next:n,run:e=>childCombinator(e)};break;case"+":n={next:n,run:e=>adjacentSiblingCombinator(e)};break;case"~":n={next:n,run:e=>generalSiblingCombinator(e)};break;default:n={next:n,run:()=>[]}}break;case"tag":n={next:n,run:e=>matchTagName(e,t.value)};break;case"pseudo":if(":not"===t.value)n={next:n,run:e=>{const n=t.nodes.map((e=>buildQuery(e))),r=e.filter((e=>n.flatMap((t=>t?executeConditions(t,[e]):[])).length>0));return notPseudo(e,r)}};else n={next:n,run:()=>[]};break;case"attribute":switch(t.operator){case"^=":n={next:n,run:n=>matchAttribute(n,t.attribute,t.value,e.StartsWith,t.insensitive)};break;case"$=":n={next:n,run:n=>matchAttribute(n,t.attribute,t.value,e.EndsWith,t.insensitive)};break;case"*=":n={next:n,run:n=>matchAttribute(n,t.attribute,t.value,e.Contains,t.insensitive)};break;default:n={next:n,run:n=>matchAttribute(n,t.attribute,t.value,e.Exact,t.insensitive)}}break;default:n={next:n,run:()=>[]}}})),n}function executeConditions(e,t){let n=e,r=t;for(;n&&r.length>0;)r=n.run(r),n=n.next;return r}!function(e){e.Exact="",e.StartsWith="^",e.EndsWith="$",e.Contains="*"}(e||(e={}));const creator=e=>{const n=Object(e),r=new Map;return Object.keys(n.queries??{}).forEach((e=>{r.set(e,t().astSync(n.queries[e]))})),n.results||(n.results=e=>{console.log(e)}),{postcssPlugin:"postcss-extract",prepare:()=>n.extractLate?{OnceExit:e=>{n.results(extract(e,r))}}:{Once:e=>{n.results(extract(e,r))}}}};creator.postcss=!0,module.exports=creator; diff --git a/plugins/postcss-extract/dist/index.d.ts b/plugins/postcss-extract/dist/index.d.ts index 9a1f9db25..0cf1e8524 100644 --- a/plugins/postcss-extract/dist/index.d.ts +++ b/plugins/postcss-extract/dist/index.d.ts @@ -1,5 +1,9 @@ import type { PluginCreator } from 'postcss'; -export type pluginOptions = { + +declare const creator: PluginCreator; +export default creator; + +export declare type pluginOptions = { /** Mapping of queries */ queries: Record; /** Extract after transforms are likely to be done, or before it */ @@ -7,5 +11,5 @@ export type pluginOptions = { /** Callback for results */ results: (results: Record>>) => void; }; -declare const creator: PluginCreator; -export default creator; + +export { } diff --git a/plugins/postcss-extract/dist/index.mjs b/plugins/postcss-extract/dist/index.mjs index 315a200b1..89889233c 100644 --- a/plugins/postcss-extract/dist/index.mjs +++ b/plugins/postcss-extract/dist/index.mjs @@ -1 +1 @@ -import e from"postcss-selector-parser";function notPseudo(e,t){return e.filter((e=>!t.includes(e)))}function adjacentSiblingCombinator(e){return e.map((e=>e.prev())).filter((e=>!!e))}function childCombinator(e){return e.map((e=>e.parent)).filter((e=>!!e))}function descendantCombinator(e){return e.flatMap((t=>{const n=[];let r=t.parent;for(;r;)n.push(r),r=r.parent;return e.length?n:[]})).filter((e=>!!e))}function generalSiblingCombinator(e){return e.flatMap((t=>{const n=[];let r=t.prev();for(;r;)n.push(r),r=r.prev();return e.length?n:[]})).filter((e=>!!e))}var t;function matchAttribute(e,n,r,a,s=!1){if(n.startsWith("__proto__")||null!=r&&r.startsWith("__proto__"))return[];let i=!1;r||""===r||(i=!0);let o="";i||(o=r.toString()),s&&(o=o.toLowerCase());return e.filter((e=>{let r="";if(r="variable"===n.toLowerCase()&&"decl"===e.type&&"variable"in e?"variable":Object.keys(e).find((t=>t.toLowerCase()===n.toLowerCase()&&Object.prototype.hasOwnProperty.call(e,t))),!r)return!1;if("boolean"==typeof e[r])return e[r];if(i)return!0;let u=[e[r].toString()];switch("rule"!==e.type||"selector"!==r&&"selectors"!==r||(u=e.selectors),s&&(u=u.map((e=>e.toLowerCase()))),a){case t.StartsWith:return!!u.find((e=>e.startsWith(o)));case t.EndsWith:return!!u.find((e=>e.endsWith(o)));case t.Contains:return!!u.find((e=>e.includes(o)));case t.Exact:default:return!!u.find((e=>e===o))}}))}function matchTagName(e,t){return e.filter((e=>e.type.toLowerCase()===t.toLowerCase()))}function simplifyASTNode(e){switch(e.type){case"decl":{const t=e;return cleanUndefinedValues({type:t.type,important:t.important,prop:t.prop,value:t.value,variable:t.variable})}case"rule":{const t=e;return cleanUndefinedValues({type:t.type,selectors:t.selectors})}case"atrule":{const t=e;return cleanUndefinedValues({type:t.type,name:t.name,params:t.params})}case"comment":{const t=e;return cleanUndefinedValues({type:t.type,text:t.text})}default:return{}}}function cleanUndefinedValues(e){return Object.keys(e).forEach((t=>{void 0===e[t]&&delete e[t]})),e}function extract(e,t){const n={};for(const[r,a]of t){let t=new Set;a.each((n=>{t=selectNodesForSingleQuery(e,n,t)})),n[r]=[];for(const e of t)n[r].push(simplifyASTNode(e))}return n}function selectNodesForSingleQuery(e,t,n){const r=buildQuery(t);if(!r)return new Set;const a=new Set(n);return e.walk((e=>{if(a.has(e))return;executeConditions(r,[e]).length>0&&a.add(e)})),a}function buildQuery(e){if(!e||!e.nodes)return;let n;return e.each((e=>{switch(e.type){case"universal":n={next:n,run:e=>e};break;case"combinator":switch(e.value){case" ":n={next:n,run:e=>descendantCombinator(e)};break;case">":n={next:n,run:e=>childCombinator(e)};break;case"+":n={next:n,run:e=>adjacentSiblingCombinator(e)};break;case"~":n={next:n,run:e=>generalSiblingCombinator(e)};break;default:n={next:n,run:()=>[]}}break;case"tag":n={next:n,run:t=>matchTagName(t,e.value)};break;case"pseudo":if(":not"===e.value)n={next:n,run:t=>{const n=e.nodes.map((e=>buildQuery(e))),r=t.filter((e=>n.flatMap((t=>t?executeConditions(t,[e]):[])).length>0));return notPseudo(t,r)}};else n={next:n,run:()=>[]};break;case"attribute":switch(e.operator){case"^=":n={next:n,run:n=>matchAttribute(n,e.attribute,e.value,t.StartsWith,e.insensitive)};break;case"$=":n={next:n,run:n=>matchAttribute(n,e.attribute,e.value,t.EndsWith,e.insensitive)};break;case"*=":n={next:n,run:n=>matchAttribute(n,e.attribute,e.value,t.Contains,e.insensitive)};break;default:n={next:n,run:n=>matchAttribute(n,e.attribute,e.value,t.Exact,e.insensitive)}}break;default:n={next:n,run:()=>[]}}})),n}function executeConditions(e,t){let n=e,r=t;for(;n&&r.length>0;)r=n.run(r),n=n.next;return r}!function(e){e.Exact="",e.StartsWith="^",e.EndsWith="$",e.Contains="*"}(t||(t={}));const creator=t=>{const n=Object(t),r=new Map;return Object.keys(n.queries??{}).forEach((t=>{r.set(t,e().astSync(n.queries[t]))})),n.results||(n.results=e=>{console.log(e)}),{postcssPlugin:"postcss-extract",prepare:()=>n.extractLate?{OnceExit:e=>{n.results(extract(e,r))}}:{Once:e=>{n.results(extract(e,r))}}}};creator.postcss=!0;export{creator as default}; +import e from"postcss-selector-parser";function notPseudo(e,t){return e.filter((e=>!t.includes(e)))}function adjacentSiblingCombinator(e){return e.map((e=>e.prev())).filter((e=>!!e))}function childCombinator(e){return e.map((e=>e.parent)).filter((e=>!!e))}function descendantCombinator(e){return e.flatMap((t=>{const n=[];let r=t.parent;for(;r;)n.push(r),r=r.parent;return e.length?n:[]})).filter((e=>!!e))}function generalSiblingCombinator(e){return e.flatMap((t=>{const n=[];let r=t.prev();for(;r;)n.push(r),r=r.prev();return e.length?n:[]})).filter((e=>!!e))}var t;function matchAttribute(e,n,r,a,s=!1){if(n.startsWith("__proto__")||r?.startsWith("__proto__"))return[];let i=!1;r||""===r||(i=!0);let o="";i||(o=r.toString()),s&&(o=o.toLowerCase());return e.filter((e=>{let r="";if(r="variable"===n.toLowerCase()&&"decl"===e.type&&"variable"in e?"variable":Object.keys(e).find((t=>t.toLowerCase()===n.toLowerCase()&&Object.prototype.hasOwnProperty.call(e,t))),!r)return!1;if("boolean"==typeof e[r])return e[r];if(i)return!0;let u=[e[r].toString()];switch("rule"!==e.type||"selector"!==r&&"selectors"!==r||(u=e.selectors),s&&(u=u.map((e=>e.toLowerCase()))),a){case t.StartsWith:return!!u.find((e=>e.startsWith(o)));case t.EndsWith:return!!u.find((e=>e.endsWith(o)));case t.Contains:return!!u.find((e=>e.includes(o)));case t.Exact:default:return!!u.find((e=>e===o))}}))}function matchTagName(e,t){return e.filter((e=>e.type.toLowerCase()===t.toLowerCase()))}function simplifyASTNode(e){switch(e.type){case"decl":{const t=e;return cleanUndefinedValues({type:t.type,important:t.important,prop:t.prop,value:t.value,variable:t.variable})}case"rule":{const t=e;return cleanUndefinedValues({type:t.type,selectors:t.selectors})}case"atrule":{const t=e;return cleanUndefinedValues({type:t.type,name:t.name,params:t.params})}case"comment":{const t=e;return cleanUndefinedValues({type:t.type,text:t.text})}default:return{}}}function cleanUndefinedValues(e){return Object.keys(e).forEach((t=>{void 0===e[t]&&delete e[t]})),e}function extract(e,t){const n={};for(const[r,a]of t){let t=new Set;a.each((n=>{t=selectNodesForSingleQuery(e,n,t)})),n[r]=[];for(const e of t)n[r].push(simplifyASTNode(e))}return n}function selectNodesForSingleQuery(e,t,n){const r=buildQuery(t);if(!r)return new Set;const a=new Set(n);return e.walk((e=>{if(a.has(e))return;executeConditions(r,[e]).length>0&&a.add(e)})),a}function buildQuery(e){if(!e||!e.nodes)return;let n;return e.each((e=>{switch(e.type){case"universal":n={next:n,run:e=>e};break;case"combinator":switch(e.value){case" ":n={next:n,run:e=>descendantCombinator(e)};break;case">":n={next:n,run:e=>childCombinator(e)};break;case"+":n={next:n,run:e=>adjacentSiblingCombinator(e)};break;case"~":n={next:n,run:e=>generalSiblingCombinator(e)};break;default:n={next:n,run:()=>[]}}break;case"tag":n={next:n,run:t=>matchTagName(t,e.value)};break;case"pseudo":if(":not"===e.value)n={next:n,run:t=>{const n=e.nodes.map((e=>buildQuery(e))),r=t.filter((e=>n.flatMap((t=>t?executeConditions(t,[e]):[])).length>0));return notPseudo(t,r)}};else n={next:n,run:()=>[]};break;case"attribute":switch(e.operator){case"^=":n={next:n,run:n=>matchAttribute(n,e.attribute,e.value,t.StartsWith,e.insensitive)};break;case"$=":n={next:n,run:n=>matchAttribute(n,e.attribute,e.value,t.EndsWith,e.insensitive)};break;case"*=":n={next:n,run:n=>matchAttribute(n,e.attribute,e.value,t.Contains,e.insensitive)};break;default:n={next:n,run:n=>matchAttribute(n,e.attribute,e.value,t.Exact,e.insensitive)}}break;default:n={next:n,run:()=>[]}}})),n}function executeConditions(e,t){let n=e,r=t;for(;n&&r.length>0;)r=n.run(r),n=n.next;return r}!function(e){e.Exact="",e.StartsWith="^",e.EndsWith="$",e.Contains="*"}(t||(t={}));const creator=t=>{const n=Object(t),r=new Map;return Object.keys(n.queries??{}).forEach((t=>{r.set(t,e().astSync(n.queries[t]))})),n.results||(n.results=e=>{console.log(e)}),{postcssPlugin:"postcss-extract",prepare:()=>n.extractLate?{OnceExit:e=>{n.results(extract(e,r))}}:{Once:e=>{n.results(extract(e,r))}}}};creator.postcss=!0;export{creator as default}; diff --git a/plugins/postcss-extract/dist/node-list.d.ts b/plugins/postcss-extract/dist/node-list.d.ts deleted file mode 100644 index 9d38f61bf..000000000 --- a/plugins/postcss-extract/dist/node-list.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import type { Node } from 'postcss'; -export type NodeList = Array; diff --git a/plugins/postcss-extract/dist/pseudos/not.d.ts b/plugins/postcss-extract/dist/pseudos/not.d.ts deleted file mode 100644 index 33ab38578..000000000 --- a/plugins/postcss-extract/dist/pseudos/not.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import type { NodeList } from '../node-list'; -export declare function notPseudo(list: NodeList, exclude: NodeList): NodeList; diff --git a/plugins/postcss-extract/dist/select-nodes.d.ts b/plugins/postcss-extract/dist/select-nodes.d.ts deleted file mode 100644 index a3f02519a..000000000 --- a/plugins/postcss-extract/dist/select-nodes.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -import type { Node, Container } from 'postcss'; -import type selectorParser from 'postcss-selector-parser'; -export declare function extract(container: Container, selectors: Map): Record>>; diff --git a/plugins/postcss-extract/dist/selector-engine/combinators/adjacent-sibling.d.ts b/plugins/postcss-extract/dist/selector-engine/combinators/adjacent-sibling.d.ts deleted file mode 100644 index 7856083d8..000000000 --- a/plugins/postcss-extract/dist/selector-engine/combinators/adjacent-sibling.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import type { NodeList } from '../../node-list'; -export declare function adjacentSiblingCombinator(list: NodeList): NodeList; diff --git a/plugins/postcss-extract/dist/selector-engine/combinators/child.d.ts b/plugins/postcss-extract/dist/selector-engine/combinators/child.d.ts deleted file mode 100644 index 8e4098bb0..000000000 --- a/plugins/postcss-extract/dist/selector-engine/combinators/child.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -import type { ChildNode, Container, Document } from 'postcss'; -import type { NodeList } from '../../node-list'; -export declare function childCombinator(list: NodeList): Array | Document>; diff --git a/plugins/postcss-extract/dist/selector-engine/combinators/descendant.d.ts b/plugins/postcss-extract/dist/selector-engine/combinators/descendant.d.ts deleted file mode 100644 index 9851cef73..000000000 --- a/plugins/postcss-extract/dist/selector-engine/combinators/descendant.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import type { NodeList } from '../../node-list'; -export declare function descendantCombinator(list: NodeList): NodeList; diff --git a/plugins/postcss-extract/dist/selector-engine/combinators/general-sibling.d.ts b/plugins/postcss-extract/dist/selector-engine/combinators/general-sibling.d.ts deleted file mode 100644 index 9a62270da..000000000 --- a/plugins/postcss-extract/dist/selector-engine/combinators/general-sibling.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import type { NodeList } from '../../node-list'; -export declare function generalSiblingCombinator(list: NodeList): NodeList; diff --git a/plugins/postcss-extract/dist/selector-engine/matchers/attribute.d.ts b/plugins/postcss-extract/dist/selector-engine/matchers/attribute.d.ts deleted file mode 100644 index 2ef515596..000000000 --- a/plugins/postcss-extract/dist/selector-engine/matchers/attribute.d.ts +++ /dev/null @@ -1,8 +0,0 @@ -import type { NodeList } from '../../node-list'; -export declare enum AttributeMatchingFlag { - Exact = "", - StartsWith = "^", - EndsWith = "$", - Contains = "*" -} -export declare function matchAttribute(list: NodeList, attributeName: string, attributeValue: string | null | undefined, flag: AttributeMatchingFlag, caseInsensitive?: boolean): NodeList; diff --git a/plugins/postcss-extract/dist/selector-engine/matchers/tag-name.d.ts b/plugins/postcss-extract/dist/selector-engine/matchers/tag-name.d.ts deleted file mode 100644 index b5f60aba3..000000000 --- a/plugins/postcss-extract/dist/selector-engine/matchers/tag-name.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import type { NodeList } from '../../node-list'; -export declare function matchTagName(list: NodeList, tagName: string): NodeList; diff --git a/plugins/postcss-extract/dist/simplify-ast-nodes.d.ts b/plugins/postcss-extract/dist/simplify-ast-nodes.d.ts deleted file mode 100644 index ae7f8b773..000000000 --- a/plugins/postcss-extract/dist/simplify-ast-nodes.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import type { Node } from 'postcss'; -export declare function simplifyASTNode(node: Node): Record; diff --git a/plugins/postcss-extract/package.json b/plugins/postcss-extract/package.json index 0e46fcdb0..300c1c284 100644 --- a/plugins/postcss-extract/package.json +++ b/plugins/postcss-extract/package.json @@ -27,15 +27,18 @@ "engines": { "node": "^14 || ^16 || >=18" }, + "type": "module", "main": "dist/index.cjs", "module": "dist/index.mjs", - "types": "dist/index.d.ts", "exports": { ".": { - "types": "./dist/index.d.ts", - "import": "./dist/index.mjs", - "require": "./dist/index.cjs", - "default": "./dist/index.mjs" + "import": { + "types": "./dist/index.d.ts", + "default": "./dist/index.mjs" + }, + "require": { + "default": "./dist/index.cjs" + } } }, "files": [ diff --git a/plugins/postcss-focus-visible/CHANGELOG.md b/plugins/postcss-focus-visible/CHANGELOG.md index 7e7618b08..b95a26cd0 100644 --- a/plugins/postcss-focus-visible/CHANGELOG.md +++ b/plugins/postcss-focus-visible/CHANGELOG.md @@ -1,5 +1,9 @@ # Changes to PostCSS Focus Visible +### Unreleased (patch) + +- Fix type definitions + ### 9.0.0 _July 3, 2023_ diff --git a/plugins/postcss-focus-visible/api-extractor.json b/plugins/postcss-focus-visible/api-extractor.json new file mode 100644 index 000000000..42058be51 --- /dev/null +++ b/plugins/postcss-focus-visible/api-extractor.json @@ -0,0 +1,4 @@ +{ + "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json", + "extends": "../../api-extractor.json" +} diff --git a/plugins/postcss-focus-visible/dist/index.cjs b/plugins/postcss-focus-visible/dist/index.cjs index bffe9315b..1c2c2c5c5 100644 --- a/plugins/postcss-focus-visible/dist/index.cjs +++ b/plugins/postcss-focus-visible/dist/index.cjs @@ -1 +1 @@ -"use strict";var e=require("postcss-selector-parser");const s="js-focus-visible",o=":focus-visible",creator=r=>{const n=Object.assign({preserve:!0,replaceWith:".focus-visible",disablePolyfillReadyClass:!1},r),t=e().astSync(n.replaceWith);return{postcssPlugin:"postcss-focus-visible",prepare(){const r=new WeakSet;return{Rule(l,{result:a}){if(r.has(l))return;if(!l.selector.toLowerCase().includes(o))return;const i=l.selectors.flatMap((r=>{if(!r.toLowerCase().includes(o))return[r];let i;try{i=e().astSync(r)}catch(e){return l.warn(a,`Failed to parse selector : "${r}" with message: "${e instanceof Error?e.message:e}"`),r}if(void 0===i)return[r];let c=!1;if(i.walkPseudos((e=>{e.value.toLowerCase()===o&&(e.nodes&&e.nodes.length||(c=!0,e.replaceWith(t.clone({}))))})),!c)return[r];const u=i.clone();if(!n.disablePolyfillReadyClass){var d,p;if(null!=(d=i.nodes)&&null!=(d=d[0])&&null!=(d=d.nodes)&&d.length)for(let o=0;o{const t=Object.assign({preserve:!0,replaceWith:".focus-visible",disablePolyfillReadyClass:!1},r),n=e().astSync(t.replaceWith);return{postcssPlugin:"postcss-focus-visible",prepare(){const r=new WeakSet;return{Rule(l,{result:a}){if(r.has(l))return;if(!l.selector.toLowerCase().includes(o))return;const i=l.selectors.flatMap((r=>{if(!r.toLowerCase().includes(o))return[r];let i;try{i=e().astSync(r)}catch(e){return l.warn(a,`Failed to parse selector : "${r}" with message: "${e instanceof Error?e.message:e}"`),r}if(void 0===i)return[r];let c=!1;if(i.walkPseudos((e=>{e.value.toLowerCase()===o&&(e.nodes&&e.nodes.length||(c=!0,e.replaceWith(n.clone({}))))})),!c)return[r];const d=i.clone();if(!t.disablePolyfillReadyClass){if(i.nodes?.[0]?.nodes?.length)for(let o=0;o; +export default creator; + /** postcss-focus-visible plugin options */ -export type pluginOptions = { +export declare type pluginOptions = { /** Preserve the original notation. default: true */ preserve?: boolean; /** The replacement class to be used in the polyfill. default: ".focus-visible" */ @@ -8,5 +12,5 @@ export type pluginOptions = { /** Disable the selector prefix that is used to prevent a flash of incorrectly styled content. default: false */ disablePolyfillReadyClass?: boolean; }; -declare const creator: PluginCreator; -export default creator; + +export { } diff --git a/plugins/postcss-focus-visible/dist/index.mjs b/plugins/postcss-focus-visible/dist/index.mjs index 89a2191ba..6db252dc8 100644 --- a/plugins/postcss-focus-visible/dist/index.mjs +++ b/plugins/postcss-focus-visible/dist/index.mjs @@ -1 +1 @@ -import e from"postcss-selector-parser";const s="js-focus-visible",o=":focus-visible",creator=n=>{const r=Object.assign({preserve:!0,replaceWith:".focus-visible",disablePolyfillReadyClass:!1},n),t=e().astSync(r.replaceWith);return{postcssPlugin:"postcss-focus-visible",prepare(){const n=new WeakSet;return{Rule(l,{result:a}){if(n.has(l))return;if(!l.selector.toLowerCase().includes(o))return;const i=l.selectors.flatMap((n=>{if(!n.toLowerCase().includes(o))return[n];let i;try{i=e().astSync(n)}catch(e){return l.warn(a,`Failed to parse selector : "${n}" with message: "${e instanceof Error?e.message:e}"`),n}if(void 0===i)return[n];let c=!1;if(i.walkPseudos((e=>{e.value.toLowerCase()===o&&(e.nodes&&e.nodes.length||(c=!0,e.replaceWith(t.clone({}))))})),!c)return[n];const d=i.clone();if(!r.disablePolyfillReadyClass){var u,p;if(null!=(u=i.nodes)&&null!=(u=u[0])&&null!=(u=u.nodes)&&u.length)for(let o=0;o{const t=Object.assign({preserve:!0,replaceWith:".focus-visible",disablePolyfillReadyClass:!1},r),n=e().astSync(t.replaceWith);return{postcssPlugin:"postcss-focus-visible",prepare(){const r=new WeakSet;return{Rule(l,{result:a}){if(r.has(l))return;if(!l.selector.toLowerCase().includes(o))return;const i=l.selectors.flatMap((r=>{if(!r.toLowerCase().includes(o))return[r];let i;try{i=e().astSync(r)}catch(e){return l.warn(a,`Failed to parse selector : "${r}" with message: "${e instanceof Error?e.message:e}"`),r}if(void 0===i)return[r];let c=!1;if(i.walkPseudos((e=>{e.value.toLowerCase()===o&&(e.nodes&&e.nodes.length||(c=!0,e.replaceWith(n.clone({}))))})),!c)return[r];const d=i.clone();if(!t.disablePolyfillReadyClass){if(i.nodes?.[0]?.nodes?.length)for(let o=0;o=18" }, + "type": "module", "main": "dist/index.cjs", "module": "dist/index.mjs", - "types": "dist/index.d.ts", "exports": { ".": { - "types": "./dist/index.d.ts", - "import": "./dist/index.mjs", - "require": "./dist/index.cjs", - "default": "./dist/index.mjs" + "import": { + "types": "./dist/index.d.ts", + "default": "./dist/index.mjs" + }, + "require": { + "default": "./dist/index.cjs" + } } }, "files": [ diff --git a/plugins/postcss-focus-visible/src/index.ts b/plugins/postcss-focus-visible/src/index.ts index 1d2c9fe2c..073e3b150 100644 --- a/plugins/postcss-focus-visible/src/index.ts +++ b/plugins/postcss-focus-visible/src/index.ts @@ -97,6 +97,7 @@ const creator: PluginCreator = (opts?: pluginOptions) => { if (i === selectorAST.nodes[0].nodes.length - 1) { // Append the class to the end of the selector if not combinator or pseudo element was found. + // @ts-expect-error https://github.com/postcss/postcss-selector-parser/pull/284 selectorAST.nodes[0].append(parser.className({ value: POLYFILL_READY_CLASSNAME })); break; } @@ -105,7 +106,9 @@ const creator: PluginCreator = (opts?: pluginOptions) => { if (selectorAST.nodes?.[0]?.nodes) { // Prepend a space combinator and the class to the beginning of the selector. + // @ts-expect-error https://github.com/postcss/postcss-selector-parser/pull/284 selectorASTClone.nodes[0].prepend(parser.combinator({ value: ' ' })); + // @ts-expect-error https://github.com/postcss/postcss-selector-parser/pull/284 selectorASTClone.nodes[0].prepend(parser.className({ value: POLYFILL_READY_CLASSNAME })); } diff --git a/plugins/postcss-focus-within/CHANGELOG.md b/plugins/postcss-focus-within/CHANGELOG.md index 299c1dd04..e1e05493d 100644 --- a/plugins/postcss-focus-within/CHANGELOG.md +++ b/plugins/postcss-focus-within/CHANGELOG.md @@ -1,5 +1,9 @@ # Changes to PostCSS Focus Within +### Unreleased (patch) + +- Fix type definitions + ### 8.0.0 _July 3, 2023_ diff --git a/plugins/postcss-focus-within/api-extractor.json b/plugins/postcss-focus-within/api-extractor.json new file mode 100644 index 000000000..42058be51 --- /dev/null +++ b/plugins/postcss-focus-within/api-extractor.json @@ -0,0 +1,4 @@ +{ + "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json", + "extends": "../../api-extractor.json" +} diff --git a/plugins/postcss-focus-within/dist/index.cjs b/plugins/postcss-focus-within/dist/index.cjs index 56d002082..684420699 100644 --- a/plugins/postcss-focus-within/dist/index.cjs +++ b/plugins/postcss-focus-within/dist/index.cjs @@ -1 +1 @@ -"use strict";var e=require("postcss-selector-parser");const s=[" ",">","~",":","+","@","#","(",")"];function isValidReplacement(e){let n=!0;for(let t=0,o=s.length;t-1&&(n=!1);return n}const n="js-focus-within",t=":focus-within",creator=s=>{const o=Object.assign({preserve:!0,replaceWith:"[focus-within]",disablePolyfillReadyClass:!1},s),r=e().astSync(o.replaceWith);return isValidReplacement(o.replaceWith)?{postcssPlugin:"postcss-focus-within",prepare(){const s=new WeakSet;return{Rule(l,{result:a}){if(s.has(l))return;if(!l.selector.toLowerCase().includes(t))return;const i=l.selectors.flatMap((s=>{if(!s.toLowerCase().includes(t))return[s];let i;try{i=e().astSync(s)}catch(e){return l.warn(a,`Failed to parse selector : "${s}" with message: "${e instanceof Error?e.message:e}"`),s}if(void 0===i)return[s];let c=!1;if(i.walkPseudos((e=>{e.value.toLowerCase()===t&&(e.nodes&&e.nodes.length||(c=!0,e.replaceWith(r.clone({}))))})),!c)return[s];const u=i.clone();if(!o.disablePolyfillReadyClass){var d,p;if(null!=(d=i.nodes)&&null!=(d=d[0])&&null!=(d=d.nodes)&&d.length)for(let s=0;s{e.warn(s,`${o.replaceWith} is not a valid replacement since it can't be applied to single elements.`)}}};creator.postcss=!0,module.exports=creator; +"use strict";var e=require("postcss-selector-parser");const s=[" ",">","~",":","+","@","#","(",")"];function isValidReplacement(e){let t=!0;for(let n=0,o=s.length;n-1&&(t=!1);return t}const t="js-focus-within",n=":focus-within",creator=s=>{const o=Object.assign({preserve:!0,replaceWith:"[focus-within]",disablePolyfillReadyClass:!1},s),r=e().astSync(o.replaceWith);return isValidReplacement(o.replaceWith)?{postcssPlugin:"postcss-focus-within",prepare(){const s=new WeakSet;return{Rule(l,{result:i}){if(s.has(l))return;if(!l.selector.toLowerCase().includes(n))return;const a=l.selectors.flatMap((s=>{if(!s.toLowerCase().includes(n))return[s];let a;try{a=e().astSync(s)}catch(e){return l.warn(i,`Failed to parse selector : "${s}" with message: "${e instanceof Error?e.message:e}"`),s}if(void 0===a)return[s];let c=!1;if(a.walkPseudos((e=>{e.value.toLowerCase()===n&&(e.nodes&&e.nodes.length||(c=!0,e.replaceWith(r.clone({}))))})),!c)return[s];const d=a.clone();if(!o.disablePolyfillReadyClass){if(a.nodes?.[0]?.nodes?.length)for(let s=0;s{e.warn(s,`${o.replaceWith} is not a valid replacement since it can't be applied to single elements.`)}}};creator.postcss=!0,module.exports=creator; diff --git a/plugins/postcss-focus-within/dist/index.d.ts b/plugins/postcss-focus-within/dist/index.d.ts index 864b359f3..767fddfc3 100644 --- a/plugins/postcss-focus-within/dist/index.d.ts +++ b/plugins/postcss-focus-within/dist/index.d.ts @@ -1,6 +1,10 @@ import type { PluginCreator } from 'postcss'; + +declare const creator: PluginCreator; +export default creator; + /** postcss-focus-within plugin options */ -export type pluginOptions = { +export declare type pluginOptions = { /** Preserve the original notation. default: true */ preserve?: boolean; /** The replacement class to be used in the polyfill. default: "[focus-within]" */ @@ -8,5 +12,5 @@ export type pluginOptions = { /** Disable the selector prefix that is used to prevent a flash of incorrectly styled content. default: false */ disablePolyfillReadyClass?: boolean; }; -declare const creator: PluginCreator; -export default creator; + +export { } diff --git a/plugins/postcss-focus-within/dist/index.mjs b/plugins/postcss-focus-within/dist/index.mjs index dac634ba6..c852057c1 100644 --- a/plugins/postcss-focus-within/dist/index.mjs +++ b/plugins/postcss-focus-within/dist/index.mjs @@ -1 +1 @@ -import e from"postcss-selector-parser";const s=[" ",">","~",":","+","@","#","(",")"];function isValidReplacement(e){let n=!0;for(let t=0,o=s.length;t-1&&(n=!1);return n}const n="js-focus-within",t=":focus-within",creator=s=>{const o=Object.assign({preserve:!0,replaceWith:"[focus-within]",disablePolyfillReadyClass:!1},s),l=e().astSync(o.replaceWith);return isValidReplacement(o.replaceWith)?{postcssPlugin:"postcss-focus-within",prepare(){const s=new WeakSet;return{Rule(r,{result:a}){if(s.has(r))return;if(!r.selector.toLowerCase().includes(t))return;const i=r.selectors.flatMap((s=>{if(!s.toLowerCase().includes(t))return[s];let i;try{i=e().astSync(s)}catch(e){return r.warn(a,`Failed to parse selector : "${s}" with message: "${e instanceof Error?e.message:e}"`),s}if(void 0===i)return[s];let c=!1;if(i.walkPseudos((e=>{e.value.toLowerCase()===t&&(e.nodes&&e.nodes.length||(c=!0,e.replaceWith(l.clone({}))))})),!c)return[s];const d=i.clone();if(!o.disablePolyfillReadyClass){var u,p;if(null!=(u=i.nodes)&&null!=(u=u[0])&&null!=(u=u.nodes)&&u.length)for(let s=0;s{e.warn(s,`${o.replaceWith} is not a valid replacement since it can't be applied to single elements.`)}}};creator.postcss=!0;export{creator as default}; +import e from"postcss-selector-parser";const s=[" ",">","~",":","+","@","#","(",")"];function isValidReplacement(e){let t=!0;for(let n=0,o=s.length;n-1&&(t=!1);return t}const t="js-focus-within",n=":focus-within",creator=s=>{const o=Object.assign({preserve:!0,replaceWith:"[focus-within]",disablePolyfillReadyClass:!1},s),r=e().astSync(o.replaceWith);return isValidReplacement(o.replaceWith)?{postcssPlugin:"postcss-focus-within",prepare(){const s=new WeakSet;return{Rule(l,{result:a}){if(s.has(l))return;if(!l.selector.toLowerCase().includes(n))return;const i=l.selectors.flatMap((s=>{if(!s.toLowerCase().includes(n))return[s];let i;try{i=e().astSync(s)}catch(e){return l.warn(a,`Failed to parse selector : "${s}" with message: "${e instanceof Error?e.message:e}"`),s}if(void 0===i)return[s];let c=!1;if(i.walkPseudos((e=>{e.value.toLowerCase()===n&&(e.nodes&&e.nodes.length||(c=!0,e.replaceWith(r.clone({}))))})),!c)return[s];const d=i.clone();if(!o.disablePolyfillReadyClass){if(i.nodes?.[0]?.nodes?.length)for(let s=0;s{e.warn(s,`${o.replaceWith} is not a valid replacement since it can't be applied to single elements.`)}}};creator.postcss=!0;export{creator as default}; diff --git a/plugins/postcss-focus-within/package.json b/plugins/postcss-focus-within/package.json index 764d0f6a7..40f180390 100644 --- a/plugins/postcss-focus-within/package.json +++ b/plugins/postcss-focus-within/package.json @@ -31,15 +31,18 @@ "engines": { "node": "^14 || ^16 || >=18" }, + "type": "module", "main": "dist/index.cjs", "module": "dist/index.mjs", - "types": "dist/index.d.ts", "exports": { ".": { - "types": "./dist/index.d.ts", - "import": "./dist/index.mjs", - "require": "./dist/index.cjs", - "default": "./dist/index.mjs" + "import": { + "types": "./dist/index.d.ts", + "default": "./dist/index.mjs" + }, + "require": { + "default": "./dist/index.cjs" + } }, "./browser": { "import": "./dist/browser.mjs", diff --git a/plugins/postcss-focus-within/src/index.ts b/plugins/postcss-focus-within/src/index.ts index 4c59579fb..441a3387f 100644 --- a/plugins/postcss-focus-within/src/index.ts +++ b/plugins/postcss-focus-within/src/index.ts @@ -109,6 +109,7 @@ const creator: PluginCreator = (opts?: pluginOptions) => { if (i === selectorAST.nodes[0].nodes.length - 1) { // Append the class to the end of the selector if not combinator or pseudo element was found. + // @ts-expect-error https://github.com/postcss/postcss-selector-parser/pull/284 selectorAST.nodes[0].append(parser.className({ value: POLYFILL_READY_CLASSNAME })); break; } @@ -117,7 +118,9 @@ const creator: PluginCreator = (opts?: pluginOptions) => { if (selectorAST.nodes?.[0]?.nodes) { // Prepend a space combinator and the class to the beginning of the selector. + // @ts-expect-error https://github.com/postcss/postcss-selector-parser/pull/284 selectorASTClone.nodes[0].prepend(parser.combinator({ value: ' ' })); + // @ts-expect-error https://github.com/postcss/postcss-selector-parser/pull/284 selectorASTClone.nodes[0].prepend(parser.className({ value: POLYFILL_READY_CLASSNAME })); } diff --git a/plugins/postcss-font-format-keywords/CHANGELOG.md b/plugins/postcss-font-format-keywords/CHANGELOG.md index 78f767689..73fe11277 100644 --- a/plugins/postcss-font-format-keywords/CHANGELOG.md +++ b/plugins/postcss-font-format-keywords/CHANGELOG.md @@ -1,5 +1,9 @@ # Changes to PostCSS Font Format +### Unreleased (patch) + +- Fix type definitions + ### 3.0.0 _July 3, 2023_ diff --git a/plugins/postcss-font-format-keywords/api-extractor.json b/plugins/postcss-font-format-keywords/api-extractor.json new file mode 100644 index 000000000..42058be51 --- /dev/null +++ b/plugins/postcss-font-format-keywords/api-extractor.json @@ -0,0 +1,4 @@ +{ + "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json", + "extends": "../../api-extractor.json" +} diff --git a/plugins/postcss-font-format-keywords/dist/has-fallback-decl.d.ts b/plugins/postcss-font-format-keywords/dist/has-fallback-decl.d.ts deleted file mode 100644 index d7ae8d890..000000000 --- a/plugins/postcss-font-format-keywords/dist/has-fallback-decl.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import type { Declaration } from 'postcss'; -export declare function hasFallback(node: Declaration): boolean; diff --git a/plugins/postcss-font-format-keywords/dist/index.cjs b/plugins/postcss-font-format-keywords/dist/index.cjs index 7ffbcdcb8..a14a3a26a 100644 --- a/plugins/postcss-font-format-keywords/dist/index.cjs +++ b/plugins/postcss-font-format-keywords/dist/index.cjs @@ -1 +1 @@ -"use strict";var e=require("postcss-value-parser");function hasFallback(e){const t=e.parent;if(!t)return!1;const o=e.prop.toLowerCase(),r=t.index(e);for(let e=0;e{const r="preserve"in Object(o)&&Boolean(null==o?void 0:o.preserve);return{postcssPlugin:"postcss-font-format-keywords",Declaration(o){if("src"!==o.prop.toLowerCase())return;if(!o.value.toLowerCase().includes("format("))return;if(hasFallback(o))return;const n=o.parent;if(!n||"atrule"!==n.type)return;if("font-face"!==n.name.toLowerCase())return;const s=e(o.value);s.walk((o=>{"function"===o.type&&"format"===o.value.toLowerCase()&&o.nodes.forEach((o=>{"word"===o.type&&t.includes(o.value.toLowerCase())&&(o.value=e.stringify({type:"string",value:o.value,quote:'"'}))}))})),s.toString()!==o.value&&(o.cloneBefore({value:s.toString()}),r||o.remove())}}};creator.postcss=!0,module.exports=creator; +"use strict";var e=require("postcss-value-parser");function hasFallback(e){const t=e.parent;if(!t)return!1;const o=e.prop.toLowerCase(),r=t.index(e);for(let e=0;e{const r="preserve"in Object(o)&&Boolean(o?.preserve);return{postcssPlugin:"postcss-font-format-keywords",Declaration(o){if("src"!==o.prop.toLowerCase())return;if(!o.value.toLowerCase().includes("format("))return;if(hasFallback(o))return;const s=o.parent;if(!s||"atrule"!==s.type)return;if("font-face"!==s.name.toLowerCase())return;const n=e(o.value);n.walk((o=>{"function"===o.type&&"format"===o.value.toLowerCase()&&o.nodes.forEach((o=>{"word"===o.type&&t.includes(o.value.toLowerCase())&&(o.value=e.stringify({type:"string",value:o.value,quote:'"'}))}))})),n.toString()!==o.value&&(o.cloneBefore({value:n.toString()}),r||o.remove())}}};creator.postcss=!0,module.exports=creator; diff --git a/plugins/postcss-font-format-keywords/dist/index.d.ts b/plugins/postcss-font-format-keywords/dist/index.d.ts index 08f712031..4bc6e82c7 100644 --- a/plugins/postcss-font-format-keywords/dist/index.d.ts +++ b/plugins/postcss-font-format-keywords/dist/index.d.ts @@ -1,8 +1,12 @@ import type { PluginCreator } from 'postcss'; + +declare const creator: PluginCreator; +export default creator; + /** postcss-font-format-keywords plugin options */ -export type pluginOptions = { +export declare type pluginOptions = { /** Preserve the original notation. default: false */ preserve?: boolean; }; -declare const creator: PluginCreator; -export default creator; + +export { } diff --git a/plugins/postcss-font-format-keywords/dist/index.mjs b/plugins/postcss-font-format-keywords/dist/index.mjs index 896d2b413..4c88bb7a7 100644 --- a/plugins/postcss-font-format-keywords/dist/index.mjs +++ b/plugins/postcss-font-format-keywords/dist/index.mjs @@ -1 +1 @@ -import e from"postcss-value-parser";function hasFallback(e){const o=e.parent;if(!o)return!1;const t=e.prop.toLowerCase(),r=o.index(e);for(let e=0;e{const r="preserve"in Object(t)&&Boolean(null==t?void 0:t.preserve);return{postcssPlugin:"postcss-font-format-keywords",Declaration(t){if("src"!==t.prop.toLowerCase())return;if(!t.value.toLowerCase().includes("format("))return;if(hasFallback(t))return;const n=t.parent;if(!n||"atrule"!==n.type)return;if("font-face"!==n.name.toLowerCase())return;const s=e(t.value);s.walk((t=>{"function"===t.type&&"format"===t.value.toLowerCase()&&t.nodes.forEach((t=>{"word"===t.type&&o.includes(t.value.toLowerCase())&&(t.value=e.stringify({type:"string",value:t.value,quote:'"'}))}))})),s.toString()!==t.value&&(t.cloneBefore({value:s.toString()}),r||t.remove())}}};creator.postcss=!0;export{creator as default}; +import e from"postcss-value-parser";function hasFallback(e){const t=e.parent;if(!t)return!1;const o=e.prop.toLowerCase(),r=t.index(e);for(let e=0;e{const r="preserve"in Object(o)&&Boolean(o?.preserve);return{postcssPlugin:"postcss-font-format-keywords",Declaration(o){if("src"!==o.prop.toLowerCase())return;if(!o.value.toLowerCase().includes("format("))return;if(hasFallback(o))return;const n=o.parent;if(!n||"atrule"!==n.type)return;if("font-face"!==n.name.toLowerCase())return;const s=e(o.value);s.walk((o=>{"function"===o.type&&"format"===o.value.toLowerCase()&&o.nodes.forEach((o=>{"word"===o.type&&t.includes(o.value.toLowerCase())&&(o.value=e.stringify({type:"string",value:o.value,quote:'"'}))}))})),s.toString()!==o.value&&(o.cloneBefore({value:s.toString()}),r||o.remove())}}};creator.postcss=!0;export{creator as default}; diff --git a/plugins/postcss-font-format-keywords/package.json b/plugins/postcss-font-format-keywords/package.json index 2f41adca7..240bcff02 100644 --- a/plugins/postcss-font-format-keywords/package.json +++ b/plugins/postcss-font-format-keywords/package.json @@ -17,15 +17,18 @@ "engines": { "node": "^14 || ^16 || >=18" }, + "type": "module", "main": "dist/index.cjs", "module": "dist/index.mjs", - "types": "dist/index.d.ts", "exports": { ".": { - "types": "./dist/index.d.ts", - "import": "./dist/index.mjs", - "require": "./dist/index.cjs", - "default": "./dist/index.mjs" + "import": { + "types": "./dist/index.d.ts", + "default": "./dist/index.mjs" + }, + "require": { + "default": "./dist/index.cjs" + } } }, "files": [ diff --git a/plugins/postcss-gamut-mapping/CHANGELOG.md b/plugins/postcss-gamut-mapping/CHANGELOG.md index 646591c85..d769d183c 100644 --- a/plugins/postcss-gamut-mapping/CHANGELOG.md +++ b/plugins/postcss-gamut-mapping/CHANGELOG.md @@ -1,5 +1,9 @@ # Changes to PostCSS gamut-mapping +### Unreleased (patch) + +- Fix type definitions + ### 1.0.0 _October 9, 2023_ diff --git a/plugins/postcss-gamut-mapping/api-extractor.json b/plugins/postcss-gamut-mapping/api-extractor.json new file mode 100644 index 000000000..42058be51 --- /dev/null +++ b/plugins/postcss-gamut-mapping/api-extractor.json @@ -0,0 +1,4 @@ +{ + "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json", + "extends": "../../api-extractor.json" +} diff --git a/plugins/postcss-gamut-mapping/dist/has-conditional-ancestor.d.ts b/plugins/postcss-gamut-mapping/dist/has-conditional-ancestor.d.ts deleted file mode 100644 index 7c0862708..000000000 --- a/plugins/postcss-gamut-mapping/dist/has-conditional-ancestor.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import type { Node } from 'postcss'; -export declare function hasConditionalAncestor(node: Node): boolean; diff --git a/plugins/postcss-gamut-mapping/dist/has-override-decl.d.ts b/plugins/postcss-gamut-mapping/dist/has-override-decl.d.ts deleted file mode 100644 index e98c4f8ab..000000000 --- a/plugins/postcss-gamut-mapping/dist/has-override-decl.d.ts +++ /dev/null @@ -1,5 +0,0 @@ -import type { Declaration } from 'postcss'; -export declare function hasOverrideOrFallback(node: Declaration): { - hasOverride: boolean; - hasFallback: boolean; -}; diff --git a/plugins/postcss-gamut-mapping/dist/index.cjs b/plugins/postcss-gamut-mapping/dist/index.cjs index 77030d6a5..e8bf04db2 100644 --- a/plugins/postcss-gamut-mapping/dist/index.cjs +++ b/plugins/postcss-gamut-mapping/dist/index.cjs @@ -1 +1 @@ -"use strict";var e=require("@csstools/css-tokenizer"),o=require("@csstools/css-parser-algorithms"),a=require("@csstools/css-color-parser");const t=/\bcolor-gamut\b/i;function hasConditionalAncestor(e){let o=e.parent;for(;o;)if("atrule"===o.type){if("media"===o.name.toLowerCase()&&t.test(o.params))return!0;o=o.parent}else o=o.parent;return!1}function hasOverrideOrFallback(e){var o;const a=e.prop.toLowerCase();let t=!1,s=!1;const r=(null==(o=e.parent)?void 0:o.nodes)??[],n=r.indexOf(e);for(let e=0;e({postcssPlugin:"postcss-gamut-mapping",prepare(){const t=new WeakMap;return{OnceExit:(n,{postcss:l})=>{n.walkDecls((n=>{const i=n.value;if(!s.test(i))return;if(!n.parent||hasConditionalAncestor(n))return;const{hasOverride:c,hasFallback:p}=hasOverrideOrFallback(n);if(c)return;const u=t.get(n.parent)||{conditionalRules:[],propNames:new Set,lastConditionParams:{media:void 0},lastConditionalRule:void 0};t.set(n.parent,u);let d=!1;const m=o.replaceComponentValues(o.parseCommaSeparatedListOfComponentValues(e.tokenize({css:i})),(e=>{if(!o.isFunctionNode(e)||!r.test(e.getName()))return;const t=a.color(e);return!t||t.syntaxFlags.has(a.SyntaxFlag.HasNoneKeywords)||a.colorDataFitsRGB_Gamut(t)?void 0:(d||a.colorDataFitsDisplayP3_Gamut(t)||(d=!0),a.serializeRGB(t,!0))})),f=o.stringify(m);if(f===i)return;const v=`(color-gamut: ${d?"rec2020":"p3"})`;if(u.lastConditionParams.media!==v&&(u.lastConditionalRule=void 0),u.lastConditionalRule)return p||n.cloneBefore({value:f}),u.lastConditionalRule.append(n.clone()),void n.remove();p||n.cloneBefore({value:f});const h=l.atRule({name:"media",params:v,source:n.parent.source,raws:{before:"\n\n",after:"\n"}}),C=n.parent.clone();C.removeAll(),C.raws.before="\n",C.append(n.clone()),n.remove(),u.lastConditionParams.media=h.params,u.lastConditionalRule=C,h.append(C),u.conditionalRules.push(h)})),n.walk((e=>{const o=t.get(e);o&&0!==o.conditionalRules.length&&o.conditionalRules.reverse().forEach((o=>{e.after(o)}))}))}}}});creator.postcss=!0,module.exports=creator; +"use strict";var e=require("@csstools/css-tokenizer"),o=require("@csstools/css-parser-algorithms"),a=require("@csstools/css-color-parser");const t=/\bcolor-gamut\b/i;function hasConditionalAncestor(e){let o=e.parent;for(;o;)if("atrule"===o.type){if("media"===o.name.toLowerCase()&&t.test(o.params))return!0;o=o.parent}else o=o.parent;return!1}function hasOverrideOrFallback(e){const o=e.prop.toLowerCase();let a=!1,t=!1;const s=e.parent?.nodes??[],r=s.indexOf(e);for(let e=0;e({postcssPlugin:"postcss-gamut-mapping",prepare(){const t=new WeakMap;return{OnceExit:(n,{postcss:l})=>{n.walkDecls((n=>{const i=n.value;if(!s.test(i))return;if(!n.parent||hasConditionalAncestor(n))return;const{hasOverride:c,hasFallback:p}=hasOverrideOrFallback(n);if(c)return;const u=t.get(n.parent)||{conditionalRules:[],propNames:new Set,lastConditionParams:{media:void 0},lastConditionalRule:void 0};t.set(n.parent,u);let d=!1;const m=o.replaceComponentValues(o.parseCommaSeparatedListOfComponentValues(e.tokenize({css:i})),(e=>{if(!o.isFunctionNode(e)||!r.test(e.getName()))return;const t=a.color(e);return!t||t.syntaxFlags.has(a.SyntaxFlag.HasNoneKeywords)||a.colorDataFitsRGB_Gamut(t)?void 0:(d||a.colorDataFitsDisplayP3_Gamut(t)||(d=!0),a.serializeRGB(t,!0))})),f=o.stringify(m);if(f===i)return;const h=`(color-gamut: ${d?"rec2020":"p3"})`;if(u.lastConditionParams.media!==h&&(u.lastConditionalRule=void 0),u.lastConditionalRule)return p||n.cloneBefore({value:f}),u.lastConditionalRule.append(n.clone()),void n.remove();p||n.cloneBefore({value:f});const v=l.atRule({name:"media",params:h,source:n.parent.source,raws:{before:"\n\n",after:"\n"}}),C=n.parent.clone();C.removeAll(),C.raws.before="\n",C.append(n.clone()),n.remove(),u.lastConditionParams.media=v.params,u.lastConditionalRule=C,v.append(C),u.conditionalRules.push(v)})),n.walk((e=>{const o=t.get(e);o&&0!==o.conditionalRules.length&&o.conditionalRules.reverse().forEach((o=>{e.after(o)}))}))}}}});creator.postcss=!0,module.exports=creator; diff --git a/plugins/postcss-gamut-mapping/dist/index.d.ts b/plugins/postcss-gamut-mapping/dist/index.d.ts index cf42343c3..c8f9aec3a 100644 --- a/plugins/postcss-gamut-mapping/dist/index.d.ts +++ b/plugins/postcss-gamut-mapping/dist/index.d.ts @@ -1,5 +1,9 @@ import type { PluginCreator } from 'postcss'; -/** postcss-gamut-mapping plugin options */ -export type pluginOptions = never; + declare const creator: PluginCreator; export default creator; + +/** postcss-gamut-mapping plugin options */ +export declare type pluginOptions = never; + +export { } diff --git a/plugins/postcss-gamut-mapping/dist/index.mjs b/plugins/postcss-gamut-mapping/dist/index.mjs index 1899c2c47..d4355811a 100644 --- a/plugins/postcss-gamut-mapping/dist/index.mjs +++ b/plugins/postcss-gamut-mapping/dist/index.mjs @@ -1 +1 @@ -import{tokenize as e}from"@csstools/css-tokenizer";import{replaceComponentValues as o,parseCommaSeparatedListOfComponentValues as t,isFunctionNode as a,stringify as r}from"@csstools/css-parser-algorithms";import{color as n,SyntaxFlag as s,colorDataFitsRGB_Gamut as l,colorDataFitsDisplayP3_Gamut as i,serializeRGB as c}from"@csstools/css-color-parser";const p=/\bcolor-gamut\b/i;function hasConditionalAncestor(e){let o=e.parent;for(;o;)if("atrule"===o.type){if("media"===o.name.toLowerCase()&&p.test(o.params))return!0;o=o.parent}else o=o.parent;return!1}function hasOverrideOrFallback(e){var o;const t=e.prop.toLowerCase();let a=!1,r=!1;const n=(null==(o=e.parent)?void 0:o.nodes)??[],s=n.indexOf(e);for(let e=0;e({postcssPlugin:"postcss-gamut-mapping",prepare(){const p=new WeakMap;return{OnceExit:(m,{postcss:f})=>{m.walkDecls((m=>{const h=m.value;if(!d.test(h))return;if(!m.parent||hasConditionalAncestor(m))return;const{hasOverride:v,hasFallback:b}=hasOverrideOrFallback(m);if(v)return;const k=p.get(m.parent)||{conditionalRules:[],propNames:new Set,lastConditionParams:{media:void 0},lastConditionalRule:void 0};p.set(m.parent,k);let C=!1;const g=o(t(e({css:h})),(e=>{if(!a(e)||!u.test(e.getName()))return;const o=n(e);return!o||o.syntaxFlags.has(s.HasNoneKeywords)||l(o)?void 0:(C||i(o)||(C=!0),c(o,!0))})),w=r(g);if(w===h)return;const R=`(color-gamut: ${C?"rec2020":"p3"})`;if(k.lastConditionParams.media!==R&&(k.lastConditionalRule=void 0),k.lastConditionalRule)return b||m.cloneBefore({value:w}),k.lastConditionalRule.append(m.clone()),void m.remove();b||m.cloneBefore({value:w});const O=f.atRule({name:"media",params:R,source:m.parent.source,raws:{before:"\n\n",after:"\n"}}),F=m.parent.clone();F.removeAll(),F.raws.before="\n",F.append(m.clone()),m.remove(),k.lastConditionParams.media=O.params,k.lastConditionalRule=F,O.append(F),k.conditionalRules.push(O)})),m.walk((e=>{const o=p.get(e);o&&0!==o.conditionalRules.length&&o.conditionalRules.reverse().forEach((o=>{e.after(o)}))}))}}}});creator.postcss=!0;export{creator as default}; +import{tokenize as e}from"@csstools/css-tokenizer";import{replaceComponentValues as o,parseCommaSeparatedListOfComponentValues as t,isFunctionNode as a,stringify as r}from"@csstools/css-parser-algorithms";import{color as s,SyntaxFlag as n,colorDataFitsRGB_Gamut as l,colorDataFitsDisplayP3_Gamut as i,serializeRGB as c}from"@csstools/css-color-parser";const p=/\bcolor-gamut\b/i;function hasConditionalAncestor(e){let o=e.parent;for(;o;)if("atrule"===o.type){if("media"===o.name.toLowerCase()&&p.test(o.params))return!0;o=o.parent}else o=o.parent;return!1}function hasOverrideOrFallback(e){const o=e.prop.toLowerCase();let t=!1,a=!1;const r=e.parent?.nodes??[],s=r.indexOf(e);for(let e=0;e({postcssPlugin:"postcss-gamut-mapping",prepare(){const p=new WeakMap;return{OnceExit:(m,{postcss:f})=>{m.walkDecls((m=>{const h=m.value;if(!d.test(h))return;if(!m.parent||hasConditionalAncestor(m))return;const{hasOverride:v,hasFallback:b}=hasOverrideOrFallback(m);if(v)return;const k=p.get(m.parent)||{conditionalRules:[],propNames:new Set,lastConditionParams:{media:void 0},lastConditionalRule:void 0};p.set(m.parent,k);let C=!1;const g=o(t(e({css:h})),(e=>{if(!a(e)||!u.test(e.getName()))return;const o=s(e);return!o||o.syntaxFlags.has(n.HasNoneKeywords)||l(o)?void 0:(C||i(o)||(C=!0),c(o,!0))})),w=r(g);if(w===h)return;const R=`(color-gamut: ${C?"rec2020":"p3"})`;if(k.lastConditionParams.media!==R&&(k.lastConditionalRule=void 0),k.lastConditionalRule)return b||m.cloneBefore({value:w}),k.lastConditionalRule.append(m.clone()),void m.remove();b||m.cloneBefore({value:w});const O=f.atRule({name:"media",params:R,source:m.parent.source,raws:{before:"\n\n",after:"\n"}}),F=m.parent.clone();F.removeAll(),F.raws.before="\n",F.append(m.clone()),m.remove(),k.lastConditionParams.media=O.params,k.lastConditionalRule=F,O.append(F),k.conditionalRules.push(O)})),m.walk((e=>{const o=p.get(e);o&&0!==o.conditionalRules.length&&o.conditionalRules.reverse().forEach((o=>{e.after(o)}))}))}}}});creator.postcss=!0;export{creator as default}; diff --git a/plugins/postcss-gamut-mapping/package.json b/plugins/postcss-gamut-mapping/package.json index 452555188..91aa4b15f 100644 --- a/plugins/postcss-gamut-mapping/package.json +++ b/plugins/postcss-gamut-mapping/package.json @@ -27,15 +27,18 @@ "engines": { "node": "^14 || ^16 || >=18" }, + "type": "module", "main": "dist/index.cjs", "module": "dist/index.mjs", - "types": "dist/index.d.ts", "exports": { ".": { - "types": "./dist/index.d.ts", - "import": "./dist/index.mjs", - "require": "./dist/index.cjs", - "default": "./dist/index.mjs" + "import": { + "types": "./dist/index.d.ts", + "default": "./dist/index.mjs" + }, + "require": { + "default": "./dist/index.cjs" + } } }, "files": [ diff --git a/plugins/postcss-gap-properties/CHANGELOG.md b/plugins/postcss-gap-properties/CHANGELOG.md index 4e948d8e4..ccffc715e 100644 --- a/plugins/postcss-gap-properties/CHANGELOG.md +++ b/plugins/postcss-gap-properties/CHANGELOG.md @@ -1,5 +1,9 @@ # Changes to PostCSS Gap Properties +### Unreleased (patch) + +- Fix type definitions + ### 5.0.0 _July 3, 2023_ diff --git a/plugins/postcss-gap-properties/api-extractor.json b/plugins/postcss-gap-properties/api-extractor.json new file mode 100644 index 000000000..42058be51 --- /dev/null +++ b/plugins/postcss-gap-properties/api-extractor.json @@ -0,0 +1,4 @@ +{ + "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json", + "extends": "../../api-extractor.json" +} diff --git a/plugins/postcss-gap-properties/dist/index.cjs b/plugins/postcss-gap-properties/dist/index.cjs index 7af188d73..9e3db0314 100644 --- a/plugins/postcss-gap-properties/dist/index.cjs +++ b/plugins/postcss-gap-properties/dist/index.cjs @@ -1 +1 @@ -"use strict";const e=["column-gap","gap","row-gap"],creator=o=>{const r=Object.assign({preserve:!0},o);return{postcssPlugin:"postcss-gap-properties",Declaration(o){var s,p;if(!e.includes(o.prop.toLowerCase()))return;if(!(null!=(s=o.parent)&&s.some((e=>"decl"===e.type&&("display"===e.prop.toLowerCase()&&"grid"===e.value.toLowerCase())))))return;const t=`grid-${o.prop.toLowerCase()}`;(null==(p=o.parent)?void 0:p.some((e=>"decl"===e.type&&e.prop.toLowerCase()===t)))||(o.cloneBefore({prop:t}),r.preserve||o.remove())}}};creator.postcss=!0,module.exports=creator; +"use strict";const e=["column-gap","gap","row-gap"],creator=o=>{const r=Object.assign({preserve:!0},o);return{postcssPlugin:"postcss-gap-properties",Declaration(o){if(!e.includes(o.prop.toLowerCase()))return;if(!o.parent?.some((e=>"decl"===e.type&&("display"===e.prop.toLowerCase()&&"grid"===e.value.toLowerCase()))))return;const s=`grid-${o.prop.toLowerCase()}`,p=o.parent?.some((e=>"decl"===e.type&&e.prop.toLowerCase()===s));p||(o.cloneBefore({prop:s}),r.preserve||o.remove())}}};creator.postcss=!0,module.exports=creator; diff --git a/plugins/postcss-gap-properties/dist/index.d.ts b/plugins/postcss-gap-properties/dist/index.d.ts index 8330bff7f..2cc7af8f7 100644 --- a/plugins/postcss-gap-properties/dist/index.d.ts +++ b/plugins/postcss-gap-properties/dist/index.d.ts @@ -1,8 +1,12 @@ import type { PluginCreator } from 'postcss'; + +declare const creator: PluginCreator; +export default creator; + /** postcss-gap-properties plugin options */ -export type pluginOptions = { +export declare type pluginOptions = { /** Preserve the original notation. default: true */ preserve?: boolean; }; -declare const creator: PluginCreator; -export default creator; + +export { } diff --git a/plugins/postcss-gap-properties/dist/index.mjs b/plugins/postcss-gap-properties/dist/index.mjs index 604df9aee..f4883c97c 100644 --- a/plugins/postcss-gap-properties/dist/index.mjs +++ b/plugins/postcss-gap-properties/dist/index.mjs @@ -1 +1 @@ -const e=["column-gap","gap","row-gap"],creator=o=>{const r=Object.assign({preserve:!0},o);return{postcssPlugin:"postcss-gap-properties",Declaration(o){var p,s;if(!e.includes(o.prop.toLowerCase()))return;if(!(null!=(p=o.parent)&&p.some((e=>"decl"===e.type&&("display"===e.prop.toLowerCase()&&"grid"===e.value.toLowerCase())))))return;const t=`grid-${o.prop.toLowerCase()}`;(null==(s=o.parent)?void 0:s.some((e=>"decl"===e.type&&e.prop.toLowerCase()===t)))||(o.cloneBefore({prop:t}),r.preserve||o.remove())}}};creator.postcss=!0;export{creator as default}; +const e=["column-gap","gap","row-gap"],creator=o=>{const r=Object.assign({preserve:!0},o);return{postcssPlugin:"postcss-gap-properties",Declaration(o){if(!e.includes(o.prop.toLowerCase()))return;if(!o.parent?.some((e=>"decl"===e.type&&("display"===e.prop.toLowerCase()&&"grid"===e.value.toLowerCase()))))return;const p=`grid-${o.prop.toLowerCase()}`,s=o.parent?.some((e=>"decl"===e.type&&e.prop.toLowerCase()===p));s||(o.cloneBefore({prop:p}),r.preserve||o.remove())}}};creator.postcss=!0;export{creator as default}; diff --git a/plugins/postcss-gap-properties/package.json b/plugins/postcss-gap-properties/package.json index bea3e4b26..22fbb13af 100644 --- a/plugins/postcss-gap-properties/package.json +++ b/plugins/postcss-gap-properties/package.json @@ -31,15 +31,18 @@ "engines": { "node": "^14 || ^16 || >=18" }, + "type": "module", "main": "dist/index.cjs", "module": "dist/index.mjs", - "types": "dist/index.d.ts", "exports": { ".": { - "types": "./dist/index.d.ts", - "import": "./dist/index.mjs", - "require": "./dist/index.cjs", - "default": "./dist/index.mjs" + "import": { + "types": "./dist/index.d.ts", + "default": "./dist/index.mjs" + }, + "require": { + "default": "./dist/index.cjs" + } } }, "files": [ diff --git a/plugins/postcss-global-data/CHANGELOG.md b/plugins/postcss-global-data/CHANGELOG.md index fd11ad781..1cc8d6451 100644 --- a/plugins/postcss-global-data/CHANGELOG.md +++ b/plugins/postcss-global-data/CHANGELOG.md @@ -1,5 +1,9 @@ # Changes to PostCSS global-data +### Unreleased (patch) + +- Fix type definitions + ### 2.1.0 _August 28, 2023_ diff --git a/plugins/postcss-global-data/api-extractor.json b/plugins/postcss-global-data/api-extractor.json new file mode 100644 index 000000000..42058be51 --- /dev/null +++ b/plugins/postcss-global-data/api-extractor.json @@ -0,0 +1,4 @@ +{ + "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json", + "extends": "../../api-extractor.json" +} diff --git a/plugins/postcss-global-data/dist/index.cjs b/plugins/postcss-global-data/dist/index.cjs index 9f5b3a230..dddab85e0 100644 --- a/plugins/postcss-global-data/dist/index.cjs +++ b/plugins/postcss-global-data/dist/index.cjs @@ -1 +1 @@ -"use strict";var e=require("path"),r=require("fs"),s=require("module");function parseImport(t,o,a,n){var c;let l="";try{if(a.startsWith("node_modules://")){l=s.createRequire(process.cwd()).resolve(a.slice(15))}else if(a.startsWith("node_modules:")){l=s.createRequire(process.cwd()).resolve(a.slice(13))}else l=e.resolve(a)}catch(e){throw new Error(`Failed to read ${a} with error ${e instanceof Error?e.message:e}`)}if(n.has(l))return!1;n.add(l),o.result.messages.push({type:"dependency",plugin:"postcss-global-data",file:l,parent:null==(c=t.source)||null==(c=c.input)?void 0:c.file});const i=r.readFileSync(l,"utf8");return o.postcss.parse(i,{from:l})}const creator=e=>{const r=Object.assign({files:[]},e);return{postcssPlugin:"postcss-global-data",prepare(){let e=new Set,s=new Set;return{Once:(t,o)=>{r.files.forEach((r=>{if(e.has(r))return;const a=parseImport(t,o,r,e);a&&a.each((e=>{t.append(e),s.add(e)}))}))},OnceExit:()=>{s.forEach((e=>{e.remove()})),s=new Set,e=new Set}}}}};creator.postcss=!0,module.exports=creator; +"use strict";var e=require("path"),s=require("fs"),r=require("module");function parseImport(t,o,a,c){let n="";try{if(a.startsWith("node_modules://")){n=r.createRequire(process.cwd()).resolve(a.slice(15))}else if(a.startsWith("node_modules:")){n=r.createRequire(process.cwd()).resolve(a.slice(13))}else n=e.resolve(a)}catch(e){throw new Error(`Failed to read ${a} with error ${e instanceof Error?e.message:e}`)}if(c.has(n))return!1;c.add(n),o.result.messages.push({type:"dependency",plugin:"postcss-global-data",file:n,parent:t.source?.input?.file});const i=s.readFileSync(n,"utf8");return o.postcss.parse(i,{from:n})}const creator=e=>{const s=Object.assign({files:[]},e);return{postcssPlugin:"postcss-global-data",prepare(){let e=new Set,r=new Set;return{Once:(t,o)=>{s.files.forEach((s=>{if(e.has(s))return;const a=parseImport(t,o,s,e);a&&a.each((e=>{t.append(e),r.add(e)}))}))},OnceExit:()=>{r.forEach((e=>{e.remove()})),r=new Set,e=new Set}}}}};creator.postcss=!0,module.exports=creator; diff --git a/plugins/postcss-global-data/dist/index.d.ts b/plugins/postcss-global-data/dist/index.d.ts index 2fe0a07c8..4311d5a99 100644 --- a/plugins/postcss-global-data/dist/index.d.ts +++ b/plugins/postcss-global-data/dist/index.d.ts @@ -1,8 +1,12 @@ import type { PluginCreator } from 'postcss'; + +declare const creator: PluginCreator; +export default creator; + /** postcss-global-data plugin options */ -export type pluginOptions = { +export declare type pluginOptions = { /** List of files to be used as context */ files?: Array; }; -declare const creator: PluginCreator; -export default creator; + +export { } diff --git a/plugins/postcss-global-data/dist/index.mjs b/plugins/postcss-global-data/dist/index.mjs index f260c0358..4711b2d8c 100644 --- a/plugins/postcss-global-data/dist/index.mjs +++ b/plugins/postcss-global-data/dist/index.mjs @@ -1 +1 @@ -import e from"path";import r from"fs";import s from"module";function parseImport(t,o,a,n){var c;let l="";try{if(a.startsWith("node_modules://")){l=s.createRequire(process.cwd()).resolve(a.slice(15))}else if(a.startsWith("node_modules:")){l=s.createRequire(process.cwd()).resolve(a.slice(13))}else l=e.resolve(a)}catch(e){throw new Error(`Failed to read ${a} with error ${e instanceof Error?e.message:e}`)}if(n.has(l))return!1;n.add(l),o.result.messages.push({type:"dependency",plugin:"postcss-global-data",file:l,parent:null==(c=t.source)||null==(c=c.input)?void 0:c.file});const i=r.readFileSync(l,"utf8");return o.postcss.parse(i,{from:l})}const creator=e=>{const r=Object.assign({files:[]},e);return{postcssPlugin:"postcss-global-data",prepare(){let e=new Set,s=new Set;return{Once:(t,o)=>{r.files.forEach((r=>{if(e.has(r))return;const a=parseImport(t,o,r,e);a&&a.each((e=>{t.append(e),s.add(e)}))}))},OnceExit:()=>{s.forEach((e=>{e.remove()})),s=new Set,e=new Set}}}}};creator.postcss=!0;export{creator as default}; +import e from"path";import s from"fs";import r from"module";function parseImport(t,o,a,n){let c="";try{if(a.startsWith("node_modules://")){c=r.createRequire(process.cwd()).resolve(a.slice(15))}else if(a.startsWith("node_modules:")){c=r.createRequire(process.cwd()).resolve(a.slice(13))}else c=e.resolve(a)}catch(e){throw new Error(`Failed to read ${a} with error ${e instanceof Error?e.message:e}`)}if(n.has(c))return!1;n.add(c),o.result.messages.push({type:"dependency",plugin:"postcss-global-data",file:c,parent:t.source?.input?.file});const i=s.readFileSync(c,"utf8");return o.postcss.parse(i,{from:c})}const creator=e=>{const s=Object.assign({files:[]},e);return{postcssPlugin:"postcss-global-data",prepare(){let e=new Set,r=new Set;return{Once:(t,o)=>{s.files.forEach((s=>{if(e.has(s))return;const a=parseImport(t,o,s,e);a&&a.each((e=>{t.append(e),r.add(e)}))}))},OnceExit:()=>{r.forEach((e=>{e.remove()})),r=new Set,e=new Set}}}}};creator.postcss=!0;export{creator as default}; diff --git a/plugins/postcss-global-data/dist/parse-import.d.ts b/plugins/postcss-global-data/dist/parse-import.d.ts deleted file mode 100644 index 63a0b8369..000000000 --- a/plugins/postcss-global-data/dist/parse-import.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import type { Helpers, Root } from 'postcss'; -export declare function parseImport(root: Root, postcssHelpers: Helpers, filePath: string, alreadyImported: Set): false | Root; diff --git a/plugins/postcss-global-data/package.json b/plugins/postcss-global-data/package.json index 509254cbf..5aececda8 100644 --- a/plugins/postcss-global-data/package.json +++ b/plugins/postcss-global-data/package.json @@ -27,15 +27,18 @@ "engines": { "node": "^14 || ^16 || >=18" }, + "type": "module", "main": "dist/index.cjs", "module": "dist/index.mjs", - "types": "dist/index.d.ts", "exports": { ".": { - "types": "./dist/index.d.ts", - "import": "./dist/index.mjs", - "require": "./dist/index.cjs", - "default": "./dist/index.mjs" + "import": { + "types": "./dist/index.d.ts", + "default": "./dist/index.mjs" + }, + "require": { + "default": "./dist/index.cjs" + } } }, "files": [ diff --git a/plugins/postcss-gradients-interpolation-method/api-extractor.json b/plugins/postcss-gradients-interpolation-method/api-extractor.json new file mode 100644 index 000000000..42058be51 --- /dev/null +++ b/plugins/postcss-gradients-interpolation-method/api-extractor.json @@ -0,0 +1,4 @@ +{ + "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json", + "extends": "../../api-extractor.json" +} diff --git a/plugins/postcss-gradients-interpolation-method/dist/color-stop-list.d.ts b/plugins/postcss-gradients-interpolation-method/dist/color-stop-list.d.ts deleted file mode 100644 index 4159c39fc..000000000 --- a/plugins/postcss-gradients-interpolation-method/dist/color-stop-list.d.ts +++ /dev/null @@ -1,9 +0,0 @@ -import type { ColorData } from '@csstools/css-color-parser'; -import type { ComponentValue } from '@csstools/css-parser-algorithms'; -import { TokenNode } from '@csstools/css-parser-algorithms'; -export type ColorStop = { - color: ComponentValue; - colorData: ColorData; - position: ComponentValue; -}; -export declare function interpolateColorsInColorStopsList(colorStops: Array, colorSpace: TokenNode, hueInterpolationMethod: TokenNode | null, wideGamut?: boolean): Array | false; diff --git a/plugins/postcss-gradients-interpolation-method/dist/has-fallback-decl.d.ts b/plugins/postcss-gradients-interpolation-method/dist/has-fallback-decl.d.ts deleted file mode 100644 index d7ae8d890..000000000 --- a/plugins/postcss-gradients-interpolation-method/dist/has-fallback-decl.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import type { Declaration } from 'postcss'; -export declare function hasFallback(node: Declaration): boolean; diff --git a/plugins/postcss-gradients-interpolation-method/dist/has-supports-at-rule-ancestor.d.ts b/plugins/postcss-gradients-interpolation-method/dist/has-supports-at-rule-ancestor.d.ts deleted file mode 100644 index a46009ecc..000000000 --- a/plugins/postcss-gradients-interpolation-method/dist/has-supports-at-rule-ancestor.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import type { Node } from 'postcss'; -export declare function hasSupportsAtRuleAncestor(node: Node): boolean; diff --git a/plugins/postcss-gradients-interpolation-method/dist/index.cjs b/plugins/postcss-gradients-interpolation-method/dist/index.cjs index 78741d124..0a4d9bfcc 100644 --- a/plugins/postcss-gradients-interpolation-method/dist/index.cjs +++ b/plugins/postcss-gradients-interpolation-method/dist/index.cjs @@ -1 +1 @@ -"use strict";var e=require("@csstools/postcss-progressive-custom-properties"),o=require("@csstools/css-parser-algorithms"),t=require("@csstools/css-tokenizer"),n=require("@csstools/css-color-parser");const i=/(repeating-)?(linear|radial|conic)-gradient\(.*?in/i,s=/^(repeating-)?(linear|radial|conic)-gradient$/i;function hasFallback(e){const o=e.parent;if(!o)return!1;const t=e.prop.toLowerCase(),n=o.index(e);for(let e=0;e0&&N.some((e=>!o.isCommentNode(e)))&&N.push(new o.TokenNode([t.TokenType.Comma,",",-1,-1,void 0]),new o.WhitespaceNode([[t.TokenType.Whitespace," ",-1,-1,void 0]])),trim([...N,...trim(g)])}function trim(e){let t=0,n=e.length-1;for(let n=0;n=0;t--)if(!o.isWhitespaceNode(e[t])){n=t;break}return e.slice(t,n+1)}const basePlugin=e=>({postcssPlugin:"postcss-gradients-interpolation-method",Declaration(n){if(!i.test(n.value))return;if(hasFallback(n))return;if(hasSupportsAtRuleAncestor(n))return;const s=t.tokenize({css:n.value}),r=o.stringify(o.replaceComponentValues(o.parseCommaSeparatedListOfComponentValues(s),(e=>{if(!o.isFunctionNode(e))return;const t=modifyGradientFunctionComponentValues(e);t&&(e.value=t)})));if(r===n.value)return;const a=o.stringify(o.replaceComponentValues(o.parseCommaSeparatedListOfComponentValues(s),(e=>{if(!o.isFunctionNode(e))return;const t=modifyGradientFunctionComponentValues(e,!0);t&&(e.value=t)})));n.cloneBefore({value:r}),r!==a&&n.cloneBefore({value:a}),null!=e&&e.preserve||n.remove()}});basePlugin.postcss=!0;const postcssPlugin=o=>{const t=Object.assign({enableProgressiveCustomProperties:!0,preserve:!0},o);return t.enableProgressiveCustomProperties?{postcssPlugin:"postcss-gradients-interpolation-method",plugins:[e(),basePlugin(t)]}:basePlugin(t)};postcssPlugin.postcss=!0,module.exports=postcssPlugin; +"use strict";var e=require("@csstools/postcss-progressive-custom-properties"),o=require("@csstools/css-parser-algorithms"),t=require("@csstools/css-tokenizer"),n=require("@csstools/css-color-parser");const i=/(repeating-)?(linear|radial|conic)-gradient\(.*?in/i,s=/^(repeating-)?(linear|radial|conic)-gradient$/i;function hasFallback(e){const o=e.parent;if(!o)return!1;const t=e.prop.toLowerCase(),n=o.index(e);for(let e=0;e0&&N.some((e=>!o.isCommentNode(e)))&&N.push(new o.TokenNode([t.TokenType.Comma,",",-1,-1,void 0]),new o.WhitespaceNode([[t.TokenType.Whitespace," ",-1,-1,void 0]])),trim([...N,...trim(g)])}function trim(e){let t=0,n=e.length-1;for(let n=0;n=0;t--)if(!o.isWhitespaceNode(e[t])){n=t;break}return e.slice(t,n+1)}const basePlugin=e=>({postcssPlugin:"postcss-gradients-interpolation-method",Declaration(n){if(!i.test(n.value))return;if(hasFallback(n))return;if(hasSupportsAtRuleAncestor(n))return;const s=t.tokenize({css:n.value}),r=o.stringify(o.replaceComponentValues(o.parseCommaSeparatedListOfComponentValues(s),(e=>{if(!o.isFunctionNode(e))return;const t=modifyGradientFunctionComponentValues(e);t&&(e.value=t)})));if(r===n.value)return;const a=o.stringify(o.replaceComponentValues(o.parseCommaSeparatedListOfComponentValues(s),(e=>{if(!o.isFunctionNode(e))return;const t=modifyGradientFunctionComponentValues(e,!0);t&&(e.value=t)})));n.cloneBefore({value:r}),r!==a&&n.cloneBefore({value:a}),e?.preserve||n.remove()}});basePlugin.postcss=!0;const postcssPlugin=o=>{const t=Object.assign({enableProgressiveCustomProperties:!0,preserve:!0},o);return t.enableProgressiveCustomProperties?{postcssPlugin:"postcss-gradients-interpolation-method",plugins:[e(),basePlugin(t)]}:basePlugin(t)};postcssPlugin.postcss=!0,module.exports=postcssPlugin; diff --git a/plugins/postcss-gradients-interpolation-method/dist/index.d.ts b/plugins/postcss-gradients-interpolation-method/dist/index.d.ts index 0520e9654..26b20e2f4 100644 --- a/plugins/postcss-gradients-interpolation-method/dist/index.d.ts +++ b/plugins/postcss-gradients-interpolation-method/dist/index.d.ts @@ -1,10 +1,14 @@ import type { PluginCreator } from 'postcss'; + /** postcss-gradients-interpolation-method plugin options */ -export type pluginOptions = { +export declare type pluginOptions = { /** Preserve the original notation. default: true */ preserve?: boolean; /** Enable "@csstools/postcss-progressive-custom-properties". default: true */ enableProgressiveCustomProperties?: boolean; }; + declare const postcssPlugin: PluginCreator; export default postcssPlugin; + +export { } diff --git a/plugins/postcss-gradients-interpolation-method/dist/index.mjs b/plugins/postcss-gradients-interpolation-method/dist/index.mjs index ffbfa92c2..c0dfa7b5a 100644 --- a/plugins/postcss-gradients-interpolation-method/dist/index.mjs +++ b/plugins/postcss-gradients-interpolation-method/dist/index.mjs @@ -1 +1 @@ -import o from"@csstools/postcss-progressive-custom-properties";import{WhitespaceNode as e,TokenNode as t,FunctionNode as r,isCommentNode as n,isWhitespaceNode as i,isTokenNode as s,stringify as l,replaceComponentValues as a,parseCommaSeparatedListOfComponentValues as c,isFunctionNode as u}from"@csstools/css-parser-algorithms";import{TokenType as p,tokenize as f}from"@csstools/css-tokenizer";import{serializeP3 as v,color as h,colorDataFitsRGB_Gamut as m,serializeRGB as d,SyntaxFlag as g}from"@csstools/css-color-parser";const w=/(repeating-)?(linear|radial|conic)-gradient\(.*?in/i,C=/^(repeating-)?(linear|radial|conic)-gradient$/i;function hasFallback(o){const e=o.parent;if(!e)return!1;const t=o.prop.toLowerCase(),r=e.index(o);for(let o=0;o0&&w.some((o=>!n(o)))&&w.push(new t([p.Comma,",",-1,-1,void 0]),new e([[p.Whitespace," ",-1,-1,void 0]])),trim([...w,...trim(g)])}function trim(o){let e=0,t=o.length-1;for(let t=0;t=0;e--)if(!i(o[e])){t=e;break}return o.slice(e,t+1)}const basePlugin=o=>({postcssPlugin:"postcss-gradients-interpolation-method",Declaration(e){if(!w.test(e.value))return;if(hasFallback(e))return;if(hasSupportsAtRuleAncestor(e))return;const t=f({css:e.value}),r=l(a(c(t),(o=>{if(!u(o))return;const e=modifyGradientFunctionComponentValues(o);e&&(o.value=e)})));if(r===e.value)return;const n=l(a(c(t),(o=>{if(!u(o))return;const e=modifyGradientFunctionComponentValues(o,!0);e&&(o.value=e)})));e.cloneBefore({value:r}),r!==n&&e.cloneBefore({value:n}),null!=o&&o.preserve||e.remove()}});basePlugin.postcss=!0;const postcssPlugin=e=>{const t=Object.assign({enableProgressiveCustomProperties:!0,preserve:!0},e);return t.enableProgressiveCustomProperties?{postcssPlugin:"postcss-gradients-interpolation-method",plugins:[o(),basePlugin(t)]}:basePlugin(t)};postcssPlugin.postcss=!0;export{postcssPlugin as default}; +import o from"@csstools/postcss-progressive-custom-properties";import{WhitespaceNode as e,TokenNode as t,FunctionNode as r,isCommentNode as n,isWhitespaceNode as i,isTokenNode as s,stringify as l,replaceComponentValues as a,parseCommaSeparatedListOfComponentValues as c,isFunctionNode as u}from"@csstools/css-parser-algorithms";import{TokenType as p,tokenize as f}from"@csstools/css-tokenizer";import{serializeP3 as v,color as h,colorDataFitsRGB_Gamut as m,serializeRGB as d,SyntaxFlag as g}from"@csstools/css-color-parser";const w=/(repeating-)?(linear|radial|conic)-gradient\(.*?in/i,C=/^(repeating-)?(linear|radial|conic)-gradient$/i;function hasFallback(o){const e=o.parent;if(!e)return!1;const t=o.prop.toLowerCase(),r=e.index(o);for(let o=0;o0&&w.some((o=>!n(o)))&&w.push(new t([p.Comma,",",-1,-1,void 0]),new e([[p.Whitespace," ",-1,-1,void 0]])),trim([...w,...trim(g)])}function trim(o){let e=0,t=o.length-1;for(let t=0;t=0;e--)if(!i(o[e])){t=e;break}return o.slice(e,t+1)}const basePlugin=o=>({postcssPlugin:"postcss-gradients-interpolation-method",Declaration(e){if(!w.test(e.value))return;if(hasFallback(e))return;if(hasSupportsAtRuleAncestor(e))return;const t=f({css:e.value}),r=l(a(c(t),(o=>{if(!u(o))return;const e=modifyGradientFunctionComponentValues(o);e&&(o.value=e)})));if(r===e.value)return;const n=l(a(c(t),(o=>{if(!u(o))return;const e=modifyGradientFunctionComponentValues(o,!0);e&&(o.value=e)})));e.cloneBefore({value:r}),r!==n&&e.cloneBefore({value:n}),o?.preserve||e.remove()}});basePlugin.postcss=!0;const postcssPlugin=e=>{const t=Object.assign({enableProgressiveCustomProperties:!0,preserve:!0},e);return t.enableProgressiveCustomProperties?{postcssPlugin:"postcss-gradients-interpolation-method",plugins:[o(),basePlugin(t)]}:basePlugin(t)};postcssPlugin.postcss=!0;export{postcssPlugin as default}; diff --git a/plugins/postcss-gradients-interpolation-method/dist/is-gradient.d.ts b/plugins/postcss-gradients-interpolation-method/dist/is-gradient.d.ts deleted file mode 100644 index 2d83e89ed..000000000 --- a/plugins/postcss-gradients-interpolation-method/dist/is-gradient.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -export declare const gradientFunctionRegex: RegExp; -export declare const gradientNameRegex: RegExp; diff --git a/plugins/postcss-gradients-interpolation-method/dist/modify-gradient-component-values.d.ts b/plugins/postcss-gradients-interpolation-method/dist/modify-gradient-component-values.d.ts deleted file mode 100644 index 6917bedab..000000000 --- a/plugins/postcss-gradients-interpolation-method/dist/modify-gradient-component-values.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import type { ComponentValue, FunctionNode } from '@csstools/css-parser-algorithms'; -export declare function modifyGradientFunctionComponentValues(gradientFunction: FunctionNode, wideGamut?: boolean): Array | false; diff --git a/plugins/postcss-gradients-interpolation-method/dist/parse-color-stops.d.ts b/plugins/postcss-gradients-interpolation-method/dist/parse-color-stops.d.ts deleted file mode 100644 index 0342da5c6..000000000 --- a/plugins/postcss-gradients-interpolation-method/dist/parse-color-stops.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -import type { ColorStop } from './color-stop-list'; -import type { ComponentValue } from '@csstools/css-parser-algorithms'; -export declare function parseColorStops(componentValues: Array): Array | false; diff --git a/plugins/postcss-gradients-interpolation-method/package.json b/plugins/postcss-gradients-interpolation-method/package.json index b6fdb43e8..112cb13dd 100644 --- a/plugins/postcss-gradients-interpolation-method/package.json +++ b/plugins/postcss-gradients-interpolation-method/package.json @@ -17,15 +17,18 @@ "engines": { "node": "^14 || ^16 || >=18" }, + "type": "module", "main": "dist/index.cjs", "module": "dist/index.mjs", - "types": "dist/index.d.ts", "exports": { ".": { - "types": "./dist/index.d.ts", - "import": "./dist/index.mjs", - "require": "./dist/index.cjs", - "default": "./dist/index.mjs" + "import": { + "types": "./dist/index.d.ts", + "default": "./dist/index.mjs" + }, + "require": { + "default": "./dist/index.cjs" + } } }, "files": [ diff --git a/plugins/postcss-hwb-function/api-extractor.json b/plugins/postcss-hwb-function/api-extractor.json new file mode 100644 index 000000000..42058be51 --- /dev/null +++ b/plugins/postcss-hwb-function/api-extractor.json @@ -0,0 +1,4 @@ +{ + "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json", + "extends": "../../api-extractor.json" +} diff --git a/plugins/postcss-hwb-function/dist/has-fallback-decl.d.ts b/plugins/postcss-hwb-function/dist/has-fallback-decl.d.ts deleted file mode 100644 index d7ae8d890..000000000 --- a/plugins/postcss-hwb-function/dist/has-fallback-decl.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import type { Declaration } from 'postcss'; -export declare function hasFallback(node: Declaration): boolean; diff --git a/plugins/postcss-hwb-function/dist/has-supports-at-rule-ancestor.d.ts b/plugins/postcss-hwb-function/dist/has-supports-at-rule-ancestor.d.ts deleted file mode 100644 index 7fbe0b290..000000000 --- a/plugins/postcss-hwb-function/dist/has-supports-at-rule-ancestor.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -import type { Node } from 'postcss'; -export declare const atSupportsHwbParams = "(color: hwb(0 0% 0%))"; -export declare function hasSupportsAtRuleAncestor(node: Node): boolean; diff --git a/plugins/postcss-hwb-function/dist/index.cjs b/plugins/postcss-hwb-function/dist/index.cjs index 1aae9a5f5..9e4a79aa2 100644 --- a/plugins/postcss-hwb-function/dist/index.cjs +++ b/plugins/postcss-hwb-function/dist/index.cjs @@ -1 +1 @@ -"use strict";var e=require("@csstools/css-color-parser"),t=require("@csstools/css-parser-algorithms"),r=require("@csstools/css-tokenizer");const s="(color: hwb(0 0% 0%))";function hasSupportsAtRuleAncestor(e){let t=e.parent;for(;t;)if("atrule"===t.type){if("supports"===t.name.toLowerCase()&&t.params.includes(s))return!0;t=t.parent}else t=t.parent;return!1}function hasFallback(e){const t=e.parent;if(!t)return!1;const r=e.prop.toLowerCase(),s=t.index(e);for(let e=0;e{const l="preserve"in Object(a)&&Boolean(null==a?void 0:a.preserve);return{postcssPlugin:"postcss-hwb-function",Declaration:(a,{postcss:p})=>{const c=a.value;if(!o.test(c))return;if(l&&hasSupportsAtRuleAncestor(a))return;if(hasFallback(a))return;const u=t.replaceComponentValues(t.parseCommaSeparatedListOfComponentValues(r.tokenize({css:c})),(r=>{if(t.isFunctionNode(r)&&n.test(r.getName())){const t=e.color(r);if(!t)return;if(t.syntaxFlags.has(e.SyntaxFlag.Experimental))return;if(t.syntaxFlags.has(e.SyntaxFlag.HasNoneKeywords))return;if(t.syntaxFlags.has(e.SyntaxFlag.RelativeColorSyntax))return;return e.serializeRGB(t)}})),i=t.stringify(u);if(i!==c)if(a.variable&&l&&a.parent){const e=a.parent,t=p.atRule({name:"supports",params:s,source:a.source}),r=e.clone();r.removeAll(),r.append(a.clone()),t.append(r),insertAtSupportsAfterCorrectRule(t,e,s),a.replaceWith(a.clone({value:i}))}else l?a.cloneBefore({value:i}):a.replaceWith(a.clone({value:i}))}}};function insertAtSupportsAfterCorrectRule(e,t,r){let s=t,o=t.next();for(;s&&o&&"atrule"===o.type&&"supports"===o.name.toLowerCase()&&o.params===r;)s=o,o=o.next();s.after(e)}postcssPlugin.postcss=!0,module.exports=postcssPlugin; +"use strict";var e=require("@csstools/css-color-parser"),t=require("@csstools/css-parser-algorithms"),r=require("@csstools/css-tokenizer");const s="(color: hwb(0 0% 0%))";function hasSupportsAtRuleAncestor(e){let t=e.parent;for(;t;)if("atrule"===t.type){if("supports"===t.name.toLowerCase()&&t.params.includes(s))return!0;t=t.parent}else t=t.parent;return!1}function hasFallback(e){const t=e.parent;if(!t)return!1;const r=e.prop.toLowerCase(),s=t.index(e);for(let e=0;e{const l="preserve"in Object(a)&&Boolean(a?.preserve);return{postcssPlugin:"postcss-hwb-function",Declaration:(a,{postcss:p})=>{const c=a.value;if(!o.test(c))return;if(l&&hasSupportsAtRuleAncestor(a))return;if(hasFallback(a))return;const u=t.replaceComponentValues(t.parseCommaSeparatedListOfComponentValues(r.tokenize({css:c})),(r=>{if(t.isFunctionNode(r)&&n.test(r.getName())){const t=e.color(r);if(!t)return;if(t.syntaxFlags.has(e.SyntaxFlag.Experimental))return;if(t.syntaxFlags.has(e.SyntaxFlag.HasNoneKeywords))return;if(t.syntaxFlags.has(e.SyntaxFlag.RelativeColorSyntax))return;return e.serializeRGB(t)}})),i=t.stringify(u);if(i!==c)if(a.variable&&l&&a.parent){const e=a.parent,t=p.atRule({name:"supports",params:s,source:a.source}),r=e.clone();r.removeAll(),r.append(a.clone()),t.append(r),insertAtSupportsAfterCorrectRule(t,e,s),a.replaceWith(a.clone({value:i}))}else l?a.cloneBefore({value:i}):a.replaceWith(a.clone({value:i}))}}};function insertAtSupportsAfterCorrectRule(e,t,r){let s=t,o=t.next();for(;s&&o&&"atrule"===o.type&&"supports"===o.name.toLowerCase()&&o.params===r;)s=o,o=o.next();s.after(e)}postcssPlugin.postcss=!0,module.exports=postcssPlugin; diff --git a/plugins/postcss-hwb-function/dist/index.d.ts b/plugins/postcss-hwb-function/dist/index.d.ts index 0304f878c..d469e87a8 100644 --- a/plugins/postcss-hwb-function/dist/index.d.ts +++ b/plugins/postcss-hwb-function/dist/index.d.ts @@ -1,9 +1,13 @@ import type { PluginCreator } from 'postcss'; + /** postcss-hwb-function plugin options */ -export type pluginOptions = { +export declare type pluginOptions = { /** Preserve the original notation. default: false */ preserve?: boolean; }; + /** Transform hwb() functions in CSS. */ declare const postcssPlugin: PluginCreator; export default postcssPlugin; + +export { } diff --git a/plugins/postcss-hwb-function/dist/index.mjs b/plugins/postcss-hwb-function/dist/index.mjs index f537127da..a8603a7ac 100644 --- a/plugins/postcss-hwb-function/dist/index.mjs +++ b/plugins/postcss-hwb-function/dist/index.mjs @@ -1 +1 @@ -import{color as e,SyntaxFlag as t,serializeRGB as r}from"@csstools/css-color-parser";import{replaceComponentValues as s,parseCommaSeparatedListOfComponentValues as o,isFunctionNode as n,stringify as a}from"@csstools/css-parser-algorithms";import{tokenize as l}from"@csstools/css-tokenizer";const p="(color: hwb(0 0% 0%))";function hasSupportsAtRuleAncestor(e){let t=e.parent;for(;t;)if("atrule"===t.type){if("supports"===t.name.toLowerCase()&&t.params.includes(p))return!0;t=t.parent}else t=t.parent;return!1}function hasFallback(e){const t=e.parent;if(!t)return!1;const r=e.prop.toLowerCase(),s=t.index(e);for(let e=0;e{const f="preserve"in Object(i)&&Boolean(null==i?void 0:i.preserve);return{postcssPlugin:"postcss-hwb-function",Declaration:(i,{postcss:m})=>{const h=i.value;if(!c.test(h))return;if(f&&hasSupportsAtRuleAncestor(i))return;if(hasFallback(i))return;const v=s(o(l({css:h})),(s=>{if(n(s)&&u.test(s.getName())){const o=e(s);if(!o)return;if(o.syntaxFlags.has(t.Experimental))return;if(o.syntaxFlags.has(t.HasNoneKeywords))return;if(o.syntaxFlags.has(t.RelativeColorSyntax))return;return r(o)}})),d=a(v);if(d!==h)if(i.variable&&f&&i.parent){const e=i.parent,t=m.atRule({name:"supports",params:p,source:i.source}),r=e.clone();r.removeAll(),r.append(i.clone()),t.append(r),insertAtSupportsAfterCorrectRule(t,e,p),i.replaceWith(i.clone({value:d}))}else f?i.cloneBefore({value:d}):i.replaceWith(i.clone({value:d}))}}};function insertAtSupportsAfterCorrectRule(e,t,r){let s=t,o=t.next();for(;s&&o&&"atrule"===o.type&&"supports"===o.name.toLowerCase()&&o.params===r;)s=o,o=o.next();s.after(e)}postcssPlugin.postcss=!0;export{postcssPlugin as default}; +import{color as e,SyntaxFlag as t,serializeRGB as r}from"@csstools/css-color-parser";import{replaceComponentValues as s,parseCommaSeparatedListOfComponentValues as o,isFunctionNode as n,stringify as a}from"@csstools/css-parser-algorithms";import{tokenize as p}from"@csstools/css-tokenizer";const l="(color: hwb(0 0% 0%))";function hasSupportsAtRuleAncestor(e){let t=e.parent;for(;t;)if("atrule"===t.type){if("supports"===t.name.toLowerCase()&&t.params.includes(l))return!0;t=t.parent}else t=t.parent;return!1}function hasFallback(e){const t=e.parent;if(!t)return!1;const r=e.prop.toLowerCase(),s=t.index(e);for(let e=0;e{const f="preserve"in Object(i)&&Boolean(i?.preserve);return{postcssPlugin:"postcss-hwb-function",Declaration:(i,{postcss:m})=>{const h=i.value;if(!c.test(h))return;if(f&&hasSupportsAtRuleAncestor(i))return;if(hasFallback(i))return;const v=s(o(p({css:h})),(s=>{if(n(s)&&u.test(s.getName())){const o=e(s);if(!o)return;if(o.syntaxFlags.has(t.Experimental))return;if(o.syntaxFlags.has(t.HasNoneKeywords))return;if(o.syntaxFlags.has(t.RelativeColorSyntax))return;return r(o)}})),w=a(v);if(w!==h)if(i.variable&&f&&i.parent){const e=i.parent,t=m.atRule({name:"supports",params:l,source:i.source}),r=e.clone();r.removeAll(),r.append(i.clone()),t.append(r),insertAtSupportsAfterCorrectRule(t,e,l),i.replaceWith(i.clone({value:w}))}else f?i.cloneBefore({value:w}):i.replaceWith(i.clone({value:w}))}}};function insertAtSupportsAfterCorrectRule(e,t,r){let s=t,o=t.next();for(;s&&o&&"atrule"===o.type&&"supports"===o.name.toLowerCase()&&o.params===r;)s=o,o=o.next();s.after(e)}postcssPlugin.postcss=!0;export{postcssPlugin as default}; diff --git a/plugins/postcss-hwb-function/package.json b/plugins/postcss-hwb-function/package.json index de60d8d8e..879c7df5c 100644 --- a/plugins/postcss-hwb-function/package.json +++ b/plugins/postcss-hwb-function/package.json @@ -17,15 +17,18 @@ "engines": { "node": "^14 || ^16 || >=18" }, + "type": "module", "main": "dist/index.cjs", "module": "dist/index.mjs", - "types": "./dist/index.d.ts", "exports": { ".": { - "types": "./dist/index.d.ts", - "import": "./dist/index.mjs", - "require": "./dist/index.cjs", - "default": "./dist/index.mjs" + "import": { + "types": "./dist/index.d.ts", + "default": "./dist/index.mjs" + }, + "require": { + "default": "./dist/index.cjs" + } } }, "files": [ diff --git a/plugins/postcss-ic-unit/CHANGELOG.md b/plugins/postcss-ic-unit/CHANGELOG.md index 33354058e..e97a56118 100644 --- a/plugins/postcss-ic-unit/CHANGELOG.md +++ b/plugins/postcss-ic-unit/CHANGELOG.md @@ -1,5 +1,9 @@ # Changes to PostCSS IC Unit +### Unreleased (patch) + +- Fix type definitions + ### 3.0.2 _October 9, 2023_ diff --git a/plugins/postcss-ic-unit/api-extractor.json b/plugins/postcss-ic-unit/api-extractor.json new file mode 100644 index 000000000..42058be51 --- /dev/null +++ b/plugins/postcss-ic-unit/api-extractor.json @@ -0,0 +1,4 @@ +{ + "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json", + "extends": "../../api-extractor.json" +} diff --git a/plugins/postcss-ic-unit/dist/has-fallback-decl.d.ts b/plugins/postcss-ic-unit/dist/has-fallback-decl.d.ts deleted file mode 100644 index d7ae8d890..000000000 --- a/plugins/postcss-ic-unit/dist/has-fallback-decl.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import type { Declaration } from 'postcss'; -export declare function hasFallback(node: Declaration): boolean; diff --git a/plugins/postcss-ic-unit/dist/has-supports-at-rule-ancestor.d.ts b/plugins/postcss-ic-unit/dist/has-supports-at-rule-ancestor.d.ts deleted file mode 100644 index a46009ecc..000000000 --- a/plugins/postcss-ic-unit/dist/has-supports-at-rule-ancestor.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import type { Node } from 'postcss'; -export declare function hasSupportsAtRuleAncestor(node: Node): boolean; diff --git a/plugins/postcss-ic-unit/dist/index.cjs b/plugins/postcss-ic-unit/dist/index.cjs index d85ab48a2..5d207a0ce 100644 --- a/plugins/postcss-ic-unit/dist/index.cjs +++ b/plugins/postcss-ic-unit/dist/index.cjs @@ -1 +1 @@ -"use strict";var e=require("@csstools/postcss-progressive-custom-properties"),s=require("postcss-value-parser");function hasFallback(e){const s=e.parent;if(!s)return!1;const t=e.prop.toLowerCase(),r=s.index(e);for(let e=0;e({postcssPlugin:"postcss-ic-unit",Declaration(r){if(!t.test(r.value))return;if(hasFallback(r))return;if(hasSupportsAtRuleAncestor(r))return;const o=s(r.value);o.walk((e=>{if(!e.type||"word"!==e.type)return;const t=s.unit(e.value);t&&"ic"===t.unit.toLowerCase()&&(e.value=`${t.number}em`)}));const n=String(o);n!==r.value&&(r.cloneBefore({value:n}),null!=e&&e.preserve||r.remove())}});basePlugin.postcss=!0;const postcssPlugin=s=>{const t=Object.assign({preserve:!1,enableProgressiveCustomProperties:!0},s);return t.enableProgressiveCustomProperties&&t.preserve?{postcssPlugin:"postcss-ic-unit",plugins:[e(),basePlugin(t)]}:basePlugin(t)};postcssPlugin.postcss=!0,module.exports=postcssPlugin; +"use strict";var e=require("@csstools/postcss-progressive-custom-properties"),s=require("postcss-value-parser");function hasFallback(e){const s=e.parent;if(!s)return!1;const t=e.prop.toLowerCase(),r=s.index(e);for(let e=0;e({postcssPlugin:"postcss-ic-unit",Declaration(r){if(!t.test(r.value))return;if(hasFallback(r))return;if(hasSupportsAtRuleAncestor(r))return;const o=s(r.value);o.walk((e=>{if(!e.type||"word"!==e.type)return;const t=s.unit(e.value);t&&"ic"===t.unit.toLowerCase()&&(e.value=`${t.number}em`)}));const n=String(o);n!==r.value&&(r.cloneBefore({value:n}),e?.preserve||r.remove())}});basePlugin.postcss=!0;const postcssPlugin=s=>{const t=Object.assign({preserve:!1,enableProgressiveCustomProperties:!0},s);return t.enableProgressiveCustomProperties&&t.preserve?{postcssPlugin:"postcss-ic-unit",plugins:[e(),basePlugin(t)]}:basePlugin(t)};postcssPlugin.postcss=!0,module.exports=postcssPlugin; diff --git a/plugins/postcss-ic-unit/dist/index.d.ts b/plugins/postcss-ic-unit/dist/index.d.ts index 6900fd7d3..d894fc822 100644 --- a/plugins/postcss-ic-unit/dist/index.d.ts +++ b/plugins/postcss-ic-unit/dist/index.d.ts @@ -1,10 +1,14 @@ import type { PluginCreator } from 'postcss'; + /** postcss-ic-unit plugin options */ -export type pluginOptions = { +export declare type pluginOptions = { /** Preserve the original notation. default: false */ preserve?: boolean; /** Enable "@csstools/postcss-progressive-custom-properties". default: true */ enableProgressiveCustomProperties?: boolean; }; + declare const postcssPlugin: PluginCreator; export default postcssPlugin; + +export { } diff --git a/plugins/postcss-ic-unit/dist/index.mjs b/plugins/postcss-ic-unit/dist/index.mjs index ef0b7a838..def48e6ef 100644 --- a/plugins/postcss-ic-unit/dist/index.mjs +++ b/plugins/postcss-ic-unit/dist/index.mjs @@ -1 +1 @@ -import e from"@csstools/postcss-progressive-custom-properties";import s from"postcss-value-parser";function hasFallback(e){const s=e.parent;if(!s)return!1;const t=e.prop.toLowerCase(),r=s.index(e);for(let e=0;e({postcssPlugin:"postcss-ic-unit",Declaration(r){if(!t.test(r.value))return;if(hasFallback(r))return;if(hasSupportsAtRuleAncestor(r))return;const o=s(r.value);o.walk((e=>{if(!e.type||"word"!==e.type)return;const t=s.unit(e.value);t&&"ic"===t.unit.toLowerCase()&&(e.value=`${t.number}em`)}));const n=String(o);n!==r.value&&(r.cloneBefore({value:n}),null!=e&&e.preserve||r.remove())}});basePlugin.postcss=!0;const postcssPlugin=s=>{const t=Object.assign({preserve:!1,enableProgressiveCustomProperties:!0},s);return t.enableProgressiveCustomProperties&&t.preserve?{postcssPlugin:"postcss-ic-unit",plugins:[e(),basePlugin(t)]}:basePlugin(t)};postcssPlugin.postcss=!0;export{postcssPlugin as default}; +import e from"@csstools/postcss-progressive-custom-properties";import s from"postcss-value-parser";function hasFallback(e){const s=e.parent;if(!s)return!1;const t=e.prop.toLowerCase(),r=s.index(e);for(let e=0;e({postcssPlugin:"postcss-ic-unit",Declaration(r){if(!t.test(r.value))return;if(hasFallback(r))return;if(hasSupportsAtRuleAncestor(r))return;const o=s(r.value);o.walk((e=>{if(!e.type||"word"!==e.type)return;const t=s.unit(e.value);t&&"ic"===t.unit.toLowerCase()&&(e.value=`${t.number}em`)}));const n=String(o);n!==r.value&&(r.cloneBefore({value:n}),e?.preserve||r.remove())}});basePlugin.postcss=!0;const postcssPlugin=s=>{const t=Object.assign({preserve:!1,enableProgressiveCustomProperties:!0},s);return t.enableProgressiveCustomProperties&&t.preserve?{postcssPlugin:"postcss-ic-unit",plugins:[e(),basePlugin(t)]}:basePlugin(t)};postcssPlugin.postcss=!0;export{postcssPlugin as default}; diff --git a/plugins/postcss-ic-unit/package.json b/plugins/postcss-ic-unit/package.json index e638c94a0..69298e2b9 100644 --- a/plugins/postcss-ic-unit/package.json +++ b/plugins/postcss-ic-unit/package.json @@ -17,15 +17,18 @@ "engines": { "node": "^14 || ^16 || >=18" }, + "type": "module", "main": "dist/index.cjs", "module": "dist/index.mjs", - "types": "dist/index.d.ts", "exports": { ".": { - "types": "./dist/index.d.ts", - "import": "./dist/index.mjs", - "require": "./dist/index.cjs", - "default": "./dist/index.mjs" + "import": { + "types": "./dist/index.d.ts", + "default": "./dist/index.mjs" + }, + "require": { + "default": "./dist/index.cjs" + } } }, "files": [ diff --git a/plugins/postcss-image-set-function/CHANGELOG.md b/plugins/postcss-image-set-function/CHANGELOG.md index fb2a5dae3..430d991f5 100644 --- a/plugins/postcss-image-set-function/CHANGELOG.md +++ b/plugins/postcss-image-set-function/CHANGELOG.md @@ -1,5 +1,9 @@ # Changes to PostCSS image-set() Function +### Unreleased (patch) + +- Fix type definitions + ### 6.0.1 _September 18, 2023_ diff --git a/plugins/postcss-image-set-function/api-extractor.json b/plugins/postcss-image-set-function/api-extractor.json new file mode 100644 index 000000000..42058be51 --- /dev/null +++ b/plugins/postcss-image-set-function/api-extractor.json @@ -0,0 +1,4 @@ +{ + "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json", + "extends": "../../api-extractor.json" +} diff --git a/plugins/postcss-image-set-function/dist/has-fallback-decl.d.ts b/plugins/postcss-image-set-function/dist/has-fallback-decl.d.ts deleted file mode 100644 index d7ae8d890..000000000 --- a/plugins/postcss-image-set-function/dist/has-fallback-decl.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import type { Declaration } from 'postcss'; -export declare function hasFallback(node: Declaration): boolean; diff --git a/plugins/postcss-image-set-function/dist/index.cjs b/plugins/postcss-image-set-function/dist/index.cjs index 1d922e9b8..7849651e0 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");const t=/^(cross-fade|image|(repeating-)?(conic|linear|radial)-gradient|url|var)$/i;function getImage(n){return!(!n||!n.type)&&("string"===n.type?"url("+e.stringify(n)+")":!("function"!==n.type||!t.test(n.value.toLowerCase()))&&e.stringify(n))}const n=new Map([["dpcm",2.54],["dpi",1],["dppx",96],["x",96]]);function getMedia(e,t,n){if("boolean"==typeof e)return!1;const r=Math.floor(e/96*100)/100;return t.atRule({name:"media",params:`(-webkit-min-device-pixel-ratio: ${r}), (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 r=e.unit(t.value);if(!r)return!1;const i=n.get(r.unit.toLowerCase());return!!i&&Number(r.number)*i}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,r)=>{const i=n.parent;if(!i)return;const o=new Map,s=n.value;for(let i=0;ie-t)).map((e=>{var t;return null==(t=o.get(e))?void 0:t.atRule})).filter((e=>!!e));if(!l.length)return;const u=l[0],c=l.slice(1);c.length&&i.after(c);const d=u.nodes[0].nodes[0];n.cloneBefore({value:d.value.trim()}),r.preserve||(n.remove(),i.nodes.length||i.remove())};function hasFallback(e){const t=e.parent;if(!t)return!1;const n=e.prop.toLowerCase(),r=t.index(e);for(let e=0;e{const n=!("preserve"in Object(t))||Boolean(null==t?void 0:t.preserve),o="onInvalid"in Object(t)?null==t?void 0:t.onInvalid:"ignore";if("oninvalid"in Object(t))throw new Error('"oninvalid" was changed to "onInvalid" to match other plugins with similar options');return{postcssPlugin:"postcss-image-set-function",Declaration(t,{result:s,postcss:a}){const l=t.value;if(!r.test(l))return;if(hasFallback(t))return;let u;try{u=e(l)}catch(e){t.warn(s,`Failed to parse value '${l}' as an image-set function. Leaving the original value intact.`)}if(void 0===u)return;const c=[];u.walk((n=>{if("function"!==n.type)return;if(!i.test(n.value))return;let r=!1;if(e.walk(n.nodes,(e=>{"function"===e.type&&i.test(e.value)&&(r=!0)})),r)return handleInvalidation({decl:t,oninvalid:o,result:s},"nested image-set functions are not allowed",e.stringify(n)),!1;const a=n.nodes.filter((e=>"comment"!==e.type&&"space"!==e.type));c.push({imageSetFunction:n,imageSetOptionNodes:a})})),processImageSet(c,t,{decl:t,oninvalid:o,preserve:n,result:s,postcss:a})}}};creator.postcss=!0,module.exports=creator; +"use strict";var e=require("postcss-value-parser");const t=/^(cross-fade|image|(repeating-)?(conic|linear|radial)-gradient|url|var)$/i;function getImage(n){return!(!n||!n.type)&&("string"===n.type?"url("+e.stringify(n)+")":!("function"!==n.type||!t.test(n.value.toLowerCase()))&&e.stringify(n))}const n=new Map([["dpcm",2.54],["dpi",1],["dppx",96],["x",96]]);function getMedia(e,t,n){if("boolean"==typeof e)return!1;const r=Math.floor(e/96*100)/100;return t.atRule({name:"media",params:`(-webkit-min-device-pixel-ratio: ${r}), (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 r=e.unit(t.value);if(!r)return!1;const i=n.get(r.unit.toLowerCase());return!!i&&Number(r.number)*i}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,r)=>{const i=n.parent;if(!i)return;const o=new Map,s=n.value;for(let i=0;ie-t)).map((e=>o.get(e)?.atRule)).filter((e=>!!e));if(!l.length)return;const u=l[0],c=l.slice(1);c.length&&i.after(c);const p=u.nodes[0].nodes[0];n.cloneBefore({value:p.value.trim()}),r.preserve||(n.remove(),i.nodes.length||i.remove())};function hasFallback(e){const t=e.parent;if(!t)return!1;const n=e.prop.toLowerCase(),r=t.index(e);for(let e=0;e{const n=!("preserve"in Object(t))||Boolean(t?.preserve),o="onInvalid"in Object(t)?t?.onInvalid:"ignore";if("oninvalid"in Object(t))throw new Error('"oninvalid" was changed to "onInvalid" to match other plugins with similar options');return{postcssPlugin:"postcss-image-set-function",Declaration(t,{result:s,postcss:a}){const l=t.value;if(!r.test(l))return;if(hasFallback(t))return;let u;try{u=e(l)}catch(e){t.warn(s,`Failed to parse value '${l}' as an image-set function. Leaving the original value intact.`)}if(void 0===u)return;const c=[];u.walk((n=>{if("function"!==n.type)return;if(!i.test(n.value))return;let r=!1;if(e.walk(n.nodes,(e=>{"function"===e.type&&i.test(e.value)&&(r=!0)})),r)return handleInvalidation({decl:t,oninvalid:o,result:s},"nested image-set functions are not allowed",e.stringify(n)),!1;const a=n.nodes.filter((e=>"comment"!==e.type&&"space"!==e.type));c.push({imageSetFunction:n,imageSetOptionNodes:a})})),processImageSet(c,t,{decl:t,oninvalid:o,preserve:n,result:s,postcss:a})}}};creator.postcss=!0,module.exports=creator; diff --git a/plugins/postcss-image-set-function/dist/index.d.ts b/plugins/postcss-image-set-function/dist/index.d.ts index f421c2d74..5eb630f7c 100644 --- a/plugins/postcss-image-set-function/dist/index.d.ts +++ b/plugins/postcss-image-set-function/dist/index.d.ts @@ -1,6 +1,10 @@ import type { PluginCreator } from 'postcss'; + +declare const creator: PluginCreator; +export default creator; + /** postcss-image-set-function plugin options */ -export type pluginOptions = { +export declare type pluginOptions = { /** Preserve the original notation. default: true */ preserve?: boolean; /** @@ -11,5 +15,5 @@ export type pluginOptions = { */ onInvalid?: 'warn' | 'throw' | 'ignore' | false; }; -declare const creator: PluginCreator; -export default creator; + +export { } diff --git a/plugins/postcss-image-set-function/dist/index.mjs b/plugins/postcss-image-set-function/dist/index.mjs index bbd71a2ec..10bb7b06a 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";const t=/^(cross-fade|image|(repeating-)?(conic|linear|radial)-gradient|url|var)$/i;function getImage(n){return!(!n||!n.type)&&("string"===n.type?"url("+e.stringify(n)+")":!("function"!==n.type||!t.test(n.value.toLowerCase()))&&e.stringify(n))}const n=new Map([["dpcm",2.54],["dpi",1],["dppx",96],["x",96]]);function getMedia(e,t,n){if("boolean"==typeof e)return!1;const r=Math.floor(e/96*100)/100;return t.atRule({name:"media",params:`(-webkit-min-device-pixel-ratio: ${r}), (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 r=e.unit(t.value);if(!r)return!1;const i=n.get(r.unit.toLowerCase());return!!i&&Number(r.number)*i}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,r)=>{const i=n.parent;if(!i)return;const o=new Map,a=n.value;for(let i=0;ie-t)).map((e=>{var t;return null==(t=o.get(e))?void 0:t.atRule})).filter((e=>!!e));if(!l.length)return;const u=l[0],c=l.slice(1);c.length&&i.after(c);const d=u.nodes[0].nodes[0];n.cloneBefore({value:d.value.trim()}),r.preserve||(n.remove(),i.nodes.length||i.remove())};function hasFallback(e){const t=e.parent;if(!t)return!1;const n=e.prop.toLowerCase(),r=t.index(e);for(let e=0;e{const n=!("preserve"in Object(t))||Boolean(null==t?void 0:t.preserve),o="onInvalid"in Object(t)?null==t?void 0:t.onInvalid:"ignore";if("oninvalid"in Object(t))throw new Error('"oninvalid" was changed to "onInvalid" to match other plugins with similar options');return{postcssPlugin:"postcss-image-set-function",Declaration(t,{result:a,postcss:s}){const l=t.value;if(!r.test(l))return;if(hasFallback(t))return;let u;try{u=e(l)}catch(e){t.warn(a,`Failed to parse value '${l}' as an image-set function. Leaving the original value intact.`)}if(void 0===u)return;const c=[];u.walk((n=>{if("function"!==n.type)return;if(!i.test(n.value))return;let r=!1;if(e.walk(n.nodes,(e=>{"function"===e.type&&i.test(e.value)&&(r=!0)})),r)return handleInvalidation({decl:t,oninvalid:o,result:a},"nested image-set functions are not allowed",e.stringify(n)),!1;const s=n.nodes.filter((e=>"comment"!==e.type&&"space"!==e.type));c.push({imageSetFunction:n,imageSetOptionNodes:s})})),processImageSet(c,t,{decl:t,oninvalid:o,preserve:n,result:a,postcss:s})}}};creator.postcss=!0;export{creator as default}; +import e from"postcss-value-parser";const t=/^(cross-fade|image|(repeating-)?(conic|linear|radial)-gradient|url|var)$/i;function getImage(n){return!(!n||!n.type)&&("string"===n.type?"url("+e.stringify(n)+")":!("function"!==n.type||!t.test(n.value.toLowerCase()))&&e.stringify(n))}const n=new Map([["dpcm",2.54],["dpi",1],["dppx",96],["x",96]]);function getMedia(e,t,n){if("boolean"==typeof e)return!1;const r=Math.floor(e/96*100)/100;return t.atRule({name:"media",params:`(-webkit-min-device-pixel-ratio: ${r}), (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 r=e.unit(t.value);if(!r)return!1;const i=n.get(r.unit.toLowerCase());return!!i&&Number(r.number)*i}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,r)=>{const i=n.parent;if(!i)return;const o=new Map,a=n.value;for(let i=0;ie-t)).map((e=>o.get(e)?.atRule)).filter((e=>!!e));if(!l.length)return;const u=l[0],c=l.slice(1);c.length&&i.after(c);const p=u.nodes[0].nodes[0];n.cloneBefore({value:p.value.trim()}),r.preserve||(n.remove(),i.nodes.length||i.remove())};function hasFallback(e){const t=e.parent;if(!t)return!1;const n=e.prop.toLowerCase(),r=t.index(e);for(let e=0;e{const n=!("preserve"in Object(t))||Boolean(t?.preserve),o="onInvalid"in Object(t)?t?.onInvalid:"ignore";if("oninvalid"in Object(t))throw new Error('"oninvalid" was changed to "onInvalid" to match other plugins with similar options');return{postcssPlugin:"postcss-image-set-function",Declaration(t,{result:a,postcss:s}){const l=t.value;if(!r.test(l))return;if(hasFallback(t))return;let u;try{u=e(l)}catch(e){t.warn(a,`Failed to parse value '${l}' as an image-set function. Leaving the original value intact.`)}if(void 0===u)return;const c=[];u.walk((n=>{if("function"!==n.type)return;if(!i.test(n.value))return;let r=!1;if(e.walk(n.nodes,(e=>{"function"===e.type&&i.test(e.value)&&(r=!0)})),r)return handleInvalidation({decl:t,oninvalid:o,result:a},"nested image-set functions are not allowed",e.stringify(n)),!1;const s=n.nodes.filter((e=>"comment"!==e.type&&"space"!==e.type));c.push({imageSetFunction:n,imageSetOptionNodes:s})})),processImageSet(c,t,{decl:t,oninvalid:o,preserve:n,result:a,postcss:s})}}};creator.postcss=!0;export{creator as default}; diff --git a/plugins/postcss-image-set-function/dist/lib/get-comma.d.ts b/plugins/postcss-image-set-function/dist/lib/get-comma.d.ts deleted file mode 100644 index 77c82734f..000000000 --- a/plugins/postcss-image-set-function/dist/lib/get-comma.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import valueParser from 'postcss-value-parser'; -export declare function getComma(node: valueParser.Node): boolean; diff --git a/plugins/postcss-image-set-function/dist/lib/get-image.d.ts b/plugins/postcss-image-set-function/dist/lib/get-image.d.ts deleted file mode 100644 index 2a1a4d208..000000000 --- a/plugins/postcss-image-set-function/dist/lib/get-image.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import valueParser from 'postcss-value-parser'; -export declare function getImage(node: valueParser.Node): string | false; diff --git a/plugins/postcss-image-set-function/dist/lib/get-media.d.ts b/plugins/postcss-image-set-function/dist/lib/get-media.d.ts deleted file mode 100644 index 324d41088..000000000 --- a/plugins/postcss-image-set-function/dist/lib/get-media.d.ts +++ /dev/null @@ -1,4 +0,0 @@ -import type { Declaration, Postcss } from 'postcss'; -import type { Node } from 'postcss-value-parser'; -export declare function getMedia(dpi: number | false, postcss: Postcss, decl: Declaration): false | import("postcss/lib/at-rule").default; -export declare function getMediaDPI(node: Node): number | false; diff --git a/plugins/postcss-image-set-function/dist/lib/handle-invalidation.d.ts b/plugins/postcss-image-set-function/dist/lib/handle-invalidation.d.ts deleted file mode 100644 index 13aad1b43..000000000 --- a/plugins/postcss-image-set-function/dist/lib/handle-invalidation.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -import type { Declaration, Result } from 'postcss'; -export declare const handleInvalidation: (opts: { - oninvalid: 'warn' | 'throw' | unknown; - decl: Declaration; - result: Result; -}, message: string, word: string) => void; diff --git a/plugins/postcss-image-set-function/dist/lib/process-image-set.d.ts b/plugins/postcss-image-set-function/dist/lib/process-image-set.d.ts deleted file mode 100644 index 76a38653c..000000000 --- a/plugins/postcss-image-set-function/dist/lib/process-image-set.d.ts +++ /dev/null @@ -1,14 +0,0 @@ -import type { Declaration, Result, Postcss } from 'postcss'; -import type { Node } from 'postcss-value-parser'; -type imageSetFunction = { - imageSetFunction: Node; - imageSetOptionNodes: Array; -}; -export declare const processImageSet: (imageSetFunctions: Array, decl: Declaration, opts: { - decl: Declaration; - oninvalid: 'warn' | 'throw' | 'ignore' | false | undefined; - preserve: boolean; - result: Result; - postcss: Postcss; -}) => void; -export {}; diff --git a/plugins/postcss-image-set-function/package.json b/plugins/postcss-image-set-function/package.json index 8536ac8e3..08974c62d 100644 --- a/plugins/postcss-image-set-function/package.json +++ b/plugins/postcss-image-set-function/package.json @@ -17,15 +17,18 @@ "engines": { "node": "^14 || ^16 || >=18" }, + "type": "module", "main": "dist/index.cjs", "module": "dist/index.mjs", - "types": "dist/index.d.ts", "exports": { ".": { - "types": "./dist/index.d.ts", - "import": "./dist/index.mjs", - "require": "./dist/index.cjs", - "default": "./dist/index.mjs" + "import": { + "types": "./dist/index.d.ts", + "default": "./dist/index.mjs" + }, + "require": { + "default": "./dist/index.cjs" + } } }, "files": [ diff --git a/plugins/postcss-initial/CHANGELOG.md b/plugins/postcss-initial/CHANGELOG.md index 296a43b5d..7ee988554 100644 --- a/plugins/postcss-initial/CHANGELOG.md +++ b/plugins/postcss-initial/CHANGELOG.md @@ -1,5 +1,9 @@ # Changes to PostCSS Initial +### Unreleased (patch) + +- Fix type definitions + ### 1.0.0 _September 18, 2023_ diff --git a/plugins/postcss-initial/api-extractor.json b/plugins/postcss-initial/api-extractor.json new file mode 100644 index 000000000..42058be51 --- /dev/null +++ b/plugins/postcss-initial/api-extractor.json @@ -0,0 +1,4 @@ +{ + "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json", + "extends": "../../api-extractor.json" +} diff --git a/plugins/postcss-initial/dist/has-fallback-decl.d.ts b/plugins/postcss-initial/dist/has-fallback-decl.d.ts deleted file mode 100644 index c044b7876..000000000 --- a/plugins/postcss-initial/dist/has-fallback-decl.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import type { Declaration } from 'postcss'; -export declare function hasExactFallback(node: Declaration, newValue: string): boolean; diff --git a/plugins/postcss-initial/dist/index.d.ts b/plugins/postcss-initial/dist/index.d.ts index 55f858c1a..20f8fc5de 100644 --- a/plugins/postcss-initial/dist/index.d.ts +++ b/plugins/postcss-initial/dist/index.d.ts @@ -1,8 +1,12 @@ import type { PluginCreator } from 'postcss'; + +declare const creator: PluginCreator; +export default creator; + /** postcss-initial plugin options */ -export type pluginOptions = { +export declare type pluginOptions = { /** Preserve the original notation. default: false */ preserve?: boolean; }; -declare const creator: PluginCreator; -export default creator; + +export { } diff --git a/plugins/postcss-initial/dist/properties.d.ts b/plugins/postcss-initial/dist/properties.d.ts deleted file mode 100644 index 5345546eb..000000000 --- a/plugins/postcss-initial/dist/properties.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -export declare const properties: Map; -export declare const allProperties: string[]; diff --git a/plugins/postcss-initial/package.json b/plugins/postcss-initial/package.json index d5b6e09eb..44a39413c 100644 --- a/plugins/postcss-initial/package.json +++ b/plugins/postcss-initial/package.json @@ -27,15 +27,18 @@ "engines": { "node": "^14 || ^16 || >=18" }, + "type": "module", "main": "dist/index.cjs", "module": "dist/index.mjs", - "types": "dist/index.d.ts", "exports": { ".": { - "types": "./dist/index.d.ts", - "import": "./dist/index.mjs", - "require": "./dist/index.cjs", - "default": "./dist/index.mjs" + "import": { + "types": "./dist/index.d.ts", + "default": "./dist/index.mjs" + }, + "require": { + "default": "./dist/index.cjs" + } } }, "files": [ diff --git a/plugins/postcss-is-pseudo-class/CHANGELOG.md b/plugins/postcss-is-pseudo-class/CHANGELOG.md index 124534341..4839342ee 100644 --- a/plugins/postcss-is-pseudo-class/CHANGELOG.md +++ b/plugins/postcss-is-pseudo-class/CHANGELOG.md @@ -1,5 +1,9 @@ # Changes to PostCSS Is Pseudo Class +### Unreleased (patch) + +- Fix type definitions + ### 4.0.3 _October 2, 2023_ diff --git a/plugins/postcss-is-pseudo-class/api-extractor.json b/plugins/postcss-is-pseudo-class/api-extractor.json new file mode 100644 index 000000000..42058be51 --- /dev/null +++ b/plugins/postcss-is-pseudo-class/api-extractor.json @@ -0,0 +1,4 @@ +{ + "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json", + "extends": "../../api-extractor.json" +} diff --git a/plugins/postcss-is-pseudo-class/dist/index.cjs b/plugins/postcss-is-pseudo-class/dist/index.cjs index 939299bd1..d1355d60c 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=>{var o,s;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||null!=(o=e.nodes)&&o.length||":hover"!==e.value.toLowerCase()&&":focus"!==e.value.toLowerCase())){if("pseudo"===e.type&&1===(null==(s=e.nodes)?void 0:s.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+")",l=":not(."+t.specificityMatchingName+")",d=":not("+t.specificityMatchingName+")";return s.flatMap((s=>{if(-1===s.toLowerCase().indexOf(":is"))return s;let i=!1;const c=[];if(e().astSync(s).walkPseudos((e=>{var s,t,n,a;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"===(null==(s=e.parent)||null==(s=s.parent)?void 0:s.type)&&":not"===(null==(t=e.parent)||null==(t=t.parent)||null==(t=t.value)?void 0:t.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"===(null==(n=e.parent)||null==(n=n.parent)?void 0:n.type)&&":has"===(null==(a=e.parent)||null==(a=a.parent)||null==(a=a.value)?void 0:a.toLowerCase()))return void(e.value=":-csstools-matches");let p=e.parent;for(;p;){if(p.value&&":is"===p.value.toLowerCase()&&"pseudo"===p.type)return void(i=!0);p=p.parent}const u=o.selectorSpecificity(e),h=e.sourceIndex,f=h+e.toString().length,y=[];e.nodes.forEach((e=>{const s={start:h,end:f,option:""},t=o.selectorSpecificity(e);let n=e.toString().trim();const i=Math.max(0,u.a-t.a),c=Math.max(0,u.b-t.b),a=Math.max(0,u.c-t.c);for(let e=0;e{let o="";for(let n=0;n!!e))}function cartesianProduct(...e){const o=[],s=e.length-1;return function helper(t,n){for(let r=0,l=e[n].length;r{const o={specificityMatchingName:"does-not-exist",...e||{}};return{postcssPlugin:"postcss-is-pseudo-class",prepare(){const e=new WeakSet;return{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 l=!1;const warnOnPseudoElements=()=>{"warning"===o.onPseudoElement&&(l||(l=!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}"`)}}}}}};creator.postcss=!0,module.exports=creator; +"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{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}"`)}}}}}};creator.postcss=!0,module.exports=creator; diff --git a/plugins/postcss-is-pseudo-class/dist/index.d.ts b/plugins/postcss-is-pseudo-class/dist/index.d.ts index 5b65f0161..6f69c11ec 100644 --- a/plugins/postcss-is-pseudo-class/dist/index.d.ts +++ b/plugins/postcss-is-pseudo-class/dist/index.d.ts @@ -1,17 +1,21 @@ import type { PluginCreator } from 'postcss'; + +declare const creator: PluginCreator; +export default creator; + /** postcss-is-pseudo-class plugin options */ -export type pluginOptions = { +export declare type pluginOptions = { /** Preserve the original notation. default: false */ preserve?: boolean; /** * Warn on complex selectors in `:is` pseudo class functions. * default: _not set_ - */ + */ onComplexSelector?: 'warning'; /** * Warn when pseudo elements are used in `:is` pseudo class functions. * default: _not set_ - */ + */ onPseudoElement?: 'warning'; /** * Change the selector used to adjust specificity. @@ -19,5 +23,5 @@ export type pluginOptions = { */ specificityMatchingName?: string; }; -declare const creator: PluginCreator; -export default creator; + +export { } diff --git a/plugins/postcss-is-pseudo-class/dist/index.mjs b/plugins/postcss-is-pseudo-class/dist/index.mjs index 98bdd1aca..a3b17fa53 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=>{var o,s;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||null!=(o=e.nodes)&&o.length||":hover"!==e.value.toLowerCase()&&":focus"!==e.value.toLowerCase())){if("pseudo"===e.type&&1===(null==(s=e.nodes)?void 0:s.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+")",l=":not(."+t.specificityMatchingName+")",d=":not("+t.specificityMatchingName+")";return s.flatMap((s=>{if(-1===s.toLowerCase().indexOf(":is"))return s;let a=!1;const i=[];if(e().astSync(s).walkPseudos((e=>{var s,t,n,c;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"===(null==(s=e.parent)||null==(s=s.parent)?void 0:s.type)&&":not"===(null==(t=e.parent)||null==(t=t.parent)||null==(t=t.value)?void 0:t.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"===(null==(n=e.parent)||null==(n=n.parent)?void 0:n.type)&&":has"===(null==(c=e.parent)||null==(c=c.parent)||null==(c=c.value)?void 0:c.toLowerCase()))return void(e.value=":-csstools-matches");let p=e.parent;for(;p;){if(p.value&&":is"===p.value.toLowerCase()&&"pseudo"===p.type)return void(a=!0);p=p.parent}const u=o(e),h=e.sourceIndex,f=h+e.toString().length,y=[];e.nodes.forEach((e=>{const s={start:h,end:f,option:""},t=o(e);let n=e.toString().trim();const a=Math.max(0,u.a-t.a),i=Math.max(0,u.b-t.b),c=Math.max(0,u.c-t.c);for(let e=0;e{let o="";for(let n=0;n!!e))}function cartesianProduct(...e){const o=[],s=e.length-1;return function helper(t,n){for(let r=0,l=e[n].length;r{const o={specificityMatchingName:"does-not-exist",...e||{}};return{postcssPlugin:"postcss-is-pseudo-class",prepare(){const e=new WeakSet;return{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 l=!1;const warnOnPseudoElements=()=>{"warning"===o.onPseudoElement&&(l||(l=!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}"`)}}}}}};creator.postcss=!0;export{creator as default}; +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{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}"`)}}}}}};creator.postcss=!0;export{creator as default}; diff --git a/plugins/postcss-is-pseudo-class/dist/split-selectors/always-valid.d.ts b/plugins/postcss-is-pseudo-class/dist/split-selectors/always-valid.d.ts deleted file mode 100644 index a3bb60b3c..000000000 --- a/plugins/postcss-is-pseudo-class/dist/split-selectors/always-valid.d.ts +++ /dev/null @@ -1 +0,0 @@ -export default function alwaysValidSelector(selector: string): boolean; diff --git a/plugins/postcss-is-pseudo-class/dist/split-selectors/complex.d.ts b/plugins/postcss-is-pseudo-class/dist/split-selectors/complex.d.ts deleted file mode 100644 index 904515e72..000000000 --- a/plugins/postcss-is-pseudo-class/dist/split-selectors/complex.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -export default function complexSelectors(selectors: Array, pluginOptions: { - onComplexSelector?: 'warning'; -}, warnOnComplexSelector: () => void, warnOnPseudoElements: () => void): string[]; diff --git a/plugins/postcss-is-pseudo-class/dist/split-selectors/complex/child-adjacent-child.d.ts b/plugins/postcss-is-pseudo-class/dist/split-selectors/complex/child-adjacent-child.d.ts deleted file mode 100644 index 644eaaec5..000000000 --- a/plugins/postcss-is-pseudo-class/dist/split-selectors/complex/child-adjacent-child.d.ts +++ /dev/null @@ -1 +0,0 @@ -export declare function childAdjacentChild(selector: any): boolean; diff --git a/plugins/postcss-is-pseudo-class/dist/split-selectors/complex/is-in-compound.d.ts b/plugins/postcss-is-pseudo-class/dist/split-selectors/complex/is-in-compound.d.ts deleted file mode 100644 index 3a91eef6c..000000000 --- a/plugins/postcss-is-pseudo-class/dist/split-selectors/complex/is-in-compound.d.ts +++ /dev/null @@ -1 +0,0 @@ -export declare function isInCompoundWithOneOtherElement(selector: any): boolean; diff --git a/plugins/postcss-is-pseudo-class/dist/split-selectors/complex/is-pseudo-in-first-compound.d.ts b/plugins/postcss-is-pseudo-class/dist/split-selectors/complex/is-pseudo-in-first-compound.d.ts deleted file mode 100644 index 06ba1481e..000000000 --- a/plugins/postcss-is-pseudo-class/dist/split-selectors/complex/is-pseudo-in-first-compound.d.ts +++ /dev/null @@ -1 +0,0 @@ -export declare function isPseudoInFirstCompound(selector: any): boolean; diff --git a/plugins/postcss-is-pseudo-class/dist/split-selectors/compound-selector-order.d.ts b/plugins/postcss-is-pseudo-class/dist/split-selectors/compound-selector-order.d.ts deleted file mode 100644 index 3fb1e39f4..000000000 --- a/plugins/postcss-is-pseudo-class/dist/split-selectors/compound-selector-order.d.ts +++ /dev/null @@ -1 +0,0 @@ -export declare function sortCompoundSelectorsInsideComplexSelector(node: any): void; diff --git a/plugins/postcss-is-pseudo-class/dist/split-selectors/split-selectors.d.ts b/plugins/postcss-is-pseudo-class/dist/split-selectors/split-selectors.d.ts deleted file mode 100644 index 7bb70f21d..000000000 --- a/plugins/postcss-is-pseudo-class/dist/split-selectors/split-selectors.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -export default function splitSelectors(selectors: Array, pluginOptions: { - specificityMatchingName: string; -}, recursionDepth?: number): Array; diff --git a/plugins/postcss-is-pseudo-class/package.json b/plugins/postcss-is-pseudo-class/package.json index 141c8c4d6..d349d0762 100644 --- a/plugins/postcss-is-pseudo-class/package.json +++ b/plugins/postcss-is-pseudo-class/package.json @@ -17,15 +17,18 @@ "engines": { "node": "^14 || ^16 || >=18" }, + "type": "module", "main": "dist/index.cjs", "module": "dist/index.mjs", - "types": "dist/index.d.ts", "exports": { ".": { - "types": "./dist/index.d.ts", - "import": "./dist/index.mjs", - "require": "./dist/index.cjs", - "default": "./dist/index.mjs" + "import": { + "types": "./dist/index.d.ts", + "default": "./dist/index.mjs" + }, + "require": { + "default": "./dist/index.cjs" + } } }, "files": [ diff --git a/plugins/postcss-lab-function/api-extractor.json b/plugins/postcss-lab-function/api-extractor.json new file mode 100644 index 000000000..42058be51 --- /dev/null +++ b/plugins/postcss-lab-function/api-extractor.json @@ -0,0 +1,4 @@ +{ + "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json", + "extends": "../../api-extractor.json" +} diff --git a/plugins/postcss-lab-function/dist/has-fallback-decl.d.ts b/plugins/postcss-lab-function/dist/has-fallback-decl.d.ts deleted file mode 100644 index d7ae8d890..000000000 --- a/plugins/postcss-lab-function/dist/has-fallback-decl.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import type { Declaration } from 'postcss'; -export declare function hasFallback(node: Declaration): boolean; diff --git a/plugins/postcss-lab-function/dist/has-supports-at-rule-ancestor.d.ts b/plugins/postcss-lab-function/dist/has-supports-at-rule-ancestor.d.ts deleted file mode 100644 index a46009ecc..000000000 --- a/plugins/postcss-lab-function/dist/has-supports-at-rule-ancestor.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import type { Node } from 'postcss'; -export declare function hasSupportsAtRuleAncestor(node: Node): boolean; diff --git a/plugins/postcss-lab-function/dist/index.cjs b/plugins/postcss-lab-function/dist/index.cjs index 47cda196d..3693b63e0 100644 --- a/plugins/postcss-lab-function/dist/index.cjs +++ b/plugins/postcss-lab-function/dist/index.cjs @@ -1 +1 @@ -"use strict";var e=require("@csstools/postcss-progressive-custom-properties"),s=require("@csstools/css-tokenizer"),r=require("@csstools/css-color-parser"),t=require("@csstools/css-parser-algorithms");function hasFallback(e){const s=e.parent;if(!s)return!1;const r=e.prop.toLowerCase(),t=s.index(e);for(let e=0;e({postcssPlugin:"postcss-lab-function",Declaration:n=>{const l=n.value;if(!a.test(l))return;if(hasFallback(n))return;if(hasSupportsAtRuleAncestor(n))return;const i=s.tokenize({css:l}),u=t.replaceComponentValues(t.parseCommaSeparatedListOfComponentValues(i),(e=>{if(t.isFunctionNode(e)&&o.test(e.getName())){const s=r.color(e);if(!s)return;if(s.syntaxFlags.has(r.SyntaxFlag.Experimental))return;if(s.syntaxFlags.has(r.SyntaxFlag.HasNoneKeywords))return;if(s.syntaxFlags.has(r.SyntaxFlag.RelativeColorSyntax))return;return r.serializeRGB(s)}})),p=t.stringify(u);if(p===l)return;let c=p;null!=e&&e.subFeatures.displayP3&&(c=t.stringify(t.replaceComponentValues(t.parseCommaSeparatedListOfComponentValues(i),(e=>{if(t.isFunctionNode(e)&&o.test(e.getName())){const s=r.color(e);if(!s)return;if(s.syntaxFlags.has(r.SyntaxFlag.HasNoneKeywords))return;if(s.syntaxFlags.has(r.SyntaxFlag.RelativeColorSyntax))return;return r.colorDataFitsRGB_Gamut(s)?r.serializeRGB(s):r.serializeP3(s)}})))),n.cloneBefore({value:p}),null!=e&&e.subFeatures.displayP3&&c!==p&&n.cloneBefore({value:c}),null!=e&&e.preserve||n.remove()}});basePlugin.postcss=!0;const postcssPlugin=s=>{const r=Object.assign({enableProgressiveCustomProperties:!0,preserve:!1,subFeatures:{displayP3:!0}},s);return r.subFeatures=Object.assign({displayP3:!0},r.subFeatures),r.enableProgressiveCustomProperties&&(r.preserve||r.subFeatures.displayP3)?{postcssPlugin:"postcss-lab-function",plugins:[e(),basePlugin(r)]}:basePlugin(r)};postcssPlugin.postcss=!0,module.exports=postcssPlugin; +"use strict";var e=require("@csstools/postcss-progressive-custom-properties"),s=require("@csstools/css-tokenizer"),r=require("@csstools/css-color-parser"),t=require("@csstools/css-parser-algorithms");function hasFallback(e){const s=e.parent;if(!s)return!1;const r=e.prop.toLowerCase(),t=s.index(e);for(let e=0;e({postcssPlugin:"postcss-lab-function",Declaration:n=>{const i=n.value;if(!a.test(i))return;if(hasFallback(n))return;if(hasSupportsAtRuleAncestor(n))return;const l=s.tokenize({css:i}),u=t.replaceComponentValues(t.parseCommaSeparatedListOfComponentValues(l),(e=>{if(t.isFunctionNode(e)&&o.test(e.getName())){const s=r.color(e);if(!s)return;if(s.syntaxFlags.has(r.SyntaxFlag.Experimental))return;if(s.syntaxFlags.has(r.SyntaxFlag.HasNoneKeywords))return;if(s.syntaxFlags.has(r.SyntaxFlag.RelativeColorSyntax))return;return r.serializeRGB(s)}})),p=t.stringify(u);if(p===i)return;let c=p;e?.subFeatures.displayP3&&(c=t.stringify(t.replaceComponentValues(t.parseCommaSeparatedListOfComponentValues(l),(e=>{if(t.isFunctionNode(e)&&o.test(e.getName())){const s=r.color(e);if(!s)return;if(s.syntaxFlags.has(r.SyntaxFlag.HasNoneKeywords))return;if(s.syntaxFlags.has(r.SyntaxFlag.RelativeColorSyntax))return;return r.colorDataFitsRGB_Gamut(s)?r.serializeRGB(s):r.serializeP3(s)}})))),n.cloneBefore({value:p}),e?.subFeatures.displayP3&&c!==p&&n.cloneBefore({value:c}),e?.preserve||n.remove()}});basePlugin.postcss=!0;const postcssPlugin=s=>{const r=Object.assign({enableProgressiveCustomProperties:!0,preserve:!1,subFeatures:{displayP3:!0}},s);return r.subFeatures=Object.assign({displayP3:!0},r.subFeatures),r.enableProgressiveCustomProperties&&(r.preserve||r.subFeatures.displayP3)?{postcssPlugin:"postcss-lab-function",plugins:[e(),basePlugin(r)]}:basePlugin(r)};postcssPlugin.postcss=!0,module.exports=postcssPlugin; diff --git a/plugins/postcss-lab-function/dist/index.d.ts b/plugins/postcss-lab-function/dist/index.d.ts index e94b09fe8..c05352512 100644 --- a/plugins/postcss-lab-function/dist/index.d.ts +++ b/plugins/postcss-lab-function/dist/index.d.ts @@ -1,6 +1,7 @@ import type { PluginCreator } from 'postcss'; + /** postcss-lab-function plugin options */ -export type pluginOptions = { +export declare type pluginOptions = { /** Preserve the original notation. default: false */ preserve?: boolean; /** Enable "@csstools/postcss-progressive-custom-properties". default: true */ @@ -11,5 +12,8 @@ export type pluginOptions = { displayP3?: boolean; }; }; + declare const postcssPlugin: PluginCreator; export default postcssPlugin; + +export { } diff --git a/plugins/postcss-lab-function/dist/index.mjs b/plugins/postcss-lab-function/dist/index.mjs index e3479305b..b5b9e2dff 100644 --- a/plugins/postcss-lab-function/dist/index.mjs +++ b/plugins/postcss-lab-function/dist/index.mjs @@ -1 +1 @@ -import s from"@csstools/postcss-progressive-custom-properties";import{tokenize as e}from"@csstools/css-tokenizer";import{color as r,SyntaxFlag as t,serializeRGB as o,colorDataFitsRGB_Gamut as a,serializeP3 as n}from"@csstools/css-color-parser";import{replaceComponentValues as l,parseCommaSeparatedListOfComponentValues as u,isFunctionNode as i,stringify as p}from"@csstools/css-parser-algorithms";function hasFallback(s){const e=s.parent;if(!e)return!1;const r=s.prop.toLowerCase(),t=e.index(s);for(let s=0;s({postcssPlugin:"postcss-lab-function",Declaration:m=>{const b=m.value;if(!c.test(b))return;if(hasFallback(m))return;if(hasSupportsAtRuleAncestor(m))return;const g=e({css:b}),y=l(u(g),(s=>{if(i(s)&&f.test(s.getName())){const e=r(s);if(!e)return;if(e.syntaxFlags.has(t.Experimental))return;if(e.syntaxFlags.has(t.HasNoneKeywords))return;if(e.syntaxFlags.has(t.RelativeColorSyntax))return;return o(e)}})),d=p(y);if(d===b)return;let h=d;null!=s&&s.subFeatures.displayP3&&(h=p(l(u(g),(s=>{if(i(s)&&f.test(s.getName())){const e=r(s);if(!e)return;if(e.syntaxFlags.has(t.HasNoneKeywords))return;if(e.syntaxFlags.has(t.RelativeColorSyntax))return;return a(e)?o(e):n(e)}})))),m.cloneBefore({value:d}),null!=s&&s.subFeatures.displayP3&&h!==d&&m.cloneBefore({value:h}),null!=s&&s.preserve||m.remove()}});basePlugin.postcss=!0;const postcssPlugin=e=>{const r=Object.assign({enableProgressiveCustomProperties:!0,preserve:!1,subFeatures:{displayP3:!0}},e);return r.subFeatures=Object.assign({displayP3:!0},r.subFeatures),r.enableProgressiveCustomProperties&&(r.preserve||r.subFeatures.displayP3)?{postcssPlugin:"postcss-lab-function",plugins:[s(),basePlugin(r)]}:basePlugin(r)};postcssPlugin.postcss=!0;export{postcssPlugin as default}; +import s from"@csstools/postcss-progressive-custom-properties";import{tokenize as e}from"@csstools/css-tokenizer";import{color as r,SyntaxFlag as t,serializeRGB as o,colorDataFitsRGB_Gamut as a,serializeP3 as n}from"@csstools/css-color-parser";import{replaceComponentValues as i,parseCommaSeparatedListOfComponentValues as l,isFunctionNode as u,stringify as p}from"@csstools/css-parser-algorithms";function hasFallback(s){const e=s.parent;if(!e)return!1;const r=s.prop.toLowerCase(),t=e.index(s);for(let s=0;s({postcssPlugin:"postcss-lab-function",Declaration:m=>{const b=m.value;if(!c.test(b))return;if(hasFallback(m))return;if(hasSupportsAtRuleAncestor(m))return;const g=e({css:b}),y=i(l(g),(s=>{if(u(s)&&f.test(s.getName())){const e=r(s);if(!e)return;if(e.syntaxFlags.has(t.Experimental))return;if(e.syntaxFlags.has(t.HasNoneKeywords))return;if(e.syntaxFlags.has(t.RelativeColorSyntax))return;return o(e)}})),d=p(y);if(d===b)return;let h=d;s?.subFeatures.displayP3&&(h=p(i(l(g),(s=>{if(u(s)&&f.test(s.getName())){const e=r(s);if(!e)return;if(e.syntaxFlags.has(t.HasNoneKeywords))return;if(e.syntaxFlags.has(t.RelativeColorSyntax))return;return a(e)?o(e):n(e)}})))),m.cloneBefore({value:d}),s?.subFeatures.displayP3&&h!==d&&m.cloneBefore({value:h}),s?.preserve||m.remove()}});basePlugin.postcss=!0;const postcssPlugin=e=>{const r=Object.assign({enableProgressiveCustomProperties:!0,preserve:!1,subFeatures:{displayP3:!0}},e);return r.subFeatures=Object.assign({displayP3:!0},r.subFeatures),r.enableProgressiveCustomProperties&&(r.preserve||r.subFeatures.displayP3)?{postcssPlugin:"postcss-lab-function",plugins:[s(),basePlugin(r)]}:basePlugin(r)};postcssPlugin.postcss=!0;export{postcssPlugin as default}; diff --git a/plugins/postcss-lab-function/package.json b/plugins/postcss-lab-function/package.json index 4ec71f7cd..8b18de384 100644 --- a/plugins/postcss-lab-function/package.json +++ b/plugins/postcss-lab-function/package.json @@ -17,15 +17,18 @@ "engines": { "node": "^14 || ^16 || >=18" }, + "type": "module", "main": "dist/index.cjs", "module": "dist/index.mjs", - "types": "./dist/index.d.ts", "exports": { ".": { - "types": "./dist/index.d.ts", - "import": "./dist/index.mjs", - "require": "./dist/index.cjs", - "default": "./dist/index.mjs" + "import": { + "types": "./dist/index.d.ts", + "default": "./dist/index.mjs" + }, + "require": { + "default": "./dist/index.cjs" + } } }, "files": [ diff --git a/plugins/postcss-logical-float-and-clear/CHANGELOG.md b/plugins/postcss-logical-float-and-clear/CHANGELOG.md index b11158f8b..3e4014ea0 100644 --- a/plugins/postcss-logical-float-and-clear/CHANGELOG.md +++ b/plugins/postcss-logical-float-and-clear/CHANGELOG.md @@ -1,5 +1,9 @@ # Changes to PostCSS Logical Float And Clear +### Unreleased (patch) + +- Fix type definitions + ### 2.0.0 _July 3, 2023_ diff --git a/plugins/postcss-logical-float-and-clear/api-extractor.json b/plugins/postcss-logical-float-and-clear/api-extractor.json new file mode 100644 index 000000000..42058be51 --- /dev/null +++ b/plugins/postcss-logical-float-and-clear/api-extractor.json @@ -0,0 +1,4 @@ +{ + "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json", + "extends": "../../api-extractor.json" +} diff --git a/plugins/postcss-logical-float-and-clear/dist/index.d.ts b/plugins/postcss-logical-float-and-clear/dist/index.d.ts index 8faa333f6..44d0817a8 100644 --- a/plugins/postcss-logical-float-and-clear/dist/index.d.ts +++ b/plugins/postcss-logical-float-and-clear/dist/index.d.ts @@ -1,9 +1,19 @@ import type { PluginCreator } from 'postcss'; -import { DirectionFlow } from './lib/types'; + +declare const creator: PluginCreator; +export default creator; + +export declare enum DirectionFlow { + TopToBottom = "top-to-bottom", + BottomToTop = "bottom-to-top", + RightToLeft = "right-to-left", + LeftToRight = "left-to-right" +} + /** postcss-logical-float-and-clear plugin options */ -export type pluginOptions = { +export declare type pluginOptions = { /** Sets the direction for inline. default: left-to-right */ inlineDirection?: DirectionFlow; }; -declare const creator: PluginCreator; -export default creator; + +export { } diff --git a/plugins/postcss-logical-float-and-clear/dist/lib/clone-declaration.d.ts b/plugins/postcss-logical-float-and-clear/dist/lib/clone-declaration.d.ts deleted file mode 100644 index 1503bf6f1..000000000 --- a/plugins/postcss-logical-float-and-clear/dist/lib/clone-declaration.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import type { Declaration } from 'postcss'; -export declare function cloneDeclaration(declaration: Declaration, value: string, prop: string): void; diff --git a/plugins/postcss-logical-float-and-clear/dist/lib/types.d.ts b/plugins/postcss-logical-float-and-clear/dist/lib/types.d.ts deleted file mode 100644 index 2b3c47f9b..000000000 --- a/plugins/postcss-logical-float-and-clear/dist/lib/types.d.ts +++ /dev/null @@ -1,18 +0,0 @@ -export declare const DirectionValues: { - BlockStart: string; - BlockEnd: string; - InlineStart: string; - InlineEnd: string; -}; -export declare enum DirectionFlow { - TopToBottom = "top-to-bottom", - BottomToTop = "bottom-to-top", - RightToLeft = "right-to-left", - LeftToRight = "left-to-right" -} -export declare enum Axes { - Top = "top", - Right = "right", - Bottom = "bottom", - Left = "left" -} diff --git a/plugins/postcss-logical-float-and-clear/dist/utils/direction-flow-to-axes.d.ts b/plugins/postcss-logical-float-and-clear/dist/utils/direction-flow-to-axes.d.ts deleted file mode 100644 index 2652d71d8..000000000 --- a/plugins/postcss-logical-float-and-clear/dist/utils/direction-flow-to-axes.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import { DirectionFlow, Axes } from '../lib/types'; -export declare function directionFlowToAxes(directionFlow: DirectionFlow): [Axes, Axes]; diff --git a/plugins/postcss-logical-float-and-clear/package.json b/plugins/postcss-logical-float-and-clear/package.json index 5738faeb2..d16e7fbc9 100644 --- a/plugins/postcss-logical-float-and-clear/package.json +++ b/plugins/postcss-logical-float-and-clear/package.json @@ -27,15 +27,18 @@ "engines": { "node": "^14 || ^16 || >=18" }, + "type": "module", "main": "dist/index.cjs", "module": "dist/index.mjs", - "types": "dist/index.d.ts", "exports": { ".": { - "types": "./dist/index.d.ts", - "import": "./dist/index.mjs", - "require": "./dist/index.cjs", - "default": "./dist/index.mjs" + "import": { + "types": "./dist/index.d.ts", + "default": "./dist/index.mjs" + }, + "require": { + "default": "./dist/index.cjs" + } } }, "files": [ diff --git a/plugins/postcss-logical-float-and-clear/src/index.ts b/plugins/postcss-logical-float-and-clear/src/index.ts index 29caabf91..9b3f7cb24 100644 --- a/plugins/postcss-logical-float-and-clear/src/index.ts +++ b/plugins/postcss-logical-float-and-clear/src/index.ts @@ -3,6 +3,8 @@ import { DirectionFlow, DirectionValues } from './lib/types'; import { directionFlowToAxes } from './utils/direction-flow-to-axes'; import { cloneDeclaration } from './lib/clone-declaration'; +export type { DirectionFlow } from './lib/types'; + /** postcss-logical-float-and-clear plugin options */ export type pluginOptions = { /** Sets the direction for inline. default: left-to-right */ diff --git a/plugins/postcss-logical-overflow/CHANGELOG.md b/plugins/postcss-logical-overflow/CHANGELOG.md index 2ac66c291..2699724ca 100644 --- a/plugins/postcss-logical-overflow/CHANGELOG.md +++ b/plugins/postcss-logical-overflow/CHANGELOG.md @@ -2,7 +2,7 @@ ### Unreleased (patch) -- Small fixes in type definitions +- Fix type definitions ### 1.0.0 diff --git a/plugins/postcss-logical-overflow/api-extractor.json b/plugins/postcss-logical-overflow/api-extractor.json new file mode 100644 index 000000000..42058be51 --- /dev/null +++ b/plugins/postcss-logical-overflow/api-extractor.json @@ -0,0 +1,4 @@ +{ + "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json", + "extends": "../../api-extractor.json" +} diff --git a/plugins/postcss-logical-overflow/dist/index.cjs b/plugins/postcss-logical-overflow/dist/index.cjs index b6fdbf74f..ada0e7981 100644 --- a/plugins/postcss-logical-overflow/dist/index.cjs +++ b/plugins/postcss-logical-overflow/dist/index.cjs @@ -1 +1 @@ -"use strict";var o;function transformAxes(o,t){var e;const i=t?"-x":"-y",n=t?"-y":"-x",s=o.prop.toLowerCase().replace("-inline",i).replace("-block",n),r=o.value;null!=(e=o.parent)&&e.some((o=>"decl"==o.type&&o.prop===s&&o.value===r))||(o.cloneBefore({prop:s,value:r}),o.remove())}!function(o){o.TopToBottom="top-to-bottom",o.BottomToTop="bottom-to-top",o.RightToLeft="right-to-left",o.LeftToRight="left-to-right"}(o||(o={}));const creator=t=>{const e=Object.assign({inlineDirection:o.LeftToRight},t);switch(e.inlineDirection){case o.LeftToRight:case o.RightToLeft:case o.TopToBottom:case o.BottomToTop:break;default:throw new Error(`[postcss-logical-viewport-units] "inlineDirection" must be one of ${Object.values(o).join(", ")}`)}const i=[o.LeftToRight,o.RightToLeft].includes(e.inlineDirection);return{postcssPlugin:"postcss-logical-overflow",Declaration:{"overflow-block":o=>transformAxes(o,i),"overflow-inline":o=>transformAxes(o,i)}}};creator.postcss=!0,module.exports=creator; +"use strict";var o;function transformAxes(o,t){const e=t?"-x":"-y",i=t?"-y":"-x",n=o.prop.toLowerCase().replace("-inline",e).replace("-block",i),s=o.value;o.parent?.some((o=>"decl"==o.type&&o.prop===n&&o.value===s))||(o.cloneBefore({prop:n,value:s}),o.remove())}!function(o){o.TopToBottom="top-to-bottom",o.BottomToTop="bottom-to-top",o.RightToLeft="right-to-left",o.LeftToRight="left-to-right"}(o||(o={}));const creator=t=>{const e=Object.assign({inlineDirection:o.LeftToRight},t);switch(e.inlineDirection){case o.LeftToRight:case o.RightToLeft:case o.TopToBottom:case o.BottomToTop:break;default:throw new Error(`[postcss-logical-viewport-units] "inlineDirection" must be one of ${Object.values(o).join(", ")}`)}const i=[o.LeftToRight,o.RightToLeft].includes(e.inlineDirection);return{postcssPlugin:"postcss-logical-overflow",Declaration:{"overflow-block":o=>transformAxes(o,i),"overflow-inline":o=>transformAxes(o,i)}}};creator.postcss=!0,module.exports=creator; diff --git a/plugins/postcss-logical-overflow/dist/index.d.ts b/plugins/postcss-logical-overflow/dist/index.d.ts index bd5398afc..d9afe9d40 100644 --- a/plugins/postcss-logical-overflow/dist/index.d.ts +++ b/plugins/postcss-logical-overflow/dist/index.d.ts @@ -1,9 +1,19 @@ import type { PluginCreator } from 'postcss'; -import { DirectionFlow } from './lib/types'; + +declare const creator: PluginCreator; +export default creator; + +export declare enum DirectionFlow { + TopToBottom = "top-to-bottom", + BottomToTop = "bottom-to-top", + RightToLeft = "right-to-left", + LeftToRight = "left-to-right" +} + /** postcss-logical-overflow plugin options */ -export type pluginOptions = { +export declare type pluginOptions = { /** Sets the direction for inline. default: left-to-right */ inlineDirection?: DirectionFlow; }; -declare const creator: PluginCreator; -export default creator; + +export { } diff --git a/plugins/postcss-logical-overflow/dist/index.mjs b/plugins/postcss-logical-overflow/dist/index.mjs index 2f9459a97..9169d1b63 100644 --- a/plugins/postcss-logical-overflow/dist/index.mjs +++ b/plugins/postcss-logical-overflow/dist/index.mjs @@ -1 +1 @@ -var o;function transformAxes(o,t){var e;const i=t?"-x":"-y",n=t?"-y":"-x",r=o.prop.toLowerCase().replace("-inline",i).replace("-block",n),s=o.value;null!=(e=o.parent)&&e.some((o=>"decl"==o.type&&o.prop===r&&o.value===s))||(o.cloneBefore({prop:r,value:s}),o.remove())}!function(o){o.TopToBottom="top-to-bottom",o.BottomToTop="bottom-to-top",o.RightToLeft="right-to-left",o.LeftToRight="left-to-right"}(o||(o={}));const creator=t=>{const e=Object.assign({inlineDirection:o.LeftToRight},t);switch(e.inlineDirection){case o.LeftToRight:case o.RightToLeft:case o.TopToBottom:case o.BottomToTop:break;default:throw new Error(`[postcss-logical-viewport-units] "inlineDirection" must be one of ${Object.values(o).join(", ")}`)}const i=[o.LeftToRight,o.RightToLeft].includes(e.inlineDirection);return{postcssPlugin:"postcss-logical-overflow",Declaration:{"overflow-block":o=>transformAxes(o,i),"overflow-inline":o=>transformAxes(o,i)}}};creator.postcss=!0;export{creator as default}; +var o;function transformAxes(o,t){const e=t?"-x":"-y",i=t?"-y":"-x",n=o.prop.toLowerCase().replace("-inline",e).replace("-block",i),s=o.value;o.parent?.some((o=>"decl"==o.type&&o.prop===n&&o.value===s))||(o.cloneBefore({prop:n,value:s}),o.remove())}!function(o){o.TopToBottom="top-to-bottom",o.BottomToTop="bottom-to-top",o.RightToLeft="right-to-left",o.LeftToRight="left-to-right"}(o||(o={}));const creator=t=>{const e=Object.assign({inlineDirection:o.LeftToRight},t);switch(e.inlineDirection){case o.LeftToRight:case o.RightToLeft:case o.TopToBottom:case o.BottomToTop:break;default:throw new Error(`[postcss-logical-viewport-units] "inlineDirection" must be one of ${Object.values(o).join(", ")}`)}const i=[o.LeftToRight,o.RightToLeft].includes(e.inlineDirection);return{postcssPlugin:"postcss-logical-overflow",Declaration:{"overflow-block":o=>transformAxes(o,i),"overflow-inline":o=>transformAxes(o,i)}}};creator.postcss=!0;export{creator as default}; diff --git a/plugins/postcss-logical-overflow/dist/lib/transform-axes.d.ts b/plugins/postcss-logical-overflow/dist/lib/transform-axes.d.ts deleted file mode 100644 index 2bd08cdfa..000000000 --- a/plugins/postcss-logical-overflow/dist/lib/transform-axes.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import type { Declaration } from 'postcss'; -export declare function transformAxes(declaration: Declaration, isHorizontal: boolean): void; diff --git a/plugins/postcss-logical-overflow/dist/lib/types.d.ts b/plugins/postcss-logical-overflow/dist/lib/types.d.ts deleted file mode 100644 index 57d34e9f8..000000000 --- a/plugins/postcss-logical-overflow/dist/lib/types.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -export declare enum DirectionFlow { - TopToBottom = "top-to-bottom", - BottomToTop = "bottom-to-top", - RightToLeft = "right-to-left", - LeftToRight = "left-to-right" -} diff --git a/plugins/postcss-logical-overflow/package.json b/plugins/postcss-logical-overflow/package.json index 19ef20a47..2d250631d 100644 --- a/plugins/postcss-logical-overflow/package.json +++ b/plugins/postcss-logical-overflow/package.json @@ -27,15 +27,18 @@ "engines": { "node": "^14 || ^16 || >=18" }, + "type": "module", "main": "dist/index.cjs", "module": "dist/index.mjs", - "types": "dist/index.d.ts", "exports": { ".": { - "types": "./dist/index.d.ts", - "import": "./dist/index.mjs", - "require": "./dist/index.cjs", - "default": "./dist/index.mjs" + "import": { + "types": "./dist/index.d.ts", + "default": "./dist/index.mjs" + }, + "require": { + "default": "./dist/index.cjs" + } } }, "files": [ diff --git a/plugins/postcss-logical-overflow/src/index.ts b/plugins/postcss-logical-overflow/src/index.ts index abbc16009..d9af1563a 100644 --- a/plugins/postcss-logical-overflow/src/index.ts +++ b/plugins/postcss-logical-overflow/src/index.ts @@ -2,6 +2,8 @@ import type { PluginCreator } from 'postcss'; import { DirectionFlow } from './lib/types'; import { transformAxes } from './lib/transform-axes'; +export type { DirectionFlow } from './lib/types'; + /** postcss-logical-overflow plugin options */ export type pluginOptions = { /** Sets the direction for inline. default: left-to-right */ diff --git a/plugins/postcss-logical-overscroll-behavior/CHANGELOG.md b/plugins/postcss-logical-overscroll-behavior/CHANGELOG.md index 4ae602306..379f655b5 100644 --- a/plugins/postcss-logical-overscroll-behavior/CHANGELOG.md +++ b/plugins/postcss-logical-overscroll-behavior/CHANGELOG.md @@ -2,7 +2,7 @@ ### Unreleased (patch) -- Small fixes in type definitions +- Fix type definitions ### 1.0.0 diff --git a/plugins/postcss-logical-overscroll-behavior/api-extractor.json b/plugins/postcss-logical-overscroll-behavior/api-extractor.json new file mode 100644 index 000000000..42058be51 --- /dev/null +++ b/plugins/postcss-logical-overscroll-behavior/api-extractor.json @@ -0,0 +1,4 @@ +{ + "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json", + "extends": "../../api-extractor.json" +} diff --git a/plugins/postcss-logical-overscroll-behavior/dist/index.cjs b/plugins/postcss-logical-overscroll-behavior/dist/index.cjs index 1a69e1f7c..d54f6b2cf 100644 --- a/plugins/postcss-logical-overscroll-behavior/dist/index.cjs +++ b/plugins/postcss-logical-overscroll-behavior/dist/index.cjs @@ -1 +1 @@ -"use strict";var o;function transformAxes(o,t){var e;const i=t?"-x":"-y",r=t?"-y":"-x",s=o.prop.toLowerCase().replace("-inline",i).replace("-block",r),n=o.value;null!=(e=o.parent)&&e.some((o=>"decl"==o.type&&o.prop===s&&o.value===n))||(o.cloneBefore({prop:s,value:n}),o.remove())}!function(o){o.TopToBottom="top-to-bottom",o.BottomToTop="bottom-to-top",o.RightToLeft="right-to-left",o.LeftToRight="left-to-right"}(o||(o={}));const creator=t=>{const e=Object.assign({inlineDirection:o.LeftToRight},t);switch(e.inlineDirection){case o.LeftToRight:case o.RightToLeft:case o.TopToBottom:case o.BottomToTop:break;default:throw new Error(`[postcss-logical-viewport-units] "inlineDirection" must be one of ${Object.values(o).join(", ")}`)}const i=[o.LeftToRight,o.RightToLeft].includes(e.inlineDirection);return{postcssPlugin:"postcss-logical-overscroll-behavior",Declaration:{"overscroll-behavior-block":o=>transformAxes(o,i),"overscroll-behavior-inline":o=>transformAxes(o,i)}}};creator.postcss=!0,module.exports=creator; +"use strict";var o;function transformAxes(o,t){const e=t?"-x":"-y",i=t?"-y":"-x",r=o.prop.toLowerCase().replace("-inline",e).replace("-block",i),s=o.value;o.parent?.some((o=>"decl"==o.type&&o.prop===r&&o.value===s))||(o.cloneBefore({prop:r,value:s}),o.remove())}!function(o){o.TopToBottom="top-to-bottom",o.BottomToTop="bottom-to-top",o.RightToLeft="right-to-left",o.LeftToRight="left-to-right"}(o||(o={}));const creator=t=>{const e=Object.assign({inlineDirection:o.LeftToRight},t);switch(e.inlineDirection){case o.LeftToRight:case o.RightToLeft:case o.TopToBottom:case o.BottomToTop:break;default:throw new Error(`[postcss-logical-viewport-units] "inlineDirection" must be one of ${Object.values(o).join(", ")}`)}const i=[o.LeftToRight,o.RightToLeft].includes(e.inlineDirection);return{postcssPlugin:"postcss-logical-overscroll-behavior",Declaration:{"overscroll-behavior-block":o=>transformAxes(o,i),"overscroll-behavior-inline":o=>transformAxes(o,i)}}};creator.postcss=!0,module.exports=creator; diff --git a/plugins/postcss-logical-overscroll-behavior/dist/index.d.ts b/plugins/postcss-logical-overscroll-behavior/dist/index.d.ts index b285c6906..69581fa58 100644 --- a/plugins/postcss-logical-overscroll-behavior/dist/index.d.ts +++ b/plugins/postcss-logical-overscroll-behavior/dist/index.d.ts @@ -1,9 +1,19 @@ import type { PluginCreator } from 'postcss'; -import { DirectionFlow } from './lib/types'; + +declare const creator: PluginCreator; +export default creator; + +export declare enum DirectionFlow { + TopToBottom = "top-to-bottom", + BottomToTop = "bottom-to-top", + RightToLeft = "right-to-left", + LeftToRight = "left-to-right" +} + /** postcss-logical-overscroll-behavior plugin options */ -export type pluginOptions = { +export declare type pluginOptions = { /** Sets the direction for inline. default: left-to-right */ inlineDirection?: DirectionFlow; }; -declare const creator: PluginCreator; -export default creator; + +export { } diff --git a/plugins/postcss-logical-overscroll-behavior/dist/index.mjs b/plugins/postcss-logical-overscroll-behavior/dist/index.mjs index c4f70b7de..3cac5a7b0 100644 --- a/plugins/postcss-logical-overscroll-behavior/dist/index.mjs +++ b/plugins/postcss-logical-overscroll-behavior/dist/index.mjs @@ -1 +1 @@ -var o;function transformAxes(o,t){var e;const i=t?"-x":"-y",r=t?"-y":"-x",n=o.prop.toLowerCase().replace("-inline",i).replace("-block",r),s=o.value;null!=(e=o.parent)&&e.some((o=>"decl"==o.type&&o.prop===n&&o.value===s))||(o.cloneBefore({prop:n,value:s}),o.remove())}!function(o){o.TopToBottom="top-to-bottom",o.BottomToTop="bottom-to-top",o.RightToLeft="right-to-left",o.LeftToRight="left-to-right"}(o||(o={}));const creator=t=>{const e=Object.assign({inlineDirection:o.LeftToRight},t);switch(e.inlineDirection){case o.LeftToRight:case o.RightToLeft:case o.TopToBottom:case o.BottomToTop:break;default:throw new Error(`[postcss-logical-viewport-units] "inlineDirection" must be one of ${Object.values(o).join(", ")}`)}const i=[o.LeftToRight,o.RightToLeft].includes(e.inlineDirection);return{postcssPlugin:"postcss-logical-overscroll-behavior",Declaration:{"overscroll-behavior-block":o=>transformAxes(o,i),"overscroll-behavior-inline":o=>transformAxes(o,i)}}};creator.postcss=!0;export{creator as default}; +var o;function transformAxes(o,t){const e=t?"-x":"-y",i=t?"-y":"-x",r=o.prop.toLowerCase().replace("-inline",e).replace("-block",i),s=o.value;o.parent?.some((o=>"decl"==o.type&&o.prop===r&&o.value===s))||(o.cloneBefore({prop:r,value:s}),o.remove())}!function(o){o.TopToBottom="top-to-bottom",o.BottomToTop="bottom-to-top",o.RightToLeft="right-to-left",o.LeftToRight="left-to-right"}(o||(o={}));const creator=t=>{const e=Object.assign({inlineDirection:o.LeftToRight},t);switch(e.inlineDirection){case o.LeftToRight:case o.RightToLeft:case o.TopToBottom:case o.BottomToTop:break;default:throw new Error(`[postcss-logical-viewport-units] "inlineDirection" must be one of ${Object.values(o).join(", ")}`)}const i=[o.LeftToRight,o.RightToLeft].includes(e.inlineDirection);return{postcssPlugin:"postcss-logical-overscroll-behavior",Declaration:{"overscroll-behavior-block":o=>transformAxes(o,i),"overscroll-behavior-inline":o=>transformAxes(o,i)}}};creator.postcss=!0;export{creator as default}; diff --git a/plugins/postcss-logical-overscroll-behavior/dist/lib/transform-axes.d.ts b/plugins/postcss-logical-overscroll-behavior/dist/lib/transform-axes.d.ts deleted file mode 100644 index 2bd08cdfa..000000000 --- a/plugins/postcss-logical-overscroll-behavior/dist/lib/transform-axes.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import type { Declaration } from 'postcss'; -export declare function transformAxes(declaration: Declaration, isHorizontal: boolean): void; diff --git a/plugins/postcss-logical-overscroll-behavior/dist/lib/types.d.ts b/plugins/postcss-logical-overscroll-behavior/dist/lib/types.d.ts deleted file mode 100644 index 57d34e9f8..000000000 --- a/plugins/postcss-logical-overscroll-behavior/dist/lib/types.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -export declare enum DirectionFlow { - TopToBottom = "top-to-bottom", - BottomToTop = "bottom-to-top", - RightToLeft = "right-to-left", - LeftToRight = "left-to-right" -} diff --git a/plugins/postcss-logical-overscroll-behavior/package.json b/plugins/postcss-logical-overscroll-behavior/package.json index 65445f671..ad4e4a597 100644 --- a/plugins/postcss-logical-overscroll-behavior/package.json +++ b/plugins/postcss-logical-overscroll-behavior/package.json @@ -27,15 +27,18 @@ "engines": { "node": "^14 || ^16 || >=18" }, + "type": "module", "main": "dist/index.cjs", "module": "dist/index.mjs", - "types": "dist/index.d.ts", "exports": { ".": { - "types": "./dist/index.d.ts", - "import": "./dist/index.mjs", - "require": "./dist/index.cjs", - "default": "./dist/index.mjs" + "import": { + "types": "./dist/index.d.ts", + "default": "./dist/index.mjs" + }, + "require": { + "default": "./dist/index.cjs" + } } }, "files": [ diff --git a/plugins/postcss-logical-overscroll-behavior/src/index.ts b/plugins/postcss-logical-overscroll-behavior/src/index.ts index 2acce9f4e..17887529d 100644 --- a/plugins/postcss-logical-overscroll-behavior/src/index.ts +++ b/plugins/postcss-logical-overscroll-behavior/src/index.ts @@ -2,6 +2,8 @@ import type { PluginCreator } from 'postcss'; import { DirectionFlow } from './lib/types'; import { transformAxes } from './lib/transform-axes'; +export type { DirectionFlow } from './lib/types'; + /** postcss-logical-overscroll-behavior plugin options */ export type pluginOptions = { /** Sets the direction for inline. default: left-to-right */ diff --git a/plugins/postcss-logical-resize/CHANGELOG.md b/plugins/postcss-logical-resize/CHANGELOG.md index 6c5254ada..3a4b61c3f 100644 --- a/plugins/postcss-logical-resize/CHANGELOG.md +++ b/plugins/postcss-logical-resize/CHANGELOG.md @@ -2,7 +2,7 @@ ### Unreleased (patch) -- Small fixes in type definitions +- Fix type definitions ### 2.0.0 diff --git a/plugins/postcss-logical-resize/api-extractor.json b/plugins/postcss-logical-resize/api-extractor.json new file mode 100644 index 000000000..42058be51 --- /dev/null +++ b/plugins/postcss-logical-resize/api-extractor.json @@ -0,0 +1,4 @@ +{ + "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json", + "extends": "../../api-extractor.json" +} diff --git a/plugins/postcss-logical-resize/dist/index.d.ts b/plugins/postcss-logical-resize/dist/index.d.ts index 0cac31d03..1a57d9f9e 100644 --- a/plugins/postcss-logical-resize/dist/index.d.ts +++ b/plugins/postcss-logical-resize/dist/index.d.ts @@ -1,11 +1,21 @@ import type { PluginCreator } from 'postcss'; -import { DirectionFlow } from './lib/types'; + +declare const creator: PluginCreator; +export default creator; + +export declare enum DirectionFlow { + TopToBottom = "top-to-bottom", + BottomToTop = "bottom-to-top", + RightToLeft = "right-to-left", + LeftToRight = "left-to-right" +} + /** postcss-logical-resize plugin options */ -export type pluginOptions = { +export declare type pluginOptions = { /** Sets the direction for block. default: top-to-bottom */ blockDirection?: DirectionFlow; /** Sets the direction for inline. default: left-to-right */ inlineDirection?: DirectionFlow; }; -declare const creator: PluginCreator; -export default creator; + +export { } diff --git a/plugins/postcss-logical-resize/dist/lib/clone-declaration.d.ts b/plugins/postcss-logical-resize/dist/lib/clone-declaration.d.ts deleted file mode 100644 index 1503bf6f1..000000000 --- a/plugins/postcss-logical-resize/dist/lib/clone-declaration.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import type { Declaration } from 'postcss'; -export declare function cloneDeclaration(declaration: Declaration, value: string, prop: string): void; diff --git a/plugins/postcss-logical-resize/dist/lib/transform-resize.d.ts b/plugins/postcss-logical-resize/dist/lib/transform-resize.d.ts deleted file mode 100644 index 12100551c..000000000 --- a/plugins/postcss-logical-resize/dist/lib/transform-resize.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -import type { Declaration } from 'postcss'; -import { DirectionConfig } from './types'; -export declare function transformResize(directionConfig: DirectionConfig): (declaration: Declaration) => boolean; diff --git a/plugins/postcss-logical-resize/dist/lib/types.d.ts b/plugins/postcss-logical-resize/dist/lib/types.d.ts deleted file mode 100644 index 53dd4d416..000000000 --- a/plugins/postcss-logical-resize/dist/lib/types.d.ts +++ /dev/null @@ -1,22 +0,0 @@ -declare enum Direction { - Block = "block", - Inline = "inline" -} -export declare enum DirectionFlow { - TopToBottom = "top-to-bottom", - BottomToTop = "bottom-to-top", - RightToLeft = "right-to-left", - LeftToRight = "left-to-right" -} -export declare enum Axes { - Top = "top", - Right = "right", - Bottom = "bottom", - Left = "left" -} -export type DirectionConfig = { - [Direction.Block]: [Axes, Axes]; - [Direction.Inline]: [Axes, Axes]; - inlineIsHorizontal: boolean; -}; -export {}; diff --git a/plugins/postcss-logical-resize/dist/utils/direction-flow-to-axes.d.ts b/plugins/postcss-logical-resize/dist/utils/direction-flow-to-axes.d.ts deleted file mode 100644 index 2652d71d8..000000000 --- a/plugins/postcss-logical-resize/dist/utils/direction-flow-to-axes.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import { DirectionFlow, Axes } from '../lib/types'; -export declare function directionFlowToAxes(directionFlow: DirectionFlow): [Axes, Axes]; diff --git a/plugins/postcss-logical-resize/package.json b/plugins/postcss-logical-resize/package.json index 9fa60ff6d..aec2c8747 100644 --- a/plugins/postcss-logical-resize/package.json +++ b/plugins/postcss-logical-resize/package.json @@ -27,15 +27,18 @@ "engines": { "node": "^14 || ^16 || >=18" }, + "type": "module", "main": "dist/index.cjs", "module": "dist/index.mjs", - "types": "dist/index.d.ts", "exports": { ".": { - "types": "./dist/index.d.ts", - "import": "./dist/index.mjs", - "require": "./dist/index.cjs", - "default": "./dist/index.mjs" + "import": { + "types": "./dist/index.d.ts", + "default": "./dist/index.mjs" + }, + "require": { + "default": "./dist/index.cjs" + } } }, "files": [ diff --git a/plugins/postcss-logical-resize/src/index.ts b/plugins/postcss-logical-resize/src/index.ts index d11196697..23cf2ce49 100644 --- a/plugins/postcss-logical-resize/src/index.ts +++ b/plugins/postcss-logical-resize/src/index.ts @@ -3,6 +3,8 @@ import { Axes, DirectionConfig, DirectionFlow } from './lib/types'; import { transformResize } from './lib/transform-resize'; import { directionFlowToAxes } from './utils/direction-flow-to-axes'; +export type { DirectionFlow } from './lib/types'; + /** postcss-logical-resize plugin options */ export type pluginOptions = { /** Sets the direction for block. default: top-to-bottom */ diff --git a/plugins/postcss-logical-viewport-units/CHANGELOG.md b/plugins/postcss-logical-viewport-units/CHANGELOG.md index 6d972b017..68a9787c4 100644 --- a/plugins/postcss-logical-viewport-units/CHANGELOG.md +++ b/plugins/postcss-logical-viewport-units/CHANGELOG.md @@ -2,7 +2,7 @@ ### Unreleased (patch) -- Small fixes in type definitions +- Fix type definitions ### 2.0.3 diff --git a/plugins/postcss-logical-viewport-units/api-extractor.json b/plugins/postcss-logical-viewport-units/api-extractor.json new file mode 100644 index 000000000..42058be51 --- /dev/null +++ b/plugins/postcss-logical-viewport-units/api-extractor.json @@ -0,0 +1,4 @@ +{ + "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json", + "extends": "../../api-extractor.json" +} diff --git a/plugins/postcss-logical-viewport-units/dist/has-feature.d.ts b/plugins/postcss-logical-viewport-units/dist/has-feature.d.ts deleted file mode 100644 index a902b0da2..000000000 --- a/plugins/postcss-logical-viewport-units/dist/has-feature.d.ts +++ /dev/null @@ -1 +0,0 @@ -export declare function hasFeature(source: string): boolean; diff --git a/plugins/postcss-logical-viewport-units/dist/has-supports-at-rule-ancestor.d.ts b/plugins/postcss-logical-viewport-units/dist/has-supports-at-rule-ancestor.d.ts deleted file mode 100644 index a46009ecc..000000000 --- a/plugins/postcss-logical-viewport-units/dist/has-supports-at-rule-ancestor.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import type { Node } from 'postcss'; -export declare function hasSupportsAtRuleAncestor(node: Node): boolean; diff --git a/plugins/postcss-logical-viewport-units/dist/index.d.ts b/plugins/postcss-logical-viewport-units/dist/index.d.ts index bf4c6641b..7933d724d 100644 --- a/plugins/postcss-logical-viewport-units/dist/index.d.ts +++ b/plugins/postcss-logical-viewport-units/dist/index.d.ts @@ -1,11 +1,21 @@ import type { PluginCreator } from 'postcss'; -import { DirectionFlow } from './lib/types'; + +declare const creator: PluginCreator; +export default creator; + +export declare enum DirectionFlow { + TopToBottom = "top-to-bottom", + BottomToTop = "bottom-to-top", + RightToLeft = "right-to-left", + LeftToRight = "left-to-right" +} + /** postcss-logical-viewport-units plugin options */ -export type pluginOptions = { +export declare type pluginOptions = { /** Preserve the original notation. default: false */ preserve?: boolean; /** Sets the direction for inline. default: left-to-right */ inlineDirection?: DirectionFlow; }; -declare const creator: PluginCreator; -export default creator; + +export { } diff --git a/plugins/postcss-logical-viewport-units/dist/lib/types.d.ts b/plugins/postcss-logical-viewport-units/dist/lib/types.d.ts deleted file mode 100644 index 57d34e9f8..000000000 --- a/plugins/postcss-logical-viewport-units/dist/lib/types.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -export declare enum DirectionFlow { - TopToBottom = "top-to-bottom", - BottomToTop = "bottom-to-top", - RightToLeft = "right-to-left", - LeftToRight = "left-to-right" -} diff --git a/plugins/postcss-logical-viewport-units/dist/transform.d.ts b/plugins/postcss-logical-viewport-units/dist/transform.d.ts deleted file mode 100644 index 0d007ffa5..000000000 --- a/plugins/postcss-logical-viewport-units/dist/transform.d.ts +++ /dev/null @@ -1,4 +0,0 @@ -export declare function transform(source: string, replacements: { - vi: 'vw' | 'vh'; - vb: 'vw' | 'vh'; -}): string; diff --git a/plugins/postcss-logical-viewport-units/package.json b/plugins/postcss-logical-viewport-units/package.json index f20a819d0..674aaa667 100644 --- a/plugins/postcss-logical-viewport-units/package.json +++ b/plugins/postcss-logical-viewport-units/package.json @@ -27,15 +27,18 @@ "engines": { "node": "^14 || ^16 || >=18" }, + "type": "module", "main": "dist/index.cjs", "module": "dist/index.mjs", - "types": "dist/index.d.ts", "exports": { ".": { - "types": "./dist/index.d.ts", - "import": "./dist/index.mjs", - "require": "./dist/index.cjs", - "default": "./dist/index.mjs" + "import": { + "types": "./dist/index.d.ts", + "default": "./dist/index.mjs" + }, + "require": { + "default": "./dist/index.cjs" + } } }, "files": [ diff --git a/plugins/postcss-logical-viewport-units/src/index.ts b/plugins/postcss-logical-viewport-units/src/index.ts index 4d654ff4f..bab3abbdd 100644 --- a/plugins/postcss-logical-viewport-units/src/index.ts +++ b/plugins/postcss-logical-viewport-units/src/index.ts @@ -3,6 +3,8 @@ import { hasSupportsAtRuleAncestor } from './has-supports-at-rule-ancestor'; import { DirectionFlow } from './lib/types'; import { transform } from './transform'; +export type { DirectionFlow } from './lib/types'; + /** postcss-logical-viewport-units plugin options */ export type pluginOptions = { /** Preserve the original notation. default: false */ diff --git a/plugins/postcss-logical/CHANGELOG.md b/plugins/postcss-logical/CHANGELOG.md index 6b9059d82..f2bcf83e1 100644 --- a/plugins/postcss-logical/CHANGELOG.md +++ b/plugins/postcss-logical/CHANGELOG.md @@ -2,7 +2,7 @@ ### Unreleased (patch) -- Small fixes in type definitions +- Fix type definitions ### 7.0.0 diff --git a/plugins/postcss-logical/api-extractor.json b/plugins/postcss-logical/api-extractor.json new file mode 100644 index 000000000..42058be51 --- /dev/null +++ b/plugins/postcss-logical/api-extractor.json @@ -0,0 +1,4 @@ +{ + "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json", + "extends": "../../api-extractor.json" +} diff --git a/plugins/postcss-logical/dist/index.cjs b/plugins/postcss-logical/dist/index.cjs index cd2f482b4..048aa3c91 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})=>{var o;if(!r)return;let t=[];try{t=r(e)}catch(r){return void e.warn(n,r instanceof Error?r.message:String(r))}null!=(o=t)&&o.length&&(t.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})=>{var o;let t=[];try{t=transformTransition(r,n,d)}catch(n){return void r.warn(e,n instanceof Error?n.message:String(n))}null!=(o=t)&&o.length&&(t.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);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; diff --git a/plugins/postcss-logical/dist/index.d.ts b/plugins/postcss-logical/dist/index.d.ts index 8e84fd80d..054498860 100644 --- a/plugins/postcss-logical/dist/index.d.ts +++ b/plugins/postcss-logical/dist/index.d.ts @@ -1,11 +1,21 @@ import type { PluginCreator } from 'postcss'; -import { DirectionFlow } from './lib/types'; + +declare const creator: PluginCreator; +export default creator; + +export declare enum DirectionFlow { + TopToBottom = "top-to-bottom", + BottomToTop = "bottom-to-top", + RightToLeft = "right-to-left", + LeftToRight = "left-to-right" +} + /** postcss-logical plugin options */ -export type pluginOptions = { +export declare type pluginOptions = { /** Sets the direction for block. default: top-to-bottom */ blockDirection?: DirectionFlow; /** Sets the direction for inline. default: left-to-right */ inlineDirection?: DirectionFlow; }; -declare const creator: PluginCreator; -export default creator; + +export { } diff --git a/plugins/postcss-logical/dist/index.mjs b/plugins/postcss-logical/dist/index.mjs index df02acf38..6359f5928 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})=>{var o;if(!r)return;let t=[];try{t=r(e)}catch(r){return void e.warn(n,r instanceof Error?r.message:String(r))}null!=(o=t)&&o.length&&(t.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})=>{var o;let t=[];try{t=transformTransition(r,n,d)}catch(n){return void r.warn(e,n instanceof Error?n.message:String(n))}null!=(o=t)&&o.length&&(t.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);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}; diff --git a/plugins/postcss-logical/dist/lib/clone-declaration.d.ts b/plugins/postcss-logical/dist/lib/clone-declaration.d.ts deleted file mode 100644 index 3aef68c65..000000000 --- a/plugins/postcss-logical/dist/lib/clone-declaration.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import type { Declaration } from 'postcss'; -export declare function cloneDeclaration(declaration: Declaration, value: string, prop: string): Array; diff --git a/plugins/postcss-logical/dist/lib/transform-borders.d.ts b/plugins/postcss-logical/dist/lib/transform-borders.d.ts deleted file mode 100644 index 3da86c21f..000000000 --- a/plugins/postcss-logical/dist/lib/transform-borders.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -import type { Declaration } from 'postcss'; -import { DirectionConfig } from './types'; -export declare function transformBorder(borderSetting: string, side: string): (declaration: Declaration) => Array; -export declare function transformBorderProperty(borderSetting: string, side: [string, string]): (declaration: Declaration) => Array; -export declare function transformBorderShorthand(side: [string] | [string, string]): (declaration: Declaration) => Array; -export declare function transformBorderRadius(config: DirectionConfig): (declaration: Declaration) => Array; diff --git a/plugins/postcss-logical/dist/lib/transform-inset.d.ts b/plugins/postcss-logical/dist/lib/transform-inset.d.ts deleted file mode 100644 index 6d028e216..000000000 --- a/plugins/postcss-logical/dist/lib/transform-inset.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import type { Declaration } from 'postcss'; -export declare function transformInset(): (declaration: Declaration) => Array; diff --git a/plugins/postcss-logical/dist/lib/transform-logical-size.d.ts b/plugins/postcss-logical/dist/lib/transform-logical-size.d.ts deleted file mode 100644 index 9831d2946..000000000 --- a/plugins/postcss-logical/dist/lib/transform-logical-size.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -import type { Declaration } from 'postcss'; -import { DirectionConfig } from './types'; -export declare function transformLogicalSize(directionConfig: DirectionConfig): (declaration: Declaration) => Array; diff --git a/plugins/postcss-logical/dist/lib/transform-offset.d.ts b/plugins/postcss-logical/dist/lib/transform-offset.d.ts deleted file mode 100644 index d8bf7e789..000000000 --- a/plugins/postcss-logical/dist/lib/transform-offset.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -import type { Declaration } from 'postcss'; -export declare function transformOffset(prop: string): (declaration: Declaration) => Array; -export declare function transformOffsetShorthand(side: [string, string]): (declaration: Declaration) => Array; diff --git a/plugins/postcss-logical/dist/lib/transform-side.d.ts b/plugins/postcss-logical/dist/lib/transform-side.d.ts deleted file mode 100644 index 56396d740..000000000 --- a/plugins/postcss-logical/dist/lib/transform-side.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -import type { Declaration } from 'postcss'; -export declare function transformSide(prop: string, side: string): (declaration: Declaration) => Array; -export declare function transformSideShorthand(prop: string, side: [string, string]): (declaration: Declaration) => Array; diff --git a/plugins/postcss-logical/dist/lib/transform-text-align.d.ts b/plugins/postcss-logical/dist/lib/transform-text-align.d.ts deleted file mode 100644 index 752a58082..000000000 --- a/plugins/postcss-logical/dist/lib/transform-text-align.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import type { Declaration } from 'postcss'; -export declare function transformTextAlign(inlineValues: [string, string]): (declaration: Declaration) => Array; diff --git a/plugins/postcss-logical/dist/lib/transform-transition.d.ts b/plugins/postcss-logical/dist/lib/transform-transition.d.ts deleted file mode 100644 index 8745ed168..000000000 --- a/plugins/postcss-logical/dist/lib/transform-transition.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -import type { Declaration, Postcss } from 'postcss'; -import { TransformFunction } from './types'; -export declare function transformTransition(declaration: Declaration, postcss: Postcss, transforms: Record): Array; diff --git a/plugins/postcss-logical/dist/lib/transform-value.d.ts b/plugins/postcss-logical/dist/lib/transform-value.d.ts deleted file mode 100644 index 23a30bbb6..000000000 --- a/plugins/postcss-logical/dist/lib/transform-value.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -import type { Declaration } from 'postcss'; -import { DirectionConfig } from './types'; -export declare function transformValue(config: DirectionConfig): (declaration: Declaration) => Array; diff --git a/plugins/postcss-logical/dist/lib/transforms.d.ts b/plugins/postcss-logical/dist/lib/transforms.d.ts deleted file mode 100644 index c54791689..000000000 --- a/plugins/postcss-logical/dist/lib/transforms.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import { Axes, DirectionConfig, TransformFunction } from './types'; -export declare function prepareTransforms(directionConfig: DirectionConfig, blockStart: Axes, blockEnd: Axes, inlineStart: Axes, inlineEnd: Axes): Record; diff --git a/plugins/postcss-logical/dist/lib/types.d.ts b/plugins/postcss-logical/dist/lib/types.d.ts deleted file mode 100644 index 52166e042..000000000 --- a/plugins/postcss-logical/dist/lib/types.d.ts +++ /dev/null @@ -1,34 +0,0 @@ -import type { Declaration } from 'postcss'; -declare enum Direction { - Block = "block", - Inline = "inline" -} -export declare enum DirectionValue { - Start = "start", - End = "end" -} -export declare const DirectionValues: { - BlockStart: string; - BlockEnd: string; - InlineStart: string; - InlineEnd: string; -}; -export declare enum DirectionFlow { - TopToBottom = "top-to-bottom", - BottomToTop = "bottom-to-top", - RightToLeft = "right-to-left", - LeftToRight = "left-to-right" -} -export declare enum Axes { - Top = "top", - Right = "right", - Bottom = "bottom", - Left = "left" -} -export type DirectionConfig = { - [Direction.Block]: [Axes, Axes]; - [Direction.Inline]: [Axes, Axes]; - inlineIsHorizontal: boolean; -}; -export type TransformFunction = (decl: Declaration) => Array; -export {}; diff --git a/plugins/postcss-logical/dist/utils/direction-flow-to-axes.d.ts b/plugins/postcss-logical/dist/utils/direction-flow-to-axes.d.ts deleted file mode 100644 index 2652d71d8..000000000 --- a/plugins/postcss-logical/dist/utils/direction-flow-to-axes.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import { DirectionFlow, Axes } from '../lib/types'; -export declare function directionFlowToAxes(directionFlow: DirectionFlow): [Axes, Axes]; diff --git a/plugins/postcss-logical/dist/utils/logical-to-physical.d.ts b/plugins/postcss-logical/dist/utils/logical-to-physical.d.ts deleted file mode 100644 index 764ee732c..000000000 --- a/plugins/postcss-logical/dist/utils/logical-to-physical.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import { DirectionConfig } from '../lib/types'; -export declare function logicalToPhysical(logical: string, config: DirectionConfig): string; diff --git a/plugins/postcss-logical/dist/utils/parse-value-couple.d.ts b/plugins/postcss-logical/dist/utils/parse-value-couple.d.ts deleted file mode 100644 index 124566572..000000000 --- a/plugins/postcss-logical/dist/utils/parse-value-couple.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import type { Declaration } from 'postcss'; -export declare function parseValueCouple(declaration: Declaration): [string, string]; diff --git a/plugins/postcss-logical/package.json b/plugins/postcss-logical/package.json index c408b37be..2845095c1 100644 --- a/plugins/postcss-logical/package.json +++ b/plugins/postcss-logical/package.json @@ -31,15 +31,18 @@ "engines": { "node": "^14 || ^16 || >=18" }, + "type": "module", "main": "dist/index.cjs", "module": "dist/index.mjs", - "types": "dist/index.d.ts", "exports": { ".": { - "types": "./dist/index.d.ts", - "import": "./dist/index.mjs", - "require": "./dist/index.cjs", - "default": "./dist/index.mjs" + "import": { + "types": "./dist/index.d.ts", + "default": "./dist/index.mjs" + }, + "require": { + "default": "./dist/index.cjs" + } } }, "files": [ diff --git a/plugins/postcss-logical/src/index.ts b/plugins/postcss-logical/src/index.ts index 8846034e2..aa18b7541 100644 --- a/plugins/postcss-logical/src/index.ts +++ b/plugins/postcss-logical/src/index.ts @@ -4,6 +4,8 @@ import { directionFlowToAxes } from './utils/direction-flow-to-axes'; import { transformTransition } from './lib/transform-transition'; import { prepareTransforms } from './lib/transforms'; +export type { DirectionFlow } from './lib/types'; + /** postcss-logical plugin options */ export type pluginOptions = { /** Sets the direction for block. default: top-to-bottom */ diff --git a/plugins/postcss-media-minmax/CHANGELOG.md b/plugins/postcss-media-minmax/CHANGELOG.md index 2ed00d6de..a02f2acc7 100644 --- a/plugins/postcss-media-minmax/CHANGELOG.md +++ b/plugins/postcss-media-minmax/CHANGELOG.md @@ -1,5 +1,9 @@ # Changes to PostCSS Media MinMax +### Unreleased (patch) + +- Fix type definitions + ### 1.1.0 _September 24, 2023_ diff --git a/plugins/postcss-media-minmax/api-extractor.json b/plugins/postcss-media-minmax/api-extractor.json new file mode 100644 index 000000000..42058be51 --- /dev/null +++ b/plugins/postcss-media-minmax/api-extractor.json @@ -0,0 +1,4 @@ +{ + "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json", + "extends": "../../api-extractor.json" +} diff --git a/plugins/postcss-media-minmax/dist/index.d.ts b/plugins/postcss-media-minmax/dist/index.d.ts index f22ef708d..e60e05c07 100644 --- a/plugins/postcss-media-minmax/dist/index.d.ts +++ b/plugins/postcss-media-minmax/dist/index.d.ts @@ -1,5 +1,9 @@ import type { PluginCreator } from 'postcss'; -/** postcss-media-minmax plugin options */ -export type pluginOptions = never; + declare const creator: PluginCreator; export default creator; + +/** postcss-media-minmax plugin options */ +export declare type pluginOptions = never; + +export { } diff --git a/plugins/postcss-media-minmax/dist/to-lower-case-a-z.d.ts b/plugins/postcss-media-minmax/dist/to-lower-case-a-z.d.ts deleted file mode 100644 index 396b252e7..000000000 --- a/plugins/postcss-media-minmax/dist/to-lower-case-a-z.d.ts +++ /dev/null @@ -1 +0,0 @@ -export declare function toLowerCaseAZ(x: string): string; diff --git a/plugins/postcss-media-minmax/dist/transform-single-pair.d.ts b/plugins/postcss-media-minmax/dist/transform-single-pair.d.ts deleted file mode 100644 index 2b3e5ce09..000000000 --- a/plugins/postcss-media-minmax/dist/transform-single-pair.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import { MediaFeature, MediaFeatureComparison, MediaFeatureValue } from '@csstools/media-query-list-parser'; -export declare function transformSingleNameValuePair(name: string, operator: MediaFeatureComparison, value: MediaFeatureValue, nameBeforeValue: boolean): MediaFeature | undefined; diff --git a/plugins/postcss-media-minmax/dist/transform.d.ts b/plugins/postcss-media-minmax/dist/transform.d.ts deleted file mode 100644 index 9bcd62232..000000000 --- a/plugins/postcss-media-minmax/dist/transform.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import { MediaQuery } from '@csstools/media-query-list-parser'; -export declare function transform(mediaQueries: Array): string; diff --git a/plugins/postcss-media-minmax/package.json b/plugins/postcss-media-minmax/package.json index aded6cb63..0d2859494 100644 --- a/plugins/postcss-media-minmax/package.json +++ b/plugins/postcss-media-minmax/package.json @@ -30,15 +30,18 @@ "engines": { "node": "^14 || ^16 || >=18" }, + "type": "module", "main": "dist/index.cjs", "module": "dist/index.mjs", - "types": "dist/index.d.ts", "exports": { ".": { - "types": "./dist/index.d.ts", - "import": "./dist/index.mjs", - "require": "./dist/index.cjs", - "default": "./dist/index.mjs" + "import": { + "types": "./dist/index.d.ts", + "default": "./dist/index.mjs" + }, + "require": { + "default": "./dist/index.cjs" + } } }, "files": [ diff --git a/plugins/postcss-media-queries-aspect-ratio-number-values/CHANGELOG.md b/plugins/postcss-media-queries-aspect-ratio-number-values/CHANGELOG.md index 71c37160c..d8cc0b9a5 100644 --- a/plugins/postcss-media-queries-aspect-ratio-number-values/CHANGELOG.md +++ b/plugins/postcss-media-queries-aspect-ratio-number-values/CHANGELOG.md @@ -1,5 +1,9 @@ # Changes to PostCSS Media Queries Aspect-Ratio Number Values +### Unreleased (patch) + +- Fix type definitions + ### 2.0.3 _September 24, 2023_ diff --git a/plugins/postcss-media-queries-aspect-ratio-number-values/api-extractor.json b/plugins/postcss-media-queries-aspect-ratio-number-values/api-extractor.json new file mode 100644 index 000000000..42058be51 --- /dev/null +++ b/plugins/postcss-media-queries-aspect-ratio-number-values/api-extractor.json @@ -0,0 +1,4 @@ +{ + "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json", + "extends": "../../api-extractor.json" +} diff --git a/plugins/postcss-media-queries-aspect-ratio-number-values/dist/index.d.ts b/plugins/postcss-media-queries-aspect-ratio-number-values/dist/index.d.ts index 92223f793..5c1498f8c 100644 --- a/plugins/postcss-media-queries-aspect-ratio-number-values/dist/index.d.ts +++ b/plugins/postcss-media-queries-aspect-ratio-number-values/dist/index.d.ts @@ -1,8 +1,12 @@ import type { PluginCreator } from 'postcss'; + +declare const creator: PluginCreator; +export default creator; + /** postcss-media-queries-aspect-ratio-number-values plugin options */ -export type pluginOptions = { +export declare type pluginOptions = { /** Preserve the original notation. default: false */ preserve?: boolean; }; -declare const creator: PluginCreator; -export default creator; + +export { } diff --git a/plugins/postcss-media-queries-aspect-ratio-number-values/dist/transform-media-feature-value.d.ts b/plugins/postcss-media-queries-aspect-ratio-number-values/dist/transform-media-feature-value.d.ts deleted file mode 100644 index 1808b9463..000000000 --- a/plugins/postcss-media-queries-aspect-ratio-number-values/dist/transform-media-feature-value.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import { MediaFeatureValue } from '@csstools/media-query-list-parser'; -export declare function transformMediaFeatureValue(value: MediaFeatureValue): void; diff --git a/plugins/postcss-media-queries-aspect-ratio-number-values/dist/transform-media-query-list.d.ts b/plugins/postcss-media-queries-aspect-ratio-number-values/dist/transform-media-query-list.d.ts deleted file mode 100644 index a2fcb6a91..000000000 --- a/plugins/postcss-media-queries-aspect-ratio-number-values/dist/transform-media-query-list.d.ts +++ /dev/null @@ -1 +0,0 @@ -export declare function transformMediaQueryList(params: string, preserve: boolean): string; diff --git a/plugins/postcss-media-queries-aspect-ratio-number-values/package.json b/plugins/postcss-media-queries-aspect-ratio-number-values/package.json index b7c3b0335..b5fd68911 100644 --- a/plugins/postcss-media-queries-aspect-ratio-number-values/package.json +++ b/plugins/postcss-media-queries-aspect-ratio-number-values/package.json @@ -27,15 +27,18 @@ "engines": { "node": "^14 || ^16 || >=18" }, + "type": "module", "main": "dist/index.cjs", "module": "dist/index.mjs", - "types": "dist/index.d.ts", "exports": { ".": { - "types": "./dist/index.d.ts", - "import": "./dist/index.mjs", - "require": "./dist/index.cjs", - "default": "./dist/index.mjs" + "import": { + "types": "./dist/index.d.ts", + "default": "./dist/index.mjs" + }, + "require": { + "default": "./dist/index.cjs" + } } }, "files": [ diff --git a/plugins/postcss-minify/CHANGELOG.md b/plugins/postcss-minify/CHANGELOG.md index 964fe07af..8d111c917 100644 --- a/plugins/postcss-minify/CHANGELOG.md +++ b/plugins/postcss-minify/CHANGELOG.md @@ -1,5 +1,9 @@ # Changes to PostCSS Minify +### Unreleased (patch) + +- Fix type definitions + ### 1.0.2 _October 5, 2023_ diff --git a/plugins/postcss-minify/api-extractor.json b/plugins/postcss-minify/api-extractor.json new file mode 100644 index 000000000..42058be51 --- /dev/null +++ b/plugins/postcss-minify/api-extractor.json @@ -0,0 +1,4 @@ +{ + "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json", + "extends": "../../api-extractor.json" +} diff --git a/plugins/postcss-minify/dist/index.cjs b/plugins/postcss-minify/dist/index.cjs index 602972b28..8c50074a6 100644 --- a/plugins/postcss-minify/dist/index.cjs +++ b/plugins/postcss-minify/dist/index.cjs @@ -1 +1 @@ -"use strict";var e=require("@csstools/css-tokenizer");const t=/(?:license|copyright)/i,r=/sourceMappingURL/i,s=/(?:\s|\/\*)/,o=/^layer$/i;function minify(t,r){if(!r)return r;if(t.has(r))return t.get(r);const o=r.trim();if(""===o)return t.set(r,""),"";if(!s.test(o))return t.set(r,o),o;const n=e.tokenize({css:o});let i,a=!1;for(let t=0;t{const e=new Map;return{postcssPlugin:"postcss-minify",OnceExit(s){s.raws.before="",s.raws.after="\n",s.walk((s=>{switch(s.type){case"atrule":if(removeEmptyNodes(s))return;return s.raws.after="",s.raws.afterName=" ",s.raws.before="",s.raws.between="",s.raws.params=void 0,setSemicolon(s),void(s.params=minify(e,s.params));case"rule":if(removeEmptyNodes(s))return;return s.raws.after="",s.raws.before="",s.raws.between="",s.raws.selector=void 0,setSemicolon(s),void(s.selector=minify(e,s.selector));case"decl":return s.prop.startsWith("--")?void(s.raws.before=""):(s.raws.before="",s.raws.between=":",s.raws.important=s.important?"!important":"",s.raws.value=void 0,void(s.value=minify(e,s.value)));case"comment":return t.test(s.text)||r.test(s.text)?void(s.raws.before=""):void s.remove()}}))}}};creator.postcss=!0,module.exports=creator; +"use strict";var e=require("@csstools/css-tokenizer");const t=/(?:license|copyright)/i,r=/sourceMappingURL/i,s=/(?:\s|\/\*)/,o=/^layer$/i;function minify(t,r){if(!r)return r;if(t.has(r))return t.get(r);const o=r.trim();if(""===o)return t.set(r,""),"";if(!s.test(o))return t.set(r,o),o;const n=e.tokenize({css:o});let i,a=!1;for(let t=0;t{const e=new Map;return{postcssPlugin:"postcss-minify",OnceExit(s){s.raws.before="",s.raws.after="\n",s.walk((s=>{switch(s.type){case"atrule":if(removeEmptyNodes(s))return;return s.raws.after="",s.raws.afterName=" ",s.raws.before="",s.raws.between="",s.raws.params=void 0,setSemicolon(s),void(s.params=minify(e,s.params));case"rule":if(removeEmptyNodes(s))return;return s.raws.after="",s.raws.before="",s.raws.between="",s.raws.selector=void 0,setSemicolon(s),void(s.selector=minify(e,s.selector));case"decl":return s.prop.startsWith("--")?void(s.raws.before=""):(s.raws.before="",s.raws.between=":",s.raws.important=s.important?"!important":"",s.raws.value=void 0,void(s.value=minify(e,s.value)));case"comment":return t.test(s.text)||r.test(s.text)?void(s.raws.before=""):void s.remove()}}))}}};creator.postcss=!0,module.exports=creator; diff --git a/plugins/postcss-minify/dist/index.d.ts b/plugins/postcss-minify/dist/index.d.ts index 89d1b34a1..332621cd8 100644 --- a/plugins/postcss-minify/dist/index.d.ts +++ b/plugins/postcss-minify/dist/index.d.ts @@ -1,5 +1,9 @@ import type { PluginCreator } from 'postcss'; -/** postcss-minify plugin options */ -export type pluginOptions = never; + declare const creator: PluginCreator; export default creator; + +/** postcss-minify plugin options */ +export declare type pluginOptions = never; + +export { } diff --git a/plugins/postcss-minify/dist/index.mjs b/plugins/postcss-minify/dist/index.mjs index b054719a8..77e2af622 100644 --- a/plugins/postcss-minify/dist/index.mjs +++ b/plugins/postcss-minify/dist/index.mjs @@ -1 +1 @@ -import{tokenize as e,TokenType as t}from"@csstools/css-tokenizer";const r=/(?:license|copyright)/i,s=/sourceMappingURL/i,o=/(?:\s|\/\*)/,n=/^layer$/i;function minify(r,s){if(!s)return s;if(r.has(s))return r.get(s);const n=s.trim();if(""===n)return r.set(s,""),"";if(!o.test(n))return r.set(s,n),n;const a=e({css:n});let i,l=!1;for(let e=0;e{const e=new Map;return{postcssPlugin:"postcss-minify",OnceExit(t){t.raws.before="",t.raws.after="\n",t.walk((t=>{switch(t.type){case"atrule":if(removeEmptyNodes(t))return;return t.raws.after="",t.raws.afterName=" ",t.raws.before="",t.raws.between="",t.raws.params=void 0,setSemicolon(t),void(t.params=minify(e,t.params));case"rule":if(removeEmptyNodes(t))return;return t.raws.after="",t.raws.before="",t.raws.between="",t.raws.selector=void 0,setSemicolon(t),void(t.selector=minify(e,t.selector));case"decl":return t.prop.startsWith("--")?void(t.raws.before=""):(t.raws.before="",t.raws.between=":",t.raws.important=t.important?"!important":"",t.raws.value=void 0,void(t.value=minify(e,t.value)));case"comment":return r.test(t.text)||s.test(t.text)?void(t.raws.before=""):void t.remove()}}))}}};creator.postcss=!0;export{creator as default}; +import{tokenize as e,TokenType as t}from"@csstools/css-tokenizer";const r=/(?:license|copyright)/i,s=/sourceMappingURL/i,o=/(?:\s|\/\*)/,n=/^layer$/i;function minify(r,s){if(!s)return s;if(r.has(s))return r.get(s);const n=s.trim();if(""===n)return r.set(s,""),"";if(!o.test(n))return r.set(s,n),n;const a=e({css:n});let i,c=!1;for(let e=0;e{const e=new Map;return{postcssPlugin:"postcss-minify",OnceExit(t){t.raws.before="",t.raws.after="\n",t.walk((t=>{switch(t.type){case"atrule":if(removeEmptyNodes(t))return;return t.raws.after="",t.raws.afterName=" ",t.raws.before="",t.raws.between="",t.raws.params=void 0,setSemicolon(t),void(t.params=minify(e,t.params));case"rule":if(removeEmptyNodes(t))return;return t.raws.after="",t.raws.before="",t.raws.between="",t.raws.selector=void 0,setSemicolon(t),void(t.selector=minify(e,t.selector));case"decl":return t.prop.startsWith("--")?void(t.raws.before=""):(t.raws.before="",t.raws.between=":",t.raws.important=t.important?"!important":"",t.raws.value=void 0,void(t.value=minify(e,t.value)));case"comment":return r.test(t.text)||s.test(t.text)?void(t.raws.before=""):void t.remove()}}))}}};creator.postcss=!0;export{creator as default}; diff --git a/plugins/postcss-minify/package.json b/plugins/postcss-minify/package.json index 750f3fba5..2338af2e2 100644 --- a/plugins/postcss-minify/package.json +++ b/plugins/postcss-minify/package.json @@ -27,15 +27,18 @@ "engines": { "node": "^14 || ^16 || >=18" }, + "type": "module", "main": "dist/index.cjs", "module": "dist/index.mjs", - "types": "dist/index.d.ts", "exports": { ".": { - "types": "./dist/index.d.ts", - "import": "./dist/index.mjs", - "require": "./dist/index.cjs", - "default": "./dist/index.mjs" + "import": { + "types": "./dist/index.d.ts", + "default": "./dist/index.mjs" + }, + "require": { + "default": "./dist/index.cjs" + } } }, "files": [ diff --git a/plugins/postcss-nested-calc/CHANGELOG.md b/plugins/postcss-nested-calc/CHANGELOG.md index fc9be8f1e..8c0a1fb70 100644 --- a/plugins/postcss-nested-calc/CHANGELOG.md +++ b/plugins/postcss-nested-calc/CHANGELOG.md @@ -1,5 +1,9 @@ # Changes to PostCSS Nested Calc +### Unreleased (patch) + +- Fix type definitions + ### 3.0.0 _July 3, 2023_ diff --git a/plugins/postcss-nested-calc/api-extractor.json b/plugins/postcss-nested-calc/api-extractor.json new file mode 100644 index 000000000..42058be51 --- /dev/null +++ b/plugins/postcss-nested-calc/api-extractor.json @@ -0,0 +1,4 @@ +{ + "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json", + "extends": "../../api-extractor.json" +} diff --git a/plugins/postcss-nested-calc/dist/has-fallback-decl.d.ts b/plugins/postcss-nested-calc/dist/has-fallback-decl.d.ts deleted file mode 100644 index d7ae8d890..000000000 --- a/plugins/postcss-nested-calc/dist/has-fallback-decl.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import type { Declaration } from 'postcss'; -export declare function hasFallback(node: Declaration): boolean; diff --git a/plugins/postcss-nested-calc/dist/index.d.ts b/plugins/postcss-nested-calc/dist/index.d.ts index 139448bef..d6f1df1ef 100644 --- a/plugins/postcss-nested-calc/dist/index.d.ts +++ b/plugins/postcss-nested-calc/dist/index.d.ts @@ -1,8 +1,12 @@ import type { PluginCreator } from 'postcss'; + +declare const creator: PluginCreator; +export default creator; + /** postcss-nested-calc plugin options */ -export type pluginOptions = { +export declare type pluginOptions = { /** Preserve the original notation. default: true */ preserve?: boolean; }; -declare const creator: PluginCreator; -export default creator; + +export { } diff --git a/plugins/postcss-nested-calc/dist/occurrences.d.ts b/plugins/postcss-nested-calc/dist/occurrences.d.ts deleted file mode 100644 index 61f8b7842..000000000 --- a/plugins/postcss-nested-calc/dist/occurrences.d.ts +++ /dev/null @@ -1 +0,0 @@ -export declare function numberOfCalcOccurrences(value: string): number; diff --git a/plugins/postcss-nested-calc/package.json b/plugins/postcss-nested-calc/package.json index 3f36e0b17..9fd923c23 100644 --- a/plugins/postcss-nested-calc/package.json +++ b/plugins/postcss-nested-calc/package.json @@ -27,15 +27,18 @@ "engines": { "node": "^14 || ^16 || >=18" }, + "type": "module", "main": "dist/index.cjs", "module": "dist/index.mjs", - "types": "dist/index.d.ts", "exports": { ".": { - "types": "./dist/index.d.ts", - "import": "./dist/index.mjs", - "require": "./dist/index.cjs", - "default": "./dist/index.mjs" + "import": { + "types": "./dist/index.d.ts", + "default": "./dist/index.mjs" + }, + "require": { + "default": "./dist/index.cjs" + } } }, "files": [ diff --git a/plugins/postcss-nesting/CHANGELOG.md b/plugins/postcss-nesting/CHANGELOG.md index c0ce85088..992c82a96 100644 --- a/plugins/postcss-nesting/CHANGELOG.md +++ b/plugins/postcss-nesting/CHANGELOG.md @@ -1,5 +1,9 @@ # Changes to PostCSS Nesting +### Unreleased (patch) + +- Fix type definitions + ### 12.0.1 _August 5, 2023_ diff --git a/plugins/postcss-nesting/api-extractor.json b/plugins/postcss-nesting/api-extractor.json new file mode 100644 index 000000000..42058be51 --- /dev/null +++ b/plugins/postcss-nesting/api-extractor.json @@ -0,0 +1,4 @@ +{ + "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json", + "extends": "../../api-extractor.json" +} diff --git a/plugins/postcss-nesting/dist/index.d.ts b/plugins/postcss-nesting/dist/index.d.ts index 777ed3e50..c441b4179 100644 --- a/plugins/postcss-nesting/dist/index.d.ts +++ b/plugins/postcss-nesting/dist/index.d.ts @@ -1,10 +1,14 @@ import type { PluginCreator } from 'postcss'; + +declare const creator: PluginCreator; +export default creator; + /** postcss-nesting plugin options */ -export type pluginOptions = { +export declare type pluginOptions = { /** Avoid the `:is()` pseudo class as much as possible. default: false */ noIsPseudoSelector?: boolean; /** Silence the `@nest` warning. */ silenceAtNestWarning?: boolean; }; -declare const creator: PluginCreator; -export default creator; + +export { } diff --git a/plugins/postcss-nesting/dist/lib/ampersand-to-scope.d.ts b/plugins/postcss-nesting/dist/lib/ampersand-to-scope.d.ts deleted file mode 100644 index f82c36f94..000000000 --- a/plugins/postcss-nesting/dist/lib/ampersand-to-scope.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import type { Result, Rule } from 'postcss'; -export default function ampersandToScope(rule: Rule, result: Result): void; diff --git a/plugins/postcss-nesting/dist/lib/atrule-within-atrule.d.ts b/plugins/postcss-nesting/dist/lib/atrule-within-atrule.d.ts deleted file mode 100644 index f06ffa9a7..000000000 --- a/plugins/postcss-nesting/dist/lib/atrule-within-atrule.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -import type { AtRule } from 'postcss'; -export default function transformAtruleWithinAtrule(node: AtRule, parent: AtRule): void; -export declare function isAtruleWithinAtrule(node: AtRule, parent: AtRule): boolean; diff --git a/plugins/postcss-nesting/dist/lib/atrule-within-rule.d.ts b/plugins/postcss-nesting/dist/lib/atrule-within-rule.d.ts deleted file mode 100644 index 3c7c0911c..000000000 --- a/plugins/postcss-nesting/dist/lib/atrule-within-rule.d.ts +++ /dev/null @@ -1,5 +0,0 @@ -import { options } from './options.js'; -import { walkFunc } from './walk-func.js'; -import type { AtRule, Result, Rule } from 'postcss'; -export default function atruleWithinRule(node: AtRule, parent: Rule, result: Result, walk: walkFunc, opts: options): void; -export declare function isAtruleWithinRule(node: AtRule): boolean; diff --git a/plugins/postcss-nesting/dist/lib/cleanup-parent.d.ts b/plugins/postcss-nesting/dist/lib/cleanup-parent.d.ts deleted file mode 100644 index 5547db143..000000000 --- a/plugins/postcss-nesting/dist/lib/cleanup-parent.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import type { ChildNode, Container } from 'postcss'; -export default function cleanupParent(parent: Container): void; diff --git a/plugins/postcss-nesting/dist/lib/group-declarations.d.ts b/plugins/postcss-nesting/dist/lib/group-declarations.d.ts deleted file mode 100644 index 116434201..000000000 --- a/plugins/postcss-nesting/dist/lib/group-declarations.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import type { ChildNode, Container } from 'postcss'; -export default function groupDeclarations(node: Container): void; diff --git a/plugins/postcss-nesting/dist/lib/is-type-of-rule.d.ts b/plugins/postcss-nesting/dist/lib/is-type-of-rule.d.ts deleted file mode 100644 index d6cb2458e..000000000 --- a/plugins/postcss-nesting/dist/lib/is-type-of-rule.d.ts +++ /dev/null @@ -1,4 +0,0 @@ -import type { AtRule, Node, Rule } from 'postcss'; -export declare function isAtRule(node?: Node): node is AtRule; -export declare function isNestRule(node?: Node): node is AtRule; -export declare function isRule(node?: Node): node is Rule; diff --git a/plugins/postcss-nesting/dist/lib/list.d.ts b/plugins/postcss-nesting/dist/lib/list.d.ts deleted file mode 100644 index 67a64736d..000000000 --- a/plugins/postcss-nesting/dist/lib/list.d.ts +++ /dev/null @@ -1 +0,0 @@ -export declare function comma(string: string): string[]; diff --git a/plugins/postcss-nesting/dist/lib/merge-params.d.ts b/plugins/postcss-nesting/dist/lib/merge-params.d.ts deleted file mode 100644 index 0547e8f7b..000000000 --- a/plugins/postcss-nesting/dist/lib/merge-params.d.ts +++ /dev/null @@ -1 +0,0 @@ -export default function mergeParams(fromParams: string, toParams: string): string; diff --git a/plugins/postcss-nesting/dist/lib/merge-selectors/combinations-of-size-n.d.ts b/plugins/postcss-nesting/dist/lib/merge-selectors/combinations-of-size-n.d.ts deleted file mode 100644 index 56bbf7231..000000000 --- a/plugins/postcss-nesting/dist/lib/merge-selectors/combinations-of-size-n.d.ts +++ /dev/null @@ -1 +0,0 @@ -export declare function combinationsWithSizeN(set: Array, n: number): Array>; diff --git a/plugins/postcss-nesting/dist/lib/merge-selectors/compound-selector-order.d.ts b/plugins/postcss-nesting/dist/lib/merge-selectors/compound-selector-order.d.ts deleted file mode 100644 index 3d43458e3..000000000 --- a/plugins/postcss-nesting/dist/lib/merge-selectors/compound-selector-order.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import type { Container, Node } from 'postcss-selector-parser'; -export declare function sortCompoundSelectorsInsideComplexSelector(node: Container): void; diff --git a/plugins/postcss-nesting/dist/lib/merge-selectors/merge-selectors.d.ts b/plugins/postcss-nesting/dist/lib/merge-selectors/merge-selectors.d.ts deleted file mode 100644 index f46fd8d7c..000000000 --- a/plugins/postcss-nesting/dist/lib/merge-selectors/merge-selectors.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import { options } from '../options'; -export default function mergeSelectors(fromSelectors: Array, toSelectors: Array, opts: options): any[]; diff --git a/plugins/postcss-nesting/dist/lib/merge-selectors/specificity.d.ts b/plugins/postcss-nesting/dist/lib/merge-selectors/specificity.d.ts deleted file mode 100644 index 2afcbaf90..000000000 --- a/plugins/postcss-nesting/dist/lib/merge-selectors/specificity.d.ts +++ /dev/null @@ -1 +0,0 @@ -export declare function nodesAreEquallySpecific(nodes: Array): boolean; diff --git a/plugins/postcss-nesting/dist/lib/nest-rule-within-rule.d.ts b/plugins/postcss-nesting/dist/lib/nest-rule-within-rule.d.ts deleted file mode 100644 index a0ea699ba..000000000 --- a/plugins/postcss-nesting/dist/lib/nest-rule-within-rule.d.ts +++ /dev/null @@ -1,5 +0,0 @@ -import type { AtRule, Result, Rule } from 'postcss'; -import { walkFunc } from './walk-func.js'; -import { options } from './options.js'; -export default function transformNestRuleWithinRule(node: AtRule, parent: Rule, result: Result, walk: walkFunc, opts: options): void; -export declare function isValidNestRuleWithinRule(node: AtRule): boolean; diff --git a/plugins/postcss-nesting/dist/lib/options.d.ts b/plugins/postcss-nesting/dist/lib/options.d.ts deleted file mode 100644 index 876771840..000000000 --- a/plugins/postcss-nesting/dist/lib/options.d.ts +++ /dev/null @@ -1,4 +0,0 @@ -export type options = { - noIsPseudoSelector: boolean; - silenceAtNestWarning: boolean; -}; diff --git a/plugins/postcss-nesting/dist/lib/rule-within-rule.d.ts b/plugins/postcss-nesting/dist/lib/rule-within-rule.d.ts deleted file mode 100644 index 5f733d3b6..000000000 --- a/plugins/postcss-nesting/dist/lib/rule-within-rule.d.ts +++ /dev/null @@ -1,4 +0,0 @@ -import type { Result, Rule } from 'postcss'; -import { options } from './options.js'; -export default function transformRuleWithinRule(node: Rule, parent: Rule, result: Result, opts: options): void; -export declare function isValidRuleWithinRule(node: Rule): boolean; diff --git a/plugins/postcss-nesting/dist/lib/shift-nodes-before-parent.d.ts b/plugins/postcss-nesting/dist/lib/shift-nodes-before-parent.d.ts deleted file mode 100644 index 0876f2ba6..000000000 --- a/plugins/postcss-nesting/dist/lib/shift-nodes-before-parent.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import type { ChildNode, Container } from 'postcss'; -export default function shiftNodesBeforeParent(node: ChildNode, parent: Container): void; diff --git a/plugins/postcss-nesting/dist/lib/valid-atrules.d.ts b/plugins/postcss-nesting/dist/lib/valid-atrules.d.ts deleted file mode 100644 index d451d2bc5..000000000 --- a/plugins/postcss-nesting/dist/lib/valid-atrules.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -declare const _default: string[]; -export default _default; diff --git a/plugins/postcss-nesting/dist/lib/walk-func.d.ts b/plugins/postcss-nesting/dist/lib/walk-func.d.ts deleted file mode 100644 index 36cff8339..000000000 --- a/plugins/postcss-nesting/dist/lib/walk-func.d.ts +++ /dev/null @@ -1,4 +0,0 @@ -import type { Container, Result } from 'postcss'; -export type walkFunc = (node: Container, result: Result, opts: { - noIsPseudoSelector: boolean; -}) => void; diff --git a/plugins/postcss-nesting/dist/lib/walk.d.ts b/plugins/postcss-nesting/dist/lib/walk.d.ts deleted file mode 100644 index b50ece788..000000000 --- a/plugins/postcss-nesting/dist/lib/walk.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -import type { Container, Result } from 'postcss'; -import { options } from './options.js'; -export default function walk(node: Container, result: Result, opts: options): void; diff --git a/plugins/postcss-nesting/package.json b/plugins/postcss-nesting/package.json index 22484fb0c..b4799475b 100644 --- a/plugins/postcss-nesting/package.json +++ b/plugins/postcss-nesting/package.json @@ -31,17 +31,20 @@ "engines": { "node": "^14 || ^16 || >=18" }, + "type": "module", "main": "dist/index.cjs", "module": "dist/index.mjs", - "types": "dist/index.d.ts", "jsdelivr": "dist/index.mjs", "unpkg": "dist/index.mjs", "exports": { ".": { - "types": "./dist/index.d.ts", - "import": "./dist/index.mjs", - "require": "./dist/index.cjs", - "default": "./dist/index.mjs" + "import": { + "types": "./dist/index.d.ts", + "default": "./dist/index.mjs" + }, + "require": { + "default": "./dist/index.cjs" + } } }, "files": [ diff --git a/plugins/postcss-normalize-display-values/CHANGELOG.md b/plugins/postcss-normalize-display-values/CHANGELOG.md index a1c02e844..f1bf2adfb 100644 --- a/plugins/postcss-normalize-display-values/CHANGELOG.md +++ b/plugins/postcss-normalize-display-values/CHANGELOG.md @@ -1,5 +1,9 @@ # Changes to PostCSS Normalize Display Values +### Unreleased (patch) + +- Fix type definitions + ### 3.0.1 _September 18, 2023_ diff --git a/plugins/postcss-normalize-display-values/api-extractor.json b/plugins/postcss-normalize-display-values/api-extractor.json new file mode 100644 index 000000000..42058be51 --- /dev/null +++ b/plugins/postcss-normalize-display-values/api-extractor.json @@ -0,0 +1,4 @@ +{ + "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json", + "extends": "../../api-extractor.json" +} diff --git a/plugins/postcss-normalize-display-values/dist/index.cjs b/plugins/postcss-normalize-display-values/dist/index.cjs index cdd54eb43..681198e81 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(null==e?void 0:e.preserve);return{postcssPlugin:"postcss-normalize-display-values",prepare(){const e=new Map;return{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,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{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; diff --git a/plugins/postcss-normalize-display-values/dist/index.d.ts b/plugins/postcss-normalize-display-values/dist/index.d.ts index b0606a311..54036ec0b 100644 --- a/plugins/postcss-normalize-display-values/dist/index.d.ts +++ b/plugins/postcss-normalize-display-values/dist/index.d.ts @@ -1,8 +1,12 @@ import type { PluginCreator } from 'postcss'; + +declare const creator: PluginCreator; +export default creator; + /** postcss-normalize-display-values plugin options */ -export type pluginOptions = { +export declare type pluginOptions = { /** Preserve the original notation. default: true */ preserve?: boolean; }; -declare const creator: PluginCreator; -export default creator; + +export { } diff --git a/plugins/postcss-normalize-display-values/dist/index.mjs b/plugins/postcss-normalize-display-values/dist/index.mjs index bda81c6d8..69df945a5 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(null==e?void 0:e.preserve);return{postcssPlugin:"postcss-normalize-display-values",prepare(){const e=new Map;return{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,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{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;export{creator as default}; diff --git a/plugins/postcss-normalize-display-values/dist/mappings.d.ts b/plugins/postcss-normalize-display-values/dist/mappings.d.ts deleted file mode 100644 index 7ca13f692..000000000 --- a/plugins/postcss-normalize-display-values/dist/mappings.d.ts +++ /dev/null @@ -1,5 +0,0 @@ -/** - * Specification: https://www.w3.org/TR/css-display-3/#the-display-properties - */ -declare const _default: Map; -export default _default; diff --git a/plugins/postcss-normalize-display-values/package.json b/plugins/postcss-normalize-display-values/package.json index d2fa0fad5..320e25da7 100644 --- a/plugins/postcss-normalize-display-values/package.json +++ b/plugins/postcss-normalize-display-values/package.json @@ -17,15 +17,18 @@ "engines": { "node": "^14 || ^16 || >=18" }, + "type": "module", "main": "dist/index.cjs", "module": "dist/index.mjs", - "types": "dist/index.d.ts", "exports": { ".": { - "types": "./dist/index.d.ts", - "import": "./dist/index.mjs", - "require": "./dist/index.cjs", - "default": "./dist/index.mjs" + "import": { + "types": "./dist/index.d.ts", + "default": "./dist/index.mjs" + }, + "require": { + "default": "./dist/index.cjs" + } } }, "files": [ diff --git a/plugins/postcss-oklab-function/api-extractor.json b/plugins/postcss-oklab-function/api-extractor.json new file mode 100644 index 000000000..42058be51 --- /dev/null +++ b/plugins/postcss-oklab-function/api-extractor.json @@ -0,0 +1,4 @@ +{ + "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json", + "extends": "../../api-extractor.json" +} diff --git a/plugins/postcss-oklab-function/dist/has-fallback-decl.d.ts b/plugins/postcss-oklab-function/dist/has-fallback-decl.d.ts deleted file mode 100644 index d7ae8d890..000000000 --- a/plugins/postcss-oklab-function/dist/has-fallback-decl.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import type { Declaration } from 'postcss'; -export declare function hasFallback(node: Declaration): boolean; diff --git a/plugins/postcss-oklab-function/dist/has-supports-at-rule-ancestor.d.ts b/plugins/postcss-oklab-function/dist/has-supports-at-rule-ancestor.d.ts deleted file mode 100644 index a46009ecc..000000000 --- a/plugins/postcss-oklab-function/dist/has-supports-at-rule-ancestor.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import type { Node } from 'postcss'; -export declare function hasSupportsAtRuleAncestor(node: Node): boolean; diff --git a/plugins/postcss-oklab-function/dist/index.cjs b/plugins/postcss-oklab-function/dist/index.cjs index d335abe0f..b93e4cd1e 100644 --- a/plugins/postcss-oklab-function/dist/index.cjs +++ b/plugins/postcss-oklab-function/dist/index.cjs @@ -1 +1 @@ -"use strict";var e=require("@csstools/postcss-progressive-custom-properties"),s=require("@csstools/css-tokenizer"),r=require("@csstools/css-color-parser"),t=require("@csstools/css-parser-algorithms");function hasFallback(e){const s=e.parent;if(!s)return!1;const r=e.prop.toLowerCase(),t=s.index(e);for(let e=0;e({postcssPlugin:"postcss-oklab-function",Declaration:n=>{const l=n.value;if(!o.test(l))return;if(hasFallback(n))return;if(hasSupportsAtRuleAncestor(n))return;const i=s.tokenize({css:l}),u=t.replaceComponentValues(t.parseCommaSeparatedListOfComponentValues(i),(e=>{if(t.isFunctionNode(e)&&a.test(e.getName())){const s=r.color(e);if(!s)return;if(s.syntaxFlags.has(r.SyntaxFlag.Experimental))return;if(s.syntaxFlags.has(r.SyntaxFlag.HasNoneKeywords))return;if(s.syntaxFlags.has(r.SyntaxFlag.RelativeColorSyntax))return;return r.serializeRGB(s)}})),p=t.stringify(u);if(p===l)return;let c=p;null!=e&&e.subFeatures.displayP3&&(c=t.stringify(t.replaceComponentValues(t.parseCommaSeparatedListOfComponentValues(i),(e=>{if(t.isFunctionNode(e)&&a.test(e.getName())){const s=r.color(e);if(!s)return;if(s.syntaxFlags.has(r.SyntaxFlag.HasNoneKeywords))return;if(s.syntaxFlags.has(r.SyntaxFlag.RelativeColorSyntax))return;return r.colorDataFitsRGB_Gamut(s)?r.serializeRGB(s):r.serializeP3(s)}})))),n.cloneBefore({value:p}),null!=e&&e.subFeatures.displayP3&&c!==p&&n.cloneBefore({value:c}),null!=e&&e.preserve||n.remove()}});basePlugin.postcss=!0;const postcssPlugin=s=>{const r=Object.assign({enableProgressiveCustomProperties:!0,preserve:!1,subFeatures:{displayP3:!0}},s);return r.subFeatures=Object.assign({displayP3:!0},r.subFeatures),r.enableProgressiveCustomProperties&&(r.preserve||r.subFeatures.displayP3)?{postcssPlugin:"postcss-oklab-function",plugins:[e(),basePlugin(r)]}:basePlugin(r)};postcssPlugin.postcss=!0,module.exports=postcssPlugin; +"use strict";var e=require("@csstools/postcss-progressive-custom-properties"),s=require("@csstools/css-tokenizer"),r=require("@csstools/css-color-parser"),t=require("@csstools/css-parser-algorithms");function hasFallback(e){const s=e.parent;if(!s)return!1;const r=e.prop.toLowerCase(),t=s.index(e);for(let e=0;e({postcssPlugin:"postcss-oklab-function",Declaration:n=>{const i=n.value;if(!o.test(i))return;if(hasFallback(n))return;if(hasSupportsAtRuleAncestor(n))return;const l=s.tokenize({css:i}),u=t.replaceComponentValues(t.parseCommaSeparatedListOfComponentValues(l),(e=>{if(t.isFunctionNode(e)&&a.test(e.getName())){const s=r.color(e);if(!s)return;if(s.syntaxFlags.has(r.SyntaxFlag.Experimental))return;if(s.syntaxFlags.has(r.SyntaxFlag.HasNoneKeywords))return;if(s.syntaxFlags.has(r.SyntaxFlag.RelativeColorSyntax))return;return r.serializeRGB(s)}})),p=t.stringify(u);if(p===i)return;let c=p;e?.subFeatures.displayP3&&(c=t.stringify(t.replaceComponentValues(t.parseCommaSeparatedListOfComponentValues(l),(e=>{if(t.isFunctionNode(e)&&a.test(e.getName())){const s=r.color(e);if(!s)return;if(s.syntaxFlags.has(r.SyntaxFlag.HasNoneKeywords))return;if(s.syntaxFlags.has(r.SyntaxFlag.RelativeColorSyntax))return;return r.colorDataFitsRGB_Gamut(s)?r.serializeRGB(s):r.serializeP3(s)}})))),n.cloneBefore({value:p}),e?.subFeatures.displayP3&&c!==p&&n.cloneBefore({value:c}),e?.preserve||n.remove()}});basePlugin.postcss=!0;const postcssPlugin=s=>{const r=Object.assign({enableProgressiveCustomProperties:!0,preserve:!1,subFeatures:{displayP3:!0}},s);return r.subFeatures=Object.assign({displayP3:!0},r.subFeatures),r.enableProgressiveCustomProperties&&(r.preserve||r.subFeatures.displayP3)?{postcssPlugin:"postcss-oklab-function",plugins:[e(),basePlugin(r)]}:basePlugin(r)};postcssPlugin.postcss=!0,module.exports=postcssPlugin; diff --git a/plugins/postcss-oklab-function/dist/index.d.ts b/plugins/postcss-oklab-function/dist/index.d.ts index aee8de5ff..cf304740d 100644 --- a/plugins/postcss-oklab-function/dist/index.d.ts +++ b/plugins/postcss-oklab-function/dist/index.d.ts @@ -1,6 +1,7 @@ import type { PluginCreator } from 'postcss'; + /** postcss-oklab-function plugin options */ -export type pluginOptions = { +export declare type pluginOptions = { /** Preserve the original notation. default: false */ preserve?: boolean; /** Enable "@csstools/postcss-progressive-custom-properties". default: true */ @@ -11,5 +12,8 @@ export type pluginOptions = { displayP3?: boolean; }; }; + declare const postcssPlugin: PluginCreator; export default postcssPlugin; + +export { } diff --git a/plugins/postcss-oklab-function/dist/index.mjs b/plugins/postcss-oklab-function/dist/index.mjs index a0b98b996..194eaedab 100644 --- a/plugins/postcss-oklab-function/dist/index.mjs +++ b/plugins/postcss-oklab-function/dist/index.mjs @@ -1 +1 @@ -import s from"@csstools/postcss-progressive-custom-properties";import{tokenize as e}from"@csstools/css-tokenizer";import{color as r,SyntaxFlag as t,serializeRGB as o,colorDataFitsRGB_Gamut as a,serializeP3 as n}from"@csstools/css-color-parser";import{replaceComponentValues as l,parseCommaSeparatedListOfComponentValues as u,isFunctionNode as i,stringify as p}from"@csstools/css-parser-algorithms";function hasFallback(s){const e=s.parent;if(!e)return!1;const r=s.prop.toLowerCase(),t=e.index(s);for(let s=0;s({postcssPlugin:"postcss-oklab-function",Declaration:m=>{const b=m.value;if(!c.test(b))return;if(hasFallback(m))return;if(hasSupportsAtRuleAncestor(m))return;const g=e({css:b}),y=l(u(g),(s=>{if(i(s)&&f.test(s.getName())){const e=r(s);if(!e)return;if(e.syntaxFlags.has(t.Experimental))return;if(e.syntaxFlags.has(t.HasNoneKeywords))return;if(e.syntaxFlags.has(t.RelativeColorSyntax))return;return o(e)}})),d=p(y);if(d===b)return;let h=d;null!=s&&s.subFeatures.displayP3&&(h=p(l(u(g),(s=>{if(i(s)&&f.test(s.getName())){const e=r(s);if(!e)return;if(e.syntaxFlags.has(t.HasNoneKeywords))return;if(e.syntaxFlags.has(t.RelativeColorSyntax))return;return a(e)?o(e):n(e)}})))),m.cloneBefore({value:d}),null!=s&&s.subFeatures.displayP3&&h!==d&&m.cloneBefore({value:h}),null!=s&&s.preserve||m.remove()}});basePlugin.postcss=!0;const postcssPlugin=e=>{const r=Object.assign({enableProgressiveCustomProperties:!0,preserve:!1,subFeatures:{displayP3:!0}},e);return r.subFeatures=Object.assign({displayP3:!0},r.subFeatures),r.enableProgressiveCustomProperties&&(r.preserve||r.subFeatures.displayP3)?{postcssPlugin:"postcss-oklab-function",plugins:[s(),basePlugin(r)]}:basePlugin(r)};postcssPlugin.postcss=!0;export{postcssPlugin as default}; +import s from"@csstools/postcss-progressive-custom-properties";import{tokenize as e}from"@csstools/css-tokenizer";import{color as r,SyntaxFlag as t,serializeRGB as o,colorDataFitsRGB_Gamut as a,serializeP3 as n}from"@csstools/css-color-parser";import{replaceComponentValues as i,parseCommaSeparatedListOfComponentValues as l,isFunctionNode as u,stringify as p}from"@csstools/css-parser-algorithms";function hasFallback(s){const e=s.parent;if(!e)return!1;const r=s.prop.toLowerCase(),t=e.index(s);for(let s=0;s({postcssPlugin:"postcss-oklab-function",Declaration:m=>{const b=m.value;if(!c.test(b))return;if(hasFallback(m))return;if(hasSupportsAtRuleAncestor(m))return;const g=e({css:b}),y=i(l(g),(s=>{if(u(s)&&f.test(s.getName())){const e=r(s);if(!e)return;if(e.syntaxFlags.has(t.Experimental))return;if(e.syntaxFlags.has(t.HasNoneKeywords))return;if(e.syntaxFlags.has(t.RelativeColorSyntax))return;return o(e)}})),d=p(y);if(d===b)return;let h=d;s?.subFeatures.displayP3&&(h=p(i(l(g),(s=>{if(u(s)&&f.test(s.getName())){const e=r(s);if(!e)return;if(e.syntaxFlags.has(t.HasNoneKeywords))return;if(e.syntaxFlags.has(t.RelativeColorSyntax))return;return a(e)?o(e):n(e)}})))),m.cloneBefore({value:d}),s?.subFeatures.displayP3&&h!==d&&m.cloneBefore({value:h}),s?.preserve||m.remove()}});basePlugin.postcss=!0;const postcssPlugin=e=>{const r=Object.assign({enableProgressiveCustomProperties:!0,preserve:!1,subFeatures:{displayP3:!0}},e);return r.subFeatures=Object.assign({displayP3:!0},r.subFeatures),r.enableProgressiveCustomProperties&&(r.preserve||r.subFeatures.displayP3)?{postcssPlugin:"postcss-oklab-function",plugins:[s(),basePlugin(r)]}:basePlugin(r)};postcssPlugin.postcss=!0;export{postcssPlugin as default}; diff --git a/plugins/postcss-oklab-function/package.json b/plugins/postcss-oklab-function/package.json index 34b11c0e1..250f771b4 100644 --- a/plugins/postcss-oklab-function/package.json +++ b/plugins/postcss-oklab-function/package.json @@ -17,15 +17,18 @@ "engines": { "node": "^14 || ^16 || >=18" }, + "type": "module", "main": "dist/index.cjs", "module": "dist/index.mjs", - "types": "./dist/index.d.ts", "exports": { ".": { - "types": "./dist/index.d.ts", - "import": "./dist/index.mjs", - "require": "./dist/index.cjs", - "default": "./dist/index.mjs" + "import": { + "types": "./dist/index.d.ts", + "default": "./dist/index.mjs" + }, + "require": { + "default": "./dist/index.cjs" + } } }, "files": [ diff --git a/plugins/postcss-overflow-shorthand/CHANGELOG.md b/plugins/postcss-overflow-shorthand/CHANGELOG.md index 1314db9cf..be6954dbe 100644 --- a/plugins/postcss-overflow-shorthand/CHANGELOG.md +++ b/plugins/postcss-overflow-shorthand/CHANGELOG.md @@ -1,5 +1,9 @@ # Changes to PostCSS Overflow Shorthand +### Unreleased (patch) + +- Fix type definitions + ### 5.0.0 _July 3, 2023_ diff --git a/plugins/postcss-overflow-shorthand/api-extractor.json b/plugins/postcss-overflow-shorthand/api-extractor.json new file mode 100644 index 000000000..42058be51 --- /dev/null +++ b/plugins/postcss-overflow-shorthand/api-extractor.json @@ -0,0 +1,4 @@ +{ + "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json", + "extends": "../../api-extractor.json" +} diff --git a/plugins/postcss-overflow-shorthand/dist/index.d.ts b/plugins/postcss-overflow-shorthand/dist/index.d.ts index 017c3aad3..51611ae6f 100644 --- a/plugins/postcss-overflow-shorthand/dist/index.d.ts +++ b/plugins/postcss-overflow-shorthand/dist/index.d.ts @@ -1,8 +1,12 @@ import type { PluginCreator } from 'postcss'; + +declare const creator: PluginCreator; +export default creator; + /** postcss-overflow-shorthand plugin options */ -export type pluginOptions = { +export declare type pluginOptions = { /** Preserve the original notation. default: true */ preserve?: boolean; }; -declare const creator: PluginCreator; -export default creator; + +export { } diff --git a/plugins/postcss-overflow-shorthand/package.json b/plugins/postcss-overflow-shorthand/package.json index 7adc491d1..0fe84f0d1 100644 --- a/plugins/postcss-overflow-shorthand/package.json +++ b/plugins/postcss-overflow-shorthand/package.json @@ -31,15 +31,18 @@ "engines": { "node": "^14 || ^16 || >=18" }, + "type": "module", "main": "dist/index.cjs", "module": "dist/index.mjs", - "types": "dist/index.d.ts", "exports": { ".": { - "types": "./dist/index.d.ts", - "import": "./dist/index.mjs", - "require": "./dist/index.cjs", - "default": "./dist/index.mjs" + "import": { + "types": "./dist/index.d.ts", + "default": "./dist/index.mjs" + }, + "require": { + "default": "./dist/index.cjs" + } } }, "files": [ diff --git a/plugins/postcss-place/CHANGELOG.md b/plugins/postcss-place/CHANGELOG.md index 0211c4862..9e1d34657 100644 --- a/plugins/postcss-place/CHANGELOG.md +++ b/plugins/postcss-place/CHANGELOG.md @@ -1,5 +1,9 @@ # Changes to PostCSS Place Properties +### Unreleased (patch) + +- Fix type definitions + ### 9.0.0 _July 3, 2023_ diff --git a/plugins/postcss-place/api-extractor.json b/plugins/postcss-place/api-extractor.json new file mode 100644 index 000000000..42058be51 --- /dev/null +++ b/plugins/postcss-place/api-extractor.json @@ -0,0 +1,4 @@ +{ + "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json", + "extends": "../../api-extractor.json" +} diff --git a/plugins/postcss-place/dist/index.cjs b/plugins/postcss-place/dist/index.cjs index 01b920a16..753f4b668 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){var n;const a=null==(n=r.prop.toLowerCase().match(t))?void 0:n[1];if(!a)return;let l;try{l=e(r.value)}catch(e){r.warn(o,`Failed to parse value '${r.value}'. Leaving the original value intact.`)}if(void 0===l)return;let i=[];i=l.nodes.length?l.nodes.filter((e=>"word"===e.type||"function"===e.type)).map((t=>e.stringify(t))):[e.stringify(l.nodes)],r.cloneBefore({prop:`align-${a}`,value:i[0]}),r.cloneBefore({prop:`justify-${a}`,value:i[1]||i[0]}),s.preserve||r.remove()}const t=/^place-(content|items|self)/,creator=e=>{const r=Object.assign({preserve:!0},e);return{postcssPlugin:"postcss-place",Declaration:(e,{result:o})=>{t.test(e.prop.toLowerCase())&&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.toLowerCase().match(t)?.[1];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)/,creator=e=>{const r=Object.assign({preserve:!0},e);return{postcssPlugin:"postcss-place",Declaration:(e,{result:o})=>{t.test(e.prop.toLowerCase())&&onCSSDeclaration(e,o,r)}}};creator.postcss=!0,module.exports=creator; diff --git a/plugins/postcss-place/dist/index.d.ts b/plugins/postcss-place/dist/index.d.ts index aaac93c53..381ddc139 100644 --- a/plugins/postcss-place/dist/index.d.ts +++ b/plugins/postcss-place/dist/index.d.ts @@ -1,8 +1,12 @@ import type { PluginCreator } from 'postcss'; + +declare const creator: PluginCreator; +export default creator; + /** postcss-place plugin options */ -export type pluginOptions = { +export declare type pluginOptions = { /** Preserve the original notation. default: true */ preserve?: boolean; }; -declare const creator: PluginCreator; -export default creator; + +export { } diff --git a/plugins/postcss-place/dist/index.mjs b/plugins/postcss-place/dist/index.mjs index 62f83b132..c39ede40a 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){var n;const a=null==(n=o.prop.toLowerCase().match(t))?void 0:n[1];if(!a)return;let l;try{l=e(o.value)}catch(e){o.warn(r,`Failed to parse value '${o.value}'. Leaving the original value intact.`)}if(void 0===l)return;let i=[];i=l.nodes.length?l.nodes.filter((e=>"word"===e.type||"function"===e.type)).map((t=>e.stringify(t))):[e.stringify(l.nodes)],o.cloneBefore({prop:`align-${a}`,value:i[0]}),o.cloneBefore({prop:`justify-${a}`,value:i[1]||i[0]}),s.preserve||o.remove()}const t=/^place-(content|items|self)/,creator=e=>{const o=Object.assign({preserve:!0},e);return{postcssPlugin:"postcss-place",Declaration:(e,{result:r})=>{t.test(e.prop.toLowerCase())&&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.toLowerCase().match(t)?.[1];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 l=[];l=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:l[0]}),o.cloneBefore({prop:`justify-${n}`,value:l[1]||l[0]}),s.preserve||o.remove()}const t=/^place-(content|items|self)/,creator=e=>{const o=Object.assign({preserve:!0},e);return{postcssPlugin:"postcss-place",Declaration:(e,{result:r})=>{t.test(e.prop.toLowerCase())&&onCSSDeclaration(e,r,o)}}};creator.postcss=!0;export{creator as default}; diff --git a/plugins/postcss-place/dist/onCSSDeclaration.d.ts b/plugins/postcss-place/dist/onCSSDeclaration.d.ts deleted file mode 100644 index e1e7aa08e..000000000 --- a/plugins/postcss-place/dist/onCSSDeclaration.d.ts +++ /dev/null @@ -1,5 +0,0 @@ -import type { Declaration, Result } from 'postcss'; -export declare function onCSSDeclaration(decl: Declaration, result: Result, options: { - preserve: boolean; -}): void; -export declare const placeMatch: RegExp; diff --git a/plugins/postcss-place/package.json b/plugins/postcss-place/package.json index 1081abcbf..31007c8e2 100644 --- a/plugins/postcss-place/package.json +++ b/plugins/postcss-place/package.json @@ -31,15 +31,18 @@ "engines": { "node": "^14 || ^16 || >=18" }, + "type": "module", "main": "dist/index.cjs", "module": "dist/index.mjs", - "types": "dist/index.d.ts", "exports": { ".": { - "types": "./dist/index.d.ts", - "import": "./dist/index.mjs", - "require": "./dist/index.cjs", - "default": "./dist/index.mjs" + "import": { + "types": "./dist/index.d.ts", + "default": "./dist/index.mjs" + }, + "require": { + "default": "./dist/index.cjs" + } } }, "files": [ diff --git a/plugins/postcss-progressive-custom-properties/CHANGELOG.md b/plugins/postcss-progressive-custom-properties/CHANGELOG.md index ad87d81d0..0bf0859ff 100644 --- a/plugins/postcss-progressive-custom-properties/CHANGELOG.md +++ b/plugins/postcss-progressive-custom-properties/CHANGELOG.md @@ -1,5 +1,9 @@ # Changes to PostCSS Progressive Custom Properties +### Unreleased (patch) + +- Fix type definitions + ### 3.0.2 _October 9, 2023_ diff --git a/plugins/postcss-progressive-custom-properties/api-extractor.json b/plugins/postcss-progressive-custom-properties/api-extractor.json new file mode 100644 index 000000000..42058be51 --- /dev/null +++ b/plugins/postcss-progressive-custom-properties/api-extractor.json @@ -0,0 +1,4 @@ +{ + "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json", + "extends": "../../api-extractor.json" +} diff --git a/plugins/postcss-progressive-custom-properties/dist/conditions-from-values.d.ts b/plugins/postcss-progressive-custom-properties/dist/conditions-from-values.d.ts deleted file mode 100644 index 250b5e914..000000000 --- a/plugins/postcss-progressive-custom-properties/dist/conditions-from-values.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -export declare function conditionsFromValue(value: string, mustContainVar?: boolean): { - support: Array; -}; diff --git a/plugins/postcss-progressive-custom-properties/dist/custom/double-position-gradients.d.ts b/plugins/postcss-progressive-custom-properties/dist/custom/double-position-gradients.d.ts deleted file mode 100644 index 6ca404c9a..000000000 --- a/plugins/postcss-progressive-custom-properties/dist/custom/double-position-gradients.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import type { Node } from 'postcss-value-parser'; -export declare function doublePositionGradients(node: Node): Array; diff --git a/plugins/postcss-progressive-custom-properties/dist/index.cjs b/plugins/postcss-progressive-custom-properties/dist/index.cjs index 35a105198..550926abd 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{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{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.d.ts b/plugins/postcss-progressive-custom-properties/dist/index.d.ts index 5b5a74dd2..240fc585b 100644 --- a/plugins/postcss-progressive-custom-properties/dist/index.d.ts +++ b/plugins/postcss-progressive-custom-properties/dist/index.d.ts @@ -1,3 +1,6 @@ -import { type PluginCreator } from 'postcss'; +import { PluginCreator } from 'postcss'; + declare const creator: PluginCreator; export default creator; + +export { } diff --git a/plugins/postcss-progressive-custom-properties/dist/index.mjs b/plugins/postcss-progressive-custom-properties/dist/index.mjs index 19ceb72e1..4c3438091 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{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{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/dist/match.d.ts b/plugins/postcss-progressive-custom-properties/dist/match.d.ts deleted file mode 100644 index 95a56e037..000000000 --- a/plugins/postcss-progressive-custom-properties/dist/match.d.ts +++ /dev/null @@ -1,11 +0,0 @@ -type MatcherNode = { - type: string; - value?: string; - nodes?: Array; - dimension?: { - unit?: string; - }; - isVariable?: boolean; -}; -export declare function matches(a: MatcherNode, b: MatcherNode): boolean; -export {}; diff --git a/plugins/postcss-progressive-custom-properties/dist/matchers.d.ts b/plugins/postcss-progressive-custom-properties/dist/matchers.d.ts deleted file mode 100644 index 746c0edbf..000000000 --- a/plugins/postcss-progressive-custom-properties/dist/matchers.d.ts +++ /dev/null @@ -1,33 +0,0 @@ -export declare const matchers: ({ - supports: string; - property: string; - sniff: string; - matchers: { - type: string; - value: string; - nodes: ({ - type: string; - value: string; - isVariable?: undefined; - } | { - type: string; - value?: undefined; - isVariable?: undefined; - } | { - type: string; - isVariable: boolean; - value?: undefined; - })[]; - }[]; -} | { - supports: string; - property: string; - sniff: string; - matchers: { - type: string; - value: string; - dimension: { - unit: string; - }; - }[]; -})[]; diff --git a/plugins/postcss-progressive-custom-properties/package.json b/plugins/postcss-progressive-custom-properties/package.json index 6a30f6543..1fbdac0a7 100644 --- a/plugins/postcss-progressive-custom-properties/package.json +++ b/plugins/postcss-progressive-custom-properties/package.json @@ -17,15 +17,18 @@ "engines": { "node": "^14 || ^16 || >=18" }, + "type": "module", "main": "dist/index.cjs", "module": "dist/index.mjs", - "types": "dist/index.d.ts", "exports": { ".": { - "types": "./dist/index.d.ts", - "import": "./dist/index.mjs", - "require": "./dist/index.cjs", - "default": "./dist/index.mjs" + "import": { + "types": "./dist/index.d.ts", + "default": "./dist/index.mjs" + }, + "require": { + "default": "./dist/index.cjs" + } } }, "files": [ diff --git a/plugins/postcss-pseudo-class-any-link/CHANGELOG.md b/plugins/postcss-pseudo-class-any-link/CHANGELOG.md index 3501fda30..b5435b39b 100644 --- a/plugins/postcss-pseudo-class-any-link/CHANGELOG.md +++ b/plugins/postcss-pseudo-class-any-link/CHANGELOG.md @@ -2,7 +2,7 @@ ### Unreleased (patch) -- Small fixes in type definitions +- Fix type definitions ### 9.0.0 diff --git a/plugins/postcss-pseudo-class-any-link/api-extractor.json b/plugins/postcss-pseudo-class-any-link/api-extractor.json new file mode 100644 index 000000000..42058be51 --- /dev/null +++ b/plugins/postcss-pseudo-class-any-link/api-extractor.json @@ -0,0 +1,4 @@ +{ + "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json", + "extends": "../../api-extractor.json" +} diff --git a/plugins/postcss-pseudo-class-any-link/dist/index.d.ts b/plugins/postcss-pseudo-class-any-link/dist/index.d.ts index 691010554..e59a9a2ce 100644 --- a/plugins/postcss-pseudo-class-any-link/dist/index.d.ts +++ b/plugins/postcss-pseudo-class-any-link/dist/index.d.ts @@ -1,6 +1,10 @@ import type { PluginCreator } from 'postcss'; + +declare const creator: PluginCreator; +export default creator; + /** postcss-pseudo-class-any-link plugin options */ -export type pluginOptions = { +export declare type pluginOptions = { /** Preserve the original notation. default: true */ preserve?: boolean; /** Add an extra fallback for the "" element in IE and Edge. default: false */ @@ -8,5 +12,5 @@ export type pluginOptions = { areaHrefNeedsFixing?: boolean; }; }; -declare const creator: PluginCreator; -export default creator; + +export { } diff --git a/plugins/postcss-pseudo-class-any-link/dist/replace-any-link.d.ts b/plugins/postcss-pseudo-class-any-link/dist/replace-any-link.d.ts deleted file mode 100644 index f465ab2b3..000000000 --- a/plugins/postcss-pseudo-class-any-link/dist/replace-any-link.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import type { Result, Rule } from 'postcss'; -export declare function replaceAnyLink(rule: Rule, result: Result, preserve: boolean, areaHrefNeedsFixing: boolean): boolean; diff --git a/plugins/postcss-pseudo-class-any-link/package.json b/plugins/postcss-pseudo-class-any-link/package.json index e4b0de328..b6946279c 100644 --- a/plugins/postcss-pseudo-class-any-link/package.json +++ b/plugins/postcss-pseudo-class-any-link/package.json @@ -31,15 +31,18 @@ "engines": { "node": "^14 || ^16 || >=18" }, + "type": "module", "main": "dist/index.cjs", "module": "dist/index.mjs", - "types": "dist/index.d.ts", "exports": { ".": { - "types": "./dist/index.d.ts", - "import": "./dist/index.mjs", - "require": "./dist/index.cjs", - "default": "./dist/index.mjs" + "import": { + "types": "./dist/index.d.ts", + "default": "./dist/index.mjs" + }, + "require": { + "default": "./dist/index.cjs" + } } }, "files": [ diff --git a/plugins/postcss-pseudo-class-any-link/src/replace-any-link.ts b/plugins/postcss-pseudo-class-any-link/src/replace-any-link.ts index 1622bff78..8257a2912 100644 --- a/plugins/postcss-pseudo-class-any-link/src/replace-any-link.ts +++ b/plugins/postcss-pseudo-class-any-link/src/replace-any-link.ts @@ -59,21 +59,25 @@ function modifiedSelector(selector: string, areaHrefNeedsFixing: boolean) { } if (!areaHrefNeedsFixing) { + // @ts-expect-error https://github.com/postcss/postcss-selector-parser/pull/284 replacements.push([linkAST.clone(), visitedAST.clone()]); return; } const tags = getTagElementsNextToPseudo(pseudo); if (tags.includes('area')) { + // @ts-expect-error https://github.com/postcss/postcss-selector-parser/pull/284 replacements.push([linkAST.clone(), visitedAST.clone(), hrefAST.clone()]); return; } if (tags.length) { + // @ts-expect-error https://github.com/postcss/postcss-selector-parser/pull/284 replacements.push([linkAST.clone(), visitedAST.clone()]); return; } + // @ts-expect-error https://github.com/postcss/postcss-selector-parser/pull/284 replacements.push([linkAST.clone(), visitedAST.clone(), areaHrefAST.clone()]); }); @@ -85,6 +89,7 @@ function modifiedSelector(selector: string, areaHrefNeedsFixing: boolean) { replacementsCartesianProduct.forEach((replacement) => { const clone = selectorsAST.clone(); + // @ts-expect-error https://github.com/postcss/postcss-selector-parser/pull/284 clone.walkPseudos((pseudo) => { if (pseudo.value.toLowerCase() !== ':any-link' || (pseudo.nodes && pseudo.nodes.length)) { return; diff --git a/plugins/postcss-rebase-url/CHANGELOG.md b/plugins/postcss-rebase-url/CHANGELOG.md index 28f33cfd7..ec65f09d2 100644 --- a/plugins/postcss-rebase-url/CHANGELOG.md +++ b/plugins/postcss-rebase-url/CHANGELOG.md @@ -1,5 +1,9 @@ # Changes to PostCSS Rebase URL +### Unreleased (patch) + +- Fix type definitions + ### 1.0.3 _September 24, 2023_ diff --git a/plugins/postcss-rebase-url/api-extractor.json b/plugins/postcss-rebase-url/api-extractor.json new file mode 100644 index 000000000..42058be51 --- /dev/null +++ b/plugins/postcss-rebase-url/api-extractor.json @@ -0,0 +1,4 @@ +{ + "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json", + "extends": "../../api-extractor.json" +} diff --git a/plugins/postcss-rebase-url/dist/index.cjs b/plugins/postcss-rebase-url/dist/index.cjs index 059f8baa2..802275b4b 100644 --- a/plugins/postcss-rebase-url/dist/index.cjs +++ b/plugins/postcss-rebase-url/dist/index.cjs @@ -1 +1 @@ -"use strict";var e=require("@csstools/css-tokenizer"),r=require("@csstools/css-parser-algorithms"),t=require("path");const i=/^([-_a-z0-9]+:)?\/\//i;function rebase(e,r,s){if(e.startsWith("data:"))return!1;if(i.test(e))return!1;if(e.startsWith("/"))return e;if(e.startsWith("#"))return e;try{const r=new URL(e);if(r.port||r.protocol)return!1}catch{}const o=t.posix.resolve(t.posix.join(r,e));return t.posix.relative(s,o)}function serializeString(e){let r="";for(const t of e){const e=t.codePointAt(0);if(void 0!==e)switch(e){case 0:r+=String.fromCodePoint(65533);break;case 127:r+=`\\${e.toString(16)}`;break;case 34:case 39:case 92:r+=`\\${t}`;break;default:if(1<=e&&e<=31){r+=`\\${e.toString(16)} `;break}r+=t}else r+=String.fromCodePoint(65533)}return r}function normalizedDir(e){return t.parse(t.resolve(e.trim())).dir.split(t.sep).join(t.posix.sep)}const s=/^initial-value$/i,o=/^property$/i,n=/^syntax$/i,a=/url\(/i,u=/^url$/i,l=//i,creator=()=>({postcssPlugin:"postcss-rebase-url",prepare(){const t=new WeakSet,i=new Set;return{Once(e){e.walkAtRules(o,(e=>{if(!e.nodes)return;const r=e.nodes.find((e=>{if("decl"===e.type&&n.test(e.prop))return!0}));r&&l.test(r.value)&&i.add(e.params.trim())}))},Declaration(n,{result:l}){var c,p;if(t.has(n))return;if(n.variable&&!i.has(n.prop))return;if(s.test(n.prop)&&"atrule"===(null==(c=n.parent)?void 0:c.type)&&o.test(n.parent.name))return;const{from:f}=l.opts;if(!f)return;if(null==(p=n.source)||!p.input.from)return;if(!a.test(n.value))return;const v=normalizedDir(f),d=n.source.input.from.trim();if(!d)return;const m=normalizedDir(d),k=r.parseCommaSeparatedListOfComponentValues(e.tokenize({css:n.value})),g=r.replaceComponentValues(k,(t=>{if(r.isTokenNode(t)&&t.value[0]===e.TokenType.URL){const e=rebase(t.value[4].value.trim(),m,v);if(e)return t.value[4].value=e,t.value[1]=`url(${serializeString(e)})`,t}if(r.isFunctionNode(t)&&u.test(t.getName()))for(const i of t.value)if(!r.isWhitespaceNode(i)&&!r.isCommentNode(i)&&r.isTokenNode(i)&&i.value[0]===e.TokenType.String){const e=rebase(i.value[4].value.trim(),m,v);if(e)return i.value[4].value=e,i.value[1]=`"${serializeString(e)}"`,t;break}})),S=r.stringify(g);S!==n.value&&(n.value=S,t.add(n))}}}});creator.postcss=!0,module.exports=creator; +"use strict";var e=require("@csstools/css-tokenizer"),r=require("@csstools/css-parser-algorithms"),t=require("path");const i=/^([-_a-z0-9]+:)?\/\//i;function rebase(e,r,s){if(e.startsWith("data:"))return!1;if(i.test(e))return!1;if(e.startsWith("/"))return e;if(e.startsWith("#"))return e;try{const r=new URL(e);if(r.port||r.protocol)return!1}catch{}const o=t.posix.resolve(t.posix.join(r,e));return t.posix.relative(s,o)}function serializeString(e){let r="";for(const t of e){const e=t.codePointAt(0);if(void 0!==e)switch(e){case 0:r+=String.fromCodePoint(65533);break;case 127:r+=`\\${e.toString(16)}`;break;case 34:case 39:case 92:r+=`\\${t}`;break;default:if(1<=e&&e<=31){r+=`\\${e.toString(16)} `;break}r+=t}else r+=String.fromCodePoint(65533)}return r}function normalizedDir(e){return t.parse(t.resolve(e.trim())).dir.split(t.sep).join(t.posix.sep)}const s=/^initial-value$/i,o=/^property$/i,n=/^syntax$/i,a=/url\(/i,u=/^url$/i,l=//i,creator=()=>({postcssPlugin:"postcss-rebase-url",prepare(){const t=new WeakSet,i=new Set;return{Once(e){e.walkAtRules(o,(e=>{if(!e.nodes)return;const r=e.nodes.find((e=>{if("decl"===e.type&&n.test(e.prop))return!0}));r&&l.test(r.value)&&i.add(e.params.trim())}))},Declaration(n,{result:l}){if(t.has(n))return;if(n.variable&&!i.has(n.prop))return;if(s.test(n.prop)&&"atrule"===n.parent?.type&&o.test(n.parent.name))return;const{from:c}=l.opts;if(!c)return;if(!n.source?.input.from)return;if(!a.test(n.value))return;const p=normalizedDir(c),f=n.source.input.from.trim();if(!f)return;const d=normalizedDir(f),v=r.parseCommaSeparatedListOfComponentValues(e.tokenize({css:n.value})),m=r.replaceComponentValues(v,(t=>{if(r.isTokenNode(t)&&t.value[0]===e.TokenType.URL){const e=rebase(t.value[4].value.trim(),d,p);if(e)return t.value[4].value=e,t.value[1]=`url(${serializeString(e)})`,t}if(r.isFunctionNode(t)&&u.test(t.getName()))for(const i of t.value)if(!r.isWhitespaceNode(i)&&!r.isCommentNode(i)&&r.isTokenNode(i)&&i.value[0]===e.TokenType.String){const e=rebase(i.value[4].value.trim(),d,p);if(e)return i.value[4].value=e,i.value[1]=`"${serializeString(e)}"`,t;break}})),k=r.stringify(m);k!==n.value&&(n.value=k,t.add(n))}}}});creator.postcss=!0,module.exports=creator; diff --git a/plugins/postcss-rebase-url/dist/index.d.ts b/plugins/postcss-rebase-url/dist/index.d.ts index 877e03130..c63d024d3 100644 --- a/plugins/postcss-rebase-url/dist/index.d.ts +++ b/plugins/postcss-rebase-url/dist/index.d.ts @@ -1,5 +1,9 @@ import type { PluginCreator } from 'postcss'; -/** postcss-rebase-url plugin options */ -export type pluginOptions = never; + declare const creator: PluginCreator; export default creator; + +/** postcss-rebase-url plugin options */ +export declare type pluginOptions = never; + +export { } diff --git a/plugins/postcss-rebase-url/dist/index.mjs b/plugins/postcss-rebase-url/dist/index.mjs index 15bc7c5a3..e1dd47062 100644 --- a/plugins/postcss-rebase-url/dist/index.mjs +++ b/plugins/postcss-rebase-url/dist/index.mjs @@ -1 +1 @@ -import{tokenize as r,TokenType as e}from"@csstools/css-tokenizer";import{parseCommaSeparatedListOfComponentValues as t,replaceComponentValues as i,isTokenNode as s,isFunctionNode as o,isWhitespaceNode as a,isCommentNode as n,stringify as u}from"@csstools/css-parser-algorithms";import l from"path";const c=/^([-_a-z0-9]+:)?\/\//i;function rebase(r,e,t){if(r.startsWith("data:"))return!1;if(c.test(r))return!1;if(r.startsWith("/"))return r;if(r.startsWith("#"))return r;try{const e=new URL(r);if(e.port||e.protocol)return!1}catch{}const i=l.posix.resolve(l.posix.join(e,r));return l.posix.relative(t,i)}function serializeString(r){let e="";for(const t of r){const r=t.codePointAt(0);if(void 0!==r)switch(r){case 0:e+=String.fromCodePoint(65533);break;case 127:e+=`\\${r.toString(16)}`;break;case 34:case 39:case 92:e+=`\\${t}`;break;default:if(1<=r&&r<=31){e+=`\\${r.toString(16)} `;break}e+=t}else e+=String.fromCodePoint(65533)}return e}function normalizedDir(r){return l.parse(l.resolve(r.trim())).dir.split(l.sep).join(l.posix.sep)}const f=/^initial-value$/i,p=/^property$/i,v=/^syntax$/i,m=/url\(/i,d=/^url$/i,g=//i,creator=()=>({postcssPlugin:"postcss-rebase-url",prepare(){const l=new WeakSet,c=new Set;return{Once(r){r.walkAtRules(p,(r=>{if(!r.nodes)return;const e=r.nodes.find((r=>{if("decl"===r.type&&v.test(r.prop))return!0}));e&&g.test(e.value)&&c.add(r.params.trim())}))},Declaration(v,{result:g}){var b,S;if(l.has(v))return;if(v.variable&&!c.has(v.prop))return;if(f.test(v.prop)&&"atrule"===(null==(b=v.parent)?void 0:b.type)&&p.test(v.parent.name))return;const{from:h}=g.opts;if(!h)return;if(null==(S=v.source)||!S.input.from)return;if(!m.test(v.value))return;const $=normalizedDir(h),k=v.source.input.from.trim();if(!k)return;const z=normalizedDir(k),x=t(r({css:v.value})),w=i(x,(r=>{if(s(r)&&r.value[0]===e.URL){const e=rebase(r.value[4].value.trim(),z,$);if(e)return r.value[4].value=e,r.value[1]=`url(${serializeString(e)})`,r}if(o(r)&&d.test(r.getName()))for(const t of r.value)if(!a(t)&&!n(t)&&s(t)&&t.value[0]===e.String){const e=rebase(t.value[4].value.trim(),z,$);if(e)return t.value[4].value=e,t.value[1]=`"${serializeString(e)}"`,r;break}})),y=u(w);y!==v.value&&(v.value=y,l.add(v))}}}});creator.postcss=!0;export{creator as default}; +import{tokenize as e,TokenType as r}from"@csstools/css-tokenizer";import{parseCommaSeparatedListOfComponentValues as t,replaceComponentValues as i,isTokenNode as s,isFunctionNode as o,isWhitespaceNode as a,isCommentNode as n,stringify as u}from"@csstools/css-parser-algorithms";import l from"path";const c=/^([-_a-z0-9]+:)?\/\//i;function rebase(e,r,t){if(e.startsWith("data:"))return!1;if(c.test(e))return!1;if(e.startsWith("/"))return e;if(e.startsWith("#"))return e;try{const r=new URL(e);if(r.port||r.protocol)return!1}catch{}const i=l.posix.resolve(l.posix.join(r,e));return l.posix.relative(t,i)}function serializeString(e){let r="";for(const t of e){const e=t.codePointAt(0);if(void 0!==e)switch(e){case 0:r+=String.fromCodePoint(65533);break;case 127:r+=`\\${e.toString(16)}`;break;case 34:case 39:case 92:r+=`\\${t}`;break;default:if(1<=e&&e<=31){r+=`\\${e.toString(16)} `;break}r+=t}else r+=String.fromCodePoint(65533)}return r}function normalizedDir(e){return l.parse(l.resolve(e.trim())).dir.split(l.sep).join(l.posix.sep)}const f=/^initial-value$/i,p=/^property$/i,v=/^syntax$/i,m=/url\(/i,d=/^url$/i,g=//i,creator=()=>({postcssPlugin:"postcss-rebase-url",prepare(){const l=new WeakSet,c=new Set;return{Once(e){e.walkAtRules(p,(e=>{if(!e.nodes)return;const r=e.nodes.find((e=>{if("decl"===e.type&&v.test(e.prop))return!0}));r&&g.test(r.value)&&c.add(e.params.trim())}))},Declaration(v,{result:g}){if(l.has(v))return;if(v.variable&&!c.has(v.prop))return;if(f.test(v.prop)&&"atrule"===v.parent?.type&&p.test(v.parent.name))return;const{from:b}=g.opts;if(!b)return;if(!v.source?.input.from)return;if(!m.test(v.value))return;const S=normalizedDir(b),h=v.source.input.from.trim();if(!h)return;const $=normalizedDir(h),k=t(e({css:v.value})),z=i(k,(e=>{if(s(e)&&e.value[0]===r.URL){const r=rebase(e.value[4].value.trim(),$,S);if(r)return e.value[4].value=r,e.value[1]=`url(${serializeString(r)})`,e}if(o(e)&&d.test(e.getName()))for(const t of e.value)if(!a(t)&&!n(t)&&s(t)&&t.value[0]===r.String){const r=rebase(t.value[4].value.trim(),$,S);if(r)return t.value[4].value=r,t.value[1]=`"${serializeString(r)}"`,e;break}})),x=u(z);x!==v.value&&(v.value=x,l.add(v))}}}});creator.postcss=!0;export{creator as default}; diff --git a/plugins/postcss-rebase-url/dist/normalized-dir.d.ts b/plugins/postcss-rebase-url/dist/normalized-dir.d.ts deleted file mode 100644 index 70ed1c972..000000000 --- a/plugins/postcss-rebase-url/dist/normalized-dir.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -/** - * Returns a posix path for the directory of the given file path. - * - * @param {string} x The file path to normalize. - * @returns {string} The normalized directory path. - */ -export declare function normalizedDir(x: string): string; diff --git a/plugins/postcss-rebase-url/dist/serialize-string.d.ts b/plugins/postcss-rebase-url/dist/serialize-string.d.ts deleted file mode 100644 index ce83d6ae2..000000000 --- a/plugins/postcss-rebase-url/dist/serialize-string.d.ts +++ /dev/null @@ -1,9 +0,0 @@ -/** - * Serialize a string as a quoted CSS string. - * - * @param {string} str The contents for the string value. - * @returns {string} The quoted CSS string. - * - * @see https://www.w3.org/TR/cssom-1/#common-serializing-idioms - */ -export declare function serializeString(str: string): string; diff --git a/plugins/postcss-rebase-url/package.json b/plugins/postcss-rebase-url/package.json index c96e5c92f..64379f7dc 100644 --- a/plugins/postcss-rebase-url/package.json +++ b/plugins/postcss-rebase-url/package.json @@ -27,15 +27,18 @@ "engines": { "node": "^14 || ^16 || >=18" }, + "type": "module", "main": "dist/index.cjs", "module": "dist/index.mjs", - "types": "dist/index.d.ts", "exports": { ".": { - "types": "./dist/index.d.ts", - "import": "./dist/index.mjs", - "require": "./dist/index.cjs", - "default": "./dist/index.mjs" + "import": { + "types": "./dist/index.d.ts", + "default": "./dist/index.mjs" + }, + "require": { + "default": "./dist/index.cjs" + } } }, "files": [ diff --git a/plugins/postcss-relative-color-syntax/api-extractor.json b/plugins/postcss-relative-color-syntax/api-extractor.json new file mode 100644 index 000000000..42058be51 --- /dev/null +++ b/plugins/postcss-relative-color-syntax/api-extractor.json @@ -0,0 +1,4 @@ +{ + "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json", + "extends": "../../api-extractor.json" +} diff --git a/plugins/postcss-relative-color-syntax/dist/has-fallback-decl.d.ts b/plugins/postcss-relative-color-syntax/dist/has-fallback-decl.d.ts deleted file mode 100644 index d7ae8d890..000000000 --- a/plugins/postcss-relative-color-syntax/dist/has-fallback-decl.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import type { Declaration } from 'postcss'; -export declare function hasFallback(node: Declaration): boolean; diff --git a/plugins/postcss-relative-color-syntax/dist/has-supports-at-rule-ancestor.d.ts b/plugins/postcss-relative-color-syntax/dist/has-supports-at-rule-ancestor.d.ts deleted file mode 100644 index a46009ecc..000000000 --- a/plugins/postcss-relative-color-syntax/dist/has-supports-at-rule-ancestor.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import type { Node } from 'postcss'; -export declare function hasSupportsAtRuleAncestor(node: Node): boolean; diff --git a/plugins/postcss-relative-color-syntax/dist/index.cjs b/plugins/postcss-relative-color-syntax/dist/index.cjs index 2ab88ea7b..c811e0bee 100644 --- a/plugins/postcss-relative-color-syntax/dist/index.cjs +++ b/plugins/postcss-relative-color-syntax/dist/index.cjs @@ -1 +1 @@ -"use strict";var e=require("@csstools/postcss-progressive-custom-properties"),s=require("@csstools/css-tokenizer"),r=require("@csstools/css-color-parser"),t=require("@csstools/css-parser-algorithms");function hasFallback(e){const s=e.parent;if(!s)return!1;const r=e.prop.toLowerCase(),t=s.index(e);for(let e=0;e({postcssPlugin:"postcss-relative-color-syntax",Declaration:o=>{const i=o.value;if(!a.test(i))return;if(!n.test(i))return;if(hasFallback(o))return;if(hasSupportsAtRuleAncestor(o))return;const u=s.tokenize({css:i}),c=t.replaceComponentValues(t.parseCommaSeparatedListOfComponentValues(u),(e=>{if(t.isFunctionNode(e)&&l.test(e.getName())){const s=r.color(e);if(!s)return;if(s.syntaxFlags.has(r.SyntaxFlag.Experimental))return;if(s.syntaxFlags.has(r.SyntaxFlag.HasNoneKeywords))return;if(!s.syntaxFlags.has(r.SyntaxFlag.RelativeColorSyntax))return;return r.serializeRGB(s)}})),p=t.stringify(c);if(p===i)return;let f=p;null!=e&&e.subFeatures.displayP3&&(f=t.stringify(t.replaceComponentValues(t.parseCommaSeparatedListOfComponentValues(u),(e=>{if(t.isFunctionNode(e)&&l.test(e.getName())){const s=r.color(e);if(!s)return;if(s.syntaxFlags.has(r.SyntaxFlag.HasNoneKeywords))return;if(!s.syntaxFlags.has(r.SyntaxFlag.RelativeColorSyntax))return;return r.colorDataFitsRGB_Gamut(s)?r.serializeRGB(s):r.serializeP3(s)}})))),o.cloneBefore({value:p}),null!=e&&e.subFeatures.displayP3&&f!==p&&o.cloneBefore({value:f}),null!=e&&e.preserve||o.remove()}});basePlugin.postcss=!0;const postcssPlugin=s=>{const r=Object.assign({enableProgressiveCustomProperties:!0,preserve:!1,subFeatures:{displayP3:!0}},s);return r.subFeatures=Object.assign({displayP3:!0},r.subFeatures),r.enableProgressiveCustomProperties&&(r.preserve||r.subFeatures.displayP3)?{postcssPlugin:"postcss-relative-color-syntax",plugins:[e(),basePlugin(r)]}:basePlugin(r)};postcssPlugin.postcss=!0,module.exports=postcssPlugin; +"use strict";var e=require("@csstools/postcss-progressive-custom-properties"),s=require("@csstools/css-tokenizer"),r=require("@csstools/css-color-parser"),t=require("@csstools/css-parser-algorithms");function hasFallback(e){const s=e.parent;if(!s)return!1;const r=e.prop.toLowerCase(),t=s.index(e);for(let e=0;e({postcssPlugin:"postcss-relative-color-syntax",Declaration:o=>{const i=o.value;if(!a.test(i))return;if(!l.test(i))return;if(hasFallback(o))return;if(hasSupportsAtRuleAncestor(o))return;const u=s.tokenize({css:i}),c=t.replaceComponentValues(t.parseCommaSeparatedListOfComponentValues(u),(e=>{if(t.isFunctionNode(e)&&n.test(e.getName())){const s=r.color(e);if(!s)return;if(s.syntaxFlags.has(r.SyntaxFlag.Experimental))return;if(s.syntaxFlags.has(r.SyntaxFlag.HasNoneKeywords))return;if(!s.syntaxFlags.has(r.SyntaxFlag.RelativeColorSyntax))return;return r.serializeRGB(s)}})),p=t.stringify(c);if(p===i)return;let f=p;e?.subFeatures.displayP3&&(f=t.stringify(t.replaceComponentValues(t.parseCommaSeparatedListOfComponentValues(u),(e=>{if(t.isFunctionNode(e)&&n.test(e.getName())){const s=r.color(e);if(!s)return;if(s.syntaxFlags.has(r.SyntaxFlag.HasNoneKeywords))return;if(!s.syntaxFlags.has(r.SyntaxFlag.RelativeColorSyntax))return;return r.colorDataFitsRGB_Gamut(s)?r.serializeRGB(s):r.serializeP3(s)}})))),o.cloneBefore({value:p}),e?.subFeatures.displayP3&&f!==p&&o.cloneBefore({value:f}),e?.preserve||o.remove()}});basePlugin.postcss=!0;const postcssPlugin=s=>{const r=Object.assign({enableProgressiveCustomProperties:!0,preserve:!1,subFeatures:{displayP3:!0}},s);return r.subFeatures=Object.assign({displayP3:!0},r.subFeatures),r.enableProgressiveCustomProperties&&(r.preserve||r.subFeatures.displayP3)?{postcssPlugin:"postcss-relative-color-syntax",plugins:[e(),basePlugin(r)]}:basePlugin(r)};postcssPlugin.postcss=!0,module.exports=postcssPlugin; diff --git a/plugins/postcss-relative-color-syntax/dist/index.d.ts b/plugins/postcss-relative-color-syntax/dist/index.d.ts index 15f89fd40..5593b607f 100644 --- a/plugins/postcss-relative-color-syntax/dist/index.d.ts +++ b/plugins/postcss-relative-color-syntax/dist/index.d.ts @@ -1,6 +1,7 @@ import type { PluginCreator } from 'postcss'; + /** postcss-relative-color-syntax plugin options */ -export type pluginOptions = { +export declare type pluginOptions = { /** Preserve the original notation. default: false */ preserve?: boolean; /** Enable "@csstools/postcss-progressive-custom-properties". default: true */ @@ -11,5 +12,8 @@ export type pluginOptions = { displayP3?: boolean; }; }; + declare const postcssPlugin: PluginCreator; export default postcssPlugin; + +export { } diff --git a/plugins/postcss-relative-color-syntax/dist/index.mjs b/plugins/postcss-relative-color-syntax/dist/index.mjs index 7964ee08d..6da2bc630 100644 --- a/plugins/postcss-relative-color-syntax/dist/index.mjs +++ b/plugins/postcss-relative-color-syntax/dist/index.mjs @@ -1 +1 @@ -import s from"@csstools/postcss-progressive-custom-properties";import{tokenize as e}from"@csstools/css-tokenizer";import{color as r,SyntaxFlag as t,serializeRGB as o,colorDataFitsRGB_Gamut as a,serializeP3 as l}from"@csstools/css-color-parser";import{replaceComponentValues as n,parseCommaSeparatedListOfComponentValues as i,isFunctionNode as u,stringify as c}from"@csstools/css-parser-algorithms";function hasFallback(s){const e=s.parent;if(!e)return!1;const r=s.prop.toLowerCase(),t=e.index(s);for(let s=0;s({postcssPlugin:"postcss-relative-color-syntax",Declaration:p=>{const m=p.value;if(!f.test(m))return;if(!h.test(m))return;if(hasFallback(p))return;if(hasSupportsAtRuleAncestor(p))return;const g=e({css:m}),y=n(i(g),(s=>{if(u(s)&&b.test(s.getName())){const e=r(s);if(!e)return;if(e.syntaxFlags.has(t.Experimental))return;if(e.syntaxFlags.has(t.HasNoneKeywords))return;if(!e.syntaxFlags.has(t.RelativeColorSyntax))return;return o(e)}})),v=c(y);if(v===m)return;let F=v;null!=s&&s.subFeatures.displayP3&&(F=c(n(i(g),(s=>{if(u(s)&&b.test(s.getName())){const e=r(s);if(!e)return;if(e.syntaxFlags.has(t.HasNoneKeywords))return;if(!e.syntaxFlags.has(t.RelativeColorSyntax))return;return a(e)?o(e):l(e)}})))),p.cloneBefore({value:v}),null!=s&&s.subFeatures.displayP3&&F!==v&&p.cloneBefore({value:F}),null!=s&&s.preserve||p.remove()}});basePlugin.postcss=!0;const postcssPlugin=e=>{const r=Object.assign({enableProgressiveCustomProperties:!0,preserve:!1,subFeatures:{displayP3:!0}},e);return r.subFeatures=Object.assign({displayP3:!0},r.subFeatures),r.enableProgressiveCustomProperties&&(r.preserve||r.subFeatures.displayP3)?{postcssPlugin:"postcss-relative-color-syntax",plugins:[s(),basePlugin(r)]}:basePlugin(r)};postcssPlugin.postcss=!0;export{postcssPlugin as default}; +import s from"@csstools/postcss-progressive-custom-properties";import{tokenize as e}from"@csstools/css-tokenizer";import{color as r,SyntaxFlag as t,serializeRGB as o,colorDataFitsRGB_Gamut as a,serializeP3 as l}from"@csstools/css-color-parser";import{replaceComponentValues as n,parseCommaSeparatedListOfComponentValues as i,isFunctionNode as c,stringify as u}from"@csstools/css-parser-algorithms";function hasFallback(s){const e=s.parent;if(!e)return!1;const r=s.prop.toLowerCase(),t=e.index(s);for(let s=0;s({postcssPlugin:"postcss-relative-color-syntax",Declaration:p=>{const m=p.value;if(!f.test(m))return;if(!h.test(m))return;if(hasFallback(p))return;if(hasSupportsAtRuleAncestor(p))return;const g=e({css:m}),y=n(i(g),(s=>{if(c(s)&&b.test(s.getName())){const e=r(s);if(!e)return;if(e.syntaxFlags.has(t.Experimental))return;if(e.syntaxFlags.has(t.HasNoneKeywords))return;if(!e.syntaxFlags.has(t.RelativeColorSyntax))return;return o(e)}})),v=u(y);if(v===m)return;let F=v;s?.subFeatures.displayP3&&(F=u(n(i(g),(s=>{if(c(s)&&b.test(s.getName())){const e=r(s);if(!e)return;if(e.syntaxFlags.has(t.HasNoneKeywords))return;if(!e.syntaxFlags.has(t.RelativeColorSyntax))return;return a(e)?o(e):l(e)}})))),p.cloneBefore({value:v}),s?.subFeatures.displayP3&&F!==v&&p.cloneBefore({value:F}),s?.preserve||p.remove()}});basePlugin.postcss=!0;const postcssPlugin=e=>{const r=Object.assign({enableProgressiveCustomProperties:!0,preserve:!1,subFeatures:{displayP3:!0}},e);return r.subFeatures=Object.assign({displayP3:!0},r.subFeatures),r.enableProgressiveCustomProperties&&(r.preserve||r.subFeatures.displayP3)?{postcssPlugin:"postcss-relative-color-syntax",plugins:[s(),basePlugin(r)]}:basePlugin(r)};postcssPlugin.postcss=!0;export{postcssPlugin as default}; diff --git a/plugins/postcss-relative-color-syntax/package.json b/plugins/postcss-relative-color-syntax/package.json index 5667037c6..754cedef3 100644 --- a/plugins/postcss-relative-color-syntax/package.json +++ b/plugins/postcss-relative-color-syntax/package.json @@ -27,15 +27,18 @@ "engines": { "node": "^14 || ^16 || >=18" }, + "type": "module", "main": "dist/index.cjs", "module": "dist/index.mjs", - "types": "dist/index.d.ts", "exports": { ".": { - "types": "./dist/index.d.ts", - "import": "./dist/index.mjs", - "require": "./dist/index.cjs", - "default": "./dist/index.mjs" + "import": { + "types": "./dist/index.d.ts", + "default": "./dist/index.mjs" + }, + "require": { + "default": "./dist/index.cjs" + } } }, "files": [ diff --git a/plugins/postcss-scope-pseudo-class/CHANGELOG.md b/plugins/postcss-scope-pseudo-class/CHANGELOG.md index 146f6b270..0b615cfaf 100644 --- a/plugins/postcss-scope-pseudo-class/CHANGELOG.md +++ b/plugins/postcss-scope-pseudo-class/CHANGELOG.md @@ -2,7 +2,7 @@ ### Unreleased (patch) -- Small fixes in type definitions +- Fix type definitions ### 3.0.0 diff --git a/plugins/postcss-scope-pseudo-class/api-extractor.json b/plugins/postcss-scope-pseudo-class/api-extractor.json new file mode 100644 index 000000000..42058be51 --- /dev/null +++ b/plugins/postcss-scope-pseudo-class/api-extractor.json @@ -0,0 +1,4 @@ +{ + "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json", + "extends": "../../api-extractor.json" +} diff --git a/plugins/postcss-scope-pseudo-class/dist/index.d.ts b/plugins/postcss-scope-pseudo-class/dist/index.d.ts index 77dc51e7b..69020b0f4 100644 --- a/plugins/postcss-scope-pseudo-class/dist/index.d.ts +++ b/plugins/postcss-scope-pseudo-class/dist/index.d.ts @@ -1,8 +1,12 @@ import type { PluginCreator } from 'postcss'; + +declare const creator: PluginCreator; +export default creator; + /** postcss-scope-pseudo-class plugin options */ -export type pluginOptions = { +export declare type pluginOptions = { /** Preserve the original notation. default: false */ preserve?: boolean; }; -declare const creator: PluginCreator; -export default creator; + +export { } diff --git a/plugins/postcss-scope-pseudo-class/package.json b/plugins/postcss-scope-pseudo-class/package.json index 2e67a4804..3486e854d 100644 --- a/plugins/postcss-scope-pseudo-class/package.json +++ b/plugins/postcss-scope-pseudo-class/package.json @@ -27,15 +27,18 @@ "engines": { "node": "^14 || ^16 || >=18" }, + "type": "module", "main": "dist/index.cjs", "module": "dist/index.mjs", - "types": "dist/index.d.ts", "exports": { ".": { - "types": "./dist/index.d.ts", - "import": "./dist/index.mjs", - "require": "./dist/index.cjs", - "default": "./dist/index.mjs" + "import": { + "types": "./dist/index.d.ts", + "default": "./dist/index.mjs" + }, + "require": { + "default": "./dist/index.cjs" + } } }, "files": [ diff --git a/plugins/postcss-selector-not/CHANGELOG.md b/plugins/postcss-selector-not/CHANGELOG.md index e5554c0f9..8fe149de1 100644 --- a/plugins/postcss-selector-not/CHANGELOG.md +++ b/plugins/postcss-selector-not/CHANGELOG.md @@ -2,7 +2,7 @@ ### Unreleased (patch) -- Small fixes in type definitions +- Fix type definitions ### 7.0.1 diff --git a/plugins/postcss-selector-not/api-extractor.json b/plugins/postcss-selector-not/api-extractor.json new file mode 100644 index 000000000..42058be51 --- /dev/null +++ b/plugins/postcss-selector-not/api-extractor.json @@ -0,0 +1,4 @@ +{ + "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json", + "extends": "../../api-extractor.json" +} diff --git a/plugins/postcss-selector-not/dist/index.d.ts b/plugins/postcss-selector-not/dist/index.d.ts index af28b15e4..9ecd70532 100644 --- a/plugins/postcss-selector-not/dist/index.d.ts +++ b/plugins/postcss-selector-not/dist/index.d.ts @@ -1,5 +1,9 @@ import type { PluginCreator } from 'postcss'; -/** postcss-selector-not plugin options */ -export type pluginOptions = Record; + declare const creator: PluginCreator; export default creator; + +/** postcss-selector-not plugin options */ +export declare type pluginOptions = Record; + +export { } diff --git a/plugins/postcss-selector-not/package.json b/plugins/postcss-selector-not/package.json index b4c492c86..eb5ae4329 100644 --- a/plugins/postcss-selector-not/package.json +++ b/plugins/postcss-selector-not/package.json @@ -30,15 +30,18 @@ "engines": { "node": "^14 || ^16 || >=18" }, + "type": "module", "main": "dist/index.cjs", "module": "dist/index.mjs", - "types": "dist/index.d.ts", "exports": { ".": { - "types": "./dist/index.d.ts", - "import": "./dist/index.mjs", - "require": "./dist/index.cjs", - "default": "./dist/index.mjs" + "import": { + "types": "./dist/index.d.ts", + "default": "./dist/index.mjs" + }, + "require": { + "default": "./dist/index.cjs" + } } }, "files": [ diff --git a/plugins/postcss-slow-plugins/CHANGELOG.md b/plugins/postcss-slow-plugins/CHANGELOG.md index 3b6b218de..4bae41368 100644 --- a/plugins/postcss-slow-plugins/CHANGELOG.md +++ b/plugins/postcss-slow-plugins/CHANGELOG.md @@ -1,5 +1,9 @@ # Changes to PostCSS Slow Plugins +### Unreleased (patch) + +- Fix type definitions + ### 1.0.1 _September 4, 2023_ diff --git a/plugins/postcss-slow-plugins/api-extractor.json b/plugins/postcss-slow-plugins/api-extractor.json new file mode 100644 index 000000000..42058be51 --- /dev/null +++ b/plugins/postcss-slow-plugins/api-extractor.json @@ -0,0 +1,4 @@ +{ + "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json", + "extends": "../../api-extractor.json" +} diff --git a/plugins/postcss-slow-plugins/dist/index.cjs b/plugins/postcss-slow-plugins/dist/index.cjs index 5786fbc5d..e7ddd5d97 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=(null==s?void 0:s.ignore)??[];return{postcssPlugin:"postcss-slow-plugins",Once:async(s,{result:n,postcss:t})=>{var e,i;console.log("Analyzing with file:\n "+(null==(e=s.source)?void 0:e.input.from)+"\n");const l=(null==(i=s.source)?void 0:i.input.css)??"",r=[...n.processor.plugins.filter((s=>"postcssPlugin"in s&&"postcss-slow-plugins"!==s.postcssPlugin))],c=(await t(r).process(l??"",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(r).process(l??"",n.opts)).css}));{const s=[];for(let e=0;es!==r[e])),a=await medianDuration((async()=>{(await t(u).process(l??"",n.opts)).css})),d=p-a;s.push({duration:`${a.toFixed(3)}ms`,"kb's per ms":`${(c/a).toFixed(3)}kb/ms`,drop:d,name:i,"index in plugins list":e})}s.sort(((s,o)=>Number(o.drop)-Number(s.drop))),s.splice(0,0,{duration:`${p.toFixed(3)}ms`,"kb's per ms":`${(c/p).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 e=0;es===r[e]||"postcssPlugin"in s&&o.includes(s.postcssPlugin)))],a=await medianDuration((async()=>{(await t(u).process(l??"",n.opts)).css})),d=p-a;s.push({duration:`${a.toFixed(3)}ms`,"kb's per ms":`${(c/a).toFixed(3)}kb/ms`,drop:d,name:i,"index in plugins list":e})}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",Once:async(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; diff --git a/plugins/postcss-slow-plugins/dist/index.d.ts b/plugins/postcss-slow-plugins/dist/index.d.ts index 753b96144..2c043bca2 100644 --- a/plugins/postcss-slow-plugins/dist/index.d.ts +++ b/plugins/postcss-slow-plugins/dist/index.d.ts @@ -1,8 +1,12 @@ import type { PluginCreator } from 'postcss'; + +declare const creator: PluginCreator; +export default creator; + /** postcss-slow-plugins plugin options */ -export type pluginOptions = { +export declare type pluginOptions = { /** Plugins to ignore when reporting the results */ ignore?: Array; }; -declare const creator: PluginCreator; -export default creator; + +export { } diff --git a/plugins/postcss-slow-plugins/dist/index.mjs b/plugins/postcss-slow-plugins/dist/index.mjs index a87dc5bf3..073cd31c7 100644 --- a/plugins/postcss-slow-plugins/dist/index.mjs +++ b/plugins/postcss-slow-plugins/dist/index.mjs @@ -1 +1 @@ -const creator=s=>{const o=(null==s?void 0:s.ignore)??[];return{postcssPlugin:"postcss-slow-plugins",Once:async(s,{result:n,postcss:t})=>{var e,i;console.log("Analyzing with file:\n "+(null==(e=s.source)?void 0:e.input.from)+"\n");const l=(null==(i=s.source)?void 0:i.input.css)??"",r=[...n.processor.plugins.filter((s=>"postcssPlugin"in s&&"postcss-slow-plugins"!==s.postcssPlugin))],c=(await t(r).process(l??"",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(r).process(l??"",n.opts)).css}));{const s=[];for(let e=0;es!==r[e])),a=await medianDuration((async()=>{(await t(u).process(l??"",n.opts)).css})),d=p-a;s.push({duration:`${a.toFixed(3)}ms`,"kb's per ms":`${(c/a).toFixed(3)}kb/ms`,drop:d,name:i,"index in plugins list":e})}s.sort(((s,o)=>Number(o.drop)-Number(s.drop))),s.splice(0,0,{duration:`${p.toFixed(3)}ms`,"kb's per ms":`${(c/p).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 e=0;es===r[e]||"postcssPlugin"in s&&o.includes(s.postcssPlugin)))],a=await medianDuration((async()=>{(await t(u).process(l??"",n.opts)).css})),d=p-a;s.push({duration:`${a.toFixed(3)}ms`,"kb's per ms":`${(c/a).toFixed(3)}kb/ms`,drop:d,name:i,"index in plugins list":e})}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",Once:async(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}; diff --git a/plugins/postcss-slow-plugins/package.json b/plugins/postcss-slow-plugins/package.json index ec49e7e85..229d2b595 100644 --- a/plugins/postcss-slow-plugins/package.json +++ b/plugins/postcss-slow-plugins/package.json @@ -27,15 +27,18 @@ "engines": { "node": "^14 || ^16 || >=18" }, + "type": "module", "main": "dist/index.cjs", "module": "dist/index.mjs", - "types": "dist/index.d.ts", "exports": { ".": { - "types": "./dist/index.d.ts", - "import": "./dist/index.mjs", - "require": "./dist/index.cjs", - "default": "./dist/index.mjs" + "import": { + "types": "./dist/index.d.ts", + "default": "./dist/index.mjs" + }, + "require": { + "default": "./dist/index.cjs" + } } }, "files": [ diff --git a/plugins/postcss-stepped-value-functions/CHANGELOG.md b/plugins/postcss-stepped-value-functions/CHANGELOG.md index f0195ccba..9b8971525 100644 --- a/plugins/postcss-stepped-value-functions/CHANGELOG.md +++ b/plugins/postcss-stepped-value-functions/CHANGELOG.md @@ -2,7 +2,7 @@ ### Unreleased (patch) -- Small fixes in type definitions +- Fix type definitions ### 3.0.2 diff --git a/plugins/postcss-stepped-value-functions/api-extractor.json b/plugins/postcss-stepped-value-functions/api-extractor.json new file mode 100644 index 000000000..42058be51 --- /dev/null +++ b/plugins/postcss-stepped-value-functions/api-extractor.json @@ -0,0 +1,4 @@ +{ + "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json", + "extends": "../../api-extractor.json" +} diff --git a/plugins/postcss-stepped-value-functions/dist/index.d.ts b/plugins/postcss-stepped-value-functions/dist/index.d.ts index c7772f768..f5f73bbff 100644 --- a/plugins/postcss-stepped-value-functions/dist/index.d.ts +++ b/plugins/postcss-stepped-value-functions/dist/index.d.ts @@ -1,8 +1,12 @@ import type { PluginCreator } from 'postcss'; + +declare const creator: PluginCreator; +export default creator; + /** postcss-stepped-value-functions plugin options */ -export type pluginOptions = { +export declare type pluginOptions = { /** Preserve the original notation. default: false */ preserve?: boolean; }; -declare const creator: PluginCreator; -export default creator; + +export { } diff --git a/plugins/postcss-stepped-value-functions/package.json b/plugins/postcss-stepped-value-functions/package.json index eab24b208..17012d657 100644 --- a/plugins/postcss-stepped-value-functions/package.json +++ b/plugins/postcss-stepped-value-functions/package.json @@ -27,15 +27,18 @@ "engines": { "node": "^14 || ^16 || >=18" }, + "type": "module", "main": "dist/index.cjs", "module": "dist/index.mjs", - "types": "dist/index.d.ts", "exports": { ".": { - "types": "./dist/index.d.ts", - "import": "./dist/index.mjs", - "require": "./dist/index.cjs", - "default": "./dist/index.mjs" + "import": { + "types": "./dist/index.d.ts", + "default": "./dist/index.mjs" + }, + "require": { + "default": "./dist/index.cjs" + } } }, "files": [ diff --git a/plugins/postcss-text-decoration-shorthand/CHANGELOG.md b/plugins/postcss-text-decoration-shorthand/CHANGELOG.md index 00ec3a12e..b631076a0 100644 --- a/plugins/postcss-text-decoration-shorthand/CHANGELOG.md +++ b/plugins/postcss-text-decoration-shorthand/CHANGELOG.md @@ -1,5 +1,9 @@ # Changes to PostCSS Text Decoration Shorthand +### Unreleased (patch) + +- Fix type definitions + ### 3.0.3 _September 18, 2023_ diff --git a/plugins/postcss-text-decoration-shorthand/api-extractor.json b/plugins/postcss-text-decoration-shorthand/api-extractor.json new file mode 100644 index 000000000..42058be51 --- /dev/null +++ b/plugins/postcss-text-decoration-shorthand/api-extractor.json @@ -0,0 +1,4 @@ +{ + "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json", + "extends": "../../api-extractor.json" +} diff --git a/plugins/postcss-text-decoration-shorthand/dist/index.d.ts b/plugins/postcss-text-decoration-shorthand/dist/index.d.ts index c98089699..d0d73801e 100644 --- a/plugins/postcss-text-decoration-shorthand/dist/index.d.ts +++ b/plugins/postcss-text-decoration-shorthand/dist/index.d.ts @@ -1,8 +1,12 @@ import type { PluginCreator } from 'postcss'; + +declare const creator: PluginCreator; +export default creator; + /** postcss-text-decoration-shorthand plugin options */ -export type pluginOptions = { +export declare type pluginOptions = { /** Preserve the original notation. default: true */ preserve?: boolean; }; -declare const creator: PluginCreator; -export default creator; + +export { } diff --git a/plugins/postcss-text-decoration-shorthand/package.json b/plugins/postcss-text-decoration-shorthand/package.json index 6d1d60064..919dff4a7 100644 --- a/plugins/postcss-text-decoration-shorthand/package.json +++ b/plugins/postcss-text-decoration-shorthand/package.json @@ -27,15 +27,18 @@ "engines": { "node": "^14 || ^16 || >=18" }, + "type": "module", "main": "dist/index.cjs", "module": "dist/index.mjs", - "types": "dist/index.d.ts", "exports": { ".": { - "types": "./dist/index.d.ts", - "import": "./dist/index.mjs", - "require": "./dist/index.cjs", - "default": "./dist/index.mjs" + "import": { + "types": "./dist/index.d.ts", + "default": "./dist/index.mjs" + }, + "require": { + "default": "./dist/index.cjs" + } } }, "files": [ diff --git a/plugins/postcss-todo-or-die/CHANGELOG.md b/plugins/postcss-todo-or-die/CHANGELOG.md index 3273c0f38..a0abf3427 100644 --- a/plugins/postcss-todo-or-die/CHANGELOG.md +++ b/plugins/postcss-todo-or-die/CHANGELOG.md @@ -2,7 +2,7 @@ ### Unreleased (patch) -- Small fixes in type definitions +- Fix type definitions ### 2.0.2 diff --git a/plugins/postcss-todo-or-die/api-extractor.json b/plugins/postcss-todo-or-die/api-extractor.json new file mode 100644 index 000000000..42058be51 --- /dev/null +++ b/plugins/postcss-todo-or-die/api-extractor.json @@ -0,0 +1,4 @@ +{ + "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json", + "extends": "../../api-extractor.json" +} diff --git a/plugins/postcss-todo-or-die/dist/died.d.ts b/plugins/postcss-todo-or-die/dist/died.d.ts deleted file mode 100644 index c44d72799..000000000 --- a/plugins/postcss-todo-or-die/dist/died.d.ts +++ /dev/null @@ -1 +0,0 @@ -export declare function died(conditionResult: string | true | undefined): conditionResult is string; diff --git a/plugins/postcss-todo-or-die/dist/index.d.ts b/plugins/postcss-todo-or-die/dist/index.d.ts index 89d75c8fd..73f8cdb79 100644 --- a/plugins/postcss-todo-or-die/dist/index.d.ts +++ b/plugins/postcss-todo-or-die/dist/index.d.ts @@ -1,3 +1,6 @@ import type { PluginCreator } from 'postcss'; + declare const creator: PluginCreator; export default creator; + +export { } diff --git a/plugins/postcss-todo-or-die/dist/match/before-date.d.ts b/plugins/postcss-todo-or-die/dist/match/before-date.d.ts deleted file mode 100644 index 17cbf8058..000000000 --- a/plugins/postcss-todo-or-die/dist/match/before-date.d.ts +++ /dev/null @@ -1 +0,0 @@ -export declare function matchBeforeDateCondition(year: number, month: number, day: number): string | true | undefined; diff --git a/plugins/postcss-todo-or-die/dist/match/browserslist.d.ts b/plugins/postcss-todo-or-die/dist/match/browserslist.d.ts deleted file mode 100644 index 0e958847a..000000000 --- a/plugins/postcss-todo-or-die/dist/match/browserslist.d.ts +++ /dev/null @@ -1 +0,0 @@ -export declare function matchBrowserslistCondition(condition: string, browsers: Set): string | true | undefined; diff --git a/plugins/postcss-todo-or-die/dist/match/if.d.ts b/plugins/postcss-todo-or-die/dist/match/if.d.ts deleted file mode 100644 index 82ad9d644..000000000 --- a/plugins/postcss-todo-or-die/dist/match/if.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import { IfCondition } from '../parse/if'; -export declare function matchIfCondition(condition: IfCondition): string | true | undefined; diff --git a/plugins/postcss-todo-or-die/dist/match/not.d.ts b/plugins/postcss-todo-or-die/dist/match/not.d.ts deleted file mode 100644 index be0ffa5f1..000000000 --- a/plugins/postcss-todo-or-die/dist/match/not.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import { IfCondition } from '../parse/if'; -export declare function matchNotCondition(condition: IfCondition): string | true | undefined; diff --git a/plugins/postcss-todo-or-die/dist/parse/before-data.d.ts b/plugins/postcss-todo-or-die/dist/parse/before-data.d.ts deleted file mode 100644 index 3802d2fa1..000000000 --- a/plugins/postcss-todo-or-die/dist/parse/before-data.d.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { FunctionNode } from '@csstools/css-parser-algorithms'; -type BeforeDateCondition = { - year: number; - month: number; - day: number; -}; -export declare function parseBeforeDateCondition(componentValue: FunctionNode): BeforeDateCondition | false; -export {}; diff --git a/plugins/postcss-todo-or-die/dist/parse/browserslist.d.ts b/plugins/postcss-todo-or-die/dist/parse/browserslist.d.ts deleted file mode 100644 index bd01ae86d..000000000 --- a/plugins/postcss-todo-or-die/dist/parse/browserslist.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import { FunctionNode } from '@csstools/css-parser-algorithms'; -export declare function parseBrowserslistCondition(componentValue: FunctionNode): string | false; diff --git a/plugins/postcss-todo-or-die/dist/parse/if.d.ts b/plugins/postcss-todo-or-die/dist/parse/if.d.ts deleted file mode 100644 index c138f0592..000000000 --- a/plugins/postcss-todo-or-die/dist/parse/if.d.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { FunctionNode } from '@csstools/css-parser-algorithms'; -import { TokenDimension, TokenIdent, TokenNumber, TokenPercentage } from '@csstools/css-tokenizer'; -type SubjectToken = TokenIdent | TokenNumber | TokenPercentage | TokenDimension; -export type IfCondition = { - a: SubjectToken; - b: SubjectToken; - operator: '<' | '>' | '='; -}; -export declare function parseIfCondition(componentValue: FunctionNode): IfCondition | false; -export {}; diff --git a/plugins/postcss-todo-or-die/dist/parse/not.d.ts b/plugins/postcss-todo-or-die/dist/parse/not.d.ts deleted file mode 100644 index 8918e965a..000000000 --- a/plugins/postcss-todo-or-die/dist/parse/not.d.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { FunctionNode } from '@csstools/css-parser-algorithms'; -import { TokenDimension, TokenIdent, TokenNumber, TokenPercentage } from '@csstools/css-tokenizer'; -type SubjectToken = TokenIdent | TokenNumber | TokenPercentage | TokenDimension; -type NotCondition = { - a: SubjectToken; - b: SubjectToken; - operator: '<' | '>' | '='; -}; -export declare function parseNotCondition(componentValue: FunctionNode): NotCondition | false; -export {}; diff --git a/plugins/postcss-todo-or-die/package.json b/plugins/postcss-todo-or-die/package.json index d174e2a35..9fbffc66f 100644 --- a/plugins/postcss-todo-or-die/package.json +++ b/plugins/postcss-todo-or-die/package.json @@ -27,14 +27,18 @@ "engines": { "node": "^14 || ^16 || >=18" }, + "type": "module", "main": "dist/index.cjs", "module": "dist/index.mjs", - "types": "dist/index.d.ts", "exports": { ".": { - "import": "./dist/index.mjs", - "require": "./dist/index.cjs", - "default": "./dist/index.mjs" + "import": { + "types": "./dist/index.d.ts", + "default": "./dist/index.mjs" + }, + "require": { + "default": "./dist/index.cjs" + } } }, "files": [ diff --git a/plugins/postcss-trigonometric-functions/CHANGELOG.md b/plugins/postcss-trigonometric-functions/CHANGELOG.md index 31e44fddb..5a6a80408 100644 --- a/plugins/postcss-trigonometric-functions/CHANGELOG.md +++ b/plugins/postcss-trigonometric-functions/CHANGELOG.md @@ -2,7 +2,7 @@ ### Unreleased (patch) -- Small fixes in type definitions +- Fix type definitions ### 3.0.2 diff --git a/plugins/postcss-trigonometric-functions/api-extractor.json b/plugins/postcss-trigonometric-functions/api-extractor.json new file mode 100644 index 000000000..42058be51 --- /dev/null +++ b/plugins/postcss-trigonometric-functions/api-extractor.json @@ -0,0 +1,4 @@ +{ + "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json", + "extends": "../../api-extractor.json" +} diff --git a/plugins/postcss-trigonometric-functions/dist/index.d.ts b/plugins/postcss-trigonometric-functions/dist/index.d.ts index 40ac49ea1..21e161538 100644 --- a/plugins/postcss-trigonometric-functions/dist/index.d.ts +++ b/plugins/postcss-trigonometric-functions/dist/index.d.ts @@ -1,8 +1,12 @@ import type { PluginCreator } from 'postcss'; + +declare const creator: PluginCreator; +export default creator; + /** postcss-trigonometric-functions plugin options */ -export type pluginOptions = { +export declare type pluginOptions = { /** Preserve the original notation. default: false */ preserve?: boolean; }; -declare const creator: PluginCreator; -export default creator; + +export { } diff --git a/plugins/postcss-trigonometric-functions/package.json b/plugins/postcss-trigonometric-functions/package.json index 95a0b08f5..e3739f4f2 100644 --- a/plugins/postcss-trigonometric-functions/package.json +++ b/plugins/postcss-trigonometric-functions/package.json @@ -27,15 +27,18 @@ "engines": { "node": "^14 || ^16 || >=18" }, + "type": "module", "main": "dist/index.cjs", "module": "dist/index.mjs", - "types": "dist/index.d.ts", "exports": { ".": { - "types": "./dist/index.d.ts", - "import": "./dist/index.mjs", - "require": "./dist/index.cjs", - "default": "./dist/index.mjs" + "import": { + "types": "./dist/index.d.ts", + "default": "./dist/index.mjs" + }, + "require": { + "default": "./dist/index.cjs" + } } }, "files": [ diff --git a/plugins/postcss-unset-value/CHANGELOG.md b/plugins/postcss-unset-value/CHANGELOG.md index 438f5c2de..cbe9628ba 100644 --- a/plugins/postcss-unset-value/CHANGELOG.md +++ b/plugins/postcss-unset-value/CHANGELOG.md @@ -1,5 +1,9 @@ # Changes to PostCSS Unset Value +### Unreleased (patch) + +- Fix type definitions + ### 3.0.0 _July 3, 2023_ diff --git a/plugins/postcss-unset-value/api-extractor.json b/plugins/postcss-unset-value/api-extractor.json new file mode 100644 index 000000000..42058be51 --- /dev/null +++ b/plugins/postcss-unset-value/api-extractor.json @@ -0,0 +1,4 @@ +{ + "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json", + "extends": "../../api-extractor.json" +} diff --git a/plugins/postcss-unset-value/dist/index.d.ts b/plugins/postcss-unset-value/dist/index.d.ts index 9bf13c0d0..c211bb827 100644 --- a/plugins/postcss-unset-value/dist/index.d.ts +++ b/plugins/postcss-unset-value/dist/index.d.ts @@ -1,8 +1,12 @@ import type { PluginCreator } from 'postcss'; + +declare const creator: PluginCreator; +export default creator; + /** postcss-unset-value plugin options */ -export type pluginOptions = { +export declare type pluginOptions = { /** Preserve the original notation. default: false */ preserve?: boolean; }; -declare const creator: PluginCreator; -export default creator; + +export { } diff --git a/plugins/postcss-unset-value/dist/property-def.d.ts b/plugins/postcss-unset-value/dist/property-def.d.ts deleted file mode 100644 index 46c840737..000000000 --- a/plugins/postcss-unset-value/dist/property-def.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -export declare const inherited: Set; -export declare const nonInherited: Set; diff --git a/plugins/postcss-unset-value/package.json b/plugins/postcss-unset-value/package.json index 6ecdd94ed..1113b5bc2 100644 --- a/plugins/postcss-unset-value/package.json +++ b/plugins/postcss-unset-value/package.json @@ -27,15 +27,18 @@ "engines": { "node": "^14 || ^16 || >=18" }, + "type": "module", "main": "dist/index.cjs", "module": "dist/index.mjs", - "types": "dist/index.d.ts", "exports": { ".": { - "types": "./dist/index.d.ts", - "import": "./dist/index.mjs", - "require": "./dist/index.cjs", - "default": "./dist/index.mjs" + "import": { + "types": "./dist/index.d.ts", + "default": "./dist/index.mjs" + }, + "require": { + "default": "./dist/index.cjs" + } } }, "files": [ diff --git a/postcss-recipes/minimal-setup/package.json b/postcss-recipes/minimal-setup/package.json index 87f979126..84b0f4bca 100644 --- a/postcss-recipes/minimal-setup/package.json +++ b/postcss-recipes/minimal-setup/package.json @@ -30,7 +30,6 @@ ] }, "volta": { - "node": "20.2.0", - "npm": "9.6.7" + "node": "20.10.0" } } diff --git a/postcss-recipes/open-props/package.json b/postcss-recipes/open-props/package.json index 96fba25b0..895cdfbf2 100644 --- a/postcss-recipes/open-props/package.json +++ b/postcss-recipes/open-props/package.json @@ -22,7 +22,6 @@ "watch": "postcss -w ./src/style.css -o ./dist/style.css -m" }, "volta": { - "node": "20.2.0", - "npm": "9.6.7" + "node": "20.10.0" } } diff --git a/rollup/configs/babel-presets.mjs b/rollup/configs/babel-presets.mjs deleted file mode 100644 index 5184fb394..000000000 --- a/rollup/configs/babel-presets.mjs +++ /dev/null @@ -1,8 +0,0 @@ -export const packageBabelPreset = [ - ['@babel/preset-env', { - loose: true, - modules: false, - targets: { node: 14 }, - useBuiltIns: false, - }], -]; diff --git a/rollup/presets/cli-typescript.mjs b/rollup/presets/cli-typescript.mjs index 636498d9c..2ec9c245d 100644 --- a/rollup/presets/cli-typescript.mjs +++ b/rollup/presets/cli-typescript.mjs @@ -1,4 +1,3 @@ -import babel from '@rollup/plugin-babel'; import commonjs from '@rollup/plugin-commonjs'; import path from 'path'; import terser from '@rollup/plugin-terser'; @@ -6,7 +5,6 @@ import typescript from '@rollup/plugin-typescript'; import { addHashBang } from '../transforms/cli-hash-bang.mjs'; import { externalsForCLI } from '../configs/externals.mjs'; import { nodeResolve } from '@rollup/plugin-node-resolve'; -import { packageBabelPreset } from '../configs/babel-presets.mjs'; export function cliTypescript() { return [ @@ -22,12 +20,6 @@ export function cliTypescript() { nodeResolve({ rootDir: path.join(process.cwd(), '..', '..'), }), - babel({ - babelHelpers: 'bundled', - exclude: 'node_modules/**', - extensions: ['.js', '.ts'], - presets: packageBabelPreset, - }), terser({ compress: { reduce_funcs: false, // https://github.com/terser/terser/issues/1305 diff --git a/rollup/presets/package-javascript.mjs b/rollup/presets/package-javascript.mjs index 986f3e0a9..a78ef6e37 100644 --- a/rollup/presets/package-javascript.mjs +++ b/rollup/presets/package-javascript.mjs @@ -1,7 +1,5 @@ -import babel from '@rollup/plugin-babel'; import terser from '@rollup/plugin-terser'; import { externalsForPlugin } from '../configs/externals.mjs'; -import { packageBabelPreset } from '../configs/babel-presets.mjs'; export function packageJavascript() { return [ @@ -13,11 +11,6 @@ export function packageJavascript() { ], external: externalsForPlugin, plugins: [ - babel({ - babelHelpers: 'bundled', - exclude: 'node_modules/**', - presets: packageBabelPreset, - }), terser({ compress: { reduce_funcs: false, // https://github.com/terser/terser/issues/1305 diff --git a/rollup/presets/package-typescript.mjs b/rollup/presets/package-typescript.mjs index 8477a020c..151630a8c 100644 --- a/rollup/presets/package-typescript.mjs +++ b/rollup/presets/package-typescript.mjs @@ -1,8 +1,7 @@ -import babel from '@rollup/plugin-babel'; import terser from '@rollup/plugin-terser'; import typescript from '@rollup/plugin-typescript'; import { externalsForPlugin } from '../configs/externals.mjs'; -import { packageBabelPreset } from '../configs/babel-presets.mjs'; +import { apiExtractor } from '../transforms/api-extractor.mjs'; export function packageTypescript() { return [ @@ -10,16 +9,36 @@ export function packageTypescript() { input: 'src/index.ts', output: [ { file: 'dist/index.cjs', format: 'cjs', sourcemap: false, exports: 'auto' }, + ], + external: externalsForPlugin, + plugins: [ + typescript({ + tsconfig: './tsconfig.json', + declaration: false, + declarationDir: undefined, + noEmit: false, + }), + terser({ + compress: { + reduce_funcs: false, // https://github.com/terser/terser/issues/1305 + }, + keep_classnames: true, + keep_fnames: true, + }), + ], + }, + { + input: 'src/index.ts', + output: [ { file: 'dist/index.mjs', format: 'esm', sourcemap: false, exports: 'auto' }, ], external: externalsForPlugin, plugins: [ - typescript({ tsconfig: './tsconfig.json' }), - babel({ - babelHelpers: 'bundled', - exclude: 'node_modules/**', - extensions: ['.js', '.ts'], - presets: packageBabelPreset, + typescript({ + tsconfig: './tsconfig.json', + declaration: true, + declarationDir: './dist/_types', + noEmit: false, }), terser({ compress: { @@ -28,6 +47,7 @@ export function packageTypescript() { keep_classnames: true, keep_fnames: true, }), + apiExtractor(), ], }, ]; diff --git a/rollup/transforms/api-extractor.mjs b/rollup/transforms/api-extractor.mjs new file mode 100644 index 000000000..79030eb9b --- /dev/null +++ b/rollup/transforms/api-extractor.mjs @@ -0,0 +1,22 @@ +import fs from 'fs/promises'; +import path from 'path'; +import { Extractor, ExtractorConfig } from '@microsoft/api-extractor'; + +export function apiExtractor() { + return { + name: 'typescript-declarations', + closeBundle: async function closeBundle() { + const extractorConfig = ExtractorConfig.loadFileAndPrepare('api-extractor.json'); + const extractorResult = Extractor.invoke(extractorConfig, {}); + + if (!extractorResult.succeeded) { + throw new Error( + `API Extractor completed with ${extractorResult.errorCount} errors` + + ` and ${extractorResult.warningCount} warnings`, + ); + } + + await fs.rm(path.join('dist', '_types'), { recursive: true, force: true }); + }, + }; +} diff --git a/sites/postcss-preset-env/package.json b/sites/postcss-preset-env/package.json index 0f18cc885..864119dcc 100644 --- a/sites/postcss-preset-env/package.json +++ b/sites/postcss-preset-env/package.json @@ -111,7 +111,6 @@ "typescript": "^5.3.3" }, "volta": { - "node": "18.13.0", - "npm": "9.4.0" + "node": "20.10.0" } }