Spaces:
Paused
Paused
Upload folder using huggingface_hub
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .gitattributes-36
- node_modules/.bin/acornDeleted-4
- node_modules/.bin/baseline-browser-mappingDeleted-2
- node_modules/.bin/browserslistDeleted-156
- node_modules/.bin/crc32Deleted-105
- node_modules/.bin/eslintDeleted-211
- node_modules/.bin/eslint-config-prettierDeleted-240
- node_modules/.bin/fxparserDeleted-97
- node_modules/.bin/jitiDeleted-16
- node_modules/.bin/js-yamlDeleted-117
- node_modules/.bin/jsescDeleted-148
- node_modules/.bin/json5Deleted-152
- node_modules/.bin/mimeDeleted-46
- node_modules/.bin/mswDeleted-35
- node_modules/.bin/nanoidDeleted-55
- node_modules/.bin/node-whichDeleted-52
- node_modules/.bin/nodemonDeleted-16
- node_modules/.bin/nodetouchDeleted-112
- node_modules/.bin/parserDeleted-15
- node_modules/.bin/pixelmatchDeleted-42
- node_modules/.bin/prebuild-installDeleted-78
- node_modules/.bin/prettierDeleted-80
- node_modules/.bin/qrcodeDeleted-159
- node_modules/.bin/rcDeleted-4
- node_modules/.bin/rolldownDeleted-2
- node_modules/.bin/rollupDeleted-1912
- node_modules/.bin/semverDeleted-195
- node_modules/.bin/specificityDeleted-14
- node_modules/.bin/terserDeleted-21
- node_modules/.bin/tldtsDeleted-21
- node_modules/.bin/tree-killDeleted-14
- node_modules/.bin/tscDeleted-2
- node_modules/.bin/tsserverDeleted-2
- node_modules/.bin/tsxDeleted
- node_modules/.bin/update-browserslist-dbDeleted-42
- node_modules/.bin/uuidDeleted-2
- node_modules/.bin/viteDeleted-79
- node_modules/.bin/vitestDeleted-2
- node_modules/.bin/why-is-node-runningDeleted-18
- node_modules/.package-lock.jsonDeleted
- node_modules/@asamuzakjp/css-color/LICENSEDeleted-21
- node_modules/@asamuzakjp/css-color/README.mdDeleted-316
- node_modules/@asamuzakjp/css-color/dist/esm/index.d.tsDeleted-20
- node_modules/@asamuzakjp/css-color/dist/esm/index.jsDeleted-29
- node_modules/@asamuzakjp/css-color/dist/esm/index.js.mapDeleted-1
- node_modules/@asamuzakjp/css-color/dist/esm/js/cache.d.tsDeleted-38
- node_modules/@asamuzakjp/css-color/dist/esm/js/cache.jsDeleted-90
- node_modules/@asamuzakjp/css-color/dist/esm/js/cache.js.mapDeleted-1
- node_modules/@asamuzakjp/css-color/dist/esm/js/color.d.tsDeleted-537
- node_modules/@asamuzakjp/css-color/dist/esm/js/color.jsDeleted-3534
24 unmodified lines25262728293031323334353637383940414243444546474849505152535455565758596061626324 unmodified lines*.eot binary*.pdf binary*.zip binaryclient/public/fonts/Poppins-Bold.ttf filter=lfs diff=lfs merge=lfs -textclient/public/fonts/Poppins-Italic.ttf filter=lfs diff=lfs merge=lfs -textclient/public/fonts/Poppins-Medium.ttf filter=lfs diff=lfs merge=lfs -textclient/public/fonts/Poppins-Regular.ttf filter=lfs diff=lfs merge=lfs -textclient/public/fonts/Poppins-SemiBold.ttf filter=lfs diff=lfs merge=lfs -textclient/public/icons/trek-loading-dark.gif filter=lfs diff=lfs merge=lfs -textclient/public/icons/trek-loading-light.gif filter=lfs diff=lfs merge=lfs -textdocs/TREK-Generated-by-MCP.pdf filter=lfs diff=lfs merge=lfs -textdocs/logo-trek-dark.gif filter=lfs diff=lfs merge=lfs -textdocs/logo-trek-light.gif filter=lfs diff=lfs merge=lfs -textdocs/screenshots/atlas.png filter=lfs diff=lfs merge=lfs -textdocs/screenshots/budget.png filter=lfs diff=lfs merge=lfs -textdocs/screenshots/dashboard.png filter=lfs diff=lfs merge=lfs -textdocs/screenshots/journey.png filter=lfs diff=lfs merge=lfs -textdocs/screenshots/trip-iceland.png filter=lfs diff=lfs merge=lfs -textdocs/screenshots/trip-planner.png filter=lfs diff=lfs merge=lfs -textdocs/screenshots/vacay.png filter=lfs diff=lfs merge=lfs -textnode_modules/@jimp/js-bmp/src/images/windows95.bmp filter=lfs diff=lfs merge=lfs -textnode_modules/@jimp/js-bmp/src/images/windows95.png filter=lfs diff=lfs merge=lfs -textnode_modules/@jimp/plugin-blit/src/__image_snapshots__/index-node-test-ts-blit-over-image-blit-alpha-1-snap.png filter=lfs diff=lfs merge=lfs -textnode_modules/@jimp/plugin-blit/src/images/blit-alpha.png filter=lfs diff=lfs merge=lfs -textnode_modules/@jimp/plugin-blur/src/__image_snapshots__/index-node-test-ts-has-alpha-image-with-alpha-1-snap.png filter=lfs diff=lfs merge=lfs -textnode_modules/@jimp/plugin-color/src/__image_snapshots__/convolution-node-test-ts-convolution-new-pixel-value-is-greater-than-255-1-snap.png filter=lfs diff=lfs merge=lfs -textnode_modules/@jimp/plugin-color/src/images/qr.jpg filter=lfs diff=lfs merge=lfs -textnode_modules/@jimp/plugin-print/dist/fonts/open-sans/open-sans-128-black/open-sans-128-black.png filter=lfs diff=lfs merge=lfs -textnode_modules/@jimp/plugin-print/dist/fonts/open-sans/open-sans-128-white/open-sans-128-white.png filter=lfs diff=lfs merge=lfs -textnode_modules/@jimp/plugin-print/fonts/open-sans/open-sans-128-black/open-sans-128-black.png filter=lfs diff=lfs merge=lfs -textnode_modules/@jimp/plugin-print/fonts/open-sans/open-sans-128-white/open-sans-128-white.png filter=lfs diff=lfs merge=lfs -textnode_modules/@jimp/plugin-threshold/src/__image_snapshots__/index-test-ts-src-index-test-ts-threshold-defines-default-threshold-for-lighter-backgrounds-1-snap.png filter=lfs diff=lfs merge=lfs -textnode_modules/@rolldown/binding-linux-x64-gnu/rolldown-binding.linux-x64-gnu.node filter=lfs diff=lfs merge=lfs -textnode_modules/@rolldown/binding-linux-x64-musl/rolldown-binding.linux-x64-musl.node filter=lfs diff=lfs merge=lfs -textnode_modules/@rollup/rollup-linux-x64-gnu/rollup.linux-x64-gnu.node filter=lfs diff=lfs merge=lfs -textnode_modules/@rollup/rollup-linux-x64-musl/rollup.linux-x64-musl.node filter=lfs diff=lfs merge=lfs -textnode_modules/@swc/core-linux-x64-gnu/swc.linux-x64-gnu.node filter=lfs diff=lfs merge=lfs -textnode_modules/@swc/core-linux-x64-musl/swc.linux-x64-musl.node filter=lfs diff=lfs merge=lfs -textnode_modules/@trivago/prettier-plugin-sort-imports/.yarn/install-state.gz filter=lfs diff=lfs merge=lfs -text24 unmodified lines25262724 unmodified lines*.eot binary*.pdf binary*.zip binary
1234#!/usr/bin/env node"use strict"
require("../dist/bin.js")12#!/usr/bin/env node"use strict";const{getCompatibleVersions:e}=require("./index.cjs"),a=process.argv.slice(2),s={};for(let e=0;e<a.length;e++){const r=a[e];r&&("-h"===r||"--help"===r?s.help=!0:"--include-downstream-browsers"===r?s["include-downstream-browsers"]=!0:"--list-all-compatible-versions"===r?s["list-all-compatible-versions"]=!0:"--include-kaios"===r?s["include-kaios"]=!0:"--suppress-warnings"===r?s["suppress-warnings"]=!0:r.startsWith("--target-year=")?s["target-year"]=r.substring(14):"--target-year"===r?s["target-year"]=a[++e]:r.startsWith("--widely-available-on-date=")?s["widely-available-on-date"]=r.substring(27):"--widely-available-on-date"===r?s["widely-available-on-date"]=a[++e]:r.startsWith("--override-last-updated=")?s["override-last-updated"]=r.substring(24):"--override-last-updated"===r?s["override-last-updated"]=a[++e]:(console.error(`Unknown argument: ${r}`),process.exit(1)))}s.help&&(console.log("\nGet Baseline Widely available browser versions or Baseline year browser versions.\n\nUsage: baseline-browser-mapping [options]\n\nOptions:\n --target-year Pass a year between 2015 and the current year to get browser versions compatible \n with all Newly Available features as of the end of the year specified.\n --widely-available-on-date Pass a date in the format 'YYYY-MM-DD' to get versions compatible with Widely \n available on the specified date.\n --include-downstream-browsers Whether to include browsers that use the same engines as a core Baseline browser.\n --include-kaios Whether to include KaiOS in downstream browsers. Requires --include-downstream-browsers.\n --list-all-compatible-versions Whether to include only the minimum compatible browser versions or all compatible versions.\n --suppress-warnings Supress potential warnings about data staleness when using a very recent feature cut off date.\n --override-last-updated Override the last updated date for the baseline data for debugging purposes.\n -h, --help Show help\n\nExamples:\n npx baseline-browser-mapping --target-year 2020\n npx baseline-browser-mapping --widely-available-on-date 2023-04-05\n npx baseline-browser-mapping --include-downstream-browsers\n npx baseline-browser-mapping --list-all-compatible-versions\n".trim()),process.exit(0)),console.log(e({targetYear:s["target-year"]?Number.parseInt(s["target-year"]):void 0,widelyAvailableOnDate:s["widely-available-on-date"],includeDownstreamBrowsers:s["include-downstream-browsers"],listAllCompatibleVersions:s["list-all-compatible-versions"],includeKaiOS:s["include-kaios"],suppressWarnings:s["suppress-warnings"],overrideLastUpdated:s["override-last-updated"]?Number.parseInt(s["override-last-updated"]):void 0}));123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156#!/usr/bin/env node
var fs = require('fs')var updateDb = require('update-browserslist-db')
var browserslist = require('./')var pkg = require('./package.json')
var args = process.argv.slice(2)
var USAGE = 'Usage:\n' + ' npx browserslist\n' + ' npx browserslist "QUERIES"\n' + ' npx browserslist --json "QUERIES"\n' + ' npx browserslist --config="path/to/browserlist/file"\n' + ' npx browserslist --coverage "QUERIES"\n' + ' npx browserslist --coverage=US "QUERIES"\n' + ' npx browserslist --coverage=US,RU,global "QUERIES"\n' + ' npx browserslist --env="environment name defined in config"\n' + ' npx browserslist --stats="path/to/browserlist/stats/file"\n' + ' npx browserslist --mobile-to-desktop\n' + ' npx browserslist --ignore-unknown-versions\n'
function isArg(arg) { return args.some(function (str) { return str === arg || str.indexOf(arg + '=') === 0 })}
function error(msg) { process.stderr.write('browserslist: ' + msg + '\n') process.exit(1)}
if (isArg('--help') || isArg('-h')) { process.stdout.write(pkg.description + '.\n\n' + USAGE + '\n')} else if (isArg('--version') || isArg('-v')) { process.stdout.write('browserslist ' + pkg.version + '\n')} else if (isArg('--update-db')) { /* c8 ignore next 8 */ process.stdout.write( 'The --update-db command is deprecated.\n' + 'Please use npx update-browserslist-db@latest instead.\n' ) process.stdout.write('Browserslist DB update will still be made.\n') updateDb(function (str) { process.stdout.write(str) })} else { var mode = 'browsers' var opts = {} var queries var areas
for (var i = 0; i < args.length; i++) { if (args[i][0] !== '-') { queries = args[i].replace(/^["']|["']$/g, '') continue }
var arg = args[i].split('=') var name = arg[0] var value = arg[1]
if (value) value = value.replace(/^["']|["']$/g, '')
if (name === '--config' || name === '-b') { opts.config = value } else if (name === '--env' || name === '-e') { opts.env = value } else if (name === '--stats' || name === '-s') { opts.stats = value } else if (name === '--coverage' || name === '-c') { if (mode !== 'json') mode = 'coverage' if (value) { areas = value.split(',') } else { areas = ['global'] } } else if (name === '--json') { mode = 'json' } else if (name === '--mobile-to-desktop') { /* c8 ignore next */ opts.mobileToDesktop = true } else if (name === '--ignore-unknown-versions') { /* c8 ignore next */ opts.ignoreUnknownVersions = true } else { error('Unknown arguments ' + args[i] + '.\n\n' + USAGE) } }
var browsers try { browsers = browserslist(queries, opts) } catch (e) { if (e.name === 'BrowserslistError') { error(e.message) } /* c8 ignore start */ else { throw e } /* c8 ignore end */ }
var coverage if (mode === 'browsers') { browsers.forEach(function (browser) { process.stdout.write(browser + '\n') }) } else if (areas) { coverage = areas.map(function (area) { var stats if (area !== 'global') { stats = area } else if (opts.stats) { stats = JSON.parse(fs.readFileSync(opts.stats)) } var result = browserslist.coverage(browsers, stats) var round = Math.round(result * 100) / 100.0
return [area, round] })
if (mode === 'coverage') { var prefix = 'These browsers account for ' process.stdout.write(prefix) coverage.forEach(function (data, index) { var area = data[0] var round = data[1] var end = 'globally' if (area && area !== 'global') { end = 'in the ' + area.toUpperCase() } else if (opts.stats) { end = 'in custom statistics' }
if (index !== 0) { process.stdout.write(prefix.replace(/./g, ' ')) }
process.stdout.write(round + '% of all users ' + end + '\n') }) } }
if (mode === 'json') { var data = { browsers: browsers } if (coverage) { data.coverage = coverage.reduce(function (object, j) { object[j[0]] = j[1] return object }, {}) } process.stdout.write(JSON.stringify(data, null, ' ') + '\n') }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105#!/usr/bin/env node/* crc32.js (C) 2014-present SheetJS -- http://sheetjs.com *//* eslint-env node *//* vim: set ts=2 ft=javascript: *//*jshint node:true */
var X/*:CRC32Module*/;try { X = require('../'); } catch(e) { X = require('crc-32'); }
function help()/*:number*/ {["usage: crc32 [options] [filename]","","Options:"," -h, --help output usage information"," -V, --version output the version number"," -S, --seed=<n> use integer seed as starting value (rolling CRC)"," -H, --hex-seed=<h> use hex seed as starting value (rolling CRC)"," -d, --signed print result with format `%d` (default)"," -u, --unsigned print result with format `%u`"," -x, --hex print result with format `%0.8x`"," -X, --HEX print result with format `%0.8X`"," -c, --crc32c use CRC32C (Castagnoli)"," -F, --format=<s> use specified printf format","","Set filename = '-' or pipe data into crc32 to read from stdin","Default output mode is signed (-d)",""].forEach(function(l) { console.log(l); }); return 0;}
function version()/*:number*/ { console.log(X.version); return 0; }
var fs = require('fs');try { require('exit-on-epipe'); } catch(e) {}
function die(msg/*:string*/, ec/*:?number*/)/*:void*/ { console.error(msg); process.exit(ec || 0); }
var args/*:Array<string>*/ = process.argv.slice(2);var filename/*:string*/ = "";var fmt/*:string*/ = "";var seed = 0, r = 10;
for(var i = 0; i < args.length; ++i) { var arg = args[i]; if(arg.charCodeAt(0) != 45) { if(filename === "") filename = arg; continue; } var m = arg.indexOf("=") == -1 ? arg : arg.substr(0, arg.indexOf("=")); switch(m) { case "-": filename = "-"; break;
case "--help": case "-h": process.exit(help()); break; case "--version": case "-V": process.exit(version()); break;
case "--crc32c": case "-c": try { X = require('../crc32c'); } catch(e) { X = require('crc-32/crc32c'); } break;
case "--signed": case "-d": fmt = "%d"; break; case "--unsigned": case "-u": fmt = "%u"; break; case "--hex": case "-x": fmt = "%0.8x"; break; case "--HEX": case "-X": fmt = "%0.8X"; break; case "--format": case "-F": try { require("printj"); fmt = ((m!=arg) ? arg.substr(m.length+1) : args[++i])||""; } catch(e) { console.error("The `crc-32` module removed the `printj` dependency for formatting"); console.error("Use the `crc32-cli` module instead:"); console.error(" $ npx crc32-cli [options] [filename]"); } break;
case "--hex-seed": case "-H": r = 16; /* falls through */ case "--seed": case "-S": seed=parseInt((m!=arg) ? arg.substr(m.length+1) : args[++i], r)||0; break;
default: die("crc32: unrecognized option `" + arg + "'", 22); }}
if(!process.stdin.isTTY) filename = filename || "-";if(filename.length===0) die("crc32: must specify a filename ('-' for stdin)",1);
var crc32 = seed;// $FlowIgnore -- Writable is callable but type sig disagreesvar writable = require('stream').Writable();writable._write = function(chunk, e, cb) { crc32 = X.buf(chunk, crc32); cb(); };writable._writev = function(chunks, cb) { chunks.forEach(function(c) { crc32 = X.buf(c.chunk, crc32);}); cb();};writable.on('finish', function() { if(fmt === "") console.log(crc32); else try { console.log(require("printj").sprintf(fmt, crc32)); } catch(e) { switch(fmt) { case "%d": console.log(crc32); break; case "%u": console.log(crc32 >>> 0); break; case "%0.8x": console.log((crc32 >>> 0).toString(16).padStart(8, "0").toLowerCase()); break; case "%0.8X": console.log((crc32 >>> 0).toString(16).padStart(8, "0").toUpperCase()); break; } }});
if(filename === "-") process.stdin.pipe(writable);else if(fs.existsSync(filename)) fs.createReadStream(filename).pipe(writable);else die("crc32: " + filename + ": No such file or directory", 2);123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211#!/usr/bin/env node
/** * @fileoverview Main CLI that is run via the eslint command. * @author Nicholas C. Zakas */
/* eslint no-console:off -- CLI */
"use strict";
const mod = require("node:module");
// to use V8's code cache to speed up instantiation timemod.enableCompileCache?.();
// must do this initialization *before* other requires in order to workif (process.argv.includes("--debug")) { require("debug").enable("eslint:*,-eslint:code-path,eslintrc:*");}
//------------------------------------------------------------------------------// Helpers//------------------------------------------------------------------------------
/** * Read data from stdin til the end. * * Note: See * - https://github.com/nodejs/node/blob/master/doc/api/process.md#processstdin * - https://github.com/nodejs/node/blob/master/doc/api/process.md#a-note-on-process-io * - https://lists.gnu.org/archive/html/bug-gnu-emacs/2016-01/msg00419.html * - https://github.com/nodejs/node/issues/7439 (historical) * * On Windows using `fs.readFileSync(STDIN_FILE_DESCRIPTOR, "utf8")` seems * to read 4096 bytes before blocking and never drains to read further data. * * The investigation on the Emacs thread indicates: * * > Emacs on MS-Windows uses pipes to communicate with subprocesses; a * > pipe on Windows has a 4K buffer. So as soon as Emacs writes more than * > 4096 bytes to the pipe, the pipe becomes full, and Emacs then waits for * > the subprocess to read its end of the pipe, at which time Emacs will * > write the rest of the stuff. * @returns {Promise<string>} The read text. */function readStdin() { return new Promise((resolve, reject) => { let content = ""; let chunk = "";
process.stdin .setEncoding("utf8") .on("readable", () => { while ((chunk = process.stdin.read()) !== null) { content += chunk; } }) .on("end", () => resolve(content)) .on("error", reject); });}
/** * Spawns an external command and propagates its exit status. * @param {string} command The command to run. * @param {string[]} args The command arguments. * @throws {Error} If the command cannot be spawned. * @returns {void} */function spawnExternalCommand(command, args) { const spawn = require("cross-spawn"); const result = spawn.sync(command, args, { encoding: "utf8", stdio: "inherit", });
if (result.error) { throw result.error; }
if (result.signal) { process.kill(process.pid, result.signal); return; }
process.exitCode = result.status ?? 0;}
/** * Get the error message of a given value. * @param {any} error The value to get. * @returns {string} The error message. */function getErrorMessage(error) { // Lazy loading because this is used only if an error happened. const util = require("node:util");
// Foolproof -- third-party module might throw non-object. if (typeof error !== "object" || error === null) { return String(error); }
// Use templates if `error.messageTemplate` is present. if (typeof error.messageTemplate === "string") { try { const template = require(`../messages/${error.messageTemplate}.js`);
return template(error.messageData || {}); } catch { // Ignore template error then fallback to use `error.stack`. } }
// Use the stacktrace if it's an error object. if (typeof error.stack === "string") { return error.stack; }
// Otherwise, dump the object. return util.format("%o", error);}
/** * Tracks error messages that are shown to the user so we only ever show the * same message once. * @type {Set<string>} */const displayedErrors = new Set();
/** * Tracks whether an unexpected error was caught * @type {boolean} */let hadFatalError = false;
/** * Catch and report unexpected error. * @param {any} error The thrown error object. * @returns {void} */function onFatalError(error) { process.exitCode = 2; hadFatalError = true;
const { version } = require("../package.json"); const message = `Oops! Something went wrong! :(
ESLint: ${version}
${getErrorMessage(error)}`;
if (!displayedErrors.has(message)) { console.error(message); displayedErrors.add(message); }}
//------------------------------------------------------------------------------// Execution//------------------------------------------------------------------------------
(async function main() { process.on("uncaughtException", onFatalError); process.on("unhandledRejection", onFatalError);
// Call the config initializer if `--init` is present. if (process.argv.includes("--init")) { // `eslint --init` has been moved to `@eslint/create-config` console.warn( "You can also run this command directly using 'npm init @eslint/config@latest'.", );
spawnExternalCommand("npm", ["init", "@eslint/config@latest"]); return; }
// start the MCP server if `--mcp` is present if (process.argv.includes("--mcp")) { console.warn( "You can also run this command directly using 'npx @eslint/mcp@latest'.", );
spawnExternalCommand("npx", ["@eslint/mcp@latest"]); return; }
// Otherwise, call the CLI. const cli = require("../lib/cli"); const exitCode = await cli.execute( process.argv, process.argv.includes("--stdin") ? await readStdin() : void 0, );
/* * If an uncaught exception or unhandled rejection was detected in the meantime, * keep the fatal exit code 2 that is already assigned to `process.exitCode`. * Without this condition, exit code 2 (unsuccessful execution) could be overwritten with * 1 (successful execution, lint problems found) or even 0 (successful execution, no lint problems found). * This ensures that unexpected errors that seemingly don't affect the success * of the execution will still cause a non-zero exit code, as it's a common * practice and the default behavior of Node.js to exit with non-zero * in case of an uncaught exception or unhandled rejection. * * Otherwise, assign the exit code returned from CLI. */ if (!hadFatalError) { process.exitCode = exitCode; }})().catch(onFatalError);123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240#!/usr/bin/env node
"use strict";
const validators = require("./validators");const config = require("..");const prettier = require("../prettier");
// Require locally installed eslint, for `npx eslint-config-prettier` support// with no local eslint-config-prettier installation.const localRequire = (request) => require( require.resolve(request, { paths: [process.cwd(), ...require.resolve.paths("eslint")], }) );
let experimentalApi = {};try { experimentalApi = localRequire("eslint/use-at-your-own-risk");} catch (_error) {}
const { ESLint, FlatESLint = experimentalApi.FlatESLint } = localRequire("eslint");
const SPECIAL_RULES_URL = "https://github.com/prettier/eslint-config-prettier#special-rules";
const PRETTIER_RULES_URL = "https://github.com/prettier/eslint-config-prettier#arrow-body-style-and-prefer-arrow-callback";
if (module === require.main) { const args = process.argv.slice(2);
if (args.length === 0) { console.error(help()); process.exit(1); }
const eslint = new ESLint(); const flatESLint = FlatESLint === undefined ? undefined : new FlatESLint();
Promise.all( args.map((file) => { switch (process.env.ESLINT_USE_FLAT_CONFIG) { case "true": { return flatESLint.calculateConfigForFile(file); } case "false": { return eslint.calculateConfigForFile(file); } default: { // This turns synchronous errors (such as `.calculateConfigForFile` not existing) // and turns them into promise rejections. return Promise.resolve() .then(() => flatESLint.calculateConfigForFile(file)) .catch(() => eslint.calculateConfigForFile(file)); } } }) ) .then((configs) => { const rules = configs.flatMap( ( // Initializing config and rules for files that aren't included in the flat config, // which is a very unlikely scenario, but should still be treated as a success { rules = {} } = {}, index ) => Object.entries(rules).map((entry) => [...entry, args[index]]) ); const result = processRules(rules); if (result.stderr) { console.error(result.stderr); } if (result.stdout) { console.error(result.stdout); } process.exit(result.code); }) .catch((error) => { console.error(error.message); process.exit(1); });}
function help() { return `Usage: npx eslint-config-prettier FILE...
Resolves an ESLint configuration for every given FILE and checks if theycontain rules that are unnecessary or conflict with Prettier. Example:
npx eslint-config-prettier index.js test/index.js other/file/to/check.js
Exit codes:
0: No automatically detectable problems found.1: General error.2: Conflicting rules found.
For more information, see:https://github.com/prettier/eslint-config-prettier#cli-helper-tool `.trim();}
function processRules(configRules) { const regularRules = filterRules(config.rules, (_, value) => value === "off"); const optionsRules = filterRules( config.rules, (ruleName, value) => value === 0 && ruleName in validators ); const specialRules = filterRules( config.rules, (ruleName, value) => value === 0 && !(ruleName in validators) );
const enabledRules = configRules .map(([ruleName, value, source]) => { const arrayValue = Array.isArray(value) ? value : [value]; const [level, ...options] = arrayValue; const isOff = level === "off" || level === 0; return isOff ? null : { ruleName, options, source }; }) .filter(Boolean);
const flaggedRules = enabledRules.filter( ({ ruleName }) => ruleName in config.rules );
const regularFlaggedRuleNames = filterRuleNames( flaggedRules, ({ ruleName }) => ruleName in regularRules ); const optionsFlaggedRuleNames = filterRuleNames( flaggedRules, ({ ruleName, ...rule }) => ruleName in optionsRules && !validators[ruleName](rule) ); const specialFlaggedRuleNames = filterRuleNames( flaggedRules, ({ ruleName }) => ruleName in specialRules ); const prettierFlaggedRuleNames = filterRuleNames( enabledRules, ({ ruleName, source }) => ruleName in prettier.rules && enabledRules.some( (rule) => rule.ruleName === "prettier/prettier" && rule.source === source ) );
const regularMessage = [ "The following rules are unnecessary or might conflict with Prettier:", "", printRuleNames(regularFlaggedRuleNames), ].join("\n");
const optionsMessage = [ "The following rules are enabled with config that might conflict with Prettier. See:", SPECIAL_RULES_URL, "", printRuleNames(optionsFlaggedRuleNames), ].join("\n");
const specialMessage = [ "The following rules are enabled but cannot be automatically checked. See:", SPECIAL_RULES_URL, "", printRuleNames(specialFlaggedRuleNames), ].join("\n");
const prettierMessage = [ "The following rules can cause issues when using eslint-plugin-prettier at the same time.", "Only enable them if you know what you are doing! See:", PRETTIER_RULES_URL, "", printRuleNames(prettierFlaggedRuleNames), ].join("\n");
if ( regularFlaggedRuleNames.length === 0 && optionsFlaggedRuleNames.length === 0 ) { const message = specialFlaggedRuleNames.length === 0 && prettierFlaggedRuleNames.length === 0 ? "No rules that are unnecessary or conflict with Prettier were found." : [ specialFlaggedRuleNames.length === 0 ? null : specialMessage, prettierFlaggedRuleNames.length === 0 ? null : prettierMessage, "Other than that, no rules that are unnecessary or conflict with Prettier were found.", ] .filter(Boolean) .join("\n\n");
return { stdout: message, code: 0, }; }
const message = [ regularFlaggedRuleNames.length === 0 ? null : regularMessage, optionsFlaggedRuleNames.length === 0 ? null : optionsMessage, specialFlaggedRuleNames.length === 0 ? null : specialMessage, prettierFlaggedRuleNames.length === 0 ? null : prettierMessage, ] .filter(Boolean) .join("\n\n");
return { stdout: message, code: 2, };}
function filterRules(rules, fn) { return Object.fromEntries( Object.entries(rules) .filter(([ruleName, value]) => fn(ruleName, value)) .map(([ruleName]) => [ruleName, true]) );}
function filterRuleNames(rules, fn) { return [ ...new Set(rules.filter((rule) => fn(rule)).map((rule) => rule.ruleName)), ];}
function printRuleNames(ruleNames) { return ruleNames .slice() .sort() .map((ruleName) => `- ${ruleName}`) .join("\n");}
exports.processRules = processRules;12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697#!/usr/bin/env node'use strict';/*eslint-disable no-console*/import fs from 'fs';import { resolve } from 'path';import {XMLParser, XMLValidator} from "../fxp.js";import ReadToEnd from './read.js';import cmdDetail from "./man.js"
console.warn("\x1b[33m%s\x1b[0m", "⚠️ Warning: The built-in CLI interface is now deprecated.");console.warn("Please install the dedicated CLI package instead:");console.warn(" npm install -g fxp-cli");
if (process.argv[2] === '--help' || process.argv[2] === '-h') { console.log(cmdDetail);} else if (process.argv[2] === '--version') { const packageJsonPath = resolve(process.cwd(), 'package.json'); const version = JSON.parse(fs.readFileSync(packageJsonPath).toString()).version; console.log(version);} else { const options = { removeNSPrefix: true, ignoreAttributes: false, parseTagValue: true, parseAttributeValue: true, }; let fileName = ''; let outputFileName; let validate = false; let validateOnly = false; for (let i = 2; i < process.argv.length; i++) { if (process.argv[i] === '-ns') { options.removeNSPrefix = false; } else if (process.argv[i] === '-a') { options.ignoreAttributes = true; } else if (process.argv[i] === '-c') { options.parseTagValue = false; options.parseAttributeValue = false; } else if (process.argv[i] === '-o') { outputFileName = process.argv[++i]; } else if (process.argv[i] === '-v') { validate = true; } else if (process.argv[i] === '-V') { validateOnly = true; } else { //filename fileName = process.argv[i]; } } const callback = function(xmlData) { let output = ''; if (validateOnly) { output = XMLValidator.validate(xmlData); process.exitCode = output === true ? 0 : 1; } else { const parser = new XMLParser(options); output = JSON.stringify(parser.parse(xmlData,validate), null, 4); } if (outputFileName) { writeToFile(outputFileName, output); } else { console.log(output); } };
try { if (!fileName) { ReadToEnd.readToEnd(process.stdin, function(err, data) { if (err) { throw err; } callback(data.toString()); }); } else { fs.readFile(fileName, function(err, data) { if (err) { throw err; } callback(data.toString()); }); } } catch (e) { console.log('Seems an invalid file or stream.' + e); }}
function writeToFile(fileName, data) { fs.writeFile(fileName, data, function(err) { if (err) { throw err; } console.log('JSON output has been written to ' + fileName); });}12345678910111213141516#!/usr/bin/env node
const { resolve } = require("node:path");
const script = process.argv.splice(2, 1)[0];
if (!script) { console.error("Usage: jiti <path> [...arguments]"); process.exit(1);}
const pwd = process.cwd();const jiti = require("..")(pwd);const resolved = (process.argv[1] = jiti.resolve(resolve(pwd, script)));jiti(resolved);123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117#!/usr/bin/env node
'use strict'
const fs = require('fs')const argparse = require('argparse')const yaml = require('..')
/// /////////////////////////////////////////////////////////////////////////////
const cli = new argparse.ArgumentParser({ prog: 'js-yaml', add_help: true})
cli.add_argument('-v', '--version', { action: 'version', version: require('../package.json').version})
cli.add_argument('-c', '--compact', { help: 'Display errors in compact mode', action: 'store_true'})
// deprecated (not needed after we removed output colors)// option suppressed, but not completely removed for compatibilitycli.add_argument('-j', '--to-json', { help: argparse.SUPPRESS, dest: 'json', action: 'store_true'})
cli.add_argument('-t', '--trace', { help: 'Show stack trace on error', action: 'store_true'})
cli.add_argument('file', { help: 'File to read, utf-8 encoded without BOM', nargs: '?', default: '-'})
/// /////////////////////////////////////////////////////////////////////////////
const options = cli.parse_args()
/// /////////////////////////////////////////////////////////////////////////////
function readFile (filename, encoding, callback) { if (options.file === '-') { // read from stdin
const chunks = []
process.stdin.on('data', function (chunk) { chunks.push(chunk) })
process.stdin.on('end', function () { return callback(null, Buffer.concat(chunks).toString(encoding)) }) } else { fs.readFile(filename, encoding, callback) }}
readFile(options.file, 'utf8', function (error, input) { let output let isYaml
if (error) { if (error.code === 'ENOENT') { console.error('File not found: ' + options.file) process.exit(2) }
console.error( (options.trace && error.stack) || error.message || String(error))
process.exit(1) }
try { output = JSON.parse(input) isYaml = false } catch (err) { if (err instanceof SyntaxError) { try { output = [] yaml.loadAll(input, function (doc) { output.push(doc) }, {}) isYaml = true
if (output.length === 0) output = null else if (output.length === 1) output = output[0] } catch (e) { if (options.trace && err.stack) console.error(e.stack) else console.error(e.toString(options.compact))
process.exit(1) } } else { console.error( (options.trace && err.stack) || err.message || String(err))
process.exit(1) } }
if (isYaml) console.log(JSON.stringify(output, null, ' ')) else console.log(yaml.dump(output))})123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148#!/usr/bin/env node(function() {
var fs = require('fs'); var stringEscape = require('../jsesc.js'); var strings = process.argv.splice(2); var stdin = process.stdin; var data; var timeout; var isObject = false; var options = {}; var log = console.log;
var main = function() { var option = strings[0];
if (/^(?:-h|--help|undefined)$/.test(option)) { log( 'jsesc v%s - https://mths.be/jsesc', stringEscape.version ); log([ '\nUsage:\n', '\tjsesc [string]', '\tjsesc [-s | --single-quotes] [string]', '\tjsesc [-d | --double-quotes] [string]', '\tjsesc [-w | --wrap] [string]', '\tjsesc [-e | --escape-everything] [string]', '\tjsesc [-t | --escape-etago] [string]', '\tjsesc [-6 | --es6] [string]', '\tjsesc [-l | --lowercase-hex] [string]', '\tjsesc [-j | --json] [string]', '\tjsesc [-o | --object] [stringified_object]', // `JSON.parse()` the argument '\tjsesc [-p | --pretty] [string]', // `compact: false` '\tjsesc [-v | --version]', '\tjsesc [-h | --help]', '\nExamples:\n', '\tjsesc \'f\xF6o \u2665 b\xE5r \uD834\uDF06 baz\'', '\tjsesc --json \'f\xF6o \u2665 b\xE5r \uD834\uDF06 baz\'', '\tjsesc --json --escape-everything \'f\xF6o \u2665 b\xE5r \uD834\uDF06 baz\'', '\tjsesc --double-quotes --wrap \'f\xF6o \u2665 b\xE5r \uD834\uDF06 baz\'', '\techo \'f\xF6o \u2665 b\xE5r \uD834\uDF06 baz\' | jsesc' ].join('\n')); return process.exit(1); }
if (/^(?:-v|--version)$/.test(option)) { log('v%s', stringEscape.version); return process.exit(1); }
strings.forEach(function(string) { // Process options if (/^(?:-s|--single-quotes)$/.test(string)) { options.quotes = 'single'; return; } if (/^(?:-d|--double-quotes)$/.test(string)) { options.quotes = 'double'; return; } if (/^(?:-w|--wrap)$/.test(string)) { options.wrap = true; return; } if (/^(?:-e|--escape-everything)$/.test(string)) { options.escapeEverything = true; return; } if (/^(?:-t|--escape-etago)$/.test(string)) { options.escapeEtago = true; return; } if (/^(?:-6|--es6)$/.test(string)) { options.es6 = true; return; } if (/^(?:-l|--lowercase-hex)$/.test(string)) { options.lowercaseHex = true; return; } if (/^(?:-j|--json)$/.test(string)) { options.json = true; return; } if (/^(?:-o|--object)$/.test(string)) { isObject = true; return; } if (/^(?:-p|--pretty)$/.test(string)) { isObject = true; options.compact = false; return; }
// Process string(s) var result; try { if (isObject) { string = JSON.parse(string); } result = stringEscape(string, options); log(result); } catch(error) { log(error.message + '\n'); log('Error: failed to escape.'); log('If you think this is a bug in jsesc, please report it:'); log('https://github.com/mathiasbynens/jsesc/issues/new'); log( '\nStack trace using jsesc@%s:\n', stringEscape.version ); log(error.stack); return process.exit(1); } }); // Return with exit status 0 outside of the `forEach` loop, in case // multiple strings were passed in. return process.exit(0);
};
if (stdin.isTTY) { // handle shell arguments main(); } else { // Either the script is called from within a non-TTY context, // or `stdin` content is being piped in. if (!process.stdout.isTTY) { // called from a non-TTY context timeout = setTimeout(function() { // if no piped data arrived after a while, handle shell arguments main(); }, 250); }
data = ''; stdin.on('data', function(chunk) { clearTimeout(timeout); data += chunk; }); stdin.on('end', function() { strings.push(data.trim()); main(); }); stdin.resume(); }
}());123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152#!/usr/bin/env node
const fs = require('fs')const path = require('path')const pkg = require('../package.json')const JSON5 = require('./')
const argv = parseArgs()
if (argv.version) { version()} else if (argv.help) { usage()} else { const inFilename = argv.defaults[0]
let readStream if (inFilename) { readStream = fs.createReadStream(inFilename) } else { readStream = process.stdin }
let json5 = '' readStream.on('data', data => { json5 += data })
readStream.on('end', () => { let space if (argv.space === 't' || argv.space === 'tab') { space = '\t' } else { space = Number(argv.space) }
let value try { value = JSON5.parse(json5) if (!argv.validate) { const json = JSON.stringify(value, null, space)
let writeStream
// --convert is for backward compatibility with v0.5.1. If // specified with <file> and not --out-file, then a file with // the same name but with a .json extension will be written. if (argv.convert && inFilename && !argv.outFile) { const parsedFilename = path.parse(inFilename) const outFilename = path.format( Object.assign( parsedFilename, {base: path.basename(parsedFilename.base, parsedFilename.ext) + '.json'} ) )
writeStream = fs.createWriteStream(outFilename) } else if (argv.outFile) { writeStream = fs.createWriteStream(argv.outFile) } else { writeStream = process.stdout }
writeStream.write(json) } } catch (err) { console.error(err.message) process.exit(1) } })}
function parseArgs () { let convert let space let validate let outFile let version let help const defaults = []
const args = process.argv.slice(2) for (let i = 0; i < args.length; i++) { const arg = args[i] switch (arg) { case '--convert': case '-c': convert = true break
case '--space': case '-s': space = args[++i] break
case '--validate': case '-v': validate = true break
case '--out-file': case '-o': outFile = args[++i] break
case '--version': case '-V': version = true break
case '--help': case '-h': help = true break
default: defaults.push(arg) break } }
return { convert, space, validate, outFile, version, help, defaults, }}
function version () { console.log(pkg.version)}
function usage () { console.log( ` Usage: json5 [options] <file>
If <file> is not provided, then STDIN is used.
Options:
-s, --space The number of spaces to indent or 't' for tabs -o, --out-file [file] Output to the specified file, otherwise STDOUT -v, --validate Validate JSON5 but do not output JSON -V, --version Output the version number -h, --help Output usage information` )}12345678910111213141516171819202122232425262728293031323334353637383940414243444546#!/usr/bin/env node
'use strict';
process.title = 'mime';let mime = require('.');let pkg = require('./package.json');let args = process.argv.splice(2);
if (args.includes('--version') || args.includes('-v') || args.includes('--v')) { console.log(pkg.version); process.exit(0);} else if (args.includes('--name') || args.includes('-n') || args.includes('--n')) { console.log(pkg.name); process.exit(0);} else if (args.includes('--help') || args.includes('-h') || args.includes('--h')) { console.log(pkg.name + ' - ' + pkg.description + '\n'); console.log(`Usage:
mime [flags] [path_or_extension]
Flags: --help, -h Show this message --version, -v Display the version --name, -n Print the name of the program
Note: the command will exit after it executes if a command is specified The path_or_extension is the path to the file or the extension of the file.
Examples: mime --help mime --version mime --name mime -v mime src/log.js mime new.py mime foo.sh `); process.exit(0);}
let file = args[0];let type = mime.getType(file);
process.stdout.write(type + '\n');
1234567891011121314151617181920212223242526272829303132333435#!/usr/bin/env nodeimport yargs from 'yargs'import { init } from './init.js'
// eslint-disable-next-line @typescript-eslint/no-unused-expressionsyargs(process.argv.slice(2)) .usage('$0 <cmd> [args]') .command( 'init', 'Initializes Mock Service Worker at the specified directory', (yargs) => { yargs .positional('publicDir', { type: 'string', description: 'Relative path to the public directory', demandOption: false, normalize: true, }) .option('save', { type: 'boolean', description: 'Save the worker directory in your package.json', }) .option('cwd', { type: 'string', description: 'Custom current worker directory', normalize: true, }) .example('msw init') .example('msw init ./public') .example('msw init ./static --save') }, init, ) .demandCommand() .help().argv12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455#!/usr/bin/env node
let { nanoid, customAlphabet } = require('..')
function print(msg) { process.stdout.write(msg + '\n')}
function error(msg) { process.stderr.write(msg + '\n') process.exit(1)}
if (process.argv.includes('--help') || process.argv.includes('-h')) { print(` Usage $ nanoid [options]
Options -s, --size Generated ID size -a, --alphabet Alphabet to use -h, --help Show this help
Examples $ nanoid --s 15 S9sBF77U6sDB8Yg
$ nanoid --size 10 --alphabet abc bcabababca`) process.exit()}
let alphabet, sizefor (let i = 2; i < process.argv.length; i++) { let arg = process.argv[i] if (arg === '--size' || arg === '-s') { size = Number(process.argv[i + 1]) i += 1 if (Number.isNaN(size) || size <= 0) { error('Size must be positive integer') } } else if (arg === '--alphabet' || arg === '-a') { alphabet = process.argv[i + 1] i += 1 } else { error('Unknown argument ' + arg) }}
if (alphabet) { let customNanoid = customAlphabet(alphabet, size) print(customNanoid())} else { print(nanoid(size))}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152#!/usr/bin/env nodevar which = require("../")if (process.argv.length < 3) usage()
function usage () { console.error('usage: which [-as] program ...') process.exit(1)}
var all = falsevar silent = falsevar dashdash = falsevar args = process.argv.slice(2).filter(function (arg) { if (dashdash || !/^-/.test(arg)) return true
if (arg === '--') { dashdash = true return false }
var flags = arg.substr(1).split('') for (var f = 0; f < flags.length; f++) { var flag = flags[f] switch (flag) { case 's': silent = true break case 'a': all = true break default: console.error('which: illegal option -- ' + flag) usage() } } return false})
process.exit(args.reduce(function (pv, current) { try { var f = which.sync(current, { all: all }) if (all) f = f.join('\n') if (!silent) console.log(f) return pv; } catch (e) { return 1; }}, 0))12345678910111213141516#!/usr/bin/env node
const cli = require('../lib/cli');const nodemon = require('../lib/');const options = cli.parse(process.argv);
nodemon(options);
const fs = require('fs');
// checks for available update and returns an instanceconst pkg = JSON.parse(fs.readFileSync(__dirname + '/../package.json'));
if (pkg.version.indexOf('0.0.0') !== 0 && options.noUpdateNotifier !== true) { require('simple-update-notifier')({ pkg });}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112#!/usr/bin/env nodeconst touch = require("../index.js")
const usage = code => { console[code ? 'error' : 'log']( 'usage:\n' + 'touch [-acfm] [-r file] [-t [[CC]YY]MMDDhhmm[.SS]] file ...' ) process.exit(code)}
const singleFlags = { a: 'atime', m: 'mtime', c: 'nocreate', f: 'force'}
const singleOpts = { r: 'ref', t: 'time'}
const files = []const args = process.argv.slice(2)const options = {}for (let i = 0; i < args.length; i++) { const arg = args[i] if (!arg.match(/^-/)) { files.push(arg) continue }
// expand shorthands if (arg.charAt(1) !== '-') { const expand = [] for (let f = 1; f < arg.length; f++) { const fc = arg.charAt(f) const sf = singleFlags[fc] const so = singleOpts[fc] if (sf) expand.push('--' + sf) else if (so) { const soslice = arg.slice(f + 1) const soval = soslice.charAt(0) === '=' ? soslice : '=' + soslice expand.push('--' + so + soval) f = arg.length } else if (arg !== '-' + fc) expand.push('-' + fc) } if (expand.length) { args.splice.apply(args, [i, 1].concat(expand)) i-- continue } }
const argsplit = arg.split('=') const key = argsplit.shift().replace(/^\-\-/, '') const val = argsplit.length ? argsplit.join('=') : null
switch (key) { case 'time': const timestr = val || args[++i] // [-t [[CC]YY]MMDDhhmm[.SS]] const parsedtime = timestr.match( /^(([0-9]{2})?([0-9]{2}))?([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})(\.([0-9]{2}))?$/ ) if (!parsedtime) { console.error('touch: out of range or illegal ' + 'time specification: ' + '[[CC]YY]MMDDhhmm[.SS]') process.exit(1) } else { const y = +parsedtime[1] const year = parsedtime[2] ? y : y <= 68 ? 2000 + y : 1900 + y
const MM = +parsedtime[4] - 1 const dd = +parsedtime[5] const hh = +parsedtime[6] const mm = +parsedtime[7] const ss = +parsedtime[8]
options.time = new Date(Date.UTC(year, MM, dd, hh, mm, ss)) } continue
case 'ref': options.ref = val || args[++i] continue
case 'mtime': case 'nocreate': case 'atime': case 'force': options[key] = true continue
default: console.error('touch: illegal option -- ' + arg) usage(1) }}
if (!files.length) usage()
process.exitCode = 0Promise.all(files.map(f => touch(f, options))) .catch(er => process.exitCode = 1)123456789101112131415#!/usr/bin/env node/* eslint-disable no-var, unicorn/prefer-node-protocol */
var parser = require("..");var fs = require("fs");
var filename = process.argv[2];if (!filename) { console.error("no filename specified");} else { var file = fs.readFileSync(filename, "utf8"); var ast = parser.parse(file);
console.log(JSON.stringify(ast, null, " "));}123456789101112131415161718192021222324252627282930313233343536373839404142#!/usr/bin/env node/* eslint-disable no-process-exit */
'use strict';
const PNG = require('pngjs').PNG;const fs = require('fs');const match = require('../.');
if (process.argv.length < 4) { console.log('Usage: pixelmatch image1.png image2.png [diff.png] [threshold] [includeAA]'); process.exit(64);}
const [,, img1Path, img2Path, diffPath, threshold, includeAA] = process.argv;const options = {};if (threshold !== undefined) options.threshold = +threshold;if (includeAA !== undefined) options.includeAA = includeAA !== 'false';
const img1 = PNG.sync.read(fs.readFileSync(img1Path));const img2 = PNG.sync.read(fs.readFileSync(img2Path));
const {width, height} = img1;
if (img2.width !== width || img2.height !== height) { console.log(`Image dimensions do not match: ${width}x${height} vs ${img2.width}x${img2.height}`); process.exit(65);}
const diff = diffPath ? new PNG({width, height}) : null;
console.time('matched in');const diffs = match(img1.data, img2.data, diff ? diff.data : null, width, height, options);console.timeEnd('matched in');
console.log(`different pixels: ${diffs}`);console.log(`error: ${Math.round(100 * 100 * diffs / (width * height)) / 100}%`);
if (diff) { fs.writeFileSync(diffPath, PNG.sync.write(diff));}process.exit(diffs ? 66 : 0);123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778#!/usr/bin/env node
const path = require('path')const fs = require('fs')const napi = require('napi-build-utils')
const pkg = require(path.resolve('package.json'))const rc = require('./rc')(pkg)const log = require('./log')(rc, process.env)const download = require('./download')const asset = require('./asset')const util = require('./util')
const prebuildClientVersion = require('./package.json').versionif (rc.version) { console.log(prebuildClientVersion) process.exit(0)}
if (rc.path) process.chdir(rc.path)
if (rc.runtime === 'electron' && rc.target[0] === '4' && rc.abi === '64') { log.error(`Electron version ${rc.target} found - skipping prebuild-install work due to known ABI issue`) log.error('More information about this issue can be found at https://github.com/lgeiger/node-abi/issues/54') process.exit(1)}
if (!fs.existsSync('package.json')) { log.error('setup', 'No package.json found. Aborting...') process.exit(1)}
if (rc.help) { console.error(fs.readFileSync(path.join(__dirname, 'help.txt'), 'utf-8')) process.exit(0)}
log.info('begin', 'Prebuild-install version', prebuildClientVersion)
const opts = Object.assign({}, rc, { pkg: pkg, log: log })
if (napi.isNapiRuntime(rc.runtime)) napi.logUnsupportedVersion(rc.target, log)
const origin = util.packageOrigin(process.env, pkg)
if (opts.force) { log.warn('install', 'prebuilt binaries enforced with --force!') log.warn('install', 'prebuilt binaries may be out of date!')} else if (origin && origin.length > 4 && origin.substr(0, 4) === 'git+') { log.info('install', 'installing from git repository, skipping download.') process.exit(1)} else if (opts.buildFromSource) { log.info('install', '--build-from-source specified, not attempting download.') process.exit(1)}
const startDownload = function (downloadUrl) { download(downloadUrl, opts, function (err) { if (err) { log.warn('install', err.message) return process.exit(1) } log.info('install', 'Successfully installed prebuilt binary!') })}
if (opts.token) { asset(opts, function (err, assetId) { if (err) { log.warn('install', err.message) return process.exit(1) }
startDownload(util.getAssetUrl(opts, assetId)) })} else { startDownload(util.getDownloadUrl(opts))}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980#!/usr/bin/env node"use strict";var __getOwnPropNames = Object.getOwnPropertyNames;var __commonJS = function(cb, mod) { return function __require() { return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; };};
// node_modules/semver-compare/index.jsvar require_semver_compare = __commonJS({ "node_modules/semver-compare/index.js": function(exports2, module2) { module2.exports = function cmp(a, b) { var pa = a.split("."); var pb = b.split("."); for (var i = 0; i < 3; i++) { var na = Number(pa[i]); var nb = Number(pb[i]); if (na > nb) return 1; if (nb > na) return -1; if (!isNaN(na) && isNaN(nb)) return 1; if (isNaN(na) && !isNaN(nb)) return -1; } return 0; }; }});
// node_modules/please-upgrade-node/index.jsvar require_please_upgrade_node = __commonJS({ "node_modules/please-upgrade-node/index.js": function(exports2, module2) { var semverCompare = require_semver_compare(); module2.exports = function pleaseUpgradeNode2(pkg, opts) { var opts = opts || {}; var requiredVersion = pkg.engines.node.replace(">=", ""); var currentVersion = process.version.replace("v", ""); if (semverCompare(currentVersion, requiredVersion) === -1) { if (opts.message) { console.error(opts.message(requiredVersion)); } else { console.error( pkg.name + " requires at least version " + requiredVersion + " of Node, please upgrade" ); } if (opts.hasOwnProperty("exitCode")) { process.exit(opts.exitCode); } else { process.exit(1); } } }; }});
// bin/prettier.cjsvar nodeModule = require("module");if (typeof nodeModule.enableCompileCache === "function") { nodeModule.enableCompileCache();}var pleaseUpgradeNode = require_please_upgrade_node();var packageJson = require("../package.json");pleaseUpgradeNode(packageJson);var dynamicImport = new Function("module", "return import(module)");var promise;var index = process.argv.indexOf("--experimental-cli");if (process.env.PRETTIER_EXPERIMENTAL_CLI || index !== -1) { if (index !== -1) { process.argv.splice(index, 1); } promise = dynamicImport("../internal/experimental-cli.mjs").then( function(cli) { return cli.__promise; } );} else { promise = dynamicImport("../internal/legacy-cli.mjs").then(function runCli(cli) { return cli.run(); });}module.exports.__promise = promise;123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159#!/usr/bin/env nodevar yargs = require('yargs')var qr = require('../lib')
function save (file, text, options) { qr.toFile(file, text, options, function (err, data) { if (err) { console.error('Error:', err.message) process.exit(1) }
console.log('saved qrcode to: ' + file + '\n') })}
function print (text, options) { options.type = 'terminal' qr.toString(text, options, function (err, text) { if (err) { console.error('Error:', err.message) process.exit(1) }
console.log(text) })}
function parseOptions (args) { return { version: args.qversion, errorCorrectionLevel: args.error, type: args.type, small: !!args.small, inverse: !!args.inverse, maskPattern: args.mask, margin: args.qzone, width: args.width, scale: args.scale, color: { light: args.lightcolor, dark: args.darkcolor } }}
function processInputs (text, opts) { if (!text.length) { yargs.showHelp() process.exit(1) }
if (opts.output) { save(opts.output, text, parseOptions(opts)) } else { print(text, parseOptions(opts)) }}
var argv = yargs .detectLocale(false) .usage('Usage: $0 [options] <input string>') .option('v', { alias: 'qversion', description: 'QR Code symbol version (1 - 40)', group: 'QR Code options:', type: 'number' }) .option('e', { alias: 'error', description: 'Error correction level', choices: ['L', 'M', 'Q', 'H'], group: 'QR Code options:' }) .option('m', { alias: 'mask', description: 'Mask pattern (0 - 7)', group: 'QR Code options:', type: 'number' }) .option('t', { alias: 'type', description: 'Output type', choices: ['png', 'svg', 'utf8'], implies: 'output', group: 'Renderer options:' }) .option('i', { alias: 'inverse', type: 'boolean', description: 'Invert colors', group: 'Renderer options:' }) .option('w', { alias: 'width', description: 'Image width (px)', conflicts: 'scale', group: 'Renderer options:', type: 'number' }) .option('s', { alias: 'scale', description: 'Scale factor', conflicts: 'width', group: 'Renderer options:', type: 'number' }) .option('q', { alias: 'qzone', description: 'Quiet zone size', group: 'Renderer options:', type: 'number' }) .option('l', { alias: 'lightcolor', description: 'Light RGBA hex color', group: 'Renderer options:' }) .option('d', { alias: 'darkcolor', description: 'Dark RGBA hex color', group: 'Renderer options:' }) .option('small', { type: 'boolean', description: 'Output smaller QR code to terminal', conflicts: 'type', group: 'Renderer options:' }) .option('o', { alias: 'output', description: 'Output file' }) .help('h') .alias('h', 'help') .version() .example('$0 "some text"', 'Draw in terminal window') .example('$0 -o out.png "some text"', 'Save as png image') .example('$0 -d F00 -o out.png "some text"', 'Use red as foreground color') .parserConfiguration({'parse-numbers': false}) .argv
if (process.stdin.isTTY) { processInputs(argv._.join(' '), argv)} else { var text = '' process.stdin.setEncoding('utf8') process.stdin.on('readable', function () { var chunk = process.stdin.read() if (chunk !== null) { text += chunk } })
process.stdin.on('end', function () { // this process can be run as a command outside of a tty so if there was no // data on stdin read from argv processInputs(text.length?text:argv._.join(' '), argv) })}1234#! /usr/bin/env nodevar rc = require('./index')
console.log(JSON.stringify(rc(process.argv[2]), false, 2))12#!/usr/bin/env nodeimport '../dist/cli.mjs';1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912#!/usr/bin/env node/* @license Rollup.js v4.62.0 Sat, 13 Jun 2026 08:30:18 GMT - commit 5e0066d92defee0097f10fb814e63f60b2a7b612
https://github.com/rollup/rollup
Released under the MIT License.*/'use strict';
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
const process$1 = require('node:process');const rollup = require('../shared/rollup.js');const require$$2 = require('util');const require$$0 = require('path');const require$$0$1 = require('fs');const parseAst_js = require('../shared/parseAst.js');const fseventsImporter = require('../shared/fsevents-importer.js');const promises = require('node:fs/promises');const path = require('node:path');const loadConfigFile_js = require('../shared/loadConfigFile.js');require('../native.js');require('node:perf_hooks');require('node:url');require('../getLogFilter.js');
const help = "rollup version 4.62.0\n=====================================\n\nUsage: rollup [options] <entry file>\n\nOptions:\n\n-c, --config <filename> Use this config file (if argument is used but value\n is unspecified, Rollup will try to load configuration files in\n the following order:\n rollup.config.mjs -> rollup.config.cjs -> rollup.config.js)\n-d, --dir <dirname> Directory for chunks (if absent, prints to stdout)\n-e, --external <ids> Comma-separate list of module IDs to exclude\n-f, --format <format> Type of output (amd, cjs, es, iife, umd, system)\n-g, --globals <pairs> Comma-separate list of `moduleID:Global` pairs\n-h, --help Show this help message\n-i, --input <filename> Input (alternative to <entry file>)\n-m, --sourcemap Generate sourcemap (`-m inline` for inline map)\n-n, --name <name> Name for UMD export\n-o, --file <output> Single output file (if absent, prints to stdout)\n-p, --plugin <plugin> Use the plugin specified (may be repeated)\n-v, --version Show version number\n-w, --watch Watch files in bundle and rebuild on changes\n--amd.autoId Generate the AMD ID based off the chunk name\n--amd.basePath <prefix> Path to prepend to auto generated AMD ID\n--amd.define <name> Function to use in place of `define`\n--amd.forceJsExtensionForImports Use `.js` extension in AMD imports\n--amd.id <id> ID for AMD module (default is anonymous)\n--assetFileNames <pattern> Name pattern for emitted assets\n--banner <text> Code to insert at top of bundle (outside wrapper)\n--chunkFileNames <pattern> Name pattern for emitted secondary chunks\n--compact Minify wrapper code\n--context <variable> Specify top-level `this` value\n--no-dynamicImportInCjs Write external dynamic CommonJS imports as require\n--entryFileNames <pattern> Name pattern for emitted entry chunks\n--environment <values> Settings passed to config file (see example)\n--no-esModule Do not add __esModule property\n--exports <mode> Specify export mode (auto, default, named, none)\n--extend Extend global variable defined by --name\n--no-externalImportAttributes Omit import attributes in \"es\" output\n--no-externalLiveBindings Do not generate code to support live bindings\n--failAfterWarnings Exit with an error if the build produced warnings\n--filterLogs <filter> Filter log messages\n--footer <text> Code to insert at end of bundle (outside wrapper)\n--forceExit Force exit the process when done\n--no-freeze Do not freeze namespace objects\n--generatedCode <preset> Which code features to use (es5/es2015)\n--generatedCode.arrowFunctions Use arrow functions in generated code\n--generatedCode.constBindings Use \"const\" in generated code\n--generatedCode.objectShorthand Use shorthand properties in generated code\n--no-generatedCode.reservedNamesAsProps Always quote reserved names as props\n--generatedCode.symbols Use symbols in generated code\n--hashCharacters <name> Use the specified character set for file hashes\n--no-hoistTransitiveImports Do not hoist transitive imports into entry chunks\n--importAttributesKey <name> Use the specified keyword for import attributes\n--no-indent Don't indent result\n--inlineDynamicImports Create single bundle when using dynamic imports\n--no-interop Do not include interop block\n--intro <text> Code to insert at top of bundle (inside wrapper)\n--logLevel <level> Which kind of logs to display\n--no-makeAbsoluteExternalsRelative Prevent normalization of external imports\n--maxParallelFileOps <value> How many files to read in parallel\n--minifyInternalExports Force or disable minification of internal exports\n--noConflict Generate a noConflict method for UMD globals\n--outro <text> Code to insert at end of bundle (inside wrapper)\n--perf Display performance timings\n--no-preserveEntrySignatures Avoid facade chunks for entry points\n--preserveModules Preserve module structure\n--preserveModulesRoot Put preserved modules under this path at root level\n--preserveSymlinks Do not follow symlinks when resolving files\n--no-reexportProtoFromExternal Ignore `__proto__` in star re-exports\n--no-sanitizeFileName Do not replace invalid characters in file names\n--shimMissingExports Create shim variables for missing exports\n--silent Don't print warnings\n--sourcemapBaseUrl <url> Emit absolute sourcemap URLs with given base\n--sourcemapDebugIds Emit unique debug ids in source and sourcemaps\n--sourcemapExcludeSources Do not include source code in source maps\n--sourcemapFile <file> Specify bundle position for source maps\n--sourcemapFileNames <pattern> Name pattern for emitted sourcemaps\n--stdin=ext Specify file extension used for stdin input\n--no-stdin Do not read \"-\" from stdin\n--no-strict Don't emit `\"use strict\";` in the generated modules\n--strictDeprecations Throw errors for deprecated features\n--no-systemNullSetters Do not replace empty SystemJS setters with `null`\n--no-treeshake Disable tree-shaking optimisations\n--no-treeshake.annotations Ignore pure call annotations\n--treeshake.correctVarValueBeforeDeclaration Deoptimize variables until declared\n--treeshake.manualPureFunctions <names> Manually declare functions as pure\n--no-treeshake.moduleSideEffects Assume modules have no side effects\n--no-treeshake.propertyReadSideEffects Ignore property access side effects\n--no-treeshake.tryCatchDeoptimization Do not turn off try-catch-tree-shaking\n--no-treeshake.unknownGlobalSideEffects Assume unknown globals do not throw\n--validate Validate output\n--waitForBundleInput Wait for bundle input files\n--watch.allowInputInsideOutputPath Whether the input path is allowed to be a\n subpath of the output path\n--watch.buildDelay <number> Throttle watch rebuilds\n--no-watch.clearScreen Do not clear the screen when rebuilding\n--watch.exclude <files> Exclude files from being watched\n--watch.include <files> Limit watching to specified files\n--watch.onBundleEnd <cmd> Shell command to run on `\"BUNDLE_END\"` event\n--watch.onBundleStart <cmd> Shell command to run on `\"BUNDLE_START\"` event\n--watch.onEnd <cmd> Shell command to run on `\"END\"` event\n--watch.onError <cmd> Shell command to run on `\"ERROR\"` event\n--watch.onStart <cmd> Shell command to run on `\"START\"` event\n--watch.skipWrite Do not write files to disk when watching\n\nExamples:\n\n# use settings in config file\nrollup -c\n\n# in config file, process.env.INCLUDE_DEPS === 'true'\n# and process.env.BUILD === 'production'\nrollup -c --environment INCLUDE_DEPS,BUILD:production\n\n# create CommonJS bundle.js from src/main.js\nrollup --format=cjs --file=bundle.js -- src/main.js\n\n# create self-executing IIFE using `window.jQuery`\n# and `window._` as external globals\nrollup -f iife --globals jquery:jQuery,lodash:_ \\\n -i src/app.js -o build/app.js -m build/app.js.map\n\nNotes:\n\n* When piping to stdout, only inline sourcemaps are permitted\n\nFor more information visit https://rollupjs.org\n";
/** * @license * Copyright (c) 2016, Contributors * SPDX-License-Identifier: ISC */function camelCase(str) { // Handle the case where an argument is provided as camel case, e.g., fooBar. // by ensuring that the string isn't already mixed case: const isCamelCase = str !== str.toLowerCase() && str !== str.toUpperCase(); if (!isCamelCase) { str = str.toLowerCase(); } if (str.indexOf('-') === -1 && str.indexOf('_') === -1) { return str; } else { let camelcase = ''; let nextChrUpper = false; const leadingHyphens = str.match(/^-+/); for (let i = leadingHyphens ? leadingHyphens[0].length : 0; i < str.length; i++) { let chr = str.charAt(i); if (nextChrUpper) { nextChrUpper = false; chr = chr.toUpperCase(); } if (i !== 0 && (chr === '-' || chr === '_')) { nextChrUpper = true; } else if (chr !== '-' && chr !== '_') { camelcase += chr; } } return camelcase; }}function decamelize(str, joinString) { const lowercase = str.toLowerCase(); joinString = joinString || '-'; let notCamelcase = ''; for (let i = 0; i < str.length; i++) { const chrLower = lowercase.charAt(i); const chrString = str.charAt(i); if (chrLower !== chrString && i > 0) { notCamelcase += `${joinString}${lowercase.charAt(i)}`; } else { notCamelcase += chrString; } } return notCamelcase;}function looksLikeNumber(x) { if (x === null || x === undefined) return false; // if loaded from config, may already be a number. if (typeof x === 'number') return true; // hexadecimal. if (/^0x[0-9a-f]+$/i.test(x)) return true; // don't treat 0123 as a number; as it drops the leading '0'. if (/^0[^.]/.test(x)) return false; return /^[-]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x);}
/** * @license * Copyright (c) 2016, Contributors * SPDX-License-Identifier: ISC */// take an un-split argv string and tokenize it.function tokenizeArgString(argString) { if (Array.isArray(argString)) { return argString.map(e => typeof e !== 'string' ? e + '' : e); } argString = argString.trim(); let i = 0; let prevC = null; let c = null; let opening = null; const args = []; for (let ii = 0; ii < argString.length; ii++) { prevC = c; c = argString.charAt(ii); // split on spaces unless we're in quotes. if (c === ' ' && !opening) { if (!(prevC === ' ')) { i++; } continue; } // don't split the string if we're in matching // opening or closing single and double quotes. if (c === opening) { opening = null; } else if ((c === "'" || c === '"') && !opening) { opening = c; } if (!args[i]) args[i] = ''; args[i] += c; } return args;}
/** * @license * Copyright (c) 2016, Contributors * SPDX-License-Identifier: ISC */var DefaultValuesForTypeKey;(function (DefaultValuesForTypeKey) { DefaultValuesForTypeKey["BOOLEAN"] = "boolean"; DefaultValuesForTypeKey["STRING"] = "string"; DefaultValuesForTypeKey["NUMBER"] = "number"; DefaultValuesForTypeKey["ARRAY"] = "array";})(DefaultValuesForTypeKey || (DefaultValuesForTypeKey = {}));
/** * @license * Copyright (c) 2016, Contributors * SPDX-License-Identifier: ISC */let mixin;class YargsParser { constructor(_mixin) { mixin = _mixin; } parse(argsInput, options) { const opts = Object.assign({ alias: undefined, array: undefined, boolean: undefined, config: undefined, configObjects: undefined, configuration: undefined, coerce: undefined, count: undefined, default: undefined, envPrefix: undefined, narg: undefined, normalize: undefined, string: undefined, number: undefined, __: undefined, key: undefined }, options); // allow a string argument to be passed in rather // than an argv array. const args = tokenizeArgString(argsInput); // tokenizeArgString adds extra quotes to args if argsInput is a string // only strip those extra quotes in processValue if argsInput is a string const inputIsString = typeof argsInput === 'string'; // aliases might have transitive relationships, normalize this. const aliases = combineAliases(Object.assign(Object.create(null), opts.alias)); const configuration = Object.assign({ 'boolean-negation': true, 'camel-case-expansion': true, 'combine-arrays': false, 'dot-notation': true, 'duplicate-arguments-array': true, 'flatten-duplicate-arrays': true, 'greedy-arrays': true, 'halt-at-non-option': false, 'nargs-eats-options': false, 'negation-prefix': 'no-', 'parse-numbers': true, 'parse-positional-numbers': true, 'populate--': false, 'set-placeholder-key': false, 'short-option-groups': true, 'strip-aliased': false, 'strip-dashed': false, 'unknown-options-as-args': false }, opts.configuration); const defaults = Object.assign(Object.create(null), opts.default); const configObjects = opts.configObjects || []; const envPrefix = opts.envPrefix; const notFlagsOption = configuration['populate--']; const notFlagsArgv = notFlagsOption ? '--' : '_'; const newAliases = Object.create(null); const defaulted = Object.create(null); // allow a i18n handler to be passed in, default to a fake one (util.format). const __ = opts.__ || mixin.format; const flags = { aliases: Object.create(null), arrays: Object.create(null), bools: Object.create(null), strings: Object.create(null), numbers: Object.create(null), counts: Object.create(null), normalize: Object.create(null), configs: Object.create(null), nargs: Object.create(null), coercions: Object.create(null), keys: [] }; const negative = /^-([0-9]+(\.[0-9]+)?|\.[0-9]+)$/; const negatedBoolean = new RegExp('^--' + configuration['negation-prefix'] + '(.+)'); [].concat(opts.array || []).filter(Boolean).forEach(function (opt) { const key = typeof opt === 'object' ? opt.key : opt; // assign to flags[bools|strings|numbers] const assignment = Object.keys(opt).map(function (key) { const arrayFlagKeys = { boolean: 'bools', string: 'strings', number: 'numbers' }; return arrayFlagKeys[key]; }).filter(Boolean).pop(); // assign key to be coerced if (assignment) { flags[assignment][key] = true; } flags.arrays[key] = true; flags.keys.push(key); }); [].concat(opts.boolean || []).filter(Boolean).forEach(function (key) { flags.bools[key] = true; flags.keys.push(key); }); [].concat(opts.string || []).filter(Boolean).forEach(function (key) { flags.strings[key] = true; flags.keys.push(key); }); [].concat(opts.number || []).filter(Boolean).forEach(function (key) { flags.numbers[key] = true; flags.keys.push(key); }); [].concat(opts.count || []).filter(Boolean).forEach(function (key) { flags.counts[key] = true; flags.keys.push(key); }); [].concat(opts.normalize || []).filter(Boolean).forEach(function (key) { flags.normalize[key] = true; flags.keys.push(key); }); if (typeof opts.narg === 'object') { Object.entries(opts.narg).forEach(([key, value]) => { if (typeof value === 'number') { flags.nargs[key] = value; flags.keys.push(key); } }); } if (typeof opts.coerce === 'object') { Object.entries(opts.coerce).forEach(([key, value]) => { if (typeof value === 'function') { flags.coercions[key] = value; flags.keys.push(key); } }); } if (typeof opts.config !== 'undefined') { if (Array.isArray(opts.config) || typeof opts.config === 'string') { [].concat(opts.config).filter(Boolean).forEach(function (key) { flags.configs[key] = true; }); } else if (typeof opts.config === 'object') { Object.entries(opts.config).forEach(([key, value]) => { if (typeof value === 'boolean' || typeof value === 'function') { flags.configs[key] = value; } }); } } // create a lookup table that takes into account all // combinations of aliases: {f: ['foo'], foo: ['f']} extendAliases(opts.key, aliases, opts.default, flags.arrays); // apply default values to all aliases. Object.keys(defaults).forEach(function (key) { (flags.aliases[key] || []).forEach(function (alias) { defaults[alias] = defaults[key]; }); }); let error = null; checkConfiguration(); let notFlags = []; const argv = Object.assign(Object.create(null), { _: [] }); // TODO(bcoe): for the first pass at removing object prototype we didn't // remove all prototypes from objects returned by this API, we might want // to gradually move towards doing so. const argvReturn = {}; for (let i = 0; i < args.length; i++) { const arg = args[i]; const truncatedArg = arg.replace(/^-{3,}/, '---'); let broken; let key; let letters; let m; let next; let value; // any unknown option (except for end-of-options, "--") if (arg !== '--' && /^-/.test(arg) && isUnknownOptionAsArg(arg)) { pushPositional(arg); // ---, ---=, ----, etc, } else if (truncatedArg.match(/^---+(=|$)/)) { // options without key name are invalid. pushPositional(arg); continue; // -- separated by = } else if (arg.match(/^--.+=/) || (!configuration['short-option-groups'] && arg.match(/^-.+=/))) { // Using [\s\S] instead of . because js doesn't support the // 'dotall' regex modifier. See: // http://stackoverflow.com/a/1068308/13216 m = arg.match(/^--?([^=]+)=([\s\S]*)$/); // arrays format = '--f=a b c' if (m !== null && Array.isArray(m) && m.length >= 3) { if (checkAllAliases(m[1], flags.arrays)) { i = eatArray(i, m[1], args, m[2]); } else if (checkAllAliases(m[1], flags.nargs) !== false) { // nargs format = '--f=monkey washing cat' i = eatNargs(i, m[1], args, m[2]); } else { setArg(m[1], m[2], true); } } } else if (arg.match(negatedBoolean) && configuration['boolean-negation']) { m = arg.match(negatedBoolean); if (m !== null && Array.isArray(m) && m.length >= 2) { key = m[1]; setArg(key, checkAllAliases(key, flags.arrays) ? [false] : false); } // -- separated by space. } else if (arg.match(/^--.+/) || (!configuration['short-option-groups'] && arg.match(/^-[^-]+/))) { m = arg.match(/^--?(.+)/); if (m !== null && Array.isArray(m) && m.length >= 2) { key = m[1]; if (checkAllAliases(key, flags.arrays)) { // array format = '--foo a b c' i = eatArray(i, key, args); } else if (checkAllAliases(key, flags.nargs) !== false) { // nargs format = '--foo a b c' // should be truthy even if: flags.nargs[key] === 0 i = eatNargs(i, key, args); } else { next = args[i + 1]; if (next !== undefined && (!next.match(/^-/) || next.match(negative)) && !checkAllAliases(key, flags.bools) && !checkAllAliases(key, flags.counts)) { setArg(key, next); i++; } else if (/^(true|false)$/.test(next)) { setArg(key, next); i++; } else { setArg(key, defaultValue(key)); } } } // dot-notation flag separated by '='. } else if (arg.match(/^-.\..+=/)) { m = arg.match(/^-([^=]+)=([\s\S]*)$/); if (m !== null && Array.isArray(m) && m.length >= 3) { setArg(m[1], m[2]); } // dot-notation flag separated by space. } else if (arg.match(/^-.\..+/) && !arg.match(negative)) { next = args[i + 1]; m = arg.match(/^-(.\..+)/); if (m !== null && Array.isArray(m) && m.length >= 2) { key = m[1]; if (next !== undefined && !next.match(/^-/) && !checkAllAliases(key, flags.bools) && !checkAllAliases(key, flags.counts)) { setArg(key, next); i++; } else { setArg(key, defaultValue(key)); } } } else if (arg.match(/^-[^-]+/) && !arg.match(negative)) { letters = arg.slice(1, -1).split(''); broken = false; for (let j = 0; j < letters.length; j++) { next = arg.slice(j + 2); if (letters[j + 1] && letters[j + 1] === '=') { value = arg.slice(j + 3); key = letters[j]; if (checkAllAliases(key, flags.arrays)) { // array format = '-f=a b c' i = eatArray(i, key, args, value); } else if (checkAllAliases(key, flags.nargs) !== false) { // nargs format = '-f=monkey washing cat' i = eatNargs(i, key, args, value); } else { setArg(key, value); } broken = true; break; } if (next === '-') { setArg(letters[j], next); continue; } // current letter is an alphabetic character and next value is a number if (/[A-Za-z]/.test(letters[j]) && /^-?\d+(\.\d*)?(e-?\d+)?$/.test(next) && checkAllAliases(next, flags.bools) === false) { setArg(letters[j], next); broken = true; break; } if (letters[j + 1] && letters[j + 1].match(/\W/)) { setArg(letters[j], next); broken = true; break; } else { setArg(letters[j], defaultValue(letters[j])); } } key = arg.slice(-1)[0]; if (!broken && key !== '-') { if (checkAllAliases(key, flags.arrays)) { // array format = '-f a b c' i = eatArray(i, key, args); } else if (checkAllAliases(key, flags.nargs) !== false) { // nargs format = '-f a b c' // should be truthy even if: flags.nargs[key] === 0 i = eatNargs(i, key, args); } else { next = args[i + 1]; if (next !== undefined && (!/^(-|--)[^-]/.test(next) || next.match(negative)) && !checkAllAliases(key, flags.bools) && !checkAllAliases(key, flags.counts)) { setArg(key, next); i++; } else if (/^(true|false)$/.test(next)) { setArg(key, next); i++; } else { setArg(key, defaultValue(key)); } } } } else if (arg.match(/^-[0-9]$/) && arg.match(negative) && checkAllAliases(arg.slice(1), flags.bools)) { // single-digit boolean alias, e.g: xargs -0 key = arg.slice(1); setArg(key, defaultValue(key)); } else if (arg === '--') { notFlags = args.slice(i + 1); break; } else if (configuration['halt-at-non-option']) { notFlags = args.slice(i); break; } else { pushPositional(arg); } } // order of precedence: // 1. command line arg // 2. value from env var // 3. value from config file // 4. value from config objects // 5. configured default value applyEnvVars(argv, true); // special case: check env vars that point to config file applyEnvVars(argv, false); setConfig(argv); setConfigObjects(); applyDefaultsAndAliases(argv, flags.aliases, defaults, true); applyCoercions(argv); if (configuration['set-placeholder-key']) setPlaceholderKeys(argv); // for any counts either not in args or without an explicit default, set to 0 Object.keys(flags.counts).forEach(function (key) { if (!hasKey(argv, key.split('.'))) setArg(key, 0); }); // '--' defaults to undefined. if (notFlagsOption && notFlags.length) argv[notFlagsArgv] = []; notFlags.forEach(function (key) { argv[notFlagsArgv].push(key); }); if (configuration['camel-case-expansion'] && configuration['strip-dashed']) { Object.keys(argv).filter(key => key !== '--' && key.includes('-')).forEach(key => { delete argv[key]; }); } if (configuration['strip-aliased']) { [].concat(...Object.keys(aliases).map(k => aliases[k])).forEach(alias => { if (configuration['camel-case-expansion'] && alias.includes('-')) { delete argv[alias.split('.').map(prop => camelCase(prop)).join('.')]; } delete argv[alias]; }); } // Push argument into positional array, applying numeric coercion: function pushPositional(arg) { const maybeCoercedNumber = maybeCoerceNumber('_', arg); if (typeof maybeCoercedNumber === 'string' || typeof maybeCoercedNumber === 'number') { argv._.push(maybeCoercedNumber); } } // how many arguments should we consume, based // on the nargs option? function eatNargs(i, key, args, argAfterEqualSign) { let ii; let toEat = checkAllAliases(key, flags.nargs); // NaN has a special meaning for the array type, indicating that one or // more values are expected. toEat = typeof toEat !== 'number' || isNaN(toEat) ? 1 : toEat; if (toEat === 0) { if (!isUndefined(argAfterEqualSign)) { error = Error(__('Argument unexpected for: %s', key)); } setArg(key, defaultValue(key)); return i; } let available = isUndefined(argAfterEqualSign) ? 0 : 1; if (configuration['nargs-eats-options']) { // classic behavior, yargs eats positional and dash arguments. if (args.length - (i + 1) + available < toEat) { error = Error(__('Not enough arguments following: %s', key)); } available = toEat; } else { // nargs will not consume flag arguments, e.g., -abc, --foo, // and terminates when one is observed. for (ii = i + 1; ii < args.length; ii++) { if (!args[ii].match(/^-[^0-9]/) || args[ii].match(negative) || isUnknownOptionAsArg(args[ii])) available++; else break; } if (available < toEat) error = Error(__('Not enough arguments following: %s', key)); } let consumed = Math.min(available, toEat); if (!isUndefined(argAfterEqualSign) && consumed > 0) { setArg(key, argAfterEqualSign); consumed--; } for (ii = i + 1; ii < (consumed + i + 1); ii++) { setArg(key, args[ii]); } return (i + consumed); } // if an option is an array, eat all non-hyphenated arguments // following it... YUM! // e.g., --foo apple banana cat becomes ["apple", "banana", "cat"] function eatArray(i, key, args, argAfterEqualSign) { let argsToSet = []; let next = argAfterEqualSign || args[i + 1]; // If both array and nargs are configured, enforce the nargs count: const nargsCount = checkAllAliases(key, flags.nargs); if (checkAllAliases(key, flags.bools) && !(/^(true|false)$/.test(next))) { argsToSet.push(true); } else if (isUndefined(next) || (isUndefined(argAfterEqualSign) && /^-/.test(next) && !negative.test(next) && !isUnknownOptionAsArg(next))) { // for keys without value ==> argsToSet remains an empty [] // set user default value, if available if (defaults[key] !== undefined) { const defVal = defaults[key]; argsToSet = Array.isArray(defVal) ? defVal : [defVal]; } } else { // value in --option=value is eaten as is if (!isUndefined(argAfterEqualSign)) { argsToSet.push(processValue(key, argAfterEqualSign, true)); } for (let ii = i + 1; ii < args.length; ii++) { if ((!configuration['greedy-arrays'] && argsToSet.length > 0) || (nargsCount && typeof nargsCount === 'number' && argsToSet.length >= nargsCount)) break; next = args[ii]; if (/^-/.test(next) && !negative.test(next) && !isUnknownOptionAsArg(next)) break; i = ii; argsToSet.push(processValue(key, next, inputIsString)); } } // If both array and nargs are configured, create an error if less than // nargs positionals were found. NaN has special meaning, indicating // that at least one value is required (more are okay). if (typeof nargsCount === 'number' && ((nargsCount && argsToSet.length < nargsCount) || (isNaN(nargsCount) && argsToSet.length === 0))) { error = Error(__('Not enough arguments following: %s', key)); } setArg(key, argsToSet); return i; } function setArg(key, val, shouldStripQuotes = inputIsString) { if (/-/.test(key) && configuration['camel-case-expansion']) { const alias = key.split('.').map(function (prop) { return camelCase(prop); }).join('.'); addNewAlias(key, alias); } const value = processValue(key, val, shouldStripQuotes); const splitKey = key.split('.'); setKey(argv, splitKey, value); // handle populating aliases of the full key if (flags.aliases[key]) { flags.aliases[key].forEach(function (x) { const keyProperties = x.split('.'); setKey(argv, keyProperties, value); }); } // handle populating aliases of the first element of the dot-notation key if (splitKey.length > 1 && configuration['dot-notation']) { (flags.aliases[splitKey[0]] || []).forEach(function (x) { let keyProperties = x.split('.'); // expand alias with nested objects in key const a = [].concat(splitKey); a.shift(); // nuke the old key. keyProperties = keyProperties.concat(a); // populate alias only if is not already an alias of the full key // (already populated above) if (!(flags.aliases[key] || []).includes(keyProperties.join('.'))) { setKey(argv, keyProperties, value); } }); } // Set normalize getter and setter when key is in 'normalize' but isn't an array if (checkAllAliases(key, flags.normalize) && !checkAllAliases(key, flags.arrays)) { const keys = [key].concat(flags.aliases[key] || []); keys.forEach(function (key) { Object.defineProperty(argvReturn, key, { enumerable: true, get() { return val; }, set(value) { val = typeof value === 'string' ? mixin.normalize(value) : value; } }); }); } } function addNewAlias(key, alias) { if (!(flags.aliases[key] && flags.aliases[key].length)) { flags.aliases[key] = [alias]; newAliases[alias] = true; } if (!(flags.aliases[alias] && flags.aliases[alias].length)) { addNewAlias(alias, key); } } function processValue(key, val, shouldStripQuotes) { // strings may be quoted, clean this up as we assign values. if (shouldStripQuotes) { val = stripQuotes(val); } // handle parsing boolean arguments --foo=true --bar false. if (checkAllAliases(key, flags.bools) || checkAllAliases(key, flags.counts)) { if (typeof val === 'string') val = val === 'true'; } let value = Array.isArray(val) ? val.map(function (v) { return maybeCoerceNumber(key, v); }) : maybeCoerceNumber(key, val); // increment a count given as arg (either no value or value parsed as boolean) if (checkAllAliases(key, flags.counts) && (isUndefined(value) || typeof value === 'boolean')) { value = increment(); } // Set normalized value when key is in 'normalize' and in 'arrays' if (checkAllAliases(key, flags.normalize) && checkAllAliases(key, flags.arrays)) { if (Array.isArray(val)) value = val.map((val) => { return mixin.normalize(val); }); else value = mixin.normalize(val); } return value; } function maybeCoerceNumber(key, value) { if (!configuration['parse-positional-numbers'] && key === '_') return value; if (!checkAllAliases(key, flags.strings) && !checkAllAliases(key, flags.bools) && !Array.isArray(value)) { const shouldCoerceNumber = looksLikeNumber(value) && configuration['parse-numbers'] && (Number.isSafeInteger(Math.floor(parseFloat(`${value}`)))); if (shouldCoerceNumber || (!isUndefined(value) && checkAllAliases(key, flags.numbers))) { value = Number(value); } } return value; } // set args from config.json file, this should be // applied last so that defaults can be applied. function setConfig(argv) { const configLookup = Object.create(null); // expand defaults/aliases, in-case any happen to reference // the config.json file. applyDefaultsAndAliases(configLookup, flags.aliases, defaults); Object.keys(flags.configs).forEach(function (configKey) { const configPath = argv[configKey] || configLookup[configKey]; if (configPath) { try { let config = null; const resolvedConfigPath = mixin.resolve(mixin.cwd(), configPath); const resolveConfig = flags.configs[configKey]; if (typeof resolveConfig === 'function') { try { config = resolveConfig(resolvedConfigPath); } catch (e) { config = e; } if (config instanceof Error) { error = config; return; } } else { config = mixin.require(resolvedConfigPath); } setConfigObject(config); } catch (ex) { // Deno will receive a PermissionDenied error if an attempt is // made to load config without the --allow-read flag: if (ex.name === 'PermissionDenied') error = ex; else if (argv[configKey]) error = Error(__('Invalid JSON config file: %s', configPath)); } } }); } // set args from config object. // it recursively checks nested objects. function setConfigObject(config, prev) { Object.keys(config).forEach(function (key) { const value = config[key]; const fullKey = prev ? prev + '.' + key : key; // if the value is an inner object and we have dot-notation // enabled, treat inner objects in config the same as // heavily nested dot notations (foo.bar.apple). if (typeof value === 'object' && value !== null && !Array.isArray(value) && configuration['dot-notation']) { // if the value is an object but not an array, check nested object setConfigObject(value, fullKey); } else { // setting arguments via CLI takes precedence over // values within the config file. if (!hasKey(argv, fullKey.split('.')) || (checkAllAliases(fullKey, flags.arrays) && configuration['combine-arrays'])) { setArg(fullKey, value); } } }); } // set all config objects passed in opts function setConfigObjects() { if (typeof configObjects !== 'undefined') { configObjects.forEach(function (configObject) { setConfigObject(configObject); }); } } function applyEnvVars(argv, configOnly) { if (typeof envPrefix === 'undefined') return; const prefix = typeof envPrefix === 'string' ? envPrefix : ''; const env = mixin.env(); Object.keys(env).forEach(function (envVar) { if (prefix === '' || envVar.lastIndexOf(prefix, 0) === 0) { // get array of nested keys and convert them to camel case const keys = envVar.split('__').map(function (key, i) { if (i === 0) { key = key.substring(prefix.length); } return camelCase(key); }); if (((configOnly && flags.configs[keys.join('.')]) || !configOnly) && !hasKey(argv, keys)) { setArg(keys.join('.'), env[envVar]); } } }); } function applyCoercions(argv) { let coerce; const applied = new Set(); Object.keys(argv).forEach(function (key) { if (!applied.has(key)) { // If we haven't already coerced this option via one of its aliases coerce = checkAllAliases(key, flags.coercions); if (typeof coerce === 'function') { try { const value = maybeCoerceNumber(key, coerce(argv[key])); ([].concat(flags.aliases[key] || [], key)).forEach(ali => { applied.add(ali); argv[ali] = value; }); } catch (err) { error = err; } } } }); } function setPlaceholderKeys(argv) { flags.keys.forEach((key) => { // don't set placeholder keys for dot notation options 'foo.bar'. if (~key.indexOf('.')) return; if (typeof argv[key] === 'undefined') argv[key] = undefined; }); return argv; } function applyDefaultsAndAliases(obj, aliases, defaults, canLog = false) { Object.keys(defaults).forEach(function (key) { if (!hasKey(obj, key.split('.'))) { setKey(obj, key.split('.'), defaults[key]); if (canLog) defaulted[key] = true; (aliases[key] || []).forEach(function (x) { if (hasKey(obj, x.split('.'))) return; setKey(obj, x.split('.'), defaults[key]); }); } }); } function hasKey(obj, keys) { let o = obj; if (!configuration['dot-notation']) keys = [keys.join('.')]; keys.slice(0, -1).forEach(function (key) { o = (o[key] || {}); }); const key = keys[keys.length - 1]; if (typeof o !== 'object') return false; else return key in o; } function setKey(obj, keys, value) { let o = obj; if (!configuration['dot-notation']) keys = [keys.join('.')]; keys.slice(0, -1).forEach(function (key) { // TODO(bcoe): in the next major version of yargs, switch to // Object.create(null) for dot notation: key = sanitizeKey(key); if (typeof o === 'object' && o[key] === undefined) { o[key] = {}; } if (typeof o[key] !== 'object' || Array.isArray(o[key])) { // ensure that o[key] is an array, and that the last item is an empty object. if (Array.isArray(o[key])) { o[key].push({}); } else { o[key] = [o[key], {}]; } // we want to update the empty object at the end of the o[key] array, so set o to that object o = o[key][o[key].length - 1]; } else { o = o[key]; } }); // TODO(bcoe): in the next major version of yargs, switch to // Object.create(null) for dot notation: const key = sanitizeKey(keys[keys.length - 1]); const isTypeArray = checkAllAliases(keys.join('.'), flags.arrays); const isValueArray = Array.isArray(value); let duplicate = configuration['duplicate-arguments-array']; // nargs has higher priority than duplicate if (!duplicate && checkAllAliases(key, flags.nargs)) { duplicate = true; if ((!isUndefined(o[key]) && flags.nargs[key] === 1) || (Array.isArray(o[key]) && o[key].length === flags.nargs[key])) { o[key] = undefined; } } if (value === increment()) { o[key] = increment(o[key]); } else if (Array.isArray(o[key])) { if (duplicate && isTypeArray && isValueArray) { o[key] = configuration['flatten-duplicate-arrays'] ? o[key].concat(value) : (Array.isArray(o[key][0]) ? o[key] : [o[key]]).concat([value]); } else if (!duplicate && Boolean(isTypeArray) === Boolean(isValueArray)) { o[key] = value; } else { o[key] = o[key].concat([value]); } } else if (o[key] === undefined && isTypeArray) { o[key] = isValueArray ? value : [value]; } else if (duplicate && !(o[key] === undefined || checkAllAliases(key, flags.counts) || checkAllAliases(key, flags.bools))) { o[key] = [o[key], value]; } else { o[key] = value; } } // extend the aliases list with inferred aliases. function extendAliases(...args) { args.forEach(function (obj) { Object.keys(obj || {}).forEach(function (key) { // short-circuit if we've already added a key // to the aliases array, for example it might // exist in both 'opts.default' and 'opts.key'. if (flags.aliases[key]) return; flags.aliases[key] = [].concat(aliases[key] || []); // For "--option-name", also set argv.optionName flags.aliases[key].concat(key).forEach(function (x) { if (/-/.test(x) && configuration['camel-case-expansion']) { const c = camelCase(x); if (c !== key && flags.aliases[key].indexOf(c) === -1) { flags.aliases[key].push(c); newAliases[c] = true; } } }); // For "--optionName", also set argv['option-name'] flags.aliases[key].concat(key).forEach(function (x) { if (x.length > 1 && /[A-Z]/.test(x) && configuration['camel-case-expansion']) { const c = decamelize(x, '-'); if (c !== key && flags.aliases[key].indexOf(c) === -1) { flags.aliases[key].push(c); newAliases[c] = true; } } }); flags.aliases[key].forEach(function (x) { flags.aliases[x] = [key].concat(flags.aliases[key].filter(function (y) { return x !== y; })); }); }); }); } function checkAllAliases(key, flag) { const toCheck = [].concat(flags.aliases[key] || [], key); const keys = Object.keys(flag); const setAlias = toCheck.find(key => keys.includes(key)); return setAlias ? flag[setAlias] : false; } function hasAnyFlag(key) { const flagsKeys = Object.keys(flags); const toCheck = [].concat(flagsKeys.map(k => flags[k])); return toCheck.some(function (flag) { return Array.isArray(flag) ? flag.includes(key) : flag[key]; }); } function hasFlagsMatching(arg, ...patterns) { const toCheck = [].concat(...patterns); return toCheck.some(function (pattern) { const match = arg.match(pattern); return match && hasAnyFlag(match[1]); }); } // based on a simplified version of the short flag group parsing logic function hasAllShortFlags(arg) { // if this is a negative number, or doesn't start with a single hyphen, it's not a short flag group if (arg.match(negative) || !arg.match(/^-[^-]+/)) { return false; } let hasAllFlags = true; let next; const letters = arg.slice(1).split(''); for (let j = 0; j < letters.length; j++) { next = arg.slice(j + 2); if (!hasAnyFlag(letters[j])) { hasAllFlags = false; break; } if ((letters[j + 1] && letters[j + 1] === '=') || next === '-' || (/[A-Za-z]/.test(letters[j]) && /^-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) || (letters[j + 1] && letters[j + 1].match(/\W/))) { break; } } return hasAllFlags; } function isUnknownOptionAsArg(arg) { return configuration['unknown-options-as-args'] && isUnknownOption(arg); } function isUnknownOption(arg) { arg = arg.replace(/^-{3,}/, '--'); // ignore negative numbers if (arg.match(negative)) { return false; } // if this is a short option group and all of them are configured, it isn't unknown if (hasAllShortFlags(arg)) { return false; } // e.g. '--count=2' const flagWithEquals = /^-+([^=]+?)=[\s\S]*$/; // e.g. '-a' or '--arg' const normalFlag = /^-+([^=]+?)$/; // e.g. '-a-' const flagEndingInHyphen = /^-+([^=]+?)-$/; // e.g. '-abc123' const flagEndingInDigits = /^-+([^=]+?\d+)$/; // e.g. '-a/usr/local' const flagEndingInNonWordCharacters = /^-+([^=]+?)\W+.*$/; // check the different types of flag styles, including negatedBoolean, a pattern defined near the start of the parse method return !hasFlagsMatching(arg, flagWithEquals, negatedBoolean, normalFlag, flagEndingInHyphen, flagEndingInDigits, flagEndingInNonWordCharacters); } // make a best effort to pick a default value // for an option based on name and type. function defaultValue(key) { if (!checkAllAliases(key, flags.bools) && !checkAllAliases(key, flags.counts) && `${key}` in defaults) { return defaults[key]; } else { return defaultForType(guessType(key)); } } // return a default value, given the type of a flag., function defaultForType(type) { const def = { [DefaultValuesForTypeKey.BOOLEAN]: true, [DefaultValuesForTypeKey.STRING]: '', [DefaultValuesForTypeKey.NUMBER]: undefined, [DefaultValuesForTypeKey.ARRAY]: [] }; return def[type]; } // given a flag, enforce a default type. function guessType(key) { let type = DefaultValuesForTypeKey.BOOLEAN; if (checkAllAliases(key, flags.strings)) type = DefaultValuesForTypeKey.STRING; else if (checkAllAliases(key, flags.numbers)) type = DefaultValuesForTypeKey.NUMBER; else if (checkAllAliases(key, flags.bools)) type = DefaultValuesForTypeKey.BOOLEAN; else if (checkAllAliases(key, flags.arrays)) type = DefaultValuesForTypeKey.ARRAY; return type; } function isUndefined(num) { return num === undefined; } // check user configuration settings for inconsistencies function checkConfiguration() { // count keys should not be set as array/narg Object.keys(flags.counts).find(key => { if (checkAllAliases(key, flags.arrays)) { error = Error(__('Invalid configuration: %s, opts.count excludes opts.array.', key)); return true; } else if (checkAllAliases(key, flags.nargs)) { error = Error(__('Invalid configuration: %s, opts.count excludes opts.narg.', key)); return true; } return false; }); } return { aliases: Object.assign({}, flags.aliases), argv: Object.assign(argvReturn, argv), configuration: configuration, defaulted: Object.assign({}, defaulted), error: error, newAliases: Object.assign({}, newAliases) }; }}// if any aliases reference each other, we should// merge them together.function combineAliases(aliases) { const aliasArrays = []; const combined = Object.create(null); let change = true; // turn alias lookup hash {key: ['alias1', 'alias2']} into // a simple array ['key', 'alias1', 'alias2'] Object.keys(aliases).forEach(function (key) { aliasArrays.push([].concat(aliases[key], key)); }); // combine arrays until zero changes are // made in an iteration. while (change) { change = false; for (let i = 0; i < aliasArrays.length; i++) { for (let ii = i + 1; ii < aliasArrays.length; ii++) { const intersect = aliasArrays[i].filter(function (v) { return aliasArrays[ii].indexOf(v) !== -1; }); if (intersect.length) { aliasArrays[i] = aliasArrays[i].concat(aliasArrays[ii]); aliasArrays.splice(ii, 1); change = true; break; } } } } // map arrays back to the hash-lookup (de-dupe while // we're at it). aliasArrays.forEach(function (aliasArray) { aliasArray = aliasArray.filter(function (v, i, self) { return self.indexOf(v) === i; }); const lastAlias = aliasArray.pop(); if (lastAlias !== undefined && typeof lastAlias === 'string') { combined[lastAlias] = aliasArray; } }); return combined;}// this function should only be called when a count is given as an arg// it is NOT called to set a default value// thus we can start the count at 1 instead of 0function increment(orig) { return orig !== undefined ? orig + 1 : 1;}// TODO(bcoe): in the next major version of yargs, switch to// Object.create(null) for dot notation:function sanitizeKey(key) { if (key === '__proto__') return '___proto___'; return key;}function stripQuotes(val) { return (typeof val === 'string' && (val[0] === "'" || val[0] === '"') && val[val.length - 1] === val[0]) ? val.substring(1, val.length - 1) : val;}
/** * @fileoverview Main entrypoint for libraries using yargs-parser in Node.js * CJS and ESM environments. * * @license * Copyright (c) 2016, Contributors * SPDX-License-Identifier: ISC */var _a, _b, _c;// See https://github.com/yargs/yargs-parser#supported-nodejs-versions for our// version support policy. The YARGS_MIN_NODE_VERSION is used for testing only.const minNodeVersion = (process && process.env && process.env.YARGS_MIN_NODE_VERSION) ? Number(process.env.YARGS_MIN_NODE_VERSION) : 12;const nodeVersion = (_b = (_a = process === null || process === void 0 ? void 0 : process.versions) === null || _a === void 0 ? void 0 : _a.node) !== null && _b !== void 0 ? _b : (_c = process === null || process === void 0 ? void 0 : process.version) === null || _c === void 0 ? void 0 : _c.slice(1);if (nodeVersion) { const major = Number(nodeVersion.match(/^([^.]+)/)[1]); if (major < minNodeVersion) { throw Error(`yargs parser supports a minimum Node.js version of ${minNodeVersion}. Read our version support policy: https://github.com/yargs/yargs-parser#supported-nodejs-versions`); }}// Creates a yargs-parser instance using Node.js standard libraries:const env = process ? process.env : {};const parser = new YargsParser({ cwd: process.cwd, env: () => { return env; }, format: require$$2.format, normalize: require$$0.normalize, resolve: require$$0.resolve, // TODO: figure out a way to combine ESM and CJS coverage, such that // we can exercise all the lines below: require: (path) => { if (typeof require !== 'undefined') { return require(path); } else if (path.match(/\.json$/)) { // Addresses: https://github.com/yargs/yargs/issues/2040 return JSON.parse(require$$0$1.readFileSync(path, 'utf8')); } else { throw Error('only .json config files are supported in ESM'); } }});const yargsParser = function Parser(args, opts) { const result = parser.parse(args.slice(), opts); return result.argv;};yargsParser.detailed = function (args, opts) { return parser.parse(args.slice(), opts);};yargsParser.camelCase = camelCase;yargsParser.decamelize = decamelize;yargsParser.looksLikeNumber = looksLikeNumber;
/******************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
/* global Reflect, Promise, SuppressedError, Symbol, Iterator */
function __addDisposableResource(env, value, async) {
if (value !== null && value !== void 0) {
if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
var dispose, inner;
if (async) {
if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
dispose = value[Symbol.asyncDispose];
}
if (dispose === void 0) {
if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
dispose = value[Symbol.dispose];
if (async) inner = dispose;
}
if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };
env.stack.push({ value: value, dispose: dispose, async: async });
}
else if (async) {
env.stack.push({ async: true });
}
return value;
}
var _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
var e = new Error(message);
return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
};
function __disposeResources(env) {
function fail(e) {
env.error = env.hasError ? new _SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
env.hasError = true;
}
var r, s = 0;
function next() {
while (r = env.stack.pop()) {
try {
if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
if (r.dispose) {
var result = r.dispose.call(r.value);
if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); });
}
else s |= 1;
}
catch (e) {
fail(e);
}
}
if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
if (env.hasError) throw env.error;
}
return next();
}
const toZeroIfInfinity = value => Number.isFinite(value) ? value : 0;
function parseNumber(milliseconds) { return { days: Math.trunc(milliseconds / 86_400_000), hours: Math.trunc(milliseconds / 3_600_000 % 24), minutes: Math.trunc(milliseconds / 60_000 % 60), seconds: Math.trunc(milliseconds / 1000 % 60), milliseconds: Math.trunc(milliseconds % 1000), microseconds: Math.trunc(toZeroIfInfinity(milliseconds * 1000) % 1000), nanoseconds: Math.trunc(toZeroIfInfinity(milliseconds * 1e6) % 1000), };}
function parseBigint(milliseconds) { return { days: milliseconds / 86_400_000n, hours: milliseconds / 3_600_000n % 24n, minutes: milliseconds / 60_000n % 60n, seconds: milliseconds / 1000n % 60n, milliseconds: milliseconds % 1000n, microseconds: 0n, nanoseconds: 0n, };}
function parseMilliseconds(milliseconds) { switch (typeof milliseconds) { case 'number': { if (Number.isFinite(milliseconds)) { return parseNumber(milliseconds); }
break; }
case 'bigint': { return parseBigint(milliseconds); }
// No default }
throw new TypeError('Expected a finite number or bigint');}
const isZero = value => value === 0 || value === 0n;const pluralize = (word, count) => (count === 1 || count === 1n) ? word : `${word}s`;
const SECOND_ROUNDING_EPSILON = 0.000_000_1;const ONE_DAY_IN_MILLISECONDS = 24n * 60n * 60n * 1000n;
function prettyMilliseconds(milliseconds, options) { const isBigInt = typeof milliseconds === 'bigint'; if (!isBigInt && !Number.isFinite(milliseconds)) { throw new TypeError('Expected a finite number or bigint'); }
options = {...options};
const sign = milliseconds < 0 ? '-' : ''; milliseconds = milliseconds < 0 ? -milliseconds : milliseconds; // Cannot use `Math.abs()` because of BigInt support.
if (options.colonNotation) { options.compact = false; options.formatSubMilliseconds = false; options.separateMilliseconds = false; options.verbose = false; }
if (options.compact) { options.unitCount = 1; options.secondsDecimalDigits = 0; options.millisecondsDecimalDigits = 0; }
let result = [];
const floorDecimals = (value, decimalDigits) => { const flooredInterimValue = Math.floor((value * (10 ** decimalDigits)) + SECOND_ROUNDING_EPSILON); const flooredValue = Math.round(flooredInterimValue) / (10 ** decimalDigits); return flooredValue.toFixed(decimalDigits); };
const add = (value, long, short, valueString) => { if ( (result.length === 0 || !options.colonNotation) && isZero(value) && !(options.colonNotation && short === 'm')) { return; }
valueString ??= String(value); if (options.colonNotation) { const wholeDigits = valueString.includes('.') ? valueString.split('.')[0].length : valueString.length; const minLength = result.length > 0 ? 2 : 1; valueString = '0'.repeat(Math.max(0, minLength - wholeDigits)) + valueString; } else { valueString += options.verbose ? ' ' + pluralize(long, value) : short; }
result.push(valueString); };
const parsed = parseMilliseconds(milliseconds); const days = BigInt(parsed.days);
if (options.hideYearAndDays) { add((BigInt(days) * 24n) + BigInt(parsed.hours), 'hour', 'h'); } else { if (options.hideYear) { add(days, 'day', 'd'); } else { add(days / 365n, 'year', 'y'); add(days % 365n, 'day', 'd'); }
add(Number(parsed.hours), 'hour', 'h'); }
add(Number(parsed.minutes), 'minute', 'm');
if (!options.hideSeconds) { if ( options.separateMilliseconds || options.formatSubMilliseconds || (!options.colonNotation && milliseconds < 1000 && !options.subSecondsAsDecimals) ) { const seconds = Number(parsed.seconds); const milliseconds = Number(parsed.milliseconds); const microseconds = Number(parsed.microseconds); const nanoseconds = Number(parsed.nanoseconds);
add(seconds, 'second', 's');
if (options.formatSubMilliseconds) { add(milliseconds, 'millisecond', 'ms'); add(microseconds, 'microsecond', 'µs'); add(nanoseconds, 'nanosecond', 'ns'); } else { const millisecondsAndBelow = milliseconds + (microseconds / 1000) + (nanoseconds / 1e6);
const millisecondsDecimalDigits = typeof options.millisecondsDecimalDigits === 'number' ? options.millisecondsDecimalDigits : 0;
const roundedMilliseconds = millisecondsAndBelow >= 1 ? Math.round(millisecondsAndBelow) : Math.ceil(millisecondsAndBelow);
const millisecondsString = millisecondsDecimalDigits ? millisecondsAndBelow.toFixed(millisecondsDecimalDigits) : roundedMilliseconds;
add( Number.parseFloat(millisecondsString), 'millisecond', 'ms', millisecondsString, ); } } else { const seconds = ( (isBigInt ? Number(milliseconds % ONE_DAY_IN_MILLISECONDS) : milliseconds) / 1000 ) % 60; const secondsDecimalDigits = typeof options.secondsDecimalDigits === 'number' ? options.secondsDecimalDigits : 1; const secondsFixed = floorDecimals(seconds, secondsDecimalDigits); const secondsString = options.keepDecimalsOnWholeSeconds ? secondsFixed : secondsFixed.replace(/\.0+$/, ''); add(Number.parseFloat(secondsString), 'second', 's', secondsString); } }
if (result.length === 0) { return sign + '0' + (options.verbose ? ' milliseconds' : 'ms'); }
const separator = options.colonNotation ? ':' : ' '; if (typeof options.unitCount === 'number') { result = result.slice(0, Math.max(options.unitCount, 1)); }
return sign + result.join(separator);}
const BYTE_UNITS = [ 'B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB',];
const BIBYTE_UNITS = [ 'B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB',];
const BIT_UNITS = [ 'b', 'kbit', 'Mbit', 'Gbit', 'Tbit', 'Pbit', 'Ebit', 'Zbit', 'Ybit',];
const BIBIT_UNITS = [ 'b', 'kibit', 'Mibit', 'Gibit', 'Tibit', 'Pibit', 'Eibit', 'Zibit', 'Yibit',];
/*Formats the given number using `Number#toLocaleString`.- If locale is a string, the value is expected to be a locale-key (for example: `de`).- If locale is true, the system default locale is used for translation.- If no value for locale is specified, the number is returned unmodified.*/const toLocaleString = (number, locale, options) => { let result = number; if (typeof locale === 'string' || Array.isArray(locale)) { result = number.toLocaleString(locale, options); } else if (locale === true || options !== undefined) { result = number.toLocaleString(undefined, options); }
return result;};
const log10 = numberOrBigInt => { if (typeof numberOrBigInt === 'number') { return Math.log10(numberOrBigInt); }
const string = numberOrBigInt.toString(10);
return string.length + Math.log10(`0.${string.slice(0, 15)}`);};
const log = numberOrBigInt => { if (typeof numberOrBigInt === 'number') { return Math.log(numberOrBigInt); }
return log10(numberOrBigInt) * Math.log(10);};
const divide = (numberOrBigInt, divisor) => { if (typeof numberOrBigInt === 'number') { return numberOrBigInt / divisor; }
const integerPart = numberOrBigInt / BigInt(divisor); const remainder = numberOrBigInt % BigInt(divisor); return Number(integerPart) + (Number(remainder) / divisor);};
const applyFixedWidth = (result, fixedWidth) => { if (fixedWidth === undefined) { return result; }
if (typeof fixedWidth !== 'number' || !Number.isSafeInteger(fixedWidth) || fixedWidth < 0) { throw new TypeError(`Expected fixedWidth to be a non-negative integer, got ${typeof fixedWidth}: ${fixedWidth}`); }
if (fixedWidth === 0) { return result; }
return result.length < fixedWidth ? result.padStart(fixedWidth, ' ') : result;};
const buildLocaleOptions = options => { const {minimumFractionDigits, maximumFractionDigits} = options;
if (minimumFractionDigits === undefined && maximumFractionDigits === undefined) { return undefined; }
return { ...(minimumFractionDigits !== undefined && {minimumFractionDigits}), ...(maximumFractionDigits !== undefined && {maximumFractionDigits}), roundingMode: 'trunc', };};
function prettyBytes(number, options) { if (typeof number !== 'bigint' && !Number.isFinite(number)) { throw new TypeError(`Expected a finite number, got ${typeof number}: ${number}`); }
options = { bits: false, binary: false, space: true, nonBreakingSpace: false, ...options, };
const UNITS = options.bits ? (options.binary ? BIBIT_UNITS : BIT_UNITS) : (options.binary ? BIBYTE_UNITS : BYTE_UNITS);
const separator = options.space ? (options.nonBreakingSpace ? '\u00A0' : ' ') : '';
// Handle signed zero case const isZero = typeof number === 'number' ? number === 0 : number === 0n; if (options.signed && isZero) { const result = ` 0${separator}${UNITS[0]}`; return applyFixedWidth(result, options.fixedWidth); }
const isNegative = number < 0; const prefix = isNegative ? '-' : (options.signed ? '+' : '');
if (isNegative) { number = -number; }
const localeOptions = buildLocaleOptions(options); let result;
if (number < 1) { const numberString = toLocaleString(number, options.locale, localeOptions); result = prefix + numberString + separator + UNITS[0]; } else { const exponent = Math.min(Math.floor(options.binary ? log(number) / Math.log(1024) : log10(number) / 3), UNITS.length - 1); number = divide(number, (options.binary ? 1024 : 1000) ** exponent);
if (!localeOptions) { const minPrecision = Math.max(3, Math.floor(number).toString().length); number = number.toPrecision(minPrecision); }
const numberString = toLocaleString(Number(number), options.locale, localeOptions); const unit = UNITS[exponent]; result = prefix + numberString + separator + unit; }
return applyFixedWidth(result, options.fixedWidth);}
function printTimings(timings) { for (const [label, [time, memory, total]] of Object.entries(timings)) { const appliedColor = label[0] === '#' ? (label[1] === '#' ? rollup.bold : rollup.underline) : (text) => text; const row = `${label}: ${time.toFixed(0)}ms, ${prettyBytes(memory)} / ${prettyBytes(total)}`; console.info(appliedColor(row)); }}
async function build(inputOptions, warnings, silent = false) { const env_1 = { stack: [], error: void 0, hasError: false }; try { const outputOptions = inputOptions.output; const useStdout = !outputOptions[0].file && !outputOptions[0].dir; const start = Date.now(); const files = useStdout ? ['stdout'] : outputOptions.map(t => parseAst_js.relativeId(t.file || t.dir)); if (!silent) { let inputFiles; if (typeof inputOptions.input === 'string') { inputFiles = inputOptions.input; } else if (Array.isArray(inputOptions.input)) { inputFiles = inputOptions.input.join(', '); } else if (typeof inputOptions.input === 'object' && inputOptions.input !== null) { inputFiles = Object.values(inputOptions.input).join(', '); } rollup.stderr(rollup.cyan(`\n${rollup.bold(inputFiles)} → ${rollup.bold(files.join(', '))}...`)); } const bundle = __addDisposableResource(env_1, await rollup.rollup(inputOptions), true); if (useStdout) { const output = outputOptions[0]; if (output.sourcemap && output.sourcemap !== 'inline') { rollup.handleError(parseAst_js.logOnlyInlineSourcemapsForStdout()); } const { output: outputs } = await bundle.generate(output); for (const file of outputs) { if (outputs.length > 1) process$1.stdout.write(`\n${rollup.cyan(rollup.bold(`//→ ${file.fileName}:`))}\n`); process$1.stdout.write(file.type === 'asset' ? file.source : file.code); } if (!silent) { warnings.flush(); } return; } await Promise.all(outputOptions.map(bundle.write)); if (!silent) { warnings.flush(); rollup.stderr(rollup.green(`created ${rollup.bold(files.join(', '))} in ${rollup.bold(prettyMilliseconds(Date.now() - start))}`)); if (bundle && bundle.getTimings) { printTimings(bundle.getTimings()); } } } catch (e_1) { env_1.error = e_1; env_1.hasError = true; } finally { const result_1 = __disposeResources(env_1); if (result_1) await result_1; }}
const DEFAULT_CONFIG_BASE = 'rollup.config';async function getConfigPath(commandConfig) { if (commandConfig === true) { return path.resolve(await findConfigFileNameInCwd()); } if (commandConfig.slice(0, 5) === 'node:') { const packageName = commandConfig.slice(5); try { return require.resolve(`rollup-config-${packageName}`, { paths: [process$1.cwd()] }); } catch { try { return require.resolve(packageName, { paths: [process$1.cwd()] }); } catch (error) { if (error.code === 'MODULE_NOT_FOUND') { rollup.handleError(parseAst_js.logMissingExternalConfig(commandConfig)); } throw error; } } } return path.resolve(commandConfig);}async function findConfigFileNameInCwd() { const filesInWorkingDirectory = new Set(await promises.readdir(process$1.cwd())); for (const extension of ['mjs', 'cjs', 'ts']) { const fileName = `${DEFAULT_CONFIG_BASE}.${extension}`; if (filesInWorkingDirectory.has(fileName)) return fileName; } return `${DEFAULT_CONFIG_BASE}.js`;}
async function loadConfigFromCommand(commandOptions, watchMode) { const warnings = loadConfigFile_js.batchWarnings(commandOptions); if (!commandOptions.input && (commandOptions.stdin || !process$1.stdin.isTTY)) { commandOptions.input = loadConfigFile_js.stdinName; } const options = await rollup.mergeOptions({ input: [] }, watchMode, commandOptions, warnings.log); await loadConfigFile_js.addCommandPluginsToInputOptions(options, commandOptions); return { options: [options], warnings };}
async function runRollup(command) { let inputSource; if (command._.length > 0) { if (command.input) { rollup.handleError(parseAst_js.logDuplicateImportOptions()); } inputSource = command._; } else if (typeof command.input === 'string') { inputSource = [command.input]; } else { inputSource = command.input; } if (inputSource && inputSource.length > 0) { if (inputSource.some((input) => input.includes('='))) { command.input = {}; for (const input of inputSource) { const equalsIndex = input.indexOf('='); const value = input.slice(Math.max(0, equalsIndex + 1)); const key = input.slice(0, Math.max(0, equalsIndex)) || parseAst_js.getAliasName(input); command.input[key] = value; } } else { command.input = inputSource; } } if (command.environment) { const environment = Array.isArray(command.environment) ? command.environment : [command.environment]; for (const argument of environment) { for (const pair of argument.split(',')) { const [key, ...value] = pair.split(':'); process$1.env[key] = value.length === 0 ? String(true) : value.join(':'); } } } if (rollup.isWatchEnabled(command.watch)) { await fseventsImporter.loadFsEvents(); const { watch } = await Promise.resolve().then(() => require('../shared/watch-cli.js')); await watch(command); } else { try { const { options, warnings } = await getConfigs(command); try { for (const inputOptions of options) { if (!inputOptions.cache) { // We explicitly disable the cache when unused as the CLI will not // use the cache object on the bundle when not in watch mode. This // improves performance as the cache is not generated. inputOptions.cache = false; } await build(inputOptions, warnings, command.silent); } if (command.failAfterWarnings && warnings.warningOccurred) { warnings.flush(); rollup.handleError(parseAst_js.logFailAfterWarnings()); } } catch (error) { warnings.flush(); rollup.handleError(error); } } catch (error) { rollup.handleError(error); } }}async function getConfigs(command) { if (command.config) { const configFile = await getConfigPath(command.config); const { options, warnings } = await loadConfigFile_js.loadConfigFile(configFile, command, false); return { options, warnings }; } return await loadConfigFromCommand(command, false);}
const command = yargsParser(process$1.argv.slice(2), { alias: rollup.commandAliases, configuration: { 'camel-case-expansion': false }});if (command.help || (process$1.argv.length <= 2 && process$1.stdin.isTTY)) { console.log(`\n${help}\n`);}else if (command.version) { console.log(`rollup v${rollup.version}`);}else { try { // eslint-disable-next-line @typescript-eslint/no-require-imports require('source-map-support').install(); } catch { // do nothing } const promise = runRollup(command); if (command.forceExit) { promise.then(() => process$1.exit()); }}
exports.getConfigPath = getConfigPath;exports.loadConfigFromCommand = loadConfigFromCommand;exports.prettyMilliseconds = prettyMilliseconds;exports.printTimings = printTimings;//# sourceMappingURL=rollup.map123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195#!/usr/bin/env node// Standalone semver comparison program.// Exits successfully and prints matching version(s) if// any supplied version is valid and passes all tests.
'use strict'
const argv = process.argv.slice(2)
let versions = []
const range = []
let inc = null
const version = require('../package.json').version
let loose = false
let includePrerelease = false
let coerce = false
let rtl = false
let identifier
let identifierBase
const semver = require('../')const parseOptions = require('../internal/parse-options')
let reverse = false
let options = {}
const main = () => { if (!argv.length) { return help() } while (argv.length) { let a = argv.shift() const indexOfEqualSign = a.indexOf('=') if (indexOfEqualSign !== -1) { const value = a.slice(indexOfEqualSign + 1) a = a.slice(0, indexOfEqualSign) argv.unshift(value) }
switch (a) { case '-rv': case '-rev': case '--rev': case '--reverse': reverse = true break case '-l': case '--loose': loose = true break case '-p': case '--include-prerelease': includePrerelease = true break case '-v': case '--version': versions.push(argv.shift()) break case '-i': case '--inc': case '--increment': if (semver.RELEASE_TYPES.includes(argv[0]) || (argv[0] === 'release')) { inc = { value: argv.shift(), maybeErrantValue: null, option: a } } else { inc = { value: 'patch', maybeErrantValue: argv[0], option: a } } break case '--preid': identifier = argv.shift() break case '-r': case '--range': range.push(argv.shift()) break case '-n': identifierBase = argv.shift() if (identifierBase === 'false') { identifierBase = false } break case '-c': case '--coerce': coerce = true break case '--rtl': rtl = true break case '--ltr': rtl = false break case '-h': case '--help': case '-?': return help() default: versions.push(a) break } }
options = parseOptions({ loose, includePrerelease, rtl })
if ( inc && versions.includes(inc.maybeErrantValue) && !semver.valid(inc.maybeErrantValue, options) ) { console.warn(`Invalid value for ${inc.option}; defaulting to 'patch'. This may become a failure in future major versions.`) }
versions = versions.map((v) => { return coerce ? (semver.coerce(v, options) || { version: v }).version : v }).filter((v) => { return semver.valid(v, options) }) if (!versions.length) { return fail() } if (inc && (versions.length !== 1 || range.length)) { return failInc() }
for (let i = 0, l = range.length; i < l; i++) { versions = versions.filter((v) => { return semver.satisfies(v, range[i], options) }) if (!versions.length) { return fail() } } versions .sort((a, b) => semver[reverse ? 'rcompare' : 'compare'](a, b, options)) .map(v => semver.clean(v, options)) .map(v => inc ? semver.inc(v, inc.value, options, identifier, identifierBase) : v) .forEach(v => console.log(v))}
const failInc = () => { console.error('--inc can only be used on a single version with no range') fail()}
const fail = () => process.exit(1)
const help = () => console.log(`SemVer ${version}
A JavaScript implementation of the https://semver.org/ specificationCopyright Isaac Z. Schlueter
Usage: semver [options] <version> [<version> [...]]Prints valid versions sorted by SemVer precedence
Options:-r --range <range> Print versions that match the specified range.
-i --increment [<level>] Increment a version by the specified level. Level can be one of: major, minor, patch, premajor, preminor, prepatch, prerelease, or release. Default level is 'patch'. Only one version may be specified.
--preid <identifier> Identifier to be used to prefix premajor, preminor, prepatch or prerelease version increments.
-l --loose Interpret versions and ranges loosely
-p --include-prerelease Always include prerelease versions in range matching
-c --coerce Coerce a string into SemVer if possible (does not imply --loose)
--rtl Coerce version strings right to left
--ltr Coerce version strings left to right (default)
-n <base> Base number to be used for the prerelease identifier. Can be either 0 or 1, or false to omit the number altogether. Defaults to 0.
Program exits successfully if any valid version satisfiesall supplied ranges, and prints all satisfying versions.
If no satisfying versions are found, then exits failure.
Versions are printed in ascending order, so supplyingmultiple versions to the utility will just sort them.`)
main()1234567891011121314#!/usr/bin/env nodeimport Specificity from '../dist/index.js';
if (!process.argv[2]) { console.error('❌ Missing selector argument'); process.exit(1);}
try { const specificities = Specificity.calculate(process.argv[2]); console.log(specificities.map((specificity) => `${specificity}`).join('\n'));} catch (e) { console.error(`❌ ${e.message}`);}123456789101112131415161718192021#!/usr/bin/env node
"use strict";
require("../tools/exit.cjs");
try { require("source-map-support").install();} catch (err) {}
const fs = require("fs");const path = require("path");const program = require("commander");
const packageJson = require("../package.json");const { _run_cli: run_cli } = require("..");
run_cli({ program, packageJson, fs, path }).catch((error) => { console.error(error); process.exitCode = 1;});123456789101112131415161718192021#!/usr/bin/env node
'use strict';
const { parse } = require('..');const readline = require('readline');
if (process.argv.length > 2) { // URL(s) was specified in the command arguments console.log( JSON.stringify(parse(process.argv[process.argv.length - 1]), null, 2), );} else { // No arguments were specified, read URLs from each line of STDIN const rlInterface = readline.createInterface({ input: process.stdin, }); rlInterface.on('line', function (line) { console.log(JSON.stringify(parse(line), null, 2)); });}1234567891011121314#!/usr/bin/env nodekill = require('.')try { kill(process.argv[2], process.argv[3], function(err){ if (err) { console.log(err.message) process.exit(1) } })}catch (err) { console.log(err.message) process.exit(1)}12#!/usr/bin/env noderequire('../lib/tsc.js')12#!/usr/bin/env noderequire('../lib/tsserver.js')123456789101112131415161718192021222324252627282930313233343536373839404142#!/usr/bin/env node
let { readFileSync } = require('fs')let { join } = require('path')
require('./check-npm-version')let updateDb = require('./')
const ROOT = __dirname
function getPackage() { return JSON.parse(readFileSync(join(ROOT, 'package.json')))}
let args = process.argv.slice(2)
let USAGE = 'Usage:\n npx update-browserslist-db\n'
function isArg(arg) { return args.some(i => i === arg)}
function error(msg) { process.stderr.write('update-browserslist-db: ' + msg + '\n') process.exit(1)}
if (isArg('--help') || isArg('-h')) { process.stdout.write(getPackage().description + '.\n\n' + USAGE + '\n')} else if (isArg('--version') || isArg('-v')) { process.stdout.write('browserslist-lint ' + getPackage().version + '\n')} else { try { updateDb() } catch (e) { if (e.name === 'BrowserslistUpdateError') { error(e.message) } else { throw e } }}12#!/usr/bin/env nodeimport '../uuid-bin.js';12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879#!/usr/bin/env nodeimport { performance } from 'node:perf_hooks'import module from 'node:module'
if (!import.meta.url.includes('node_modules')) { if (!process.env.DEBUG_DISABLE_SOURCE_MAP) { // eslint-disable-next-line n/no-unsupported-features/node-builtins -- only used in dev process.setSourceMapsEnabled(true) }
process.on('unhandledRejection', (err) => { throw new Error('UNHANDLED PROMISE REJECTION', { cause: err }) })}
global.__vite_start_time = performance.now()
// check debug mode first before requiring the CLI.const debugIndex = process.argv.findIndex((arg) => /^(?:-d|--debug)$/.test(arg))const filterIndex = process.argv.findIndex((arg) => /^(?:-f|--filter)$/.test(arg),)const profileIndex = process.argv.indexOf('--profile')
if (debugIndex > 0) { let value = process.argv[debugIndex + 1] if (!value || value[0] === '-') { value = 'vite:*' } else { // support debugging multiple flags with comma-separated list value = value .split(',') .map((v) => `vite:${v}`) .join(',') } process.env.DEBUG = `${ process.env.DEBUG ? process.env.DEBUG + ',' : '' }${value}`
if (filterIndex > 0) { const filter = process.argv[filterIndex + 1] if (filter && filter[0] !== '-') { process.env.VITE_DEBUG_FILTER = filter } }}
function start() { try { // eslint-disable-next-line n/no-unsupported-features/node-builtins -- it is supported in Node 22.8.0+ and only called if it exists module.enableCompileCache?.() // flush the cache after 10s because the cache is not flushed until process end // for dev server, the cache is never flushed unless manually flushed because the process.exit is called // also flushing the cache in SIGINT handler seems to cause the process to hang setTimeout(() => { try { // eslint-disable-next-line n/no-unsupported-features/node-builtins -- it is supported in Node 22.12.0+ and only called if it exists module.flushCompileCache?.() } catch {} }, 10 * 1000).unref() } catch {} return import('../dist/node/cli.js')}
if (profileIndex > 0) { process.argv.splice(profileIndex, 1) const next = process.argv[profileIndex] if (next && next[0] !== '-') { process.argv.splice(profileIndex, 1) } const inspector = await import('node:inspector').then((r) => r.default) const session = (global.__vite_profile_session = new inspector.Session()) session.connect() session.post('Profiler.enable', () => { session.post('Profiler.start', start) })} else { start()}12#!/usr/bin/env nodeimport './dist/cli.js'123456789101112131415161718#!/usr/bin/env node
var spawn = require('child_process').spawnvar path = require('path')
var prog = path.resolve(process.argv[2])var progArgs = process.argv.slice(3)
console.log('probing program', prog)
var nodeArgs = [ '-r', path.join(__dirname, 'include.js')]var nodeOpts = { stdio: 'inherit' }var child = spawn('node', nodeArgs.concat(prog).concat(progArgs), nodeOpts)
console.log('kill -SIGUSR1', child.pid, 'for logging')123456789101112131415161718192021MIT License
Copyright (c) 2024 asamuzaK (Kazz)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316# CSS color
[](https://github.com/asamuzaK/cssColor/actions/workflows/node.js.yml)[](https://github.com/asamuzaK/cssColor/actions/workflows/github-code-scanning/codeql)[](https://www.npmjs.com/package/@asamuzakjp/css-color)
Resolve and convert CSS colors.
## Install
```consolenpm i @asamuzakjp/css-color```
## Usage
```javascriptimport { convert, resolve, utils } from '@asamuzakjp/css-color';
const resolvedValue = resolve( 'color-mix(in oklab, lch(67.5345 42.5 258.2), color(srgb 0 0.5 0))');// 'oklab(0.620754 -0.0931934 -0.00374881)'
const convertedValue = convert.colorToHex('lab(46.2775% -47.5621 48.5837)');// '#008000'
const result = utils.isColor('green');// true```
<!-- Generated by documentation.js. Update this documentation by updating the source code. -->
### resolve(color, opt)
resolves CSS color
#### Parameters
- `color` **[string][133]** color value - system colors are not supported- `opt` **[object][135]?** options (optional, default `{}`) - `opt.currentColor` **[string][133]?** - color to use for `currentcolor` keyword - if omitted, it will be treated as a missing color, i.e. `rgb(none none none / none)` - `opt.customProperty` **[object][135]?** - custom properties - pair of `--` prefixed property name as a key and it's value, e.g. ```javascript const opt = { customProperty: { '--some-color': '#008000', '--some-length': '16px' } }; ``` - and/or `callback` function to get the value of the custom property, e.g. ```javascript const node = document.getElementById('foo'); const opt = { customProperty: { callback: node.style.getPropertyValue } }; ``` - `opt.dimension` **[object][135]?** - dimension, e.g. for converting relative length to pixels - pair of unit as a key and number in pixels as it's value, e.g. suppose `1em === 12px`, `1rem === 16px` and `100vw === 1024px`, then ```javascript const opt = { dimension: { em: 12, rem: 16, vw: 10.24 } }; ``` - and/or `callback` function to get the value as a number in pixels, e.g. ```javascript const opt = { dimension: { callback: unit => { switch (unit) { case 'em': return 12; case 'rem': return 16; case 'vw': return 10.24; default: return; } } } }; ``` - `opt.format` **[string][133]?** - output format, one of below - `computedValue` (default), [computed value][139] of the color - `specifiedValue`, [specified value][140] of the color - `hex`, hex color notation, i.e. `#rrggbb` - `hexAlpha`, hex color notation with alpha channel, i.e. `#rrggbbaa`
Returns **[string][133]?** one of `rgba?()`, `#rrggbb(aa)?`, `color-name`, `color(color-space r g b / alpha)`, `color(color-space x y z / alpha)`, `(ok)?lab(l a b / alpha)`, `(ok)?lch(l c h / alpha)`, `'(empty-string)'`, `null`
- in `computedValue`, values are numbers, however `rgb()` values are integers- in `specifiedValue`, returns `empty string` for unknown and/or invalid color- in `hex`, returns `null` for `transparent`, and also returns `null` if any of `r`, `g`, `b`, `alpha` is not a number- in `hexAlpha`, returns `#00000000` for `transparent`, however returns `null` if any of `r`, `g`, `b`, `alpha` is not a number
### convert
Contains various color conversion functions.
### convert.numberToHex(value)
convert number to hex string
#### Parameters
- `value` **[number][134]** color value
Returns **[string][133]** hex string: 00..ff
### convert.colorToHex(value, opt)
convert color to hex
#### Parameters
- `value` **[string][133]** color value- `opt` **[object][135]?** options (optional, default `{}`) - `opt.alpha` **[boolean][136]?** return in #rrggbbaa notation - `opt.customProperty` **[object][135]?** - custom properties, see `resolve()` function above - `opt.dimension` **[object][135]?** - dimension, see `resolve()` function above
Returns **[string][133]** #rrggbb(aa)?
### convert.colorToHsl(value, opt)
convert color to hsl
#### Parameters
- `value` **[string][133]** color value- `opt` **[object][135]?** options (optional, default `{}`) - `opt.customProperty` **[object][135]?** - custom properties, see `resolve()` function above - `opt.dimension` **[object][135]?** - dimension, see `resolve()` function above
Returns **[Array][137]<[number][134]>** \[h, s, l, alpha]
### convert.colorToHwb(value, opt)
convert color to hwb
#### Parameters
- `value` **[string][133]** color value- `opt` **[object][135]?** options (optional, default `{}`) - `opt.customProperty` **[object][135]?** - custom properties, see `resolve()` function above - `opt.dimension` **[object][135]?** - dimension, see `resolve()` function above
Returns **[Array][137]<[number][134]>** \[h, w, b, alpha]
### convert.colorToLab(value, opt)
convert color to lab
#### Parameters
- `value` **[string][133]** color value- `opt` **[object][135]?** options (optional, default `{}`) - `opt.customProperty` **[object][135]?** - custom properties, see `resolve()` function above - `opt.dimension` **[object][135]?** - dimension, see `resolve()` function above
Returns **[Array][137]<[number][134]>** \[l, a, b, alpha]
### convert.colorToLch(value, opt)
convert color to lch
#### Parameters
- `value` **[string][133]** color value- `opt` **[object][135]?** options (optional, default `{}`) - `opt.customProperty` **[object][135]?** - custom properties, see `resolve()` function above - `opt.dimension` **[object][135]?** - dimension, see `resolve()` function above
Returns **[Array][137]<[number][134]>** \[l, c, h, alpha]
### convert.colorToOklab(value, opt)
convert color to oklab
#### Parameters
- `value` **[string][133]** color value- `opt` **[object][135]?** options (optional, default `{}`) - `opt.customProperty` **[object][135]?** - custom properties, see `resolve()` function above - `opt.dimension` **[object][135]?** - dimension, see `resolve()` function above
Returns **[Array][137]<[number][134]>** \[l, a, b, alpha]
### convert.colorToOklch(value, opt)
convert color to oklch
#### Parameters
- `value` **[string][133]** color value- `opt` **[object][135]?** options (optional, default `{}`) - `opt.customProperty` **[object][135]?** - custom properties, see `resolve()` function above - `opt.dimension` **[object][135]?** - dimension, see `resolve()` function above
Returns **[Array][137]<[number][134]>** \[l, c, h, alpha]
### convert.colorToRgb(value, opt)
convert color to rgb
#### Parameters
- `value` **[string][133]** color value- `opt` **[object][135]?** options (optional, default `{}`) - `opt.customProperty` **[object][135]?** - custom properties, see `resolve()` function above - `opt.dimension` **[object][135]?** - dimension, see `resolve()` function above
Returns **[Array][137]<[number][134]>** \[r, g, b, alpha]
### convert.colorToXyz(value, opt)
convert color to xyz
#### Parameters
- `value` **[string][133]** color value- `opt` **[object][135]?** options (optional, default `{}`) - `opt.customProperty` **[object][135]?** - custom properties, see `resolve()` function above - `opt.dimension` **[object][135]?** - dimension, see `resolve()` function above - `opt.d50` **[boolean][136]?** xyz in d50 white point
Returns **[Array][137]<[number][134]>** \[x, y, z, alpha]
### convert.colorToXyzD50(value, opt)
convert color to xyz-d50
#### Parameters
- `value` **[string][133]** color value- `opt` **[object][135]?** options (optional, default `{}`) - `opt.customProperty` **[object][135]?** - custom properties, see `resolve()` function above - `opt.dimension` **[object][135]?** - dimension, see `resolve()` function above
Returns **[Array][137]<[number][134]>** \[x, y, z, alpha]
### utils
Contains utility functions.
### utils.isColor(color)
is valid color type
#### Parameters
- `color` **[string][133]** color value - system colors are not supported
Returns **[boolean][136]**
## Acknowledgments
The following resources have been of great help in the development of the CSS color.
- [csstools/postcss-plugins](https://github.com/csstools/postcss-plugins)- [lru-cache](https://github.com/isaacs/node-lru-cache)
---
Copyright (c) 2024 [asamuzaK (Kazz)](https://github.com/asamuzaK/)
[133]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String[134]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number[135]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object[136]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean[137]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array[138]: https://w3c.github.io/csswg-drafts/css-color-4/#color-conversion-code[139]: https://developer.mozilla.org/en-US/docs/Web/CSS/computed_value[140]: https://developer.mozilla.org/en-US/docs/Web/CSS/specified_value[141]: https://www.npmjs.com/package/@csstools/css-calc1234567891011121314151617181920/*! * CSS color - Resolve, parse, convert CSS color. * @license MIT * @copyright asamuzaK (Kazz) * @see {@link https://github.com/asamuzaK/cssColor/blob/main/LICENSE} */export { convert } from './js/convert.js';export { resolve } from './js/resolve.js';export declare const utils: { cssCalc: (value: string, opt?: import('./js/typedef.js').Options) => string; cssVar: (value: string, opt?: import('./js/typedef.js').Options) => string; extractDashedIdent: (value: string) => string[]; isAbsoluteFontSize: (css: unknown) => boolean; isAbsoluteSizeOrLength: (value: number | string, unit: string | undefined) => boolean; isColor: (value: unknown, opt?: import('./js/typedef.js').Options) => boolean; isGradient: (value: string, opt?: import('./js/typedef.js').Options) => boolean; resolveGradient: (value: string, opt?: import('./js/typedef.js').Options) => string; resolveLengthInPixels: (value: number | string, unit: string | undefined, opt?: import('./js/typedef.js').Options) => number; splitValue: (value: string, opt?: import('./js/typedef.js').Options) => string[];};1234567891011121314151617181920212223242526272829import { resolve } from "./js/resolve.js";import { extractDashedIdent, isAbsoluteFontSize, isAbsoluteSizeOrLength, isColor, resolveLengthInPixels, splitValue } from "./js/util.js";import { cssVar } from "./js/css-var.js";import { cssCalc } from "./js/css-calc.js";import { isGradient, resolveGradient } from "./js/css-gradient.js";import { convert } from "./js/convert.js";//#region src/index.ts/*!* CSS color - Resolve, parse, convert CSS color.* @license MIT* @copyright asamuzaK (Kazz)* @see {@link https://github.com/asamuzaK/cssColor/blob/main/LICENSE}*/var utils = { cssCalc, cssVar, extractDashedIdent, isAbsoluteFontSize, isAbsoluteSizeOrLength, isColor, isGradient, resolveGradient, resolveLengthInPixels, splitValue};//#endregionexport { convert, resolve, utils };
//# sourceMappingURL=index.js.map1{"version":3,"file":"index.js","names":[],"sources":["../../src/index.ts"],"sourcesContent":["/*!\n * CSS color - Resolve, parse, convert CSS color.\n * @license MIT\n * @copyright asamuzaK (Kazz)\n * @see {@link https://github.com/asamuzaK/cssColor/blob/main/LICENSE}\n */\n\nimport { cssCalc } from './js/css-calc';\nimport { isGradient, resolveGradient } from './js/css-gradient';\nimport { cssVar } from './js/css-var';\nimport {\n extractDashedIdent,\n isAbsoluteFontSize,\n isAbsoluteSizeOrLength,\n isColor,\n resolveLengthInPixels,\n splitValue\n} from './js/util';\n\nexport { convert } from './js/convert';\nexport { resolve } from './js/resolve';\n/* utils */\nexport const utils = {\n cssCalc,\n cssVar,\n extractDashedIdent,\n isAbsoluteFontSize,\n isAbsoluteSizeOrLength,\n isColor,\n isGradient,\n resolveGradient,\n resolveLengthInPixels,\n splitValue\n};\n"],"mappings":";;;;;;;;;;;;;AAsBA,IAAa,QAAQ;CACnB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD"}1234567891011121314151617181920212223242526272829303132333435363738import { GenerationalCache } from '@asamuzakjp/generational-cache';import { Options } from './typedef.js';/** * CacheItem */export declare class CacheItem { #private; constructor(item: unknown, isNull?: boolean); get item(): unknown; get isNull(): boolean;}/** * NullObject */export declare class NullObject extends CacheItem { constructor();}export declare const genCache: GenerationalCache<string, CacheItem>;/** * set cache * @param key - cache key * @param value - value to cache * @returns void */export declare const setCache: (key: string, value: unknown) => void;/** * get cache * @param key - cache key * @returns cached item or false otherwise */export declare const getCache: (key: string) => CacheItem | false;/** * create cache key * @param keyData - key data * @param [opt] - options * @returns cache key */export declare const createCacheKey: (keyData: Record<string, string>, opt?: Options) => string;123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990import { GenerationalCache } from "@asamuzakjp/generational-cache";//#region src/js/cache.ts/*** cache*/var CACHE_SIZE = 2048;/*** CacheItem*/var CacheItem = class { #isNull; #item; constructor(item, isNull = false) { this.#item = item; this.#isNull = !!isNull; } get item() { return this.#item; } get isNull() { return this.#isNull; }};/*** NullObject*/var NullObject = class extends CacheItem { constructor() { super(Symbol("null"), true); }};var genCache = new GenerationalCache(CACHE_SIZE);/*** shared null object*/var sharedNullObject = new NullObject();/*** set cache* @param key - cache key* @param value - value to cache* @returns void*/var setCache = (key, value) => { if (!key) return; if (value === null) genCache.set(key, sharedNullObject); else if (value instanceof CacheItem) genCache.set(key, value); else genCache.set(key, new CacheItem(value));};/*** get cache* @param key - cache key* @returns cached item or false otherwise*/var getCache = (key) => { if (!key) return false; const item = genCache.get(key); if (item !== void 0) return item; return false;};/*** helper function to sort object keys alphabetically* @param obj - Object* @returns stringified JSON*/var stringifySorted = (obj) => { const keys = Object.keys(obj); if (keys.length === 0) return ""; keys.sort(); let result = ""; for (const key of keys) result += `${key}:${JSON.stringify(obj[key])};`; return result;};/*** create cache key* @param keyData - key data* @param [opt] - options* @returns cache key*/var createCacheKey = (keyData, opt = {}) => { if (!keyData || opt.customProperty && typeof opt.customProperty.callback === "function" || opt.dimension && typeof opt.dimension.callback === "function") return ""; const namespace = keyData.namespace || ""; const name = keyData.name || ""; const value = keyData.value || ""; if (!namespace && !name && !value) return ""; return `${`${namespace}:${name}:${value}`}::${`${opt.format || ""}|${opt.colorSpace || ""}|${opt.colorScheme || ""}|${opt.currentColor || ""}|${opt.d50 ? "1" : "0"}|${opt.nullable ? "1" : "0"}|${opt.preserveComment ? "1" : "0"}|${opt.delimiter || ""}`}::${opt.customProperty ? stringifySorted(opt.customProperty) : ""}::${opt.dimension ? stringifySorted(opt.dimension) : ""}`;};//#endregionexport { CacheItem, NullObject, createCacheKey, getCache, setCache };
//# sourceMappingURL=cache.js.map1{"version":3,"file":"cache.js","names":["#item","#isNull"],"sources":["../../../src/js/cache.ts"],"sourcesContent":["/**\n * cache\n */\n\nimport { GenerationalCache } from '@asamuzakjp/generational-cache';\nimport { Options } from './typedef';\n\n/* constants */\nconst CACHE_SIZE = 2048;\n\n/**\n * CacheItem\n */\nexport class CacheItem {\n /* private */\n #isNull: boolean;\n #item: unknown;\n\n constructor(item: unknown, isNull: boolean = false) {\n this.#item = item;\n this.#isNull = !!isNull;\n }\n\n get item() {\n return this.#item;\n }\n\n get isNull() {\n return this.#isNull;\n }\n}\n\n/**\n * NullObject\n */\nexport class NullObject extends CacheItem {\n constructor() {\n super(Symbol('null'), true);\n }\n}\n\n/*\n * generational cache instance\n */\nexport const genCache = new GenerationalCache<string, CacheItem>(CACHE_SIZE);\n\n/**\n * shared null object\n */\nconst sharedNullObject = new NullObject();\n\n/**\n * set cache\n * @param key - cache key\n * @param value - value to cache\n * @returns void\n */\nexport const setCache = (key: string, value: unknown): void => {\n if (!key) {\n return;\n }\n if (value === null) {\n genCache.set(key, sharedNullObject);\n } else if (value instanceof CacheItem) {\n genCache.set(key, value);\n } else {\n genCache.set(key, new CacheItem(value));\n }\n};\n\n/**\n * get cache\n * @param key - cache key\n * @returns cached item or false otherwise\n */\nexport const getCache = (key: string): CacheItem | false => {\n if (!key) {\n return false;\n }\n const item = genCache.get(key);\n if (item !== undefined) {\n return item as CacheItem;\n }\n return false;\n};\n\n/**\n * helper function to sort object keys alphabetically\n * @param obj - Object\n * @returns stringified JSON\n */\nconst stringifySorted = (obj: Record<string, unknown>): string => {\n const keys = Object.keys(obj);\n if (keys.length === 0) {\n return '';\n }\n keys.sort();\n let result = '';\n for (const key of keys) {\n result += `${key}:${JSON.stringify(obj[key])};`;\n }\n return result;\n};\n\n/**\n * create cache key\n * @param keyData - key data\n * @param [opt] - options\n * @returns cache key\n */\nexport const createCacheKey = (\n keyData: Record<string, string>,\n opt: Options = {}\n): string => {\n if (\n !keyData ||\n (opt.customProperty && typeof opt.customProperty.callback === 'function') ||\n (opt.dimension && typeof opt.dimension.callback === 'function')\n ) {\n return '';\n }\n const namespace = keyData.namespace || '';\n const name = keyData.name || '';\n const value = keyData.value || '';\n if (!namespace && !name && !value) {\n return '';\n }\n const baseKey = `${namespace}:${name}:${value}`;\n const optStr = `${opt.format || ''}|${opt.colorSpace || ''}|${opt.colorScheme || ''}|${opt.currentColor || ''}|${opt.d50 ? '1' : '0'}|${opt.nullable ? '1' : '0'}|${opt.preserveComment ? '1' : '0'}|${opt.delimiter || ''}`;\n const customPropStr = opt.customProperty\n ? stringifySorted(opt.customProperty as Record<string, unknown>)\n : '';\n const dimStr = opt.dimension\n ? stringifySorted(opt.dimension as Record<string, unknown>)\n : '';\n return `${baseKey}::${optStr}::${customPropStr}::${dimStr}`;\n};\n"],"mappings":";;;;;AAQA,IAAM,aAAa;;;;AAKnB,IAAa,YAAb,MAAuB;CAErB;CACA;CAEA,YAAY,MAAe,SAAkB,OAAO;AAClD,QAAA,OAAa;AACb,QAAA,SAAe,CAAC,CAAC;;CAGnB,IAAI,OAAO;AACT,SAAO,MAAA;;CAGT,IAAI,SAAS;AACX,SAAO,MAAA;;;;;;AAOX,IAAa,aAAb,cAAgC,UAAU;CACxC,cAAc;AACZ,QAAM,OAAO,OAAO,EAAE,KAAK;;;AAO/B,IAAa,WAAW,IAAI,kBAAqC,WAAW;;;;AAK5E,IAAM,mBAAmB,IAAI,YAAY;;;;;;;AAQzC,IAAa,YAAY,KAAa,UAAyB;AAC7D,KAAI,CAAC,IACH;AAEF,KAAI,UAAU,KACZ,UAAS,IAAI,KAAK,iBAAiB;UAC1B,iBAAiB,UAC1B,UAAS,IAAI,KAAK,MAAM;KAExB,UAAS,IAAI,KAAK,IAAI,UAAU,MAAM,CAAC;;;;;;;AAS3C,IAAa,YAAY,QAAmC;AAC1D,KAAI,CAAC,IACH,QAAO;CAET,MAAM,OAAO,SAAS,IAAI,IAAI;AAC9B,KAAI,SAAS,KAAA,EACX,QAAO;AAET,QAAO;;;;;;;AAQT,IAAM,mBAAmB,QAAyC;CAChE,MAAM,OAAO,OAAO,KAAK,IAAI;AAC7B,KAAI,KAAK,WAAW,EAClB,QAAO;AAET,MAAK,MAAM;CACX,IAAI,SAAS;AACb,MAAK,MAAM,OAAO,KAChB,WAAU,GAAG,IAAI,GAAG,KAAK,UAAU,IAAI,KAAK,CAAC;AAE/C,QAAO;;;;;;;;AAST,IAAa,kBACX,SACA,MAAe,EAAE,KACN;AACX,KACE,CAAC,WACA,IAAI,kBAAkB,OAAO,IAAI,eAAe,aAAa,cAC7D,IAAI,aAAa,OAAO,IAAI,UAAU,aAAa,WAEpD,QAAO;CAET,MAAM,YAAY,QAAQ,aAAa;CACvC,MAAM,OAAO,QAAQ,QAAQ;CAC7B,MAAM,QAAQ,QAAQ,SAAS;AAC/B,KAAI,CAAC,aAAa,CAAC,QAAQ,CAAC,MAC1B,QAAO;AAUT,QAAO,GARS,GAAG,UAAU,GAAG,KAAK,GAAG,QAQtB,IAPH,GAAG,IAAI,UAAU,GAAG,GAAG,IAAI,cAAc,GAAG,GAAG,IAAI,eAAe,GAAG,GAAG,IAAI,gBAAgB,GAAG,GAAG,IAAI,MAAM,MAAM,IAAI,GAAG,IAAI,WAAW,MAAM,IAAI,GAAG,IAAI,kBAAkB,MAAM,IAAI,GAAG,IAAI,aAAa,KAO3L,IANP,IAAI,iBACtB,gBAAgB,IAAI,eAA0C,GAC9D,GAI2C,IAHhC,IAAI,YACf,gBAAgB,IAAI,UAAqC,GACzD"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537import { NullObject } from './cache.js';import { ColorChannels, Options, SpecifiedColorChannels } from './typedef.js';/** * @type TriColorChannels - color channels without alpha */type TriColorChannels = [x: number, y: number, z: number];/** * @type ColorMatrix - color matrix */type ColorMatrix = [ r1: TriColorChannels, r2: TriColorChannels, r3: TriColorChannels];/** * named colors */export declare const NAMED_COLORS: { readonly aliceblue: [240, 248, 255]; readonly antiquewhite: [250, 235, 215]; readonly aqua: [0, 255, 255]; readonly aquamarine: [127, 255, 212]; readonly azure: [240, 255, 255]; readonly beige: [245, 245, 220]; readonly bisque: [255, 228, 196]; readonly black: [0, 0, 0]; readonly blanchedalmond: [255, 235, 205]; readonly blue: [0, 0, 255]; readonly blueviolet: [138, 43, 226]; readonly brown: [165, 42, 42]; readonly burlywood: [222, 184, 135]; readonly cadetblue: [95, 158, 160]; readonly chartreuse: [127, 255, 0]; readonly chocolate: [210, 105, 30]; readonly coral: [255, 127, 80]; readonly cornflowerblue: [100, 149, 237]; readonly cornsilk: [255, 248, 220]; readonly crimson: [220, 20, 60]; readonly cyan: [0, 255, 255]; readonly darkblue: [0, 0, 139]; readonly darkcyan: [0, 139, 139]; readonly darkgoldenrod: [184, 134, 11]; readonly darkgray: [169, 169, 169]; readonly darkgreen: [0, 100, 0]; readonly darkgrey: [169, 169, 169]; readonly darkkhaki: [189, 183, 107]; readonly darkmagenta: [139, 0, 139]; readonly darkolivegreen: [85, 107, 47]; readonly darkorange: [255, 140, 0]; readonly darkorchid: [153, 50, 204]; readonly darkred: [139, 0, 0]; readonly darksalmon: [233, 150, 122]; readonly darkseagreen: [143, 188, 143]; readonly darkslateblue: [72, 61, 139]; readonly darkslategray: [47, 79, 79]; readonly darkslategrey: [47, 79, 79]; readonly darkturquoise: [0, 206, 209]; readonly darkviolet: [148, 0, 211]; readonly deeppink: [255, 20, 147]; readonly deepskyblue: [0, 191, 255]; readonly dimgray: [105, 105, 105]; readonly dimgrey: [105, 105, 105]; readonly dodgerblue: [30, 144, 255]; readonly firebrick: [178, 34, 34]; readonly floralwhite: [255, 250, 240]; readonly forestgreen: [34, 139, 34]; readonly fuchsia: [255, 0, 255]; readonly gainsboro: [220, 220, 220]; readonly ghostwhite: [248, 248, 255]; readonly gold: [255, 215, 0]; readonly goldenrod: [218, 165, 32]; readonly gray: [128, 128, 128]; readonly green: [0, 128, 0]; readonly greenyellow: [173, 255, 47]; readonly grey: [128, 128, 128]; readonly honeydew: [240, 255, 240]; readonly hotpink: [255, 105, 180]; readonly indianred: [205, 92, 92]; readonly indigo: [75, 0, 130]; readonly ivory: [255, 255, 240]; readonly khaki: [240, 230, 140]; readonly lavender: [230, 230, 250]; readonly lavenderblush: [255, 240, 245]; readonly lawngreen: [124, 252, 0]; readonly lemonchiffon: [255, 250, 205]; readonly lightblue: [173, 216, 230]; readonly lightcoral: [240, 128, 128]; readonly lightcyan: [224, 255, 255]; readonly lightgoldenrodyellow: [250, 250, 210]; readonly lightgray: [211, 211, 211]; readonly lightgreen: [144, 238, 144]; readonly lightgrey: [211, 211, 211]; readonly lightpink: [255, 182, 193]; readonly lightsalmon: [255, 160, 122]; readonly lightseagreen: [32, 178, 170]; readonly lightskyblue: [135, 206, 250]; readonly lightslategray: [119, 136, 153]; readonly lightslategrey: [119, 136, 153]; readonly lightsteelblue: [176, 196, 222]; readonly lightyellow: [255, 255, 224]; readonly lime: [0, 255, 0]; readonly limegreen: [50, 205, 50]; readonly linen: [250, 240, 230]; readonly magenta: [255, 0, 255]; readonly maroon: [128, 0, 0]; readonly mediumaquamarine: [102, 205, 170]; readonly mediumblue: [0, 0, 205]; readonly mediumorchid: [186, 85, 211]; readonly mediumpurple: [147, 112, 219]; readonly mediumseagreen: [60, 179, 113]; readonly mediumslateblue: [123, 104, 238]; readonly mediumspringgreen: [0, 250, 154]; readonly mediumturquoise: [72, 209, 204]; readonly mediumvioletred: [199, 21, 133]; readonly midnightblue: [25, 25, 112]; readonly mintcream: [245, 255, 250]; readonly mistyrose: [255, 228, 225]; readonly moccasin: [255, 228, 181]; readonly navajowhite: [255, 222, 173]; readonly navy: [0, 0, 128]; readonly oldlace: [253, 245, 230]; readonly olive: [128, 128, 0]; readonly olivedrab: [107, 142, 35]; readonly orange: [255, 165, 0]; readonly orangered: [255, 69, 0]; readonly orchid: [218, 112, 214]; readonly palegoldenrod: [238, 232, 170]; readonly palegreen: [152, 251, 152]; readonly paleturquoise: [175, 238, 238]; readonly palevioletred: [219, 112, 147]; readonly papayawhip: [255, 239, 213]; readonly peachpuff: [255, 218, 185]; readonly peru: [205, 133, 63]; readonly pink: [255, 192, 203]; readonly plum: [221, 160, 221]; readonly powderblue: [176, 224, 230]; readonly purple: [128, 0, 128]; readonly rebeccapurple: [102, 51, 153]; readonly red: [255, 0, 0]; readonly rosybrown: [188, 143, 143]; readonly royalblue: [65, 105, 225]; readonly saddlebrown: [139, 69, 19]; readonly salmon: [250, 128, 114]; readonly sandybrown: [244, 164, 96]; readonly seagreen: [46, 139, 87]; readonly seashell: [255, 245, 238]; readonly sienna: [160, 82, 45]; readonly silver: [192, 192, 192]; readonly skyblue: [135, 206, 235]; readonly slateblue: [106, 90, 205]; readonly slategray: [112, 128, 144]; readonly slategrey: [112, 128, 144]; readonly snow: [255, 250, 250]; readonly springgreen: [0, 255, 127]; readonly steelblue: [70, 130, 180]; readonly tan: [210, 180, 140]; readonly teal: [0, 128, 128]; readonly thistle: [216, 191, 216]; readonly tomato: [255, 99, 71]; readonly turquoise: [64, 224, 208]; readonly violet: [238, 130, 238]; readonly wheat: [245, 222, 179]; readonly white: [255, 255, 255]; readonly whitesmoke: [245, 245, 245]; readonly yellow: [255, 255, 0]; readonly yellowgreen: [154, 205, 50];};/** * cache invalid color value * @param key - cache key * @param nullable - is nullable * @returns cached value */export declare const cacheInvalidColorValue: (cacheKey: string, format: string, nullable?: boolean) => SpecifiedColorChannels | string | NullObject;/** * resolve invalid color value * @param format - output format * @param nullable - is nullable * @returns resolved value */export declare const resolveInvalidColorValue: (format: string, nullable?: boolean) => SpecifiedColorChannels | string | NullObject;/** * validate color components * @param arr - color components * @param [opt] - options * @param [opt.alpha] - alpha channel * @param [opt.minLength] - min length * @param [opt.maxLength] - max length * @param [opt.minRange] - min range * @param [opt.maxRange] - max range * @param [opt.validateRange] - validate range * @returns result - validated color components */export declare const validateColorComponents: (arr: ColorChannels | TriColorChannels, opt?: { alpha?: boolean; minLength?: number; maxLength?: number; minRange?: number; maxRange?: number; validateRange?: boolean;}) => ColorChannels | TriColorChannels;/** * transform matrix * @param mtx - 3 * 3 matrix * @param vct - vector * @param [skip] - skip validate * @returns TriColorChannels - [p1, p2, p3] */export declare const transformMatrix: (mtx: ColorMatrix, vct: TriColorChannels, skip?: boolean) => TriColorChannels;/** * normalize color components * @param colorA - color components [v1, v2, v3, v4] * @param colorB - color components [v1, v2, v3, v4] * @param [skip] - skip validate * @returns result - [colorA, colorB] */export declare const normalizeColorComponents: (colorA: [number | string, number | string, number | string, number | string], colorB: [number | string, number | string, number | string, number | string], skip?: boolean) => [ColorChannels, ColorChannels];/** * number to hex string * @param value - numeric value * @returns hex string */export declare const numberToHexString: (value: number) => string;/** * angle to deg * @param angle * @returns deg: 0..360 */export declare const angleToDeg: (angle: string) => number;/** * parse alpha * @param [alpha] - alpha value * @returns alpha: 0..1 */export declare const parseAlpha: (alpha?: string) => number;/** * parse hex alpha * @param value - alpha value in hex string * @returns alpha: 0..1 */export declare const parseHexAlpha: (value: string) => number;/** * transform rgb to linear rgb * @param rgb - [r, g, b] r|g|b: 0..255 * @param [skip] - skip validate * @returns TriColorChannels - [r, g, b] r|g|b: 0..1 */export declare const transformRgbToLinearRgb: (rgb: TriColorChannels, skip?: boolean) => TriColorChannels;/** * transform rgb to xyz * @param rgb - [r, g, b] r|g|b: 0..255 * @param [skip] - skip validate * @returns TriColorChannels - [x, y, z] */export declare const transformRgbToXyz: (rgb: TriColorChannels, skip?: boolean) => TriColorChannels;/** * transform rgb to xyz-d50 * @param rgb - [r, g, b] r|g|b: 0..255 alpha: 0..1 * @returns TriColorChannels - [x, y, z] */export declare const transformRgbToXyzD50: (rgb: TriColorChannels) => TriColorChannels;/** * transform linear rgb to rgb * @param rgb - [r, g, b] r|g|b: 0..1 * @param [round] - round result * @returns TriColorChannels - [r, g, b] r|g|b: 0..255 */export declare const transformLinearRgbToRgb: (rgb: TriColorChannels, round?: boolean) => TriColorChannels;/** * transform xyz to rgb * @param xyz - [x, y, z] * @param [skip] - skip validate * @returns TriColorChannels - [r, g, b] r|g|b: 0..255 */export declare const transformXyzToRgb: (xyz: TriColorChannels, skip?: boolean) => TriColorChannels;/** * transform xyz to xyz-d50 * @param xyz - [x, y, z] * @returns TriColorChannels - [x, y, z] */export declare const transformXyzToXyzD50: (xyz: TriColorChannels) => TriColorChannels;/** * transform xyz to hsl * @param xyz - [x, y, z] * @param [skip] - skip validate * @returns TriColorChannels - [h, s, l] */export declare const transformXyzToHsl: (xyz: TriColorChannels, skip?: boolean) => TriColorChannels;/** * transform xyz to hwb * @param xyz - [x, y, z] * @param [skip] - skip validate * @returns TriColorChannels - [h, w, b] */export declare const transformXyzToHwb: (xyz: TriColorChannels, skip?: boolean) => TriColorChannels;/** * transform xyz to oklab * @param xyz - [x, y, z] * @param [skip] - skip validate * @returns TriColorChannels - [l, a, b] */export declare const transformXyzToOklab: (xyz: TriColorChannels, skip?: boolean) => TriColorChannels;/** * transform xyz to oklch * @param xyz - [x, y, z] * @param [skip] - skip validate * @returns TriColorChannels - [l, c, h] */export declare const transformXyzToOklch: (xyz: TriColorChannels, skip?: boolean) => TriColorChannels;/** * transform xyz D50 to rgb * @param xyz - [x, y, z] * @param [skip] - skip validate * @returns TriColorChannels - [r, g, b] r|g|b: 0..255 */export declare const transformXyzD50ToRgb: (xyz: TriColorChannels, skip?: boolean) => TriColorChannels;/** * transform xyz-d50 to lab * @param xyz - [x, y, z] * @param [skip] - skip validate * @returns TriColorChannels - [l, a, b] */export declare const transformXyzD50ToLab: (xyz: TriColorChannels, skip?: boolean) => TriColorChannels;/** * transform xyz-d50 to lch * @param xyz - [x, y, z] * @param [skip] - skip validate * @returns TriColorChannels - [l, c, h] */export declare const transformXyzD50ToLch: (xyz: TriColorChannels, skip?: boolean) => TriColorChannels;/** * convert rgb to hex color * @param rgb - [r, g, b, alpha] r|g|b: 0..255 alpha: 0..1 * @returns hex color */export declare const convertRgbToHex: (rgb: ColorChannels) => string;/** * convert linear rgb to hex color * @param rgb - [r, g, b, alpha] r|g|b|alpha: 0..1 * @param [skip] - skip validate * @returns hex color */export declare const convertLinearRgbToHex: (rgb: ColorChannels, skip?: boolean) => string;/** * convert xyz to hex color * @param xyz - [x, y, z, alpha] * @returns hex color */export declare const convertXyzToHex: (xyz: ColorChannels) => string;/** * convert xyz D50 to hex color * @param xyz - [x, y, z, alpha] * @returns hex color */export declare const convertXyzD50ToHex: (xyz: ColorChannels) => string;/** * convert hex color to rgb * @param value - hex color value * @returns ColorChannels - [r, g, b, alpha] r|g|b: 0..255 alpha: 0..1 */export declare const convertHexToRgb: (value: string) => ColorChannels;/** * convert hex color to linear rgb * @param value - hex color value * @returns ColorChannels - [r, g, b, alpha] r|g|b|alpha: 0..1 */export declare const convertHexToLinearRgb: (value: string) => ColorChannels;/** * convert hex color to xyz * @param value - hex color value * @returns ColorChannels - [x, y, z, alpha] */export declare const convertHexToXyz: (value: string) => ColorChannels;/** * parse rgb() * @param value - rgb color value * @param [opt] - options * @returns parsed color - ['rgb', r, g, b, alpha], '(empty)', NullObject */export declare const parseRgb: (value: string, opt?: Options) => SpecifiedColorChannels | string | NullObject;/** * parse hsl() * @param value - hsl color value * @param [opt] - options * @returns parsed color - ['rgb', r, g, b, alpha], '(empty)', NullObject */export declare const parseHsl: (value: string, opt?: Options) => SpecifiedColorChannels | string | NullObject;/** * parse hwb() * @param value - hwb color value * @param [opt] - options * @returns parsed color - ['rgb', r, g, b, alpha], '(empty)', NullObject */export declare const parseHwb: (value: string, opt?: Options) => SpecifiedColorChannels | string | NullObject;/** * parse lab() * @param value - lab color value * @param [opt] - options * @returns parsed color * - [xyz-d50, x, y, z, alpha], ['lab', l, a, b, alpha], '(empty)', NullObject */export declare const parseLab: (value: string, opt?: Options) => SpecifiedColorChannels | string | NullObject;/** * parse lch() * @param value - lch color value * @param [opt] - options * @returns parsed color * - ['xyz-d50', x, y, z, alpha], ['lch', l, c, h, alpha] * - '(empty)', NullObject */export declare const parseLch: (value: string, opt?: Options) => SpecifiedColorChannels | string | NullObject;/** * parse oklab() * @param value - oklab color value * @param [opt] - options * @returns parsed color * - ['xyz-d65', x, y, z, alpha], ['oklab', l, a, b, alpha] * - '(empty)', NullObject */export declare const parseOklab: (value: string, opt?: Options) => SpecifiedColorChannels | string | NullObject;/** * parse oklch() * @param value - oklch color value * @param [opt] - options * @returns parsed color * - ['xyz-d65', x, y, z, alpha], ['oklch', l, c, h, alpha] * - '(empty)', NullObject */export declare const parseOklch: (value: string, opt?: Options) => SpecifiedColorChannels | string | NullObject;/** * parse color() * @param value - color function value * @param [opt] - options * @returns parsed color * - ['xyz-(d50|d65)', x, y, z, alpha], [cs, r, g, b, alpha] * - '(empty)', NullObject */export declare const parseColorFunc: (value: string, opt?: Options) => SpecifiedColorChannels | string | NullObject;/** * parse color value * @param value - CSS color value * @param [opt] - options * @returns parsed color * - ['xyz-(d50|d65)', x, y, z, alpha], ['rgb', r, g, b, alpha] * - value, '(empty)', NullObject */export declare const parseColorValue: (value: string, opt?: Options) => SpecifiedColorChannels | string | NullObject;/** * resolve color value * @param value - CSS color value * @param [opt] - options * @returns resolved color * - [cs, v1, v2, v3, alpha], value, '(empty)', NullObject */export declare const resolveColorValue: (value: string, opt?: Options) => SpecifiedColorChannels | string | NullObject;/** * resolve color() * @param value - color function value * @param [opt] - options * @returns resolved color - [cs, v1, v2, v3, alpha], '(empty)', NullObject */export declare const resolveColorFunc: (value: string, opt?: Options) => SpecifiedColorChannels | string | NullObject;/** * convert color value to linear rgb * @param value - CSS color value * @param [opt] - options * @returns ColorChannels | NullObject - [r, g, b, alpha] r|g|b|alpha: 0..1 */export declare const convertColorToLinearRgb: (value: string, opt?: { colorSpace?: string; format?: string;}) => ColorChannels | NullObject;/** * convert color value to rgb * @param value - CSS color value * @param [opt] - options * @returns ColorChannels | NullObject * - [r, g, b, alpha] r|g|b: 0..255 alpha: 0..1 */export declare const convertColorToRgb: (value: string, opt?: Options) => ColorChannels | NullObject;/** * convert color value to xyz * @param value - CSS color value * @param [opt] - options * @returns ColorChannels | NullObject - [x, y, z, alpha] */export declare const convertColorToXyz: (value: string, opt?: Options) => ColorChannels | NullObject;/** * convert color value to hsl * @param value - CSS color value * @param [opt] - options * @returns ColorChannels | NullObject - [h, s, l, alpha], hue may be powerless */export declare const convertColorToHsl: (value: string, opt?: Options) => ColorChannels | [number | string, number, number, number] | NullObject;/** * convert color value to hwb * @param value - CSS color value * @param [opt] - options * @returns ColorChannels | NullObject - [h, w, b, alpha], hue may be powerless */export declare const convertColorToHwb: (value: string, opt?: Options) => ColorChannels | [number | string, number, number, number] | NullObject;/** * convert color value to lab * @param value - CSS color value * @param [opt] - options * @returns ColorChannels | NullObject - [l, a, b, alpha] */export declare const convertColorToLab: (value: string, opt?: Options) => ColorChannels | NullObject;/** * convert color value to lch * @param value - CSS color value * @param [opt] - options * @returns ColorChannels | NullObject - [l, c, h, alpha], hue may be powerless */export declare const convertColorToLch: (value: string, opt?: Options) => ColorChannels | [number, number, number | string, number] | NullObject;/** * convert color value to oklab * @param value - CSS color value * @param [opt] - options * @returns ColorChannels | NullObject - [l, a, b, alpha] */export declare const convertColorToOklab: (value: string, opt?: Options) => ColorChannels | NullObject;/** * convert color value to oklch * @param value - CSS color value * @param [opt] - options * @returns ColorChannels | NullObject - [l, c, h, alpha], hue may be powerless */export declare const convertColorToOklch: (value: string, opt?: Options) => ColorChannels | [number, number, number | string, number] | NullObject;/** * resolve color-mix() * @param value - color-mix color value * @param [opt] - options * @returns resolved color - [cs, v1, v2, v3, alpha], '(empty)' */export declare const resolveColorMix: (value: string, opt?: Options) => SpecifiedColorChannels | string | NullObject;export {};123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534import { CacheItem, NullObject, createCacheKey, getCache, setCache } from "./cache.js";import { isString } from "./common.js";import { ANGLE, CS_HUE_CAPT, CS_MIX, CS_RGB, CS_XYZ, FN_MIX, NONE, NUM, PCT, SYN_COLOR_TYPE, SYN_FN_COLOR, SYN_HSL, SYN_HSL_LV3, SYN_LCH, SYN_MIX, SYN_MIX_CAPT, SYN_MIX_PART, SYN_MOD, SYN_RGB_LV3, VAL_COMP, VAL_MIX, VAL_SPEC } from "./constant.js";import { resolveColor } from "./resolve.js";import { interpolateHue, roundToPrecision, splitValue } from "./util.js";//#region src/js/color.ts/*** color** Ref: CSS Color Module Level 4* Sample code for Color Conversions* https://w3c.github.io/csswg-drafts/css-color-4/#color-conversion-code*/var NAMESPACE = "color";var PPTH = .001;var HALF = .5;var DUO = 2;var TRIA = 3;var QUAD = 4;var OCT = 8;var DEC = 10;var DOZ = 12;var HEX = 16;var SEXA = 60;var DEG_HALF = 180;var DEG = 360;var MAX_PCT = 100;var MAX_RGB = 255;var POW_SQR = 2;var POW_CUBE = 3;var POW_LINEAR = 2.4;var LINEAR_COEF = 12.92;var LINEAR_OFFSET = .055;var LAB_L = 116;var LAB_A = 500;var LAB_B = 200;var LAB_EPSILON = 216 / 24389;var LAB_KAPPA = 24389 / 27;var D50 = [ .3457 / .3585, 1, .2958 / .3585];var MATRIX_D50_TO_D65 = [ [ .955473421488075, -.02309845494876471, .06325924320057072 ], [ -.0283697093338637, 1.0099953980813041, .021041441191917323 ], [ .012314014864481998, -.020507649298898964, 1.330365926242124 ]];var MATRIX_D65_TO_D50 = [ [ 1.0479297925449969, .022946870601609652, -.05019226628920524 ], [ .02962780877005599, .9904344267538799, -.017073799063418826 ], [ -.009243040646204504, .015055191490298152, .7518742814281371 ]];var MATRIX_L_RGB_TO_XYZ = [ [ 506752 / 1228815, 87881 / 245763, 12673 / 70218 ], [ 87098 / 409605, 175762 / 245763, 12673 / 175545 ], [ 7918 / 409605, 87881 / 737289, 1001167 / 1053270 ]];var MATRIX_XYZ_TO_L_RGB = [ [ 12831 / 3959, -329 / 214, -1974 / 3959 ], [ -851781 / 878810, 1648619 / 878810, 36519 / 878810 ], [ 705 / 12673, -2585 / 12673, 705 / 667 ]];var MATRIX_XYZ_TO_LMS = [ [ .819022437996703, .3619062600528904, -.1288737815209879 ], [ .0329836539323885, .9292868615863434, .0361446663506424 ], [ .0481771893596242, .2642395317527308, .6335478284694309 ]];var MATRIX_LMS_TO_XYZ = [ [ 1.2268798758459243, -.5578149944602171, .2813910456659647 ], [ -.0405757452148008, 1.112286803280317, -.0717110580655164 ], [ -.0763729366746601, -.4214933324022432, 1.5869240198367816 ]];var MATRIX_OKLAB_TO_LMS = [ [ 1, .3963377773761749, .2158037573099136 ], [ 1, -.1055613458156586, -.0638541728258133 ], [ 1, -.0894841775298119, -1.2914855480194092 ]];var MATRIX_LMS_TO_OKLAB = [ [ .210454268309314, .7936177747023054, -.0040720430116193 ], [ 1.9779985324311684, -2.42859224204858, .450593709617411 ], [ .0259040424655478, .7827717124575296, -.8086757549230774 ]];var MATRIX_P3_TO_XYZ = [ [ 608311 / 1250200, 189793 / 714400, 198249 / 1000160 ], [ 35783 / 156275, 247089 / 357200, 198249 / 2500400 ], [ 0 / 1, 32229 / 714400, 5220557 / 5000800 ]];var MATRIX_REC2020_TO_XYZ = [ [ 63426534 / 99577255, 20160776 / 139408157, 47086771 / 278816314 ], [ 26158966 / 99577255, 472592308 / 697040785, 8267143 / 139408157 ], [ 0 / 1, 19567812 / 697040785, 295819943 / 278816314 ]];var MATRIX_A98_TO_XYZ = [ [ 573536 / 994567, 263643 / 1420810, 187206 / 994567 ], [ 591459 / 1989134, 6239551 / 9945670, 374412 / 4972835 ], [ 53769 / 1989134, 351524 / 4972835, 4929758 / 4972835 ]];var MATRIX_PROPHOTO_TO_XYZ_D50 = [ [ .7977666449006423, .13518129740053308, .0313477341283922 ], [ .2880748288194013, .711835234241873, 8993693872564e-17 ], [ 0, 0, .8251046025104602 ]];var REG_COLOR = new RegExp(`^(?:${SYN_COLOR_TYPE})$`);var REG_CS_HUE = new RegExp(`^${CS_HUE_CAPT}$`);var REG_CS_XYZ = /^xyz(?:-d(?:50|65))?$/;var REG_CURRENT = /^currentColor$/i;var REG_FN_COLOR = new RegExp(`^color\\(\\s*(${SYN_FN_COLOR})\\s*\\)$`);var REG_HSL = new RegExp(`^hsla?\\(\\s*(${SYN_HSL}|${SYN_HSL_LV3})\\s*\\)$`);var REG_HWB = new RegExp(`^hwb\\(\\s*(${SYN_HSL})\\s*\\)$`);var REG_LAB = new RegExp(`^lab\\(\\s*(${SYN_MOD})\\s*\\)$`);var REG_LCH = new RegExp(`^lch\\(\\s*(${SYN_LCH})\\s*\\)$`);var REG_MIX = new RegExp(`^${SYN_MIX}$`);var REG_MIX_CAPT = new RegExp(`^${SYN_MIX_CAPT}$`);var REG_MIX_NEST = new RegExp(`${SYN_MIX}`, "g");var REG_OKLAB = new RegExp(`^oklab\\(\\s*(${SYN_MOD})\\s*\\)$`);var REG_OKLCH = new RegExp(`^oklch\\(\\s*(${SYN_LCH})\\s*\\)$`);var REG_SPEC = /^(?:specifi|comput)edValue$/;var REG_ANGLE_TO_DEG = new RegExp(`^(${NUM})(${ANGLE})?$`);var REG_PARSE_RGB = new RegExp(`^rgba?\\(\\s*(${SYN_MOD}|${SYN_RGB_LV3})\\s*\\)$`);var REG_MIX_CS_RGB_XYZ = new RegExp(`^(?:${CS_RGB}|${CS_XYZ})$`);var REG_MIX_IN_CS = new RegExp(`in\\s+(${CS_MIX})`);var REG_MIX_START = new RegExp(`^color-mix\\(\\s*in\\s+(${CS_MIX})\\s*,`);var REG_MIX_COLOR_PART = new RegExp(`^(${SYN_COLOR_TYPE})(?:\\s+(${PCT}))?$`);/*** named colors*/var NAMED_COLORS = { 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 ]};/*** cache invalid color value* @param key - cache key* @param nullable - is nullable* @returns cached value*/var cacheInvalidColorValue = (cacheKey, format, nullable = false) => { if (format === "specifiedValue") { const res = ""; setCache(cacheKey, res); return res; } if (nullable) { setCache(cacheKey, null); return new NullObject(); } const res = [ "rgb", 0, 0, 0, 0 ]; setCache(cacheKey, res); return res;};/*** resolve invalid color value* @param format - output format* @param nullable - is nullable* @returns resolved value*/var resolveInvalidColorValue = (format, nullable = false) => { switch (format) { case "hsl": case "hwb": case VAL_MIX: return new NullObject(); case VAL_SPEC: return ""; default: if (nullable) return new NullObject(); return [ "rgb", 0, 0, 0, 0 ]; }};/*** validate color components* @param arr - color components* @param [opt] - options* @param [opt.alpha] - alpha channel* @param [opt.minLength] - min length* @param [opt.maxLength] - max length* @param [opt.minRange] - min range* @param [opt.maxRange] - max range* @param [opt.validateRange] - validate range* @returns result - validated color components*/var validateColorComponents = (arr, opt = {}) => { if (!Array.isArray(arr)) throw new TypeError(`${arr} is not an array.`); const { alpha = false, minLength = TRIA, maxLength = QUAD, minRange = 0, maxRange = 1, validateRange = true } = opt; if (!Number.isFinite(minLength)) throw new TypeError(`${minLength} is not a number.`); if (!Number.isFinite(maxLength)) throw new TypeError(`${maxLength} is not a number.`); if (!Number.isFinite(minRange)) throw new TypeError(`${minRange} is not a number.`); if (!Number.isFinite(maxRange)) throw new TypeError(`${maxRange} is not a number.`); const l = arr.length; if (l < minLength || l > maxLength) throw new Error(`Unexpected array length ${l}.`); let i = 0; while (i < l) { const v = arr[i]; if (!Number.isFinite(v)) throw new TypeError(`${v} is not a number.`); else if (i < TRIA && validateRange && (v < minRange || v > maxRange)) throw new RangeError(`${v} is not between ${minRange} and ${maxRange}.`); else if (i === TRIA && (v < 0 || v > 1)) throw new RangeError(`${v} is not between 0 and 1.`); i++; } if (alpha && l === TRIA) arr.push(1); return arr;};/*** transform matrix* @param mtx - 3 * 3 matrix* @param vct - vector* @param [skip] - skip validate* @returns TriColorChannels - [p1, p2, p3]*/var transformMatrix = (mtx, vct, skip = false) => { if (!Array.isArray(mtx)) throw new TypeError(`${mtx} is not an array.`); else if (mtx.length !== TRIA) throw new Error(`Unexpected array length ${mtx.length}.`); else if (!skip) for (let i of mtx) i = validateColorComponents(i, { maxLength: TRIA, validateRange: false }); const [[r1c1, r1c2, r1c3], [r2c1, r2c2, r2c3], [r3c1, r3c2, r3c3]] = mtx; let v1, v2, v3; if (skip) [v1, v2, v3] = vct; else [v1, v2, v3] = validateColorComponents(vct, { maxLength: TRIA, validateRange: false }); return [ r1c1 * v1 + r1c2 * v2 + r1c3 * v3, r2c1 * v1 + r2c2 * v2 + r2c3 * v3, r3c1 * v1 + r3c2 * v2 + r3c3 * v3 ];};/*** normalize color components* @param colorA - color components [v1, v2, v3, v4]* @param colorB - color components [v1, v2, v3, v4]* @param [skip] - skip validate* @returns result - [colorA, colorB]*/var normalizeColorComponents = (colorA, colorB, skip = false) => { if (!Array.isArray(colorA)) throw new TypeError(`${colorA} is not an array.`); else if (colorA.length !== QUAD) throw new Error(`Unexpected array length ${colorA.length}.`); if (!Array.isArray(colorB)) throw new TypeError(`${colorB} is not an array.`); else if (colorB.length !== QUAD) throw new Error(`Unexpected array length ${colorB.length}.`); let i = 0; while (i < QUAD) { if (colorA[i] === "none" && colorB[i] === "none") { colorA[i] = 0; colorB[i] = 0; } else if (colorA[i] === "none") colorA[i] = colorB[i]; else if (colorB[i] === "none") colorB[i] = colorA[i]; i++; } if (skip) return [colorA, colorB]; return [validateColorComponents(colorA, { minLength: QUAD, validateRange: false }), validateColorComponents(colorB, { minLength: QUAD, validateRange: false })];};/*** number to hex string* @param value - numeric value* @returns hex string*/var numberToHexString = (value) => { if (!Number.isFinite(value)) throw new TypeError(`${value} is not a number.`); else { value = Math.round(value); if (value < 0 || value > MAX_RGB) throw new RangeError(`${value} is not between 0 and ${MAX_RGB}.`); } let hex = value.toString(HEX); if (hex.length === 1) hex = `0${hex}`; return hex;};/*** angle to deg* @param angle* @returns deg: 0..360*/var angleToDeg = (angle) => { if (isString(angle)) angle = angle.trim(); else throw new TypeError(`${angle} is not a string.`); const GRAD = DEG / 400; const RAD = DEG / (Math.PI * DUO); if (!REG_ANGLE_TO_DEG.test(angle)) throw new SyntaxError(`Invalid property value: ${angle}`); const [, value, unit] = angle.match(REG_ANGLE_TO_DEG); let deg; switch (unit) { case "grad": deg = parseFloat(value) * GRAD; break; case "rad": deg = parseFloat(value) * RAD; break; case "turn": deg = parseFloat(value) * DEG; break; default: deg = parseFloat(value); } deg %= DEG; if (deg < 0) deg += DEG; else if (Object.is(deg, -0)) deg = 0; return deg;};/*** parse alpha* @param [alpha] - alpha value* @returns alpha: 0..1*/var parseAlpha = (alpha = "") => { if (isString(alpha)) { alpha = alpha.trim(); if (!alpha) alpha = "1"; else if (alpha === "none") alpha = "0"; else { let a; if (alpha.endsWith("%")) a = parseFloat(alpha) / MAX_PCT; else a = parseFloat(alpha); if (!Number.isFinite(a)) throw new TypeError(`${a} is not a finite number.`); if (a < PPTH) alpha = "0"; else if (a > 1) alpha = "1"; else alpha = a.toFixed(TRIA); } } else alpha = "1"; return parseFloat(alpha);};/*** parse hex alpha* @param value - alpha value in hex string* @returns alpha: 0..1*/var parseHexAlpha = (value) => { if (isString(value)) { if (value === "") throw new SyntaxError("Invalid property value: (empty string)"); value = value.trim(); } else throw new TypeError(`${value} is not a string.`); let alpha = parseInt(value, HEX); if (alpha <= 0) return 0; if (alpha >= MAX_RGB) return 1; const alphaMap = /* @__PURE__ */ new Map(); for (let i = 1; i < MAX_PCT; i++) alphaMap.set(Math.round(i * MAX_RGB / MAX_PCT), i); if (alphaMap.has(alpha)) alpha = alphaMap.get(alpha) / MAX_PCT; else alpha = Math.round(alpha / MAX_RGB / PPTH) * PPTH; return parseFloat(alpha.toFixed(TRIA));};/*** transform rgb to linear rgb* @param rgb - [r, g, b] r|g|b: 0..255* @param [skip] - skip validate* @returns TriColorChannels - [r, g, b] r|g|b: 0..1*/var transformRgbToLinearRgb = (rgb, skip = false) => { let rr, gg, bb; if (skip) [rr, gg, bb] = rgb; else [rr, gg, bb] = validateColorComponents(rgb, { maxLength: TRIA, maxRange: MAX_RGB }); let r = rr / MAX_RGB; let g = gg / MAX_RGB; let b = bb / MAX_RGB; const COND_POW = .04045; if (r > COND_POW) r = Math.pow((r + LINEAR_OFFSET) / (1 + LINEAR_OFFSET), POW_LINEAR); else r /= LINEAR_COEF; if (g > COND_POW) g = Math.pow((g + LINEAR_OFFSET) / (1 + LINEAR_OFFSET), POW_LINEAR); else g /= LINEAR_COEF; if (b > COND_POW) b = Math.pow((b + LINEAR_OFFSET) / (1 + LINEAR_OFFSET), POW_LINEAR); else b /= LINEAR_COEF; return [ r, g, b ];};/*** transform rgb to xyz* @param rgb - [r, g, b] r|g|b: 0..255* @param [skip] - skip validate* @returns TriColorChannels - [x, y, z]*/var transformRgbToXyz = (rgb, skip = false) => { if (!skip) rgb = validateColorComponents(rgb, { maxLength: TRIA, maxRange: MAX_RGB }); rgb = transformRgbToLinearRgb(rgb, true); return transformMatrix(MATRIX_L_RGB_TO_XYZ, rgb, true);};/*** transform linear rgb to rgb* @param rgb - [r, g, b] r|g|b: 0..1* @param [round] - round result* @returns TriColorChannels - [r, g, b] r|g|b: 0..255*/var transformLinearRgbToRgb = (rgb, round = false) => { let [r, g, b] = validateColorComponents(rgb, { maxLength: TRIA }); const COND_POW = 809 / 258400; if (r > COND_POW) r = Math.pow(r, 1 / POW_LINEAR) * (1 + LINEAR_OFFSET) - LINEAR_OFFSET; else r *= LINEAR_COEF; r *= MAX_RGB; if (g > COND_POW) g = Math.pow(g, 1 / POW_LINEAR) * (1 + LINEAR_OFFSET) - LINEAR_OFFSET; else g *= LINEAR_COEF; g *= MAX_RGB; if (b > COND_POW) b = Math.pow(b, 1 / POW_LINEAR) * (1 + LINEAR_OFFSET) - LINEAR_OFFSET; else b *= LINEAR_COEF; b *= MAX_RGB; return [ round ? Math.round(r) : r, round ? Math.round(g) : g, round ? Math.round(b) : b ];};/*** transform xyz to rgb* @param xyz - [x, y, z]* @param [skip] - skip validate* @returns TriColorChannels - [r, g, b] r|g|b: 0..255*/var transformXyzToRgb = (xyz, skip = false) => { if (!skip) xyz = validateColorComponents(xyz, { maxLength: TRIA, validateRange: false }); let [r, g, b] = transformMatrix(MATRIX_XYZ_TO_L_RGB, xyz, true); [r, g, b] = transformLinearRgbToRgb([ Math.min(Math.max(r, 0), 1), Math.min(Math.max(g, 0), 1), Math.min(Math.max(b, 0), 1) ], true); return [ r, g, b ];};/*** transform xyz to hsl* @param xyz - [x, y, z]* @param [skip] - skip validate* @returns TriColorChannels - [h, s, l]*/var transformXyzToHsl = (xyz, skip = false) => { const [rr, gg, bb] = transformXyzToRgb(xyz, skip); const r = rr / MAX_RGB; const g = gg / MAX_RGB; const b = bb / MAX_RGB; const max = Math.max(r, g, b); const min = Math.min(r, g, b); const d = max - min; const l = (max + min) * HALF * MAX_PCT; let h, s; if (Math.round(l) === 0 || Math.round(l) === MAX_PCT) { h = 0; s = 0; } else { s = d / (1 - Math.abs(max + min - 1)) * MAX_PCT; if (s === 0) h = 0; else { switch (max) { case r: h = (g - b) / d; break; case g: h = (b - r) / d + DUO; break; case b: default: h = (r - g) / d + QUAD; break; } h = h * SEXA % DEG; if (h < 0) h += DEG; } } return [ h, s, l ];};/*** transform xyz to hwb* @param xyz - [x, y, z]* @param [skip] - skip validate* @returns TriColorChannels - [h, w, b]*/var transformXyzToHwb = (xyz, skip = false) => { const [r, g, b] = transformXyzToRgb(xyz, skip); const wh = Math.min(r, g, b) / MAX_RGB; const bk = 1 - Math.max(r, g, b) / MAX_RGB; let h; if (wh + bk === 1) h = 0; else [h] = transformXyzToHsl(xyz); return [ h, wh * MAX_PCT, bk * MAX_PCT ];};/*** transform xyz to oklab* @param xyz - [x, y, z]* @param [skip] - skip validate* @returns TriColorChannels - [l, a, b]*/var transformXyzToOklab = (xyz, skip = false) => { if (!skip) xyz = validateColorComponents(xyz, { maxLength: TRIA, validateRange: false }); let [l, a, b] = transformMatrix(MATRIX_LMS_TO_OKLAB, transformMatrix(MATRIX_XYZ_TO_LMS, xyz, true).map((c) => Math.cbrt(c)), true); l = Math.min(Math.max(l, 0), 1); const lPct = Math.round(parseFloat(l.toFixed(QUAD)) * MAX_PCT); if (lPct === 0 || lPct === MAX_PCT) { a = 0; b = 0; } return [ l, a, b ];};/*** transform xyz to oklch* @param xyz - [x, y, z]* @param [skip] - skip validate* @returns TriColorChannels - [l, c, h]*/var transformXyzToOklch = (xyz, skip = false) => { const [l, a, b] = transformXyzToOklab(xyz, skip); let c, h; const lPct = Math.round(parseFloat(l.toFixed(QUAD)) * MAX_PCT); if (lPct === 0 || lPct === MAX_PCT) { c = 0; h = 0; } else { c = Math.max(Math.sqrt(Math.pow(a, POW_SQR) + Math.pow(b, POW_SQR)), 0); if (parseFloat(c.toFixed(QUAD)) === 0) h = 0; else { h = Math.atan2(b, a) * DEG_HALF / Math.PI; if (h < 0) h += DEG; } } return [ l, c, h ];};/*** transform xyz D50 to rgb* @param xyz - [x, y, z]* @param [skip] - skip validate* @returns TriColorChannels - [r, g, b] r|g|b: 0..255*/var transformXyzD50ToRgb = (xyz, skip = false) => { if (!skip) xyz = validateColorComponents(xyz, { maxLength: TRIA, validateRange: false }); return transformXyzToRgb(transformMatrix(MATRIX_D50_TO_D65, xyz, true), true);};/*** transform xyz-d50 to lab* @param xyz - [x, y, z]* @param [skip] - skip validate* @returns TriColorChannels - [l, a, b]*/var transformXyzD50ToLab = (xyz, skip = false) => { if (!skip) xyz = validateColorComponents(xyz, { maxLength: TRIA, validateRange: false }); const [f0, f1, f2] = xyz.map((val, i) => val / D50[i]).map((val) => val > LAB_EPSILON ? Math.cbrt(val) : (val * LAB_KAPPA + HEX) / LAB_L); const l = Math.min(Math.max(LAB_L * f1 - HEX, 0), MAX_PCT); let a, b; if (l === 0 || l === MAX_PCT) { a = 0; b = 0; } else { a = (f0 - f1) * LAB_A; b = (f1 - f2) * LAB_B; } return [ l, a, b ];};/*** transform xyz-d50 to lch* @param xyz - [x, y, z]* @param [skip] - skip validate* @returns TriColorChannels - [l, c, h]*/var transformXyzD50ToLch = (xyz, skip = false) => { const [l, a, b] = transformXyzD50ToLab(xyz, skip); let c, h; if (l === 0 || l === MAX_PCT) { c = 0; h = 0; } else { c = Math.max(Math.sqrt(Math.pow(a, POW_SQR) + Math.pow(b, POW_SQR)), 0); h = Math.atan2(b, a) * DEG_HALF / Math.PI; if (h < 0) h += DEG; } return [ l, c, h ];};/*** convert rgb to hex color* @param rgb - [r, g, b, alpha] r|g|b: 0..255 alpha: 0..1* @returns hex color*/var convertRgbToHex = (rgb) => { const [r, g, b, alpha] = validateColorComponents(rgb, { alpha: true, maxRange: MAX_RGB }); const rr = numberToHexString(r); const gg = numberToHexString(g); const bb = numberToHexString(b); const aa = numberToHexString(alpha * MAX_RGB); let hex; if (aa === "ff") hex = `#${rr}${gg}${bb}`; else hex = `#${rr}${gg}${bb}${aa}`; return hex;};/*** convert hex color to rgb* @param value - hex color value* @returns ColorChannels - [r, g, b, alpha] r|g|b: 0..255 alpha: 0..1*/var convertHexToRgb = (value) => { if (isString(value)) value = value.toLowerCase().trim(); else throw new TypeError(`${value} is not a string.`); if (!(/^#[\da-f]{6}$/.test(value) || /^#[\da-f]{3}$/.test(value) || /^#[\da-f]{8}$/.test(value) || /^#[\da-f]{4}$/.test(value))) throw new SyntaxError(`Invalid property value: ${value}`); const arr = []; if (/^#[\da-f]{3}$/.test(value)) { const [, r, g, b] = value.match(/^#([\da-f])([\da-f])([\da-f])$/); arr.push(parseInt(`${r}${r}`, HEX), parseInt(`${g}${g}`, HEX), parseInt(`${b}${b}`, HEX), 1); } else if (/^#[\da-f]{4}$/.test(value)) { const [, r, g, b, alpha] = value.match(/^#([\da-f])([\da-f])([\da-f])([\da-f])$/); arr.push(parseInt(`${r}${r}`, HEX), parseInt(`${g}${g}`, HEX), parseInt(`${b}${b}`, HEX), parseHexAlpha(`${alpha}${alpha}`)); } else if (/^#[\da-f]{8}$/.test(value)) { const [, r, g, b, alpha] = value.match(/^#([\da-f]{2})([\da-f]{2})([\da-f]{2})([\da-f]{2})$/); arr.push(parseInt(r, HEX), parseInt(g, HEX), parseInt(b, HEX), parseHexAlpha(alpha)); } else { const [, r, g, b] = value.match(/^#([\da-f]{2})([\da-f]{2})([\da-f]{2})$/); arr.push(parseInt(r, HEX), parseInt(g, HEX), parseInt(b, HEX), 1); } return arr;};/*** convert hex color to linear rgb* @param value - hex color value* @returns ColorChannels - [r, g, b, alpha] r|g|b|alpha: 0..1*/var convertHexToLinearRgb = (value) => { const [rr, gg, bb, alpha] = convertHexToRgb(value); const [r, g, b] = transformRgbToLinearRgb([ rr, gg, bb ], true); return [ r, g, b, alpha ];};/*** convert hex color to xyz* @param value - hex color value* @returns ColorChannels - [x, y, z, alpha]*/var convertHexToXyz = (value) => { const [r, g, b, alpha] = convertHexToLinearRgb(value); const [x, y, z] = transformMatrix(MATRIX_L_RGB_TO_XYZ, [ r, g, b ], true); return [ x, y, z, alpha ];};/*** parse rgb()* @param value - rgb color value* @param [opt] - options* @returns parsed color - ['rgb', r, g, b, alpha], '(empty)', NullObject*/var parseRgb = (value, opt = {}) => { if (isString(value)) value = value.toLowerCase().trim(); else throw new TypeError(`${value} is not a string.`); const { format = "", nullable = false } = opt; if (!REG_PARSE_RGB.test(value)) { const res = resolveInvalidColorValue(format, nullable); if (res instanceof NullObject) return res; if (isString(res)) return res; return res; } const [, val] = value.match(REG_PARSE_RGB); const [v1, v2, v3, v4 = ""] = val.match(/[^\s,/]+/g); let r, g, b; if (v1 === "none") r = 0; else { if (v1.endsWith("%")) r = parseFloat(v1) * MAX_RGB / MAX_PCT; else r = parseFloat(v1); r = Math.min(Math.max(roundToPrecision(r, OCT), 0), MAX_RGB); } if (v2 === "none") g = 0; else { if (v2.endsWith("%")) g = parseFloat(v2) * MAX_RGB / MAX_PCT; else g = parseFloat(v2); g = Math.min(Math.max(roundToPrecision(g, OCT), 0), MAX_RGB); } if (v3 === "none") b = 0; else { if (v3.endsWith("%")) b = parseFloat(v3) * MAX_RGB / MAX_PCT; else b = parseFloat(v3); b = Math.min(Math.max(roundToPrecision(b, OCT), 0), MAX_RGB); } const alpha = parseAlpha(v4); return [ "rgb", r, g, b, format === "mixValue" && v4 === "none" ? NONE : alpha ];};/*** parse hsl()* @param value - hsl color value* @param [opt] - options* @returns parsed color - ['rgb', r, g, b, alpha], '(empty)', NullObject*/var parseHsl = (value, opt = {}) => { if (isString(value)) value = value.trim(); else throw new TypeError(`${value} is not a string.`); const { format = "", nullable = false } = opt; if (!REG_HSL.test(value)) { const res = resolveInvalidColorValue(format, nullable); if (res instanceof NullObject) return res; if (isString(res)) return res; return res; } const [, val] = value.match(REG_HSL); const [v1, v2, v3, v4 = ""] = val.match(/[^\s,/]+/g); let h, s, l; if (v1 === "none") h = 0; else h = angleToDeg(v1); if (v2 === "none") s = 0; else s = Math.min(Math.max(parseFloat(v2), 0), MAX_PCT); if (v3 === "none") l = 0; else l = Math.min(Math.max(parseFloat(v3), 0), MAX_PCT); const alpha = parseAlpha(v4); if (format === "hsl") return [ format, v1 === "none" ? v1 : h, v2 === "none" ? v2 : s, v3 === "none" ? v3 : l, v4 === "none" ? v4 : alpha ]; h = h / DEG * DOZ; l /= MAX_PCT; const sa = s / MAX_PCT * Math.min(l, 1 - l); const rk = h % DOZ; const gk = (8 + h) % DOZ; const bk = (4 + h) % DOZ; const r = l - sa * Math.max(-1, Math.min(rk - TRIA, TRIA ** POW_SQR - rk, 1)); const g = l - sa * Math.max(-1, Math.min(gk - TRIA, TRIA ** POW_SQR - gk, 1)); const b = l - sa * Math.max(-1, Math.min(bk - TRIA, TRIA ** POW_SQR - bk, 1)); return [ "rgb", Math.min(Math.max(roundToPrecision(r * MAX_RGB, OCT), 0), MAX_RGB), Math.min(Math.max(roundToPrecision(g * MAX_RGB, OCT), 0), MAX_RGB), Math.min(Math.max(roundToPrecision(b * MAX_RGB, OCT), 0), MAX_RGB), alpha ];};/*** parse hwb()* @param value - hwb color value* @param [opt] - options* @returns parsed color - ['rgb', r, g, b, alpha], '(empty)', NullObject*/var parseHwb = (value, opt = {}) => { if (isString(value)) value = value.trim(); else throw new TypeError(`${value} is not a string.`); const { format = "", nullable = false } = opt; if (!REG_HWB.test(value)) { const res = resolveInvalidColorValue(format, nullable); if (res instanceof NullObject) return res; if (isString(res)) return res; return res; } const [, val] = value.match(REG_HWB); const [v1, v2, v3, v4 = ""] = val.match(/[^\s,/]+/g); let h, wh, bk; if (v1 === "none") h = 0; else h = angleToDeg(v1); if (v2 === "none") wh = 0; else wh = Math.min(Math.max(parseFloat(v2), 0), MAX_PCT) / MAX_PCT; if (v3 === "none") bk = 0; else bk = Math.min(Math.max(parseFloat(v3), 0), MAX_PCT) / MAX_PCT; const alpha = parseAlpha(v4); if (format === "hwb") return [ format, v1 === "none" ? v1 : h, v2 === "none" ? v2 : wh * MAX_PCT, v3 === "none" ? v3 : bk * MAX_PCT, v4 === "none" ? v4 : alpha ]; if (wh + bk >= 1) { const v = roundToPrecision(wh / (wh + bk) * MAX_RGB, OCT); return [ "rgb", v, v, v, alpha ]; } const factor = (1 - wh - bk) / MAX_RGB; let [, r, g, b] = parseHsl(`hsl(${h} 100 50)`); r = roundToPrecision((r * factor + wh) * MAX_RGB, OCT); g = roundToPrecision((g * factor + wh) * MAX_RGB, OCT); b = roundToPrecision((b * factor + wh) * MAX_RGB, OCT); return [ "rgb", Math.min(Math.max(r, 0), MAX_RGB), Math.min(Math.max(g, 0), MAX_RGB), Math.min(Math.max(b, 0), MAX_RGB), alpha ];};/*** parse lab()* @param value - lab color value* @param [opt] - options* @returns parsed color* - [xyz-d50, x, y, z, alpha], ['lab', l, a, b, alpha], '(empty)', NullObject*/var parseLab = (value, opt = {}) => { if (isString(value)) value = value.trim(); else throw new TypeError(`${value} is not a string.`); const { format = "", nullable = false } = opt; if (!REG_LAB.test(value)) { const res = resolveInvalidColorValue(format, nullable); if (res instanceof NullObject) return res; if (isString(res)) return res; return res; } const COEF_PCT = 1.25; const COND_POW = 8; const [, val] = value.match(REG_LAB); const [v1, v2, v3, v4 = ""] = val.match(/[^\s,/]+/g); let l, a, b; if (v1 === "none") l = 0; else { if (v1.endsWith("%")) { l = parseFloat(v1); if (l > MAX_PCT) l = MAX_PCT; } else l = parseFloat(v1); if (l < 0) l = 0; } if (v2 === "none") a = 0; else a = v2.endsWith("%") ? parseFloat(v2) * COEF_PCT : parseFloat(v2); if (v3 === "none") b = 0; else b = v3.endsWith("%") ? parseFloat(v3) * COEF_PCT : parseFloat(v3); const alpha = parseAlpha(v4); if (REG_SPEC.test(format)) return [ "lab", v1 === "none" ? v1 : roundToPrecision(l, HEX), v2 === "none" ? v2 : roundToPrecision(a, HEX), v3 === "none" ? v3 : roundToPrecision(b, HEX), v4 === "none" ? v4 : alpha ]; const fl = (l + HEX) / LAB_L; const fa = a / LAB_A + fl; const fb = fl - b / LAB_B; const powFl = Math.pow(fl, POW_CUBE); const powFa = Math.pow(fa, POW_CUBE); const powFb = Math.pow(fb, POW_CUBE); const [x, y, z] = [ powFa > LAB_EPSILON ? powFa : (fa * LAB_L - HEX) / LAB_KAPPA, l > COND_POW ? powFl : l / LAB_KAPPA, powFb > LAB_EPSILON ? powFb : (fb * LAB_L - HEX) / LAB_KAPPA ].map((val, i) => val * D50[i]); return [ "xyz-d50", roundToPrecision(x, HEX), roundToPrecision(y, HEX), roundToPrecision(z, HEX), alpha ];};/*** parse lch()* @param value - lch color value* @param [opt] - options* @returns parsed color* - ['xyz-d50', x, y, z, alpha], ['lch', l, c, h, alpha]* - '(empty)', NullObject*/var parseLch = (value, opt = {}) => { if (isString(value)) value = value.trim(); else throw new TypeError(`${value} is not a string.`); const { format = "", nullable = false } = opt; if (!REG_LCH.test(value)) { const res = resolveInvalidColorValue(format, nullable); if (res instanceof NullObject) return res; if (isString(res)) return res; return res; } const COEF_PCT = 1.5; const [, val] = value.match(REG_LCH); const [v1, v2, v3, v4 = ""] = val.match(/[^\s,/]+/g); let l, c, h; if (v1 === "none") l = 0; else { l = parseFloat(v1); if (l < 0) l = 0; } if (v2 === "none") c = 0; else c = v2.endsWith("%") ? parseFloat(v2) * COEF_PCT : parseFloat(v2); if (v3 === "none") h = 0; else h = angleToDeg(v3); const alpha = parseAlpha(v4); if (REG_SPEC.test(format)) return [ "lch", v1 === "none" ? v1 : roundToPrecision(l, HEX), v2 === "none" ? v2 : roundToPrecision(c, HEX), v3 === "none" ? v3 : roundToPrecision(h, HEX), v4 === "none" ? v4 : alpha ]; const a = c * Math.cos(h * Math.PI / DEG_HALF); const b = c * Math.sin(h * Math.PI / DEG_HALF); const [, x, y, z] = parseLab(`lab(${l} ${a} ${b})`); return [ "xyz-d50", roundToPrecision(x, HEX), roundToPrecision(y, HEX), roundToPrecision(z, HEX), alpha ];};/*** parse oklab()* @param value - oklab color value* @param [opt] - options* @returns parsed color* - ['xyz-d65', x, y, z, alpha], ['oklab', l, a, b, alpha]* - '(empty)', NullObject*/var parseOklab = (value, opt = {}) => { if (isString(value)) value = value.trim(); else throw new TypeError(`${value} is not a string.`); const { format = "", nullable = false } = opt; if (!REG_OKLAB.test(value)) { const res = resolveInvalidColorValue(format, nullable); if (res instanceof NullObject) return res; if (isString(res)) return res; return res; } const COEF_PCT = .4; const [, val] = value.match(REG_OKLAB); const [v1, v2, v3, v4 = ""] = val.match(/[^\s,/]+/g); let l, a, b; if (v1 === "none") l = 0; else { l = v1.endsWith("%") ? parseFloat(v1) / MAX_PCT : parseFloat(v1); if (l < 0) l = 0; } if (v2 === "none") a = 0; else if (v2.endsWith("%")) a = parseFloat(v2) * COEF_PCT / MAX_PCT; else a = parseFloat(v2); if (v3 === "none") b = 0; else if (v3.endsWith("%")) b = parseFloat(v3) * COEF_PCT / MAX_PCT; else b = parseFloat(v3); const alpha = parseAlpha(v4); if (REG_SPEC.test(format)) return [ "oklab", v1 === "none" ? v1 : roundToPrecision(l, HEX), v2 === "none" ? v2 : roundToPrecision(a, HEX), v3 === "none" ? v3 : roundToPrecision(b, HEX), v4 === "none" ? v4 : alpha ]; const [x, y, z] = transformMatrix(MATRIX_LMS_TO_XYZ, transformMatrix(MATRIX_OKLAB_TO_LMS, [ l, a, b ]).map((c) => Math.pow(c, POW_CUBE)), true); return [ "xyz-d65", roundToPrecision(x, HEX), roundToPrecision(y, HEX), roundToPrecision(z, HEX), alpha ];};/*** parse oklch()* @param value - oklch color value* @param [opt] - options* @returns parsed color* - ['xyz-d65', x, y, z, alpha], ['oklch', l, c, h, alpha]* - '(empty)', NullObject*/var parseOklch = (value, opt = {}) => { if (isString(value)) value = value.trim(); else throw new TypeError(`${value} is not a string.`); const { format = "", nullable = false } = opt; if (!REG_OKLCH.test(value)) { const res = resolveInvalidColorValue(format, nullable); if (res instanceof NullObject) return res; if (isString(res)) return res; return res; } const COEF_PCT = .4; const [, val] = value.match(REG_OKLCH); const [v1, v2, v3, v4 = ""] = val.match(/[^\s,/]+/g); let l, c, h; if (v1 === "none") l = 0; else { l = v1.endsWith("%") ? parseFloat(v1) / MAX_PCT : parseFloat(v1); if (l < 0) l = 0; } if (v2 === "none") c = 0; else { if (v2.endsWith("%")) c = parseFloat(v2) * COEF_PCT / MAX_PCT; else c = parseFloat(v2); if (c < 0) c = 0; } if (v3 === "none") h = 0; else h = angleToDeg(v3); const alpha = parseAlpha(v4); if (REG_SPEC.test(format)) return [ "oklch", v1 === "none" ? v1 : roundToPrecision(l, HEX), v2 === "none" ? v2 : roundToPrecision(c, HEX), v3 === "none" ? v3 : roundToPrecision(h, HEX), v4 === "none" ? v4 : alpha ]; const a = c * Math.cos(h * Math.PI / DEG_HALF); const b = c * Math.sin(h * Math.PI / DEG_HALF); const [x, y, z] = transformMatrix(MATRIX_LMS_TO_XYZ, transformMatrix(MATRIX_OKLAB_TO_LMS, [ l, a, b ]).map((cc) => Math.pow(cc, POW_CUBE)), true); return [ "xyz-d65", roundToPrecision(x, HEX), roundToPrecision(y, HEX), roundToPrecision(z, HEX), alpha ];};/*** parse color()* @param value - color function value* @param [opt] - options* @returns parsed color* - ['xyz-(d50|d65)', x, y, z, alpha], [cs, r, g, b, alpha]* - '(empty)', NullObject*/var parseColorFunc = (value, opt = {}) => { if (isString(value)) value = value.trim(); else throw new TypeError(`${value} is not a string.`); const { colorSpace = "", d50 = false, format = "", nullable = false } = opt; if (!REG_FN_COLOR.test(value)) { const res = resolveInvalidColorValue(format, nullable); if (res instanceof NullObject) return res; if (isString(res)) return res; return res; } const [, val] = value.match(REG_FN_COLOR); let [cs, v1, v2, v3, v4 = ""] = val.match(/[^\s,/]+/g); let r, g, b; if (cs === "xyz") cs = "xyz-d65"; if (v1 === "none") r = 0; else r = v1.endsWith("%") ? parseFloat(v1) / MAX_PCT : parseFloat(v1); if (v2 === "none") g = 0; else g = v2.endsWith("%") ? parseFloat(v2) / MAX_PCT : parseFloat(v2); if (v3 === "none") b = 0; else b = v3.endsWith("%") ? parseFloat(v3) / MAX_PCT : parseFloat(v3); const alpha = parseAlpha(v4); if (REG_SPEC.test(format) || format === "mixValue" && cs === colorSpace) return [ cs, v1 === "none" ? v1 : roundToPrecision(r, DEC), v2 === "none" ? v2 : roundToPrecision(g, DEC), v3 === "none" ? v3 : roundToPrecision(b, DEC), v4 === "none" ? v4 : alpha ]; let x = 0; let y = 0; let z = 0; if (cs === "srgb-linear") { [x, y, z] = transformMatrix(MATRIX_L_RGB_TO_XYZ, [ r, g, b ]); if (d50) [x, y, z] = transformMatrix(MATRIX_D65_TO_D50, [ x, y, z ], true); } else if (cs === "display-p3") { const linearRgb = transformRgbToLinearRgb([ r * MAX_RGB, g * MAX_RGB, b * MAX_RGB ]); [x, y, z] = transformMatrix(MATRIX_P3_TO_XYZ, linearRgb); if (d50) [x, y, z] = transformMatrix(MATRIX_D65_TO_D50, [ x, y, z ], true); } else if (cs === "rec2020") { const ALPHA = 1.09929682680944; const BETA = .018053968510807; const REC_COEF = .45; const rgb = [ r, g, b ].map((c) => { let cl; if (c < BETA * REC_COEF * DEC) cl = c / (REC_COEF * DEC); else cl = Math.pow((c + ALPHA - 1) / ALPHA, 1 / REC_COEF); return cl; }); [x, y, z] = transformMatrix(MATRIX_REC2020_TO_XYZ, rgb); if (d50) [x, y, z] = transformMatrix(MATRIX_D65_TO_D50, [ x, y, z ], true); } else if (cs === "a98-rgb") { const POW_A98 = 563 / 256; const rgb = [ r, g, b ].map((c) => { return Math.pow(c, POW_A98); }); [x, y, z] = transformMatrix(MATRIX_A98_TO_XYZ, rgb); if (d50) [x, y, z] = transformMatrix(MATRIX_D65_TO_D50, [ x, y, z ], true); } else if (cs === "prophoto-rgb") { const POW_PROPHOTO = 1.8; const rgb = [ r, g, b ].map((c) => { let cl; if (c > 1 / (HEX * DUO)) cl = Math.pow(c, POW_PROPHOTO); else cl = c / HEX; return cl; }); [x, y, z] = transformMatrix(MATRIX_PROPHOTO_TO_XYZ_D50, rgb); if (!d50) [x, y, z] = transformMatrix(MATRIX_D50_TO_D65, [ x, y, z ], true); } else if (/^xyz(?:-d(?:50|65))?$/.test(cs)) { [x, y, z] = [ r, g, b ]; if (cs === "xyz-d50") { if (!d50) [x, y, z] = transformMatrix(MATRIX_D50_TO_D65, [ x, y, z ]); } else if (d50) [x, y, z] = transformMatrix(MATRIX_D65_TO_D50, [ x, y, z ], true); } else { [x, y, z] = transformRgbToXyz([ r * MAX_RGB, g * MAX_RGB, b * MAX_RGB ]); if (d50) [x, y, z] = transformMatrix(MATRIX_D65_TO_D50, [ x, y, z ], true); } return [ d50 ? "xyz-d50" : "xyz-d65", roundToPrecision(x, HEX), roundToPrecision(y, HEX), roundToPrecision(z, HEX), format === "mixValue" && v4 === "none" ? v4 : alpha ];};/*** parse color value* @param value - CSS color value* @param [opt] - options* @returns parsed color* - ['xyz-(d50|d65)', x, y, z, alpha], ['rgb', r, g, b, alpha]* - value, '(empty)', NullObject*/var parseColorValue = (value, opt = {}) => { if (isString(value)) value = value.toLowerCase().trim(); else throw new TypeError(`${value} is not a string.`); const { d50 = false, format = "", nullable = false } = opt; if (!REG_COLOR.test(value)) { const res = resolveInvalidColorValue(format, nullable); if (res instanceof NullObject) return res; if (isString(res)) return res; return res; } let x = 0; let y = 0; let z = 0; let alpha = 0; if (REG_CURRENT.test(value)) { if (format === "computedValue") return [ "rgb", 0, 0, 0, 0 ]; if (format === "specifiedValue") return value; } else if (/^[a-z]+$/.test(value)) if (Object.hasOwn(NAMED_COLORS, value)) { if (format === "specifiedValue") return value; const [r, g, b] = NAMED_COLORS[value]; alpha = 1; if (format === "computedValue") return [ "rgb", r, g, b, alpha ]; [x, y, z] = transformRgbToXyz([ r, g, b ], true); if (d50) [x, y, z] = transformMatrix(MATRIX_D65_TO_D50, [ x, y, z ], true); } else switch (format) { case VAL_COMP: if (nullable && value !== "transparent") return new NullObject(); return [ "rgb", 0, 0, 0, 0 ]; case VAL_SPEC: if (value === "transparent") return value; return ""; case VAL_MIX: if (value === "transparent") return [ "rgb", 0, 0, 0, 0 ]; return new NullObject(); default: } else if (value[0] === "#") { if (REG_SPEC.test(format)) return ["rgb", ...convertHexToRgb(value)]; [x, y, z, alpha] = convertHexToXyz(value); if (d50) [x, y, z] = transformMatrix(MATRIX_D65_TO_D50, [ x, y, z ], true); } else if (value.startsWith("lab")) { if (REG_SPEC.test(format)) return parseLab(value, opt); [, x, y, z, alpha] = parseLab(value); if (!d50) [x, y, z] = transformMatrix(MATRIX_D50_TO_D65, [ x, y, z ], true); } else if (value.startsWith("lch")) { if (REG_SPEC.test(format)) return parseLch(value, opt); [, x, y, z, alpha] = parseLch(value); if (!d50) [x, y, z] = transformMatrix(MATRIX_D50_TO_D65, [ x, y, z ], true); } else if (value.startsWith("oklab")) { if (REG_SPEC.test(format)) return parseOklab(value, opt); [, x, y, z, alpha] = parseOklab(value); if (d50) [x, y, z] = transformMatrix(MATRIX_D65_TO_D50, [ x, y, z ], true); } else if (value.startsWith("oklch")) { if (REG_SPEC.test(format)) return parseOklch(value, opt); [, x, y, z, alpha] = parseOklch(value); if (d50) [x, y, z] = transformMatrix(MATRIX_D65_TO_D50, [ x, y, z ], true); } else { let r, g, b; if (value.startsWith("hsl")) [, r, g, b, alpha] = parseHsl(value); else if (value.startsWith("hwb")) [, r, g, b, alpha] = parseHwb(value); else [, r, g, b, alpha] = parseRgb(value, opt); if (REG_SPEC.test(format)) return [ "rgb", Math.round(r), Math.round(g), Math.round(b), alpha ]; [x, y, z] = transformRgbToXyz([ r, g, b ]); if (d50) [x, y, z] = transformMatrix(MATRIX_D65_TO_D50, [ x, y, z ], true); } return [ d50 ? "xyz-d50" : "xyz-d65", roundToPrecision(x, HEX), roundToPrecision(y, HEX), roundToPrecision(z, HEX), alpha ];};/*** resolve color value* @param value - CSS color value* @param [opt] - options* @returns resolved color* - [cs, v1, v2, v3, alpha], value, '(empty)', NullObject*/var resolveColorValue = (value, opt = {}) => { if (isString(value)) value = value.toLowerCase().trim(); else throw new TypeError(`${value} is not a string.`); const { colorSpace = "", format = "", nullable = false } = opt; const cacheKey = createCacheKey({ namespace: NAMESPACE, name: "resolveColorValue", value }, opt); const cachedResult = getCache(cacheKey); if (cachedResult instanceof CacheItem) { if (cachedResult.isNull) return cachedResult; const cachedItem = cachedResult.item; if (isString(cachedItem)) return cachedItem; return cachedItem; } if (!REG_COLOR.test(value)) { const res = resolveInvalidColorValue(format, nullable); if (res instanceof NullObject) { setCache(cacheKey, null); return res; } setCache(cacheKey, res); if (isString(res)) return res; return res; } let cs = ""; let r = 0; let g = 0; let b = 0; let alpha = 0; if (REG_CURRENT.test(value)) { if (format === "specifiedValue") { setCache(cacheKey, value); return value; } } else if (/^[a-z]+$/.test(value)) if (Object.hasOwn(NAMED_COLORS, value)) { if (format === "specifiedValue") { setCache(cacheKey, value); return value; } [r, g, b] = NAMED_COLORS[value]; alpha = 1; } else switch (format) { case VAL_SPEC: { if (value === "transparent") { setCache(cacheKey, value); return value; } const res = ""; setCache(cacheKey, res); return res; } case VAL_MIX: if (value === "transparent") { const res = [ "rgb", 0, 0, 0, 0 ]; setCache(cacheKey, res); return res; } setCache(cacheKey, null); return new NullObject(); case VAL_COMP: default: { if (nullable && value !== "transparent") { setCache(cacheKey, null); return new NullObject(); } const res = [ "rgb", 0, 0, 0, 0 ]; setCache(cacheKey, res); return res; } } else if (value[0] === "#") [r, g, b, alpha] = convertHexToRgb(value); else if (value.startsWith("hsl")) [, r, g, b, alpha] = parseHsl(value, opt); else if (value.startsWith("hwb")) [, r, g, b, alpha] = parseHwb(value, opt); else if (/^l(?:ab|ch)/.test(value)) { let x, y, z; if (value.startsWith("lab")) [cs, x, y, z, alpha] = parseLab(value, opt); else [cs, x, y, z, alpha] = parseLch(value, opt); if (REG_SPEC.test(format)) { const res = [ cs, x, y, z, alpha ]; setCache(cacheKey, res); return res; } [r, g, b] = transformXyzD50ToRgb([ x, y, z ]); } else if (/^okl(?:ab|ch)/.test(value)) { let x, y, z; if (value.startsWith("oklab")) [cs, x, y, z, alpha] = parseOklab(value, opt); else [cs, x, y, z, alpha] = parseOklch(value, opt); if (REG_SPEC.test(format)) { const res = [ cs, x, y, z, alpha ]; setCache(cacheKey, res); return res; } [r, g, b] = transformXyzToRgb([ x, y, z ]); } else [, r, g, b, alpha] = parseRgb(value, opt); if (format === "mixValue" && colorSpace === "srgb") { const res = [ "srgb", r / MAX_RGB, g / MAX_RGB, b / MAX_RGB, alpha ]; setCache(cacheKey, res); return res; } const res = [ "rgb", Math.round(r), Math.round(g), Math.round(b), alpha ]; setCache(cacheKey, res); return res;};/*** resolve color()* @param value - color function value* @param [opt] - options* @returns resolved color - [cs, v1, v2, v3, alpha], '(empty)', NullObject*/var resolveColorFunc = (value, opt = {}) => { if (isString(value)) value = value.toLowerCase().trim(); else throw new TypeError(`${value} is not a string.`); const { colorSpace = "", format = "", nullable = false } = opt; const cacheKey = createCacheKey({ namespace: NAMESPACE, name: "resolveColorFunc", value }, opt); const cachedResult = getCache(cacheKey); if (cachedResult instanceof CacheItem) { if (cachedResult.isNull) return cachedResult; const cachedItem = cachedResult.item; if (isString(cachedItem)) return cachedItem; return cachedItem; } if (!REG_FN_COLOR.test(value)) { const res = resolveInvalidColorValue(format, nullable); if (res instanceof NullObject) { setCache(cacheKey, null); return res; } setCache(cacheKey, res); if (isString(res)) return res; return res; } const [cs, v1, v2, v3, v4] = parseColorFunc(value, opt); if (REG_SPEC.test(format) || format === "mixValue" && cs === colorSpace) { const res = [ cs, v1, v2, v3, v4 ]; setCache(cacheKey, res); return res; } const x = parseFloat(`${v1}`); const y = parseFloat(`${v2}`); const z = parseFloat(`${v3}`); const alpha = parseAlpha(`${v4}`); const [r, g, b] = transformXyzToRgb([ x, y, z ], true); const res = [ "rgb", r, g, b, alpha ]; setCache(cacheKey, res); return res;};/*** convert color value to linear rgb* @param value - CSS color value* @param [opt] - options* @returns ColorChannels | NullObject - [r, g, b, alpha] r|g|b|alpha: 0..1*/var convertColorToLinearRgb = (value, opt = {}) => { if (isString(value)) value = value.trim(); else throw new TypeError(`${value} is not a string.`); const { colorSpace = "", format = "" } = opt; let cs = ""; let r, g, b, alpha, x, y, z; if (format === "mixValue") { let xyz; if (value.startsWith("color(")) xyz = parseColorFunc(value, opt); else xyz = parseColorValue(value, opt); if (xyz instanceof NullObject) return xyz; [cs, x, y, z, alpha] = xyz; if (cs === colorSpace) return [ x, y, z, alpha ]; [r, g, b] = transformMatrix(MATRIX_XYZ_TO_L_RGB, [ x, y, z ], true); } else if (value.startsWith("color(")) { const [, val] = value.match(REG_FN_COLOR); const [cs] = val.match(/[^\s,/]+/g); if (cs === "srgb-linear") [, r, g, b, alpha] = resolveColorFunc(value, { format: VAL_COMP }); else { [, x, y, z, alpha] = parseColorFunc(value); [r, g, b] = transformMatrix(MATRIX_XYZ_TO_L_RGB, [ x, y, z ], true); } } else { [, x, y, z, alpha] = parseColorValue(value); [r, g, b] = transformMatrix(MATRIX_XYZ_TO_L_RGB, [ x, y, z ], true); } return [ Math.min(Math.max(r, 0), 1), Math.min(Math.max(g, 0), 1), Math.min(Math.max(b, 0), 1), alpha ];};/*** convert color value to rgb* @param value - CSS color value* @param [opt] - options* @returns ColorChannels | NullObject* - [r, g, b, alpha] r|g|b: 0..255 alpha: 0..1*/var convertColorToRgb = (value, opt = {}) => { if (isString(value)) value = value.trim(); else throw new TypeError(`${value} is not a string.`); const { format = "" } = opt; let r, g, b, alpha; if (format === "mixValue") { let rgb; if (value.startsWith("color(")) rgb = resolveColorFunc(value, opt); else rgb = resolveColorValue(value, opt); if (rgb instanceof NullObject) return rgb; [, r, g, b, alpha] = rgb; } else if (value.startsWith("color(")) { const [, val] = value.match(REG_FN_COLOR); const [cs] = val.match(/[^\s,/]+/g); if (cs === "srgb") { [, r, g, b, alpha] = resolveColorFunc(value, { format: VAL_COMP }); r *= MAX_RGB; g *= MAX_RGB; b *= MAX_RGB; } else [, r, g, b, alpha] = resolveColorFunc(value); } else if (/^(?:ok)?l(?:ab|ch)/.test(value)) { [r, g, b, alpha] = convertColorToLinearRgb(value); [r, g, b] = transformLinearRgbToRgb([ r, g, b ]); } else [, r, g, b, alpha] = resolveColorValue(value, { format: VAL_COMP }); return [ r, g, b, alpha ];};/*** convert color value to xyz* @param value - CSS color value* @param [opt] - options* @returns ColorChannels | NullObject - [x, y, z, alpha]*/var convertColorToXyz = (value, opt = {}) => { if (isString(value)) value = value.trim(); else throw new TypeError(`${value} is not a string.`); const { d50 = false, format = "" } = opt; let x, y, z, alpha; if (format === "mixValue") { let xyz; if (value.startsWith("color(")) xyz = parseColorFunc(value, opt); else xyz = parseColorValue(value, opt); if (xyz instanceof NullObject) return xyz; [, x, y, z, alpha] = xyz; } else if (value.startsWith("color(")) { const [, val] = value.match(REG_FN_COLOR); const [cs] = val.match(/[^\s,/]+/g); if (d50) if (cs === "xyz-d50") [, x, y, z, alpha] = resolveColorFunc(value, { format: VAL_COMP }); else [, x, y, z, alpha] = parseColorFunc(value, opt); else if (/^xyz(?:-d65)?$/.test(cs)) [, x, y, z, alpha] = resolveColorFunc(value, { format: VAL_COMP }); else [, x, y, z, alpha] = parseColorFunc(value); } else [, x, y, z, alpha] = parseColorValue(value, opt); return [ x, y, z, alpha ];};/*** convert color value to hsl* @param value - CSS color value* @param [opt] - options* @returns ColorChannels | NullObject - [h, s, l, alpha], hue may be powerless*/var convertColorToHsl = (value, opt = {}) => { if (isString(value)) value = value.trim(); else throw new TypeError(`${value} is not a string.`); const { format = "" } = opt; let h, s, l, alpha; if (REG_HSL.test(value)) { [, h, s, l, alpha] = parseHsl(value, { format: "hsl" }); if (format === "hsl") return [ Math.round(h), Math.round(s), Math.round(l), alpha ]; return [ h, s, l, alpha ]; } let x, y, z; if (format === "mixValue") { let xyz; if (value.startsWith("color(")) xyz = parseColorFunc(value, opt); else xyz = parseColorValue(value, opt); if (xyz instanceof NullObject) return xyz; [, x, y, z, alpha] = xyz; } else if (value.startsWith("color(")) [, x, y, z, alpha] = parseColorFunc(value); else [, x, y, z, alpha] = parseColorValue(value); [h, s, l] = transformXyzToHsl([ x, y, z ], true); if (format === "hsl") return [ Math.round(h), Math.round(s), Math.round(l), alpha ]; return [ format === "mixValue" && s === 0 ? NONE : h, s, l, alpha ];};/*** convert color value to hwb* @param value - CSS color value* @param [opt] - options* @returns ColorChannels | NullObject - [h, w, b, alpha], hue may be powerless*/var convertColorToHwb = (value, opt = {}) => { if (isString(value)) value = value.trim(); else throw new TypeError(`${value} is not a string.`); const { format = "" } = opt; let h, w, b, alpha; if (REG_HWB.test(value)) { [, h, w, b, alpha] = parseHwb(value, { format: "hwb" }); if (format === "hwb") return [ Math.round(h), Math.round(w), Math.round(b), alpha ]; return [ h, w, b, alpha ]; } let x, y, z; if (format === "mixValue") { let xyz; if (value.startsWith("color(")) xyz = parseColorFunc(value, opt); else xyz = parseColorValue(value, opt); if (xyz instanceof NullObject) return xyz; [, x, y, z, alpha] = xyz; } else if (value.startsWith("color(")) [, x, y, z, alpha] = parseColorFunc(value); else [, x, y, z, alpha] = parseColorValue(value); [h, w, b] = transformXyzToHwb([ x, y, z ], true); if (format === "hwb") return [ Math.round(h), Math.round(w), Math.round(b), alpha ]; return [ format === "mixValue" && w + b >= 100 ? NONE : h, w, b, alpha ];};/*** convert color value to lab* @param value - CSS color value* @param [opt] - options* @returns ColorChannels | NullObject - [l, a, b, alpha]*/var convertColorToLab = (value, opt = {}) => { if (isString(value)) value = value.trim(); else throw new TypeError(`${value} is not a string.`); const { format = "" } = opt; let l, a, b, alpha; if (REG_LAB.test(value)) { [, l, a, b, alpha] = parseLab(value, { format: VAL_COMP }); return [ l, a, b, alpha ]; } let x, y, z; if (format === "mixValue") { let xyz; opt.d50 = true; if (value.startsWith("color(")) xyz = parseColorFunc(value, opt); else xyz = parseColorValue(value, opt); if (xyz instanceof NullObject) return xyz; [, x, y, z, alpha] = xyz; } else if (value.startsWith("color(")) [, x, y, z, alpha] = parseColorFunc(value, { d50: true }); else [, x, y, z, alpha] = parseColorValue(value, { d50: true }); [l, a, b] = transformXyzD50ToLab([ x, y, z ], true); return [ l, a, b, alpha ];};/*** convert color value to lch* @param value - CSS color value* @param [opt] - options* @returns ColorChannels | NullObject - [l, c, h, alpha], hue may be powerless*/var convertColorToLch = (value, opt = {}) => { if (isString(value)) value = value.trim(); else throw new TypeError(`${value} is not a string.`); const { format = "" } = opt; let l, c, h, alpha; if (REG_LCH.test(value)) { [, l, c, h, alpha] = parseLch(value, { format: VAL_COMP }); return [ l, c, h, alpha ]; } let x, y, z; if (format === "mixValue") { let xyz; opt.d50 = true; if (value.startsWith("color(")) xyz = parseColorFunc(value, opt); else xyz = parseColorValue(value, opt); if (xyz instanceof NullObject) return xyz; [, x, y, z, alpha] = xyz; } else if (value.startsWith("color(")) [, x, y, z, alpha] = parseColorFunc(value, { d50: true }); else [, x, y, z, alpha] = parseColorValue(value, { d50: true }); [l, c, h] = transformXyzD50ToLch([ x, y, z ], true); return [ l, c, format === "mixValue" && c === 0 ? NONE : h, alpha ];};/*** convert color value to oklab* @param value - CSS color value* @param [opt] - options* @returns ColorChannels | NullObject - [l, a, b, alpha]*/var convertColorToOklab = (value, opt = {}) => { if (isString(value)) value = value.trim(); else throw new TypeError(`${value} is not a string.`); const { format = "" } = opt; let l, a, b, alpha; if (REG_OKLAB.test(value)) { [, l, a, b, alpha] = parseOklab(value, { format: VAL_COMP }); return [ l, a, b, alpha ]; } let x, y, z; if (format === "mixValue") { let xyz; if (value.startsWith("color(")) xyz = parseColorFunc(value, opt); else xyz = parseColorValue(value, opt); if (xyz instanceof NullObject) return xyz; [, x, y, z, alpha] = xyz; } else if (value.startsWith("color(")) [, x, y, z, alpha] = parseColorFunc(value); else [, x, y, z, alpha] = parseColorValue(value); [l, a, b] = transformXyzToOklab([ x, y, z ], true); return [ l, a, b, alpha ];};/*** convert color value to oklch* @param value - CSS color value* @param [opt] - options* @returns ColorChannels | NullObject - [l, c, h, alpha], hue may be powerless*/var convertColorToOklch = (value, opt = {}) => { if (isString(value)) value = value.trim(); else throw new TypeError(`${value} is not a string.`); const { format = "" } = opt; let l, c, h, alpha; if (REG_OKLCH.test(value)) { [, l, c, h, alpha] = parseOklch(value, { format: VAL_COMP }); return [ l, c, h, alpha ]; } let x, y, z; if (format === "mixValue") { let xyz; if (value.startsWith("color(")) xyz = parseColorFunc(value, opt); else xyz = parseColorValue(value, opt); if (xyz instanceof NullObject) return xyz; [, x, y, z, alpha] = xyz; } else if (value.startsWith("color(")) [, x, y, z, alpha] = parseColorFunc(value); else [, x, y, z, alpha] = parseColorValue(value); [l, c, h] = transformXyzToOklch([ x, y, z ], true); return [ l, c, format === "mixValue" && c === 0 ? NONE : h, alpha ];};/*** resolve color-mix()* @param value - color-mix color value* @param [opt] - options* @returns resolved color - [cs, v1, v2, v3, alpha], '(empty)'*/var resolveColorMix = (value, opt = {}) => { if (isString(value)) value = value.toLowerCase().trim(); else throw new TypeError(`${value} is not a string.`); const { format = "", nullable = false } = opt; const cacheKey = createCacheKey({ namespace: NAMESPACE, name: "resolveColorMix", value }, opt); const cachedResult = getCache(cacheKey); if (cachedResult instanceof CacheItem) { if (cachedResult.isNull) return cachedResult; const cachedItem = cachedResult.item; if (isString(cachedItem)) return cachedItem; return cachedItem; } const nestedItems = []; let colorSpace = ""; let hueArc = ""; let colorA = ""; let pctA = ""; let colorB = ""; let pctB = ""; let parsed = false; if (!REG_MIX.test(value)) if (value.startsWith("color-mix(") && REG_MIX_NEST.test(value)) { const items = value.match(REG_MIX_NEST); for (const item of items) if (item) { let val = resolveColorMix(item, { format: format === "specifiedValue" ? format : VAL_COMP }); if (Array.isArray(val)) { const [cs, v1, v2, v3, v4] = val; if (v1 === 0 && v2 === 0 && v3 === 0 && v4 === 0) { value = ""; break; } if (REG_MIX_CS_RGB_XYZ.test(cs)) if (v4 === 1) val = `color(${cs} ${v1} ${v2} ${v3})`; else val = `color(${cs} ${v1} ${v2} ${v3} / ${v4})`; else if (v4 === 1) val = `${cs}(${v1} ${v2} ${v3})`; else val = `${cs}(${v1} ${v2} ${v3} / ${v4})`; } else if (!REG_MIX.test(val)) { value = ""; break; } nestedItems.push(val); value = value.replace(item, val); } if (!value) return cacheInvalidColorValue(cacheKey, format, nullable); } else if (value.startsWith("color-mix(") && value.endsWith(")") && value.includes("light-dark(")) { const [csPart = "", partA = "", partB = ""] = splitValue(value.replace(FN_MIX, "").replace(/\)$/, ""), { delimiter: "," }); const [colorPartA = "", pctPartA = ""] = splitValue(partA); const [colorPartB = "", pctPartB = ""] = splitValue(partB); const specifiedColorA = resolveColor(colorPartA, { format: VAL_SPEC }); const specifiedColorB = resolveColor(colorPartB, { format: VAL_SPEC }); if (REG_MIX_IN_CS.test(csPart) && specifiedColorA && specifiedColorB) if (format === "specifiedValue") { const [, cs] = csPart.match(REG_MIX_IN_CS); if (REG_CS_HUE.test(cs)) [, colorSpace, hueArc] = cs.match(REG_CS_HUE); else colorSpace = cs; colorA = specifiedColorA; if (pctPartA) pctA = pctPartA; colorB = specifiedColorB; if (pctPartB) pctB = pctPartB; value = value.replace(colorPartA, specifiedColorA).replace(colorPartB, specifiedColorB); parsed = true; } else { const resolvedColorA = resolveColor(colorPartA, opt); const resolvedColorB = resolveColor(colorPartB, opt); if (isString(resolvedColorA) && isString(resolvedColorB)) value = value.replace(colorPartA, resolvedColorA).replace(colorPartB, resolvedColorB); } else return cacheInvalidColorValue(cacheKey, format, nullable); } else return cacheInvalidColorValue(cacheKey, format, nullable); if (nestedItems.length && format === "specifiedValue") { const [, cs] = value.match(REG_MIX_START); if (REG_CS_HUE.test(cs)) [, colorSpace, hueArc] = cs.match(REG_CS_HUE); else colorSpace = cs; if (nestedItems.length === 2) { let [itemA, itemB] = nestedItems; itemA = itemA.replace(/(?=[()])/g, "\\"); itemB = itemB.replace(/(?=[()])/g, "\\"); const regA = new RegExp(`(${itemA})(?:\\s+(${PCT}))?`); const regB = new RegExp(`(${itemB})(?:\\s+(${PCT}))?`); [, colorA, pctA] = value.match(regA); [, colorB, pctB] = value.match(regB); } else { let [item] = nestedItems; item = item.replace(/(?=[()])/g, "\\"); const itemPart = `${item}(?:\\s+${PCT})?`; const itemPartCapt = `(${item})(?:\\s+(${PCT}))?`; const regItemPart = new RegExp(`^${itemPartCapt}$`); if (new RegExp(`${itemPartCapt}\\s*\\)$`).test(value)) { const reg = new RegExp(`(${SYN_MIX_PART})\\s*,\\s*(${itemPart})\\s*\\)$`); const [, colorPartA, colorPartB] = value.match(reg); [, colorA, pctA] = colorPartA.match(REG_MIX_COLOR_PART); [, colorB, pctB] = colorPartB.match(regItemPart); } else { const reg = new RegExp(`(${itemPart})\\s*,\\s*(${SYN_MIX_PART})\\s*\\)$`); const [, colorPartA, colorPartB] = value.match(reg); [, colorA, pctA] = colorPartA.match(regItemPart); [, colorB, pctB] = colorPartB.match(REG_MIX_COLOR_PART); } } } else if (!parsed) { const [, cs, colorPartA, colorPartB] = value.match(REG_MIX_CAPT); [, colorA, pctA] = colorPartA.match(REG_MIX_COLOR_PART); [, colorB, pctB] = colorPartB.match(REG_MIX_COLOR_PART); if (REG_CS_HUE.test(cs)) [, colorSpace, hueArc] = cs.match(REG_CS_HUE); else colorSpace = cs; } let pA, pB, m; if (pctA && pctB) { const p1 = parseFloat(pctA) / MAX_PCT; const p2 = parseFloat(pctB) / MAX_PCT; if (p1 < 0 || p1 > 1 || p2 < 0 || p2 > 1 || p1 === 0 && p2 === 0) return cacheInvalidColorValue(cacheKey, format, nullable); const factor = p1 + p2; pA = p1 / factor; pB = p2 / factor; m = factor < 1 ? factor : 1; } else { if (pctA) { pA = parseFloat(pctA) / MAX_PCT; if (pA < 0 || pA > 1) return cacheInvalidColorValue(cacheKey, format, nullable); pB = 1 - pA; } else if (pctB) { pB = parseFloat(pctB) / MAX_PCT; if (pB < 0 || pB > 1) return cacheInvalidColorValue(cacheKey, format, nullable); pA = 1 - pB; } else { pA = HALF; pB = HALF; } m = 1; } if (colorSpace === "xyz") colorSpace = "xyz-d65"; if (format === "specifiedValue") { let valueA = ""; let valueB = ""; if (colorA.startsWith("color-mix(") || colorA.startsWith("light-dark(")) valueA = colorA; else if (colorA.startsWith("color(")) { const [cs, v1, v2, v3, v4] = parseColorFunc(colorA, opt); if (v4 === 1) valueA = `color(${cs} ${v1} ${v2} ${v3})`; else valueA = `color(${cs} ${v1} ${v2} ${v3} / ${v4})`; } else { const val = parseColorValue(colorA, opt); if (Array.isArray(val)) { const [cs, v1, v2, v3, v4] = val; if (v4 === 1) if (cs === "rgb") valueA = `${cs}(${v1}, ${v2}, ${v3})`; else valueA = `${cs}(${v1} ${v2} ${v3})`; else if (cs === "rgb") valueA = `${cs}a(${v1}, ${v2}, ${v3}, ${v4})`; else valueA = `${cs}(${v1} ${v2} ${v3} / ${v4})`; } else { if (!isString(val) || !val) { setCache(cacheKey, ""); return ""; } valueA = val; } } if (colorB.startsWith("color-mix(") || colorB.startsWith("light-dark(")) valueB = colorB; else if (colorB.startsWith("color(")) { const [cs, v1, v2, v3, v4] = parseColorFunc(colorB, opt); if (v4 === 1) valueB = `color(${cs} ${v1} ${v2} ${v3})`; else valueB = `color(${cs} ${v1} ${v2} ${v3} / ${v4})`; } else { const val = parseColorValue(colorB, opt); if (Array.isArray(val)) { const [cs, v1, v2, v3, v4] = val; if (v4 === 1) if (cs === "rgb") valueB = `${cs}(${v1}, ${v2}, ${v3})`; else valueB = `${cs}(${v1} ${v2} ${v3})`; else if (cs === "rgb") valueB = `${cs}a(${v1}, ${v2}, ${v3}, ${v4})`; else valueB = `${cs}(${v1} ${v2} ${v3} / ${v4})`; } else { if (!isString(val) || !val) { setCache(cacheKey, ""); return ""; } valueB = val; } } if (pctA && pctB) { valueA += ` ${parseFloat(pctA)}%`; valueB += ` ${parseFloat(pctB)}%`; } else if (pctA) { const pA = parseFloat(pctA); if (pA !== MAX_PCT * HALF) valueA += ` ${pA}%`; } else if (pctB) { const pA = MAX_PCT - parseFloat(pctB); if (pA !== MAX_PCT * HALF) valueA += ` ${pA}%`; } if (hueArc) { const res = `color-mix(in ${colorSpace} ${hueArc} hue, ${valueA}, ${valueB})`; setCache(cacheKey, res); return res; } else { const res = `color-mix(in ${colorSpace}, ${valueA}, ${valueB})`; setCache(cacheKey, res); return res; } } let r = 0; let g = 0; let b = 0; let alpha = 0; if (/^srgb(?:-linear)?$/.test(colorSpace)) { let rgbA, rgbB; if (colorSpace === "srgb") { if (REG_CURRENT.test(colorA)) rgbA = [ NONE, NONE, NONE, NONE ]; else rgbA = convertColorToRgb(colorA, { colorSpace, format: VAL_MIX }); if (REG_CURRENT.test(colorB)) rgbB = [ NONE, NONE, NONE, NONE ]; else rgbB = convertColorToRgb(colorB, { colorSpace, format: VAL_MIX }); } else { if (REG_CURRENT.test(colorA)) rgbA = [ NONE, NONE, NONE, NONE ]; else rgbA = convertColorToLinearRgb(colorA, { colorSpace, format: VAL_MIX }); if (REG_CURRENT.test(colorB)) rgbB = [ NONE, NONE, NONE, NONE ]; else rgbB = convertColorToLinearRgb(colorB, { colorSpace, format: VAL_MIX }); } if (rgbA instanceof NullObject || rgbB instanceof NullObject) return cacheInvalidColorValue(cacheKey, format, nullable); const [rrA, ggA, bbA, aaA] = rgbA; const [rrB, ggB, bbB, aaB] = rgbB; const rNone = rrA === "none" && rrB === "none"; const gNone = ggA === "none" && ggB === "none"; const bNone = bbA === "none" && bbB === "none"; const alphaNone = aaA === "none" && aaB === "none"; const [[rA, gA, bA, alphaA], [rB, gB, bB, alphaB]] = normalizeColorComponents([ rrA, ggA, bbA, aaA ], [ rrB, ggB, bbB, aaB ], true); const factorA = alphaA * pA; const factorB = alphaB * pB; alpha = factorA + factorB; if (alpha === 0) { r = rA * pA + rB * pB; g = gA * pA + gB * pB; b = bA * pA + bB * pB; } else { r = (rA * factorA + rB * factorB) / alpha; g = (gA * factorA + gB * factorB) / alpha; b = (bA * factorA + bB * factorB) / alpha; alpha = parseFloat(alpha.toFixed(3)); } if (format === "computedValue") { const res = [ colorSpace, rNone ? NONE : roundToPrecision(r, HEX), gNone ? NONE : roundToPrecision(g, HEX), bNone ? NONE : roundToPrecision(b, HEX), alphaNone ? NONE : alpha * m ]; setCache(cacheKey, res); return res; } r *= MAX_RGB; g *= MAX_RGB; b *= MAX_RGB; } else if (REG_CS_XYZ.test(colorSpace)) { let xyzA, xyzB; if (REG_CURRENT.test(colorA)) xyzA = [ NONE, NONE, NONE, NONE ]; else xyzA = convertColorToXyz(colorA, { colorSpace, d50: colorSpace === "xyz-d50", format: VAL_MIX }); if (REG_CURRENT.test(colorB)) xyzB = [ NONE, NONE, NONE, NONE ]; else xyzB = convertColorToXyz(colorB, { colorSpace, d50: colorSpace === "xyz-d50", format: VAL_MIX }); if (xyzA instanceof NullObject || xyzB instanceof NullObject) return cacheInvalidColorValue(cacheKey, format, nullable); const [xxA, yyA, zzA, aaA] = xyzA; const [xxB, yyB, zzB, aaB] = xyzB; const xNone = xxA === "none" && xxB === "none"; const yNone = yyA === "none" && yyB === "none"; const zNone = zzA === "none" && zzB === "none"; const alphaNone = aaA === "none" && aaB === "none"; const [[xA, yA, zA, alphaA], [xB, yB, zB, alphaB]] = normalizeColorComponents([ xxA, yyA, zzA, aaA ], [ xxB, yyB, zzB, aaB ], true); const factorA = alphaA * pA; const factorB = alphaB * pB; alpha = factorA + factorB; let x, y, z; if (alpha === 0) { x = xA * pA + xB * pB; y = yA * pA + yB * pB; z = zA * pA + zB * pB; } else { x = (xA * factorA + xB * factorB) / alpha; y = (yA * factorA + yB * factorB) / alpha; z = (zA * factorA + zB * factorB) / alpha; alpha = parseFloat(alpha.toFixed(3)); } if (format === "computedValue") { const res = [ colorSpace, xNone ? NONE : roundToPrecision(x, HEX), yNone ? NONE : roundToPrecision(y, HEX), zNone ? NONE : roundToPrecision(z, HEX), alphaNone ? NONE : alpha * m ]; setCache(cacheKey, res); return res; } if (colorSpace === "xyz-d50") [r, g, b] = transformXyzD50ToRgb([ x, y, z ], true); else [r, g, b] = transformXyzToRgb([ x, y, z ], true); } else if (/^h(?:sl|wb)$/.test(colorSpace)) { let hslA, hslB; if (colorSpace === "hsl") { if (REG_CURRENT.test(colorA)) hslA = [ NONE, NONE, NONE, NONE ]; else hslA = convertColorToHsl(colorA, { colorSpace, format: VAL_MIX }); if (REG_CURRENT.test(colorB)) hslB = [ NONE, NONE, NONE, NONE ]; else hslB = convertColorToHsl(colorB, { colorSpace, format: VAL_MIX }); } else { if (REG_CURRENT.test(colorA)) hslA = [ NONE, NONE, NONE, NONE ]; else hslA = convertColorToHwb(colorA, { colorSpace, format: VAL_MIX }); if (REG_CURRENT.test(colorB)) hslB = [ NONE, NONE, NONE, NONE ]; else hslB = convertColorToHwb(colorB, { colorSpace, format: VAL_MIX }); } if (hslA instanceof NullObject || hslB instanceof NullObject) return cacheInvalidColorValue(cacheKey, format, nullable); const [hhA, ssA, llA, aaA] = hslA; const [hhB, ssB, llB, aaB] = hslB; const alphaNone = aaA === "none" && aaB === "none"; let [[hA, sA, lA, alphaA], [hB, sB, lB, alphaB]] = normalizeColorComponents([ hhA, ssA, llA, aaA ], [ hhB, ssB, llB, aaB ], true); if (hueArc) [hA, hB] = interpolateHue(hA, hB, hueArc); const factorA = alphaA * pA; const factorB = alphaB * pB; alpha = factorA + factorB; const h = (hA * pA + hB * pB) % DEG; let s, l; if (alpha === 0) { s = sA * pA + sB * pB; l = lA * pA + lB * pB; } else { s = (sA * factorA + sB * factorB) / alpha; l = (lA * factorA + lB * factorB) / alpha; alpha = parseFloat(alpha.toFixed(3)); } [r, g, b] = convertColorToRgb(`${colorSpace}(${h} ${s} ${l})`); if (format === "computedValue") { const res = [ "srgb", roundToPrecision(r / MAX_RGB, HEX), roundToPrecision(g / MAX_RGB, HEX), roundToPrecision(b / MAX_RGB, HEX), alphaNone ? NONE : alpha * m ]; setCache(cacheKey, res); return res; } } else if (/^(?:ok)?lch$/.test(colorSpace)) { let lchA, lchB; if (colorSpace === "lch") { if (REG_CURRENT.test(colorA)) lchA = [ NONE, NONE, NONE, NONE ]; else lchA = convertColorToLch(colorA, { colorSpace, format: VAL_MIX }); if (REG_CURRENT.test(colorB)) lchB = [ NONE, NONE, NONE, NONE ]; else lchB = convertColorToLch(colorB, { colorSpace, format: VAL_MIX }); } else { if (REG_CURRENT.test(colorA)) lchA = [ NONE, NONE, NONE, NONE ]; else lchA = convertColorToOklch(colorA, { colorSpace, format: VAL_MIX }); if (REG_CURRENT.test(colorB)) lchB = [ NONE, NONE, NONE, NONE ]; else lchB = convertColorToOklch(colorB, { colorSpace, format: VAL_MIX }); } if (lchA instanceof NullObject || lchB instanceof NullObject) return cacheInvalidColorValue(cacheKey, format, nullable); const [llA, ccA, hhA, aaA] = lchA; const [llB, ccB, hhB, aaB] = lchB; const lNone = llA === "none" && llB === "none"; const cNone = ccA === "none" && ccB === "none"; const hNone = hhA === "none" && hhB === "none"; const alphaNone = aaA === "none" && aaB === "none"; let [[lA, cA, hA, alphaA], [lB, cB, hB, alphaB]] = normalizeColorComponents([ llA, ccA, hhA, aaA ], [ llB, ccB, hhB, aaB ], true); if (hueArc) [hA, hB] = interpolateHue(hA, hB, hueArc); const factorA = alphaA * pA; const factorB = alphaB * pB; alpha = factorA + factorB; const h = (hA * pA + hB * pB) % DEG; let l, c; if (alpha === 0) { l = lA * pA + lB * pB; c = cA * pA + cB * pB; } else { l = (lA * factorA + lB * factorB) / alpha; c = (cA * factorA + cB * factorB) / alpha; alpha = parseFloat(alpha.toFixed(3)); } if (format === "computedValue") { const res = [ colorSpace, lNone ? NONE : roundToPrecision(l, HEX), cNone ? NONE : roundToPrecision(c, HEX), hNone ? NONE : roundToPrecision(h, HEX), alphaNone ? NONE : alpha * m ]; setCache(cacheKey, res); return res; } [, r, g, b] = resolveColorValue(`${colorSpace}(${l} ${c} ${h})`); } else { let labA, labB; if (colorSpace === "lab") { if (REG_CURRENT.test(colorA)) labA = [ NONE, NONE, NONE, NONE ]; else labA = convertColorToLab(colorA, { colorSpace, format: VAL_MIX }); if (REG_CURRENT.test(colorB)) labB = [ NONE, NONE, NONE, NONE ]; else labB = convertColorToLab(colorB, { colorSpace, format: VAL_MIX }); } else { if (REG_CURRENT.test(colorA)) labA = [ NONE, NONE, NONE, NONE ]; else labA = convertColorToOklab(colorA, { colorSpace, format: VAL_MIX }); if (REG_CURRENT.test(colorB)) labB = [ NONE, NONE, NONE, NONE ]; else labB = convertColorToOklab(colorB, { colorSpace, format: VAL_MIX }); } if (labA instanceof NullObject || labB instanceof NullObject) return cacheInvalidColorValue(cacheKey, format, nullable); const [llA, aaA, bbA, alA] = labA; const [llB, aaB, bbB, alB] = labB; const lNone = llA === "none" && llB === "none"; const aNone = aaA === "none" && aaB === "none"; const bNone = bbA === "none" && bbB === "none"; const alphaNone = alA === "none" && alB === "none"; const [[lA, aA, bA, alphaA], [lB, aB, bB, alphaB]] = normalizeColorComponents([ llA, aaA, bbA, alA ], [ llB, aaB, bbB, alB ], true); const factorA = alphaA * pA; const factorB = alphaB * pB; alpha = factorA + factorB; let l, aO, bO; if (alpha === 0) { l = lA * pA + lB * pB; aO = aA * pA + aB * pB; bO = bA * pA + bB * pB; } else { l = (lA * factorA + lB * factorB) / alpha; aO = (aA * factorA + aB * factorB) / alpha; bO = (bA * factorA + bB * factorB) / alpha; alpha = parseFloat(alpha.toFixed(3)); } if (format === "computedValue") { const res = [ colorSpace, lNone ? NONE : roundToPrecision(l, HEX), aNone ? NONE : roundToPrecision(aO, HEX), bNone ? NONE : roundToPrecision(bO, HEX), alphaNone ? NONE : alpha * m ]; setCache(cacheKey, res); return res; } [, r, g, b] = resolveColorValue(`${colorSpace}(${l} ${aO} ${bO})`); } const res = [ "rgb", Math.round(r), Math.round(g), Math.round(b), parseFloat((alpha * m).toFixed(3)) ]; setCache(cacheKey, res); return res;};//#endregionexport { NAMED_COLORS, convertColorToHsl, convertColorToHwb, convertColorToLab, convertColorToLch, convertColorToOklab, convertColorToOklch, convertColorToRgb, convertRgbToHex, numberToHexString, parseColorFunc, parseColorValue, resolveColorFunc, resolveColorMix, resolveColorValue };
//# sourceMappingURL=color.js.map.gitattributes-36
node_modules/.bin/acornDeleted-4
node_modules/.bin/baseline-browser-mappingDeleted-2
node_modules/.bin/browserslistDeleted-156
node_modules/.bin/crc32Deleted-105
node_modules/.bin/eslintDeleted-211
node_modules/.bin/eslint-config-prettierDeleted-240
node_modules/.bin/fxparserDeleted-97
node_modules/.bin/jitiDeleted-16
node_modules/.bin/js-yamlDeleted-117
node_modules/.bin/jsescDeleted-148
node_modules/.bin/json5Deleted-152
node_modules/.bin/mimeDeleted-46
node_modules/.bin/mswDeleted-35
node_modules/.bin/nanoidDeleted-55
node_modules/.bin/node-whichDeleted-52
node_modules/.bin/nodemonDeleted-16
node_modules/.bin/nodetouchDeleted-112
node_modules/.bin/parserDeleted-15
node_modules/.bin/pixelmatchDeleted-42
node_modules/.bin/prebuild-installDeleted-78
node_modules/.bin/prettierDeleted-80
node_modules/.bin/qrcodeDeleted-159
node_modules/.bin/rcDeleted-4
node_modules/.bin/rolldownDeleted-2
node_modules/.bin/rollupDeleted-1912
node_modules/.bin/semverDeleted-195
node_modules/.bin/specificityDeleted-14
node_modules/.bin/terserDeleted-21
node_modules/.bin/tldtsDeleted-21
node_modules/.bin/tree-killDeleted-14
node_modules/.bin/tscDeleted-2
node_modules/.bin/tsserverDeleted-2
node_modules/.bin/tsxDeleted
node_modules/.bin/update-browserslist-dbDeleted-42
node_modules/.bin/uuidDeleted-2
node_modules/.bin/viteDeleted-79
node_modules/.bin/vitestDeleted-2
node_modules/.bin/why-is-node-runningDeleted-18
node_modules/.package-lock.jsonDeleted
node_modules/@asamuzakjp/css-color/LICENSEDeleted-21
node_modules/@asamuzakjp/css-color/README.mdDeleted-316
node_modules/@asamuzakjp/css-color/dist/esm/index.d.tsDeleted-20
node_modules/@asamuzakjp/css-color/dist/esm/index.jsDeleted-29
node_modules/@asamuzakjp/css-color/dist/esm/index.js.mapDeleted-1
node_modules/@asamuzakjp/css-color/dist/esm/js/cache.d.tsDeleted-38
node_modules/@asamuzakjp/css-color/dist/esm/js/cache.jsDeleted-90
node_modules/@asamuzakjp/css-color/dist/esm/js/cache.js.mapDeleted-1
node_modules/@asamuzakjp/css-color/dist/esm/js/color.d.tsDeleted-537
node_modules/@asamuzakjp/css-color/dist/esm/js/color.jsDeleted-3534