modified: .github/pr-auto-fix.yml

This commit is contained in:
nikolai@vontainment.com 2025-08-14 00:05:37 -04:00
parent 3295239862
commit 06afc44ac5
3658 changed files with 518516 additions and 44 deletions

View file

@ -1,5 +1,9 @@
name: PR Lint and Auto-Fix
on:
pull_request:
types: [opened, synchronize, reopened]
permissions:
contents: write
pull-requests: write
@ -9,53 +13,62 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with: { fetch-depth: 0 }
with:
fetch-depth: 0
ref: ${{ github.head_ref }}
- uses: shivammathur/setup-php@v2
with:
php-version: '8.2'
tools: composer, phpcs, php-cs-fixer
tools: phpcs, php-cs-fixer
- uses: actions/cache@v4
with:
path: ~/.composer/cache
key: ${{ runner.os }}-composer-root-${{ hashFiles('composer.lock') }}
restore-keys: ${{ runner.os }}-composer-root-
- uses: actions/cache@v4
with:
path: ~/.composer/cache
key: ${{ runner.os }}-composer-updateapi-${{ hashFiles('update-api/composer.lock') }}
restore-keys: ${{ runner.os }}-composer-updateapi-
- name: Composer install (root)
if: hashFiles('composer.json') != ''
run: composer install --no-interaction --prefer-dist || true
- name: Composer install (update-api)
if: hashFiles('update-api/composer.json') != ''
working-directory: update-api
run: composer install --no-interaction --prefer-dist || true
# Fix PHP (WordPress in mu-plugins/, PSR-12 in update-api via phpcs.xml)
# PHPCBF only if installed in vendor/
- name: PHPCBF
run: |
if [ -f vendor/bin/phpcbf ]; then vendor/bin/phpcbf; else phpcbf; fi || true
if [ -f vendor/bin/phpcbf ]; then
chmod +x vendor/bin/phpcbf
vendor/bin/phpcbf || true
else
echo "PHPCBF not found in vendor/, skipping."
fi
# PHP-CS-Fixer only if installed in vendor/
- name: PHP-CS-Fixer
run: |
if [ -f vendor/bin/php-cs-fixer ]; then vendor/bin/php-cs-fixer fix --allow-risky=yes; else php-cs-fixer fix --allow-risky=yes; fi || true
if [ -f vendor/bin/php-cs-fixer ]; then
chmod +x vendor/bin/php-cs-fixer
vendor/bin/php-cs-fixer fix --allow-risky=yes || true
else
echo "PHP-CS-Fixer not found in vendor/, skipping."
fi
# JS/CSS fixes inside update-api/ only (adjust globs if needed)
# ESLint Fix
- name: ESLint Fix
run: npx eslint "update-api/**/*.js" --fix || true
- name: Stylelint Fix
run: npx stylelint "update-api/**/*.css" --fix || true
run: |
if [ -d node_modules ] && command -v npx > /dev/null; then
npx eslint "update-api/**/*.js" --fix || true
else
echo "node_modules or npx not found, skipping ESLint."
fi
- name: Create PR with fixes
uses: peter-evans/create-pull-request@v6
with:
branch: lint-fixes
title: "Lint auto-fixes"
commit-message: "chore: lint auto-fixes"
body: "Automated fixes across mu-plugins/ and update-api/"
# Stylelint Fix
- name: Stylelint Fix
run: |
if [ -d node_modules ] && command -v npx > /dev/null; then
npx stylelint "update-api/**/*.css" --fix || true
else
echo "node_modules or npx not found, skipping Stylelint."
fi
# Commit changes directly to the PR branch
- name: Commit fixes to PR branch
run: |
if [ -n "$(git status --porcelain)" ]; then
git config --global user.name "github-actions[bot]"
git config --global user.email "github-actions[bot]@users.noreply.github.com"
git add .
git commit -m "chore: auto-lint fixes"
git push origin HEAD:${{ github.head_ref }}
else
echo "No changes to commit."
fi

6
.gitignore vendored
View file

@ -1,9 +1,3 @@
# Ignore files and directories that should not be tracked by Git
.vscode/
*.code-workspace
# Ensure these files are ignored no matter where they are located
*/phpcs.xml
*/composer.lock
*/composer.json
*/vendor/

16
node_modules/.bin/acorn generated vendored Normal file
View file

@ -0,0 +1,16 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*|*MINGW*|*MSYS*)
if command -v cygpath > /dev/null 2>&1; then
basedir=`cygpath -w "$basedir"`
fi
;;
esac
if [ -x "$basedir/node" ]; then
exec "$basedir/node" "$basedir/../acorn/bin/acorn" "$@"
else
exec node "$basedir/../acorn/bin/acorn" "$@"
fi

17
node_modules/.bin/acorn.cmd generated vendored Normal file
View file

@ -0,0 +1,17 @@
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\acorn\bin\acorn" %*

28
node_modules/.bin/acorn.ps1 generated vendored Normal file
View file

@ -0,0 +1,28 @@
#!/usr/bin/env pwsh
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
$exe=""
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
# Fix case when both the Windows and Linux builds of Node
# are installed in the same directory
$exe=".exe"
}
$ret=0
if (Test-Path "$basedir/node$exe") {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "$basedir/node$exe" "$basedir/../acorn/bin/acorn" $args
} else {
& "$basedir/node$exe" "$basedir/../acorn/bin/acorn" $args
}
$ret=$LASTEXITCODE
} else {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "node$exe" "$basedir/../acorn/bin/acorn" $args
} else {
& "node$exe" "$basedir/../acorn/bin/acorn" $args
}
$ret=$LASTEXITCODE
}
exit $ret

16
node_modules/.bin/cssesc generated vendored Normal file
View file

@ -0,0 +1,16 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*|*MINGW*|*MSYS*)
if command -v cygpath > /dev/null 2>&1; then
basedir=`cygpath -w "$basedir"`
fi
;;
esac
if [ -x "$basedir/node" ]; then
exec "$basedir/node" "$basedir/../cssesc/bin/cssesc" "$@"
else
exec node "$basedir/../cssesc/bin/cssesc" "$@"
fi

17
node_modules/.bin/cssesc.cmd generated vendored Normal file
View file

@ -0,0 +1,17 @@
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\cssesc\bin\cssesc" %*

28
node_modules/.bin/cssesc.ps1 generated vendored Normal file
View file

@ -0,0 +1,28 @@
#!/usr/bin/env pwsh
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
$exe=""
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
# Fix case when both the Windows and Linux builds of Node
# are installed in the same directory
$exe=".exe"
}
$ret=0
if (Test-Path "$basedir/node$exe") {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "$basedir/node$exe" "$basedir/../cssesc/bin/cssesc" $args
} else {
& "$basedir/node$exe" "$basedir/../cssesc/bin/cssesc" $args
}
$ret=$LASTEXITCODE
} else {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "node$exe" "$basedir/../cssesc/bin/cssesc" $args
} else {
& "node$exe" "$basedir/../cssesc/bin/cssesc" $args
}
$ret=$LASTEXITCODE
}
exit $ret

16
node_modules/.bin/eslint generated vendored Normal file
View file

@ -0,0 +1,16 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*|*MINGW*|*MSYS*)
if command -v cygpath > /dev/null 2>&1; then
basedir=`cygpath -w "$basedir"`
fi
;;
esac
if [ -x "$basedir/node" ]; then
exec "$basedir/node" "$basedir/../eslint/bin/eslint.js" "$@"
else
exec node "$basedir/../eslint/bin/eslint.js" "$@"
fi

17
node_modules/.bin/eslint.cmd generated vendored Normal file
View file

@ -0,0 +1,17 @@
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\eslint\bin\eslint.js" %*

28
node_modules/.bin/eslint.ps1 generated vendored Normal file
View file

@ -0,0 +1,28 @@
#!/usr/bin/env pwsh
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
$exe=""
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
# Fix case when both the Windows and Linux builds of Node
# are installed in the same directory
$exe=".exe"
}
$ret=0
if (Test-Path "$basedir/node$exe") {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "$basedir/node$exe" "$basedir/../eslint/bin/eslint.js" $args
} else {
& "$basedir/node$exe" "$basedir/../eslint/bin/eslint.js" $args
}
$ret=$LASTEXITCODE
} else {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "node$exe" "$basedir/../eslint/bin/eslint.js" $args
} else {
& "node$exe" "$basedir/../eslint/bin/eslint.js" $args
}
$ret=$LASTEXITCODE
}
exit $ret

16
node_modules/.bin/js-yaml generated vendored Normal file
View file

@ -0,0 +1,16 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*|*MINGW*|*MSYS*)
if command -v cygpath > /dev/null 2>&1; then
basedir=`cygpath -w "$basedir"`
fi
;;
esac
if [ -x "$basedir/node" ]; then
exec "$basedir/node" "$basedir/../js-yaml/bin/js-yaml.js" "$@"
else
exec node "$basedir/../js-yaml/bin/js-yaml.js" "$@"
fi

17
node_modules/.bin/js-yaml.cmd generated vendored Normal file
View file

@ -0,0 +1,17 @@
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\js-yaml\bin\js-yaml.js" %*

28
node_modules/.bin/js-yaml.ps1 generated vendored Normal file
View file

@ -0,0 +1,28 @@
#!/usr/bin/env pwsh
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
$exe=""
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
# Fix case when both the Windows and Linux builds of Node
# are installed in the same directory
$exe=".exe"
}
$ret=0
if (Test-Path "$basedir/node$exe") {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "$basedir/node$exe" "$basedir/../js-yaml/bin/js-yaml.js" $args
} else {
& "$basedir/node$exe" "$basedir/../js-yaml/bin/js-yaml.js" $args
}
$ret=$LASTEXITCODE
} else {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "node$exe" "$basedir/../js-yaml/bin/js-yaml.js" $args
} else {
& "node$exe" "$basedir/../js-yaml/bin/js-yaml.js" $args
}
$ret=$LASTEXITCODE
}
exit $ret

16
node_modules/.bin/nanoid generated vendored Normal file
View file

@ -0,0 +1,16 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*|*MINGW*|*MSYS*)
if command -v cygpath > /dev/null 2>&1; then
basedir=`cygpath -w "$basedir"`
fi
;;
esac
if [ -x "$basedir/node" ]; then
exec "$basedir/node" "$basedir/../nanoid/bin/nanoid.cjs" "$@"
else
exec node "$basedir/../nanoid/bin/nanoid.cjs" "$@"
fi

17
node_modules/.bin/nanoid.cmd generated vendored Normal file
View file

@ -0,0 +1,17 @@
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\nanoid\bin\nanoid.cjs" %*

28
node_modules/.bin/nanoid.ps1 generated vendored Normal file
View file

@ -0,0 +1,28 @@
#!/usr/bin/env pwsh
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
$exe=""
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
# Fix case when both the Windows and Linux builds of Node
# are installed in the same directory
$exe=".exe"
}
$ret=0
if (Test-Path "$basedir/node$exe") {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "$basedir/node$exe" "$basedir/../nanoid/bin/nanoid.cjs" $args
} else {
& "$basedir/node$exe" "$basedir/../nanoid/bin/nanoid.cjs" $args
}
$ret=$LASTEXITCODE
} else {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "node$exe" "$basedir/../nanoid/bin/nanoid.cjs" $args
} else {
& "node$exe" "$basedir/../nanoid/bin/nanoid.cjs" $args
}
$ret=$LASTEXITCODE
}
exit $ret

16
node_modules/.bin/node-which generated vendored Normal file
View file

@ -0,0 +1,16 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*|*MINGW*|*MSYS*)
if command -v cygpath > /dev/null 2>&1; then
basedir=`cygpath -w "$basedir"`
fi
;;
esac
if [ -x "$basedir/node" ]; then
exec "$basedir/node" "$basedir/../which/bin/node-which" "$@"
else
exec node "$basedir/../which/bin/node-which" "$@"
fi

17
node_modules/.bin/node-which.cmd generated vendored Normal file
View file

@ -0,0 +1,17 @@
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\which\bin\node-which" %*

28
node_modules/.bin/node-which.ps1 generated vendored Normal file
View file

@ -0,0 +1,28 @@
#!/usr/bin/env pwsh
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
$exe=""
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
# Fix case when both the Windows and Linux builds of Node
# are installed in the same directory
$exe=".exe"
}
$ret=0
if (Test-Path "$basedir/node$exe") {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "$basedir/node$exe" "$basedir/../which/bin/node-which" $args
} else {
& "$basedir/node$exe" "$basedir/../which/bin/node-which" $args
}
$ret=$LASTEXITCODE
} else {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "node$exe" "$basedir/../which/bin/node-which" $args
} else {
& "node$exe" "$basedir/../which/bin/node-which" $args
}
$ret=$LASTEXITCODE
}
exit $ret

16
node_modules/.bin/stylelint generated vendored Normal file
View file

@ -0,0 +1,16 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*|*MINGW*|*MSYS*)
if command -v cygpath > /dev/null 2>&1; then
basedir=`cygpath -w "$basedir"`
fi
;;
esac
if [ -x "$basedir/node" ]; then
exec "$basedir/node" "$basedir/../stylelint/bin/stylelint.mjs" "$@"
else
exec node "$basedir/../stylelint/bin/stylelint.mjs" "$@"
fi

17
node_modules/.bin/stylelint.cmd generated vendored Normal file
View file

@ -0,0 +1,17 @@
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\stylelint\bin\stylelint.mjs" %*

28
node_modules/.bin/stylelint.ps1 generated vendored Normal file
View file

@ -0,0 +1,28 @@
#!/usr/bin/env pwsh
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
$exe=""
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
# Fix case when both the Windows and Linux builds of Node
# are installed in the same directory
$exe=".exe"
}
$ret=0
if (Test-Path "$basedir/node$exe") {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "$basedir/node$exe" "$basedir/../stylelint/bin/stylelint.mjs" $args
} else {
& "$basedir/node$exe" "$basedir/../stylelint/bin/stylelint.mjs" $args
}
$ret=$LASTEXITCODE
} else {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "node$exe" "$basedir/../stylelint/bin/stylelint.mjs" $args
} else {
& "node$exe" "$basedir/../stylelint/bin/stylelint.mjs" $args
}
$ret=$LASTEXITCODE
}
exit $ret

2254
node_modules/.package-lock.json generated vendored Normal file

File diff suppressed because it is too large Load diff

22
node_modules/@babel/code-frame/LICENSE generated vendored Normal file
View file

@ -0,0 +1,22 @@
MIT License
Copyright (c) 2014-present Sebastian McKenzie and other contributors
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

19
node_modules/@babel/code-frame/README.md generated vendored Normal file
View file

@ -0,0 +1,19 @@
# @babel/code-frame
> Generate errors that contain a code frame that point to source locations.
See our website [@babel/code-frame](https://babeljs.io/docs/babel-code-frame) for more information.
## Install
Using npm:
```sh
npm install --save-dev @babel/code-frame
```
or using yarn:
```sh
yarn add @babel/code-frame --dev
```

216
node_modules/@babel/code-frame/lib/index.js generated vendored Normal file
View file

@ -0,0 +1,216 @@
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var picocolors = require('picocolors');
var jsTokens = require('js-tokens');
var helperValidatorIdentifier = require('@babel/helper-validator-identifier');
function isColorSupported() {
return (typeof process === "object" && (process.env.FORCE_COLOR === "0" || process.env.FORCE_COLOR === "false") ? false : picocolors.isColorSupported
);
}
const compose = (f, g) => v => f(g(v));
function buildDefs(colors) {
return {
keyword: colors.cyan,
capitalized: colors.yellow,
jsxIdentifier: colors.yellow,
punctuator: colors.yellow,
number: colors.magenta,
string: colors.green,
regex: colors.magenta,
comment: colors.gray,
invalid: compose(compose(colors.white, colors.bgRed), colors.bold),
gutter: colors.gray,
marker: compose(colors.red, colors.bold),
message: compose(colors.red, colors.bold),
reset: colors.reset
};
}
const defsOn = buildDefs(picocolors.createColors(true));
const defsOff = buildDefs(picocolors.createColors(false));
function getDefs(enabled) {
return enabled ? defsOn : defsOff;
}
const sometimesKeywords = new Set(["as", "async", "from", "get", "of", "set"]);
const NEWLINE$1 = /\r\n|[\n\r\u2028\u2029]/;
const BRACKET = /^[()[\]{}]$/;
let tokenize;
{
const JSX_TAG = /^[a-z][\w-]*$/i;
const getTokenType = function (token, offset, text) {
if (token.type === "name") {
if (helperValidatorIdentifier.isKeyword(token.value) || helperValidatorIdentifier.isStrictReservedWord(token.value, true) || sometimesKeywords.has(token.value)) {
return "keyword";
}
if (JSX_TAG.test(token.value) && (text[offset - 1] === "<" || text.slice(offset - 2, offset) === "</")) {
return "jsxIdentifier";
}
if (token.value[0] !== token.value[0].toLowerCase()) {
return "capitalized";
}
}
if (token.type === "punctuator" && BRACKET.test(token.value)) {
return "bracket";
}
if (token.type === "invalid" && (token.value === "@" || token.value === "#")) {
return "punctuator";
}
return token.type;
};
tokenize = function* (text) {
let match;
while (match = jsTokens.default.exec(text)) {
const token = jsTokens.matchToToken(match);
yield {
type: getTokenType(token, match.index, text),
value: token.value
};
}
};
}
function highlight(text) {
if (text === "") return "";
const defs = getDefs(true);
let highlighted = "";
for (const {
type,
value
} of tokenize(text)) {
if (type in defs) {
highlighted += value.split(NEWLINE$1).map(str => defs[type](str)).join("\n");
} else {
highlighted += value;
}
}
return highlighted;
}
let deprecationWarningShown = false;
const NEWLINE = /\r\n|[\n\r\u2028\u2029]/;
function getMarkerLines(loc, source, opts) {
const startLoc = Object.assign({
column: 0,
line: -1
}, loc.start);
const endLoc = Object.assign({}, startLoc, loc.end);
const {
linesAbove = 2,
linesBelow = 3
} = opts || {};
const startLine = startLoc.line;
const startColumn = startLoc.column;
const endLine = endLoc.line;
const endColumn = endLoc.column;
let start = Math.max(startLine - (linesAbove + 1), 0);
let end = Math.min(source.length, endLine + linesBelow);
if (startLine === -1) {
start = 0;
}
if (endLine === -1) {
end = source.length;
}
const lineDiff = endLine - startLine;
const markerLines = {};
if (lineDiff) {
for (let i = 0; i <= lineDiff; i++) {
const lineNumber = i + startLine;
if (!startColumn) {
markerLines[lineNumber] = true;
} else if (i === 0) {
const sourceLength = source[lineNumber - 1].length;
markerLines[lineNumber] = [startColumn, sourceLength - startColumn + 1];
} else if (i === lineDiff) {
markerLines[lineNumber] = [0, endColumn];
} else {
const sourceLength = source[lineNumber - i].length;
markerLines[lineNumber] = [0, sourceLength];
}
}
} else {
if (startColumn === endColumn) {
if (startColumn) {
markerLines[startLine] = [startColumn, 0];
} else {
markerLines[startLine] = true;
}
} else {
markerLines[startLine] = [startColumn, endColumn - startColumn];
}
}
return {
start,
end,
markerLines
};
}
function codeFrameColumns(rawLines, loc, opts = {}) {
const shouldHighlight = opts.forceColor || isColorSupported() && opts.highlightCode;
const defs = getDefs(shouldHighlight);
const lines = rawLines.split(NEWLINE);
const {
start,
end,
markerLines
} = getMarkerLines(loc, lines, opts);
const hasColumns = loc.start && typeof loc.start.column === "number";
const numberMaxWidth = String(end).length;
const highlightedLines = shouldHighlight ? highlight(rawLines) : rawLines;
let frame = highlightedLines.split(NEWLINE, end).slice(start, end).map((line, index) => {
const number = start + 1 + index;
const paddedNumber = ` ${number}`.slice(-numberMaxWidth);
const gutter = ` ${paddedNumber} |`;
const hasMarker = markerLines[number];
const lastMarkerLine = !markerLines[number + 1];
if (hasMarker) {
let markerLine = "";
if (Array.isArray(hasMarker)) {
const markerSpacing = line.slice(0, Math.max(hasMarker[0] - 1, 0)).replace(/[^\t]/g, " ");
const numberOfMarkers = hasMarker[1] || 1;
markerLine = ["\n ", defs.gutter(gutter.replace(/\d/g, " ")), " ", markerSpacing, defs.marker("^").repeat(numberOfMarkers)].join("");
if (lastMarkerLine && opts.message) {
markerLine += " " + defs.message(opts.message);
}
}
return [defs.marker(">"), defs.gutter(gutter), line.length > 0 ? ` ${line}` : "", markerLine].join("");
} else {
return ` ${defs.gutter(gutter)}${line.length > 0 ? ` ${line}` : ""}`;
}
}).join("\n");
if (opts.message && !hasColumns) {
frame = `${" ".repeat(numberMaxWidth + 1)}${opts.message}\n${frame}`;
}
if (shouldHighlight) {
return defs.reset(frame);
} else {
return frame;
}
}
function index (rawLines, lineNumber, colNumber, opts = {}) {
if (!deprecationWarningShown) {
deprecationWarningShown = true;
const message = "Passing lineNumber and colNumber is deprecated to @babel/code-frame. Please use `codeFrameColumns`.";
if (process.emitWarning) {
process.emitWarning(message, "DeprecationWarning");
} else {
const deprecationError = new Error(message);
deprecationError.name = "DeprecationWarning";
console.warn(new Error(message));
}
}
colNumber = Math.max(colNumber, 0);
const location = {
start: {
column: colNumber,
line: lineNumber
}
};
return codeFrameColumns(rawLines, location, opts);
}
exports.codeFrameColumns = codeFrameColumns;
exports.default = index;
exports.highlight = highlight;
//# sourceMappingURL=index.js.map

1
node_modules/@babel/code-frame/lib/index.js.map generated vendored Normal file

File diff suppressed because one or more lines are too long

31
node_modules/@babel/code-frame/package.json generated vendored Normal file
View file

@ -0,0 +1,31 @@
{
"name": "@babel/code-frame",
"version": "7.27.1",
"description": "Generate errors that contain a code frame that point to source locations.",
"author": "The Babel Team (https://babel.dev/team)",
"homepage": "https://babel.dev/docs/en/next/babel-code-frame",
"bugs": "https://github.com/babel/babel/issues?utf8=%E2%9C%93&q=is%3Aissue+is%3Aopen",
"license": "MIT",
"publishConfig": {
"access": "public"
},
"repository": {
"type": "git",
"url": "https://github.com/babel/babel.git",
"directory": "packages/babel-code-frame"
},
"main": "./lib/index.js",
"dependencies": {
"@babel/helper-validator-identifier": "^7.27.1",
"js-tokens": "^4.0.0",
"picocolors": "^1.1.1"
},
"devDependencies": {
"import-meta-resolve": "^4.1.0",
"strip-ansi": "^4.0.0"
},
"engines": {
"node": ">=6.9.0"
},
"type": "commonjs"
}

View file

@ -0,0 +1,22 @@
MIT License
Copyright (c) 2014-present Sebastian McKenzie and other contributors
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View file

@ -0,0 +1,19 @@
# @babel/helper-validator-identifier
> Validate identifier/keywords name
See our website [@babel/helper-validator-identifier](https://babeljs.io/docs/babel-helper-validator-identifier) for more information.
## Install
Using npm:
```sh
npm install --save @babel/helper-validator-identifier
```
or using yarn:
```sh
yarn add @babel/helper-validator-identifier
```

View file

@ -0,0 +1,70 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.isIdentifierChar = isIdentifierChar;
exports.isIdentifierName = isIdentifierName;
exports.isIdentifierStart = isIdentifierStart;
let nonASCIIidentifierStartChars = "\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0560-\u0588\u05d0-\u05ea\u05ef-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u0860-\u086a\u0870-\u0887\u0889-\u088e\u08a0-\u08c9\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u09fc\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c5d\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cdd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d04-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e86-\u0e8a\u0e8c-\u0ea3\u0ea5\u0ea7-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u1711\u171f-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1878\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4c\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c8a\u1c90-\u1cba\u1cbd-\u1cbf\u1ce9-\u1cec\u1cee-\u1cf3\u1cf5\u1cf6\u1cfa\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312f\u3131-\u318e\u31a0-\u31bf\u31f0-\u31ff\u3400-\u4dbf\u4e00-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7cd\ua7d0\ua7d1\ua7d3\ua7d5-\ua7dc\ua7f2-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua8fe\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab69\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc";
let nonASCIIidentifierChars = "\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u07fd\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u0897-\u089f\u08ca-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u09fe\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0afa-\u0aff\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b55-\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c04\u0c3c\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0cf3\u0d00-\u0d03\u0d3b\u0d3c\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d81-\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0ebc\u0ec8-\u0ece\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1715\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u180f-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1abf-\u1ace\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf4\u1cf7-\u1cf9\u1dc0-\u1dff\u200c\u200d\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\u30fb\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua82c\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua8ff-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f\uff65";
const nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
const nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
nonASCIIidentifierStartChars = nonASCIIidentifierChars = null;
const astralIdentifierStartCodes = [0, 11, 2, 25, 2, 18, 2, 1, 2, 14, 3, 13, 35, 122, 70, 52, 268, 28, 4, 48, 48, 31, 14, 29, 6, 37, 11, 29, 3, 35, 5, 7, 2, 4, 43, 157, 19, 35, 5, 35, 5, 39, 9, 51, 13, 10, 2, 14, 2, 6, 2, 1, 2, 10, 2, 14, 2, 6, 2, 1, 4, 51, 13, 310, 10, 21, 11, 7, 25, 5, 2, 41, 2, 8, 70, 5, 3, 0, 2, 43, 2, 1, 4, 0, 3, 22, 11, 22, 10, 30, 66, 18, 2, 1, 11, 21, 11, 25, 71, 55, 7, 1, 65, 0, 16, 3, 2, 2, 2, 28, 43, 28, 4, 28, 36, 7, 2, 27, 28, 53, 11, 21, 11, 18, 14, 17, 111, 72, 56, 50, 14, 50, 14, 35, 39, 27, 10, 22, 251, 41, 7, 1, 17, 2, 60, 28, 11, 0, 9, 21, 43, 17, 47, 20, 28, 22, 13, 52, 58, 1, 3, 0, 14, 44, 33, 24, 27, 35, 30, 0, 3, 0, 9, 34, 4, 0, 13, 47, 15, 3, 22, 0, 2, 0, 36, 17, 2, 24, 20, 1, 64, 6, 2, 0, 2, 3, 2, 14, 2, 9, 8, 46, 39, 7, 3, 1, 3, 21, 2, 6, 2, 1, 2, 4, 4, 0, 19, 0, 13, 4, 31, 9, 2, 0, 3, 0, 2, 37, 2, 0, 26, 0, 2, 0, 45, 52, 19, 3, 21, 2, 31, 47, 21, 1, 2, 0, 185, 46, 42, 3, 37, 47, 21, 0, 60, 42, 14, 0, 72, 26, 38, 6, 186, 43, 117, 63, 32, 7, 3, 0, 3, 7, 2, 1, 2, 23, 16, 0, 2, 0, 95, 7, 3, 38, 17, 0, 2, 0, 29, 0, 11, 39, 8, 0, 22, 0, 12, 45, 20, 0, 19, 72, 200, 32, 32, 8, 2, 36, 18, 0, 50, 29, 113, 6, 2, 1, 2, 37, 22, 0, 26, 5, 2, 1, 2, 31, 15, 0, 328, 18, 16, 0, 2, 12, 2, 33, 125, 0, 80, 921, 103, 110, 18, 195, 2637, 96, 16, 1071, 18, 5, 26, 3994, 6, 582, 6842, 29, 1763, 568, 8, 30, 18, 78, 18, 29, 19, 47, 17, 3, 32, 20, 6, 18, 433, 44, 212, 63, 129, 74, 6, 0, 67, 12, 65, 1, 2, 0, 29, 6135, 9, 1237, 42, 9, 8936, 3, 2, 6, 2, 1, 2, 290, 16, 0, 30, 2, 3, 0, 15, 3, 9, 395, 2309, 106, 6, 12, 4, 8, 8, 9, 5991, 84, 2, 70, 2, 1, 3, 0, 3, 1, 3, 3, 2, 11, 2, 0, 2, 6, 2, 64, 2, 3, 3, 7, 2, 6, 2, 27, 2, 3, 2, 4, 2, 0, 4, 6, 2, 339, 3, 24, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 7, 1845, 30, 7, 5, 262, 61, 147, 44, 11, 6, 17, 0, 322, 29, 19, 43, 485, 27, 229, 29, 3, 0, 496, 6, 2, 3, 2, 1, 2, 14, 2, 196, 60, 67, 8, 0, 1205, 3, 2, 26, 2, 1, 2, 0, 3, 0, 2, 9, 2, 3, 2, 0, 2, 0, 7, 0, 5, 0, 2, 0, 2, 0, 2, 2, 2, 1, 2, 0, 3, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 1, 2, 0, 3, 3, 2, 6, 2, 3, 2, 3, 2, 0, 2, 9, 2, 16, 6, 2, 2, 4, 2, 16, 4421, 42719, 33, 4153, 7, 221, 3, 5761, 15, 7472, 16, 621, 2467, 541, 1507, 4938, 6, 4191];
const astralIdentifierCodes = [509, 0, 227, 0, 150, 4, 294, 9, 1368, 2, 2, 1, 6, 3, 41, 2, 5, 0, 166, 1, 574, 3, 9, 9, 7, 9, 32, 4, 318, 1, 80, 3, 71, 10, 50, 3, 123, 2, 54, 14, 32, 10, 3, 1, 11, 3, 46, 10, 8, 0, 46, 9, 7, 2, 37, 13, 2, 9, 6, 1, 45, 0, 13, 2, 49, 13, 9, 3, 2, 11, 83, 11, 7, 0, 3, 0, 158, 11, 6, 9, 7, 3, 56, 1, 2, 6, 3, 1, 3, 2, 10, 0, 11, 1, 3, 6, 4, 4, 68, 8, 2, 0, 3, 0, 2, 3, 2, 4, 2, 0, 15, 1, 83, 17, 10, 9, 5, 0, 82, 19, 13, 9, 214, 6, 3, 8, 28, 1, 83, 16, 16, 9, 82, 12, 9, 9, 7, 19, 58, 14, 5, 9, 243, 14, 166, 9, 71, 5, 2, 1, 3, 3, 2, 0, 2, 1, 13, 9, 120, 6, 3, 6, 4, 0, 29, 9, 41, 6, 2, 3, 9, 0, 10, 10, 47, 15, 343, 9, 54, 7, 2, 7, 17, 9, 57, 21, 2, 13, 123, 5, 4, 0, 2, 1, 2, 6, 2, 0, 9, 9, 49, 4, 2, 1, 2, 4, 9, 9, 330, 3, 10, 1, 2, 0, 49, 6, 4, 4, 14, 10, 5350, 0, 7, 14, 11465, 27, 2343, 9, 87, 9, 39, 4, 60, 6, 26, 9, 535, 9, 470, 0, 2, 54, 8, 3, 82, 0, 12, 1, 19628, 1, 4178, 9, 519, 45, 3, 22, 543, 4, 4, 5, 9, 7, 3, 6, 31, 3, 149, 2, 1418, 49, 513, 54, 5, 49, 9, 0, 15, 0, 23, 4, 2, 14, 1361, 6, 2, 16, 3, 6, 2, 1, 2, 4, 101, 0, 161, 6, 10, 9, 357, 0, 62, 13, 499, 13, 245, 1, 2, 9, 726, 6, 110, 6, 6, 9, 4759, 9, 787719, 239];
function isInAstralSet(code, set) {
let pos = 0x10000;
for (let i = 0, length = set.length; i < length; i += 2) {
pos += set[i];
if (pos > code) return false;
pos += set[i + 1];
if (pos >= code) return true;
}
return false;
}
function isIdentifierStart(code) {
if (code < 65) return code === 36;
if (code <= 90) return true;
if (code < 97) return code === 95;
if (code <= 122) return true;
if (code <= 0xffff) {
return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code));
}
return isInAstralSet(code, astralIdentifierStartCodes);
}
function isIdentifierChar(code) {
if (code < 48) return code === 36;
if (code < 58) return true;
if (code < 65) return false;
if (code <= 90) return true;
if (code < 97) return code === 95;
if (code <= 122) return true;
if (code <= 0xffff) {
return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code));
}
return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes);
}
function isIdentifierName(name) {
let isFirst = true;
for (let i = 0; i < name.length; i++) {
let cp = name.charCodeAt(i);
if ((cp & 0xfc00) === 0xd800 && i + 1 < name.length) {
const trail = name.charCodeAt(++i);
if ((trail & 0xfc00) === 0xdc00) {
cp = 0x10000 + ((cp & 0x3ff) << 10) + (trail & 0x3ff);
}
}
if (isFirst) {
isFirst = false;
if (!isIdentifierStart(cp)) {
return false;
}
} else if (!isIdentifierChar(cp)) {
return false;
}
}
return !isFirst;
}
//# sourceMappingURL=identifier.js.map

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,57 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "isIdentifierChar", {
enumerable: true,
get: function () {
return _identifier.isIdentifierChar;
}
});
Object.defineProperty(exports, "isIdentifierName", {
enumerable: true,
get: function () {
return _identifier.isIdentifierName;
}
});
Object.defineProperty(exports, "isIdentifierStart", {
enumerable: true,
get: function () {
return _identifier.isIdentifierStart;
}
});
Object.defineProperty(exports, "isKeyword", {
enumerable: true,
get: function () {
return _keyword.isKeyword;
}
});
Object.defineProperty(exports, "isReservedWord", {
enumerable: true,
get: function () {
return _keyword.isReservedWord;
}
});
Object.defineProperty(exports, "isStrictBindOnlyReservedWord", {
enumerable: true,
get: function () {
return _keyword.isStrictBindOnlyReservedWord;
}
});
Object.defineProperty(exports, "isStrictBindReservedWord", {
enumerable: true,
get: function () {
return _keyword.isStrictBindReservedWord;
}
});
Object.defineProperty(exports, "isStrictReservedWord", {
enumerable: true,
get: function () {
return _keyword.isStrictReservedWord;
}
});
var _identifier = require("./identifier.js");
var _keyword = require("./keyword.js");
//# sourceMappingURL=index.js.map

View file

@ -0,0 +1 @@
{"version":3,"names":["_identifier","require","_keyword"],"sources":["../src/index.ts"],"sourcesContent":["export {\n isIdentifierName,\n isIdentifierChar,\n isIdentifierStart,\n} from \"./identifier.ts\";\nexport {\n isReservedWord,\n isStrictBindOnlyReservedWord,\n isStrictBindReservedWord,\n isStrictReservedWord,\n isKeyword,\n} from \"./keyword.ts\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,IAAAA,WAAA,GAAAC,OAAA;AAKA,IAAAC,QAAA,GAAAD,OAAA","ignoreList":[]}

View file

@ -0,0 +1,35 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.isKeyword = isKeyword;
exports.isReservedWord = isReservedWord;
exports.isStrictBindOnlyReservedWord = isStrictBindOnlyReservedWord;
exports.isStrictBindReservedWord = isStrictBindReservedWord;
exports.isStrictReservedWord = isStrictReservedWord;
const reservedWords = {
keyword: ["break", "case", "catch", "continue", "debugger", "default", "do", "else", "finally", "for", "function", "if", "return", "switch", "throw", "try", "var", "const", "while", "with", "new", "this", "super", "class", "extends", "export", "import", "null", "true", "false", "in", "instanceof", "typeof", "void", "delete"],
strict: ["implements", "interface", "let", "package", "private", "protected", "public", "static", "yield"],
strictBind: ["eval", "arguments"]
};
const keywords = new Set(reservedWords.keyword);
const reservedWordsStrictSet = new Set(reservedWords.strict);
const reservedWordsStrictBindSet = new Set(reservedWords.strictBind);
function isReservedWord(word, inModule) {
return inModule && word === "await" || word === "enum";
}
function isStrictReservedWord(word, inModule) {
return isReservedWord(word, inModule) || reservedWordsStrictSet.has(word);
}
function isStrictBindOnlyReservedWord(word) {
return reservedWordsStrictBindSet.has(word);
}
function isStrictBindReservedWord(word, inModule) {
return isStrictReservedWord(word, inModule) || isStrictBindOnlyReservedWord(word);
}
function isKeyword(word) {
return keywords.has(word);
}
//# sourceMappingURL=keyword.js.map

View file

@ -0,0 +1 @@
{"version":3,"names":["reservedWords","keyword","strict","strictBind","keywords","Set","reservedWordsStrictSet","reservedWordsStrictBindSet","isReservedWord","word","inModule","isStrictReservedWord","has","isStrictBindOnlyReservedWord","isStrictBindReservedWord","isKeyword"],"sources":["../src/keyword.ts"],"sourcesContent":["const reservedWords = {\n keyword: [\n \"break\",\n \"case\",\n \"catch\",\n \"continue\",\n \"debugger\",\n \"default\",\n \"do\",\n \"else\",\n \"finally\",\n \"for\",\n \"function\",\n \"if\",\n \"return\",\n \"switch\",\n \"throw\",\n \"try\",\n \"var\",\n \"const\",\n \"while\",\n \"with\",\n \"new\",\n \"this\",\n \"super\",\n \"class\",\n \"extends\",\n \"export\",\n \"import\",\n \"null\",\n \"true\",\n \"false\",\n \"in\",\n \"instanceof\",\n \"typeof\",\n \"void\",\n \"delete\",\n ],\n strict: [\n \"implements\",\n \"interface\",\n \"let\",\n \"package\",\n \"private\",\n \"protected\",\n \"public\",\n \"static\",\n \"yield\",\n ],\n strictBind: [\"eval\", \"arguments\"],\n};\nconst keywords = new Set(reservedWords.keyword);\nconst reservedWordsStrictSet = new Set(reservedWords.strict);\nconst reservedWordsStrictBindSet = new Set(reservedWords.strictBind);\n\n/**\n * Checks if word is a reserved word in non-strict mode\n */\nexport function isReservedWord(word: string, inModule: boolean): boolean {\n return (inModule && word === \"await\") || word === \"enum\";\n}\n\n/**\n * Checks if word is a reserved word in non-binding strict mode\n *\n * Includes non-strict reserved words\n */\nexport function isStrictReservedWord(word: string, inModule: boolean): boolean {\n return isReservedWord(word, inModule) || reservedWordsStrictSet.has(word);\n}\n\n/**\n * Checks if word is a reserved word in binding strict mode, but it is allowed as\n * a normal identifier.\n */\nexport function isStrictBindOnlyReservedWord(word: string): boolean {\n return reservedWordsStrictBindSet.has(word);\n}\n\n/**\n * Checks if word is a reserved word in binding strict mode\n *\n * Includes non-strict reserved words and non-binding strict reserved words\n */\nexport function isStrictBindReservedWord(\n word: string,\n inModule: boolean,\n): boolean {\n return (\n isStrictReservedWord(word, inModule) || isStrictBindOnlyReservedWord(word)\n );\n}\n\nexport function isKeyword(word: string): boolean {\n return keywords.has(word);\n}\n"],"mappings":";;;;;;;;;;AAAA,MAAMA,aAAa,GAAG;EACpBC,OAAO,EAAE,CACP,OAAO,EACP,MAAM,EACN,OAAO,EACP,UAAU,EACV,UAAU,EACV,SAAS,EACT,IAAI,EACJ,MAAM,EACN,SAAS,EACT,KAAK,EACL,UAAU,EACV,IAAI,EACJ,QAAQ,EACR,QAAQ,EACR,OAAO,EACP,KAAK,EACL,KAAK,EACL,OAAO,EACP,OAAO,EACP,MAAM,EACN,KAAK,EACL,MAAM,EACN,OAAO,EACP,OAAO,EACP,SAAS,EACT,QAAQ,EACR,QAAQ,EACR,MAAM,EACN,MAAM,EACN,OAAO,EACP,IAAI,EACJ,YAAY,EACZ,QAAQ,EACR,MAAM,EACN,QAAQ,CACT;EACDC,MAAM,EAAE,CACN,YAAY,EACZ,WAAW,EACX,KAAK,EACL,SAAS,EACT,SAAS,EACT,WAAW,EACX,QAAQ,EACR,QAAQ,EACR,OAAO,CACR;EACDC,UAAU,EAAE,CAAC,MAAM,EAAE,WAAW;AAClC,CAAC;AACD,MAAMC,QAAQ,GAAG,IAAIC,GAAG,CAACL,aAAa,CAACC,OAAO,CAAC;AAC/C,MAAMK,sBAAsB,GAAG,IAAID,GAAG,CAACL,aAAa,CAACE,MAAM,CAAC;AAC5D,MAAMK,0BAA0B,GAAG,IAAIF,GAAG,CAACL,aAAa,CAACG,UAAU,CAAC;AAK7D,SAASK,cAAcA,CAACC,IAAY,EAAEC,QAAiB,EAAW;EACvE,OAAQA,QAAQ,IAAID,IAAI,KAAK,OAAO,IAAKA,IAAI,KAAK,MAAM;AAC1D;AAOO,SAASE,oBAAoBA,CAACF,IAAY,EAAEC,QAAiB,EAAW;EAC7E,OAAOF,cAAc,CAACC,IAAI,EAAEC,QAAQ,CAAC,IAAIJ,sBAAsB,CAACM,GAAG,CAACH,IAAI,CAAC;AAC3E;AAMO,SAASI,4BAA4BA,CAACJ,IAAY,EAAW;EAClE,OAAOF,0BAA0B,CAACK,GAAG,CAACH,IAAI,CAAC;AAC7C;AAOO,SAASK,wBAAwBA,CACtCL,IAAY,EACZC,QAAiB,EACR;EACT,OACEC,oBAAoB,CAACF,IAAI,EAAEC,QAAQ,CAAC,IAAIG,4BAA4B,CAACJ,IAAI,CAAC;AAE9E;AAEO,SAASM,SAASA,CAACN,IAAY,EAAW;EAC/C,OAAOL,QAAQ,CAACQ,GAAG,CAACH,IAAI,CAAC;AAC3B","ignoreList":[]}

View file

@ -0,0 +1,31 @@
{
"name": "@babel/helper-validator-identifier",
"version": "7.27.1",
"description": "Validate identifier/keywords name",
"repository": {
"type": "git",
"url": "https://github.com/babel/babel.git",
"directory": "packages/babel-helper-validator-identifier"
},
"license": "MIT",
"publishConfig": {
"access": "public"
},
"main": "./lib/index.js",
"exports": {
".": {
"types": "./lib/index.d.ts",
"default": "./lib/index.js"
},
"./package.json": "./package.json"
},
"devDependencies": {
"@unicode/unicode-16.0.0": "^1.0.0",
"charcodes": "^0.2.0"
},
"engines": {
"node": ">=6.9.0"
},
"author": "The Babel Team (https://babel.dev/team)",
"type": "commonjs"
}

View file

@ -0,0 +1,9 @@
# Changes to CSS Parser Algorithms
### 3.0.5
_May 27, 2025_
- Updated [`@csstools/css-tokenizer`](https://github.com/csstools/postcss-plugins/tree/main/packages/css-tokenizer) to [`3.0.4`](https://github.com/csstools/postcss-plugins/tree/main/packages/css-tokenizer/CHANGELOG.md#304) (patch)
[Full CHANGELOG](https://github.com/csstools/postcss-plugins/tree/main/packages/css-parser-algorithms/CHANGELOG.md)

View file

@ -0,0 +1,20 @@
The MIT License (MIT)
Copyright 2022 Romain Menke, Antonio Laguna <antonio@laguna.es>
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.

119
node_modules/@csstools/css-parser-algorithms/README.md generated vendored Normal file
View file

@ -0,0 +1,119 @@
# CSS Parser Algorithms <img src="https://cssdb.org/images/css.svg" alt="for CSS" width="90" height="90" align="right">
[<img alt="npm version" src="https://img.shields.io/npm/v/@csstools/css-parser-algorithms.svg" height="20">][npm-url]
[<img alt="Build Status" src="https://github.com/csstools/postcss-plugins/actions/workflows/test.yml/badge.svg?branch=main" height="20">][cli-url]
[<img alt="Discord" src="https://shields.io/badge/Discord-5865F2?logo=discord&logoColor=white">][discord]
Implemented from : https://www.w3.org/TR/2021/CRD-css-syntax-3-20211224/
## API
[Read the API docs](./docs/css-parser-algorithms.md)
## Usage
Add [CSS Parser Algorithms] to your project:
```bash
npm install @csstools/css-parser-algorithms @csstools/css-tokenizer --save-dev
```
[CSS Parser Algorithms] only accepts tokenized CSS.
It must be used together with `@csstools/css-tokenizer`.
```js
import { tokenizer, TokenType } from '@csstools/css-tokenizer';
import { parseComponentValue } from '@csstools/css-parser-algorithms';
const myCSS = `@media only screen and (min-width: 768rem) {
.foo {
content: 'Some content!' !important;
}
}
`;
const t = tokenizer({
css: myCSS,
});
const tokens = [];
{
while (!t.endOfFile()) {
tokens.push(t.nextToken());
}
tokens.push(t.nextToken()); // EOF-token
}
const options = {
onParseError: ((err) => {
throw err;
}),
};
const result = parseComponentValue(tokens, options);
console.log(result);
```
### Available functions
- [`parseComponentValue`](https://www.w3.org/TR/css-syntax-3/#parse-component-value)
- [`parseListOfComponentValues`](https://www.w3.org/TR/css-syntax-3/#parse-list-of-component-values)
- [`parseCommaSeparatedListOfComponentValues`](https://www.w3.org/TR/css-syntax-3/#parse-comma-separated-list-of-component-values)
### Utilities
#### `gatherNodeAncestry`
The AST does not expose the entire ancestry of each node.
The walker methods do provide access to the current parent, but also not the entire ancestry.
To gather the entire ancestry for a a given sub tree of the AST you can use `gatherNodeAncestry`.
The result is a `Map` with the child nodes as keys and the parents as values.
This allows you to lookup any ancestor of any node.
```js
import { parseComponentValue } from '@csstools/css-parser-algorithms';
const result = parseComponentValue(tokens, options);
const ancestry = gatherNodeAncestry(result);
```
### Options
```ts
{
onParseError?: (error: ParseError) => void
}
```
#### `onParseError`
The parser algorithms are forgiving and won't stop when a parse error is encountered.
Parse errors also aren't tokens.
To receive parsing error information you can set a callback.
Parser errors will try to inform you about the point in the parsing logic the error happened.
This tells you the kind of error.
## Goals and non-goals
Things this package aims to be:
- specification compliant CSS parser
- a reliable low level package to be used in CSS sub-grammars
What it is not:
- opinionated
- fast
- small
- a replacement for PostCSS (PostCSS is fast and also an ecosystem)
[cli-url]: https://github.com/csstools/postcss-plugins/actions/workflows/test.yml?query=workflow/test
[discord]: https://discord.gg/bUadyRwkJS
[npm-url]: https://www.npmjs.com/package/@csstools/css-parser-algorithms
[CSS Parser Algorithms]: https://github.com/csstools/postcss-plugins/tree/main/packages/css-parser-algorithms

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,604 @@
/**
* Parse CSS following the {@link https://drafts.csswg.org/css-syntax/#parsing | CSS Syntax Level 3 specification}.
*
* @remarks
* The tokenizing and parsing tools provided by CSS Tools are designed to be low level and generic with strong ties to their respective specifications.
*
* Any analysis or mutation of CSS source code should be done with the least powerful tool that can accomplish the task.
* For many applications it is sufficient to work with tokens.
* For others you might need to use {@link https://github.com/csstools/postcss-plugins/tree/main/packages/css-parser-algorithms | @csstools/css-parser-algorithms} or a more specific parser.
*
* The implementation of the AST nodes is kept lightweight and simple.
* Do not expect magic methods, instead assume that arrays and class instances behave like any other JavaScript.
*
* @example
* Parse a string of CSS into a component value:
* ```js
* import { tokenize } from '@csstools/css-tokenizer';
* import { parseComponentValue } from '@csstools/css-parser-algorithms';
*
* const myCSS = `calc(1px * 2)`;
*
* const componentValue = parseComponentValue(tokenize({
* css: myCSS,
* }));
*
* console.log(componentValue);
* ```
*
* @example
* Use the right algorithm for the job.
*
* Algorithms that can parse larger structures (comma-separated lists, ...) can also parse smaller structures.
* However, the opposite is not true.
*
* If your context allows a list of component values, use {@link parseListOfComponentValues}:
* ```js
* import { tokenize } from '@csstools/css-tokenizer';
* import { parseListOfComponentValues } from '@csstools/css-parser-algorithms';
*
* parseListOfComponentValues(tokenize({ css: `10x 20px` }));
* ```
*
* If your context allows a comma-separated list of component values, use {@link parseCommaSeparatedListOfComponentValues}:
* ```js
* import { tokenize } from '@csstools/css-tokenizer';
* import { parseCommaSeparatedListOfComponentValues } from '@csstools/css-parser-algorithms';
*
* parseCommaSeparatedListOfComponentValues(tokenize({ css: `20deg, 50%, 30%` }));
* ```
*
* @example
* Use the stateful walkers to keep track of the context of a given component value.
*
* ```js
* import { tokenize } from '@csstools/css-tokenizer';
* import { parseComponentValue, isSimpleBlockNode } from '@csstools/css-parser-algorithms';
*
* const myCSS = `calc(1px * (5 / 2))`;
*
* const componentValue = parseComponentValue(tokenize({ css: myCSS }));
*
* let state = { inSimpleBlock: false };
* componentValue.walk((entry) => {
* if (isSimpleBlockNode(entry)) {
* entry.state.inSimpleBlock = true;
* return;
* }
*
* if (entry.state.inSimpleBlock) {
* console.log(entry.node.toString()); // `5`, ...
* }
* }, state);
* ```
*
* @packageDocumentation
*/
import type { CSSToken } from '@csstools/css-tokenizer';
import { ParseError } from '@csstools/css-tokenizer';
import type { TokenFunction } from '@csstools/css-tokenizer';
export declare class CommentNode {
/**
* The node type, always `ComponentValueType.Comment`
*/
type: ComponentValueType;
/**
* The comment token.
*/
value: CSSToken;
constructor(value: CSSToken);
/**
* Retrieve the tokens for the current comment.
* This is the inverse of parsing from a list of tokens.
*/
tokens(): Array<CSSToken>;
/**
* Convert the current comment to a string.
* This is not a true serialization.
* It is purely a concatenation of the string representation of the tokens.
*/
toString(): string;
/**
* @internal
*
* A debug helper to convert the current object to a JSON representation.
* This is useful in asserts and to store large ASTs in files.
*/
toJSON(): Record<string, unknown>;
/**
* @internal
*/
isCommentNode(): this is CommentNode;
/**
* @internal
*/
static isCommentNode(x: unknown): x is CommentNode;
}
export declare type ComponentValue = FunctionNode | SimpleBlockNode | WhitespaceNode | CommentNode | TokenNode;
export declare enum ComponentValueType {
Function = "function",
SimpleBlock = "simple-block",
Whitespace = "whitespace",
Comment = "comment",
Token = "token"
}
export declare type ContainerNode = FunctionNode | SimpleBlockNode;
export declare abstract class ContainerNodeBaseClass {
/**
* The contents of the `Function` or `Simple Block`.
* This is a list of component values.
*/
value: Array<ComponentValue>;
/**
* Retrieve the index of the given item in the current node.
* For most node types this will be trivially implemented as `this.value.indexOf(item)`.
*/
indexOf(item: ComponentValue): number | string;
/**
* Retrieve the item at the given index in the current node.
* For most node types this will be trivially implemented as `this.value[index]`.
*/
at(index: number | string): ComponentValue | undefined;
/**
* Iterates over each item in the `value` array of the current node.
*
* @param cb - The callback function to execute for each item.
* The function receives an object containing the current node (`node`), its parent (`parent`),
* and an optional `state` object.
* A second parameter is the index of the current node.
* The function can return `false` to stop the iteration.
*
* @param state - An optional state object that can be used to pass additional information to the callback function.
* The state object is cloned for each iteration. This means that changes to the state object are not reflected in the next iteration.
*
* @returns `false` if the iteration was halted, `undefined` otherwise.
*/
forEach<T extends Record<string, unknown>, U extends ContainerNode>(this: U, cb: (entry: {
node: ComponentValue;
parent: ContainerNode;
state?: T;
}, index: number | string) => boolean | void, state?: T): false | undefined;
/**
* Walks the current node and all its children.
*
* @param cb - The callback function to execute for each item.
* The function receives an object containing the current node (`node`), its parent (`parent`),
* and an optional `state` object.
* A second parameter is the index of the current node.
* The function can return `false` to stop the iteration.
*
* @param state - An optional state object that can be used to pass additional information to the callback function.
* The state object is cloned for each iteration. This means that changes to the state object are not reflected in the next iteration.
* However changes are passed down to child node iterations.
*
* @returns `false` if the iteration was halted, `undefined` otherwise.
*/
walk<T extends Record<string, unknown>, U extends ContainerNode>(this: U, cb: (entry: {
node: ComponentValue;
parent: ContainerNode;
state?: T;
}, index: number | string) => boolean | void, state?: T): false | undefined;
}
/**
* Iterates over each item in a list of component values.
*
* @param cb - The callback function to execute for each item.
* The function receives an object containing the current node (`node`), its parent (`parent`),
* and an optional `state` object.
* A second parameter is the index of the current node.
* The function can return `false` to stop the iteration.
*
* @param state - An optional state object that can be used to pass additional information to the callback function.
* The state object is cloned for each iteration. This means that changes to the state object are not reflected in the next iteration.
*
* @returns `false` if the iteration was halted, `undefined` otherwise.
*/
export declare function forEach<T extends Record<string, unknown>>(componentValues: Array<ComponentValue>, cb: (entry: {
node: ComponentValue;
parent: ContainerNode | {
value: Array<ComponentValue>;
};
state?: T;
}, index: number | string) => boolean | void, state?: T): false | undefined;
/**
* A function node.
*
* @example
* ```js
* const node = parseComponentValue(tokenize('calc(1 + 1)'));
*
* isFunctionNode(node); // true
* node.getName(); // 'calc'
* ```
*/
export declare class FunctionNode extends ContainerNodeBaseClass {
/**
* The node type, always `ComponentValueType.Function`
*/
type: ComponentValueType;
/**
* The token for the name of the function.
*/
name: TokenFunction;
/**
* The token for the closing parenthesis of the function.
* If the function is unclosed, this will be an EOF token.
*/
endToken: CSSToken;
constructor(name: TokenFunction, endToken: CSSToken, value: Array<ComponentValue>);
/**
* Retrieve the name of the current function.
* This is the parsed and unescaped name of the function.
*/
getName(): string;
/**
* Normalize the current function:
* 1. if the "endToken" is EOF, replace with a ")-token"
*/
normalize(): void;
/**
* Retrieve the tokens for the current function.
* This is the inverse of parsing from a list of tokens.
*/
tokens(): Array<CSSToken>;
/**
* Convert the current function to a string.
* This is not a true serialization.
* It is purely a concatenation of the string representation of the tokens.
*/
toString(): string;
/**
* @internal
*
* A debug helper to convert the current object to a JSON representation.
* This is useful in asserts and to store large ASTs in files.
*/
toJSON(): unknown;
/**
* @internal
*/
isFunctionNode(): this is FunctionNode;
/**
* @internal
*/
static isFunctionNode(x: unknown): x is FunctionNode;
}
/**
* AST nodes do not have a `parent` property or method.
* This makes it harder to traverse the AST upwards.
* This function builds a `Map<Child, Parent>` that can be used to lookup ancestors of a node.
*
* @remarks
* There is no magic behind this or the map it returns.
* Mutating the AST will not update the map.
*
* Types are erased and any content of the map has type `unknown`.
* If someone knows a clever way to type this, please let us know.
*
* @example
* ```js
* const ancestry = gatherNodeAncestry(mediaQuery);
* mediaQuery.walk((entry) => {
* const node = entry.node; // directly exposed
* const parent = entry.parent; // directly exposed
* const grandParent: unknown = ancestry.get(parent); // lookup
*
* console.log('node', node);
* console.log('parent', parent);
* console.log('grandParent', grandParent);
* });
* ```
*/
export declare function gatherNodeAncestry(node: {
walk(cb: (entry: {
node: unknown;
parent: unknown;
}, index: number | string) => boolean | void): false | undefined;
}): Map<unknown, unknown>;
/**
* Check if the current object is a `CommentNode`.
* This is a type guard.
*/
export declare function isCommentNode(x: unknown): x is CommentNode;
/**
* Check if the current object is a `FunctionNode`.
* This is a type guard.
*/
export declare function isFunctionNode(x: unknown): x is FunctionNode;
/**
* Check if the current object is a `SimpleBlockNode`.
* This is a type guard.
*/
export declare function isSimpleBlockNode(x: unknown): x is SimpleBlockNode;
/**
* Check if the current object is a `TokenNode`.
* This is a type guard.
*/
export declare function isTokenNode(x: unknown): x is TokenNode;
/**
* Check if the current object is a `WhitespaceNode`.
* This is a type guard.
*/
export declare function isWhitespaceNode(x: unknown): x is WhitespaceNode;
/**
* Check if the current object is a `WhiteSpaceNode` or a `CommentNode`.
* This is a type guard.
*/
export declare function isWhiteSpaceOrCommentNode(x: unknown): x is WhitespaceNode | CommentNode;
/**
* Parse a comma-separated list of component values.
*
* @example
* ```js
* import { tokenize } from '@csstools/css-tokenizer';
* import { parseCommaSeparatedListOfComponentValues } from '@csstools/css-parser-algorithms';
*
* parseCommaSeparatedListOfComponentValues(tokenize({ css: `20deg, 50%, 30%` }));
* ```
*/
export declare function parseCommaSeparatedListOfComponentValues(tokens: Array<CSSToken>, options?: {
onParseError?: (error: ParseError) => void;
}): Array<Array<ComponentValue>>;
/**
* Parse a single component value.
*
* @example
* ```js
* import { tokenize } from '@csstools/css-tokenizer';
* import { parseCommaSeparatedListOfComponentValues } from '@csstools/css-parser-algorithms';
*
* parseCommaSeparatedListOfComponentValues(tokenize({ css: `10px` }));
* parseCommaSeparatedListOfComponentValues(tokenize({ css: `calc((10px + 1x) * 4)` }));
* ```
*/
export declare function parseComponentValue(tokens: Array<CSSToken>, options?: {
onParseError?: (error: ParseError) => void;
}): ComponentValue | undefined;
/**
* Parse a list of component values.
*
* @example
* ```js
* import { tokenize } from '@csstools/css-tokenizer';
* import { parseListOfComponentValues } from '@csstools/css-parser-algorithms';
*
* parseListOfComponentValues(tokenize({ css: `20deg 30%` }));
* ```
*/
export declare function parseListOfComponentValues(tokens: Array<CSSToken>, options?: {
onParseError?: (error: ParseError) => void;
}): Array<ComponentValue>;
/**
* Replace specific component values in a list of component values.
* A helper for the most common and simplistic cases when mutating an AST.
*/
export declare function replaceComponentValues(componentValuesList: Array<Array<ComponentValue>>, replaceWith: (componentValue: ComponentValue) => Array<ComponentValue> | ComponentValue | void): Array<Array<ComponentValue>>;
/**
* A simple block node.
*
* @example
* ```js
* const node = parseComponentValue(tokenize('[foo=bar]'));
*
* isSimpleBlockNode(node); // true
* node.startToken; // [TokenType.OpenSquare, '[', 0, 0, undefined]
* ```
*/
export declare class SimpleBlockNode extends ContainerNodeBaseClass {
/**
* The node type, always `ComponentValueType.SimpleBlock`
*/
type: ComponentValueType;
/**
* The token for the opening token of the block.
*/
startToken: CSSToken;
/**
* The token for the closing token of the block.
* If the block is closed it will be the mirror variant of the `startToken`.
* If the block is unclosed, this will be an EOF token.
*/
endToken: CSSToken;
constructor(startToken: CSSToken, endToken: CSSToken, value: Array<ComponentValue>);
/**
* Normalize the current simple block
* 1. if the "endToken" is EOF, replace with the mirror token of the "startToken"
*/
normalize(): void;
/**
* Retrieve the tokens for the current simple block.
* This is the inverse of parsing from a list of tokens.
*/
tokens(): Array<CSSToken>;
/**
* Convert the current simple block to a string.
* This is not a true serialization.
* It is purely a concatenation of the string representation of the tokens.
*/
toString(): string;
/**
* @internal
*
* A debug helper to convert the current object to a JSON representation.
* This is useful in asserts and to store large ASTs in files.
*/
toJSON(): unknown;
/**
* @internal
*/
isSimpleBlockNode(): this is SimpleBlockNode;
/**
* @internal
*/
static isSimpleBlockNode(x: unknown): x is SimpleBlockNode;
}
/**
* Returns the start and end index of a node in the CSS source string.
*/
export declare function sourceIndices(x: {
tokens(): Array<CSSToken>;
} | Array<{
tokens(): Array<CSSToken>;
}>): [number, number];
/**
* Concatenate the string representation of a collection of component values.
* This is not a proper serializer that will handle escaping and whitespace.
* It only produces valid CSS for token lists that are also valid.
*/
export declare function stringify(componentValueLists: Array<Array<ComponentValue>>): string;
export declare class TokenNode {
/**
* The node type, always `ComponentValueType.Token`
*/
type: ComponentValueType;
/**
* The token.
*/
value: CSSToken;
constructor(value: CSSToken);
/**
* This is the inverse of parsing from a list of tokens.
*/
tokens(): [CSSToken];
/**
* Convert the current token to a string.
* This is not a true serialization.
* It is purely the string representation of token.
*/
toString(): string;
/**
* @internal
*
* A debug helper to convert the current object to a JSON representation.
* This is useful in asserts and to store large ASTs in files.
*/
toJSON(): Record<string, unknown>;
/**
* @internal
*/
isTokenNode(): this is TokenNode;
/**
* @internal
*/
static isTokenNode(x: unknown): x is TokenNode;
}
/**
* Walks each item in a list of component values all of their children.
*
* @param cb - The callback function to execute for each item.
* The function receives an object containing the current node (`node`), its parent (`parent`),
* and an optional `state` object.
* A second parameter is the index of the current node.
* The function can return `false` to stop the iteration.
*
* @param state - An optional state object that can be used to pass additional information to the callback function.
* The state object is cloned for each iteration. This means that changes to the state object are not reflected in the next iteration.
* However changes are passed down to child node iterations.
*
* @returns `false` if the iteration was halted, `undefined` otherwise.
*
* @example
* ```js
* import { tokenize } from '@csstools/css-tokenizer';
* import { parseListOfComponentValues, isSimpleBlockNode } from '@csstools/css-parser-algorithms';
*
* const myCSS = `calc(1px * (5 / 2)) 10px`;
*
* const componentValues = parseListOfComponentValues(tokenize({ css: myCSS }));
*
* let state = { inSimpleBlock: false };
* walk(componentValues, (entry) => {
* if (isSimpleBlockNode(entry)) {
* entry.state.inSimpleBlock = true;
* return;
* }
*
* if (entry.state.inSimpleBlock) {
* console.log(entry.node.toString()); // `5`, ...
* }
* }, state);
* ```
*/
export declare function walk<T extends Record<string, unknown>>(componentValues: Array<ComponentValue>, cb: (entry: {
node: ComponentValue;
parent: ContainerNode | {
value: Array<ComponentValue>;
};
state?: T;
}, index: number | string) => boolean | void, state?: T): false | undefined;
/**
* Generate a function that finds the next element that should be visited when walking an AST.
* Rules :
* 1. the previous iteration is used as a reference, so any checks are relative to the start of the current iteration.
* 2. the next element always appears after the current index.
* 3. the next element always exists in the list.
* 4. replacing an element does not cause the replaced element to be visited.
* 5. removing an element does not cause elements to be skipped.
* 6. an element added later in the list will be visited.
*/
export declare function walkerIndexGenerator<T>(initialList: Array<T>): (list: Array<T>, child: T, index: number) => number;
export declare class WhitespaceNode {
/**
* The node type, always `ComponentValueType.WhiteSpace`
*/
type: ComponentValueType;
/**
* The list of consecutive whitespace tokens.
*/
value: Array<CSSToken>;
constructor(value: Array<CSSToken>);
/**
* Retrieve the tokens for the current whitespace.
* This is the inverse of parsing from a list of tokens.
*/
tokens(): Array<CSSToken>;
/**
* Convert the current whitespace to a string.
* This is not a true serialization.
* It is purely a concatenation of the string representation of the tokens.
*/
toString(): string;
/**
* @internal
*
* A debug helper to convert the current object to a JSON representation.
* This is useful in asserts and to store large ASTs in files.
*/
toJSON(): Record<string, unknown>;
/**
* @internal
*/
isWhitespaceNode(): this is WhitespaceNode;
/**
* @internal
*/
static isWhitespaceNode(x: unknown): x is WhitespaceNode;
}
export { }

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,65 @@
{
"name": "@csstools/css-parser-algorithms",
"description": "Algorithms to help you parse CSS from an array of tokens.",
"version": "3.0.5",
"contributors": [
{
"name": "Antonio Laguna",
"email": "antonio@laguna.es",
"url": "https://antonio.laguna.es"
},
{
"name": "Romain Menke",
"email": "romainmenke@gmail.com"
}
],
"license": "MIT",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/csstools"
},
{
"type": "opencollective",
"url": "https://opencollective.com/csstools"
}
],
"engines": {
"node": ">=18"
},
"type": "module",
"main": "dist/index.cjs",
"module": "dist/index.mjs",
"exports": {
".": {
"import": {
"types": "./dist/index.d.ts",
"default": "./dist/index.mjs"
},
"require": {
"default": "./dist/index.cjs"
}
}
},
"files": [
"CHANGELOG.md",
"LICENSE.md",
"README.md",
"dist"
],
"peerDependencies": {
"@csstools/css-tokenizer": "^3.0.4"
},
"scripts": {},
"homepage": "https://github.com/csstools/postcss-plugins/tree/main/packages/css-parser-algorithms#readme",
"repository": {
"type": "git",
"url": "git+https://github.com/csstools/postcss-plugins.git",
"directory": "packages/css-parser-algorithms"
},
"bugs": "https://github.com/csstools/postcss-plugins/issues",
"keywords": [
"css",
"parser"
]
}

9
node_modules/@csstools/css-tokenizer/CHANGELOG.md generated vendored Normal file
View file

@ -0,0 +1,9 @@
# Changes to CSS Tokenizer
### 3.0.4
_May 27, 2025_
- align serializers with CSSOM
[Full CHANGELOG](https://github.com/csstools/postcss-plugins/tree/main/packages/css-tokenizer/CHANGELOG.md)

20
node_modules/@csstools/css-tokenizer/LICENSE.md generated vendored Normal file
View file

@ -0,0 +1,20 @@
The MIT License (MIT)
Copyright 2022 Romain Menke, Antonio Laguna <antonio@laguna.es>
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.

111
node_modules/@csstools/css-tokenizer/README.md generated vendored Normal file
View file

@ -0,0 +1,111 @@
# CSS Tokenizer <img src="https://cssdb.org/images/css.svg" alt="for CSS" width="90" height="90" align="right">
[<img alt="npm version" src="https://img.shields.io/npm/v/@csstools/css-tokenizer.svg" height="20">][npm-url]
[<img alt="Build Status" src="https://github.com/csstools/postcss-plugins/actions/workflows/test.yml/badge.svg?branch=main" height="20">][cli-url]
[<img alt="Discord" src="https://shields.io/badge/Discord-5865F2?logo=discord&logoColor=white">][discord]
Implemented from : https://www.w3.org/TR/2021/CRD-css-syntax-3-20211224/
## API
[Read the API docs](./docs/css-tokenizer.md)
## Usage
Add [CSS Tokenizer] to your project:
```bash
npm install @csstools/css-tokenizer --save-dev
```
```js
import { tokenizer, TokenType } from '@csstools/css-tokenizer';
const myCSS = `@media only screen and (min-width: 768rem) {
.foo {
content: 'Some content!' !important;
}
}
`;
const t = tokenizer({
css: myCSS,
});
while (true) {
const token = t.nextToken();
if (token[0] === TokenType.EOF) {
break;
}
console.log(token);
}
```
Or use the `tokenize` helper function:
```js
import { tokenize } from '@csstools/css-tokenizer';
const myCSS = `@media only screen and (min-width: 768rem) {
.foo {
content: 'Some content!' !important;
}
}
`;
const tokens = tokenize({
css: myCSS,
});
console.log(tokens);
```
### Options
```ts
{
onParseError?: (error: ParseError) => void
}
```
#### `onParseError`
The tokenizer is forgiving and won't stop when a parse error is encountered.
To receive parsing error information you can set a callback.
```js
import { tokenizer, TokenType } from '@csstools/css-tokenizer';
const t = tokenizer({
css: '\\',
}, { onParseError: (err) => console.warn(err) });
while (true) {
const token = t.nextToken();
if (token[0] === TokenType.EOF) {
break;
}
}
```
Parser errors will try to inform you where in the tokenizer logic the error happened.
This tells you what kind of error occurred.
## Goals and non-goals
Things this package aims to be:
- specification compliant CSS tokenizer
- a reliable low level package to be used in CSS parsers
What it is not:
- opinionated
- fast
- small
[cli-url]: https://github.com/csstools/postcss-plugins/actions/workflows/test.yml?query=workflow/test
[discord]: https://discord.gg/bUadyRwkJS
[npm-url]: https://www.npmjs.com/package/@csstools/css-tokenizer
[CSS Tokenizer]: https://github.com/csstools/postcss-plugins/tree/main/packages/css-tokenizer

1
node_modules/@csstools/css-tokenizer/dist/index.cjs generated vendored Normal file

File diff suppressed because one or more lines are too long

593
node_modules/@csstools/css-tokenizer/dist/index.d.ts generated vendored Normal file
View file

@ -0,0 +1,593 @@
/**
* Tokenize CSS following the {@link https://drafts.csswg.org/css-syntax/#tokenization | CSS Syntax Level 3 specification}.
*
* @remarks
* The tokenizing and parsing tools provided by CSS Tools are designed to be low level and generic with strong ties to their respective specifications.
*
* Any analysis or mutation of CSS source code should be done with the least powerful tool that can accomplish the task.
* For many applications it is sufficient to work with tokens.
* For others you might need to use {@link https://github.com/csstools/postcss-plugins/tree/main/packages/css-parser-algorithms | @csstools/css-parser-algorithms} or a more specific parser.
*
* @example
* Tokenize a string of CSS into an array of tokens:
* ```js
* import { tokenize } from '@csstools/css-tokenizer';
*
* const myCSS = `@media only screen and (min-width: 768rem) {
* .foo {
* content: 'Some content!' !important;
* }
* }
* `;
*
* const tokens = tokenize({
* css: myCSS,
* });
*
* console.log(tokens);
* ```
*
* @packageDocumentation
*/
/**
* Deep clone a list of tokens.
* Useful for mutations without altering the original list.
*/
export declare function cloneTokens(tokens: Array<CSSToken>): Array<CSSToken>;
/**
* The union of all possible CSS tokens
*/
export declare type CSSToken = TokenAtKeyword | TokenBadString | TokenBadURL | TokenCDC | TokenCDO | TokenColon | TokenComma | TokenComment | TokenDelim | TokenDimension | TokenEOF | TokenFunction | TokenHash | TokenIdent | TokenNumber | TokenPercentage | TokenSemicolon | TokenString | TokenURL | TokenWhitespace | TokenOpenParen | TokenCloseParen | TokenOpenSquare | TokenCloseSquare | TokenOpenCurly | TokenCloseCurly | TokenUnicodeRange;
/**
* The type of hash token
*/
export declare enum HashType {
/**
* The hash token did not start with an ident sequence (e.g. `#-2`)
*/
Unrestricted = "unrestricted",
/**
* The hash token started with an ident sequence (e.g. `#foo`)
* Only hash tokens with the "id" type are valid ID selectors.
*/
ID = "id"
}
/**
* Assert that a given value has the general structure of a CSS token:
* 1. is an array.
* 2. has at least four items.
* 3. has a known token type.
* 4. has a string representation.
* 5. has a start position.
* 6. has an end position.
*/
export declare function isToken(x: any): x is CSSToken;
export declare function isTokenAtKeyword(x?: CSSToken | null): x is TokenAtKeyword;
export declare function isTokenBadString(x?: CSSToken | null): x is TokenBadString;
export declare function isTokenBadURL(x?: CSSToken | null): x is TokenBadURL;
export declare function isTokenCDC(x?: CSSToken | null): x is TokenCDC;
export declare function isTokenCDO(x?: CSSToken | null): x is TokenCDO;
export declare function isTokenCloseCurly(x?: CSSToken | null): x is TokenCloseCurly;
export declare function isTokenCloseParen(x?: CSSToken | null): x is TokenCloseParen;
export declare function isTokenCloseSquare(x?: CSSToken | null): x is TokenCloseSquare;
export declare function isTokenColon(x?: CSSToken | null): x is TokenColon;
export declare function isTokenComma(x?: CSSToken | null): x is TokenComma;
export declare function isTokenComment(x?: CSSToken | null): x is TokenComment;
export declare function isTokenDelim(x?: CSSToken | null): x is TokenDelim;
export declare function isTokenDimension(x?: CSSToken | null): x is TokenDimension;
export declare function isTokenEOF(x?: CSSToken | null): x is TokenEOF;
export declare function isTokenFunction(x?: CSSToken | null): x is TokenFunction;
export declare function isTokenHash(x?: CSSToken | null): x is TokenHash;
export declare function isTokenIdent(x?: CSSToken | null): x is TokenIdent;
export declare function isTokenNumber(x?: CSSToken | null): x is TokenNumber;
/**
* Assert that a token is a numeric token
*/
export declare function isTokenNumeric(x?: CSSToken | null): x is NumericToken;
export declare function isTokenOpenCurly(x?: CSSToken | null): x is TokenOpenCurly;
export declare function isTokenOpenParen(x?: CSSToken | null): x is TokenOpenParen;
export declare function isTokenOpenSquare(x?: CSSToken | null): x is TokenOpenSquare;
export declare function isTokenPercentage(x?: CSSToken | null): x is TokenPercentage;
export declare function isTokenSemicolon(x?: CSSToken | null): x is TokenSemicolon;
export declare function isTokenString(x?: CSSToken | null): x is TokenString;
export declare function isTokenUnicodeRange(x?: CSSToken | null): x is TokenUnicodeRange;
export declare function isTokenURL(x?: CSSToken | null): x is TokenURL;
export declare function isTokenWhitespace(x?: CSSToken | null): x is TokenWhitespace;
/**
* Assert that a token is a whitespace or comment token
*/
export declare function isTokenWhiteSpaceOrComment(x?: CSSToken | null): x is TokenWhitespace | TokenComment;
/**
* Get the mirror variant of a given token
*
* @example
*
* ```js
* const input = [TokenType.OpenParen, '(', 0, 1, undefined];
* const output = mirrorVariant(input);
*
* console.log(output); // [TokenType.CloseParen, ')', -1, -1, undefined]
* ```
*/
export declare function mirrorVariant(token: CSSToken): CSSToken | null;
/**
* Get the mirror variant type of a given token type
*
* @example
*
* ```js
* const input = TokenType.OpenParen;
* const output = mirrorVariantType(input);
*
* console.log(output); // TokenType.CloseParen
* ```
*/
export declare function mirrorVariantType(type: TokenType): TokenType | null;
/**
* Set the ident value and update the string representation.
* This handles escaping.
*/
export declare function mutateIdent(ident: TokenIdent, newValue: string): void;
/**
* Set the unit and update the string representation.
* This handles escaping.
*/
export declare function mutateUnit(ident: TokenDimension, newUnit: string): void;
/**
* The type of number token
* Either `integer` or `number`
*/
export declare enum NumberType {
Integer = "integer",
Number = "number"
}
/**
* The union of all possible CSS tokens that represent a numeric value
*/
export declare type NumericToken = TokenDimension | TokenNumber | TokenPercentage;
/**
* The CSS Tokenizer is forgiving and will never throw on invalid input.
* Any errors are reported through the `onParseError` callback.
*/
export declare class ParseError extends Error {
/** The index of the start character of the current token. */
sourceStart: number;
/** The index of the end character of the current token. */
sourceEnd: number;
/** The parser steps that preceded the error. */
parserState: Array<string>;
constructor(message: string, sourceStart: number, sourceEnd: number, parserState: Array<string>);
}
export declare const ParseErrorMessage: {
UnexpectedNewLineInString: string;
UnexpectedEOFInString: string;
UnexpectedEOFInComment: string;
UnexpectedEOFInURL: string;
UnexpectedEOFInEscapedCodePoint: string;
UnexpectedCharacterInURL: string;
InvalidEscapeSequenceInURL: string;
InvalidEscapeSequenceAfterBackslash: string;
};
export declare class ParseErrorWithToken extends ParseError {
/** The associated token. */
token: CSSToken;
constructor(message: string, sourceStart: number, sourceEnd: number, parserState: Array<string>, token: CSSToken);
}
/**
* Concatenate the string representation of a list of tokens.
* This is not a proper serializer that will handle escaping and whitespace.
* It only produces valid CSS for a token list that is also valid.
*/
export declare function stringify(...tokens: Array<CSSToken>): string;
/**
* The CSS Token interface
*
* @remarks
* CSS Tokens are fully typed and have a strict structure.
* This makes it easier to iterate and analyze a token stream.
*
* The string representation and the parsed value are stored separately for many token types.
* It is always assumed that the string representation will be used when stringifying, while the parsed value should be used when analyzing tokens.
*/
export declare interface Token<T extends TokenType, U> extends Array<T | string | number | U> {
/**
* The type of token
*/
0: T;
/**
* The token representation
*
* @remarks
* This field will be used when stringifying the token.
* Any stored value is assumed to be valid CSS.
*
* You should never use this field when analyzing the token when there is a parsed value available.
* But you must store mutated values here.
*/
1: string;
/**
* Start position of representation
*/
2: number;
/**
* End position of representation
*/
3: number;
/**
* Extra data
*
* @remarks
* This holds the parsed value of each token.
* These values are unescaped, unquoted, converted to numbers, etc.
*
* You should always use this field when analyzing the token.
* But you must not assume that mutating only this field will have any effect.
*/
4: U;
}
export declare interface TokenAtKeyword extends Token<TokenType.AtKeyword, {
/**
* The unescaped at-keyword name without the leading `@`.
*/
value: string;
}> {
}
export declare interface TokenBadString extends Token<TokenType.BadString, undefined> {
}
export declare interface TokenBadURL extends Token<TokenType.BadURL, undefined> {
}
export declare interface TokenCDC extends Token<TokenType.CDC, undefined> {
}
export declare interface TokenCDO extends Token<TokenType.CDO, undefined> {
}
export declare interface TokenCloseCurly extends Token<TokenType.CloseCurly, undefined> {
}
export declare interface TokenCloseParen extends Token<TokenType.CloseParen, undefined> {
}
export declare interface TokenCloseSquare extends Token<TokenType.CloseSquare, undefined> {
}
export declare interface TokenColon extends Token<TokenType.Colon, undefined> {
}
export declare interface TokenComma extends Token<TokenType.Comma, undefined> {
}
export declare interface TokenComment extends Token<TokenType.Comment, undefined> {
}
export declare interface TokenDelim extends Token<TokenType.Delim, {
/**
* The delim character.
*/
value: string;
}> {
}
export declare interface TokenDimension extends Token<TokenType.Dimension, {
/**
* The numeric value.
*/
value: number;
/**
* The unescaped unit name.
*/
unit: string;
/**
* `integer` or `number`
*/
type: NumberType;
/**
* The sign character as it appeared in the source.
* This is only useful if you need to determine if a value was written as "2px" or "+2px".
*/
signCharacter?: '+' | '-';
}> {
}
export declare interface TokenEOF extends Token<TokenType.EOF, undefined> {
}
export declare interface TokenFunction extends Token<TokenType.Function, {
/**
* The unescaped function name without the trailing `(`.
*/
value: string;
}> {
}
export declare interface TokenHash extends Token<TokenType.Hash, {
/**
* The unescaped hash value without the leading `#`.
*/
value: string;
/**
* The hash type.
*/
type: HashType;
}> {
}
export declare interface TokenIdent extends Token<TokenType.Ident, {
/**
* The unescaped ident value.
*/
value: string;
}> {
}
/**
* Tokenize a CSS string into a list of tokens.
*/
export declare function tokenize(input: {
css: {
valueOf(): string;
};
unicodeRangesAllowed?: boolean;
}, options?: {
onParseError?: (error: ParseError) => void;
}): Array<CSSToken>;
/**
* Create a tokenizer for a CSS string.
*/
export declare function tokenizer(input: {
css: {
valueOf(): string;
};
unicodeRangesAllowed?: boolean;
}, options?: {
onParseError?: (error: ParseError) => void;
}): {
nextToken: () => CSSToken;
endOfFile: () => boolean;
};
export declare interface TokenNumber extends Token<TokenType.Number, {
/**
* The numeric value.
*/
value: number;
/**
* `integer` or `number`
*/
type: NumberType;
/**
* The sign character as it appeared in the source.
* This is only useful if you need to determine if a value was written as "2" or "+2".
*/
signCharacter?: '+' | '-';
}> {
}
export declare interface TokenOpenCurly extends Token<TokenType.OpenCurly, undefined> {
}
export declare interface TokenOpenParen extends Token<TokenType.OpenParen, undefined> {
}
export declare interface TokenOpenSquare extends Token<TokenType.OpenSquare, undefined> {
}
export declare interface TokenPercentage extends Token<TokenType.Percentage, {
/**
* The numeric value.
*/
value: number;
/**
* The sign character as it appeared in the source.
* This is only useful if you need to determine if a value was written as "2%" or "+2%".
*/
signCharacter?: '+' | '-';
}> {
}
export declare interface TokenSemicolon extends Token<TokenType.Semicolon, undefined> {
}
export declare interface TokenString extends Token<TokenType.String, {
/**
* The unescaped string value without the leading and trailing quotes.
*/
value: string;
}> {
}
/**
* All possible CSS token types
*/
export declare enum TokenType {
/**
* @see {@link https://www.w3.org/TR/2021/CRD-css-syntax-3-20211224/#comment-diagram}
*/
Comment = "comment",
/**
* @see {@link https://www.w3.org/TR/2021/CRD-css-syntax-3-20211224/#typedef-at-keyword-token}
*/
AtKeyword = "at-keyword-token",
/**
* @see {@link https://www.w3.org/TR/2021/CRD-css-syntax-3-20211224/#typedef-bad-string-token}
*/
BadString = "bad-string-token",
/**
* @see {@link https://www.w3.org/TR/2021/CRD-css-syntax-3-20211224/#typedef-bad-url-token}
*/
BadURL = "bad-url-token",
/**
* @see {@link https://www.w3.org/TR/2021/CRD-css-syntax-3-20211224/#typedef-cdc-token}
*/
CDC = "CDC-token",
/**
* @see {@link https://www.w3.org/TR/2021/CRD-css-syntax-3-20211224/#typedef-cdo-token}
*/
CDO = "CDO-token",
/**
* @see {@link https://www.w3.org/TR/2021/CRD-css-syntax-3-20211224/#typedef-colon-token}
*/
Colon = "colon-token",
/**
* @see {@link https://www.w3.org/TR/2021/CRD-css-syntax-3-20211224/#typedef-comma-token}
*/
Comma = "comma-token",
/**
* @see {@link https://www.w3.org/TR/2021/CRD-css-syntax-3-20211224/#typedef-delim-token}
*/
Delim = "delim-token",
/**
* @see {@link https://www.w3.org/TR/2021/CRD-css-syntax-3-20211224/#typedef-dimension-token}
*/
Dimension = "dimension-token",
/**
* @see {@link https://www.w3.org/TR/2021/CRD-css-syntax-3-20211224/#typedef-eof-token}
*/
EOF = "EOF-token",
/**
* @see {@link https://www.w3.org/TR/2021/CRD-css-syntax-3-20211224/#typedef-function-token}
*/
Function = "function-token",
/**
* @see {@link https://www.w3.org/TR/2021/CRD-css-syntax-3-20211224/#typedef-hash-token}
*/
Hash = "hash-token",
/**
* @see {@link https://www.w3.org/TR/2021/CRD-css-syntax-3-20211224/#typedef-ident-token}
*/
Ident = "ident-token",
/**
* @see {@link https://www.w3.org/TR/2021/CRD-css-syntax-3-20211224/#typedef-percentage-token}
*/
Number = "number-token",
/**
* @see {@link https://www.w3.org/TR/2021/CRD-css-syntax-3-20211224/#typedef-percentage-token}
*/
Percentage = "percentage-token",
/**
* @see {@link https://www.w3.org/TR/2021/CRD-css-syntax-3-20211224/#typedef-semicolon-token}
*/
Semicolon = "semicolon-token",
/**
* @see {@link https://www.w3.org/TR/2021/CRD-css-syntax-3-20211224/#typedef-string-token}
*/
String = "string-token",
/**
* @see {@link https://www.w3.org/TR/2021/CRD-css-syntax-3-20211224/#typedef-url-token}
*/
URL = "url-token",
/**
* @see {@link https://www.w3.org/TR/2021/CRD-css-syntax-3-20211224/#typedef-whitespace-token}
*/
Whitespace = "whitespace-token",
/**
* @see {@link https://www.w3.org/TR/2021/CRD-css-syntax-3-20211224/#tokendef-open-paren}
*/
OpenParen = "(-token",
/**
* @see {@link https://www.w3.org/TR/2021/CRD-css-syntax-3-20211224/#tokendef-close-paren}
*/
CloseParen = ")-token",
/**
* @see {@link https://www.w3.org/TR/2021/CRD-css-syntax-3-20211224/#tokendef-open-square}
*/
OpenSquare = "[-token",
/**
* @see {@link https://www.w3.org/TR/2021/CRD-css-syntax-3-20211224/#tokendef-close-square}
*/
CloseSquare = "]-token",
/**
* @see {@link https://www.w3.org/TR/2021/CRD-css-syntax-3-20211224/#tokendef-open-curly}
*/
OpenCurly = "{-token",
/**
* @see {@link https://www.w3.org/TR/2021/CRD-css-syntax-3-20211224/#tokendef-close-curly}
*/
CloseCurly = "}-token",
/**
* Only appears in the token stream when the `unicodeRangesAllowed` option is set to true.
*
* @example
* ```js
* import { tokenize } from '@csstools/css-tokenizer';
*
* const tokens = tokenize({
* css: `U+0025-00FF, U+4??`,
* unicodeRangesAllowed: true,
* });
*
* console.log(tokens);
* ```
*
* @see {@link https://drafts.csswg.org/css-syntax/#typedef-unicode-range-token}
*/
UnicodeRange = "unicode-range-token"
}
export declare interface TokenUnicodeRange extends Token<TokenType.UnicodeRange, {
startOfRange: number;
endOfRange: number;
}> {
}
export declare interface TokenURL extends Token<TokenType.URL, {
/**
* The unescaped URL value without the leading `url(` and trailing `)`.
*/
value: string;
}> {
}
export declare interface TokenWhitespace extends Token<TokenType.Whitespace, undefined> {
}
export { }

1
node_modules/@csstools/css-tokenizer/dist/index.mjs generated vendored Normal file

File diff suppressed because one or more lines are too long

62
node_modules/@csstools/css-tokenizer/package.json generated vendored Normal file
View file

@ -0,0 +1,62 @@
{
"name": "@csstools/css-tokenizer",
"description": "Tokenize CSS",
"version": "3.0.4",
"contributors": [
{
"name": "Antonio Laguna",
"email": "antonio@laguna.es",
"url": "https://antonio.laguna.es"
},
{
"name": "Romain Menke",
"email": "romainmenke@gmail.com"
}
],
"license": "MIT",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/csstools"
},
{
"type": "opencollective",
"url": "https://opencollective.com/csstools"
}
],
"engines": {
"node": ">=18"
},
"type": "module",
"main": "dist/index.cjs",
"module": "dist/index.mjs",
"exports": {
".": {
"import": {
"types": "./dist/index.d.ts",
"default": "./dist/index.mjs"
},
"require": {
"default": "./dist/index.cjs"
}
}
},
"files": [
"CHANGELOG.md",
"LICENSE.md",
"README.md",
"dist"
],
"scripts": {},
"homepage": "https://github.com/csstools/postcss-plugins/tree/main/packages/css-tokenizer#readme",
"repository": {
"type": "git",
"url": "git+https://github.com/csstools/postcss-plugins.git",
"directory": "packages/css-tokenizer"
},
"bugs": "https://github.com/csstools/postcss-plugins/issues",
"keywords": [
"css",
"tokenizer"
]
}

View file

@ -0,0 +1,10 @@
# Changes to Media Query List Parser
### 4.0.3
_May 27, 2025_
- Updated [`@csstools/css-tokenizer`](https://github.com/csstools/postcss-plugins/tree/main/packages/css-tokenizer) to [`3.0.4`](https://github.com/csstools/postcss-plugins/tree/main/packages/css-tokenizer/CHANGELOG.md#304) (patch)
- Updated [`@csstools/css-parser-algorithms`](https://github.com/csstools/postcss-plugins/tree/main/packages/css-parser-algorithms) to [`3.0.5`](https://github.com/csstools/postcss-plugins/tree/main/packages/css-parser-algorithms/CHANGELOG.md#305) (patch)
[Full CHANGELOG](https://github.com/csstools/postcss-plugins/tree/main/packages/media-query-list-parser/CHANGELOG.md)

View file

@ -0,0 +1,20 @@
The MIT License (MIT)
Copyright 2022 Romain Menke, Antonio Laguna <antonio@laguna.es>
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View file

@ -0,0 +1,61 @@
# Media Query List Parser <img src="https://cssdb.org/images/css.svg" alt="for CSS" width="90" height="90" align="right">
[<img alt="npm version" src="https://img.shields.io/npm/v/@csstools/media-query-list-parser.svg" height="20">][npm-url]
[<img alt="Build Status" src="https://github.com/csstools/postcss-plugins/actions/workflows/test.yml/badge.svg?branch=main" height="20">][cli-url]
[<img alt="Discord" src="https://shields.io/badge/Discord-5865F2?logo=discord&logoColor=white">][discord]
Implemented from : https://www.w3.org/TR/mediaqueries-5/
## Usage
Add [Media Query List Parser] to your project:
```bash
npm install @csstools/media-query-list-parser @csstools/css-parser-algorithms @csstools/css-tokenizer --save-dev
```
[Media Query List Parser] depends on our CSS tokenizer and parser algorithms.
It must be used together with `@csstools/css-tokenizer` and `@csstools/css-parser-algorithms`.
```ts
import { parse } from '@csstools/media-query-list-parser';
export function parseCustomMedia() {
const mediaQueryList = parse('screen and (min-width: 300px), (50px < height < 30vw)');
mediaQueryList.forEach((mediaQuery) => {
mediaQuery.walk((entry, index) => {
// Index of the current Node in `parent`.
console.log(index);
// Type of `parent`.
console.log(entry.parent.type);
// Type of `node`
{
// Sometimes nodes can be arrays.
if (Array.isArray(entry.node)) {
entry.node.forEach((item) => {
console.log(item.type);
});
}
if ('type' in entry.node) {
console.log(entry.node.type);
}
}
// stringified version of the current node.
console.log(entry.node.toString());
// Return `false` to stop the walker.
return false;
});
});
}
```
[cli-url]: https://github.com/csstools/postcss-plugins/actions/workflows/test.yml?query=workflow/test
[discord]: https://discord.gg/bUadyRwkJS
[npm-url]: https://www.npmjs.com/package/@csstools/media-query-list-parser
[Media Query List Parser]: https://github.com/csstools/postcss-plugins/tree/main/packages/media-query-list-parser

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,775 @@
import type { ComponentValue } from '@csstools/css-parser-algorithms';
import type { ContainerNode } from '@csstools/css-parser-algorithms';
import { CSSToken } from '@csstools/css-tokenizer';
import type { ParseError } from '@csstools/css-tokenizer';
import type { TokenColon } from '@csstools/css-tokenizer';
import type { TokenDelim } from '@csstools/css-tokenizer';
import type { TokenIdent } from '@csstools/css-tokenizer';
export declare function cloneMediaQuery<T extends MediaQueryWithType | MediaQueryWithoutType | MediaQueryInvalid>(x: T): T;
export declare function comparisonFromTokens(tokens: [TokenDelim, TokenDelim] | [TokenDelim]): MediaFeatureComparison | false;
export declare class CustomMedia {
type: NodeType;
name: Array<CSSToken>;
mediaQueryList: Array<MediaQuery> | null;
trueOrFalseKeyword: Array<CSSToken> | null;
constructor(name: Array<CSSToken>, mediaQueryList: Array<MediaQuery> | null, trueOrFalseKeyword?: Array<CSSToken>);
getName(): string;
getNameToken(): CSSToken | null;
hasMediaQueryList(): boolean;
hasTrueKeyword(): boolean;
hasFalseKeyword(): boolean;
tokens(): Array<CSSToken>;
toString(): string;
/**
* @internal
*/
toJSON(): Record<string, unknown>;
/**
* @internal
*/
isCustomMedia(): this is CustomMedia;
static isCustomMedia(x: unknown): x is CustomMedia;
}
export declare class GeneralEnclosed {
type: NodeType;
value: ComponentValue;
constructor(value: ComponentValue);
tokens(): Array<CSSToken>;
toString(): string;
/**
* @internal
*/
hasLeadingSpace(): boolean;
indexOf(item: ComponentValue): number | string;
at(index: number | string): ComponentValue | undefined;
walk<T extends Record<string, unknown>>(cb: (entry: {
node: GeneralEnclosedWalkerEntry;
parent: GeneralEnclosedWalkerParent;
state?: T;
}, index: number | string) => boolean | void, state?: T): false | undefined;
/**
* @internal
*/
toJSON(): Record<string, unknown>;
/**
* @internal
*/
isGeneralEnclosed(): this is GeneralEnclosed;
static isGeneralEnclosed(x: unknown): x is GeneralEnclosed;
}
export declare type GeneralEnclosedWalkerEntry = ComponentValue;
export declare type GeneralEnclosedWalkerParent = ContainerNode | GeneralEnclosed;
export declare function invertComparison(operator: MediaFeatureComparison): MediaFeatureComparison | false;
export declare function isCustomMedia(x: unknown): x is GeneralEnclosed;
export declare function isGeneralEnclosed(x: unknown): x is GeneralEnclosed;
export declare function isMediaAnd(x: unknown): x is MediaAnd;
export declare function isMediaCondition(x: unknown): x is MediaCondition;
export declare function isMediaConditionList(x: unknown): x is MediaConditionList;
export declare function isMediaConditionListWithAnd(x: unknown): x is MediaConditionListWithAnd;
export declare function isMediaConditionListWithOr(x: unknown): x is MediaConditionListWithOr;
export declare function isMediaFeature(x: unknown): x is MediaFeature;
export declare function isMediaFeatureBoolean(x: unknown): x is MediaFeatureBoolean;
export declare function isMediaFeatureName(x: unknown): x is MediaFeatureName;
export declare function isMediaFeaturePlain(x: unknown): x is MediaFeaturePlain;
export declare function isMediaFeatureRange(x: unknown): x is MediaFeatureRange;
export declare function isMediaFeatureRangeNameValue(x: unknown): x is MediaFeatureRangeNameValue;
export declare function isMediaFeatureRangeValueName(x: unknown): x is MediaFeatureRangeValueName;
export declare function isMediaFeatureRangeValueNameValue(x: unknown): x is MediaFeatureRangeValueNameValue;
export declare function isMediaFeatureValue(x: unknown): x is MediaFeatureValue;
export declare function isMediaInParens(x: unknown): x is MediaInParens;
export declare function isMediaNot(x: unknown): x is MediaNot;
export declare function isMediaOr(x: unknown): x is MediaOr;
export declare function isMediaQuery(x: unknown): x is MediaQuery;
export declare function isMediaQueryInvalid(x: unknown): x is MediaQueryInvalid;
export declare function isMediaQueryWithoutType(x: unknown): x is MediaQueryWithoutType;
export declare function isMediaQueryWithType(x: unknown): x is MediaQueryWithType;
export declare function matchesComparison(componentValues: Array<ComponentValue>): false | [number, number];
export declare function matchesRatio(componentValues: Array<ComponentValue>): -1 | [number, number];
export declare function matchesRatioExactly(componentValues: Array<ComponentValue>): -1 | [number, number];
export declare class MediaAnd {
type: NodeType;
modifier: Array<CSSToken>;
media: MediaInParens;
constructor(modifier: Array<CSSToken>, media: MediaInParens);
tokens(): Array<CSSToken>;
toString(): string;
/**
* @internal
*/
hasLeadingSpace(): boolean;
indexOf(item: MediaInParens): number | string;
at(index: number | string): MediaInParens | null;
walk<T extends Record<string, unknown>>(cb: (entry: {
node: MediaAndWalkerEntry;
parent: MediaAndWalkerParent;
state?: T;
}, index: number | string) => boolean | void, state?: T): false | undefined;
/**
* @internal
*/
toJSON(): unknown;
/**
* @internal
*/
isMediaAnd(): this is MediaAnd;
static isMediaAnd(x: unknown): x is MediaAnd;
}
export declare type MediaAndWalkerEntry = MediaInParensWalkerEntry | MediaInParens;
export declare type MediaAndWalkerParent = MediaInParensWalkerParent | MediaAnd;
export declare class MediaCondition {
type: NodeType;
media: MediaNot | MediaInParens | MediaConditionListWithAnd | MediaConditionListWithOr;
constructor(media: MediaNot | MediaInParens | MediaConditionListWithAnd | MediaConditionListWithOr);
tokens(): Array<CSSToken>;
toString(): string;
/**
* @internal
*/
hasLeadingSpace(): boolean;
indexOf(item: MediaNot | MediaInParens | MediaConditionListWithAnd | MediaConditionListWithOr): number | string;
at(index: number | string): MediaNot | MediaInParens | MediaConditionListWithAnd | MediaConditionListWithOr | undefined;
walk<T extends Record<string, unknown>>(cb: (entry: {
node: MediaConditionWalkerEntry;
parent: MediaConditionWalkerParent;
state?: T;
}, index: number | string) => boolean | void, state?: T): false | undefined;
/**
* @internal
*/
toJSON(): unknown;
/**
* @internal
*/
isMediaCondition(): this is MediaCondition;
static isMediaCondition(x: unknown): x is MediaCondition;
}
export declare type MediaConditionList = MediaConditionListWithAnd | MediaConditionListWithOr;
export declare class MediaConditionListWithAnd {
type: NodeType;
leading: MediaInParens;
list: Array<MediaAnd>;
before: Array<CSSToken>;
after: Array<CSSToken>;
constructor(leading: MediaInParens, list: Array<MediaAnd>, before?: Array<CSSToken>, after?: Array<CSSToken>);
tokens(): Array<CSSToken>;
toString(): string;
/**
* @internal
*/
hasLeadingSpace(): boolean;
indexOf(item: MediaInParens | MediaAnd): number | string;
at(index: number | string): MediaInParens | MediaAnd | undefined;
walk<T extends Record<string, unknown>>(cb: (entry: {
node: MediaConditionListWithAndWalkerEntry;
parent: MediaConditionListWithAndWalkerParent;
state?: T;
}, index: number | string) => boolean | void, state?: T): false | undefined;
toJSON(): unknown;
isMediaConditionListWithAnd(): this is MediaConditionListWithAnd;
static isMediaConditionListWithAnd(x: unknown): x is MediaConditionListWithAnd;
}
export declare type MediaConditionListWithAndWalkerEntry = MediaAndWalkerEntry | MediaAnd;
export declare type MediaConditionListWithAndWalkerParent = MediaAndWalkerParent | MediaConditionListWithAnd;
export declare class MediaConditionListWithOr {
type: NodeType;
leading: MediaInParens;
list: Array<MediaOr>;
before: Array<CSSToken>;
after: Array<CSSToken>;
constructor(leading: MediaInParens, list: Array<MediaOr>, before?: Array<CSSToken>, after?: Array<CSSToken>);
tokens(): Array<CSSToken>;
toString(): string;
/**
* @internal
*/
hasLeadingSpace(): boolean;
indexOf(item: MediaInParens | MediaOr): number | string;
at(index: number | string): MediaInParens | MediaOr | undefined;
walk<T extends Record<string, unknown>>(cb: (entry: {
node: MediaConditionListWithOrWalkerEntry;
parent: MediaConditionListWithOrWalkerParent;
state?: T;
}, index: number | string) => boolean | void, state?: T): false | undefined;
/**
* @internal
*/
toJSON(): unknown;
/**
* @internal
*/
isMediaConditionListWithOr(): this is MediaConditionListWithOr;
static isMediaConditionListWithOr(x: unknown): x is MediaConditionListWithOr;
}
export declare type MediaConditionListWithOrWalkerEntry = MediaOrWalkerEntry | MediaOr;
export declare type MediaConditionListWithOrWalkerParent = MediaOrWalkerParent | MediaConditionListWithOr;
export declare type MediaConditionWalkerEntry = MediaNotWalkerEntry | MediaConditionListWithAndWalkerEntry | MediaConditionListWithOrWalkerEntry | MediaNot | MediaConditionListWithAnd | MediaConditionListWithOr;
export declare type MediaConditionWalkerParent = MediaNotWalkerParent | MediaConditionListWithAndWalkerParent | MediaConditionListWithOrWalkerParent | MediaCondition;
export declare class MediaFeature {
type: NodeType;
feature: MediaFeaturePlain | MediaFeatureBoolean | MediaFeatureRange;
before: Array<CSSToken>;
after: Array<CSSToken>;
constructor(feature: MediaFeaturePlain | MediaFeatureBoolean | MediaFeatureRange, before?: Array<CSSToken>, after?: Array<CSSToken>);
getName(): string;
getNameToken(): CSSToken;
tokens(): Array<CSSToken>;
toString(): string;
/**
* @internal
*/
hasLeadingSpace(): boolean;
indexOf(item: MediaFeaturePlain | MediaFeatureBoolean | MediaFeatureRange): number | string;
at(index: number | string): MediaFeatureBoolean | MediaFeaturePlain | MediaFeatureRange | undefined;
walk<T extends Record<string, unknown>>(cb: (entry: {
node: MediaFeatureWalkerEntry;
parent: MediaFeatureWalkerParent;
state?: T;
}, index: number | string) => boolean | void, state?: T): false | undefined;
/**
* @internal
*/
toJSON(): Record<string, unknown>;
/**
* @internal
*/
isMediaFeature(): this is MediaFeature;
static isMediaFeature(x: unknown): x is MediaFeature;
}
export declare class MediaFeatureBoolean {
type: NodeType;
name: MediaFeatureName;
constructor(name: MediaFeatureName);
getName(): string;
getNameToken(): CSSToken;
tokens(): Array<CSSToken>;
toString(): string;
indexOf(item: MediaFeatureName): number | string;
at(index: number | string): MediaFeatureName | undefined;
/**
* @internal
*/
toJSON(): Record<string, unknown>;
/**
* @internal
*/
isMediaFeatureBoolean(): this is MediaFeatureBoolean;
static isMediaFeatureBoolean(x: unknown): x is MediaFeatureBoolean;
}
export declare type MediaFeatureComparison = MediaFeatureLT | MediaFeatureGT | MediaFeatureEQ;
export declare enum MediaFeatureEQ {
EQ = "="
}
export declare enum MediaFeatureGT {
GT = ">",
GT_OR_EQ = ">="
}
export declare enum MediaFeatureLT {
LT = "<",
LT_OR_EQ = "<="
}
export declare class MediaFeatureName {
type: NodeType;
name: ComponentValue;
before: Array<CSSToken>;
after: Array<CSSToken>;
constructor(name: ComponentValue, before?: Array<CSSToken>, after?: Array<CSSToken>);
getName(): string;
getNameToken(): CSSToken;
tokens(): Array<CSSToken>;
toString(): string;
indexOf(item: ComponentValue): number | string;
at(index: number | string): ComponentValue | undefined;
/**
* @internal
*/
toJSON(): Record<string, unknown>;
/**
* @internal
*/
isMediaFeatureName(): this is MediaFeatureName;
static isMediaFeatureName(x: unknown): x is MediaFeatureName;
}
export declare class MediaFeaturePlain {
type: NodeType;
name: MediaFeatureName;
colon: TokenColon;
value: MediaFeatureValue;
constructor(name: MediaFeatureName, colon: TokenColon, value: MediaFeatureValue);
getName(): string;
getNameToken(): CSSToken;
tokens(): Array<CSSToken>;
toString(): string;
indexOf(item: MediaFeatureName | MediaFeatureValue): number | string;
at(index: number | string): MediaFeatureName | MediaFeatureValue | undefined;
walk<T extends Record<string, unknown>>(cb: (entry: {
node: MediaFeaturePlainWalkerEntry;
parent: MediaFeaturePlainWalkerParent;
state?: T;
}, index: number | string) => boolean | void, state?: T): false | undefined;
/**
* @internal
*/
toJSON(): Record<string, unknown>;
/**
* @internal
*/
isMediaFeaturePlain(): this is MediaFeaturePlain;
static isMediaFeaturePlain(x: unknown): x is MediaFeaturePlain;
}
export declare type MediaFeaturePlainWalkerEntry = MediaFeatureValueWalkerEntry | MediaFeatureValue;
export declare type MediaFeaturePlainWalkerParent = MediaFeatureValueWalkerParent | MediaFeaturePlain;
export declare type MediaFeatureRange = MediaFeatureRangeNameValue | MediaFeatureRangeValueName | MediaFeatureRangeValueNameValue;
export declare class MediaFeatureRangeNameValue {
type: NodeType;
name: MediaFeatureName;
operator: [TokenDelim, TokenDelim] | [TokenDelim];
value: MediaFeatureValue;
constructor(name: MediaFeatureName, operator: [TokenDelim, TokenDelim] | [TokenDelim], value: MediaFeatureValue);
operatorKind(): MediaFeatureComparison | false;
getName(): string;
getNameToken(): CSSToken;
tokens(): Array<CSSToken>;
toString(): string;
indexOf(item: MediaFeatureName | MediaFeatureValue): number | string;
at(index: number | string): MediaFeatureName | MediaFeatureValue | undefined;
walk<T extends Record<string, unknown>>(cb: (entry: {
node: MediaFeatureRangeWalkerEntry;
parent: MediaFeatureRangeWalkerParent;
state?: T;
}, index: number | string) => boolean | void, state?: T): false | undefined;
/**
* @internal
*/
toJSON(): Record<string, unknown>;
/**
* @internal
*/
isMediaFeatureRangeNameValue(): this is MediaFeatureRangeNameValue;
static isMediaFeatureRangeNameValue(x: unknown): x is MediaFeatureRangeNameValue;
}
export declare class MediaFeatureRangeValueName {
type: NodeType;
name: MediaFeatureName;
operator: [TokenDelim, TokenDelim] | [TokenDelim];
value: MediaFeatureValue;
constructor(name: MediaFeatureName, operator: [TokenDelim, TokenDelim] | [TokenDelim], value: MediaFeatureValue);
operatorKind(): MediaFeatureComparison | false;
getName(): string;
getNameToken(): CSSToken;
tokens(): Array<CSSToken>;
toString(): string;
indexOf(item: MediaFeatureName | MediaFeatureValue): number | string;
at(index: number | string): MediaFeatureName | MediaFeatureValue | undefined;
walk<T extends Record<string, unknown>>(cb: (entry: {
node: MediaFeatureRangeWalkerEntry;
parent: MediaFeatureRangeWalkerParent;
state?: T;
}, index: number | string) => boolean | void, state?: T): false | undefined;
/**
* @internal
*/
toJSON(): Record<string, unknown>;
/**
* @internal
*/
isMediaFeatureRangeValueName(): this is MediaFeatureRangeValueName;
static isMediaFeatureRangeValueName(x: unknown): x is MediaFeatureRangeValueName;
}
export declare class MediaFeatureRangeValueNameValue {
type: NodeType;
name: MediaFeatureName;
valueOne: MediaFeatureValue;
valueOneOperator: [TokenDelim, TokenDelim] | [TokenDelim];
valueTwo: MediaFeatureValue;
valueTwoOperator: [TokenDelim, TokenDelim] | [TokenDelim];
constructor(name: MediaFeatureName, valueOne: MediaFeatureValue, valueOneOperator: [TokenDelim, TokenDelim] | [TokenDelim], valueTwo: MediaFeatureValue, valueTwoOperator: [TokenDelim, TokenDelim] | [TokenDelim]);
valueOneOperatorKind(): MediaFeatureComparison | false;
valueTwoOperatorKind(): MediaFeatureComparison | false;
getName(): string;
getNameToken(): CSSToken;
tokens(): Array<CSSToken>;
toString(): string;
indexOf(item: MediaFeatureName | MediaFeatureValue): number | string;
at(index: number | string): MediaFeatureName | MediaFeatureValue | undefined;
walk<T extends Record<string, unknown>>(cb: (entry: {
node: MediaFeatureRangeWalkerEntry;
parent: MediaFeatureRangeWalkerParent;
state?: T;
}, index: number | string) => boolean | void, state?: T): false | undefined;
/**
* @internal
*/
toJSON(): Record<string, unknown>;
/**
* @internal
*/
isMediaFeatureRangeValueNameValue(): this is MediaFeatureRangeValueNameValue;
static isMediaFeatureRangeValueNameValue(x: unknown): x is MediaFeatureRangeValueNameValue;
}
export declare type MediaFeatureRangeWalkerEntry = MediaFeatureValueWalkerEntry | MediaFeatureValue;
export declare type MediaFeatureRangeWalkerParent = MediaFeatureValueWalkerParent | MediaFeatureRange;
export declare class MediaFeatureValue {
type: NodeType;
value: ComponentValue | Array<ComponentValue>;
before: Array<CSSToken>;
after: Array<CSSToken>;
constructor(value: ComponentValue | Array<ComponentValue>, before?: Array<CSSToken>, after?: Array<CSSToken>);
tokens(): Array<CSSToken>;
toString(): string;
indexOf(item: ComponentValue): number | string;
at(index: number | string): ComponentValue | Array<ComponentValue> | undefined;
walk<T extends Record<string, unknown>>(cb: (entry: {
node: MediaFeatureValueWalkerEntry;
parent: MediaFeatureValueWalkerParent;
state?: T;
}, index: number | string) => boolean | void, state?: T): false | undefined;
/**
* @internal
*/
toJSON(): Record<string, unknown>;
/**
* @internal
*/
isMediaFeatureValue(): this is MediaFeatureValue;
static isMediaFeatureValue(x: unknown): x is MediaFeatureValue;
}
export declare type MediaFeatureValueWalkerEntry = ComponentValue;
export declare type MediaFeatureValueWalkerParent = ContainerNode | MediaFeatureValue;
export declare type MediaFeatureWalkerEntry = MediaFeaturePlainWalkerEntry | MediaFeatureRangeWalkerEntry | MediaFeaturePlain | MediaFeatureBoolean | MediaFeatureRange;
export declare type MediaFeatureWalkerParent = MediaFeaturePlainWalkerParent | MediaFeatureRangeWalkerParent | MediaFeature;
export declare class MediaInParens {
type: NodeType;
media: MediaCondition | MediaFeature | GeneralEnclosed;
before: Array<CSSToken>;
after: Array<CSSToken>;
constructor(media: MediaCondition | MediaFeature | GeneralEnclosed, before?: Array<CSSToken>, after?: Array<CSSToken>);
tokens(): Array<CSSToken>;
toString(): string;
/**
* @internal
*/
hasLeadingSpace(): boolean;
indexOf(item: MediaCondition | MediaFeature | GeneralEnclosed): number | string;
at(index: number | string): MediaCondition | MediaFeature | GeneralEnclosed | undefined;
walk<T extends Record<string, unknown>>(cb: (entry: {
node: MediaInParensWalkerEntry;
parent: MediaInParensWalkerParent;
state?: T;
}, index: number | string) => boolean | void, state?: T): false | undefined;
/**
* @internal
*/
toJSON(): Record<string, unknown>;
/**
* @internal
*/
isMediaInParens(): this is MediaInParens;
static isMediaInParens(x: unknown): x is MediaInParens;
}
export declare type MediaInParensWalkerEntry = ComponentValue | GeneralEnclosed | MediaAnd | MediaNot | MediaOr | MediaConditionList | MediaCondition | MediaFeatureBoolean | MediaFeatureName | MediaFeaturePlain | MediaFeatureRange | MediaFeatureValue | MediaFeature | MediaInParens;
export declare type MediaInParensWalkerParent = ContainerNode | GeneralEnclosed | MediaAnd | MediaNot | MediaOr | MediaConditionList | MediaCondition | MediaFeatureBoolean | MediaFeatureName | MediaFeaturePlain | MediaFeatureRange | MediaFeatureValue | MediaFeature | MediaInParens;
export declare class MediaNot {
type: NodeType;
modifier: Array<CSSToken>;
media: MediaInParens;
constructor(modifier: Array<CSSToken>, media: MediaInParens);
tokens(): Array<CSSToken>;
toString(): string;
/**
* @internal
*/
hasLeadingSpace(): boolean;
indexOf(item: MediaInParens): number | string;
at(index: number | string): MediaInParens | undefined;
walk<T extends Record<string, unknown>>(cb: (entry: {
node: MediaNotWalkerEntry;
parent: MediaNotWalkerParent;
state?: T;
}, index: number | string) => boolean | void, state?: T): false | undefined;
/**
* @internal
*/
toJSON(): Record<string, unknown>;
/**
* @internal
*/
isMediaNot(): this is MediaNot;
static isMediaNot(x: unknown): x is MediaNot;
}
export declare type MediaNotWalkerEntry = MediaInParensWalkerEntry | MediaInParens;
export declare type MediaNotWalkerParent = MediaInParensWalkerParent | MediaNot;
export declare class MediaOr {
type: NodeType;
modifier: Array<CSSToken>;
media: MediaInParens;
constructor(modifier: Array<CSSToken>, media: MediaInParens);
tokens(): Array<CSSToken>;
toString(): string;
indexOf(item: MediaInParens): number | string;
at(index: number | string): MediaInParens | undefined;
walk<T extends Record<string, unknown>>(cb: (entry: {
node: MediaOrWalkerEntry;
parent: MediaOrWalkerParent;
state?: T;
}, index: number | string) => boolean | void, state?: T): false | undefined;
/**
* @internal
*/
toJSON(): Record<string, unknown>;
/**
* @internal
*/
isMediaOr(): this is MediaOr;
static isMediaOr(x: unknown): x is MediaOr;
}
export declare type MediaOrWalkerEntry = MediaInParensWalkerEntry | MediaInParens;
export declare type MediaOrWalkerParent = MediaInParensWalkerParent | MediaOr;
export declare type MediaQuery = MediaQueryWithType | MediaQueryWithoutType | MediaQueryInvalid;
export declare class MediaQueryInvalid {
type: NodeType;
media: Array<ComponentValue>;
constructor(media: Array<ComponentValue>);
negateQuery(): Array<MediaQuery>;
tokens(): Array<CSSToken>;
toString(): string;
walk<T extends Record<string, unknown>>(cb: (entry: {
node: MediaQueryInvalidWalkerEntry;
parent: MediaQueryInvalidWalkerParent;
state?: T;
}, index: number | string) => boolean | void, state?: T): false | undefined;
/**
* @internal
*/
toJSON(): Record<string, unknown>;
/**
* @internal
*/
isMediaQueryInvalid(): this is MediaQueryInvalid;
static isMediaQueryInvalid(x: unknown): x is MediaQueryInvalid;
}
export declare type MediaQueryInvalidWalkerEntry = ComponentValue;
export declare type MediaQueryInvalidWalkerParent = ComponentValue | MediaQueryInvalid;
export declare enum MediaQueryModifier {
Not = "not",
Only = "only"
}
export declare class MediaQueryWithoutType {
type: NodeType;
media: MediaCondition;
constructor(media: MediaCondition);
negateQuery(): Array<MediaQuery>;
tokens(): Array<CSSToken>;
toString(): string;
indexOf(item: MediaCondition): number | string;
at(index: number | string): MediaCondition | undefined;
walk<T extends Record<string, unknown>>(cb: (entry: {
node: MediaQueryWithoutTypeWalkerEntry;
parent: MediaQueryWithoutTypeWalkerParent;
state?: T;
}, index: number | string) => boolean | void, state?: T): false | undefined;
/**
* @internal
*/
toJSON(): Record<string, unknown>;
/**
* @internal
*/
isMediaQueryWithoutType(): this is MediaQueryWithoutType;
static isMediaQueryWithoutType(x: unknown): x is MediaQueryWithoutType;
}
export declare type MediaQueryWithoutTypeWalkerEntry = MediaConditionWalkerEntry | MediaCondition;
export declare type MediaQueryWithoutTypeWalkerParent = MediaConditionWalkerParent | MediaQueryWithoutType;
export declare class MediaQueryWithType {
type: NodeType;
modifier: Array<CSSToken>;
mediaType: Array<CSSToken>;
and: Array<CSSToken> | undefined;
media: MediaCondition | undefined;
constructor(modifier: Array<CSSToken>, mediaType: Array<CSSToken>, and?: Array<CSSToken>, media?: MediaCondition);
getModifier(): string;
negateQuery(): Array<MediaQuery>;
getMediaType(): string;
tokens(): Array<CSSToken>;
toString(): string;
indexOf(item: MediaCondition): number | string;
at(index: number | string): MediaCondition | undefined;
walk<T extends Record<string, unknown>>(cb: (entry: {
node: MediaQueryWithTypeWalkerEntry;
parent: MediaQueryWithTypeWalkerParent;
state?: T;
}, index: number | string) => boolean | void, state?: T): false | undefined;
/**
* @internal
*/
toJSON(): Record<string, unknown>;
/**
* @internal
*/
isMediaQueryWithType(): this is MediaQueryWithType;
static isMediaQueryWithType(x: unknown): x is MediaQueryWithType;
}
export declare type MediaQueryWithTypeWalkerEntry = MediaConditionWalkerEntry | MediaCondition;
export declare type MediaQueryWithTypeWalkerParent = MediaConditionWalkerParent | MediaQueryWithType;
export declare enum MediaType {
/** Always matches */
All = "all",
Print = "print",
Screen = "screen",
/** Never matches */
Tty = "tty",
/** Never matches */
Tv = "tv",
/** Never matches */
Projection = "projection",
/** Never matches */
Handheld = "handheld",
/** Never matches */
Braille = "braille",
/** Never matches */
Embossed = "embossed",
/** Never matches */
Aural = "aural",
/** Never matches */
Speech = "speech"
}
export declare function modifierFromToken(token: TokenIdent): MediaQueryModifier | false;
export declare function newMediaFeatureBoolean(name: string): MediaFeature;
export declare function newMediaFeaturePlain(name: string, ...value: Array<CSSToken>): MediaFeature;
export declare enum NodeType {
CustomMedia = "custom-media",
GeneralEnclosed = "general-enclosed",
MediaAnd = "media-and",
MediaCondition = "media-condition",
MediaConditionListWithAnd = "media-condition-list-and",
MediaConditionListWithOr = "media-condition-list-or",
MediaFeature = "media-feature",
MediaFeatureBoolean = "mf-boolean",
MediaFeatureName = "mf-name",
MediaFeaturePlain = "mf-plain",
MediaFeatureRangeNameValue = "mf-range-name-value",
MediaFeatureRangeValueName = "mf-range-value-name",
MediaFeatureRangeValueNameValue = "mf-range-value-name-value",
MediaFeatureValue = "mf-value",
MediaInParens = "media-in-parens",
MediaNot = "media-not",
MediaOr = "media-or",
MediaQueryWithType = "media-query-with-type",
MediaQueryWithoutType = "media-query-without-type",
MediaQueryInvalid = "media-query-invalid"
}
export declare function parse(source: string, options?: {
preserveInvalidMediaQueries?: boolean;
onParseError?: (error: ParseError) => void;
}): Array<MediaQuery>;
export declare function parseCustomMedia(source: string, options?: {
preserveInvalidMediaQueries?: boolean;
onParseError?: (error: ParseError) => void;
}): CustomMedia | false;
export declare function parseCustomMediaFromTokens(tokens: Array<CSSToken>, options?: {
preserveInvalidMediaQueries?: boolean;
onParseError?: (error: ParseError) => void;
}): CustomMedia | false;
export declare function parseFromTokens(tokens: Array<CSSToken>, options?: {
preserveInvalidMediaQueries?: boolean;
onParseError?: (error: ParseError) => void;
}): Array<MediaQuery>;
export declare function typeFromToken(token: TokenIdent): MediaType | false;
export { }

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,67 @@
{
"name": "@csstools/media-query-list-parser",
"description": "Parse CSS media query lists.",
"version": "4.0.3",
"contributors": [
{
"name": "Antonio Laguna",
"email": "antonio@laguna.es",
"url": "https://antonio.laguna.es"
},
{
"name": "Romain Menke",
"email": "romainmenke@gmail.com"
}
],
"license": "MIT",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/csstools"
},
{
"type": "opencollective",
"url": "https://opencollective.com/csstools"
}
],
"engines": {
"node": ">=18"
},
"type": "module",
"main": "dist/index.cjs",
"module": "dist/index.mjs",
"exports": {
".": {
"import": {
"types": "./dist/index.d.ts",
"default": "./dist/index.mjs"
},
"require": {
"default": "./dist/index.cjs"
}
}
},
"files": [
"CHANGELOG.md",
"LICENSE.md",
"README.md",
"dist"
],
"peerDependencies": {
"@csstools/css-parser-algorithms": "^3.0.5",
"@csstools/css-tokenizer": "^3.0.4"
},
"scripts": {},
"homepage": "https://github.com/csstools/postcss-plugins/tree/main/packages/media-query-list-parser#readme",
"repository": {
"type": "git",
"url": "git+https://github.com/csstools/postcss-plugins.git",
"directory": "packages/media-query-list-parser"
},
"bugs": "https://github.com/csstools/postcss-plugins/issues",
"keywords": [
"css",
"media query",
"parser"
]
}

View file

@ -0,0 +1,9 @@
# Changes to Selector Specificity
### 5.0.0
_October 23, 2024_
- Updated: `postcss-selector-parser`
[Full CHANGELOG](https://github.com/csstools/postcss-plugins/tree/main/packages/selector-specificity/CHANGELOG.md)

18
node_modules/@csstools/selector-specificity/LICENSE.md generated vendored Normal file
View file

@ -0,0 +1,18 @@
MIT No Attribution (MIT-0)
Copyright © CSSTools Contributors
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the “Software”), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so.
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.

57
node_modules/@csstools/selector-specificity/README.md generated vendored Normal file
View file

@ -0,0 +1,57 @@
# Selector Specificity
[<img alt="npm version" src="https://img.shields.io/npm/v/@csstools/selector-specificity.svg" height="20">][npm-url]
[<img alt="Build Status" src="https://github.com/csstools/postcss-plugins/workflows/test/badge.svg" height="20">][cli-url]
[<img alt="Discord" src="https://shields.io/badge/Discord-5865F2?logo=discord&logoColor=white">][discord]
## Usage
Add [Selector Specificity] to your project:
```bash
npm install @csstools/selector-specificity --save-dev
```
```js
import parser from 'postcss-selector-parser';
import { selectorSpecificity } from '@csstools/selector-specificity';
const selectorAST = parser().astSync('#foo:has(> .foo)');
const specificity = selectorSpecificity(selectorAST);
console.log(specificity.a); // 1
console.log(specificity.b); // 1
console.log(specificity.c); // 0
```
_`selectorSpecificity` takes a single selector, not a list of selectors (not : `a, b, c`).
To compare or otherwise manipulate lists of selectors you need to call `selectorSpecificity` on each part._
### Comparing
The package exports a utility function to compare two specificities.
```js
import { selectorSpecificity, compare } from '@csstools/selector-specificity';
const s1 = selectorSpecificity(ast1);
const s2 = selectorSpecificity(ast2);
compare(s1, s2); // -1 | 0 | 1
```
- if `s1 < s2` then `compare(s1, s2)` returns a negative number (`< 0`)
- if `s1 > s2` then `compare(s1, s2)` returns a positive number (`> 0`)
- if `s1 === s2` then `compare(s1, s2)` returns zero (`=== 0`)
## Prior Art
- [keeganstreet/specificity](https://github.com/keeganstreet/specificity)
- [bramus/specificity](https://github.com/bramus/specificity)
For CSSTools we always use `postcss-selector-parser` and want to calculate specificity from this AST.
[cli-url]: https://github.com/csstools/postcss-plugins/actions/workflows/test.yml?query=workflow/test
[discord]: https://discord.gg/bUadyRwkJS
[npm-url]: https://www.npmjs.com/package/@csstools/selector-specificity
[Selector Specificity]: https://github.com/csstools/postcss-plugins/tree/main/packages/selector-specificity

View file

@ -0,0 +1 @@
"use strict";var e=require("postcss-selector-parser");function compare(e,t){return e.a===t.a?e.b===t.b?e.c-t.c:e.b-t.b:e.a-t.a}function selectorSpecificity(t,s){const i=s?.customSpecificity?.(t);if(i)return i;if(!t)return{a:0,b:0,c:0};let c=0,n=0,o=0;if("universal"==t.type)return{a:0,b:0,c:0};if("id"===t.type)c+=1;else if("tag"===t.type)o+=1;else if("class"===t.type)n+=1;else if("attribute"===t.type)n+=1;else if(isPseudoElement(t))switch(t.value.toLowerCase()){case"::slotted":if(o+=1,t.nodes&&t.nodes.length>0){const e=specificityOfMostSpecificListItem(t.nodes,s);c+=e.a,n+=e.b,o+=e.c}break;case"::view-transition-group":case"::view-transition-image-pair":case"::view-transition-old":case"::view-transition-new":return t.nodes&&1===t.nodes.length&&"selector"===t.nodes[0].type&&selectorNodeContainsNothingOrOnlyUniversal(t.nodes[0])?{a:0,b:0,c:0}:{a:0,b:0,c:1};default:o+=1}else if(e.isPseudoClass(t))switch(t.value.toLowerCase()){case":-webkit-any":case":any":default:n+=1;break;case":-moz-any":case":has":case":is":case":matches":case":not":if(t.nodes&&t.nodes.length>0){const e=specificityOfMostSpecificListItem(t.nodes,s);c+=e.a,n+=e.b,o+=e.c}break;case":where":break;case":nth-child":case":nth-last-child":if(n+=1,t.nodes&&t.nodes.length>0){const i=t.nodes[0].nodes.findIndex((e=>"tag"===e.type&&"of"===e.value.toLowerCase()));if(i>-1){const a=e.selector({nodes:[],value:""});t.nodes[0].nodes.slice(i+1).forEach((e=>{a.append(e.clone())}));const r=[a];t.nodes.length>1&&r.push(...t.nodes.slice(1));const l=specificityOfMostSpecificListItem(r,s);c+=l.a,n+=l.b,o+=l.c}}break;case":local":case":global":t.nodes&&t.nodes.length>0&&t.nodes.forEach((e=>{const t=selectorSpecificity(e,s);c+=t.a,n+=t.b,o+=t.c}));break;case":host":case":host-context":if(n+=1,t.nodes&&t.nodes.length>0){const e=specificityOfMostSpecificListItem(t.nodes,s);c+=e.a,n+=e.b,o+=e.c}break;case":active-view-transition":case":active-view-transition-type":return{a:0,b:1,c:0}}else e.isContainer(t)&&t.nodes?.length>0&&t.nodes.forEach((e=>{const t=selectorSpecificity(e,s);c+=t.a,n+=t.b,o+=t.c}));return{a:c,b:n,c:o}}function specificityOfMostSpecificListItem(e,t){let s={a:0,b:0,c:0};return e.forEach((e=>{const i=selectorSpecificity(e,t);compare(i,s)<0||(s=i)})),s}function isPseudoElement(t){return e.isPseudoElement(t)}function selectorNodeContainsNothingOrOnlyUniversal(e){if(!e)return!1;if(!e.nodes)return!1;const t=e.nodes.filter((e=>"comment"!==e.type));return 0===t.length||1===t.length&&"universal"===t[0].type}exports.compare=compare,exports.selectorSpecificity=selectorSpecificity,exports.specificityOfMostSpecificListItem=specificityOfMostSpecificListItem;

View file

@ -0,0 +1,58 @@
import type { Node } from 'postcss-selector-parser';
/**
* Options for the calculation of the specificity of a selector
*/
export declare type CalculationOptions = {
/**
* The callback to calculate a custom specificity for a node
*/
customSpecificity?: CustomSpecificityCallback;
};
/**
* Compare two specificities
* @param s1 The first specificity
* @param s2 The second specificity
* @returns A value smaller than `0` if `s1` is less specific than `s2`, `0` if `s1` is equally specific as `s2`, a value larger than `0` if `s1` is more specific than `s2`
*/
export declare function compare(s1: Specificity, s2: Specificity): number;
/**
* Calculate a custom specificity for a node
*/
export declare type CustomSpecificityCallback = (node: Node) => Specificity | void | false | null | undefined;
/**
* Calculate the specificity for a selector
*/
export declare function selectorSpecificity(node: Node, options?: CalculationOptions): Specificity;
/**
* The specificity of a selector
*/
export declare type Specificity = {
/**
* The number of ID selectors in the selector
*/
a: number;
/**
* The number of class selectors, attribute selectors, and pseudo-classes in the selector
*/
b: number;
/**
* The number of type selectors and pseudo-elements in the selector
*/
c: number;
};
/**
* Calculate the most specific selector in a list
*/
export declare function specificityOfMostSpecificListItem(nodes: Array<Node>, options?: CalculationOptions): {
a: number;
b: number;
c: number;
};
export { }

View file

@ -0,0 +1 @@
import e from"postcss-selector-parser";function compare(e,t){return e.a===t.a?e.b===t.b?e.c-t.c:e.b-t.b:e.a-t.a}function selectorSpecificity(t,s){const i=s?.customSpecificity?.(t);if(i)return i;if(!t)return{a:0,b:0,c:0};let c=0,n=0,o=0;if("universal"==t.type)return{a:0,b:0,c:0};if("id"===t.type)c+=1;else if("tag"===t.type)o+=1;else if("class"===t.type)n+=1;else if("attribute"===t.type)n+=1;else if(isPseudoElement(t))switch(t.value.toLowerCase()){case"::slotted":if(o+=1,t.nodes&&t.nodes.length>0){const e=specificityOfMostSpecificListItem(t.nodes,s);c+=e.a,n+=e.b,o+=e.c}break;case"::view-transition-group":case"::view-transition-image-pair":case"::view-transition-old":case"::view-transition-new":return t.nodes&&1===t.nodes.length&&"selector"===t.nodes[0].type&&selectorNodeContainsNothingOrOnlyUniversal(t.nodes[0])?{a:0,b:0,c:0}:{a:0,b:0,c:1};default:o+=1}else if(e.isPseudoClass(t))switch(t.value.toLowerCase()){case":-webkit-any":case":any":default:n+=1;break;case":-moz-any":case":has":case":is":case":matches":case":not":if(t.nodes&&t.nodes.length>0){const e=specificityOfMostSpecificListItem(t.nodes,s);c+=e.a,n+=e.b,o+=e.c}break;case":where":break;case":nth-child":case":nth-last-child":if(n+=1,t.nodes&&t.nodes.length>0){const i=t.nodes[0].nodes.findIndex((e=>"tag"===e.type&&"of"===e.value.toLowerCase()));if(i>-1){const a=e.selector({nodes:[],value:""});t.nodes[0].nodes.slice(i+1).forEach((e=>{a.append(e.clone())}));const r=[a];t.nodes.length>1&&r.push(...t.nodes.slice(1));const l=specificityOfMostSpecificListItem(r,s);c+=l.a,n+=l.b,o+=l.c}}break;case":local":case":global":t.nodes&&t.nodes.length>0&&t.nodes.forEach((e=>{const t=selectorSpecificity(e,s);c+=t.a,n+=t.b,o+=t.c}));break;case":host":case":host-context":if(n+=1,t.nodes&&t.nodes.length>0){const e=specificityOfMostSpecificListItem(t.nodes,s);c+=e.a,n+=e.b,o+=e.c}break;case":active-view-transition":case":active-view-transition-type":return{a:0,b:1,c:0}}else e.isContainer(t)&&t.nodes?.length>0&&t.nodes.forEach((e=>{const t=selectorSpecificity(e,s);c+=t.a,n+=t.b,o+=t.c}));return{a:c,b:n,c:o}}function specificityOfMostSpecificListItem(e,t){let s={a:0,b:0,c:0};return e.forEach((e=>{const i=selectorSpecificity(e,t);compare(i,s)<0||(s=i)})),s}function isPseudoElement(t){return e.isPseudoElement(t)}function selectorNodeContainsNothingOrOnlyUniversal(e){if(!e)return!1;if(!e.nodes)return!1;const t=e.nodes.filter((e=>"comment"!==e.type));return 0===t.length||1===t.length&&"universal"===t[0].type}export{compare,selectorSpecificity,specificityOfMostSpecificListItem};

View file

@ -0,0 +1,66 @@
{
"name": "@csstools/selector-specificity",
"description": "Determine selector specificity with postcss-selector-parser",
"version": "5.0.0",
"contributors": [
{
"name": "Antonio Laguna",
"email": "antonio@laguna.es",
"url": "https://antonio.laguna.es"
},
{
"name": "Romain Menke",
"email": "romainmenke@gmail.com"
}
],
"license": "MIT-0",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/csstools"
},
{
"type": "opencollective",
"url": "https://opencollective.com/csstools"
}
],
"engines": {
"node": ">=18"
},
"type": "module",
"main": "dist/index.cjs",
"module": "dist/index.mjs",
"exports": {
".": {
"import": {
"types": "./dist/index.d.ts",
"default": "./dist/index.mjs"
},
"require": {
"default": "./dist/index.cjs"
}
}
},
"files": [
"CHANGELOG.md",
"LICENSE.md",
"README.md",
"dist"
],
"peerDependencies": {
"postcss-selector-parser": "^7.0.0"
},
"scripts": {},
"homepage": "https://github.com/csstools/postcss-plugins/tree/main/packages/selector-specificity#readme",
"repository": {
"type": "git",
"url": "git+https://github.com/csstools/postcss-plugins.git",
"directory": "packages/selector-specificity"
},
"bugs": "https://github.com/csstools/postcss-plugins/issues",
"keywords": [
"css",
"postcss-selector-parser",
"specificity"
]
}

1414
node_modules/@dual-bundle/import-meta-resolve/index.cjs generated vendored Normal file

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,18 @@
/**
* Match `import.meta.resolve` except that `parent` is required (you can pass
* `import.meta.url`).
*
* @param {string} specifier
* The module specifier to resolve relative to parent
* (`/example.js`, `./example.js`, `../example.js`, `some-package`, `fs`,
* etc).
* @param {string} parent
* The absolute parent module URL to resolve from.
* You must pass `import.meta.url` or something else.
* @returns {string}
* Returns a string to a full `file:`, `data:`, or `node:` URL
* to the found thing.
*/
export function resolve(specifier: string, parent: string): string;
export { moduleResolve } from "./lib/resolve.js";
export type ErrnoException = import('./lib/errors.js').ErrnoException;

47
node_modules/@dual-bundle/import-meta-resolve/index.js generated vendored Normal file
View file

@ -0,0 +1,47 @@
/**
* @typedef {import('./lib/errors.js').ErrnoException} ErrnoException
*/
import {defaultResolve} from './lib/resolve.js'
export {moduleResolve} from './lib/resolve.js'
/**
* Match `import.meta.resolve` except that `parent` is required (you can pass
* `import.meta.url`).
*
* @param {string} specifier
* The module specifier to resolve relative to parent
* (`/example.js`, `./example.js`, `../example.js`, `some-package`, `fs`,
* etc).
* @param {string} parent
* The absolute parent module URL to resolve from.
* You must pass `import.meta.url` or something else.
* @returns {string}
* Returns a string to a full `file:`, `data:`, or `node:` URL
* to the found thing.
*/
export function resolve(specifier, parent) {
if (!parent) {
throw new Error(
'Please pass `parent`: `import-meta-resolve` cannot ponyfill that'
)
}
try {
return defaultResolve(specifier, {parentURL: parent}).url
} catch (error) {
// See: <https://github.com/nodejs/node/blob/45f5c9b/lib/internal/modules/esm/initialize_import_meta.js#L34>
const exception = /** @type {ErrnoException} */ (error)
if (
(exception.code === 'ERR_UNSUPPORTED_DIR_IMPORT' ||
exception.code === 'ERR_MODULE_NOT_FOUND') &&
typeof exception.url === 'string'
) {
return exception.url
}
throw error
}
}

View file

@ -0,0 +1,23 @@
export namespace codes {
let ERR_INVALID_ARG_TYPE: new (...parameters: any[]) => Error;
let ERR_INVALID_MODULE_SPECIFIER: new (...parameters: any[]) => Error;
let ERR_INVALID_PACKAGE_CONFIG: new (...parameters: any[]) => Error;
let ERR_INVALID_PACKAGE_TARGET: new (...parameters: any[]) => Error;
let ERR_MODULE_NOT_FOUND: new (...parameters: any[]) => Error;
let ERR_NETWORK_IMPORT_DISALLOWED: new (...parameters: any[]) => Error;
let ERR_PACKAGE_IMPORT_NOT_DEFINED: new (...parameters: any[]) => Error;
let ERR_PACKAGE_PATH_NOT_EXPORTED: new (...parameters: any[]) => Error;
let ERR_UNSUPPORTED_DIR_IMPORT: new (...parameters: any[]) => Error;
let ERR_UNSUPPORTED_RESOLVE_REQUEST: new (...parameters: any[]) => Error;
let ERR_UNKNOWN_FILE_EXTENSION: new (...parameters: any[]) => Error;
let ERR_INVALID_ARG_VALUE: new (...parameters: any[]) => Error;
}
export type ErrnoExceptionFields = {
errnode?: number | undefined;
code?: string | undefined;
path?: string | undefined;
syscall?: string | undefined;
url?: string | undefined;
};
export type ErrnoException = Error & ErrnoExceptionFields;
export type MessageFunction = (...parameters: Array<any>) => string;

View file

@ -0,0 +1,507 @@
/**
* @typedef ErrnoExceptionFields
* @property {number | undefined} [errnode]
* @property {string | undefined} [code]
* @property {string | undefined} [path]
* @property {string | undefined} [syscall]
* @property {string | undefined} [url]
*
* @typedef {Error & ErrnoExceptionFields} ErrnoException
*/
/**
* @typedef {(...parameters: Array<any>) => string} MessageFunction
*/
// Manually “tree shaken” from:
// <https://github.com/nodejs/node/blob/45f5c9b/lib/internal/errors.js>
// Last checked on: Apr 29, 2024.
import v8 from 'node:v8'
import assert from 'node:assert'
// Needed for types.
// eslint-disable-next-line no-unused-vars
import {URL} from 'node:url'
import {format, inspect} from 'node:util'
const own = {}.hasOwnProperty
const classRegExp = /^([A-Z][a-z\d]*)+$/
// Sorted by a rough estimate on most frequently used entries.
const kTypes = new Set([
'string',
'function',
'number',
'object',
// Accept 'Function' and 'Object' as alternative to the lower cased version.
'Function',
'Object',
'boolean',
'bigint',
'symbol'
])
export const codes = {}
/**
* Create a list string in the form like 'A and B' or 'A, B, ..., and Z'.
* We cannot use Intl.ListFormat because it's not available in
* --without-intl builds.
*
* @param {Array<string>} array
* An array of strings.
* @param {string} [type]
* The list type to be inserted before the last element.
* @returns {string}
*/
function formatList(array, type = 'and') {
return array.length < 3
? array.join(` ${type} `)
: `${array.slice(0, -1).join(', ')}, ${type} ${array[array.length - 1]}`
}
/** @type {Map<string, MessageFunction | string>} */
const messages = new Map()
const nodeInternalPrefix = '__node_internal_'
/** @type {number} */
let userStackTraceLimit
codes.ERR_INVALID_ARG_TYPE = createError(
'ERR_INVALID_ARG_TYPE',
/**
* @param {string} name
* @param {Array<string> | string} expected
* @param {unknown} actual
*/
(name, expected, actual) => {
assert(typeof name === 'string', "'name' must be a string")
if (!Array.isArray(expected)) {
expected = [expected]
}
let message = 'The '
if (name.endsWith(' argument')) {
// For cases like 'first argument'
message += `${name} `
} else {
const type = name.includes('.') ? 'property' : 'argument'
message += `"${name}" ${type} `
}
message += 'must be '
/** @type {Array<string>} */
const types = []
/** @type {Array<string>} */
const instances = []
/** @type {Array<string>} */
const other = []
for (const value of expected) {
assert(
typeof value === 'string',
'All expected entries have to be of type string'
)
if (kTypes.has(value)) {
types.push(value.toLowerCase())
} else if (classRegExp.exec(value) === null) {
assert(
value !== 'object',
'The value "object" should be written as "Object"'
)
other.push(value)
} else {
instances.push(value)
}
}
// Special handle `object` in case other instances are allowed to outline
// the differences between each other.
if (instances.length > 0) {
const pos = types.indexOf('object')
if (pos !== -1) {
types.slice(pos, 1)
instances.push('Object')
}
}
if (types.length > 0) {
message += `${types.length > 1 ? 'one of type' : 'of type'} ${formatList(
types,
'or'
)}`
if (instances.length > 0 || other.length > 0) message += ' or '
}
if (instances.length > 0) {
message += `an instance of ${formatList(instances, 'or')}`
if (other.length > 0) message += ' or '
}
if (other.length > 0) {
if (other.length > 1) {
message += `one of ${formatList(other, 'or')}`
} else {
if (other[0].toLowerCase() !== other[0]) message += 'an '
message += `${other[0]}`
}
}
message += `. Received ${determineSpecificType(actual)}`
return message
},
TypeError
)
codes.ERR_INVALID_MODULE_SPECIFIER = createError(
'ERR_INVALID_MODULE_SPECIFIER',
/**
* @param {string} request
* @param {string} reason
* @param {string} [base]
*/
(request, reason, base = undefined) => {
return `Invalid module "${request}" ${reason}${
base ? ` imported from ${base}` : ''
}`
},
TypeError
)
codes.ERR_INVALID_PACKAGE_CONFIG = createError(
'ERR_INVALID_PACKAGE_CONFIG',
/**
* @param {string} path
* @param {string} [base]
* @param {string} [message]
*/
(path, base, message) => {
return `Invalid package config ${path}${
base ? ` while importing ${base}` : ''
}${message ? `. ${message}` : ''}`
},
Error
)
codes.ERR_INVALID_PACKAGE_TARGET = createError(
'ERR_INVALID_PACKAGE_TARGET',
/**
* @param {string} packagePath
* @param {string} key
* @param {unknown} target
* @param {boolean} [isImport=false]
* @param {string} [base]
*/
(packagePath, key, target, isImport = false, base = undefined) => {
const relatedError =
typeof target === 'string' &&
!isImport &&
target.length > 0 &&
!target.startsWith('./')
if (key === '.') {
assert(isImport === false)
return (
`Invalid "exports" main target ${JSON.stringify(target)} defined ` +
`in the package config ${packagePath}package.json${
base ? ` imported from ${base}` : ''
}${relatedError ? '; targets must start with "./"' : ''}`
)
}
return `Invalid "${
isImport ? 'imports' : 'exports'
}" target ${JSON.stringify(
target
)} defined for '${key}' in the package config ${packagePath}package.json${
base ? ` imported from ${base}` : ''
}${relatedError ? '; targets must start with "./"' : ''}`
},
Error
)
codes.ERR_MODULE_NOT_FOUND = createError(
'ERR_MODULE_NOT_FOUND',
/**
* @param {string} path
* @param {string} base
* @param {boolean} [exactUrl]
*/
(path, base, exactUrl = false) => {
return `Cannot find ${
exactUrl ? 'module' : 'package'
} '${path}' imported from ${base}`
},
Error
)
codes.ERR_NETWORK_IMPORT_DISALLOWED = createError(
'ERR_NETWORK_IMPORT_DISALLOWED',
"import of '%s' by %s is not supported: %s",
Error
)
codes.ERR_PACKAGE_IMPORT_NOT_DEFINED = createError(
'ERR_PACKAGE_IMPORT_NOT_DEFINED',
/**
* @param {string} specifier
* @param {string} packagePath
* @param {string} base
*/
(specifier, packagePath, base) => {
return `Package import specifier "${specifier}" is not defined${
packagePath ? ` in package ${packagePath}package.json` : ''
} imported from ${base}`
},
TypeError
)
codes.ERR_PACKAGE_PATH_NOT_EXPORTED = createError(
'ERR_PACKAGE_PATH_NOT_EXPORTED',
/**
* @param {string} packagePath
* @param {string} subpath
* @param {string} [base]
*/
(packagePath, subpath, base = undefined) => {
if (subpath === '.')
return `No "exports" main defined in ${packagePath}package.json${
base ? ` imported from ${base}` : ''
}`
return `Package subpath '${subpath}' is not defined by "exports" in ${packagePath}package.json${
base ? ` imported from ${base}` : ''
}`
},
Error
)
codes.ERR_UNSUPPORTED_DIR_IMPORT = createError(
'ERR_UNSUPPORTED_DIR_IMPORT',
"Directory import '%s' is not supported " +
'resolving ES modules imported from %s',
Error
)
codes.ERR_UNSUPPORTED_RESOLVE_REQUEST = createError(
'ERR_UNSUPPORTED_RESOLVE_REQUEST',
'Failed to resolve module specifier "%s" from "%s": Invalid relative URL or base scheme is not hierarchical.',
TypeError
)
codes.ERR_UNKNOWN_FILE_EXTENSION = createError(
'ERR_UNKNOWN_FILE_EXTENSION',
/**
* @param {string} extension
* @param {string} path
*/
(extension, path) => {
return `Unknown file extension "${extension}" for ${path}`
},
TypeError
)
codes.ERR_INVALID_ARG_VALUE = createError(
'ERR_INVALID_ARG_VALUE',
/**
* @param {string} name
* @param {unknown} value
* @param {string} [reason='is invalid']
*/
(name, value, reason = 'is invalid') => {
let inspected = inspect(value)
if (inspected.length > 128) {
inspected = `${inspected.slice(0, 128)}...`
}
const type = name.includes('.') ? 'property' : 'argument'
return `The ${type} '${name}' ${reason}. Received ${inspected}`
},
TypeError
// Note: extra classes have been shaken out.
// , RangeError
)
/**
* Utility function for registering the error codes. Only used here. Exported
* *only* to allow for testing.
* @param {string} sym
* @param {MessageFunction | string} value
* @param {ErrorConstructor} constructor
* @returns {new (...parameters: Array<any>) => Error}
*/
function createError(sym, value, constructor) {
// Special case for SystemError that formats the error message differently
// The SystemErrors only have SystemError as their base classes.
messages.set(sym, value)
return makeNodeErrorWithCode(constructor, sym)
}
/**
* @param {ErrorConstructor} Base
* @param {string} key
* @returns {ErrorConstructor}
*/
function makeNodeErrorWithCode(Base, key) {
// @ts-expect-error Its a Node error.
return NodeError
/**
* @param {Array<unknown>} parameters
*/
function NodeError(...parameters) {
const limit = Error.stackTraceLimit
if (isErrorStackTraceLimitWritable()) Error.stackTraceLimit = 0
const error = new Base()
// Reset the limit and setting the name property.
if (isErrorStackTraceLimitWritable()) Error.stackTraceLimit = limit
const message = getMessage(key, parameters, error)
Object.defineProperties(error, {
// Note: no need to implement `kIsNodeError` symbol, would be hard,
// probably.
message: {
value: message,
enumerable: false,
writable: true,
configurable: true
},
toString: {
/** @this {Error} */
value() {
return `${this.name} [${key}]: ${this.message}`
},
enumerable: false,
writable: true,
configurable: true
}
})
captureLargerStackTrace(error)
// @ts-expect-error Its a Node error.
error.code = key
return error
}
}
/**
* @returns {boolean}
*/
function isErrorStackTraceLimitWritable() {
// Do no touch Error.stackTraceLimit as V8 would attempt to install
// it again during deserialization.
try {
if (v8.startupSnapshot.isBuildingSnapshot()) {
return false
}
} catch {}
const desc = Object.getOwnPropertyDescriptor(Error, 'stackTraceLimit')
if (desc === undefined) {
return Object.isExtensible(Error)
}
return own.call(desc, 'writable') && desc.writable !== undefined
? desc.writable
: desc.set !== undefined
}
/**
* This function removes unnecessary frames from Node.js core errors.
* @template {(...parameters: unknown[]) => unknown} T
* @param {T} wrappedFunction
* @returns {T}
*/
function hideStackFrames(wrappedFunction) {
// We rename the functions that will be hidden to cut off the stacktrace
// at the outermost one
const hidden = nodeInternalPrefix + wrappedFunction.name
Object.defineProperty(wrappedFunction, 'name', {value: hidden})
return wrappedFunction
}
const captureLargerStackTrace = hideStackFrames(
/**
* @param {Error} error
* @returns {Error}
*/
// @ts-expect-error: fine
function (error) {
const stackTraceLimitIsWritable = isErrorStackTraceLimitWritable()
if (stackTraceLimitIsWritable) {
userStackTraceLimit = Error.stackTraceLimit
Error.stackTraceLimit = Number.POSITIVE_INFINITY
}
Error.captureStackTrace(error)
// Reset the limit
if (stackTraceLimitIsWritable) Error.stackTraceLimit = userStackTraceLimit
return error
}
)
/**
* @param {string} key
* @param {Array<unknown>} parameters
* @param {Error} self
* @returns {string}
*/
function getMessage(key, parameters, self) {
const message = messages.get(key)
assert(message !== undefined, 'expected `message` to be found')
if (typeof message === 'function') {
assert(
message.length <= parameters.length, // Default options do not count.
`Code: ${key}; The provided arguments length (${parameters.length}) does not ` +
`match the required ones (${message.length}).`
)
return Reflect.apply(message, self, parameters)
}
const regex = /%[dfijoOs]/g
let expectedLength = 0
while (regex.exec(message) !== null) expectedLength++
assert(
expectedLength === parameters.length,
`Code: ${key}; The provided arguments length (${parameters.length}) does not ` +
`match the required ones (${expectedLength}).`
)
if (parameters.length === 0) return message
parameters.unshift(message)
return Reflect.apply(format, null, parameters)
}
/**
* Determine the specific type of a value for type-mismatch errors.
* @param {unknown} value
* @returns {string}
*/
function determineSpecificType(value) {
if (value === null || value === undefined) {
return String(value)
}
if (typeof value === 'function' && value.name) {
return `function ${value.name}`
}
if (typeof value === 'object') {
if (value.constructor && value.constructor.name) {
return `an instance of ${value.constructor.name}`
}
return `${inspect(value, {depth: -1})}`
}
let inspected = inspect(value, {colors: false})
if (inspected.length > 28) {
inspected = `${inspected.slice(0, 25)}...`
}
return `type ${typeof value} (${inspected})`
}

View file

@ -0,0 +1,12 @@
/**
* @param {URL} url
* @param {{parentURL: string}} context
* @returns {string | null}
*/
export function defaultGetFormatWithoutErrors(url: URL, context: {
parentURL: string;
}): string | null;
export type ProtocolHandler = (parsed: URL, context: {
parentURL: string;
source?: Buffer;
}, ignoreErrors: boolean) => string | null | void;

View file

@ -0,0 +1,159 @@
// Manually “tree shaken” from:
// <https://github.com/nodejs/node/blob/7c3dce0/lib/internal/modules/esm/get_format.js>
// Last checked on: Apr 29, 2024.
import {fileURLToPath} from 'node:url'
import {getPackageType} from './package-json-reader.js'
import {codes} from './errors.js'
const {ERR_UNKNOWN_FILE_EXTENSION} = codes
const hasOwnProperty = {}.hasOwnProperty
/** @type {Record<string, string>} */
const extensionFormatMap = {
// @ts-expect-error: hush.
__proto__: null,
'.cjs': 'commonjs',
'.js': 'module',
'.json': 'json',
'.mjs': 'module'
}
/**
* @param {string | null} mime
* @returns {string | null}
*/
function mimeToFormat(mime) {
if (
mime &&
/\s*(text|application)\/javascript\s*(;\s*charset=utf-?8\s*)?/i.test(mime)
)
return 'module'
if (mime === 'application/json') return 'json'
return null
}
/**
* @callback ProtocolHandler
* @param {URL} parsed
* @param {{parentURL: string, source?: Buffer}} context
* @param {boolean} ignoreErrors
* @returns {string | null | void}
*/
/**
* @type {Record<string, ProtocolHandler>}
*/
const protocolHandlers = {
// @ts-expect-error: hush.
__proto__: null,
'data:': getDataProtocolModuleFormat,
'file:': getFileProtocolModuleFormat,
'http:': getHttpProtocolModuleFormat,
'https:': getHttpProtocolModuleFormat,
'node:'() {
return 'builtin'
}
}
/**
* @param {URL} parsed
*/
function getDataProtocolModuleFormat(parsed) {
const {1: mime} = /^([^/]+\/[^;,]+)[^,]*?(;base64)?,/.exec(
parsed.pathname
) || [null, null, null]
return mimeToFormat(mime)
}
/**
* Returns the file extension from a URL.
*
* Should give similar result to
* `require('node:path').extname(require('node:url').fileURLToPath(url))`
* when used with a `file:` URL.
*
* @param {URL} url
* @returns {string}
*/
function extname(url) {
const pathname = url.pathname
let index = pathname.length
while (index--) {
const code = pathname.codePointAt(index)
if (code === 47 /* `/` */) {
return ''
}
if (code === 46 /* `.` */) {
return pathname.codePointAt(index - 1) === 47 /* `/` */
? ''
: pathname.slice(index)
}
}
return ''
}
/**
* @type {ProtocolHandler}
*/
function getFileProtocolModuleFormat(url, _context, ignoreErrors) {
const value = extname(url)
if (value === '.js') {
const packageType = getPackageType(url)
if (packageType !== 'none') {
return packageType
}
return 'commonjs'
}
if (value === '') {
const packageType = getPackageType(url)
// Legacy behavior
if (packageType === 'none' || packageType === 'commonjs') {
return 'commonjs'
}
// Note: we dont implement WASM, so we dont need
// `getFormatOfExtensionlessFile` from `formats`.
return 'module'
}
const format = extensionFormatMap[value]
if (format) return format
// Explicit undefined return indicates load hook should rerun format check
if (ignoreErrors) {
return undefined
}
const filepath = fileURLToPath(url)
throw new ERR_UNKNOWN_FILE_EXTENSION(value, filepath)
}
function getHttpProtocolModuleFormat() {
// To do: HTTPS imports.
}
/**
* @param {URL} url
* @param {{parentURL: string}} context
* @returns {string | null}
*/
export function defaultGetFormatWithoutErrors(url, context) {
const protocol = url.protocol
if (!hasOwnProperty.call(protocolHandlers, protocol)) {
return null
}
return protocolHandlers[protocol](url, context, true) || null
}

View file

@ -0,0 +1,31 @@
/**
* @param {string} jsonPath
* @param {{specifier: URL | string, base?: URL}} options
* @returns {PackageConfig}
*/
export function read(jsonPath: string, { base, specifier }: {
specifier: URL | string;
base?: URL;
}): PackageConfig;
/**
* @param {URL | string} resolved
* @returns {PackageConfig}
*/
export function getPackageScopeConfig(resolved: URL | string): PackageConfig;
/**
* Returns the package type for a given URL.
* @param {URL} url - The URL to get the package type for.
* @returns {PackageType}
*/
export function getPackageType(url: URL): PackageType;
export type ErrnoException = import('./errors.js').ErrnoException;
export type PackageType = 'commonjs' | 'module' | 'none';
export type PackageConfig = {
pjsonPath: string;
exists: boolean;
main?: string | undefined;
name?: string | undefined;
type: PackageType;
exports?: Record<string, unknown> | undefined;
imports?: Record<string, unknown> | undefined;
};

View file

@ -0,0 +1,177 @@
// Manually “tree shaken” from:
// <https://github.com/nodejs/node/blob/7c3dce0/lib/internal/modules/package_json_reader.js>
// Last checked on: Apr 29, 2024.
// Removed the native dependency.
// Also: no need to cache, we do that in resolve already.
/**
* @typedef {import('./errors.js').ErrnoException} ErrnoException
*
* @typedef {'commonjs' | 'module' | 'none'} PackageType
*
* @typedef PackageConfig
* @property {string} pjsonPath
* @property {boolean} exists
* @property {string | undefined} [main]
* @property {string | undefined} [name]
* @property {PackageType} type
* @property {Record<string, unknown> | undefined} [exports]
* @property {Record<string, unknown> | undefined} [imports]
*/
import fs from 'node:fs'
import path from 'node:path'
import {fileURLToPath} from 'node:url'
import {codes} from './errors.js'
const hasOwnProperty = {}.hasOwnProperty
const {ERR_INVALID_PACKAGE_CONFIG} = codes
/** @type {Map<string, PackageConfig>} */
const cache = new Map()
/**
* @param {string} jsonPath
* @param {{specifier: URL | string, base?: URL}} options
* @returns {PackageConfig}
*/
export function read(jsonPath, {base, specifier}) {
const existing = cache.get(jsonPath)
if (existing) {
return existing
}
/** @type {string | undefined} */
let string
try {
string = fs.readFileSync(path.toNamespacedPath(jsonPath), 'utf8')
} catch (error) {
const exception = /** @type {ErrnoException} */ (error)
if (exception.code !== 'ENOENT') {
throw exception
}
}
/** @type {PackageConfig} */
const result = {
exists: false,
pjsonPath: jsonPath,
main: undefined,
name: undefined,
type: 'none', // Ignore unknown types for forwards compatibility
exports: undefined,
imports: undefined
}
if (string !== undefined) {
/** @type {Record<string, unknown>} */
let parsed
try {
parsed = JSON.parse(string)
} catch (error_) {
const cause = /** @type {ErrnoException} */ (error_)
const error = new ERR_INVALID_PACKAGE_CONFIG(
jsonPath,
(base ? `"${specifier}" from ` : '') + fileURLToPath(base || specifier),
cause.message
)
error.cause = cause
throw error
}
result.exists = true
if (
hasOwnProperty.call(parsed, 'name') &&
typeof parsed.name === 'string'
) {
result.name = parsed.name
}
if (
hasOwnProperty.call(parsed, 'main') &&
typeof parsed.main === 'string'
) {
result.main = parsed.main
}
if (hasOwnProperty.call(parsed, 'exports')) {
// @ts-expect-error: assume valid.
result.exports = parsed.exports
}
if (hasOwnProperty.call(parsed, 'imports')) {
// @ts-expect-error: assume valid.
result.imports = parsed.imports
}
// Ignore unknown types for forwards compatibility
if (
hasOwnProperty.call(parsed, 'type') &&
(parsed.type === 'commonjs' || parsed.type === 'module')
) {
result.type = parsed.type
}
}
cache.set(jsonPath, result)
return result
}
/**
* @param {URL | string} resolved
* @returns {PackageConfig}
*/
export function getPackageScopeConfig(resolved) {
// Note: in Node, this is now a native module.
let packageJSONUrl = new URL('package.json', resolved)
while (true) {
const packageJSONPath = packageJSONUrl.pathname
if (packageJSONPath.endsWith('node_modules/package.json')) {
break
}
const packageConfig = read(fileURLToPath(packageJSONUrl), {
specifier: resolved
})
if (packageConfig.exists) {
return packageConfig
}
const lastPackageJSONUrl = packageJSONUrl
packageJSONUrl = new URL('../package.json', packageJSONUrl)
// Terminates at root where ../package.json equals ../../package.json
// (can't just check "/package.json" for Windows support).
if (packageJSONUrl.pathname === lastPackageJSONUrl.pathname) {
break
}
}
const packageJSONPath = fileURLToPath(packageJSONUrl)
// ^^ Note: in Node, this is now a native module.
return {
pjsonPath: packageJSONPath,
exists: false,
type: 'none'
}
}
/**
* Returns the package type for a given URL.
* @param {URL} url - The URL to get the package type for.
* @returns {PackageType}
*/
export function getPackageType(url) {
// To do @anonrig: Write a C++ function that returns only "type".
return getPackageScopeConfig(url).type
}

View file

@ -0,0 +1,33 @@
/// <reference types="node" resolution-mode="require"/>
/**
* The Resolver Algorithm Specification as detailed in the Node docs (which is
* sync and slightly lower-level than `resolve`).
*
* @param {string} specifier
* `/example.js`, `./example.js`, `../example.js`, `some-package`, `fs`, etc.
* @param {URL} base
* Full URL (to a file) that `specifier` is resolved relative from.
* @param {Set<string>} [conditions]
* Conditions.
* @param {boolean} [preserveSymlinks]
* Keep symlinks instead of resolving them.
* @returns {URL}
* A URL object to the found thing.
*/
export function moduleResolve(specifier: string, base: URL, conditions?: Set<string> | undefined, preserveSymlinks?: boolean | undefined): URL;
/**
* @param {string} specifier
* @param {{parentURL?: string, conditions?: Array<string>}} context
* @returns {{url: string, format?: string | null}}
*/
export function defaultResolve(specifier: string, context?: {
parentURL?: string;
conditions?: Array<string>;
}): {
url: string;
format?: string | null;
};
export type Stats = import('node:fs').Stats;
export type ErrnoException = import('./errors.js').ErrnoException;
export type PackageConfig = import('./package-json-reader.js').PackageConfig;
import { URL } from 'node:url';

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,5 @@
/**
* @param {Array<string>} [conditions]
* @returns {Set<string>}
*/
export function getConditionsSet(conditions?: string[] | undefined): Set<string>;

View file

@ -0,0 +1,47 @@
// Manually “tree shaken” from:
// <https://github.com/nodejs/node/blob/81a9a97/lib/internal/modules/esm/utils.js>
// Last checked on: Apr 29, 2024.
import {codes} from './errors.js'
const {ERR_INVALID_ARG_VALUE} = codes
// In Node itself these values are populated from CLI arguments, before any
// user code runs.
// Here we just define the defaults.
const DEFAULT_CONDITIONS = Object.freeze(['node', 'import'])
const DEFAULT_CONDITIONS_SET = new Set(DEFAULT_CONDITIONS)
/**
* Returns the default conditions for ES module loading.
*/
function getDefaultConditions() {
return DEFAULT_CONDITIONS
}
/**
* Returns the default conditions for ES module loading, as a Set.
*/
function getDefaultConditionsSet() {
return DEFAULT_CONDITIONS_SET
}
/**
* @param {Array<string>} [conditions]
* @returns {Set<string>}
*/
export function getConditionsSet(conditions) {
if (conditions !== undefined && conditions !== getDefaultConditions()) {
if (!Array.isArray(conditions)) {
throw new ERR_INVALID_ARG_VALUE(
'conditions',
conditions,
'expected an array'
)
}
return new Set(conditions)
}
return getDefaultConditionsSet()
}

74
node_modules/@dual-bundle/import-meta-resolve/license generated vendored Normal file
View file

@ -0,0 +1,74 @@
(The MIT License)
Copyright (c) 2021 Titus Wormer <mailto:tituswormer@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
---
This is a derivative work based on:
<https://github.com/nodejs/node>.
Which is licensed:
"""
Copyright Node.js contributors. All rights reserved.
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.
"""
This license applies to parts of Node.js originating from the
https://github.com/joyent/node repository:
"""
Copyright Joyent, Inc. and other Node contributors. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to
deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.
"""

View file

@ -0,0 +1,112 @@
{
"name": "@dual-bundle/import-meta-resolve",
"version": "4.1.0",
"description": "A fork of `import-meta-resolve` with commonjs + ESM support at the same time, AKA dual package.",
"license": "MIT",
"keywords": [
"resolve",
"node",
"esm",
"module",
"import",
"import-meta-resolve"
],
"repository": "un-es/import-meta-resolve",
"bugs": "https://github.com/wooorm/import-meta-resolve/issues",
"funding": {
"type": "github",
"url": "https://github.com/sponsors/wooorm"
},
"author": "Titus Wormer <tituswormer@gmail.com> (https://wooorm.com)",
"maintainers": [
"JounQin <admin@1stg.me> (https://www.1stG.me)"
],
"contributors": [
"Titus Wormer <tituswormer@gmail.com> (https://wooorm.com)"
],
"sideEffects": false,
"type": "module",
"main": "index.cjs",
"module": "index.js",
"types": "index.d.ts",
"exports": {
"types": "./index.d.ts",
"require": "./index.cjs",
"default": "./index.js"
},
"files": [
"lib/",
"index.d.ts",
"index.cjs",
"index.js"
],
"devDependencies": {
"@types/node": "^20.0.0",
"@types/semver": "^7.0.0",
"c8": "^9.0.0",
"esbuild": "^0.21.1",
"f-ck": "^2.0.0",
"prettier": "^3.0.0",
"remark-cli": "^12.0.0",
"remark-preset-wooorm": "^10.0.0",
"semver": "^7.0.0",
"type-coverage": "^2.0.0",
"typescript": "^5.0.0",
"xo": "^0.58.0"
},
"scripts": {
"prepack": "npm run generate && npm run build && npm run format",
"generate": "node --conditions development script.js",
"build": "tsc --build --clean && tsc --build && type-coverage && esbuild --bundle --outfile=index.cjs --platform=node --format=cjs index.js",
"format": "remark . -qfo && prettier . -w --log-level warn && xo --fix",
"test-api": "node --experimental-import-meta-resolve test/baseline.js && node --experimental-import-meta-resolve test/baseline-async.js && node test/index.js",
"test-coverage": "c8 --check-coverage --branches 75 --functions 75 --lines 75 --statements 75 --reporter lcov npm run test-api",
"test": "npm run generate && npm run build && npm run format && npm run test-coverage"
},
"prettier": {
"tabWidth": 2,
"useTabs": false,
"singleQuote": true,
"bracketSpacing": false,
"semi": false,
"trailingComma": "none"
},
"xo": {
"prettier": true,
"rules": {
"complexity": "off",
"max-depth": "off",
"max-params": "off",
"no-constant-condition": "off",
"no-new": "off",
"prefer-arrow-callback": "off",
"unicorn/prefer-at": "off",
"unicorn/prefer-string-replace-all": "off"
},
"ignore": [
"test/node_modules/"
]
},
"remarkConfig": {
"plugins": [
"preset-wooorm",
[
"remark-lint-maximum-heading-length",
false
],
[
"remark-lint-no-multiple-toplevel-headings",
false
]
]
},
"typeCoverage": {
"atLeast": 100,
"detail": true,
"strict": true,
"ignoreCatch": true,
"ignoreFiles": [
"lib/errors.d.ts"
]
}
}

272
node_modules/@dual-bundle/import-meta-resolve/readme.md generated vendored Normal file
View file

@ -0,0 +1,272 @@
# `@dual-bundle/import-meta-resolve`
A fork of [`import-meta-resolve`](https://github.com/wooorm/import-meta-resolve)
with commonjs + ESM support at the same time, AKA dual package.
It will rebase and try to release in order to sync with the upstream every day,
see [.github/workflows/rebase.yml](.github/workflows/rebase.yml) for details.
## Installation
```bash
# npm
npm install @dual-bundle/import-meta-resolve
# yarn
yarn add @dual-bundle/import-meta-resolve
```
***
# import-meta-resolve
[![Build][build-badge]][build]
[![Coverage][coverage-badge]][coverage]
[![Downloads][downloads-badge]][downloads]
Resolve things like Node.js.
## Contents
* [What is this?](#what-is-this)
* [When to use this?](#when-to-use-this)
* [Install](#install)
* [Use](#use)
* [API](#api)
* [`resolve(specifier, parent)`](#resolvespecifier-parent)
* [`moduleResolve(specifier, parent, conditions, preserveSymlinks)`](#moduleresolvespecifier-parent-conditions-preservesymlinks)
* [`ErrnoException`](#errnoexception)
* [Algorithm](#algorithm)
* [Differences to Node](#differences-to-node)
* [Types](#types)
* [Compatibility](#compatibility)
* [Contribute](#contribute)
* [License](#license)
## What is this?
This package is a ponyfill for [`import.meta.resolve`][native-resolve].
It supports everything you need to resolve files just like modern Node does:
import maps, export maps, loading CJS and ESM projects, all of that!
## When to use this?
As of Node.js 20.0, `import.meta.resolve` is still behind an experimental flag.
This package can be used to do what it does in Node 1620.
## Install
This package is [ESM only][esm].
In Node.js (version 16+), install with [npm][]:
```sh
npm install import-meta-resolve
```
## Use
```js
import {resolve} from 'import-meta-resolve'
// A file:
console.log(resolve('./index.js', import.meta.url))
//=> file:///Users/tilde/Projects/oss/import-meta-resolve/index.js
// A CJS package:
console.log(resolve('builtins', import.meta.url))
//=> file:///Users/tilde/Projects/oss/import-meta-resolve/node_modules/builtins/index.js
// A scoped CJS package:
console.log(resolve('@eslint/eslintrc', import.meta.url))
//=> file:///Users/tilde/Projects/oss/import-meta-resolve/node_modules/@eslint/eslintrc/lib/index.js
// A package with an export map:
console.log(resolve('micromark/lib/parse', import.meta.url))
//=> file:///Users/tilde/Projects/oss/import-meta-resolve/node_modules/micromark/lib/parse.js
// A node builtin:
console.log(resolve('fs', import.meta.url))
//=> node:fs
```
## API
This package exports the identifiers [`moduleResolve`][moduleresolve] and
[`resolve`][resolve].
There is no default export.
### `resolve(specifier, parent)`
Match `import.meta.resolve` except that `parent` is required (you can pass
`import.meta.url`).
###### Parameters
* `specifier` (`string`)
— the module specifier to resolve relative to parent
(`/example.js`, `./example.js`, `../example.js`, `some-package`, `fs`, etc)
* `parent` (`string`, example: `import.meta.url`)
— the absolute parent module URL to resolve from; you must pass
`import.meta.url` or something else
###### Returns
Full `file:`, `data:`, or `node:` URL (`string`) to the found thing
###### Throws
Throws an [`ErrnoException`][errnoexception].
### `moduleResolve(specifier, parent, conditions, preserveSymlinks)`
The [“Resolver Algorithm Specification”][algo] as detailed in the Node docs
(which is slightly lower-level than `resolve`).
###### Parameters
* `specifier` (`string`)
`/example.js`, `./example.js`, `../example.js`, `some-package`, `fs`, etc
* `parent` (`URL`, example: `import.meta.url`)
— full URL (to a file) that `specifier` is resolved relative from
* `conditions` (`Set<string>`, default: `new Set(['node', 'import'])`)
— conditions
* `preserveSymlinks` (`boolean`, default: `false`)
— keep symlinks instead of resolving them
###### Returns
A URL object (`URL`) to the found thing.
###### Throws
Throws an [`ErrnoException`][errnoexception].
### `ErrnoException`
One of many different errors that occur when resolving (TypeScript type).
###### Type
```ts
type ErrnoExceptionFields = Error & {
errnode?: number | undefined
code?: string | undefined
path?: string | undefined
syscall?: string | undefined
url?: string | undefined
}
```
The `code` field on errors is one of the following strings:
* `'ERR_INVALID_MODULE_SPECIFIER'`
— when `specifier` is invalid (example: `'#'`)
* `'ERR_INVALID_PACKAGE_CONFIG'`
— when a `package.json` is invalid (example: invalid JSON)
* `'ERR_INVALID_PACKAGE_TARGET'`
— when a `package.json` `exports` or `imports` is invalid (example: when it
does not start with `'./'`)
* `'ERR_MODULE_NOT_FOUND'`
— when `specifier` cannot be found in `parent` (example: `'some-missing-package'`)
* `'ERR_NETWORK_IMPORT_DISALLOWED'`
— thrown when trying to resolve a local file or builtin from a remote file
(`node:fs` relative to `'https://example.com'`)
* `'ERR_PACKAGE_IMPORT_NOT_DEFINED'`
— when a local import is not defined in an import map (example: `'#local'`
when not defined)
* `'ERR_PACKAGE_PATH_NOT_EXPORTED'`
— when an export is not defined in an export map (example: `'tape/index.js'`,
which is not in its export map)
* `'ERR_UNSUPPORTED_DIR_IMPORT'`
— when attempting to import a directory (example: `'./lib/'`)
* `'ERR_UNKNOWN_FILE_EXTENSION'`
— when somehow reading a file that has an unexpected extensions (`'./readme.md'`)
* `'ERR_INVALID_ARG_VALUE'`
— when `conditions` is incorrect
## Algorithm
The algorithm for `resolve` matches how Node handles `import.meta.resolve`, with
a couple of differences.
The algorithm for `moduleResolve` matches the [Resolver Algorithm
Specification][algo] as detailed in the Node docs (which is sync and slightly
lower-level than `resolve`).
## Differences to Node
* `parent` defaulting to `import.meta.url` cannot be ponyfilled: you have to
explicitly pass it
* no support for loaders (that would mean implementing all of loaders)
* no support for CLI flags:
`--conditions`,
`--experimental-default-type`,
`--experimental-json-modules`,
`--experimental-network-imports`,
`--experimental-policy`,
`--experimental-wasm-modules`,
`--input-type`,
`--no-addons`,
`--preserve-symlinks`, nor
`--preserve-symlinks-main`
work
* no support for `WATCH_REPORT_DEPENDENCIES` env variable
* no attempt is made to add a suggestion based on how things used to work in
CJS before to not-found errors
* prototypal methods are not guarded: Node protects for example `String#slice`
or so from being tampered with, whereas this doesnt
## Types
This package is fully typed with [TypeScript][].
It exports the additional type [`ErrnoException`][errnoexception].
## Compatibility
This package is at least compatible with all maintained versions of Node.js.
As of now, that is Node.js 16 and later.
## Contribute
Yes please!
See [How to Contribute to Open Source][contribute].
## License
[MIT][license] © [Titus Wormer][author] and Node.js contributors
<!-- Definitions -->
[build-badge]: https://github.com/wooorm/import-meta-resolve/workflows/main/badge.svg
[build]: https://github.com/wooorm/import-meta-resolve/actions
[coverage-badge]: https://img.shields.io/codecov/c/github/wooorm/import-meta-resolve.svg
[coverage]: https://codecov.io/github/wooorm/import-meta-resolve
[downloads-badge]: https://img.shields.io/npm/dm/import-meta-resolve.svg
[downloads]: https://www.npmjs.com/package/import-meta-resolve
[npm]: https://docs.npmjs.com/cli/install
[license]: license
[author]: https://wooorm.com
[esm]: https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c
[typescript]: https://www.typescriptlang.org
[contribute]: https://opensource.guide/how-to-contribute/
[algo]: https://nodejs.org/dist/latest-v14.x/docs/api/esm.html#esm_resolver_algorithm
[native-resolve]: https://nodejs.org/api/esm.html#esm_import_meta_resolve_specifier_parent
[resolve]: #resolvespecifier-parent
[moduleresolve]: #moduleResolvespecifier-parent-conditions-preserveSymlinks
[errnoexception]: #errnoexception

21
node_modules/@eslint-community/eslint-utils/LICENSE generated vendored Normal file
View file

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2018 Toru Nagashima
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.

37
node_modules/@eslint-community/eslint-utils/README.md generated vendored Normal file
View file

@ -0,0 +1,37 @@
# @eslint-community/eslint-utils
[![npm version](https://img.shields.io/npm/v/@eslint-community/eslint-utils.svg)](https://www.npmjs.com/package/@eslint-community/eslint-utils)
[![Downloads/month](https://img.shields.io/npm/dm/@eslint-community/eslint-utils.svg)](http://www.npmtrends.com/@eslint-community/eslint-utils)
[![Build Status](https://github.com/eslint-community/eslint-utils/workflows/CI/badge.svg)](https://github.com/eslint-community/eslint-utils/actions)
[![Coverage Status](https://codecov.io/gh/eslint-community/eslint-utils/branch/main/graph/badge.svg)](https://codecov.io/gh/eslint-community/eslint-utils)
## 🏁 Goal
This package provides utility functions and classes for make ESLint custom rules.
For examples:
- [`getStaticValue`](https://eslint-community.github.io/eslint-utils/api/ast-utils.html#getstaticvalue) evaluates static value on AST.
- [`ReferenceTracker`](https://eslint-community.github.io/eslint-utils/api/scope-utils.html#referencetracker-class) checks the members of modules/globals as handling assignments and destructuring.
## 📖 Usage
See [documentation](https://eslint-community.github.io/eslint-utils).
## 📰 Changelog
See [releases](https://github.com/eslint-community/eslint-utils/releases).
## ❤️ Contributing
Welcome contributing!
Please use GitHub's Issues/PRs.
### Development Tools
- `npm run test-coverage` runs tests and measures coverage.
- `npm run clean` removes the coverage result of `npm run test-coverage` command.
- `npm run coverage` shows the coverage result of the last `npm run test-coverage` command.
- `npm run lint` runs ESLint.
- `npm run watch` runs tests on each file change.

217
node_modules/@eslint-community/eslint-utils/index.d.mts generated vendored Normal file
View file

@ -0,0 +1,217 @@
import * as eslint from 'eslint';
import { Rule, AST } from 'eslint';
import * as estree from 'estree';
declare const READ: unique symbol;
declare const CALL: unique symbol;
declare const CONSTRUCT: unique symbol;
declare const ESM: unique symbol;
declare class ReferenceTracker {
constructor(globalScope: Scope$2, options?: {
mode?: "legacy" | "strict" | undefined;
globalObjectNames?: string[] | undefined;
} | undefined);
private variableStack;
private globalScope;
private mode;
private globalObjectNames;
iterateGlobalReferences<T>(traceMap: TraceMap$2<T>): IterableIterator<TrackedReferences$2<T>>;
iterateCjsReferences<T_1>(traceMap: TraceMap$2<T_1>): IterableIterator<TrackedReferences$2<T_1>>;
iterateEsmReferences<T_2>(traceMap: TraceMap$2<T_2>): IterableIterator<TrackedReferences$2<T_2>>;
iteratePropertyReferences<T_3>(node: Expression, traceMap: TraceMap$2<T_3>): IterableIterator<TrackedReferences$2<T_3>>;
private _iterateVariableReferences;
private _iteratePropertyReferences;
private _iterateLhsReferences;
private _iterateImportReferences;
}
declare namespace ReferenceTracker {
export { READ };
export { CALL };
export { CONSTRUCT };
export { ESM };
}
type Scope$2 = eslint.Scope.Scope;
type Expression = estree.Expression;
type TraceMap$2<T> = TraceMap$1<T>;
type TrackedReferences$2<T> = TrackedReferences$1<T>;
type StaticValue$2 = StaticValueProvided$1 | StaticValueOptional$1;
type StaticValueProvided$1 = {
optional?: undefined;
value: unknown;
};
type StaticValueOptional$1 = {
optional?: true;
value: undefined;
};
type ReferenceTrackerOptions$1 = {
globalObjectNames?: string[];
mode?: "legacy" | "strict";
};
type TraceMap$1<T = unknown> = {
[i: string]: TraceMapObject<T>;
};
type TraceMapObject<T> = {
[i: string]: TraceMapObject<T>;
[CALL]?: T;
[CONSTRUCT]?: T;
[READ]?: T;
[ESM]?: boolean;
};
type TrackedReferences$1<T> = {
info: T;
node: Rule.Node;
path: string[];
type: typeof CALL | typeof CONSTRUCT | typeof READ;
};
type HasSideEffectOptions$1 = {
considerGetters?: boolean;
considerImplicitTypeConversion?: boolean;
};
type PunctuatorToken<Value extends string> = AST.Token & {
type: "Punctuator";
value: Value;
};
type ArrowToken$1 = PunctuatorToken<"=>">;
type CommaToken$1 = PunctuatorToken<",">;
type SemicolonToken$1 = PunctuatorToken<";">;
type ColonToken$1 = PunctuatorToken<":">;
type OpeningParenToken$1 = PunctuatorToken<"(">;
type ClosingParenToken$1 = PunctuatorToken<")">;
type OpeningBracketToken$1 = PunctuatorToken<"[">;
type ClosingBracketToken$1 = PunctuatorToken<"]">;
type OpeningBraceToken$1 = PunctuatorToken<"{">;
type ClosingBraceToken$1 = PunctuatorToken<"}">;
declare function findVariable(initialScope: Scope$1, nameOrNode: string | Identifier): Variable | null;
type Scope$1 = eslint.Scope.Scope;
type Variable = eslint.Scope.Variable;
type Identifier = estree.Identifier;
declare function getFunctionHeadLocation(node: FunctionNode$1, sourceCode: SourceCode$2): SourceLocation | null;
type SourceCode$2 = eslint.SourceCode;
type FunctionNode$1 = estree.Function;
type SourceLocation = estree.SourceLocation;
declare function getFunctionNameWithKind(node: FunctionNode, sourceCode?: eslint.SourceCode | undefined): string;
type FunctionNode = estree.Function;
declare function getInnermostScope(initialScope: Scope, node: Node$4): Scope;
type Scope = eslint.Scope.Scope;
type Node$4 = estree.Node;
declare function getPropertyName(node: MemberExpression | MethodDefinition | Property | PropertyDefinition, initialScope?: eslint.Scope.Scope | undefined): string | null | undefined;
type MemberExpression = estree.MemberExpression;
type MethodDefinition = estree.MethodDefinition;
type Property = estree.Property;
type PropertyDefinition = estree.PropertyDefinition;
declare function getStaticValue(node: Node$3, initialScope?: eslint.Scope.Scope | null | undefined): StaticValue$1 | null;
type StaticValue$1 = StaticValue$2;
type Node$3 = estree.Node;
declare function getStringIfConstant(node: Node$2, initialScope?: eslint.Scope.Scope | null | undefined): string | null;
type Node$2 = estree.Node;
declare function hasSideEffect(node: Node$1, sourceCode: SourceCode$1, options?: HasSideEffectOptions$1 | undefined): boolean;
type Node$1 = estree.Node;
type SourceCode$1 = eslint.SourceCode;
declare function isArrowToken(token: CommentOrToken): token is ArrowToken$1;
declare function isCommaToken(token: CommentOrToken): token is CommaToken$1;
declare function isSemicolonToken(token: CommentOrToken): token is SemicolonToken$1;
declare function isColonToken(token: CommentOrToken): token is ColonToken$1;
declare function isOpeningParenToken(token: CommentOrToken): token is OpeningParenToken$1;
declare function isClosingParenToken(token: CommentOrToken): token is ClosingParenToken$1;
declare function isOpeningBracketToken(token: CommentOrToken): token is OpeningBracketToken$1;
declare function isClosingBracketToken(token: CommentOrToken): token is ClosingBracketToken$1;
declare function isOpeningBraceToken(token: CommentOrToken): token is OpeningBraceToken$1;
declare function isClosingBraceToken(token: CommentOrToken): token is ClosingBraceToken$1;
declare function isCommentToken(token: CommentOrToken): token is estree.Comment;
declare function isNotArrowToken(arg0: CommentOrToken): boolean;
declare function isNotCommaToken(arg0: CommentOrToken): boolean;
declare function isNotSemicolonToken(arg0: CommentOrToken): boolean;
declare function isNotColonToken(arg0: CommentOrToken): boolean;
declare function isNotOpeningParenToken(arg0: CommentOrToken): boolean;
declare function isNotClosingParenToken(arg0: CommentOrToken): boolean;
declare function isNotOpeningBracketToken(arg0: CommentOrToken): boolean;
declare function isNotClosingBracketToken(arg0: CommentOrToken): boolean;
declare function isNotOpeningBraceToken(arg0: CommentOrToken): boolean;
declare function isNotClosingBraceToken(arg0: CommentOrToken): boolean;
declare function isNotCommentToken(arg0: CommentOrToken): boolean;
type Token = eslint.AST.Token;
type Comment = estree.Comment;
type CommentOrToken = Comment | Token;
declare function isParenthesized(timesOrNode: Node | number, nodeOrSourceCode: Node | SourceCode, optionalSourceCode?: eslint.SourceCode | undefined): boolean;
type Node = estree.Node;
type SourceCode = eslint.SourceCode;
declare class PatternMatcher {
constructor(pattern: RegExp, options?: {
escaped?: boolean | undefined;
} | undefined);
execAll(str: string): IterableIterator<RegExpExecArray>;
test(str: string): boolean;
[Symbol.replace](str: string, replacer: string | ((...strs: string[]) => string)): string;
}
declare namespace _default {
export { CALL };
export { CONSTRUCT };
export { ESM };
export { findVariable };
export { getFunctionHeadLocation };
export { getFunctionNameWithKind };
export { getInnermostScope };
export { getPropertyName };
export { getStaticValue };
export { getStringIfConstant };
export { hasSideEffect };
export { isArrowToken };
export { isClosingBraceToken };
export { isClosingBracketToken };
export { isClosingParenToken };
export { isColonToken };
export { isCommaToken };
export { isCommentToken };
export { isNotArrowToken };
export { isNotClosingBraceToken };
export { isNotClosingBracketToken };
export { isNotClosingParenToken };
export { isNotColonToken };
export { isNotCommaToken };
export { isNotCommentToken };
export { isNotOpeningBraceToken };
export { isNotOpeningBracketToken };
export { isNotOpeningParenToken };
export { isNotSemicolonToken };
export { isOpeningBraceToken };
export { isOpeningBracketToken };
export { isOpeningParenToken };
export { isParenthesized };
export { isSemicolonToken };
export { PatternMatcher };
export { READ };
export { ReferenceTracker };
}
type StaticValue = StaticValue$2;
type StaticValueOptional = StaticValueOptional$1;
type StaticValueProvided = StaticValueProvided$1;
type ReferenceTrackerOptions = ReferenceTrackerOptions$1;
type TraceMap<T> = TraceMap$1<T>;
type TrackedReferences<T> = TrackedReferences$1<T>;
type HasSideEffectOptions = HasSideEffectOptions$1;
type ArrowToken = ArrowToken$1;
type CommaToken = CommaToken$1;
type SemicolonToken = SemicolonToken$1;
type ColonToken = ColonToken$1;
type OpeningParenToken = OpeningParenToken$1;
type ClosingParenToken = ClosingParenToken$1;
type OpeningBracketToken = OpeningBracketToken$1;
type ClosingBracketToken = ClosingBracketToken$1;
type OpeningBraceToken = OpeningBraceToken$1;
type ClosingBraceToken = ClosingBraceToken$1;
export { ArrowToken, CALL, CONSTRUCT, ClosingBraceToken, ClosingBracketToken, ClosingParenToken, ColonToken, CommaToken, ESM, HasSideEffectOptions, OpeningBraceToken, OpeningBracketToken, OpeningParenToken, PatternMatcher, READ, ReferenceTracker, ReferenceTrackerOptions, SemicolonToken, StaticValue, StaticValueOptional, StaticValueProvided, TraceMap, TrackedReferences, _default as default, findVariable, getFunctionHeadLocation, getFunctionNameWithKind, getInnermostScope, getPropertyName, getStaticValue, getStringIfConstant, hasSideEffect, isArrowToken, isClosingBraceToken, isClosingBracketToken, isClosingParenToken, isColonToken, isCommaToken, isCommentToken, isNotArrowToken, isNotClosingBraceToken, isNotClosingBracketToken, isNotClosingParenToken, isNotColonToken, isNotCommaToken, isNotCommentToken, isNotOpeningBraceToken, isNotOpeningBracketToken, isNotOpeningParenToken, isNotSemicolonToken, isOpeningBraceToken, isOpeningBracketToken, isOpeningParenToken, isParenthesized, isSemicolonToken };

217
node_modules/@eslint-community/eslint-utils/index.d.ts generated vendored Normal file
View file

@ -0,0 +1,217 @@
import * as eslint from 'eslint';
import { Rule, AST } from 'eslint';
import * as estree from 'estree';
declare const READ: unique symbol;
declare const CALL: unique symbol;
declare const CONSTRUCT: unique symbol;
declare const ESM: unique symbol;
declare class ReferenceTracker {
constructor(globalScope: Scope$2, options?: {
mode?: "legacy" | "strict" | undefined;
globalObjectNames?: string[] | undefined;
} | undefined);
private variableStack;
private globalScope;
private mode;
private globalObjectNames;
iterateGlobalReferences<T>(traceMap: TraceMap$2<T>): IterableIterator<TrackedReferences$2<T>>;
iterateCjsReferences<T_1>(traceMap: TraceMap$2<T_1>): IterableIterator<TrackedReferences$2<T_1>>;
iterateEsmReferences<T_2>(traceMap: TraceMap$2<T_2>): IterableIterator<TrackedReferences$2<T_2>>;
iteratePropertyReferences<T_3>(node: Expression, traceMap: TraceMap$2<T_3>): IterableIterator<TrackedReferences$2<T_3>>;
private _iterateVariableReferences;
private _iteratePropertyReferences;
private _iterateLhsReferences;
private _iterateImportReferences;
}
declare namespace ReferenceTracker {
export { READ };
export { CALL };
export { CONSTRUCT };
export { ESM };
}
type Scope$2 = eslint.Scope.Scope;
type Expression = estree.Expression;
type TraceMap$2<T> = TraceMap$1<T>;
type TrackedReferences$2<T> = TrackedReferences$1<T>;
type StaticValue$2 = StaticValueProvided$1 | StaticValueOptional$1;
type StaticValueProvided$1 = {
optional?: undefined;
value: unknown;
};
type StaticValueOptional$1 = {
optional?: true;
value: undefined;
};
type ReferenceTrackerOptions$1 = {
globalObjectNames?: string[];
mode?: "legacy" | "strict";
};
type TraceMap$1<T = unknown> = {
[i: string]: TraceMapObject<T>;
};
type TraceMapObject<T> = {
[i: string]: TraceMapObject<T>;
[CALL]?: T;
[CONSTRUCT]?: T;
[READ]?: T;
[ESM]?: boolean;
};
type TrackedReferences$1<T> = {
info: T;
node: Rule.Node;
path: string[];
type: typeof CALL | typeof CONSTRUCT | typeof READ;
};
type HasSideEffectOptions$1 = {
considerGetters?: boolean;
considerImplicitTypeConversion?: boolean;
};
type PunctuatorToken<Value extends string> = AST.Token & {
type: "Punctuator";
value: Value;
};
type ArrowToken$1 = PunctuatorToken<"=>">;
type CommaToken$1 = PunctuatorToken<",">;
type SemicolonToken$1 = PunctuatorToken<";">;
type ColonToken$1 = PunctuatorToken<":">;
type OpeningParenToken$1 = PunctuatorToken<"(">;
type ClosingParenToken$1 = PunctuatorToken<")">;
type OpeningBracketToken$1 = PunctuatorToken<"[">;
type ClosingBracketToken$1 = PunctuatorToken<"]">;
type OpeningBraceToken$1 = PunctuatorToken<"{">;
type ClosingBraceToken$1 = PunctuatorToken<"}">;
declare function findVariable(initialScope: Scope$1, nameOrNode: string | Identifier): Variable | null;
type Scope$1 = eslint.Scope.Scope;
type Variable = eslint.Scope.Variable;
type Identifier = estree.Identifier;
declare function getFunctionHeadLocation(node: FunctionNode$1, sourceCode: SourceCode$2): SourceLocation | null;
type SourceCode$2 = eslint.SourceCode;
type FunctionNode$1 = estree.Function;
type SourceLocation = estree.SourceLocation;
declare function getFunctionNameWithKind(node: FunctionNode, sourceCode?: eslint.SourceCode | undefined): string;
type FunctionNode = estree.Function;
declare function getInnermostScope(initialScope: Scope, node: Node$4): Scope;
type Scope = eslint.Scope.Scope;
type Node$4 = estree.Node;
declare function getPropertyName(node: MemberExpression | MethodDefinition | Property | PropertyDefinition, initialScope?: eslint.Scope.Scope | undefined): string | null | undefined;
type MemberExpression = estree.MemberExpression;
type MethodDefinition = estree.MethodDefinition;
type Property = estree.Property;
type PropertyDefinition = estree.PropertyDefinition;
declare function getStaticValue(node: Node$3, initialScope?: eslint.Scope.Scope | null | undefined): StaticValue$1 | null;
type StaticValue$1 = StaticValue$2;
type Node$3 = estree.Node;
declare function getStringIfConstant(node: Node$2, initialScope?: eslint.Scope.Scope | null | undefined): string | null;
type Node$2 = estree.Node;
declare function hasSideEffect(node: Node$1, sourceCode: SourceCode$1, options?: HasSideEffectOptions$1 | undefined): boolean;
type Node$1 = estree.Node;
type SourceCode$1 = eslint.SourceCode;
declare function isArrowToken(token: CommentOrToken): token is ArrowToken$1;
declare function isCommaToken(token: CommentOrToken): token is CommaToken$1;
declare function isSemicolonToken(token: CommentOrToken): token is SemicolonToken$1;
declare function isColonToken(token: CommentOrToken): token is ColonToken$1;
declare function isOpeningParenToken(token: CommentOrToken): token is OpeningParenToken$1;
declare function isClosingParenToken(token: CommentOrToken): token is ClosingParenToken$1;
declare function isOpeningBracketToken(token: CommentOrToken): token is OpeningBracketToken$1;
declare function isClosingBracketToken(token: CommentOrToken): token is ClosingBracketToken$1;
declare function isOpeningBraceToken(token: CommentOrToken): token is OpeningBraceToken$1;
declare function isClosingBraceToken(token: CommentOrToken): token is ClosingBraceToken$1;
declare function isCommentToken(token: CommentOrToken): token is estree.Comment;
declare function isNotArrowToken(arg0: CommentOrToken): boolean;
declare function isNotCommaToken(arg0: CommentOrToken): boolean;
declare function isNotSemicolonToken(arg0: CommentOrToken): boolean;
declare function isNotColonToken(arg0: CommentOrToken): boolean;
declare function isNotOpeningParenToken(arg0: CommentOrToken): boolean;
declare function isNotClosingParenToken(arg0: CommentOrToken): boolean;
declare function isNotOpeningBracketToken(arg0: CommentOrToken): boolean;
declare function isNotClosingBracketToken(arg0: CommentOrToken): boolean;
declare function isNotOpeningBraceToken(arg0: CommentOrToken): boolean;
declare function isNotClosingBraceToken(arg0: CommentOrToken): boolean;
declare function isNotCommentToken(arg0: CommentOrToken): boolean;
type Token = eslint.AST.Token;
type Comment = estree.Comment;
type CommentOrToken = Comment | Token;
declare function isParenthesized(timesOrNode: Node | number, nodeOrSourceCode: Node | SourceCode, optionalSourceCode?: eslint.SourceCode | undefined): boolean;
type Node = estree.Node;
type SourceCode = eslint.SourceCode;
declare class PatternMatcher {
constructor(pattern: RegExp, options?: {
escaped?: boolean | undefined;
} | undefined);
execAll(str: string): IterableIterator<RegExpExecArray>;
test(str: string): boolean;
[Symbol.replace](str: string, replacer: string | ((...strs: string[]) => string)): string;
}
declare namespace _default {
export { CALL };
export { CONSTRUCT };
export { ESM };
export { findVariable };
export { getFunctionHeadLocation };
export { getFunctionNameWithKind };
export { getInnermostScope };
export { getPropertyName };
export { getStaticValue };
export { getStringIfConstant };
export { hasSideEffect };
export { isArrowToken };
export { isClosingBraceToken };
export { isClosingBracketToken };
export { isClosingParenToken };
export { isColonToken };
export { isCommaToken };
export { isCommentToken };
export { isNotArrowToken };
export { isNotClosingBraceToken };
export { isNotClosingBracketToken };
export { isNotClosingParenToken };
export { isNotColonToken };
export { isNotCommaToken };
export { isNotCommentToken };
export { isNotOpeningBraceToken };
export { isNotOpeningBracketToken };
export { isNotOpeningParenToken };
export { isNotSemicolonToken };
export { isOpeningBraceToken };
export { isOpeningBracketToken };
export { isOpeningParenToken };
export { isParenthesized };
export { isSemicolonToken };
export { PatternMatcher };
export { READ };
export { ReferenceTracker };
}
type StaticValue = StaticValue$2;
type StaticValueOptional = StaticValueOptional$1;
type StaticValueProvided = StaticValueProvided$1;
type ReferenceTrackerOptions = ReferenceTrackerOptions$1;
type TraceMap<T> = TraceMap$1<T>;
type TrackedReferences<T> = TrackedReferences$1<T>;
type HasSideEffectOptions = HasSideEffectOptions$1;
type ArrowToken = ArrowToken$1;
type CommaToken = CommaToken$1;
type SemicolonToken = SemicolonToken$1;
type ColonToken = ColonToken$1;
type OpeningParenToken = OpeningParenToken$1;
type ClosingParenToken = ClosingParenToken$1;
type OpeningBracketToken = OpeningBracketToken$1;
type ClosingBracketToken = ClosingBracketToken$1;
type OpeningBraceToken = OpeningBraceToken$1;
type ClosingBraceToken = ClosingBraceToken$1;
export { ArrowToken, CALL, CONSTRUCT, ClosingBraceToken, ClosingBracketToken, ClosingParenToken, ColonToken, CommaToken, ESM, HasSideEffectOptions, OpeningBraceToken, OpeningBracketToken, OpeningParenToken, PatternMatcher, READ, ReferenceTracker, ReferenceTrackerOptions, SemicolonToken, StaticValue, StaticValueOptional, StaticValueProvided, TraceMap, TrackedReferences, _default as default, findVariable, getFunctionHeadLocation, getFunctionNameWithKind, getInnermostScope, getPropertyName, getStaticValue, getStringIfConstant, hasSideEffect, isArrowToken, isClosingBraceToken, isClosingBracketToken, isClosingParenToken, isColonToken, isCommaToken, isCommentToken, isNotArrowToken, isNotClosingBraceToken, isNotClosingBracketToken, isNotClosingParenToken, isNotColonToken, isNotCommaToken, isNotCommentToken, isNotOpeningBraceToken, isNotOpeningBracketToken, isNotOpeningParenToken, isNotSemicolonToken, isOpeningBraceToken, isOpeningBracketToken, isOpeningParenToken, isParenthesized, isSemicolonToken };

2494
node_modules/@eslint-community/eslint-utils/index.js generated vendored Normal file

File diff suppressed because it is too large Load diff

File diff suppressed because one or more lines are too long

2453
node_modules/@eslint-community/eslint-utils/index.mjs generated vendored Normal file

File diff suppressed because it is too large Load diff

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright contributors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View file

@ -0,0 +1,105 @@
# eslint-visitor-keys
[![npm version](https://img.shields.io/npm/v/eslint-visitor-keys.svg)](https://www.npmjs.com/package/eslint-visitor-keys)
[![Downloads/month](https://img.shields.io/npm/dm/eslint-visitor-keys.svg)](http://www.npmtrends.com/eslint-visitor-keys)
[![Build Status](https://github.com/eslint/eslint-visitor-keys/workflows/CI/badge.svg)](https://github.com/eslint/eslint-visitor-keys/actions)
Constants and utilities about visitor keys to traverse AST.
## 💿 Installation
Use [npm] to install.
```bash
$ npm install eslint-visitor-keys
```
### Requirements
- [Node.js] `^12.22.0`, `^14.17.0`, or `>=16.0.0`
## 📖 Usage
To use in an ESM file:
```js
import * as evk from "eslint-visitor-keys"
```
To use in a CommonJS file:
```js
const evk = require("eslint-visitor-keys")
```
### evk.KEYS
> type: `{ [type: string]: string[] | undefined }`
Visitor keys. This keys are frozen.
This is an object. Keys are the type of [ESTree] nodes. Their values are an array of property names which have child nodes.
For example:
```
console.log(evk.KEYS.AssignmentExpression) // → ["left", "right"]
```
### evk.getKeys(node)
> type: `(node: object) => string[]`
Get the visitor keys of a given AST node.
This is similar to `Object.keys(node)` of ES Standard, but some keys are excluded: `parent`, `leadingComments`, `trailingComments`, and names which start with `_`.
This will be used to traverse unknown nodes.
For example:
```js
const node = {
type: "AssignmentExpression",
left: { type: "Identifier", name: "foo" },
right: { type: "Literal", value: 0 }
}
console.log(evk.getKeys(node)) // → ["type", "left", "right"]
```
### evk.unionWith(additionalKeys)
> type: `(additionalKeys: object) => { [type: string]: string[] | undefined }`
Make the union set with `evk.KEYS` and the given keys.
- The order of keys is, `additionalKeys` is at first, then `evk.KEYS` is concatenated after that.
- It removes duplicated keys as keeping the first one.
For example:
```js
console.log(evk.unionWith({
MethodDefinition: ["decorators"]
})) // → { ..., MethodDefinition: ["decorators", "key", "value"], ... }
```
## 📰 Change log
See [GitHub releases](https://github.com/eslint/eslint-visitor-keys/releases).
## 🍻 Contributing
Welcome. See [ESLint contribution guidelines](https://eslint.org/docs/developer-guide/contributing/).
### Development commands
- `npm test` runs tests and measures code coverage.
- `npm run lint` checks source codes with ESLint.
- `npm run test:open-coverage` opens the code coverage report of the previous test with your default browser.
[npm]: https://www.npmjs.com/
[Node.js]: https://nodejs.org/
[ESTree]: https://github.com/estree/estree

View file

@ -0,0 +1,384 @@
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
/**
* @typedef {{ readonly [type: string]: ReadonlyArray<string> }} VisitorKeys
*/
/**
* @type {VisitorKeys}
*/
const KEYS = {
ArrayExpression: [
"elements"
],
ArrayPattern: [
"elements"
],
ArrowFunctionExpression: [
"params",
"body"
],
AssignmentExpression: [
"left",
"right"
],
AssignmentPattern: [
"left",
"right"
],
AwaitExpression: [
"argument"
],
BinaryExpression: [
"left",
"right"
],
BlockStatement: [
"body"
],
BreakStatement: [
"label"
],
CallExpression: [
"callee",
"arguments"
],
CatchClause: [
"param",
"body"
],
ChainExpression: [
"expression"
],
ClassBody: [
"body"
],
ClassDeclaration: [
"id",
"superClass",
"body"
],
ClassExpression: [
"id",
"superClass",
"body"
],
ConditionalExpression: [
"test",
"consequent",
"alternate"
],
ContinueStatement: [
"label"
],
DebuggerStatement: [],
DoWhileStatement: [
"body",
"test"
],
EmptyStatement: [],
ExperimentalRestProperty: [
"argument"
],
ExperimentalSpreadProperty: [
"argument"
],
ExportAllDeclaration: [
"exported",
"source"
],
ExportDefaultDeclaration: [
"declaration"
],
ExportNamedDeclaration: [
"declaration",
"specifiers",
"source"
],
ExportSpecifier: [
"exported",
"local"
],
ExpressionStatement: [
"expression"
],
ForInStatement: [
"left",
"right",
"body"
],
ForOfStatement: [
"left",
"right",
"body"
],
ForStatement: [
"init",
"test",
"update",
"body"
],
FunctionDeclaration: [
"id",
"params",
"body"
],
FunctionExpression: [
"id",
"params",
"body"
],
Identifier: [],
IfStatement: [
"test",
"consequent",
"alternate"
],
ImportDeclaration: [
"specifiers",
"source"
],
ImportDefaultSpecifier: [
"local"
],
ImportExpression: [
"source"
],
ImportNamespaceSpecifier: [
"local"
],
ImportSpecifier: [
"imported",
"local"
],
JSXAttribute: [
"name",
"value"
],
JSXClosingElement: [
"name"
],
JSXClosingFragment: [],
JSXElement: [
"openingElement",
"children",
"closingElement"
],
JSXEmptyExpression: [],
JSXExpressionContainer: [
"expression"
],
JSXFragment: [
"openingFragment",
"children",
"closingFragment"
],
JSXIdentifier: [],
JSXMemberExpression: [
"object",
"property"
],
JSXNamespacedName: [
"namespace",
"name"
],
JSXOpeningElement: [
"name",
"attributes"
],
JSXOpeningFragment: [],
JSXSpreadAttribute: [
"argument"
],
JSXSpreadChild: [
"expression"
],
JSXText: [],
LabeledStatement: [
"label",
"body"
],
Literal: [],
LogicalExpression: [
"left",
"right"
],
MemberExpression: [
"object",
"property"
],
MetaProperty: [
"meta",
"property"
],
MethodDefinition: [
"key",
"value"
],
NewExpression: [
"callee",
"arguments"
],
ObjectExpression: [
"properties"
],
ObjectPattern: [
"properties"
],
PrivateIdentifier: [],
Program: [
"body"
],
Property: [
"key",
"value"
],
PropertyDefinition: [
"key",
"value"
],
RestElement: [
"argument"
],
ReturnStatement: [
"argument"
],
SequenceExpression: [
"expressions"
],
SpreadElement: [
"argument"
],
StaticBlock: [
"body"
],
Super: [],
SwitchCase: [
"test",
"consequent"
],
SwitchStatement: [
"discriminant",
"cases"
],
TaggedTemplateExpression: [
"tag",
"quasi"
],
TemplateElement: [],
TemplateLiteral: [
"quasis",
"expressions"
],
ThisExpression: [],
ThrowStatement: [
"argument"
],
TryStatement: [
"block",
"handler",
"finalizer"
],
UnaryExpression: [
"argument"
],
UpdateExpression: [
"argument"
],
VariableDeclaration: [
"declarations"
],
VariableDeclarator: [
"id",
"init"
],
WhileStatement: [
"test",
"body"
],
WithStatement: [
"object",
"body"
],
YieldExpression: [
"argument"
]
};
// Types.
const NODE_TYPES = Object.keys(KEYS);
// Freeze the keys.
for (const type of NODE_TYPES) {
Object.freeze(KEYS[type]);
}
Object.freeze(KEYS);
/**
* @author Toru Nagashima <https://github.com/mysticatea>
* See LICENSE file in root directory for full license.
*/
/**
* @typedef {import('./visitor-keys.js').VisitorKeys} VisitorKeys
*/
// List to ignore keys.
const KEY_BLACKLIST = new Set([
"parent",
"leadingComments",
"trailingComments"
]);
/**
* Check whether a given key should be used or not.
* @param {string} key The key to check.
* @returns {boolean} `true` if the key should be used.
*/
function filterKey(key) {
return !KEY_BLACKLIST.has(key) && key[0] !== "_";
}
/**
* Get visitor keys of a given node.
* @param {object} node The AST node to get keys.
* @returns {readonly string[]} Visitor keys of the node.
*/
function getKeys(node) {
return Object.keys(node).filter(filterKey);
}
// Disable valid-jsdoc rule because it reports syntax error on the type of @returns.
// eslint-disable-next-line valid-jsdoc
/**
* Make the union set with `KEYS` and given keys.
* @param {VisitorKeys} additionalKeys The additional keys.
* @returns {VisitorKeys} The union set.
*/
function unionWith(additionalKeys) {
const retv = /** @type {{
[type: string]: ReadonlyArray<string>
}} */ (Object.assign({}, KEYS));
for (const type of Object.keys(additionalKeys)) {
if (Object.prototype.hasOwnProperty.call(retv, type)) {
const keys = new Set(additionalKeys[type]);
for (const key of retv[type]) {
keys.add(key);
}
retv[type] = Object.freeze(Array.from(keys));
} else {
retv[type] = Object.freeze(Array.from(additionalKeys[type]));
}
}
return Object.freeze(retv);
}
exports.KEYS = KEYS;
exports.getKeys = getKeys;
exports.unionWith = unionWith;

View file

@ -0,0 +1,27 @@
type VisitorKeys$1 = {
readonly [type: string]: readonly string[];
};
/**
* @typedef {{ readonly [type: string]: ReadonlyArray<string> }} VisitorKeys
*/
/**
* @type {VisitorKeys}
*/
declare const KEYS: VisitorKeys$1;
/**
* Get visitor keys of a given node.
* @param {object} node The AST node to get keys.
* @returns {readonly string[]} Visitor keys of the node.
*/
declare function getKeys(node: object): readonly string[];
/**
* Make the union set with `KEYS` and given keys.
* @param {VisitorKeys} additionalKeys The additional keys.
* @returns {VisitorKeys} The union set.
*/
declare function unionWith(additionalKeys: VisitorKeys): VisitorKeys;
type VisitorKeys = VisitorKeys$1;
export { KEYS, VisitorKeys, getKeys, unionWith };

View file

@ -0,0 +1,16 @@
/**
* Get visitor keys of a given node.
* @param {object} node The AST node to get keys.
* @returns {readonly string[]} Visitor keys of the node.
*/
export function getKeys(node: object): readonly string[];
/**
* Make the union set with `KEYS` and given keys.
* @param {VisitorKeys} additionalKeys The additional keys.
* @returns {VisitorKeys} The union set.
*/
export function unionWith(additionalKeys: VisitorKeys): VisitorKeys;
export { KEYS };
export type VisitorKeys = import('./visitor-keys.js').VisitorKeys;
import KEYS from "./visitor-keys.js";
//# sourceMappingURL=index.d.ts.map

View file

@ -0,0 +1,12 @@
export default KEYS;
export type VisitorKeys = {
readonly [type: string]: readonly string[];
};
/**
* @typedef {{ readonly [type: string]: ReadonlyArray<string> }} VisitorKeys
*/
/**
* @type {VisitorKeys}
*/
declare const KEYS: VisitorKeys;
//# sourceMappingURL=visitor-keys.d.ts.map

View file

@ -0,0 +1,65 @@
/**
* @author Toru Nagashima <https://github.com/mysticatea>
* See LICENSE file in root directory for full license.
*/
import KEYS from "./visitor-keys.js";
/**
* @typedef {import('./visitor-keys.js').VisitorKeys} VisitorKeys
*/
// List to ignore keys.
const KEY_BLACKLIST = new Set([
"parent",
"leadingComments",
"trailingComments"
]);
/**
* Check whether a given key should be used or not.
* @param {string} key The key to check.
* @returns {boolean} `true` if the key should be used.
*/
function filterKey(key) {
return !KEY_BLACKLIST.has(key) && key[0] !== "_";
}
/**
* Get visitor keys of a given node.
* @param {object} node The AST node to get keys.
* @returns {readonly string[]} Visitor keys of the node.
*/
export function getKeys(node) {
return Object.keys(node).filter(filterKey);
}
// Disable valid-jsdoc rule because it reports syntax error on the type of @returns.
// eslint-disable-next-line valid-jsdoc
/**
* Make the union set with `KEYS` and given keys.
* @param {VisitorKeys} additionalKeys The additional keys.
* @returns {VisitorKeys} The union set.
*/
export function unionWith(additionalKeys) {
const retv = /** @type {{
[type: string]: ReadonlyArray<string>
}} */ (Object.assign({}, KEYS));
for (const type of Object.keys(additionalKeys)) {
if (Object.prototype.hasOwnProperty.call(retv, type)) {
const keys = new Set(additionalKeys[type]);
for (const key of retv[type]) {
keys.add(key);
}
retv[type] = Object.freeze(Array.from(keys));
} else {
retv[type] = Object.freeze(Array.from(additionalKeys[type]));
}
}
return Object.freeze(retv);
}
export { KEYS };

View file

@ -0,0 +1,315 @@
/**
* @typedef {{ readonly [type: string]: ReadonlyArray<string> }} VisitorKeys
*/
/**
* @type {VisitorKeys}
*/
const KEYS = {
ArrayExpression: [
"elements"
],
ArrayPattern: [
"elements"
],
ArrowFunctionExpression: [
"params",
"body"
],
AssignmentExpression: [
"left",
"right"
],
AssignmentPattern: [
"left",
"right"
],
AwaitExpression: [
"argument"
],
BinaryExpression: [
"left",
"right"
],
BlockStatement: [
"body"
],
BreakStatement: [
"label"
],
CallExpression: [
"callee",
"arguments"
],
CatchClause: [
"param",
"body"
],
ChainExpression: [
"expression"
],
ClassBody: [
"body"
],
ClassDeclaration: [
"id",
"superClass",
"body"
],
ClassExpression: [
"id",
"superClass",
"body"
],
ConditionalExpression: [
"test",
"consequent",
"alternate"
],
ContinueStatement: [
"label"
],
DebuggerStatement: [],
DoWhileStatement: [
"body",
"test"
],
EmptyStatement: [],
ExperimentalRestProperty: [
"argument"
],
ExperimentalSpreadProperty: [
"argument"
],
ExportAllDeclaration: [
"exported",
"source"
],
ExportDefaultDeclaration: [
"declaration"
],
ExportNamedDeclaration: [
"declaration",
"specifiers",
"source"
],
ExportSpecifier: [
"exported",
"local"
],
ExpressionStatement: [
"expression"
],
ForInStatement: [
"left",
"right",
"body"
],
ForOfStatement: [
"left",
"right",
"body"
],
ForStatement: [
"init",
"test",
"update",
"body"
],
FunctionDeclaration: [
"id",
"params",
"body"
],
FunctionExpression: [
"id",
"params",
"body"
],
Identifier: [],
IfStatement: [
"test",
"consequent",
"alternate"
],
ImportDeclaration: [
"specifiers",
"source"
],
ImportDefaultSpecifier: [
"local"
],
ImportExpression: [
"source"
],
ImportNamespaceSpecifier: [
"local"
],
ImportSpecifier: [
"imported",
"local"
],
JSXAttribute: [
"name",
"value"
],
JSXClosingElement: [
"name"
],
JSXClosingFragment: [],
JSXElement: [
"openingElement",
"children",
"closingElement"
],
JSXEmptyExpression: [],
JSXExpressionContainer: [
"expression"
],
JSXFragment: [
"openingFragment",
"children",
"closingFragment"
],
JSXIdentifier: [],
JSXMemberExpression: [
"object",
"property"
],
JSXNamespacedName: [
"namespace",
"name"
],
JSXOpeningElement: [
"name",
"attributes"
],
JSXOpeningFragment: [],
JSXSpreadAttribute: [
"argument"
],
JSXSpreadChild: [
"expression"
],
JSXText: [],
LabeledStatement: [
"label",
"body"
],
Literal: [],
LogicalExpression: [
"left",
"right"
],
MemberExpression: [
"object",
"property"
],
MetaProperty: [
"meta",
"property"
],
MethodDefinition: [
"key",
"value"
],
NewExpression: [
"callee",
"arguments"
],
ObjectExpression: [
"properties"
],
ObjectPattern: [
"properties"
],
PrivateIdentifier: [],
Program: [
"body"
],
Property: [
"key",
"value"
],
PropertyDefinition: [
"key",
"value"
],
RestElement: [
"argument"
],
ReturnStatement: [
"argument"
],
SequenceExpression: [
"expressions"
],
SpreadElement: [
"argument"
],
StaticBlock: [
"body"
],
Super: [],
SwitchCase: [
"test",
"consequent"
],
SwitchStatement: [
"discriminant",
"cases"
],
TaggedTemplateExpression: [
"tag",
"quasi"
],
TemplateElement: [],
TemplateLiteral: [
"quasis",
"expressions"
],
ThisExpression: [],
ThrowStatement: [
"argument"
],
TryStatement: [
"block",
"handler",
"finalizer"
],
UnaryExpression: [
"argument"
],
UpdateExpression: [
"argument"
],
VariableDeclaration: [
"declarations"
],
VariableDeclarator: [
"id",
"init"
],
WhileStatement: [
"test",
"body"
],
WithStatement: [
"object",
"body"
],
YieldExpression: [
"argument"
]
};
// Types.
const NODE_TYPES = Object.keys(KEYS);
// Freeze the keys.
for (const type of NODE_TYPES) {
Object.freeze(KEYS[type]);
}
Object.freeze(KEYS);
export default KEYS;

View file

@ -0,0 +1,74 @@
{
"name": "eslint-visitor-keys",
"version": "3.4.3",
"description": "Constants and utilities about visitor keys to traverse AST.",
"type": "module",
"main": "dist/eslint-visitor-keys.cjs",
"types": "./dist/index.d.ts",
"exports": {
".": [
{
"import": "./lib/index.js",
"require": "./dist/eslint-visitor-keys.cjs"
},
"./dist/eslint-visitor-keys.cjs"
],
"./package.json": "./package.json"
},
"files": [
"dist/index.d.ts",
"dist/visitor-keys.d.ts",
"dist/eslint-visitor-keys.cjs",
"dist/eslint-visitor-keys.d.cts",
"lib"
],
"engines": {
"node": "^12.22.0 || ^14.17.0 || >=16.0.0"
},
"devDependencies": {
"@types/estree": "^0.0.51",
"@types/estree-jsx": "^0.0.1",
"@typescript-eslint/parser": "^5.14.0",
"c8": "^7.11.0",
"chai": "^4.3.6",
"eslint": "^7.29.0",
"eslint-config-eslint": "^7.0.0",
"eslint-plugin-jsdoc": "^35.4.0",
"eslint-plugin-node": "^11.1.0",
"eslint-release": "^3.2.0",
"esquery": "^1.4.0",
"json-diff": "^0.7.3",
"mocha": "^9.2.1",
"opener": "^1.5.2",
"rollup": "^2.70.0",
"rollup-plugin-dts": "^4.2.3",
"tsd": "^0.19.1",
"typescript": "^4.6.2"
},
"scripts": {
"build": "npm run build:cjs && npm run build:types",
"build:cjs": "rollup -c",
"build:debug": "npm run build:cjs -- -m && npm run build:types",
"build:keys": "node tools/build-keys-from-ts",
"build:types": "tsc",
"lint": "eslint .",
"prepare": "npm run build",
"release:generate:latest": "eslint-generate-release",
"release:generate:alpha": "eslint-generate-prerelease alpha",
"release:generate:beta": "eslint-generate-prerelease beta",
"release:generate:rc": "eslint-generate-prerelease rc",
"release:publish": "eslint-publish-release",
"test": "mocha tests/lib/**/*.cjs && c8 mocha tests/lib/**/*.js && npm run test:types",
"test:open-coverage": "c8 report --reporter lcov && opener coverage/lcov-report/index.html",
"test:types": "tsd"
},
"repository": "eslint/eslint-visitor-keys",
"funding": "https://opencollective.com/eslint",
"keywords": [],
"author": "Toru Nagashima (https://github.com/mysticatea)",
"license": "Apache-2.0",
"bugs": {
"url": "https://github.com/eslint/eslint-visitor-keys/issues"
},
"homepage": "https://github.com/eslint/eslint-visitor-keys#readme"
}

View file

@ -0,0 +1,89 @@
{
"name": "@eslint-community/eslint-utils",
"version": "4.7.0",
"description": "Utilities for ESLint plugins.",
"keywords": [
"eslint"
],
"homepage": "https://github.com/eslint-community/eslint-utils#readme",
"bugs": {
"url": "https://github.com/eslint-community/eslint-utils/issues"
},
"repository": {
"type": "git",
"url": "https://github.com/eslint-community/eslint-utils"
},
"license": "MIT",
"author": "Toru Nagashima",
"sideEffects": false,
"exports": {
".": {
"import": "./index.mjs",
"require": "./index.js"
},
"./package.json": "./package.json"
},
"main": "index",
"module": "index.mjs",
"files": [
"index.*"
],
"scripts": {
"prebuild": "npm run -s clean",
"build": "npm run build:dts && npm run build:rollup",
"build:dts": "tsc -p tsconfig.build.json",
"build:rollup": "rollup -c",
"clean": "rimraf .nyc_output coverage index.* dist",
"coverage": "opener ./coverage/lcov-report/index.html",
"docs:build": "vitepress build docs",
"docs:watch": "vitepress dev docs",
"format": "npm run -s format:prettier -- --write",
"format:prettier": "prettier .",
"format:check": "npm run -s format:prettier -- --check",
"lint:eslint": "eslint .",
"lint:format": "npm run -s format:check",
"lint:installed-check": "installed-check -v -i installed-check -i npm-run-all2 -i knip -i rollup-plugin-dts",
"lint:knip": "knip",
"lint": "run-p lint:*",
"test-coverage": "c8 mocha --reporter dot \"test/*.mjs\"",
"test": "mocha --reporter dot \"test/*.mjs\"",
"preversion": "npm run test-coverage && npm run -s build",
"postversion": "git push && git push --tags",
"prewatch": "npm run -s clean",
"watch": "warun \"{src,test}/**/*.mjs\" -- npm run -s test:mocha"
},
"dependencies": {
"eslint-visitor-keys": "^3.4.3"
},
"devDependencies": {
"@eslint-community/eslint-plugin-mysticatea": "^15.6.1",
"@types/eslint": "^9.6.1",
"@types/estree": "^1.0.7",
"@typescript-eslint/parser": "^5.62.0",
"@typescript-eslint/types": "^5.62.0",
"c8": "^8.0.1",
"dot-prop": "^7.2.0",
"eslint": "^8.57.1",
"installed-check": "^8.0.1",
"knip": "^5.33.3",
"mocha": "^9.2.2",
"npm-run-all2": "^6.2.3",
"opener": "^1.5.2",
"prettier": "2.8.8",
"rimraf": "^3.0.2",
"rollup": "^2.79.2",
"rollup-plugin-dts": "^4.2.3",
"rollup-plugin-sourcemaps": "^0.6.3",
"semver": "^7.6.3",
"typescript": "^4.9.5",
"vitepress": "^1.4.1",
"warun": "^1.0.0"
},
"peerDependencies": {
"eslint": "^6.0.0 || ^7.0.0 || >=8.0.0"
},
"engines": {
"node": "^12.22.0 || ^14.17.0 || >=16.0.0"
},
"funding": "https://opencollective.com/eslint"
}

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