tools: update eslint to 9.7.0

PR-URL: https://github.com/nodejs/node/pull/53839
Reviewed-By: Luigi Pinca <luigipinca@gmail.com>
Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
Reviewed-By: Moshe Atlow <moshe@atlow.co.il>
Reviewed-By: James M Snell <jasnell@gmail.com>
This commit is contained in:
Node.js GitHub Bot 2024-07-16 03:33:10 +03:00 committed by GitHub
parent d9b0450d92
commit 3ad38e4938
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
147 changed files with 4516 additions and 2374 deletions

View file

@ -1,6 +1,6 @@
{ {
"name": "@babel/compat-data", "name": "@babel/compat-data",
"version": "7.24.7", "version": "7.24.8",
"author": "The Babel Team (https://babel.dev/team)", "author": "The Babel Team (https://babel.dev/team)",
"license": "MIT", "license": "MIT",
"description": "", "description": "",
@ -29,9 +29,9 @@
"compat-data" "compat-data"
], ],
"devDependencies": { "devDependencies": {
"@mdn/browser-compat-data": "^5.3.0", "@mdn/browser-compat-data": "^5.5.36",
"core-js-compat": "^3.31.0", "core-js-compat": "^3.37.1",
"electron-to-chromium": "^1.4.441" "electron-to-chromium": "^1.4.816"
}, },
"engines": { "engines": {
"node": ">=6.9.0" "node": ">=6.9.0"

View file

@ -137,7 +137,7 @@ function babelrcLoadEnabled(context, pkgData, babelrcRoots, babelrcRootsDirector
if (typeof babelrcRoots === "boolean") return babelrcRoots; if (typeof babelrcRoots === "boolean") return babelrcRoots;
const absoluteRoot = context.root; const absoluteRoot = context.root;
if (babelrcRoots === undefined) { if (babelrcRoots === undefined) {
return pkgData.directories.indexOf(absoluteRoot) !== -1; return pkgData.directories.includes(absoluteRoot);
} }
let babelrcPatterns = babelrcRoots; let babelrcPatterns = babelrcRoots;
if (!Array.isArray(babelrcPatterns)) { if (!Array.isArray(babelrcPatterns)) {
@ -147,7 +147,7 @@ function babelrcLoadEnabled(context, pkgData, babelrcRoots, babelrcRootsDirector
return typeof pat === "string" ? _path().resolve(babelrcRootsDirectory, pat) : pat; return typeof pat === "string" ? _path().resolve(babelrcRootsDirectory, pat) : pat;
}); });
if (babelrcPatterns.length === 1 && babelrcPatterns[0] === absoluteRoot) { if (babelrcPatterns.length === 1 && babelrcPatterns[0] === absoluteRoot) {
return pkgData.directories.indexOf(absoluteRoot) !== -1; return pkgData.directories.includes(absoluteRoot);
} }
return babelrcPatterns.some(pat => { return babelrcPatterns.some(pat => {
if (typeof pat === "string") { if (typeof pat === "string") {

View file

@ -83,7 +83,7 @@ function loadCachedDescriptor(cache, desc) {
possibilities = []; possibilities = [];
cacheByOptions.set(options, possibilities); cacheByOptions.set(options, possibilities);
} }
if (possibilities.indexOf(desc) === -1) { if (!possibilities.includes(desc)) {
const matches = possibilities.filter(possibility => isEqualDescriptor(possibility, desc)); const matches = possibilities.filter(possibility => isEqualDescriptor(possibility, desc));
if (matches.length > 0) { if (matches.length > 0) {
return matches[0]; return matches[0];

View file

@ -224,7 +224,7 @@ var _transformAst = require("./transform-ast.js");
var _parse = require("./parse.js"); var _parse = require("./parse.js");
var thisFile = require("./index.js"); var thisFile = require("./index.js");
; ;
const version = exports.version = "7.24.7"; const version = exports.version = "7.24.8";
const DEFAULT_EXTENSIONS = exports.DEFAULT_EXTENSIONS = Object.freeze([".js", ".jsx", ".es6", ".es", ".mjs", ".cjs"]); const DEFAULT_EXTENSIONS = exports.DEFAULT_EXTENSIONS = Object.freeze([".js", ".jsx", ".es6", ".es", ".mjs", ".cjs"]);
; ;
{ {

View file

@ -112,7 +112,7 @@ function buildHelpers(body, namespace, allowlist) {
}; };
const refs = {}; const refs = {};
helpers().list.forEach(function (name) { helpers().list.forEach(function (name) {
if (allowlist && allowlist.indexOf(name) < 0) return; if (allowlist && !allowlist.includes(name)) return;
const ref = refs[name] = getHelperReference(name); const ref = refs[name] = getHelperReference(name);
const { const {
nodes nodes

View file

@ -32,13 +32,6 @@ function _t() {
}; };
return data; return data;
} }
function _helperModuleTransforms() {
const data = require("@babel/helper-module-transforms");
_helperModuleTransforms = function () {
return data;
};
return data;
}
function _semver() { function _semver() {
const data = require("semver"); const data = require("semver");
_semver = function () { _semver = function () {
@ -121,9 +114,6 @@ class File {
has(key) { has(key) {
return this._map.has(key); return this._map.has(key);
} }
getModuleName() {
return (0, _helperModuleTransforms().getModuleName)(this.opts, this.opts);
}
availableHelper(name, versionRange) { availableHelper(name, versionRange) {
let minVersion; let minVersion;
try { try {
@ -210,6 +200,11 @@ exports.default = File;
File.prototype.addTemplateObject = function addTemplateObject() { File.prototype.addTemplateObject = function addTemplateObject() {
throw new Error("This function has been moved into the template literal transform itself."); throw new Error("This function has been moved into the template literal transform itself.");
}; };
{
File.prototype.getModuleName = function getModuleName() {
return require("@babel/helper-module-transforms").getModuleName(this.opts, this.opts);
};
}
} }
0 && 0; 0 && 0;

View file

@ -1,6 +1,6 @@
{ {
"name": "@babel/core", "name": "@babel/core",
"version": "7.24.7", "version": "7.24.8",
"description": "Babel compiler core.", "description": "Babel compiler core.",
"main": "./lib/index.js", "main": "./lib/index.js",
"author": "The Babel Team (https://babel.dev/team)", "author": "The Babel Team (https://babel.dev/team)",
@ -48,14 +48,14 @@
"dependencies": { "dependencies": {
"@ampproject/remapping": "^2.2.0", "@ampproject/remapping": "^2.2.0",
"@babel/code-frame": "^7.24.7", "@babel/code-frame": "^7.24.7",
"@babel/generator": "^7.24.7", "@babel/generator": "^7.24.8",
"@babel/helper-compilation-targets": "^7.24.7", "@babel/helper-compilation-targets": "^7.24.8",
"@babel/helper-module-transforms": "^7.24.7", "@babel/helper-module-transforms": "^7.24.8",
"@babel/helpers": "^7.24.7", "@babel/helpers": "^7.24.8",
"@babel/parser": "^7.24.7", "@babel/parser": "^7.24.8",
"@babel/template": "^7.24.7", "@babel/template": "^7.24.7",
"@babel/traverse": "^7.24.7", "@babel/traverse": "^7.24.8",
"@babel/types": "^7.24.7", "@babel/types": "^7.24.8",
"convert-source-map": "^2.0.0", "convert-source-map": "^2.0.0",
"debug": "^4.1.0", "debug": "^4.1.0",
"gensync": "^1.0.0-beta.2", "gensync": "^1.0.0-beta.2",
@ -63,11 +63,11 @@
"semver": "^6.3.1" "semver": "^6.3.1"
}, },
"devDependencies": { "devDependencies": {
"@babel/helper-transform-fixture-test-runner": "^7.24.7", "@babel/helper-transform-fixture-test-runner": "^7.24.8",
"@babel/plugin-syntax-flow": "^7.24.7", "@babel/plugin-syntax-flow": "^7.24.7",
"@babel/plugin-transform-flow-strip-types": "^7.24.7", "@babel/plugin-transform-flow-strip-types": "^7.24.7",
"@babel/plugin-transform-modules-commonjs": "^7.24.7", "@babel/plugin-transform-modules-commonjs": "^7.24.8",
"@babel/preset-env": "^7.24.7", "@babel/preset-env": "^7.24.8",
"@babel/preset-typescript": "^7.24.7", "@babel/preset-typescript": "^7.24.7",
"@jridgewell/trace-mapping": "^0.3.25", "@jridgewell/trace-mapping": "^0.3.25",
"@types/convert-source-map": "^2.0.0", "@types/convert-source-map": "^2.0.0",

View file

@ -5,7 +5,6 @@ Object.defineProperty(exports, "__esModule", {
}); });
exports.meta = void 0; exports.meta = void 0;
exports.parseForESLint = parseForESLint; exports.parseForESLint = parseForESLint;
var _client = require("./client.cjs");
const [major, minor] = process.versions.node.split(".").map(Number); const [major, minor] = process.versions.node.split(".").map(Number);
if (major < 12 || major === 12 && minor < 3) { if (major < 12 || major === 12 && minor < 3) {
throw new Error("@babel/eslint-parser/experimental-worker requires Node.js >= 12.3.0"); throw new Error("@babel/eslint-parser/experimental-worker requires Node.js >= 12.3.0");
@ -13,10 +12,11 @@ if (major < 12 || major === 12 && minor < 3) {
const normalizeESLintConfig = require("./configuration.cjs"); const normalizeESLintConfig = require("./configuration.cjs");
const analyzeScope = require("./analyze-scope.cjs"); const analyzeScope = require("./analyze-scope.cjs");
const baseParse = require("./parse.cjs"); const baseParse = require("./parse.cjs");
const client = new _client.WorkerClient(); const Clients = require("./client.cjs");
const client = new Clients.WorkerClient();
const meta = exports.meta = { const meta = exports.meta = {
name: "@babel/eslint-parser/experimental-worker", name: "@babel/eslint-parser/experimental-worker",
version: "7.24.7" version: "7.24.8"
}; };
function parseForESLint(code, options = {}) { function parseForESLint(code, options = {}) {
const normalizedOptions = normalizeESLintConfig(options); const normalizedOptions = normalizeESLintConfig(options);

View file

@ -13,7 +13,7 @@ const baseParse = require("./parse.cjs");
const client = new _client.LocalClient(); const client = new _client.LocalClient();
const meta = exports.meta = { const meta = exports.meta = {
name: "@babel/eslint-parser", name: "@babel/eslint-parser",
version: "7.24.7" version: "7.24.8"
}; };
function parse(code, options = {}) { function parse(code, options = {}) {
return baseParse(code, normalizeESLintConfig(options), client); return baseParse(code, normalizeESLintConfig(options), client);

View file

@ -20,7 +20,7 @@ module.exports = function parse(code, options, client) {
isRunningMinSupportedCoreVersion = semver.satisfies(client.getVersion(), minSupportedCoreVersion); isRunningMinSupportedCoreVersion = semver.satisfies(client.getVersion(), minSupportedCoreVersion);
} }
if (!isRunningMinSupportedCoreVersion) { if (!isRunningMinSupportedCoreVersion) {
throw new Error(`@babel/eslint-parser@${"7.24.7"} does not support @babel/core@${client.getVersion()}. Please upgrade to @babel/core@${minSupportedCoreVersion}.`); throw new Error(`@babel/eslint-parser@${"7.24.8"} does not support @babel/core@${client.getVersion()}. Please upgrade to @babel/core@${minSupportedCoreVersion}.`);
} }
const { const {
ast, ast,

View file

@ -1,28 +1,29 @@
"use strict"; "use strict";
var _astInfo = require("./ast-info.cjs");
var _configuration = require("./configuration.cjs");
var _client = require("../client.cjs");
const babel = require("./babel-core.cjs"); const babel = require("./babel-core.cjs");
const maybeParse = require("./maybeParse.cjs"); const maybeParse = require("./maybeParse.cjs");
const astInfo = require("./ast-info.cjs");
const config = require("./configuration.cjs");
const Clients = require("../client.cjs");
var ACTIONS = Clients.ACTIONS;
module.exports = function handleMessage(action, payload) { module.exports = function handleMessage(action, payload) {
switch (action) { switch (action) {
case _client.ACTIONS.GET_VERSION: case ACTIONS.GET_VERSION:
return babel.version; return babel.version;
case _client.ACTIONS.GET_TYPES_INFO: case ACTIONS.GET_TYPES_INFO:
return { return {
FLOW_FLIPPED_ALIAS_KEYS: babel.types.FLIPPED_ALIAS_KEYS.Flow, FLOW_FLIPPED_ALIAS_KEYS: babel.types.FLIPPED_ALIAS_KEYS.Flow,
VISITOR_KEYS: babel.types.VISITOR_KEYS VISITOR_KEYS: babel.types.VISITOR_KEYS
}; };
case _client.ACTIONS.GET_TOKEN_LABELS: case ACTIONS.GET_TOKEN_LABELS:
return (0, _astInfo.getTokLabels)(); return astInfo.getTokLabels();
case _client.ACTIONS.GET_VISITOR_KEYS: case ACTIONS.GET_VISITOR_KEYS:
return (0, _astInfo.getVisitorKeys)(); return astInfo.getVisitorKeys();
case _client.ACTIONS.MAYBE_PARSE: case ACTIONS.MAYBE_PARSE:
return (0, _configuration.normalizeBabelParseConfig)(payload.options).then(options => maybeParse(payload.code, options)); return config.normalizeBabelParseConfig(payload.options).then(options => maybeParse(payload.code, options));
case _client.ACTIONS.MAYBE_PARSE_SYNC: case ACTIONS.MAYBE_PARSE_SYNC:
{ {
return maybeParse(payload.code, (0, _configuration.normalizeBabelParseConfigSync)(payload.options)); return maybeParse(payload.code, config.normalizeBabelParseConfigSync(payload.options));
} }
} }
throw new Error(`Unknown internal parser worker action: ${action}`); throw new Error(`Unknown internal parser worker action: ${action}`);

View file

@ -1,6 +1,6 @@
{ {
"name": "@babel/eslint-parser", "name": "@babel/eslint-parser",
"version": "7.24.7", "version": "7.24.8",
"description": "ESLint parser that allows for linting of experimental syntax transformed by Babel", "description": "ESLint parser that allows for linting of experimental syntax transformed by Babel",
"author": "The Babel Team (https://babel.dev/team)", "author": "The Babel Team (https://babel.dev/team)",
"license": "MIT", "license": "MIT",
@ -36,7 +36,7 @@
"semver": "^6.3.1" "semver": "^6.3.1"
}, },
"devDependencies": { "devDependencies": {
"@babel/core": "^7.24.7", "@babel/core": "^7.24.8",
"@types/eslint": "^8.56.2", "@types/eslint": "^8.56.2",
"@types/estree": "^1.0.5", "@types/estree": "^1.0.5",
"@typescript-eslint/scope-manager": "^6.19.0", "@typescript-eslint/scope-manager": "^6.19.0",

File diff suppressed because one or more lines are too long

View file

@ -278,12 +278,6 @@ class Buffer {
if (!this._map) return; if (!this._map) return;
this._normalizePosition(prop, loc, columnOffset); this._normalizePosition(prop, loc, columnOffset);
} }
withSource(prop, loc, cb) {
if (this._map) {
this.source(prop, loc);
}
cb();
}
_normalizePosition(prop, loc, columnOffset) { _normalizePosition(prop, loc, columnOffset) {
const pos = loc[prop]; const pos = loc[prop];
const target = this._sourcePosition; const target = this._sourcePosition;

View file

@ -48,9 +48,11 @@ function BlockStatement(node) {
this.newline(newline); this.newline(newline);
} }
} }
const exit = this.enterForStatementInit(false);
this.printSequence(node.body, node, { this.printSequence(node.body, node, {
indent: true indent: true
}); });
exit();
this.rightBrace(node); this.rightBrace(node);
} }
function Directive(node) { function Directive(node) {

View file

@ -58,9 +58,11 @@ function ClassBody(node) {
this.tokenChar(125); this.tokenChar(125);
} else { } else {
this.newline(); this.newline();
const exit = this.enterForStatementInit(false);
this.printSequence(node.body, node, { this.printSequence(node.body, node, {
indent: true indent: true
}); });
exit();
if (!this.endsWith(10)) this.newline(); if (!this.endsWith(10)) this.newline();
this.rightBrace(node); this.rightBrace(node);
} }

View file

@ -31,7 +31,6 @@ exports.V8IntrinsicIdentifier = V8IntrinsicIdentifier;
exports.YieldExpression = YieldExpression; exports.YieldExpression = YieldExpression;
exports._shouldPrintDecoratorsBeforeExport = _shouldPrintDecoratorsBeforeExport; exports._shouldPrintDecoratorsBeforeExport = _shouldPrintDecoratorsBeforeExport;
var _t = require("@babel/types"); var _t = require("@babel/types");
var n = require("../node/index.js");
const { const {
isCallExpression, isCallExpression,
isLiteral, isLiteral,
@ -99,7 +98,9 @@ function NewExpression(node, parent) {
this.token("?."); this.token("?.");
} }
this.tokenChar(40); this.tokenChar(40);
const exit = this.enterForStatementInit(false);
this.printList(node.arguments, node); this.printList(node.arguments, node);
exit();
this.rightParens(node); this.rightParens(node);
} }
function SequenceExpression(node) { function SequenceExpression(node) {
@ -111,22 +112,6 @@ function ThisExpression() {
function Super() { function Super() {
this.word("super"); this.word("super");
} }
function isDecoratorMemberExpression(node) {
switch (node.type) {
case "Identifier":
return true;
case "MemberExpression":
return !node.computed && node.property.type === "Identifier" && isDecoratorMemberExpression(node.object);
default:
return false;
}
}
function shouldParenthesizeDecoratorExpression(node) {
if (node.type === "ParenthesizedExpression") {
return false;
}
return !isDecoratorMemberExpression(node.type === "CallExpression" ? node.callee : node);
}
function _shouldPrintDecoratorsBeforeExport(node) { function _shouldPrintDecoratorsBeforeExport(node) {
if (typeof this.format.decoratorsBeforeExport === "boolean") { if (typeof this.format.decoratorsBeforeExport === "boolean") {
return this.format.decoratorsBeforeExport; return this.format.decoratorsBeforeExport;
@ -135,16 +120,7 @@ function _shouldPrintDecoratorsBeforeExport(node) {
} }
function Decorator(node) { function Decorator(node) {
this.tokenChar(64); this.tokenChar(64);
const { this.print(node.expression, node);
expression
} = node;
if (shouldParenthesizeDecoratorExpression(expression)) {
this.tokenChar(40);
this.print(expression, node);
this.tokenChar(41);
} else {
this.print(expression, node);
}
this.newline(); this.newline();
} }
function OptionalMemberExpression(node) { function OptionalMemberExpression(node) {
@ -184,7 +160,9 @@ function OptionalCallExpression(node) {
} }
this.print(node.typeArguments, node); this.print(node.typeArguments, node);
this.tokenChar(40); this.tokenChar(40);
const exit = this.enterForStatementInit(false);
this.printList(node.arguments, node); this.printList(node.arguments, node);
exit();
this.rightParens(node); this.rightParens(node);
} }
function CallExpression(node) { function CallExpression(node) {
@ -192,7 +170,9 @@ function CallExpression(node) {
this.print(node.typeArguments, node); this.print(node.typeArguments, node);
this.print(node.typeParameters, node); this.print(node.typeParameters, node);
this.tokenChar(40); this.tokenChar(40);
const exit = this.enterForStatementInit(false);
this.printList(node.arguments, node); this.printList(node.arguments, node);
exit();
this.rightParens(node); this.rightParens(node);
} }
function Import() { function Import() {
@ -236,11 +216,7 @@ function AssignmentPattern(node) {
this.space(); this.space();
this.print(node.right, node); this.print(node.right, node);
} }
function AssignmentExpression(node, parent) { function AssignmentExpression(node) {
const parens = this.inForStatementInitCounter && node.operator === "in" && !n.needsParens(node, parent);
if (parens) {
this.tokenChar(40);
}
this.print(node.left, node); this.print(node.left, node);
this.space(); this.space();
if (node.operator === "in" || node.operator === "instanceof") { if (node.operator === "in" || node.operator === "instanceof") {
@ -250,9 +226,6 @@ function AssignmentExpression(node, parent) {
} }
this.space(); this.space();
this.print(node.right, node); this.print(node.right, node);
if (parens) {
this.tokenChar(41);
}
} }
function BindExpression(node) { function BindExpression(node) {
this.print(node.object, node); this.print(node.object, node);
@ -269,9 +242,11 @@ function MemberExpression(node) {
computed = true; computed = true;
} }
if (computed) { if (computed) {
const exit = this.enterForStatementInit(false);
this.tokenChar(91); this.tokenChar(91);
this.print(node.property, node); this.print(node.property, node);
this.tokenChar(93); this.tokenChar(93);
exit();
} else { } else {
this.tokenChar(46); this.tokenChar(46);
this.print(node.property, node); this.print(node.property, node);

View file

@ -29,6 +29,7 @@ function _params(node, idNode, parentNode) {
this._noLineTerminator = noLineTerminator; this._noLineTerminator = noLineTerminator;
} }
function _parameters(parameters, parent) { function _parameters(parameters, parent) {
const exit = this.enterForStatementInit(false);
const paramLength = parameters.length; const paramLength = parameters.length;
for (let i = 0; i < paramLength; i++) { for (let i = 0; i < paramLength; i++) {
this._param(parameters[i], parent); this._param(parameters[i], parent);
@ -37,6 +38,7 @@ function _parameters(parameters, parent) {
this.space(); this.space();
} }
} }
exit();
} }
function _param(parameter, parent) { function _param(parameter, parent) {
this.printJoin(parameter.decorators, parameter); this.printJoin(parameter.decorators, parameter);

View file

@ -75,9 +75,11 @@ function ForStatement(node) {
this.word("for"); this.word("for");
this.space(); this.space();
this.tokenChar(40); this.tokenChar(40);
this.inForStatementInitCounter++; {
const exit = this.enterForStatementInit(true);
this.print(node.init, node); this.print(node.init, node);
this.inForStatementInitCounter--; exit();
}
this.tokenChar(59); this.tokenChar(59);
if (node.test) { if (node.test) {
this.space(); this.space();
@ -109,7 +111,11 @@ function ForXStatement(node) {
} }
this.noIndentInnerCommentsHere(); this.noIndentInnerCommentsHere();
this.tokenChar(40); this.tokenChar(40);
{
const exit = isForOf ? null : this.enterForStatementInit(true);
this.print(node.left, node); this.print(node.left, node);
exit == null || exit();
}
this.space(); this.space();
this.word(isForOf ? "of" : "in"); this.word(isForOf ? "of" : "in");
this.space(); this.space();
@ -234,7 +240,13 @@ function VariableDeclaration(node, parent) {
const { const {
kind kind
} = node; } = node;
this.word(kind, kind === "using" || kind === "await using"); if (kind === "await using") {
this.word("await");
this.space();
this.word("using", true);
} else {
this.word(kind, kind === "using");
}
this.space(); this.space();
let hasInits = false; let hasInits = false;
if (!isFor(parent)) { if (!isFor(parent)) {

View file

@ -45,12 +45,14 @@ function ObjectExpression(node) {
const props = node.properties; const props = node.properties;
this.tokenChar(123); this.tokenChar(123);
if (props.length) { if (props.length) {
const exit = this.enterForStatementInit(false);
this.space(); this.space();
this.printList(props, node, { this.printList(props, node, {
indent: true, indent: true,
statement: true statement: true
}); });
this.space(); this.space();
exit();
} }
this.sourceWithOffset("end", node.loc, -1); this.sourceWithOffset("end", node.loc, -1);
this.tokenChar(125); this.tokenChar(125);
@ -85,6 +87,7 @@ function ArrayExpression(node) {
const elems = node.elements; const elems = node.elements;
const len = elems.length; const len = elems.length;
this.tokenChar(91); this.tokenChar(91);
const exit = this.enterForStatementInit(false);
for (let i = 0; i < elems.length; i++) { for (let i = 0; i < elems.length; i++) {
const elem = elems[i]; const elem = elems[i];
if (elem) { if (elem) {
@ -95,6 +98,7 @@ function ArrayExpression(node) {
this.tokenChar(44); this.tokenChar(44);
} }
} }
exit();
this.tokenChar(93); this.tokenChar(93);
} }
function RecordExpression(node) { function RecordExpression(node) {

View file

@ -13,17 +13,19 @@ var _t = require("@babel/types");
const { const {
FLIPPED_ALIAS_KEYS, FLIPPED_ALIAS_KEYS,
isCallExpression, isCallExpression,
isDecorator,
isExpressionStatement, isExpressionStatement,
isMemberExpression, isMemberExpression,
isNewExpression isNewExpression,
isParenthesizedExpression
} = _t; } = _t;
function expandAliases(obj) { function expandAliases(obj) {
const map = new Map(); const map = new Map();
function add(type, func) { function add(type, func) {
const fn = map.get(type); const fn = map.get(type);
map.set(type, fn ? function (node, parent, stack) { map.set(type, fn ? function (node, parent, stack, inForInit) {
var _fn; var _fn;
return (_fn = fn(node, parent, stack)) != null ? _fn : func(node, parent, stack); return (_fn = fn(node, parent, stack, inForInit)) != null ? _fn : func(node, parent, stack, inForInit);
} : func); } : func);
} }
for (const type of Object.keys(obj)) { for (const type of Object.keys(obj)) {
@ -64,13 +66,26 @@ function needsWhitespaceBefore(node, parent) {
function needsWhitespaceAfter(node, parent) { function needsWhitespaceAfter(node, parent) {
return needsWhitespace(node, parent, 2); return needsWhitespace(node, parent, 2);
} }
function needsParens(node, parent, printStack) { function needsParens(node, parent, printStack, inForInit) {
var _expandedParens$get; var _expandedParens$get;
if (!parent) return false; if (!parent) return false;
if (isNewExpression(parent) && parent.callee === node) { if (isNewExpression(parent) && parent.callee === node) {
if (isOrHasCallExpression(node)) return true; if (isOrHasCallExpression(node)) return true;
} }
return (_expandedParens$get = expandedParens.get(node.type)) == null ? void 0 : _expandedParens$get(node, parent, printStack); if (isDecorator(parent)) {
return !isDecoratorMemberExpression(node) && !(isCallExpression(node) && isDecoratorMemberExpression(node.callee)) && !isParenthesizedExpression(node);
}
return (_expandedParens$get = expandedParens.get(node.type)) == null ? void 0 : _expandedParens$get(node, parent, printStack, inForInit);
}
function isDecoratorMemberExpression(node) {
switch (node.type) {
case "Identifier":
return true;
case "MemberExpression":
return !node.computed && node.property.type === "Identifier" && isDecoratorMemberExpression(node.object);
default:
return false;
}
} }
//# sourceMappingURL=index.js.map //# sourceMappingURL=index.js.map

View file

@ -112,12 +112,8 @@ function TSInstantiationExpression(node, parent) {
const parentType = parent.type; const parentType = parent.type;
return (parentType === "CallExpression" || parentType === "OptionalCallExpression" || parentType === "NewExpression" || parentType === "TSInstantiationExpression") && !!parent.typeParameters; return (parentType === "CallExpression" || parentType === "OptionalCallExpression" || parentType === "NewExpression" || parentType === "TSInstantiationExpression") && !!parent.typeParameters;
} }
function BinaryExpression(node, parent) { function BinaryExpression(node, parent, stack, inForStatementInit) {
if (node.operator === "in") { return node.operator === "in" && inForStatementInit;
const parentType = parent.type;
return parentType === "VariableDeclarator" || parentType === "ForStatement" || parentType === "ForInStatement" || parentType === "ForOfStatement";
}
return false;
} }
function SequenceExpression(node, parent) { function SequenceExpression(node, parent) {
const parentType = parent.type; const parentType = parent.type;
@ -128,7 +124,7 @@ function SequenceExpression(node, parent) {
} }
function YieldExpression(node, parent) { function YieldExpression(node, parent) {
const parentType = parent.type; const parentType = parent.type;
return parentType === "BinaryExpression" || parentType === "LogicalExpression" || parentType === "UnaryExpression" || parentType === "SpreadElement" || hasPostfixPart(node, parent) || parentType === "AwaitExpression" && isYieldExpression(node) || parentType === "ConditionalExpression" && node === parent.test || isClassExtendsClause(node, parent); return parentType === "BinaryExpression" || parentType === "LogicalExpression" || parentType === "UnaryExpression" || parentType === "SpreadElement" || hasPostfixPart(node, parent) || parentType === "AwaitExpression" && isYieldExpression(node) || parentType === "ConditionalExpression" && node === parent.test || isClassExtendsClause(node, parent) || isTSTypeExpression(parentType);
} }
function ClassExpression(node, parent, printStack) { function ClassExpression(node, parent, printStack) {
return isFirstInContext(printStack, 1 | 4); return isFirstInContext(printStack, 1 | 4);
@ -192,7 +188,10 @@ function Identifier(node, parent, printStack) {
}); });
return isFirstInContext(printStack, isFollowedByBracket ? 1 | 8 | 16 | 32 : 32); return isFirstInContext(printStack, isFollowedByBracket ? 1 | 8 | 16 | 32 : 32);
} }
return node.name === "async" && isForOfStatement(parent) && node === parent.left; return node.name === "async" && isForOfStatement(parent, {
left: node,
await: false
});
} }
function isFirstInContext(printStack, checkParam) { function isFirstInContext(printStack, checkParam) {
const expressionStatement = checkParam & 1; const expressionStatement = checkParam & 1;

View file

@ -24,7 +24,7 @@ const {
} = n; } = n;
class Printer { class Printer {
constructor(format, map) { constructor(format, map) {
this.inForStatementInitCounter = 0; this.inForStatementInit = false;
this._printStack = []; this._printStack = [];
this._indent = 0; this._indent = 0;
this._indentRepeat = 0; this._indentRepeat = 0;
@ -43,6 +43,14 @@ class Printer {
this._inputMap = map == null ? void 0 : map._inputMap; this._inputMap = map == null ? void 0 : map._inputMap;
this._buf = new _buffer.default(map, format.indent.style[0]); this._buf = new _buffer.default(map, format.indent.style[0]);
} }
enterForStatementInit(val) {
const old = this.inForStatementInit;
if (old === val) return () => {};
this.inForStatementInit = val;
return () => {
this.inForStatementInit = old;
};
}
generate(ast) { generate(ast) {
this.print(ast); this.print(ast);
this._maybeAddAuxComment(); this._maybeAddAuxComment();
@ -175,14 +183,6 @@ class Printer {
this._catchUp(prop, loc); this._catchUp(prop, loc);
this._buf.sourceWithOffset(prop, loc, columnOffset); this._buf.sourceWithOffset(prop, loc, columnOffset);
} }
withSource(prop, loc, cb) {
if (!loc) {
cb();
return;
}
this._catchUp(prop, loc);
this._buf.withSource(prop, loc, cb);
}
sourceIdentifierName(identifierName, pos) { sourceIdentifierName(identifierName, pos) {
if (!this._buf._canMarkIdName) return; if (!this._buf._canMarkIdName) return;
const sourcePosition = this._buf._sourcePosition; const sourcePosition = this._buf._sourcePosition;
@ -324,7 +324,7 @@ class Printer {
this._insideAux = node.loc == null; this._insideAux = node.loc == null;
this._maybeAddAuxComment(this._insideAux && !oldInAux); this._maybeAddAuxComment(this._insideAux && !oldInAux);
const parenthesized = (_node$extra = node.extra) == null ? void 0 : _node$extra.parenthesized; const parenthesized = (_node$extra = node.extra) == null ? void 0 : _node$extra.parenthesized;
let shouldPrintParens = forceParens || parenthesized && format.retainFunctionParens && nodeType === "FunctionExpression" || needsParens(node, parent, this._printStack); let shouldPrintParens = forceParens || parenthesized && format.retainFunctionParens && nodeType === "FunctionExpression" || needsParens(node, parent, this._printStack, this.inForStatementInit);
if (!shouldPrintParens && parenthesized && (_node$leadingComments = node.leadingComments) != null && _node$leadingComments.length && node.leadingComments[0].type === "CommentBlock") { if (!shouldPrintParens && parenthesized && (_node$leadingComments = node.leadingComments) != null && _node$leadingComments.length && node.leadingComments[0].type === "CommentBlock") {
const parentType = parent == null ? void 0 : parent.type; const parentType = parent == null ? void 0 : parent.type;
switch (parentType) { switch (parentType) {
@ -341,9 +341,11 @@ class Printer {
shouldPrintParens = true; shouldPrintParens = true;
} }
} }
let exitInForStatementInit;
if (shouldPrintParens) { if (shouldPrintParens) {
this.tokenChar(40); this.tokenChar(40);
this._endsWithInnerRaw = false; this._endsWithInnerRaw = false;
exitInForStatementInit = this.enterForStatementInit(false);
} }
this._lastCommentLine = 0; this._lastCommentLine = 0;
this._printLeadingComments(node, parent); this._printLeadingComments(node, parent);
@ -353,6 +355,7 @@ class Printer {
this._printTrailingComments(node, parent); this._printTrailingComments(node, parent);
this.tokenChar(41); this.tokenChar(41);
this._noLineTerminator = noLineTerminatorAfter; this._noLineTerminator = noLineTerminatorAfter;
exitInForStatementInit();
} else if (noLineTerminatorAfter && !this._noLineTerminator) { } else if (noLineTerminatorAfter && !this._noLineTerminator) {
this._noLineTerminator = true; this._noLineTerminator = true;
this._printTrailingComments(node, parent); this._printTrailingComments(node, parent);

View file

@ -1,6 +1,6 @@
{ {
"name": "@babel/generator", "name": "@babel/generator",
"version": "7.24.7", "version": "7.24.8",
"description": "Turns an AST into code.", "description": "Turns an AST into code.",
"author": "The Babel Team (https://babel.dev/team)", "author": "The Babel Team (https://babel.dev/team)",
"license": "MIT", "license": "MIT",
@ -19,14 +19,14 @@
"lib" "lib"
], ],
"dependencies": { "dependencies": {
"@babel/types": "^7.24.7", "@babel/types": "^7.24.8",
"@jridgewell/gen-mapping": "^0.3.5", "@jridgewell/gen-mapping": "^0.3.5",
"@jridgewell/trace-mapping": "^0.3.25", "@jridgewell/trace-mapping": "^0.3.25",
"jsesc": "^2.5.1" "jsesc": "^2.5.1"
}, },
"devDependencies": { "devDependencies": {
"@babel/helper-fixtures": "^7.24.7", "@babel/helper-fixtures": "^7.24.8",
"@babel/parser": "^7.24.7", "@babel/parser": "^7.24.8",
"@jridgewell/sourcemap-codec": "^1.4.15", "@jridgewell/sourcemap-codec": "^1.4.15",
"@types/jsesc": "^2.5.0", "@types/jsesc": "^2.5.0",
"charcodes": "^0.2.0" "charcodes": "^0.2.0"

View file

@ -94,7 +94,7 @@ function getLowestVersions(browsers) {
const parsedBrowserVersion = (0, _utils.semverify)(splitVersion); const parsedBrowserVersion = (0, _utils.semverify)(splitVersion);
all[target] = (0, _utils.semverMin)(version, parsedBrowserVersion); all[target] = (0, _utils.semverMin)(version, parsedBrowserVersion);
} }
} catch (e) {} } catch (_) {}
return all; return all;
}, {}); }, {});
} }
@ -115,7 +115,7 @@ getting parsed as 6.1, which can lead to unexpected behavior.
function semverifyTarget(target, value) { function semverifyTarget(target, value) {
try { try {
return (0, _utils.semverify)(value); return (0, _utils.semverify)(value);
} catch (error) { } catch (_) {
throw new Error(v.formatMessage(`'${value}' is not a valid value for 'targets.${target}'.`)); throw new Error(v.formatMessage(`'${value}' is not a valid value for 'targets.${target}'.`));
} }
} }

View file

@ -1,6 +1,6 @@
{ {
"name": "@babel/helper-compilation-targets", "name": "@babel/helper-compilation-targets",
"version": "7.24.7", "version": "7.24.8",
"author": "The Babel Team (https://babel.dev/team)", "author": "The Babel Team (https://babel.dev/team)",
"license": "MIT", "license": "MIT",
"description": "Helper functions on Babel compilation targets", "description": "Helper functions on Babel compilation targets",
@ -25,9 +25,9 @@
"babel-plugin" "babel-plugin"
], ],
"dependencies": { "dependencies": {
"@babel/compat-data": "^7.24.7", "@babel/compat-data": "^7.24.8",
"@babel/helper-validator-option": "^7.24.7", "@babel/helper-validator-option": "^7.24.8",
"browserslist": "^4.22.2", "browserslist": "^4.23.1",
"lru-cache": "^5.1.1", "lru-cache": "^5.1.1",
"semver": "^6.3.1" "semver": "^6.3.1"
}, },

View file

@ -12,10 +12,10 @@ function toGetWrapperPayload(lazy) {
if (lazy === false) return null; if (lazy === false) return null;
if ((0, _normalizeAndLoadMetadata.isSideEffectImport)(metadata) || metadata.reexportAll) return null; if ((0, _normalizeAndLoadMetadata.isSideEffectImport)(metadata) || metadata.reexportAll) return null;
if (lazy === true) { if (lazy === true) {
return /\./.test(source) ? null : "lazy"; return source.includes(".") ? null : "lazy";
} }
if (Array.isArray(lazy)) { if (Array.isArray(lazy)) {
return lazy.indexOf(source) === -1 ? null : "lazy"; return !lazy.includes(source) ? null : "lazy";
} }
if (typeof lazy === "function") { if (typeof lazy === "function") {
return lazy(source) ? "lazy" : null; return lazy(source) ? "lazy" : null;

View file

@ -1,6 +1,6 @@
{ {
"name": "@babel/helper-module-transforms", "name": "@babel/helper-module-transforms",
"version": "7.24.7", "version": "7.24.8",
"description": "Babel helper functions for implementing ES6 module transformations", "description": "Babel helper functions for implementing ES6 module transformations",
"author": "The Babel Team (https://babel.dev/team)", "author": "The Babel Team (https://babel.dev/team)",
"homepage": "https://babel.dev/docs/en/next/babel-helper-module-transforms", "homepage": "https://babel.dev/docs/en/next/babel-helper-module-transforms",
@ -22,7 +22,7 @@
"@babel/helper-validator-identifier": "^7.24.7" "@babel/helper-validator-identifier": "^7.24.7"
}, },
"devDependencies": { "devDependencies": {
"@babel/core": "^7.24.7" "@babel/core": "^7.24.8"
}, },
"peerDependencies": { "peerDependencies": {
"@babel/core": "^7.0.0" "@babel/core": "^7.0.0"

View file

@ -1,6 +1,6 @@
{ {
"name": "@babel/helper-plugin-utils", "name": "@babel/helper-plugin-utils",
"version": "7.24.7", "version": "7.24.8",
"description": "General utilities for plugins to use", "description": "General utilities for plugins to use",
"author": "The Babel Team (https://babel.dev/team)", "author": "The Babel Team (https://babel.dev/team)",
"homepage": "https://babel.dev/docs/en/next/babel-helper-plugin-utils", "homepage": "https://babel.dev/docs/en/next/babel-helper-plugin-utils",
@ -18,7 +18,7 @@
"node": ">=6.9.0" "node": ">=6.9.0"
}, },
"devDependencies": { "devDependencies": {
"@babel/core": "^7.24.7" "@babel/core": "^7.24.8"
}, },
"type": "commonjs" "type": "commonjs"
} }

File diff suppressed because one or more lines are too long

View file

@ -154,7 +154,7 @@ function readEscapedChar(input, pos, lineStart, curLine, inTemplate, errors) {
default: default:
if (ch >= 48 && ch <= 55) { if (ch >= 48 && ch <= 55) {
const startPos = pos - 1; const startPos = pos - 1;
const match = input.slice(startPos, pos + 2).match(/^[0-7]+/); const match = /^[0-7]+/.exec(input.slice(startPos, pos + 2));
let octalStr = match[0]; let octalStr = match[0];
let octal = parseInt(octalStr, 8); let octal = parseInt(octalStr, 8);
if (octal > 255) { if (octal > 255) {

View file

@ -1,6 +1,6 @@
{ {
"name": "@babel/helper-string-parser", "name": "@babel/helper-string-parser",
"version": "7.24.7", "version": "7.24.8",
"description": "A utility package to parse strings", "description": "A utility package to parse strings",
"repository": { "repository": {
"type": "git", "type": "git",

View file

@ -1,6 +1,6 @@
{ {
"name": "@babel/helper-validator-option", "name": "@babel/helper-validator-option",
"version": "7.24.7", "version": "7.24.8",
"description": "Validate plugin/preset options", "description": "Validate plugin/preset options",
"repository": { "repository": {
"type": "git", "type": "git",

View file

@ -25,7 +25,7 @@ const helpers = exports.default = {
exportName: "_OverloadYield", exportName: "_OverloadYield",
dependencies: {} dependencies: {}
}), }),
applyDecoratedDescriptor: helper("7.0.0-beta.0", 'function _applyDecoratedDescriptor(i,e,r,n,l){var a={};return Object.keys(n).forEach((function(i){a[i]=n[i]})),a.enumerable=!!a.enumerable,a.configurable=!!a.configurable,("value"in a||a.initializer)&&(a.writable=!0),a=r.slice().reverse().reduce((function(r,n){return n(i,e,r)||r}),a),l&&void 0!==a.initializer&&(a.value=a.initializer?a.initializer.call(l):void 0,a.initializer=void 0),void 0===a.initializer&&(Object.defineProperty(i,e,a),a=null),a}', { applyDecoratedDescriptor: helper("7.0.0-beta.0", 'function _applyDecoratedDescriptor(i,e,r,n,l){var a={};return Object.keys(n).forEach((function(i){a[i]=n[i]})),a.enumerable=!!a.enumerable,a.configurable=!!a.configurable,("value"in a||a.initializer)&&(a.writable=!0),a=r.slice().reverse().reduce((function(r,n){return n(i,e,r)||r}),a),l&&void 0!==a.initializer&&(a.value=a.initializer?a.initializer.call(l):void 0,a.initializer=void 0),void 0===a.initializer?(Object.defineProperty(i,e,a),null):a}', {
globals: ["Object"], globals: ["Object"],
locals: { locals: {
_applyDecoratedDescriptor: ["body.0.id"] _applyDecoratedDescriptor: ["body.0.id"]
@ -617,7 +617,7 @@ const helpers = exports.default = {
defineProperty: ["body.1.body.body.0.body.body.1.expression.consequent.arguments.0.body.body.0.expression.callee"] defineProperty: ["body.1.body.body.0.body.body.1.expression.consequent.arguments.0.body.body.0.expression.callee"]
} }
}), }),
objectWithoutProperties: helper("7.0.0-beta.0", "function _objectWithoutProperties(e,t){if(null==e)return{};var o,r,i=objectWithoutPropertiesLoose(e,t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);for(r=0;r<n.length;r++)o=n[r],t.indexOf(o)>=0||{}.propertyIsEnumerable.call(e,o)&&(i[o]=e[o])}return i}", { objectWithoutProperties: helper("7.0.0-beta.0", "function _objectWithoutProperties(e,t){if(null==e)return{};var o,r,i=objectWithoutPropertiesLoose(e,t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);for(r=0;r<s.length;r++)o=s[r],t.includes(o)||{}.propertyIsEnumerable.call(e,o)&&(i[o]=e[o])}return i}", {
globals: ["Object"], globals: ["Object"],
locals: { locals: {
_objectWithoutProperties: ["body.0.id"] _objectWithoutProperties: ["body.0.id"]
@ -628,7 +628,7 @@ const helpers = exports.default = {
objectWithoutPropertiesLoose: ["body.0.body.body.1.declarations.2.init.callee"] objectWithoutPropertiesLoose: ["body.0.body.body.1.declarations.2.init.callee"]
} }
}), }),
objectWithoutPropertiesLoose: helper("7.0.0-beta.0", "function _objectWithoutPropertiesLoose(r,e){if(null==r)return{};var t={};for(var n in r)if({}.hasOwnProperty.call(r,n)){if(e.indexOf(n)>=0)continue;t[n]=r[n]}return t}", { objectWithoutPropertiesLoose: helper("7.0.0-beta.0", "function _objectWithoutPropertiesLoose(r,e){if(null==r)return{};var t={};for(var n in r)if({}.hasOwnProperty.call(r,n)){if(e.includes(n))continue;t[n]=r[n]}return t}", {
globals: [], globals: [],
locals: { locals: {
_objectWithoutPropertiesLoose: ["body.0.id"] _objectWithoutPropertiesLoose: ["body.0.id"]

View file

@ -19,11 +19,11 @@ function _applyDecoratedDescriptor(target, property, decorators, descriptor, con
}, desc); }, desc);
if (context && desc.initializer !== void 0) { if (context && desc.initializer !== void 0) {
desc.value = desc.initializer ? desc.initializer.call(context) : void 0; desc.value = desc.initializer ? desc.initializer.call(context) : void 0;
desc.initializer = undefined; desc.initializer = void 0;
} }
if (desc.initializer === void 0) { if (desc.initializer === void 0) {
Object.defineProperty(target, property, desc); Object.defineProperty(target, property, desc);
desc = null; return null;
} }
return desc; return desc;
} }

View file

@ -48,7 +48,9 @@ function AsyncFromSyncIterator(s) {
}, },
throw: function (maybeError) { throw: function (maybeError) {
var thr = this.s.return; var thr = this.s.return;
if (thr === undefined) return Promise.reject(maybeError); if (thr === undefined) {
return Promise.reject(maybeError);
}
return AsyncFromSyncIteratorContinuation(thr.apply(this.s, arguments)); return AsyncFromSyncIteratorContinuation(thr.apply(this.s, arguments));
} }
}; };

View file

@ -4,12 +4,12 @@ Object.defineProperty(exports, "__esModule", {
value: true value: true
}); });
exports.default = _callSuper; exports.default = _callSuper;
var _getPrototypeOf = require("getPrototypeOf"); var _getPrototypeOf = require("./getPrototypeOf.js");
var _isNativeReflectConstruct = require("./isNativeReflectConstruct.js"); var _isNativeReflectConstruct = require("./isNativeReflectConstruct.js");
var _possibleConstructorReturn = require("possibleConstructorReturn"); var _possibleConstructorReturn = require("./possibleConstructorReturn.js");
function _callSuper(_this, derived, args) { function _callSuper(_this, derived, args) {
derived = _getPrototypeOf(derived); derived = (0, _getPrototypeOf.default)(derived);
return _possibleConstructorReturn(_this, (0, _isNativeReflectConstruct.default)() ? Reflect.construct(derived, args || [], _getPrototypeOf(_this).constructor) : derived.apply(_this, args)); return (0, _possibleConstructorReturn.default)(_this, (0, _isNativeReflectConstruct.default)() ? Reflect.construct(derived, args || [], (0, _getPrototypeOf.default)(_this).constructor) : derived.apply(_this, args));
} }
//# sourceMappingURL=callSuper.js.map //# sourceMappingURL=callSuper.js.map

View file

@ -4,20 +4,22 @@ Object.defineProperty(exports, "__esModule", {
value: true value: true
}); });
exports.default = _createForOfIteratorHelper; exports.default = _createForOfIteratorHelper;
var _unsupportedIterableToArray = require("unsupportedIterableToArray"); var _unsupportedIterableToArray = require("./unsupportedIterableToArray.js");
function _createForOfIteratorHelper(o, allowArrayLike) { function _createForOfIteratorHelper(o, allowArrayLike) {
var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"];
if (!it) { if (!it) {
if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (Array.isArray(o) || (it = (0, _unsupportedIterableToArray.default)(o)) || allowArrayLike && o && typeof o.length === "number") {
if (it) o = it; if (it) o = it;
var i = 0; var i = 0;
var F = function () {}; var F = function () {};
return { return {
s: F, s: F,
n: function () { n: function () {
if (i >= o.length) return { if (i >= o.length) {
return {
done: true done: true
}; };
}
return { return {
done: false, done: false,
value: o[i++] value: o[i++]
@ -49,7 +51,9 @@ function _createForOfIteratorHelper(o, allowArrayLike) {
}, },
f: function () { f: function () {
try { try {
if (!normalCompletion && it.return != null) it.return(); if (!normalCompletion && it.return != null) {
it.return();
}
} finally { } finally {
if (didErr) throw err; if (didErr) throw err;
} }

View file

@ -4,17 +4,19 @@ Object.defineProperty(exports, "__esModule", {
value: true value: true
}); });
exports.default = _createForOfIteratorHelperLoose; exports.default = _createForOfIteratorHelperLoose;
var _unsupportedIterableToArray = require("unsupportedIterableToArray"); var _unsupportedIterableToArray = require("./unsupportedIterableToArray.js");
function _createForOfIteratorHelperLoose(o, allowArrayLike) { function _createForOfIteratorHelperLoose(o, allowArrayLike) {
var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"];
if (it) return (it = it.call(o)).next.bind(it); if (it) return (it = it.call(o)).next.bind(it);
if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (Array.isArray(o) || (it = (0, _unsupportedIterableToArray.default)(o)) || allowArrayLike && o && typeof o.length === "number") {
if (it) o = it; if (it) o = it;
var i = 0; var i = 0;
return function () { return function () {
if (i >= o.length) return { if (i >= o.length) {
return {
done: true done: true
}; };
}
return { return {
done: false, done: false,
value: o[i++] value: o[i++]

View file

@ -4,7 +4,7 @@ Object.defineProperty(exports, "__esModule", {
value: true value: true
}); });
exports.default = _inherits; exports.default = _inherits;
var _setPrototypeOf = require("setPrototypeOf"); var _setPrototypeOf = require("./setPrototypeOf.js");
function _inherits(subClass, superClass) { function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) { if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function"); throw new TypeError("Super expression must either be null or a function");
@ -19,7 +19,7 @@ function _inherits(subClass, superClass) {
Object.defineProperty(subClass, "prototype", { Object.defineProperty(subClass, "prototype", {
writable: false writable: false
}); });
if (superClass) _setPrototypeOf(subClass, superClass); if (superClass) (0, _setPrototypeOf.default)(subClass, superClass);
} }
//# sourceMappingURL=inherits.js.map //# sourceMappingURL=inherits.js.map

View file

@ -4,11 +4,11 @@ Object.defineProperty(exports, "__esModule", {
value: true value: true
}); });
exports.default = _inheritsLoose; exports.default = _inheritsLoose;
var _setPrototypeOf = require("setPrototypeOf"); var _setPrototypeOf = require("./setPrototypeOf.js");
function _inheritsLoose(subClass, superClass) { function _inheritsLoose(subClass, superClass) {
subClass.prototype = Object.create(superClass.prototype); subClass.prototype = Object.create(superClass.prototype);
subClass.prototype.constructor = subClass; subClass.prototype.constructor = subClass;
_setPrototypeOf(subClass, superClass); (0, _setPrototypeOf.default)(subClass, superClass);
} }
//# sourceMappingURL=inheritsLoose.js.map //# sourceMappingURL=inheritsLoose.js.map

View file

@ -7,7 +7,7 @@ exports.default = _isNativeFunction;
function _isNativeFunction(fn) { function _isNativeFunction(fn) {
try { try {
return Function.toString.call(fn).indexOf("[native code]") !== -1; return Function.toString.call(fn).indexOf("[native code]") !== -1;
} catch (e) { } catch (_e) {
return typeof fn === "function"; return typeof fn === "function";
} }
} }

View file

@ -7,7 +7,7 @@ exports.default = _isNativeReflectConstruct;
function _isNativeReflectConstruct() { function _isNativeReflectConstruct() {
try { try {
var result = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); var result = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));
} catch (e) {} } catch (_) {}
return (exports.default = _isNativeReflectConstruct = function () { return (exports.default = _isNativeReflectConstruct = function () {
return !!result; return !!result;
})(); })();

View file

@ -13,7 +13,7 @@ function _objectWithoutProperties(source, excluded) {
var sourceSymbolKeys = Object.getOwnPropertySymbols(source); var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
for (i = 0; i < sourceSymbolKeys.length; i++) { for (i = 0; i < sourceSymbolKeys.length; i++) {
key = sourceSymbolKeys[i]; key = sourceSymbolKeys[i];
if (excluded.indexOf(key) >= 0) continue; if (excluded.includes(key)) continue;
if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
target[key] = source[key]; target[key] = source[key];
} }

View file

@ -9,7 +9,7 @@ function _objectWithoutPropertiesLoose(source, excluded) {
var target = {}; var target = {};
for (var key in source) { for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) { if (Object.prototype.hasOwnProperty.call(source, key)) {
if (excluded.indexOf(key) >= 0) continue; if (excluded.includes(key)) continue;
target[key] = source[key]; target[key] = source[key];
} }
} }

View file

@ -4,14 +4,14 @@ Object.defineProperty(exports, "__esModule", {
value: true value: true
}); });
exports.default = _wrapNativeSuper; exports.default = _wrapNativeSuper;
var _getPrototypeOf = require("getPrototypeOf"); var _getPrototypeOf = require("./getPrototypeOf.js");
var _setPrototypeOf = require("setPrototypeOf"); var _setPrototypeOf = require("./setPrototypeOf.js");
var _isNativeFunction = require("isNativeFunction"); var _isNativeFunction = require("./isNativeFunction.js");
var _construct = require("construct"); var _construct = require("./construct.js");
function _wrapNativeSuper(Class) { function _wrapNativeSuper(Class) {
var _cache = typeof Map === "function" ? new Map() : undefined; var _cache = typeof Map === "function" ? new Map() : undefined;
exports.default = _wrapNativeSuper = function _wrapNativeSuper(Class) { exports.default = _wrapNativeSuper = function _wrapNativeSuper(Class) {
if (Class === null || !_isNativeFunction(Class)) return Class; if (Class === null || !(0, _isNativeFunction.default)(Class)) return Class;
if (typeof Class !== "function") { if (typeof Class !== "function") {
throw new TypeError("Super expression must either be null or a function"); throw new TypeError("Super expression must either be null or a function");
} }
@ -20,7 +20,7 @@ function _wrapNativeSuper(Class) {
_cache.set(Class, Wrapper); _cache.set(Class, Wrapper);
} }
function Wrapper() { function Wrapper() {
return _construct(Class, arguments, _getPrototypeOf(this).constructor); return (0, _construct.default)(Class, arguments, (0, _getPrototypeOf.default)(this).constructor);
} }
Wrapper.prototype = Object.create(Class.prototype, { Wrapper.prototype = Object.create(Class.prototype, {
constructor: { constructor: {
@ -30,7 +30,7 @@ function _wrapNativeSuper(Class) {
configurable: true configurable: true
} }
}); });
return _setPrototypeOf(Wrapper, Class); return (0, _setPrototypeOf.default)(Wrapper, Class);
}; };
return _wrapNativeSuper(Class); return _wrapNativeSuper(Class);
} }

View file

@ -4,8 +4,8 @@ Object.defineProperty(exports, "__esModule", {
value: true value: true
}); });
exports.default = _wrapRegExp; exports.default = _wrapRegExp;
var _setPrototypeOf = require("setPrototypeOf"); var _setPrototypeOf = require("./setPrototypeOf.js");
var _inherits = require("inherits"); var _inherits = require("./inherits.js");
function _wrapRegExp() { function _wrapRegExp() {
exports.default = _wrapRegExp = function (re, groups) { exports.default = _wrapRegExp = function (re, groups) {
return new BabelRegExp(re, undefined, groups); return new BabelRegExp(re, undefined, groups);
@ -15,9 +15,9 @@ function _wrapRegExp() {
function BabelRegExp(re, flags, groups) { function BabelRegExp(re, flags, groups) {
var _this = new RegExp(re, flags); var _this = new RegExp(re, flags);
_groups.set(_this, groups || _groups.get(re)); _groups.set(_this, groups || _groups.get(re));
return _setPrototypeOf(_this, BabelRegExp.prototype); return (0, _setPrototypeOf.default)(_this, BabelRegExp.prototype);
} }
_inherits(BabelRegExp, RegExp); (0, _inherits.default)(BabelRegExp, RegExp);
BabelRegExp.prototype.exec = function (str) { BabelRegExp.prototype.exec = function (str) {
var result = _super.exec.call(this, str); var result = _super.exec.call(this, str);
if (result) { if (result) {
@ -54,7 +54,9 @@ function _wrapRegExp() {
var i = g[name]; var i = g[name];
if (typeof i === "number") groups[name] = result[i];else { if (typeof i === "number") groups[name] = result[i];else {
var k = 0; var k = 0;
while (result[i[k]] === undefined && k + 1 < i.length) k++; while (result[i[k]] === undefined && k + 1 < i.length) {
k++;
}
groups[name] = result[i[k]]; groups[name] = result[i[k]];
} }
return groups; return groups;

View file

@ -1,6 +1,6 @@
{ {
"name": "@babel/helpers", "name": "@babel/helpers",
"version": "7.24.7", "version": "7.24.8",
"description": "Collection of helper functions used by Babel transforms.", "description": "Collection of helper functions used by Babel transforms.",
"author": "The Babel Team (https://babel.dev/team)", "author": "The Babel Team (https://babel.dev/team)",
"homepage": "https://babel.dev/docs/en/next/babel-helpers", "homepage": "https://babel.dev/docs/en/next/babel-helpers",
@ -16,12 +16,12 @@
"main": "./lib/index.js", "main": "./lib/index.js",
"dependencies": { "dependencies": {
"@babel/template": "^7.24.7", "@babel/template": "^7.24.7",
"@babel/types": "^7.24.7" "@babel/types": "^7.24.8"
}, },
"devDependencies": { "devDependencies": {
"@babel/generator": "^7.24.7", "@babel/generator": "^7.24.8",
"@babel/helper-plugin-test-runner": "^7.24.7", "@babel/helper-plugin-test-runner": "^7.24.7",
"@babel/parser": "^7.24.7", "@babel/parser": "^7.24.8",
"regenerator-runtime": "^0.14.0" "regenerator-runtime": "^0.14.0"
}, },
"engines": { "engines": {

View file

@ -1,5 +1,3 @@
/* eslint-disable import/no-extraneous-dependencies */
import fs from "fs"; import fs from "fs";
import { createRequire } from "module"; import { createRequire } from "module";

View file

@ -416,13 +416,17 @@ const Errors = Object.assign({}, ParseErrorEnum(ModuleErrors), ParseErrorEnum(St
const { const {
defineProperty defineProperty
} = Object; } = Object;
const toUnenumerable = (object, key) => defineProperty(object, key, { const toUnenumerable = (object, key) => {
if (object) {
defineProperty(object, key, {
enumerable: false, enumerable: false,
value: object[key] value: object[key]
}); });
}
};
function toESTreeLocation(node) { function toESTreeLocation(node) {
node.loc.start && toUnenumerable(node.loc.start, "index"); toUnenumerable(node.loc.start, "index");
node.loc.end && toUnenumerable(node.loc.end, "index"); toUnenumerable(node.loc.end, "index");
return node; return node;
} }
var estree = superClass => class ESTreeParserMixin extends superClass { var estree = superClass => class ESTreeParserMixin extends superClass {
@ -440,7 +444,7 @@ var estree = superClass => class ESTreeParserMixin extends superClass {
let regex = null; let regex = null;
try { try {
regex = new RegExp(pattern, flags); regex = new RegExp(pattern, flags);
} catch (e) {} } catch (_) {}
const node = this.estreeParseLiteral(regex); const node = this.estreeParseLiteral(regex);
node.regex = { node.regex = {
pattern, pattern,
@ -2123,7 +2127,7 @@ function readEscapedChar(input, pos, lineStart, curLine, inTemplate, errors) {
default: default:
if (ch >= 48 && ch <= 55) { if (ch >= 48 && ch <= 55) {
const startPos = pos - 1; const startPos = pos - 1;
const match = input.slice(startPos, pos + 2).match(/^[0-7]+/); const match = /^[0-7]+/.exec(input.slice(startPos, pos + 2));
let octalStr = match[0]; let octalStr = match[0];
let octal = parseInt(octalStr, 8); let octal = parseInt(octalStr, 8);
if (octal > 255) { if (octal > 255) {
@ -3554,7 +3558,9 @@ class UtilParser extends Tokenizer {
this.raise(Errors.MissingSemicolon, this.state.lastTokEndLoc); this.raise(Errors.MissingSemicolon, this.state.lastTokEndLoc);
} }
expect(type, loc) { expect(type, loc) {
this.eat(type) || this.unexpected(loc, type); if (!this.eat(type)) {
this.unexpected(loc, type);
}
} }
tryParse(fn, oldState = this.state.clone()) { tryParse(fn, oldState = this.state.clone()) {
const abortSignal = { const abortSignal = {
@ -5159,7 +5165,7 @@ var flow = superClass => class FlowParserMixin extends superClass {
} }
forwardNoArrowParamsConversionAt(node, parse) { forwardNoArrowParamsConversionAt(node, parse) {
let result; let result;
if (this.state.noArrowParamsConversionAt.indexOf(node.start) !== -1) { if (this.state.noArrowParamsConversionAt.includes(node.start)) {
this.state.noArrowParamsConversionAt.push(this.state.start); this.state.noArrowParamsConversionAt.push(this.state.start);
result = parse(); result = parse();
this.state.noArrowParamsConversionAt.pop(); this.state.noArrowParamsConversionAt.pop();
@ -5669,14 +5675,14 @@ var flow = superClass => class FlowParserMixin extends superClass {
return this.match(14) || super.shouldParseArrow(params); return this.match(14) || super.shouldParseArrow(params);
} }
setArrowFunctionParameters(node, params) { setArrowFunctionParameters(node, params) {
if (this.state.noArrowParamsConversionAt.indexOf(node.start) !== -1) { if (this.state.noArrowParamsConversionAt.includes(node.start)) {
node.params = params; node.params = params;
} else { } else {
super.setArrowFunctionParameters(node, params); super.setArrowFunctionParameters(node, params);
} }
} }
checkParams(node, allowDuplicates, isArrowFunction, strictModeChanged = true) { checkParams(node, allowDuplicates, isArrowFunction, strictModeChanged = true) {
if (isArrowFunction && this.state.noArrowParamsConversionAt.indexOf(node.start) !== -1) { if (isArrowFunction && this.state.noArrowParamsConversionAt.includes(node.start)) {
return; return;
} }
for (let i = 0; i < node.params.length; i++) { for (let i = 0; i < node.params.length; i++) {
@ -5687,10 +5693,10 @@ var flow = superClass => class FlowParserMixin extends superClass {
super.checkParams(node, allowDuplicates, isArrowFunction, strictModeChanged); super.checkParams(node, allowDuplicates, isArrowFunction, strictModeChanged);
} }
parseParenAndDistinguishExpression(canBeArrow) { parseParenAndDistinguishExpression(canBeArrow) {
return super.parseParenAndDistinguishExpression(canBeArrow && this.state.noArrowAt.indexOf(this.state.start) === -1); return super.parseParenAndDistinguishExpression(canBeArrow && !this.state.noArrowAt.includes(this.state.start));
} }
parseSubscripts(base, startLoc, noCalls) { parseSubscripts(base, startLoc, noCalls) {
if (base.type === "Identifier" && base.name === "async" && this.state.noArrowAt.indexOf(startLoc.index) !== -1) { if (base.type === "Identifier" && base.name === "async" && this.state.noArrowAt.includes(startLoc.index)) {
this.next(); this.next();
const node = this.startNodeAt(startLoc); const node = this.startNodeAt(startLoc);
node.callee = base; node.callee = base;
@ -7505,7 +7511,7 @@ var typescript = superClass => class TypeScriptParserMixin extends superClass {
return undefined; return undefined;
} }
const modifier = this.state.value; const modifier = this.state.value;
if (allowedModifiers.indexOf(modifier) !== -1) { if (allowedModifiers.includes(modifier)) {
if (stopOnStartOfClassStaticBlock && this.tsIsStartOfStaticBlocks()) { if (stopOnStartOfClassStaticBlock && this.tsIsStartOfStaticBlocks()) {
return undefined; return undefined;
} }
@ -9648,12 +9654,17 @@ var typescript = superClass => class TypeScriptParserMixin extends superClass {
return param; return param;
} }
tsInAmbientContext(cb) { tsInAmbientContext(cb) {
const oldIsAmbientContext = this.state.isAmbientContext; const {
isAmbientContext: oldIsAmbientContext,
strict: oldStrict
} = this.state;
this.state.isAmbientContext = true; this.state.isAmbientContext = true;
this.state.strict = false;
try { try {
return cb(); return cb();
} finally { } finally {
this.state.isAmbientContext = oldIsAmbientContext; this.state.isAmbientContext = oldIsAmbientContext;
this.state.strict = oldStrict;
} }
} }
parseClass(node, isStatement, optionalId) { parseClass(node, isStatement, optionalId) {
@ -11125,10 +11136,12 @@ class ExpressionParser extends LValParser {
return this.parseLiteral(value, "DecimalLiteral"); return this.parseLiteral(value, "DecimalLiteral");
} }
parseRegExpLiteral(value) { parseRegExpLiteral(value) {
const node = this.parseLiteral(value.value, "RegExpLiteral"); const node = this.startNode();
this.addExtra(node, "raw", this.input.slice(node.start, this.state.end));
node.pattern = value.pattern; node.pattern = value.pattern;
node.flags = value.flags; node.flags = value.flags;
return node; this.next();
return this.finishNode(node, "RegExpLiteral");
} }
parseBooleanLiteral(value) { parseBooleanLiteral(value) {
const node = this.startNode(); const node = this.startNode();
@ -12167,10 +12180,10 @@ class StatementParser extends ExpressionParser {
const nextCh = this.codePointAtPos(next); const nextCh = this.codePointAtPos(next);
return this.chStartsBindingPattern(nextCh) || this.chStartsBindingIdentifier(nextCh, next); return this.chStartsBindingPattern(nextCh) || this.chStartsBindingIdentifier(nextCh, next);
} }
hasInLineFollowingBindingIdentifier() { hasInLineFollowingBindingIdentifierOrBrace() {
const next = this.nextTokenInLineStart(); const next = this.nextTokenInLineStart();
const nextCh = this.codePointAtPos(next); const nextCh = this.codePointAtPos(next);
return this.chStartsBindingIdentifier(nextCh, next); return nextCh === 123 || this.chStartsBindingIdentifier(nextCh, next);
} }
startsUsingForOf() { startsUsingForOf() {
const { const {
@ -12270,7 +12283,7 @@ class StatementParser extends ExpressionParser {
} }
break; break;
case 107: case 107:
if (this.state.containsEsc || !this.hasInLineFollowingBindingIdentifier()) { if (this.state.containsEsc || !this.hasInLineFollowingBindingIdentifierOrBrace()) {
break; break;
} }
this.expectPlugin("explicitResourceManagement"); this.expectPlugin("explicitResourceManagement");
@ -12864,6 +12877,11 @@ class StatementParser extends ExpressionParser {
} }
parseVarId(decl, kind) { parseVarId(decl, kind) {
const id = this.parseBindingAtom(); const id = this.parseBindingAtom();
if (kind === "using" || kind === "await using") {
if (id.type === "ArrayPattern" || id.type === "ObjectPattern") {
this.raise(Errors.UsingDeclarationHasBindingPattern, id.loc.start);
}
}
this.checkLVal(id, { this.checkLVal(id, {
in: { in: {
type: "VariableDeclarator" type: "VariableDeclarator"
@ -13563,7 +13581,7 @@ class StatementParser extends ExpressionParser {
parseModuleExportName() { parseModuleExportName() {
if (this.match(133)) { if (this.match(133)) {
const result = this.parseStringLiteral(this.state.value); const result = this.parseStringLiteral(this.state.value);
const surrogate = result.value.match(loneSurrogate); const surrogate = loneSurrogate.exec(result.value);
if (surrogate) { if (surrogate) {
this.raise(Errors.ModuleExportNameHasLoneSurrogate, result, { this.raise(Errors.ModuleExportNameHasLoneSurrogate, result, {
surrogateCharCode: surrogate[0].charCodeAt(0) surrogateCharCode: surrogate[0].charCodeAt(0)

View file

@ -1,6 +1,6 @@
{ {
"name": "@babel/parser", "name": "@babel/parser",
"version": "7.24.7", "version": "7.24.8",
"description": "A JavaScript parser", "description": "A JavaScript parser",
"author": "The Babel Team (https://babel.dev/team)", "author": "The Babel Team (https://babel.dev/team)",
"homepage": "https://babel.dev/docs/en/next/babel-parser", "homepage": "https://babel.dev/docs/en/next/babel-parser",
@ -36,10 +36,10 @@
"devDependencies": { "devDependencies": {
"@babel/code-frame": "^7.24.7", "@babel/code-frame": "^7.24.7",
"@babel/helper-check-duplicate-nodes": "^7.24.7", "@babel/helper-check-duplicate-nodes": "^7.24.7",
"@babel/helper-fixtures": "^7.24.7", "@babel/helper-fixtures": "^7.24.8",
"@babel/helper-string-parser": "^7.24.7", "@babel/helper-string-parser": "^7.24.8",
"@babel/helper-validator-identifier": "^7.24.7", "@babel/helper-validator-identifier": "^7.24.7",
"@babel/types": "^7.24.7", "@babel/types": "^7.24.8",
"charcodes": "^0.2.0" "charcodes": "^0.2.0"
}, },
"bin": "./bin/babel-parser.js", "bin": "./bin/babel-parser.js",

View file

@ -25,15 +25,16 @@ exports.stop = stop;
exports.visit = visit; exports.visit = visit;
var _traverseNode = require("../traverse-node.js"); var _traverseNode = require("../traverse-node.js");
var _index = require("./index.js"); var _index = require("./index.js");
var _removal = require("./removal.js");
function call(key) { function call(key) {
const opts = this.opts; const opts = this.opts;
this.debug(key); this.debug(key);
if (this.node) { if (this.node) {
if (this._call(opts[key])) return true; if (_call.call(this, opts[key])) return true;
} }
if (this.node) { if (this.node) {
var _opts$this$node$type; var _opts$this$node$type;
return this._call((_opts$this$node$type = opts[this.node.type]) == null ? void 0 : _opts$this$node$type[key]); return _call.call(this, (_opts$this$node$type = opts[this.node.type]) == null ? void 0 : _opts$this$node$type[key]);
} }
return false; return false;
} }
@ -134,9 +135,9 @@ function setContext(context) {
} }
function resync() { function resync() {
if (this.removed) return; if (this.removed) return;
this._resyncParent(); _resyncParent.call(this);
this._resyncList(); _resyncList.call(this);
this._resyncKey(); _resyncKey.call(this);
} }
function _resyncParent() { function _resyncParent() {
if (this.parentPath) { if (this.parentPath) {
@ -173,7 +174,7 @@ function _resyncList() {
} }
function _resyncRemoved() { function _resyncRemoved() {
if (this.key == null || !this.container || this.container[this.key] !== this.node) { if (this.key == null || !this.container || this.container[this.key] !== this.node) {
this._markRemoved(); _removal._markRemoved.call(this);
} }
} }
function popContext() { function popContext() {

View file

@ -232,9 +232,9 @@ function get(key, context = true) {
if (context === true) context = this.context; if (context === true) context = this.context;
const parts = key.split("."); const parts = key.split(".");
if (parts.length === 1) { if (parts.length === 1) {
return this._getKey(key, context); return _getKey.call(this, key, context);
} else { } else {
return this._getPattern(parts, context); return _getPattern.call(this, parts, context);
} }
} }
function _getKey(key, context) { function _getKey(key, context) {

View file

@ -163,7 +163,6 @@ const methods = {
isDescendant: NodePath_ancestry.isDescendant, isDescendant: NodePath_ancestry.isDescendant,
inType: NodePath_ancestry.inType, inType: NodePath_ancestry.inType,
getTypeAnnotation: NodePath_inference.getTypeAnnotation, getTypeAnnotation: NodePath_inference.getTypeAnnotation,
_getTypeAnnotation: NodePath_inference._getTypeAnnotation,
isBaseType: NodePath_inference.isBaseType, isBaseType: NodePath_inference.isBaseType,
couldBeBaseType: NodePath_inference.couldBeBaseType, couldBeBaseType: NodePath_inference.couldBeBaseType,
baseTypeStrictlyMatches: NodePath_inference.baseTypeStrictlyMatches, baseTypeStrictlyMatches: NodePath_inference.baseTypeStrictlyMatches,
@ -171,7 +170,6 @@ const methods = {
replaceWithMultiple: NodePath_replacement.replaceWithMultiple, replaceWithMultiple: NodePath_replacement.replaceWithMultiple,
replaceWithSourceString: NodePath_replacement.replaceWithSourceString, replaceWithSourceString: NodePath_replacement.replaceWithSourceString,
replaceWith: NodePath_replacement.replaceWith, replaceWith: NodePath_replacement.replaceWith,
_replaceWith: NodePath_replacement._replaceWith,
replaceExpressionWithStatements: NodePath_replacement.replaceExpressionWithStatements, replaceExpressionWithStatements: NodePath_replacement.replaceExpressionWithStatements,
replaceInline: NodePath_replacement.replaceInline, replaceInline: NodePath_replacement.replaceInline,
evaluateTruthy: NodePath_evaluation.evaluateTruthy, evaluateTruthy: NodePath_evaluation.evaluateTruthy,
@ -196,11 +194,9 @@ const methods = {
willIMaybeExecuteBefore: NodePath_introspection.willIMaybeExecuteBefore, willIMaybeExecuteBefore: NodePath_introspection.willIMaybeExecuteBefore,
_guessExecutionStatusRelativeTo: NodePath_introspection._guessExecutionStatusRelativeTo, _guessExecutionStatusRelativeTo: NodePath_introspection._guessExecutionStatusRelativeTo,
resolve: NodePath_introspection.resolve, resolve: NodePath_introspection.resolve,
_resolve: NodePath_introspection._resolve,
isConstantExpression: NodePath_introspection.isConstantExpression, isConstantExpression: NodePath_introspection.isConstantExpression,
isInStrictMode: NodePath_introspection.isInStrictMode, isInStrictMode: NodePath_introspection.isInStrictMode,
call: NodePath_context.call, call: NodePath_context.call,
_call: NodePath_context._call,
isDenylisted: NodePath_context.isDenylisted, isDenylisted: NodePath_context.isDenylisted,
isBlacklisted: NodePath_context.isBlacklisted, isBlacklisted: NodePath_context.isBlacklisted,
visit: NodePath_context.visit, visit: NodePath_context.visit,
@ -210,29 +206,15 @@ const methods = {
setScope: NodePath_context.setScope, setScope: NodePath_context.setScope,
setContext: NodePath_context.setContext, setContext: NodePath_context.setContext,
resync: NodePath_context.resync, resync: NodePath_context.resync,
_resyncParent: NodePath_context._resyncParent,
_resyncKey: NodePath_context._resyncKey,
_resyncList: NodePath_context._resyncList,
_resyncRemoved: NodePath_context._resyncRemoved,
popContext: NodePath_context.popContext, popContext: NodePath_context.popContext,
pushContext: NodePath_context.pushContext, pushContext: NodePath_context.pushContext,
setup: NodePath_context.setup, setup: NodePath_context.setup,
setKey: NodePath_context.setKey, setKey: NodePath_context.setKey,
requeue: NodePath_context.requeue, requeue: NodePath_context.requeue,
_getQueueContexts: NodePath_context._getQueueContexts,
remove: NodePath_removal.remove, remove: NodePath_removal.remove,
_removeFromScope: NodePath_removal._removeFromScope,
_callRemovalHooks: NodePath_removal._callRemovalHooks,
_remove: NodePath_removal._remove,
_markRemoved: NodePath_removal._markRemoved,
_assertUnremoved: NodePath_removal._assertUnremoved,
insertBefore: NodePath_modification.insertBefore, insertBefore: NodePath_modification.insertBefore,
_containerInsert: NodePath_modification._containerInsert,
_containerInsertBefore: NodePath_modification._containerInsertBefore,
_containerInsertAfter: NodePath_modification._containerInsertAfter,
insertAfter: NodePath_modification.insertAfter, insertAfter: NodePath_modification.insertAfter,
updateSiblingKeys: NodePath_modification.updateSiblingKeys, updateSiblingKeys: NodePath_modification.updateSiblingKeys,
_verifyNodeList: NodePath_modification._verifyNodeList,
unshiftContainer: NodePath_modification.unshiftContainer, unshiftContainer: NodePath_modification.unshiftContainer,
pushContainer: NodePath_modification.pushContainer, pushContainer: NodePath_modification.pushContainer,
hoist: NodePath_modification.hoist, hoist: NodePath_modification.hoist,
@ -244,8 +226,6 @@ const methods = {
getAllNextSiblings: NodePath_family.getAllNextSiblings, getAllNextSiblings: NodePath_family.getAllNextSiblings,
getAllPrevSiblings: NodePath_family.getAllPrevSiblings, getAllPrevSiblings: NodePath_family.getAllPrevSiblings,
get: NodePath_family.get, get: NodePath_family.get,
_getKey: NodePath_family._getKey,
_getPattern: NodePath_family._getPattern,
getBindingIdentifiers: NodePath_family.getBindingIdentifiers, getBindingIdentifiers: NodePath_family.getBindingIdentifiers,
getOuterBindingIdentifiers: NodePath_family.getOuterBindingIdentifiers, getOuterBindingIdentifiers: NodePath_family.getOuterBindingIdentifiers,
getBindingIdentifierPaths: NodePath_family.getBindingIdentifierPaths, getBindingIdentifierPaths: NodePath_family.getBindingIdentifierPaths,
@ -261,6 +241,31 @@ Object.assign(NodePath_Final.prototype, methods);
{ {
NodePath_Final.prototype._guessExecutionStatusRelativeToDifferentFunctions = NodePath_introspection._guessExecutionStatusRelativeTo; NodePath_Final.prototype._guessExecutionStatusRelativeToDifferentFunctions = NodePath_introspection._guessExecutionStatusRelativeTo;
} }
{
NodePath_Final.prototype._guessExecutionStatusRelativeToDifferentFunctions = NodePath_introspection._guessExecutionStatusRelativeTo;
Object.assign(NodePath_Final.prototype, {
_getTypeAnnotation: NodePath_inference._getTypeAnnotation,
_replaceWith: NodePath_replacement._replaceWith,
_resolve: NodePath_introspection._resolve,
_call: NodePath_context._call,
_resyncParent: NodePath_context._resyncParent,
_resyncKey: NodePath_context._resyncKey,
_resyncList: NodePath_context._resyncList,
_resyncRemoved: NodePath_context._resyncRemoved,
_getQueueContexts: NodePath_context._getQueueContexts,
_removeFromScope: NodePath_removal._removeFromScope,
_callRemovalHooks: NodePath_removal._callRemovalHooks,
_remove: NodePath_removal._remove,
_markRemoved: NodePath_removal._markRemoved,
_assertUnremoved: NodePath_removal._assertUnremoved,
_containerInsert: NodePath_modification._containerInsert,
_containerInsertBefore: NodePath_modification._containerInsertBefore,
_containerInsertAfter: NodePath_modification._containerInsertAfter,
_verifyNodeList: NodePath_modification._verifyNodeList,
_getKey: NodePath_family._getKey,
_getPattern: NodePath_family._getPattern
});
}
for (const type of t.TYPES) { for (const type of t.TYPES) {
const typeKey = `is${type}`; const typeKey = `is${type}`;
const fn = t[typeKey]; const fn = t[typeKey];

View file

@ -38,7 +38,7 @@ function getTypeAnnotation() {
if (type != null) { if (type != null) {
return type; return type;
} }
type = this._getTypeAnnotation() || anyTypeAnnotation(); type = _getTypeAnnotation.call(this) || anyTypeAnnotation();
if (isTypeAnnotation(type) || isTSTypeAnnotation(type)) { if (isTypeAnnotation(type) || isTSTypeAnnotation(type)) {
type = type.typeAnnotation; type = type.typeAnnotation;
} }

View file

@ -35,7 +35,7 @@ function getTypeAnnotationBindingConstantViolations(binding, path, name) {
const testType = getConditionalAnnotation(binding, path, name); const testType = getConditionalAnnotation(binding, path, name);
if (testType) { if (testType) {
const testConstantViolations = getConstantViolationsBefore(binding, testType.ifStatement); const testConstantViolations = getConstantViolationsBefore(binding, testType.ifStatement);
constantViolations = constantViolations.filter(path => testConstantViolations.indexOf(path) < 0); constantViolations = constantViolations.filter(path => !testConstantViolations.includes(path));
types.push(testType.typeAnnotation); types.push(testType.typeAnnotation);
} }
if (constantViolations.length) { if (constantViolations.length) {
@ -77,7 +77,7 @@ function inferAnnotationFromBinaryExpression(name, path) {
if (operator === "===") { if (operator === "===") {
return target.getTypeAnnotation(); return target.getTypeAnnotation();
} }
if (BOOLEAN_NUMBER_BINARY_OPERATORS.indexOf(operator) >= 0) { if (BOOLEAN_NUMBER_BINARY_OPERATORS.includes(operator)) {
return numberTypeAnnotation(); return numberTypeAnnotation();
} }
return; return;

View file

@ -84,19 +84,19 @@ function UnaryExpression(node) {
const operator = node.operator; const operator = node.operator;
if (operator === "void") { if (operator === "void") {
return voidTypeAnnotation(); return voidTypeAnnotation();
} else if (NUMBER_UNARY_OPERATORS.indexOf(operator) >= 0) { } else if (NUMBER_UNARY_OPERATORS.includes(operator)) {
return numberTypeAnnotation(); return numberTypeAnnotation();
} else if (STRING_UNARY_OPERATORS.indexOf(operator) >= 0) { } else if (STRING_UNARY_OPERATORS.includes(operator)) {
return stringTypeAnnotation(); return stringTypeAnnotation();
} else if (BOOLEAN_UNARY_OPERATORS.indexOf(operator) >= 0) { } else if (BOOLEAN_UNARY_OPERATORS.includes(operator)) {
return booleanTypeAnnotation(); return booleanTypeAnnotation();
} }
} }
function BinaryExpression(node) { function BinaryExpression(node) {
const operator = node.operator; const operator = node.operator;
if (NUMBER_BINARY_OPERATORS.indexOf(operator) >= 0) { if (NUMBER_BINARY_OPERATORS.includes(operator)) {
return numberTypeAnnotation(); return numberTypeAnnotation();
} else if (BOOLEAN_BINARY_OPERATORS.indexOf(operator) >= 0) { } else if (BOOLEAN_BINARY_OPERATORS.includes(operator)) {
return booleanTypeAnnotation(); return booleanTypeAnnotation();
} else if (operator === "+") { } else if (operator === "+") {
const right = this.get("right"); const right = this.get("right");

View file

@ -198,8 +198,8 @@ function _guessExecutionStatusRelativeToCached(base, target, cache) {
target: target.getAncestry(), target: target.getAncestry(),
this: base.getAncestry() this: base.getAncestry()
}; };
if (paths.target.indexOf(base) >= 0) return "after"; if (paths.target.includes(base)) return "after";
if (paths.this.indexOf(target) >= 0) return "before"; if (paths.this.includes(target)) return "before";
let commonPath; let commonPath;
const commonIndex = { const commonIndex = {
target: 0, target: 0,
@ -279,10 +279,11 @@ function _guessExecutionStatusRelativeToDifferentFunctionsCached(base, target, c
return result; return result;
} }
function resolve(dangerous, resolved) { function resolve(dangerous, resolved) {
return this._resolve(dangerous, resolved) || this; return _resolve.call(this, dangerous, resolved) || this;
} }
function _resolve(dangerous, resolved) { function _resolve(dangerous, resolved) {
if (resolved && resolved.indexOf(this) >= 0) return; var _resolved;
if ((_resolved = resolved) != null && _resolved.includes(this)) return;
resolved = resolved || []; resolved = resolved || [];
resolved.push(this); resolved.push(this);
if (this.isVariableDeclarator()) { if (this.isVariableDeclarator()) {

View file

@ -76,7 +76,7 @@ class PathHoister {
} else { } else {
break; break;
} }
if (this.breakOnScopePaths.indexOf(scope.path) >= 0) { if (this.breakOnScopePaths.includes(scope.path)) {
break; break;
} }
} while (scope = scope.parent); } while (scope = scope.parent);

View file

@ -16,6 +16,8 @@ exports.updateSiblingKeys = updateSiblingKeys;
var _cache = require("../cache.js"); var _cache = require("../cache.js");
var _hoister = require("./lib/hoister.js"); var _hoister = require("./lib/hoister.js");
var _index = require("./index.js"); var _index = require("./index.js");
var _context = require("./context.js");
var _removal = require("./removal.js");
var _t = require("@babel/types"); var _t = require("@babel/types");
const { const {
arrowFunctionExpression, arrowFunctionExpression,
@ -35,8 +37,8 @@ const {
thisExpression thisExpression
} = _t; } = _t;
function insertBefore(nodes_) { function insertBefore(nodes_) {
this._assertUnremoved(); _removal._assertUnremoved.call(this);
const nodes = this._verifyNodeList(nodes_); const nodes = _verifyNodeList.call(this, nodes_);
const { const {
parentPath, parentPath,
parent parent
@ -47,7 +49,7 @@ function insertBefore(nodes_) {
if (this.node) nodes.push(this.node); if (this.node) nodes.push(this.node);
return this.replaceExpressionWithStatements(nodes); return this.replaceExpressionWithStatements(nodes);
} else if (Array.isArray(this.container)) { } else if (Array.isArray(this.container)) {
return this._containerInsertBefore(nodes); return _containerInsertBefore.call(this, nodes);
} else if (this.isStatementOrBlock()) { } else if (this.isStatementOrBlock()) {
const node = this.node; const node = this.node;
const shouldInsertCurrentNode = node && (!this.isExpressionStatement() || node.expression != null); const shouldInsertCurrentNode = node && (!this.isExpressionStatement() || node.expression != null);
@ -70,7 +72,7 @@ function _containerInsert(from, nodes) {
path.pushContext(this.context); path.pushContext(this.context);
} }
} }
const contexts = this._getQueueContexts(); const contexts = _context._getQueueContexts.call(this);
for (const path of paths) { for (const path of paths) {
path.setScope(); path.setScope();
path.debug("Inserted."); path.debug("Inserted.");
@ -81,10 +83,10 @@ function _containerInsert(from, nodes) {
return paths; return paths;
} }
function _containerInsertBefore(nodes) { function _containerInsertBefore(nodes) {
return this._containerInsert(this.key, nodes); return _containerInsert.call(this, this.key, nodes);
} }
function _containerInsertAfter(nodes) { function _containerInsertAfter(nodes) {
return this._containerInsert(this.key + 1, nodes); return _containerInsert.call(this, this.key + 1, nodes);
} }
const last = arr => arr[arr.length - 1]; const last = arr => arr[arr.length - 1];
function isHiddenInSequenceExpression(path) { function isHiddenInSequenceExpression(path) {
@ -98,11 +100,11 @@ function isAlmostConstantAssignment(node, scope) {
return blockScope.hasOwnBinding(node.left.name) && blockScope.getOwnBinding(node.left.name).constantViolations.length <= 1; return blockScope.hasOwnBinding(node.left.name) && blockScope.getOwnBinding(node.left.name).constantViolations.length <= 1;
} }
function insertAfter(nodes_) { function insertAfter(nodes_) {
this._assertUnremoved(); _removal._assertUnremoved.call(this);
if (this.isSequenceExpression()) { if (this.isSequenceExpression()) {
return last(this.get("expressions")).insertAfter(nodes_); return last(this.get("expressions")).insertAfter(nodes_);
} }
const nodes = this._verifyNodeList(nodes_); const nodes = _verifyNodeList.call(this, nodes_);
const { const {
parentPath, parentPath,
parent parent
@ -148,7 +150,7 @@ function insertAfter(nodes_) {
} }
return this.replaceExpressionWithStatements(nodes); return this.replaceExpressionWithStatements(nodes);
} else if (Array.isArray(this.container)) { } else if (Array.isArray(this.container)) {
return this._containerInsertAfter(nodes); return _containerInsertAfter.call(this, nodes);
} else if (this.isStatementOrBlock()) { } else if (this.isStatementOrBlock()) {
const node = this.node; const node = this.node;
const shouldInsertCurrentNode = node && (!this.isExpressionStatement() || node.expression != null); const shouldInsertCurrentNode = node && (!this.isExpressionStatement() || node.expression != null);
@ -194,8 +196,8 @@ function _verifyNodeList(nodes) {
return nodes; return nodes;
} }
function unshiftContainer(listKey, nodes) { function unshiftContainer(listKey, nodes) {
this._assertUnremoved(); _removal._assertUnremoved.call(this);
nodes = this._verifyNodeList(nodes); nodes = _verifyNodeList.call(this, nodes);
const path = _index.default.get({ const path = _index.default.get({
parentPath: this, parentPath: this,
parent: this.node, parent: this.node,
@ -203,11 +205,11 @@ function unshiftContainer(listKey, nodes) {
listKey, listKey,
key: 0 key: 0
}).setContext(this.context); }).setContext(this.context);
return path._containerInsertBefore(nodes); return _containerInsertBefore.call(path, nodes);
} }
function pushContainer(listKey, nodes) { function pushContainer(listKey, nodes) {
this._assertUnremoved(); _removal._assertUnremoved.call(this);
const verifiedNodes = this._verifyNodeList(nodes); const verifiedNodes = _verifyNodeList.call(this, nodes);
const container = this.node[listKey]; const container = this.node[listKey];
const path = _index.default.get({ const path = _index.default.get({
parentPath: this, parentPath: this,

View file

@ -11,6 +11,7 @@ exports._removeFromScope = _removeFromScope;
exports.remove = remove; exports.remove = remove;
var _removalHooks = require("./lib/removal-hooks.js"); var _removalHooks = require("./lib/removal-hooks.js");
var _cache = require("../cache.js"); var _cache = require("../cache.js");
var _replacement = require("./replacement.js");
var _index = require("./index.js"); var _index = require("./index.js");
var _t = require("@babel/types"); var _t = require("@babel/types");
const { const {
@ -18,18 +19,18 @@ const {
} = _t; } = _t;
function remove() { function remove() {
var _this$opts; var _this$opts;
this._assertUnremoved(); _assertUnremoved.call(this);
this.resync(); this.resync();
if (!((_this$opts = this.opts) != null && _this$opts.noScope)) { if (!((_this$opts = this.opts) != null && _this$opts.noScope)) {
this._removeFromScope(); _removeFromScope.call(this);
} }
if (this._callRemovalHooks()) { if (_callRemovalHooks.call(this)) {
this._markRemoved(); _markRemoved.call(this);
return; return;
} }
this.shareCommentsWithSiblings(); this.shareCommentsWithSiblings();
this._remove(); _remove.call(this);
this._markRemoved(); _markRemoved.call(this);
} }
function _removeFromScope() { function _removeFromScope() {
const bindings = getBindingIdentifiers(this.node, false, false, true); const bindings = getBindingIdentifiers(this.node, false, false, true);
@ -47,7 +48,7 @@ function _remove() {
this.container.splice(this.key, 1); this.container.splice(this.key, 1);
this.updateSiblingKeys(this.key, -1); this.updateSiblingKeys(this.key, -1);
} else { } else {
this._replaceWith(null); _replacement._replaceWith.call(this, null);
} }
} }
function _markRemoved() { function _markRemoved() {

View file

@ -13,6 +13,7 @@ var _codeFrame = require("@babel/code-frame");
var _index = require("../index.js"); var _index = require("../index.js");
var _index2 = require("./index.js"); var _index2 = require("./index.js");
var _cache = require("../cache.js"); var _cache = require("../cache.js");
var _modification = require("./modification.js");
var _parser = require("@babel/parser"); var _parser = require("@babel/parser");
var _t = require("@babel/types"); var _t = require("@babel/types");
var _helperHoistVariables = require("@babel/helper-hoist-variables"); var _helperHoistVariables = require("@babel/helper-hoist-variables");
@ -49,7 +50,7 @@ const {
function replaceWithMultiple(nodes) { function replaceWithMultiple(nodes) {
var _getCachedPaths; var _getCachedPaths;
this.resync(); this.resync();
nodes = this._verifyNodeList(nodes); nodes = _modification._verifyNodeList.call(this, nodes);
inheritLeadingComments(nodes[0], this.node); inheritLeadingComments(nodes[0], this.node);
inheritTrailingComments(nodes[nodes.length - 1], this.node); inheritTrailingComments(nodes[nodes.length - 1], this.node);
(_getCachedPaths = (0, _cache.getCachedPaths)(this.hub, this.parent)) == null || _getCachedPaths.delete(this.node); (_getCachedPaths = (0, _cache.getCachedPaths)(this.hub, this.parent)) == null || _getCachedPaths.delete(this.node);
@ -123,7 +124,7 @@ function replaceWith(replacementPath) {
inheritsComments(replacement, oldNode); inheritsComments(replacement, oldNode);
removeComments(oldNode); removeComments(oldNode);
} }
this._replaceWith(replacement); _replaceWith.call(this, replacement);
this.type = replacement.type; this.type = replacement.type;
this.setScope(); this.setScope();
this.requeue(); this.requeue();
@ -249,8 +250,8 @@ function replaceInline(nodes) {
this.resync(); this.resync();
if (Array.isArray(nodes)) { if (Array.isArray(nodes)) {
if (Array.isArray(this.container)) { if (Array.isArray(this.container)) {
nodes = this._verifyNodeList(nodes); nodes = _modification._verifyNodeList.call(this, nodes);
const paths = this._containerInsertAfter(nodes); const paths = _modification._containerInsertAfter.call(this, nodes);
this.remove(); this.remove();
return paths; return paths;
} else { } else {

View file

@ -45,13 +45,13 @@ class Binding {
} }
reassign(path) { reassign(path) {
this.constant = false; this.constant = false;
if (this.constantViolations.indexOf(path) !== -1) { if (this.constantViolations.includes(path)) {
return; return;
} }
this.constantViolations.push(path); this.constantViolations.push(path);
} }
reference(path) { reference(path) {
if (this.referencePaths.indexOf(path) !== -1) { if (this.referencePaths.includes(path)) {
return; return;
} }
this.referenced = true; this.referenced = true;

View file

@ -857,18 +857,24 @@ class Scope {
return !!this.getOwnBinding(name); return !!this.getOwnBinding(name);
} }
hasBinding(name, opts) { hasBinding(name, opts) {
var _opts, _opts2, _opts3;
if (!name) return false; if (!name) return false;
if (this.hasOwnBinding(name)) return true; let scope = this;
{ do {
if (typeof opts === "boolean") opts = { if (scope.hasOwnBinding(name)) {
noGlobals: opts return true;
};
} }
if (this.parentHasBinding(name, opts)) return true; } while (scope = scope.parent);
if (!((_opts = opts) != null && _opts.noUids) && this.hasUid(name)) return true; let noGlobals;
if (!((_opts2 = opts) != null && _opts2.noGlobals) && Scope.globals.includes(name)) return true; let noUids;
if (!((_opts3 = opts) != null && _opts3.noGlobals) && Scope.contextVariables.includes(name)) return true; if (typeof opts === "object") {
noGlobals = opts.noGlobals;
noUids = opts.noUids;
} else if (typeof opts === "boolean") {
noGlobals = opts;
}
if (!noUids && this.hasUid(name)) return true;
if (!noGlobals && Scope.globals.includes(name)) return true;
if (!noGlobals && Scope.contextVariables.includes(name)) return true;
return false; return false;
} }
parentHasBinding(name, opts) { parentHasBinding(name, opts) {

View file

@ -101,7 +101,7 @@ function verify$1(visitor) {
validateVisitorMethods(nodeType, visitor[nodeType]); validateVisitorMethods(nodeType, visitor[nodeType]);
} }
if (shouldIgnoreKey(nodeType)) continue; if (shouldIgnoreKey(nodeType)) continue;
if (TYPES.indexOf(nodeType) < 0) { if (!TYPES.includes(nodeType)) {
throw new Error(`You gave us a visitor for the node type ${nodeType} but it's not a valid type`); throw new Error(`You gave us a visitor for the node type ${nodeType} but it's not a valid type`);
} }
const visitors = visitor[nodeType]; const visitors = visitor[nodeType];

View file

@ -1,6 +1,6 @@
{ {
"name": "@babel/traverse", "name": "@babel/traverse",
"version": "7.24.7", "version": "7.24.8",
"description": "The Babel Traverse module maintains the overall tree state, and is responsible for replacing, removing, and adding nodes", "description": "The Babel Traverse module maintains the overall tree state, and is responsible for replacing, removing, and adding nodes",
"author": "The Babel Team (https://babel.dev/team)", "author": "The Babel Team (https://babel.dev/team)",
"homepage": "https://babel.dev/docs/en/next/babel-traverse", "homepage": "https://babel.dev/docs/en/next/babel-traverse",
@ -17,18 +17,18 @@
"main": "./lib/index.js", "main": "./lib/index.js",
"dependencies": { "dependencies": {
"@babel/code-frame": "^7.24.7", "@babel/code-frame": "^7.24.7",
"@babel/generator": "^7.24.7", "@babel/generator": "^7.24.8",
"@babel/helper-environment-visitor": "^7.24.7", "@babel/helper-environment-visitor": "^7.24.7",
"@babel/helper-function-name": "^7.24.7", "@babel/helper-function-name": "^7.24.7",
"@babel/helper-hoist-variables": "^7.24.7", "@babel/helper-hoist-variables": "^7.24.7",
"@babel/helper-split-export-declaration": "^7.24.7", "@babel/helper-split-export-declaration": "^7.24.7",
"@babel/parser": "^7.24.7", "@babel/parser": "^7.24.8",
"@babel/types": "^7.24.7", "@babel/types": "^7.24.8",
"debug": "^4.3.1", "debug": "^4.3.1",
"globals": "^11.1.0" "globals": "^11.1.0"
}, },
"devDependencies": { "devDependencies": {
"@babel/core": "^7.24.7", "@babel/core": "^7.24.8",
"@babel/helper-plugin-test-runner": "^7.24.7" "@babel/helper-plugin-test-runner": "^7.24.7"
}, },
"engines": { "engines": {

View file

@ -51,7 +51,7 @@ function valueToNode(value) {
} }
if (isRegExp(value)) { if (isRegExp(value)) {
const pattern = value.source; const pattern = value.source;
const flags = value.toString().match(/\/([a-z]+|)$/)[1]; const flags = /\/([a-z]+|)$/.exec(value.toString())[1];
return (0, _index.regExpLiteral)(pattern, flags); return (0, _index.regExpLiteral)(pattern, flags);
} }
if (Array.isArray(value)) { if (Array.isArray(value)) {

View file

@ -236,7 +236,8 @@ defineType("ObjectTypeAnnotation", {
} }
}); });
defineType("ObjectTypeInternalSlot", { defineType("ObjectTypeInternalSlot", {
visitor: ["id", "value", "optional", "static", "method"], visitor: ["id", "value"],
builder: ["id", "value", "optional", "static", "method"],
aliases: ["UserWhitespacable"], aliases: ["UserWhitespacable"],
fields: { fields: {
id: (0, _utils.validateType)("Identifier"), id: (0, _utils.validateType)("Identifier"),

View file

@ -87,7 +87,7 @@ function assertEach(callback) {
} }
function assertOneOf(...values) { function assertOneOf(...values) {
function validate(node, key, val) { function validate(node, key, val) {
if (values.indexOf(val) < 0) { if (!values.includes(val)) {
throw new TypeError(`Property ${key} expected value to be one of ${JSON.stringify(values)} but got ${JSON.stringify(val)}`); throw new TypeError(`Property ${key} expected value to be one of ${JSON.stringify(values)} but got ${JSON.stringify(val)}`);
} }
} }
@ -230,7 +230,7 @@ function defineType(type, opts = {}) {
const aliases = opts.aliases || inherits.aliases || []; const aliases = opts.aliases || inherits.aliases || [];
const builder = opts.builder || inherits.builder || opts.visitor || []; const builder = opts.builder || inherits.builder || opts.visitor || [];
for (const k of Object.keys(opts)) { for (const k of Object.keys(opts)) {
if (validTypeOpts.indexOf(k) === -1) { if (!validTypeOpts.includes(k)) {
throw new Error(`Unknown type option "${k}" on ${type}`); throw new Error(`Unknown type option "${k}" on ${type}`);
} }
} }
@ -242,7 +242,7 @@ function defineType(type, opts = {}) {
} }
for (const key of Object.keys(fields)) { for (const key of Object.keys(fields)) {
const field = fields[key]; const field = fields[key];
if (field.default !== undefined && builder.indexOf(key) === -1) { if (field.default !== undefined && !builder.includes(key)) {
field.optional = true; field.optional = true;
} }
if (field.default === undefined) { if (field.default === undefined) {
@ -251,7 +251,7 @@ function defineType(type, opts = {}) {
field.validate = assertValueType(getType(field.default)); field.validate = assertValueType(getType(field.default));
} }
for (const k of Object.keys(field)) { for (const k of Object.keys(field)) {
if (validFieldKeys.indexOf(k) === -1) { if (!validFieldKeys.includes(k)) {
throw new Error(`Unknown field key "${k}" on ${type}.${key}`); throw new Error(`Unknown field key "${k}" on ${type}.${key}`);
} }
} }

View file

@ -17,7 +17,7 @@ function removeTypeDuplicates(nodesIn) {
for (let i = 0; i < nodes.length; i++) { for (let i = 0; i < nodes.length; i++) {
const node = nodes[i]; const node = nodes[i];
if (!node) continue; if (!node) continue;
if (types.indexOf(node) >= 0) { if (types.includes(node)) {
continue; continue;
} }
if ((0, _index.isAnyTypeAnnotation)(node)) { if ((0, _index.isAnyTypeAnnotation)(node)) {

View file

@ -17,7 +17,7 @@ function removeTypeDuplicates(nodesIn) {
for (let i = 0; i < nodes.length; i++) { for (let i = 0; i < nodes.length; i++) {
const node = nodes[i]; const node = nodes[i];
if (!node) continue; if (!node) continue;
if (types.indexOf(node) >= 0) { if (types.includes(node)) {
continue; continue;
} }
if ((0, _index.isTSAnyKeyword)(node)) { if ((0, _index.isTSAnyKeyword)(node)) {

View file

@ -44,14 +44,18 @@ function getBindingIdentifiers(node, duplicates, outerOnly, newBindingsOnly) {
const key = keys[i]; const key = keys[i];
const nodes = id[key]; const nodes = id[key];
if (nodes) { if (nodes) {
Array.isArray(nodes) ? search.push(...nodes) : search.push(nodes); if (Array.isArray(nodes)) {
search.push(...nodes);
} else {
search.push(nodes);
}
} }
} }
} }
} }
return ids; return ids;
} }
getBindingIdentifiers.keys = { const keys = {
DeclareClass: ["id"], DeclareClass: ["id"],
DeclareFunction: ["id"], DeclareFunction: ["id"],
DeclareModule: ["id"], DeclareModule: ["id"],
@ -92,5 +96,6 @@ getBindingIdentifiers.keys = {
VariableDeclaration: ["declarations"], VariableDeclaration: ["declarations"],
VariableDeclarator: ["id"] VariableDeclarator: ["id"]
}; };
getBindingIdentifiers.keys = keys;
//# sourceMappingURL=getBindingIdentifiers.js.map //# sourceMappingURL=getBindingIdentifiers.js.map

View file

@ -10,7 +10,7 @@ function cleanJSXElementLiteralChild(child, args) {
const lines = child.value.split(/\r\n|\n|\r/); const lines = child.value.split(/\r\n|\n|\r/);
let lastNonEmptyLine = 0; let lastNonEmptyLine = 0;
for (let i = 0; i < lines.length; i++) { for (let i = 0; i < lines.length; i++) {
if (lines[i].match(/[^ \t]/)) { if (/[^ \t]/.exec(lines[i])) {
lastNonEmptyLine = i; lastNonEmptyLine = i;
} }
} }

View file

@ -15,7 +15,7 @@ function isBinding(node, parent, grandparent) {
const key = keys[i]; const key = keys[i];
const val = parent[key]; const val = parent[key];
if (Array.isArray(val)) { if (Array.isArray(val)) {
if (val.indexOf(node) >= 0) return true; if (val.includes(node)) return true;
} else { } else {
if (val === node) return true; if (val === node) return true;
} }

View file

@ -1,6 +1,6 @@
{ {
"name": "@babel/types", "name": "@babel/types",
"version": "7.24.7", "version": "7.24.8",
"description": "Babel Types is a Lodash-esque utility library for AST nodes", "description": "Babel Types is a Lodash-esque utility library for AST nodes",
"author": "The Babel Team (https://babel.dev/team)", "author": "The Babel Team (https://babel.dev/team)",
"homepage": "https://babel.dev/docs/en/next/babel-types", "homepage": "https://babel.dev/docs/en/next/babel-types",
@ -24,13 +24,13 @@
} }
}, },
"dependencies": { "dependencies": {
"@babel/helper-string-parser": "^7.24.7", "@babel/helper-string-parser": "^7.24.8",
"@babel/helper-validator-identifier": "^7.24.7", "@babel/helper-validator-identifier": "^7.24.7",
"to-fast-properties": "^2.0.0" "to-fast-properties": "^2.0.0"
}, },
"devDependencies": { "devDependencies": {
"@babel/generator": "^7.24.7", "@babel/generator": "^7.24.8",
"@babel/parser": "^7.24.7", "@babel/parser": "^7.24.8",
"glob": "^7.2.0" "glob": "^7.2.0"
}, },
"engines": { "engines": {

View file

@ -164,8 +164,7 @@ const commentParserToESTree = (jsdoc, mode, {
} catch (err) { } catch (err) {
// Ignore // Ignore
if (lastTag.rawType && throwOnTypeParsingErrors) { if (lastTag.rawType && throwOnTypeParsingErrors) {
/** @type {Error} */err.message = `Tag @${lastTag.tag} with raw type ` + `\`${lastTag.rawType}\` had parsing error: ${ /** @type {Error} */err.message = `Tag @${lastTag.tag} with raw type ` + `\`${lastTag.rawType}\` had parsing error: ${/** @type {Error} */err.message}`;
/** @type {Error} */err.message}`;
throw err; throw err;
} }
} }
@ -681,7 +680,7 @@ const isCommentToken = token => {
}; };
/** /**
* @param {(import('estree').Comment|import('eslint').Rule.Node) & { * @param {(ESLintOrTSNode|import('estree').Comment) & {
* declaration?: any, * declaration?: any,
* decorators?: any[], * decorators?: any[],
* parent?: import('eslint').Rule.Node & { * parent?: import('eslint').Rule.Node & {
@ -698,7 +697,7 @@ const getDecorator = node => {
/** /**
* Check to see if it is a ES6 export declaration. * Check to see if it is a ES6 export declaration.
* *
* @param {import('eslint').Rule.Node} astNode An AST node. * @param {ESLintOrTSNode} astNode An AST node.
* @returns {boolean} whether the given node represents an export declaration. * @returns {boolean} whether the given node represents an export declaration.
* @private * @private
*/ */
@ -707,8 +706,8 @@ const looksLikeExport = function (astNode) {
}; };
/** /**
* @param {import('eslint').Rule.Node} astNode * @param {ESLintOrTSNode} astNode
* @returns {import('eslint').Rule.Node} * @returns {ESLintOrTSNode}
*/ */
const getTSFunctionComment = function (astNode) { const getTSFunctionComment = function (astNode) {
const { const {
@ -753,7 +752,6 @@ const getTSFunctionComment = function (astNode) {
} }
return greatGreatGrandparent.parent; return greatGreatGrandparent.parent;
} }
/* v8 ignore next */ /* v8 ignore next */
return astNode; return astNode;
case 'FunctionExpression': case 'FunctionExpression':
@ -761,7 +759,6 @@ const getTSFunctionComment = function (astNode) {
if (!greatGreatGrandparent) { if (!greatGreatGrandparent) {
return astNode; return astNode;
} }
/* v8 ignore next 3 */
if (greatGrandparent.type === 'MethodDefinition') { if (greatGrandparent.type === 'MethodDefinition') {
return greatGrandparent; return greatGrandparent;
} }
@ -778,28 +775,22 @@ const getTSFunctionComment = function (astNode) {
if (!greatGreatGrandparent) { if (!greatGreatGrandparent) {
return astNode; return astNode;
} }
/* v8 ignore next */
switch (greatGrandparent.type) { switch (greatGrandparent.type) {
case 'ArrowFunctionExpression': case 'ArrowFunctionExpression':
/* v8 ignore next 6 */
if (greatGreatGrandparent.type === 'VariableDeclarator' && greatGreatGrandparent.parent.type === 'VariableDeclaration') { if (greatGreatGrandparent.type === 'VariableDeclarator' && greatGreatGrandparent.parent.type === 'VariableDeclaration') {
return greatGreatGrandparent.parent; return greatGreatGrandparent.parent;
} }
/* v8 ignore next */
return astNode; return astNode;
case 'FunctionDeclaration': case 'FunctionDeclaration':
return greatGrandparent; return greatGrandparent;
case 'VariableDeclarator': case 'VariableDeclarator':
/* v8 ignore next 3 */
if (greatGreatGrandparent.type === 'VariableDeclaration') { if (greatGreatGrandparent.type === 'VariableDeclaration') {
return greatGreatGrandparent; return greatGreatGrandparent;
} }
/* v8 ignore next 2 */
// Fallthrough // Fallthrough
default: default:
/* v8 ignore next */ /* v8 ignore next 3 */
return astNode; return astNode;
} }
}; };
@ -810,9 +801,9 @@ const allowableCommentNode = new Set(['AssignmentPattern', 'VariableDeclaration'
* Reduces the provided node to the appropriate node for evaluating * Reduces the provided node to the appropriate node for evaluating
* JSDoc comment status. * JSDoc comment status.
* *
* @param {import('eslint').Rule.Node} node An AST node. * @param {ESLintOrTSNode} node An AST node.
* @param {import('eslint').SourceCode} sourceCode The ESLint SourceCode. * @param {import('eslint').SourceCode} sourceCode The ESLint SourceCode.
* @returns {import('eslint').Rule.Node} The AST node that * @returns {ESLintOrTSNode} The AST node that
* can be evaluated for appropriate JSDoc comments. * can be evaluated for appropriate JSDoc comments.
*/ */
const getReducedASTNode = function (node, sourceCode) { const getReducedASTNode = function (node, sourceCode) {
@ -844,7 +835,7 @@ const getReducedASTNode = function (node, sourceCode) {
} }
if (!invokedExpression.has(parent.type)) { if (!invokedExpression.has(parent.type)) {
/** /**
* @type {import('eslint').Rule.Node|Token|null} * @type {ESLintOrTSNode|Token|null}
*/ */
let token = node; let token = node;
do { do {
@ -856,10 +847,12 @@ const getReducedASTNode = function (node, sourceCode) {
if (token && token.type === 'Block') { if (token && token.type === 'Block') {
return node; return node;
} }
if (sourceCode.getCommentsBefore(node).length) { if (sourceCode.getCommentsBefore( /** @type {import('eslint').Rule.Node} */
node).length) {
return node; return node;
} }
while (!sourceCode.getCommentsBefore(parent).length && !/Function/u.test(parent.type) && !allowableCommentNode.has(parent.type)) { while (!sourceCode.getCommentsBefore( /** @type {import('eslint').Rule.Node} */
parent).length && !/Function/u.test(parent.type) && !allowableCommentNode.has(parent.type)) {
({ ({
parent parent
} = parent); } = parent);
@ -883,37 +876,43 @@ const getReducedASTNode = function (node, sourceCode) {
/** /**
* Checks for the presence of a JSDoc comment for the given node and returns it. * Checks for the presence of a JSDoc comment for the given node and returns it.
* *
* @param {import('eslint').Rule.Node} astNode The AST node to get * @param {ESLintOrTSNode} astNode The AST node to get
* the comment for. * the comment for.
* @param {import('eslint').SourceCode} sourceCode * @param {import('eslint').SourceCode} sourceCode
* @param {{maxLines: int, minLines: int, [name: string]: any}} settings * @param {{maxLines: int, minLines: int, [name: string]: any}} settings
* @param {{nonJSDoc?: boolean}} [opts]
* @returns {Token|null} The Block comment token containing the JSDoc comment * @returns {Token|null} The Block comment token containing the JSDoc comment
* for the given node or null if not found. * for the given node or null if not found.
* @private
*/ */
const findJSDocComment = (astNode, sourceCode, settings) => { const findJSDocComment = (astNode, sourceCode, settings, opts = {}) => {
var _parenthesisToken, _parenthesisToken2; var _parenthesisToken, _parenthesisToken2;
const {
nonJSDoc
} = opts;
const { const {
minLines, minLines,
maxLines maxLines
} = settings; } = settings;
/** @type {import('eslint').Rule.Node|import('estree').Comment} */ /** @type {ESLintOrTSNode|import('estree').Comment} */
let currentNode = astNode; let currentNode = astNode;
let tokenBefore = null; let tokenBefore = null;
let parenthesisToken = null; let parenthesisToken = null;
while (currentNode) { while (currentNode) {
const decorator = getDecorator(currentNode); const decorator = getDecorator( /** @type {import('eslint').Rule.Node} */
currentNode);
if (decorator) { if (decorator) {
const dec = /** @type {unknown} */decorator; const dec = /** @type {unknown} */decorator;
currentNode = /** @type {import('eslint').Rule.Node} */dec; currentNode = /** @type {import('eslint').Rule.Node} */dec;
} }
tokenBefore = sourceCode.getTokenBefore(currentNode, { tokenBefore = sourceCode.getTokenBefore( /** @type {import('eslint').Rule.Node} */
currentNode, {
includeComments: true includeComments: true
}); });
if (tokenBefore && tokenBefore.type === 'Punctuator' && tokenBefore.value === '(') { if (tokenBefore && tokenBefore.type === 'Punctuator' && tokenBefore.value === '(') {
parenthesisToken = tokenBefore; parenthesisToken = tokenBefore;
[tokenBefore] = sourceCode.getTokensBefore(currentNode, { [tokenBefore] = sourceCode.getTokensBefore( /** @type {import('eslint').Rule.Node} */
currentNode, {
count: 2, count: 2,
includeComments: true includeComments: true
}); });
@ -921,7 +920,7 @@ const findJSDocComment = (astNode, sourceCode, settings) => {
if (!tokenBefore || !isCommentToken(tokenBefore)) { if (!tokenBefore || !isCommentToken(tokenBefore)) {
return null; return null;
} }
if (tokenBefore.type === 'Line') { if (!nonJSDoc && tokenBefore.type === 'Line') {
currentNode = tokenBefore; currentNode = tokenBefore;
continue; continue;
} }
@ -932,7 +931,7 @@ const findJSDocComment = (astNode, sourceCode, settings) => {
if (!tokenBefore || !currentNode.loc || !tokenBefore.loc) { if (!tokenBefore || !currentNode.loc || !tokenBefore.loc) {
return null; return null;
} }
if (tokenBefore.type === 'Block' && /^\*\s/u.test(tokenBefore.value) && currentNode.loc.start.line - ( /** @type {import('eslint').AST.Token} */(_parenthesisToken = parenthesisToken) !== null && _parenthesisToken !== void 0 ? _parenthesisToken : tokenBefore).loc.end.line >= minLines && currentNode.loc.start.line - ( /** @type {import('eslint').AST.Token} */(_parenthesisToken2 = parenthesisToken) !== null && _parenthesisToken2 !== void 0 ? _parenthesisToken2 : tokenBefore).loc.end.line <= maxLines) { if ((nonJSDoc && (tokenBefore.type !== 'Block' || !/^\*\s/u.test(tokenBefore.value)) || !nonJSDoc && tokenBefore.type === 'Block' && /^\*\s/u.test(tokenBefore.value)) && currentNode.loc.start.line - ( /** @type {import('eslint').AST.Token} */(_parenthesisToken = parenthesisToken) !== null && _parenthesisToken !== void 0 ? _parenthesisToken : tokenBefore).loc.end.line >= minLines && currentNode.loc.start.line - ( /** @type {import('eslint').AST.Token} */(_parenthesisToken2 = parenthesisToken) !== null && _parenthesisToken2 !== void 0 ? _parenthesisToken2 : tokenBefore).loc.end.line <= maxLines) {
return tokenBefore; return tokenBefore;
} }
return null; return null;
@ -956,6 +955,96 @@ const getJSDocComment = function (sourceCode, node, settings) {
return findJSDocComment(reducedNode, sourceCode, settings); return findJSDocComment(reducedNode, sourceCode, settings);
}; };
/**
* Retrieves the comment preceding a given node.
*
* @param {import('eslint').SourceCode} sourceCode The ESLint SourceCode
* @param {ESLintOrTSNode} node The AST node to get
* the comment for.
* @param {{maxLines: int, minLines: int, [name: string]: any}} settings The
* settings in context
* @returns {Token|null} The Block comment
* token containing the JSDoc comment for the given node or
* null if not found.
* @public
*/
const getNonJsdocComment = function (sourceCode, node, settings) {
const reducedNode = getReducedASTNode(node, sourceCode);
return findJSDocComment(reducedNode, sourceCode, settings, {
nonJSDoc: true
});
};
/**
* @param {ESLintOrTSNode|import('eslint').AST.Token|
* import('estree').Comment
* } nodeA The AST node or token to compare
* @param {ESLintOrTSNode|import('eslint').AST.Token|
* import('estree').Comment} nodeB The
* AST node or token to compare
*/
const compareLocEndToStart = (nodeA, nodeB) => {
var _nodeA$loc$end$line, _nodeA$loc, _nodeB$loc$start$line, _nodeB$loc;
/* v8 ignore next */
return ((_nodeA$loc$end$line = (_nodeA$loc = nodeA.loc) === null || _nodeA$loc === void 0 ? void 0 : _nodeA$loc.end.line) !== null && _nodeA$loc$end$line !== void 0 ? _nodeA$loc$end$line : 0) === ((_nodeB$loc$start$line = (_nodeB$loc = nodeB.loc) === null || _nodeB$loc === void 0 ? void 0 : _nodeB$loc.start.line) !== null && _nodeB$loc$start$line !== void 0 ? _nodeB$loc$start$line : 0);
};
/**
* Checks for the presence of a comment following the given node and
* returns it.
*
* This method is experimental.
*
* @param {import('eslint').SourceCode} sourceCode
* @param {ESLintOrTSNode} astNode The AST node to get
* the comment for.
* @returns {Token|null} The comment token containing the comment
* for the given node or null if not found.
*/
const getFollowingComment = function (sourceCode, astNode) {
/**
* @param {ESLintOrTSNode} node The
* AST node to get the comment for.
*/
const getTokensAfterIgnoringSemis = node => {
let tokenAfter = sourceCode.getTokenAfter( /** @type {import('eslint').Rule.Node} */
node, {
includeComments: true
});
while (tokenAfter && tokenAfter.type === 'Punctuator' &&
// tokenAfter.value === ')' // Don't apparently need to ignore
tokenAfter.value === ';') {
[tokenAfter] = sourceCode.getTokensAfter(tokenAfter, {
includeComments: true
});
}
return tokenAfter;
};
/**
* @param {ESLintOrTSNode} node The
* AST node to get the comment for.
*/
const tokenAfterIgnoringSemis = node => {
const tokenAfter = getTokensAfterIgnoringSemis(node);
return tokenAfter && isCommentToken(tokenAfter) && compareLocEndToStart(node, tokenAfter) ? tokenAfter : null;
};
let tokenAfter = tokenAfterIgnoringSemis(astNode);
if (!tokenAfter) {
switch (astNode.type) {
case 'FunctionDeclaration':
tokenAfter = tokenAfterIgnoringSemis( /** @type {ESLintOrTSNode} */
astNode.body);
break;
case 'ExpressionStatement':
tokenAfter = tokenAfterIgnoringSemis( /** @type {ESLintOrTSNode} */
astNode.expression);
break;
}
}
return tokenAfter;
};
/** /**
* @param {RegExpMatchArray & { * @param {RegExpMatchArray & {
* indices: { * indices: {
@ -1227,7 +1316,9 @@ exports.defaultNoTypes = defaultNoTypes;
exports.estreeToString = estreeToString; exports.estreeToString = estreeToString;
exports.findJSDocComment = findJSDocComment; exports.findJSDocComment = findJSDocComment;
exports.getDecorator = getDecorator; exports.getDecorator = getDecorator;
exports.getFollowingComment = getFollowingComment;
exports.getJSDocComment = getJSDocComment; exports.getJSDocComment = getJSDocComment;
exports.getNonJsdocComment = getNonJsdocComment;
exports.getReducedASTNode = getReducedASTNode; exports.getReducedASTNode = getReducedASTNode;
exports.getTokenizers = getTokenizers; exports.getTokenizers = getTokenizers;
exports.hasSeeWithLink = hasSeeWithLink; exports.hasSeeWithLink = hasSeeWithLink;

View file

@ -1,6 +1,6 @@
{ {
"name": "@es-joy/jsdoccomment", "name": "@es-joy/jsdoccomment",
"version": "0.43.1", "version": "0.46.0",
"author": "Brett Zamir <brettz9@yahoo.com>", "author": "Brett Zamir <brettz9@yahoo.com>",
"contributors": [], "contributors": [],
"description": "Maintained replacement for ESLint's deprecated SourceCode#getJSDocComment along with other jsdoc utilities", "description": "Maintained replacement for ESLint's deprecated SourceCode#getJSDocComment along with other jsdoc utilities",
@ -42,25 +42,26 @@
"node": ">=16" "node": ">=16"
}, },
"dependencies": { "dependencies": {
"@types/eslint": "^8.56.5",
"@types/estree": "^1.0.5",
"@typescript-eslint/types": "^7.2.0",
"comment-parser": "1.4.1", "comment-parser": "1.4.1",
"esquery": "^1.5.0", "esquery": "^1.6.0",
"jsdoc-type-pratt-parser": "~4.0.0" "jsdoc-type-pratt-parser": "~4.0.0"
}, },
"devDependencies": { "devDependencies": {
"@babel/core": "^7.23.9", "@babel/core": "^7.24.7",
"@babel/plugin-syntax-class-properties": "^7.12.13", "@babel/plugin-syntax-class-properties": "^7.12.13",
"@babel/preset-env": "^7.23.9", "@babel/preset-env": "^7.24.7",
"@brettz9/eslint-plugin": "^1.0.4", "@brettz9/eslint-plugin": "^1.0.4",
"@rollup/plugin-babel": "^6.0.4", "@rollup/plugin-babel": "^6.0.4",
"@types/esquery": "^1.5.3", "@types/eslint": "^8.56.10",
"@types/esquery": "^1.5.4",
"@types/estraverse": "^5.1.7", "@types/estraverse": "^5.1.7",
"@types/estree": "^1.0.5",
"@typescript-eslint/types": "^7.16.0",
"@typescript-eslint/visitor-keys": "^7.16.0",
"@typhonjs-build-test/esm-d-ts": "0.3.0-next.1", "@typhonjs-build-test/esm-d-ts": "0.3.0-next.1",
"@typhonjs-typedoc/typedoc-pkg": "^0.0.4", "@typhonjs-typedoc/typedoc-pkg": "^0.0.5",
"@vitest/coverage-v8": "^1.3.0", "@vitest/coverage-v8": "^2.0.1",
"@vitest/ui": "^1.3.0", "@vitest/ui": "^2.0.1",
"eslint": "^8.56.0", "eslint": "^8.56.0",
"eslint-config-ash-nazg": "35.3.0", "eslint-config-ash-nazg": "35.3.0",
"eslint-config-standard": "^17.1.0", "eslint-config-standard": "^17.1.0",
@ -77,11 +78,12 @@
"eslint-plugin-promise": "^6.1.1", "eslint-plugin-promise": "^6.1.1",
"eslint-plugin-sonarjs": "^0.23.0", "eslint-plugin-sonarjs": "^0.23.0",
"eslint-plugin-unicorn": "^50.0.1", "eslint-plugin-unicorn": "^50.0.1",
"espree": "^10.0.0", "espree": "^10.1.0",
"estraverse": "^5.3.0", "estraverse": "^5.3.0",
"rollup": "^4.9.6", "rollup": "^4.18.1",
"typescript": "^5.4.2", "typescript": "^5.5.3",
"vitest": "^1.3.0" "typescript-eslint": "^7.16.0",
"vitest": "^2.0.1"
}, },
"files": [ "files": [
"/dist", "/dist",
@ -95,8 +97,9 @@
"eslint": "eslint --ext=js,cjs,md,html .", "eslint": "eslint --ext=js,cjs,md,html .",
"lint": "npm run eslint --", "lint": "npm run eslint --",
"open": "open ./coverage/index.html", "open": "open ./coverage/index.html",
"test": "npm run lint && npm run build && vitest run --coverage", "test": "npm run lint && npm run build && npm run test-ui",
"test-ui": "vitest --ui --coverage", "test-ui": "vitest --ui --coverage",
"test-cov": "vitest --coverage",
"tsc": "tsc", "tsc": "tsc",
"types": "esm-d-ts gen ./src/index.js --output ./dist/index.d.ts" "types": "esm-d-ts gen ./src/index.js --output ./dist/index.d.ts"
} }

View file

@ -33,7 +33,7 @@ const isCommentToken = (token) => {
}; };
/** /**
* @param {(import('estree').Comment|import('eslint').Rule.Node) & { * @param {(ESLintOrTSNode|import('estree').Comment) & {
* declaration?: any, * declaration?: any,
* decorators?: any[], * decorators?: any[],
* parent?: import('eslint').Rule.Node & { * parent?: import('eslint').Rule.Node & {
@ -50,7 +50,7 @@ const getDecorator = (node) => {
/** /**
* Check to see if it is a ES6 export declaration. * Check to see if it is a ES6 export declaration.
* *
* @param {import('eslint').Rule.Node} astNode An AST node. * @param {ESLintOrTSNode} astNode An AST node.
* @returns {boolean} whether the given node represents an export declaration. * @returns {boolean} whether the given node represents an export declaration.
* @private * @private
*/ */
@ -62,8 +62,8 @@ const looksLikeExport = function (astNode) {
}; };
/** /**
* @param {import('eslint').Rule.Node} astNode * @param {ESLintOrTSNode} astNode
* @returns {import('eslint').Rule.Node} * @returns {ESLintOrTSNode}
*/ */
const getTSFunctionComment = function (astNode) { const getTSFunctionComment = function (astNode) {
const {parent} = astNode; const {parent} = astNode;
@ -108,7 +108,6 @@ const getTSFunctionComment = function (astNode) {
} }
return greatGreatGrandparent.parent; return greatGreatGrandparent.parent;
} }
/* v8 ignore next */ /* v8 ignore next */
return astNode; return astNode;
case 'FunctionExpression': case 'FunctionExpression':
@ -116,7 +115,6 @@ const getTSFunctionComment = function (astNode) {
if (!greatGreatGrandparent) { if (!greatGreatGrandparent) {
return astNode; return astNode;
} }
/* v8 ignore next 3 */
if (greatGrandparent.type === 'MethodDefinition') { if (greatGrandparent.type === 'MethodDefinition') {
return greatGrandparent; return greatGrandparent;
} }
@ -134,10 +132,8 @@ const getTSFunctionComment = function (astNode) {
return astNode; return astNode;
} }
/* v8 ignore next */
switch (greatGrandparent.type) { switch (greatGrandparent.type) {
case 'ArrowFunctionExpression': case 'ArrowFunctionExpression':
/* v8 ignore next 6 */
if ( if (
greatGreatGrandparent.type === 'VariableDeclarator' && greatGreatGrandparent.type === 'VariableDeclarator' &&
greatGreatGrandparent.parent.type === 'VariableDeclaration' greatGreatGrandparent.parent.type === 'VariableDeclaration'
@ -145,19 +141,17 @@ const getTSFunctionComment = function (astNode) {
return greatGreatGrandparent.parent; return greatGreatGrandparent.parent;
} }
/* v8 ignore next */
return astNode; return astNode;
case 'FunctionDeclaration': case 'FunctionDeclaration':
return greatGrandparent; return greatGrandparent;
case 'VariableDeclarator': case 'VariableDeclarator':
/* v8 ignore next 3 */
if (greatGreatGrandparent.type === 'VariableDeclaration') { if (greatGreatGrandparent.type === 'VariableDeclaration') {
return greatGreatGrandparent; return greatGreatGrandparent;
} }
/* v8 ignore next 2 */
// Fallthrough // Fallthrough
default: default:
/* v8 ignore next */ /* v8 ignore next 3 */
return astNode; return astNode;
} }
}; };
@ -182,9 +176,9 @@ const allowableCommentNode = new Set([
* Reduces the provided node to the appropriate node for evaluating * Reduces the provided node to the appropriate node for evaluating
* JSDoc comment status. * JSDoc comment status.
* *
* @param {import('eslint').Rule.Node} node An AST node. * @param {ESLintOrTSNode} node An AST node.
* @param {import('eslint').SourceCode} sourceCode The ESLint SourceCode. * @param {import('eslint').SourceCode} sourceCode The ESLint SourceCode.
* @returns {import('eslint').Rule.Node} The AST node that * @returns {ESLintOrTSNode} The AST node that
* can be evaluated for appropriate JSDoc comments. * can be evaluated for appropriate JSDoc comments.
*/ */
const getReducedASTNode = function (node, sourceCode) { const getReducedASTNode = function (node, sourceCode) {
@ -218,7 +212,7 @@ const getReducedASTNode = function (node, sourceCode) {
!invokedExpression.has(parent.type) !invokedExpression.has(parent.type)
) { ) {
/** /**
* @type {import('eslint').Rule.Node|Token|null} * @type {ESLintOrTSNode|Token|null}
*/ */
let token = node; let token = node;
do { do {
@ -229,17 +223,22 @@ const getReducedASTNode = function (node, sourceCode) {
{includeComments: true} {includeComments: true}
); );
} while (token && token.type === 'Punctuator' && token.value === '('); } while (token && token.type === 'Punctuator' && token.value === '(');
if (token && token.type === 'Block') { if (token && token.type === 'Block') {
return node; return node;
} }
if (sourceCode.getCommentsBefore(node).length) { if (sourceCode.getCommentsBefore(
/** @type {import('eslint').Rule.Node} */
(node)
).length) {
return node; return node;
} }
while ( while (
!sourceCode.getCommentsBefore(parent).length && !sourceCode.getCommentsBefore(
/** @type {import('eslint').Rule.Node} */
(parent)
).length &&
!(/Function/u).test(parent.type) && !(/Function/u).test(parent.type) &&
!allowableCommentNode.has(parent.type) !allowableCommentNode.has(parent.type)
) { ) {
@ -270,45 +269,55 @@ const getReducedASTNode = function (node, sourceCode) {
/** /**
* Checks for the presence of a JSDoc comment for the given node and returns it. * Checks for the presence of a JSDoc comment for the given node and returns it.
* *
* @param {import('eslint').Rule.Node} astNode The AST node to get * @param {ESLintOrTSNode} astNode The AST node to get
* the comment for. * the comment for.
* @param {import('eslint').SourceCode} sourceCode * @param {import('eslint').SourceCode} sourceCode
* @param {{maxLines: int, minLines: int, [name: string]: any}} settings * @param {{maxLines: int, minLines: int, [name: string]: any}} settings
* @param {{nonJSDoc?: boolean}} [opts]
* @returns {Token|null} The Block comment token containing the JSDoc comment * @returns {Token|null} The Block comment token containing the JSDoc comment
* for the given node or null if not found. * for the given node or null if not found.
* @private
*/ */
const findJSDocComment = (astNode, sourceCode, settings) => { const findJSDocComment = (astNode, sourceCode, settings, opts = {}) => {
const {nonJSDoc} = opts;
const {minLines, maxLines} = settings; const {minLines, maxLines} = settings;
/** @type {import('eslint').Rule.Node|import('estree').Comment} */ /** @type {ESLintOrTSNode|import('estree').Comment} */
let currentNode = astNode; let currentNode = astNode;
let tokenBefore = null; let tokenBefore = null;
let parenthesisToken = null; let parenthesisToken = null;
while (currentNode) { while (currentNode) {
const decorator = getDecorator(currentNode); const decorator = getDecorator(
/** @type {import('eslint').Rule.Node} */
(currentNode)
);
if (decorator) { if (decorator) {
const dec = /** @type {unknown} */ (decorator); const dec = /** @type {unknown} */ (decorator);
currentNode = /** @type {import('eslint').Rule.Node} */ (dec); currentNode = /** @type {import('eslint').Rule.Node} */ (dec);
} }
tokenBefore = sourceCode.getTokenBefore( tokenBefore = sourceCode.getTokenBefore(
currentNode, {includeComments: true} /** @type {import('eslint').Rule.Node} */
(currentNode),
{includeComments: true}
); );
if ( if (
tokenBefore && tokenBefore.type === 'Punctuator' && tokenBefore && tokenBefore.type === 'Punctuator' &&
tokenBefore.value === '(' tokenBefore.value === '('
) { ) {
parenthesisToken = tokenBefore; parenthesisToken = tokenBefore;
[tokenBefore] = sourceCode.getTokensBefore(currentNode, { [tokenBefore] = sourceCode.getTokensBefore(
/** @type {import('eslint').Rule.Node} */
(currentNode),
{
count: 2, count: 2,
includeComments: true includeComments: true
}); }
);
} }
if (!tokenBefore || !isCommentToken(tokenBefore)) { if (!tokenBefore || !isCommentToken(tokenBefore)) {
return null; return null;
} }
if (tokenBefore.type === 'Line') { if (!nonJSDoc && tokenBefore.type === 'Line') {
currentNode = tokenBefore; currentNode = tokenBefore;
continue; continue;
} }
@ -321,8 +330,12 @@ const findJSDocComment = (astNode, sourceCode, settings) => {
} }
if ( if (
tokenBefore.type === 'Block' && (
(/^\*\s/u).test(tokenBefore.value) && (nonJSDoc && (tokenBefore.type !== 'Block' ||
!(/^\*\s/u).test(tokenBefore.value))) ||
(!nonJSDoc && tokenBefore.type === 'Block' &&
(/^\*\s/u).test(tokenBefore.value))
) &&
currentNode.loc.start.line - ( currentNode.loc.start.line - (
/** @type {import('eslint').AST.Token} */ /** @type {import('eslint').AST.Token} */
(parenthesisToken ?? tokenBefore) (parenthesisToken ?? tokenBefore)
@ -357,6 +370,118 @@ const getJSDocComment = function (sourceCode, node, settings) {
return findJSDocComment(reducedNode, sourceCode, settings); return findJSDocComment(reducedNode, sourceCode, settings);
}; };
export { /**
getReducedASTNode, getJSDocComment, getDecorator, findJSDocComment * Retrieves the comment preceding a given node.
*
* @param {import('eslint').SourceCode} sourceCode The ESLint SourceCode
* @param {ESLintOrTSNode} node The AST node to get
* the comment for.
* @param {{maxLines: int, minLines: int, [name: string]: any}} settings The
* settings in context
* @returns {Token|null} The Block comment
* token containing the JSDoc comment for the given node or
* null if not found.
* @public
*/
const getNonJsdocComment = function (sourceCode, node, settings) {
const reducedNode = getReducedASTNode(node, sourceCode);
return findJSDocComment(reducedNode, sourceCode, settings, {
nonJSDoc: true
});
};
/**
* @param {ESLintOrTSNode|import('eslint').AST.Token|
* import('estree').Comment
* } nodeA The AST node or token to compare
* @param {ESLintOrTSNode|import('eslint').AST.Token|
* import('estree').Comment} nodeB The
* AST node or token to compare
*/
const compareLocEndToStart = (nodeA, nodeB) => {
/* v8 ignore next */
return (nodeA.loc?.end.line ?? 0) === (nodeB.loc?.start.line ?? 0);
};
/**
* Checks for the presence of a comment following the given node and
* returns it.
*
* This method is experimental.
*
* @param {import('eslint').SourceCode} sourceCode
* @param {ESLintOrTSNode} astNode The AST node to get
* the comment for.
* @returns {Token|null} The comment token containing the comment
* for the given node or null if not found.
*/
const getFollowingComment = function (sourceCode, astNode) {
/**
* @param {ESLintOrTSNode} node The
* AST node to get the comment for.
*/
const getTokensAfterIgnoringSemis = (node) => {
let tokenAfter = sourceCode.getTokenAfter(
/** @type {import('eslint').Rule.Node} */
(node),
{includeComments: true}
);
while (
tokenAfter && tokenAfter.type === 'Punctuator' &&
// tokenAfter.value === ')' // Don't apparently need to ignore
tokenAfter.value === ';'
) {
[tokenAfter] = sourceCode.getTokensAfter(tokenAfter, {
includeComments: true
});
}
return tokenAfter;
};
/**
* @param {ESLintOrTSNode} node The
* AST node to get the comment for.
*/
const tokenAfterIgnoringSemis = (node) => {
const tokenAfter = getTokensAfterIgnoringSemis(node);
return (
tokenAfter &&
isCommentToken(tokenAfter) &&
compareLocEndToStart(node, tokenAfter)
)
? tokenAfter
: null;
};
let tokenAfter = tokenAfterIgnoringSemis(astNode);
if (!tokenAfter) {
switch (astNode.type) {
case 'FunctionDeclaration':
tokenAfter = tokenAfterIgnoringSemis(
/** @type {ESLintOrTSNode} */
(astNode.body)
);
break;
case 'ExpressionStatement':
tokenAfter = tokenAfterIgnoringSemis(
/** @type {ESLintOrTSNode} */
(astNode.expression)
);
break;
/* v8 ignore next 3 */
default:
break;
}
}
return tokenAfter;
};
export {
getReducedASTNode, getJSDocComment, getNonJsdocComment,
getDecorator, findJSDocComment, getFollowingComment
}; };

View file

@ -1,6 +1,6 @@
{ {
"name": "@eslint/js", "name": "@eslint/js",
"version": "9.6.0", "version": "9.7.0",
"description": "ESLint JavaScript language implementation", "description": "ESLint JavaScript language implementation",
"main": "./src/index.js", "main": "./src/index.js",
"scripts": {}, "scripts": {},

View file

@ -8,6 +8,42 @@ for (let i = 0; i < chars.length; i++) {
intToChar[i] = c; intToChar[i] = c;
charToInt[c] = i; charToInt[c] = i;
} }
function decodeInteger(reader, relative) {
let value = 0;
let shift = 0;
let integer = 0;
do {
const c = reader.next();
integer = charToInt[c];
value |= (integer & 31) << shift;
shift += 5;
} while (integer & 32);
const shouldNegate = value & 1;
value >>>= 1;
if (shouldNegate) {
value = -0x80000000 | -value;
}
return relative + value;
}
function encodeInteger(builder, num, relative) {
let delta = num - relative;
delta = delta < 0 ? (-delta << 1) | 1 : delta << 1;
do {
let clamped = delta & 0b011111;
delta >>>= 5;
if (delta > 0)
clamped |= 0b100000;
builder.write(intToChar[clamped]);
} while (delta > 0);
return num;
}
function hasMoreVlq(reader, max) {
if (reader.pos >= max)
return false;
return reader.peek() !== comma;
}
const bufLength = 1024 * 16;
// Provide a fallback for older environments. // Provide a fallback for older environments.
const td = typeof TextDecoder !== 'undefined' const td = typeof TextDecoder !== 'undefined'
? /* #__PURE__ */ new TextDecoder() ? /* #__PURE__ */ new TextDecoder()
@ -27,74 +63,326 @@ const td = typeof TextDecoder !== 'undefined'
return out; return out;
}, },
}; };
function decode(mappings) { class StringWriter {
const state = new Int32Array(5); constructor() {
const decoded = []; this.pos = 0;
let index = 0; this.out = '';
this.buffer = new Uint8Array(bufLength);
}
write(v) {
const { buffer } = this;
buffer[this.pos++] = v;
if (this.pos === bufLength) {
this.out += td.decode(buffer);
this.pos = 0;
}
}
flush() {
const { buffer, out, pos } = this;
return pos > 0 ? out + td.decode(buffer.subarray(0, pos)) : out;
}
}
class StringReader {
constructor(buffer) {
this.pos = 0;
this.buffer = buffer;
}
next() {
return this.buffer.charCodeAt(this.pos++);
}
peek() {
return this.buffer.charCodeAt(this.pos);
}
indexOf(char) {
const { buffer, pos } = this;
const idx = buffer.indexOf(char, pos);
return idx === -1 ? buffer.length : idx;
}
}
const EMPTY = [];
function decodeOriginalScopes(input) {
const { length } = input;
const reader = new StringReader(input);
const scopes = [];
const stack = [];
let line = 0;
for (; reader.pos < length; reader.pos++) {
line = decodeInteger(reader, line);
const column = decodeInteger(reader, 0);
if (!hasMoreVlq(reader, length)) {
const last = stack.pop();
last[2] = line;
last[3] = column;
continue;
}
const kind = decodeInteger(reader, 0);
const fields = decodeInteger(reader, 0);
const hasName = fields & 0b0001;
const scope = (hasName ? [line, column, 0, 0, kind, decodeInteger(reader, 0)] : [line, column, 0, 0, kind]);
let vars = EMPTY;
if (hasMoreVlq(reader, length)) {
vars = [];
do { do {
const semi = indexOf(mappings, index); const varsIndex = decodeInteger(reader, 0);
vars.push(varsIndex);
} while (hasMoreVlq(reader, length));
}
scope.vars = vars;
scopes.push(scope);
stack.push(scope);
}
return scopes;
}
function encodeOriginalScopes(scopes) {
const writer = new StringWriter();
for (let i = 0; i < scopes.length;) {
i = _encodeOriginalScopes(scopes, i, writer, [0]);
}
return writer.flush();
}
function _encodeOriginalScopes(scopes, index, writer, state) {
const scope = scopes[index];
const { 0: startLine, 1: startColumn, 2: endLine, 3: endColumn, 4: kind, vars } = scope;
if (index > 0)
writer.write(comma);
state[0] = encodeInteger(writer, startLine, state[0]);
encodeInteger(writer, startColumn, 0);
encodeInteger(writer, kind, 0);
const fields = scope.length === 6 ? 0b0001 : 0;
encodeInteger(writer, fields, 0);
if (scope.length === 6)
encodeInteger(writer, scope[5], 0);
for (const v of vars) {
encodeInteger(writer, v, 0);
}
for (index++; index < scopes.length;) {
const next = scopes[index];
const { 0: l, 1: c } = next;
if (l > endLine || (l === endLine && c >= endColumn)) {
break;
}
index = _encodeOriginalScopes(scopes, index, writer, state);
}
writer.write(comma);
state[0] = encodeInteger(writer, endLine, state[0]);
encodeInteger(writer, endColumn, 0);
return index;
}
function decodeGeneratedRanges(input) {
const { length } = input;
const reader = new StringReader(input);
const ranges = [];
const stack = [];
let genLine = 0;
let definitionSourcesIndex = 0;
let definitionScopeIndex = 0;
let callsiteSourcesIndex = 0;
let callsiteLine = 0;
let callsiteColumn = 0;
let bindingLine = 0;
let bindingColumn = 0;
do {
const semi = reader.indexOf(';');
let genColumn = 0;
for (; reader.pos < semi; reader.pos++) {
genColumn = decodeInteger(reader, genColumn);
if (!hasMoreVlq(reader, semi)) {
const last = stack.pop();
last[2] = genLine;
last[3] = genColumn;
continue;
}
const fields = decodeInteger(reader, 0);
const hasDefinition = fields & 0b0001;
const hasCallsite = fields & 0b0010;
const hasScope = fields & 0b0100;
let callsite = null;
let bindings = EMPTY;
let range;
if (hasDefinition) {
const defSourcesIndex = decodeInteger(reader, definitionSourcesIndex);
definitionScopeIndex = decodeInteger(reader, definitionSourcesIndex === defSourcesIndex ? definitionScopeIndex : 0);
definitionSourcesIndex = defSourcesIndex;
range = [genLine, genColumn, 0, 0, defSourcesIndex, definitionScopeIndex];
}
else {
range = [genLine, genColumn, 0, 0];
}
range.isScope = !!hasScope;
if (hasCallsite) {
const prevCsi = callsiteSourcesIndex;
const prevLine = callsiteLine;
callsiteSourcesIndex = decodeInteger(reader, callsiteSourcesIndex);
const sameSource = prevCsi === callsiteSourcesIndex;
callsiteLine = decodeInteger(reader, sameSource ? callsiteLine : 0);
callsiteColumn = decodeInteger(reader, sameSource && prevLine === callsiteLine ? callsiteColumn : 0);
callsite = [callsiteSourcesIndex, callsiteLine, callsiteColumn];
}
range.callsite = callsite;
if (hasMoreVlq(reader, semi)) {
bindings = [];
do {
bindingLine = genLine;
bindingColumn = genColumn;
const expressionsCount = decodeInteger(reader, 0);
let expressionRanges;
if (expressionsCount < -1) {
expressionRanges = [[decodeInteger(reader, 0)]];
for (let i = -1; i > expressionsCount; i--) {
const prevBl = bindingLine;
bindingLine = decodeInteger(reader, bindingLine);
bindingColumn = decodeInteger(reader, bindingLine === prevBl ? bindingColumn : 0);
const expression = decodeInteger(reader, 0);
expressionRanges.push([expression, bindingLine, bindingColumn]);
}
}
else {
expressionRanges = [[expressionsCount]];
}
bindings.push(expressionRanges);
} while (hasMoreVlq(reader, semi));
}
range.bindings = bindings;
ranges.push(range);
stack.push(range);
}
genLine++;
reader.pos = semi + 1;
} while (reader.pos < length);
return ranges;
}
function encodeGeneratedRanges(ranges) {
if (ranges.length === 0)
return '';
const writer = new StringWriter();
for (let i = 0; i < ranges.length;) {
i = _encodeGeneratedRanges(ranges, i, writer, [0, 0, 0, 0, 0, 0, 0]);
}
return writer.flush();
}
function _encodeGeneratedRanges(ranges, index, writer, state) {
const range = ranges[index];
const { 0: startLine, 1: startColumn, 2: endLine, 3: endColumn, isScope, callsite, bindings, } = range;
if (state[0] < startLine) {
catchupLine(writer, state[0], startLine);
state[0] = startLine;
state[1] = 0;
}
else if (index > 0) {
writer.write(comma);
}
state[1] = encodeInteger(writer, range[1], state[1]);
const fields = (range.length === 6 ? 0b0001 : 0) | (callsite ? 0b0010 : 0) | (isScope ? 0b0100 : 0);
encodeInteger(writer, fields, 0);
if (range.length === 6) {
const { 4: sourcesIndex, 5: scopesIndex } = range;
if (sourcesIndex !== state[2]) {
state[3] = 0;
}
state[2] = encodeInteger(writer, sourcesIndex, state[2]);
state[3] = encodeInteger(writer, scopesIndex, state[3]);
}
if (callsite) {
const { 0: sourcesIndex, 1: callLine, 2: callColumn } = range.callsite;
if (sourcesIndex !== state[4]) {
state[5] = 0;
state[6] = 0;
}
else if (callLine !== state[5]) {
state[6] = 0;
}
state[4] = encodeInteger(writer, sourcesIndex, state[4]);
state[5] = encodeInteger(writer, callLine, state[5]);
state[6] = encodeInteger(writer, callColumn, state[6]);
}
if (bindings) {
for (const binding of bindings) {
if (binding.length > 1)
encodeInteger(writer, -binding.length, 0);
const expression = binding[0][0];
encodeInteger(writer, expression, 0);
let bindingStartLine = startLine;
let bindingStartColumn = startColumn;
for (let i = 1; i < binding.length; i++) {
const expRange = binding[i];
bindingStartLine = encodeInteger(writer, expRange[1], bindingStartLine);
bindingStartColumn = encodeInteger(writer, expRange[2], bindingStartColumn);
encodeInteger(writer, expRange[0], 0);
}
}
}
for (index++; index < ranges.length;) {
const next = ranges[index];
const { 0: l, 1: c } = next;
if (l > endLine || (l === endLine && c >= endColumn)) {
break;
}
index = _encodeGeneratedRanges(ranges, index, writer, state);
}
if (state[0] < endLine) {
catchupLine(writer, state[0], endLine);
state[0] = endLine;
state[1] = 0;
}
else {
writer.write(comma);
}
state[1] = encodeInteger(writer, endColumn, state[1]);
return index;
}
function catchupLine(writer, lastLine, line) {
do {
writer.write(semicolon);
} while (++lastLine < line);
}
function decode(mappings) {
const { length } = mappings;
const reader = new StringReader(mappings);
const decoded = [];
let genColumn = 0;
let sourcesIndex = 0;
let sourceLine = 0;
let sourceColumn = 0;
let namesIndex = 0;
do {
const semi = reader.indexOf(';');
const line = []; const line = [];
let sorted = true; let sorted = true;
let lastCol = 0; let lastCol = 0;
state[0] = 0; genColumn = 0;
for (let i = index; i < semi; i++) { while (reader.pos < semi) {
let seg; let seg;
i = decodeInteger(mappings, i, state, 0); // genColumn genColumn = decodeInteger(reader, genColumn);
const col = state[0]; if (genColumn < lastCol)
if (col < lastCol)
sorted = false; sorted = false;
lastCol = col; lastCol = genColumn;
if (hasMoreVlq(mappings, i, semi)) { if (hasMoreVlq(reader, semi)) {
i = decodeInteger(mappings, i, state, 1); // sourcesIndex sourcesIndex = decodeInteger(reader, sourcesIndex);
i = decodeInteger(mappings, i, state, 2); // sourceLine sourceLine = decodeInteger(reader, sourceLine);
i = decodeInteger(mappings, i, state, 3); // sourceColumn sourceColumn = decodeInteger(reader, sourceColumn);
if (hasMoreVlq(mappings, i, semi)) { if (hasMoreVlq(reader, semi)) {
i = decodeInteger(mappings, i, state, 4); // namesIndex namesIndex = decodeInteger(reader, namesIndex);
seg = [col, state[1], state[2], state[3], state[4]]; seg = [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex];
} }
else { else {
seg = [col, state[1], state[2], state[3]]; seg = [genColumn, sourcesIndex, sourceLine, sourceColumn];
} }
} }
else { else {
seg = [col]; seg = [genColumn];
} }
line.push(seg); line.push(seg);
reader.pos++;
} }
if (!sorted) if (!sorted)
sort(line); sort(line);
decoded.push(line); decoded.push(line);
index = semi + 1; reader.pos = semi + 1;
} while (index <= mappings.length); } while (reader.pos <= length);
return decoded; return decoded;
} }
function indexOf(mappings, index) {
const idx = mappings.indexOf(';', index);
return idx === -1 ? mappings.length : idx;
}
function decodeInteger(mappings, pos, state, j) {
let value = 0;
let shift = 0;
let integer = 0;
do {
const c = mappings.charCodeAt(pos++);
integer = charToInt[c];
value |= (integer & 31) << shift;
shift += 5;
} while (integer & 32);
const shouldNegate = value & 1;
value >>>= 1;
if (shouldNegate) {
value = -0x80000000 | -value;
}
state[j] += value;
return pos;
}
function hasMoreVlq(mappings, i, length) {
if (i >= length)
return false;
return mappings.charCodeAt(i) !== comma;
}
function sort(line) { function sort(line) {
line.sort(sortComparator); line.sort(sortComparator);
} }
@ -102,63 +390,35 @@ function sortComparator(a, b) {
return a[0] - b[0]; return a[0] - b[0];
} }
function encode(decoded) { function encode(decoded) {
const state = new Int32Array(5); const writer = new StringWriter();
const bufLength = 1024 * 16; let sourcesIndex = 0;
const subLength = bufLength - 36; let sourceLine = 0;
const buf = new Uint8Array(bufLength); let sourceColumn = 0;
const sub = buf.subarray(0, subLength); let namesIndex = 0;
let pos = 0;
let out = '';
for (let i = 0; i < decoded.length; i++) { for (let i = 0; i < decoded.length; i++) {
const line = decoded[i]; const line = decoded[i];
if (i > 0) { if (i > 0)
if (pos === bufLength) { writer.write(semicolon);
out += td.decode(buf);
pos = 0;
}
buf[pos++] = semicolon;
}
if (line.length === 0) if (line.length === 0)
continue; continue;
state[0] = 0; let genColumn = 0;
for (let j = 0; j < line.length; j++) { for (let j = 0; j < line.length; j++) {
const segment = line[j]; const segment = line[j];
// We can push up to 5 ints, each int can take at most 7 chars, and we
// may push a comma.
if (pos > subLength) {
out += td.decode(sub);
buf.copyWithin(0, subLength, pos);
pos -= subLength;
}
if (j > 0) if (j > 0)
buf[pos++] = comma; writer.write(comma);
pos = encodeInteger(buf, pos, state, segment, 0); // genColumn genColumn = encodeInteger(writer, segment[0], genColumn);
if (segment.length === 1) if (segment.length === 1)
continue; continue;
pos = encodeInteger(buf, pos, state, segment, 1); // sourcesIndex sourcesIndex = encodeInteger(writer, segment[1], sourcesIndex);
pos = encodeInteger(buf, pos, state, segment, 2); // sourceLine sourceLine = encodeInteger(writer, segment[2], sourceLine);
pos = encodeInteger(buf, pos, state, segment, 3); // sourceColumn sourceColumn = encodeInteger(writer, segment[3], sourceColumn);
if (segment.length === 4) if (segment.length === 4)
continue; continue;
pos = encodeInteger(buf, pos, state, segment, 4); // namesIndex namesIndex = encodeInteger(writer, segment[4], namesIndex);
} }
} }
return out + td.decode(buf.subarray(0, pos)); return writer.flush();
}
function encodeInteger(buf, pos, state, segment, j) {
const next = segment[j];
let num = next - state[j];
state[j] = next;
num = num < 0 ? (-num << 1) | 1 : num << 1;
do {
let clamped = num & 0b011111;
num >>>= 5;
if (num > 0)
clamped |= 0b100000;
buf[pos++] = intToChar[clamped];
} while (num > 0);
return pos;
} }
export { decode, encode }; export { decode, decodeGeneratedRanges, decodeOriginalScopes, encode, encodeGeneratedRanges, encodeOriginalScopes };
//# sourceMappingURL=sourcemap-codec.mjs.map //# sourceMappingURL=sourcemap-codec.mjs.map

View file

@ -14,6 +14,42 @@
intToChar[i] = c; intToChar[i] = c;
charToInt[c] = i; charToInt[c] = i;
} }
function decodeInteger(reader, relative) {
let value = 0;
let shift = 0;
let integer = 0;
do {
const c = reader.next();
integer = charToInt[c];
value |= (integer & 31) << shift;
shift += 5;
} while (integer & 32);
const shouldNegate = value & 1;
value >>>= 1;
if (shouldNegate) {
value = -0x80000000 | -value;
}
return relative + value;
}
function encodeInteger(builder, num, relative) {
let delta = num - relative;
delta = delta < 0 ? (-delta << 1) | 1 : delta << 1;
do {
let clamped = delta & 0b011111;
delta >>>= 5;
if (delta > 0)
clamped |= 0b100000;
builder.write(intToChar[clamped]);
} while (delta > 0);
return num;
}
function hasMoreVlq(reader, max) {
if (reader.pos >= max)
return false;
return reader.peek() !== comma;
}
const bufLength = 1024 * 16;
// Provide a fallback for older environments. // Provide a fallback for older environments.
const td = typeof TextDecoder !== 'undefined' const td = typeof TextDecoder !== 'undefined'
? /* #__PURE__ */ new TextDecoder() ? /* #__PURE__ */ new TextDecoder()
@ -33,74 +69,326 @@
return out; return out;
}, },
}; };
function decode(mappings) { class StringWriter {
const state = new Int32Array(5); constructor() {
const decoded = []; this.pos = 0;
let index = 0; this.out = '';
this.buffer = new Uint8Array(bufLength);
}
write(v) {
const { buffer } = this;
buffer[this.pos++] = v;
if (this.pos === bufLength) {
this.out += td.decode(buffer);
this.pos = 0;
}
}
flush() {
const { buffer, out, pos } = this;
return pos > 0 ? out + td.decode(buffer.subarray(0, pos)) : out;
}
}
class StringReader {
constructor(buffer) {
this.pos = 0;
this.buffer = buffer;
}
next() {
return this.buffer.charCodeAt(this.pos++);
}
peek() {
return this.buffer.charCodeAt(this.pos);
}
indexOf(char) {
const { buffer, pos } = this;
const idx = buffer.indexOf(char, pos);
return idx === -1 ? buffer.length : idx;
}
}
const EMPTY = [];
function decodeOriginalScopes(input) {
const { length } = input;
const reader = new StringReader(input);
const scopes = [];
const stack = [];
let line = 0;
for (; reader.pos < length; reader.pos++) {
line = decodeInteger(reader, line);
const column = decodeInteger(reader, 0);
if (!hasMoreVlq(reader, length)) {
const last = stack.pop();
last[2] = line;
last[3] = column;
continue;
}
const kind = decodeInteger(reader, 0);
const fields = decodeInteger(reader, 0);
const hasName = fields & 0b0001;
const scope = (hasName ? [line, column, 0, 0, kind, decodeInteger(reader, 0)] : [line, column, 0, 0, kind]);
let vars = EMPTY;
if (hasMoreVlq(reader, length)) {
vars = [];
do { do {
const semi = indexOf(mappings, index); const varsIndex = decodeInteger(reader, 0);
vars.push(varsIndex);
} while (hasMoreVlq(reader, length));
}
scope.vars = vars;
scopes.push(scope);
stack.push(scope);
}
return scopes;
}
function encodeOriginalScopes(scopes) {
const writer = new StringWriter();
for (let i = 0; i < scopes.length;) {
i = _encodeOriginalScopes(scopes, i, writer, [0]);
}
return writer.flush();
}
function _encodeOriginalScopes(scopes, index, writer, state) {
const scope = scopes[index];
const { 0: startLine, 1: startColumn, 2: endLine, 3: endColumn, 4: kind, vars } = scope;
if (index > 0)
writer.write(comma);
state[0] = encodeInteger(writer, startLine, state[0]);
encodeInteger(writer, startColumn, 0);
encodeInteger(writer, kind, 0);
const fields = scope.length === 6 ? 0b0001 : 0;
encodeInteger(writer, fields, 0);
if (scope.length === 6)
encodeInteger(writer, scope[5], 0);
for (const v of vars) {
encodeInteger(writer, v, 0);
}
for (index++; index < scopes.length;) {
const next = scopes[index];
const { 0: l, 1: c } = next;
if (l > endLine || (l === endLine && c >= endColumn)) {
break;
}
index = _encodeOriginalScopes(scopes, index, writer, state);
}
writer.write(comma);
state[0] = encodeInteger(writer, endLine, state[0]);
encodeInteger(writer, endColumn, 0);
return index;
}
function decodeGeneratedRanges(input) {
const { length } = input;
const reader = new StringReader(input);
const ranges = [];
const stack = [];
let genLine = 0;
let definitionSourcesIndex = 0;
let definitionScopeIndex = 0;
let callsiteSourcesIndex = 0;
let callsiteLine = 0;
let callsiteColumn = 0;
let bindingLine = 0;
let bindingColumn = 0;
do {
const semi = reader.indexOf(';');
let genColumn = 0;
for (; reader.pos < semi; reader.pos++) {
genColumn = decodeInteger(reader, genColumn);
if (!hasMoreVlq(reader, semi)) {
const last = stack.pop();
last[2] = genLine;
last[3] = genColumn;
continue;
}
const fields = decodeInteger(reader, 0);
const hasDefinition = fields & 0b0001;
const hasCallsite = fields & 0b0010;
const hasScope = fields & 0b0100;
let callsite = null;
let bindings = EMPTY;
let range;
if (hasDefinition) {
const defSourcesIndex = decodeInteger(reader, definitionSourcesIndex);
definitionScopeIndex = decodeInteger(reader, definitionSourcesIndex === defSourcesIndex ? definitionScopeIndex : 0);
definitionSourcesIndex = defSourcesIndex;
range = [genLine, genColumn, 0, 0, defSourcesIndex, definitionScopeIndex];
}
else {
range = [genLine, genColumn, 0, 0];
}
range.isScope = !!hasScope;
if (hasCallsite) {
const prevCsi = callsiteSourcesIndex;
const prevLine = callsiteLine;
callsiteSourcesIndex = decodeInteger(reader, callsiteSourcesIndex);
const sameSource = prevCsi === callsiteSourcesIndex;
callsiteLine = decodeInteger(reader, sameSource ? callsiteLine : 0);
callsiteColumn = decodeInteger(reader, sameSource && prevLine === callsiteLine ? callsiteColumn : 0);
callsite = [callsiteSourcesIndex, callsiteLine, callsiteColumn];
}
range.callsite = callsite;
if (hasMoreVlq(reader, semi)) {
bindings = [];
do {
bindingLine = genLine;
bindingColumn = genColumn;
const expressionsCount = decodeInteger(reader, 0);
let expressionRanges;
if (expressionsCount < -1) {
expressionRanges = [[decodeInteger(reader, 0)]];
for (let i = -1; i > expressionsCount; i--) {
const prevBl = bindingLine;
bindingLine = decodeInteger(reader, bindingLine);
bindingColumn = decodeInteger(reader, bindingLine === prevBl ? bindingColumn : 0);
const expression = decodeInteger(reader, 0);
expressionRanges.push([expression, bindingLine, bindingColumn]);
}
}
else {
expressionRanges = [[expressionsCount]];
}
bindings.push(expressionRanges);
} while (hasMoreVlq(reader, semi));
}
range.bindings = bindings;
ranges.push(range);
stack.push(range);
}
genLine++;
reader.pos = semi + 1;
} while (reader.pos < length);
return ranges;
}
function encodeGeneratedRanges(ranges) {
if (ranges.length === 0)
return '';
const writer = new StringWriter();
for (let i = 0; i < ranges.length;) {
i = _encodeGeneratedRanges(ranges, i, writer, [0, 0, 0, 0, 0, 0, 0]);
}
return writer.flush();
}
function _encodeGeneratedRanges(ranges, index, writer, state) {
const range = ranges[index];
const { 0: startLine, 1: startColumn, 2: endLine, 3: endColumn, isScope, callsite, bindings, } = range;
if (state[0] < startLine) {
catchupLine(writer, state[0], startLine);
state[0] = startLine;
state[1] = 0;
}
else if (index > 0) {
writer.write(comma);
}
state[1] = encodeInteger(writer, range[1], state[1]);
const fields = (range.length === 6 ? 0b0001 : 0) | (callsite ? 0b0010 : 0) | (isScope ? 0b0100 : 0);
encodeInteger(writer, fields, 0);
if (range.length === 6) {
const { 4: sourcesIndex, 5: scopesIndex } = range;
if (sourcesIndex !== state[2]) {
state[3] = 0;
}
state[2] = encodeInteger(writer, sourcesIndex, state[2]);
state[3] = encodeInteger(writer, scopesIndex, state[3]);
}
if (callsite) {
const { 0: sourcesIndex, 1: callLine, 2: callColumn } = range.callsite;
if (sourcesIndex !== state[4]) {
state[5] = 0;
state[6] = 0;
}
else if (callLine !== state[5]) {
state[6] = 0;
}
state[4] = encodeInteger(writer, sourcesIndex, state[4]);
state[5] = encodeInteger(writer, callLine, state[5]);
state[6] = encodeInteger(writer, callColumn, state[6]);
}
if (bindings) {
for (const binding of bindings) {
if (binding.length > 1)
encodeInteger(writer, -binding.length, 0);
const expression = binding[0][0];
encodeInteger(writer, expression, 0);
let bindingStartLine = startLine;
let bindingStartColumn = startColumn;
for (let i = 1; i < binding.length; i++) {
const expRange = binding[i];
bindingStartLine = encodeInteger(writer, expRange[1], bindingStartLine);
bindingStartColumn = encodeInteger(writer, expRange[2], bindingStartColumn);
encodeInteger(writer, expRange[0], 0);
}
}
}
for (index++; index < ranges.length;) {
const next = ranges[index];
const { 0: l, 1: c } = next;
if (l > endLine || (l === endLine && c >= endColumn)) {
break;
}
index = _encodeGeneratedRanges(ranges, index, writer, state);
}
if (state[0] < endLine) {
catchupLine(writer, state[0], endLine);
state[0] = endLine;
state[1] = 0;
}
else {
writer.write(comma);
}
state[1] = encodeInteger(writer, endColumn, state[1]);
return index;
}
function catchupLine(writer, lastLine, line) {
do {
writer.write(semicolon);
} while (++lastLine < line);
}
function decode(mappings) {
const { length } = mappings;
const reader = new StringReader(mappings);
const decoded = [];
let genColumn = 0;
let sourcesIndex = 0;
let sourceLine = 0;
let sourceColumn = 0;
let namesIndex = 0;
do {
const semi = reader.indexOf(';');
const line = []; const line = [];
let sorted = true; let sorted = true;
let lastCol = 0; let lastCol = 0;
state[0] = 0; genColumn = 0;
for (let i = index; i < semi; i++) { while (reader.pos < semi) {
let seg; let seg;
i = decodeInteger(mappings, i, state, 0); // genColumn genColumn = decodeInteger(reader, genColumn);
const col = state[0]; if (genColumn < lastCol)
if (col < lastCol)
sorted = false; sorted = false;
lastCol = col; lastCol = genColumn;
if (hasMoreVlq(mappings, i, semi)) { if (hasMoreVlq(reader, semi)) {
i = decodeInteger(mappings, i, state, 1); // sourcesIndex sourcesIndex = decodeInteger(reader, sourcesIndex);
i = decodeInteger(mappings, i, state, 2); // sourceLine sourceLine = decodeInteger(reader, sourceLine);
i = decodeInteger(mappings, i, state, 3); // sourceColumn sourceColumn = decodeInteger(reader, sourceColumn);
if (hasMoreVlq(mappings, i, semi)) { if (hasMoreVlq(reader, semi)) {
i = decodeInteger(mappings, i, state, 4); // namesIndex namesIndex = decodeInteger(reader, namesIndex);
seg = [col, state[1], state[2], state[3], state[4]]; seg = [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex];
} }
else { else {
seg = [col, state[1], state[2], state[3]]; seg = [genColumn, sourcesIndex, sourceLine, sourceColumn];
} }
} }
else { else {
seg = [col]; seg = [genColumn];
} }
line.push(seg); line.push(seg);
reader.pos++;
} }
if (!sorted) if (!sorted)
sort(line); sort(line);
decoded.push(line); decoded.push(line);
index = semi + 1; reader.pos = semi + 1;
} while (index <= mappings.length); } while (reader.pos <= length);
return decoded; return decoded;
} }
function indexOf(mappings, index) {
const idx = mappings.indexOf(';', index);
return idx === -1 ? mappings.length : idx;
}
function decodeInteger(mappings, pos, state, j) {
let value = 0;
let shift = 0;
let integer = 0;
do {
const c = mappings.charCodeAt(pos++);
integer = charToInt[c];
value |= (integer & 31) << shift;
shift += 5;
} while (integer & 32);
const shouldNegate = value & 1;
value >>>= 1;
if (shouldNegate) {
value = -0x80000000 | -value;
}
state[j] += value;
return pos;
}
function hasMoreVlq(mappings, i, length) {
if (i >= length)
return false;
return mappings.charCodeAt(i) !== comma;
}
function sort(line) { function sort(line) {
line.sort(sortComparator); line.sort(sortComparator);
} }
@ -108,66 +396,42 @@
return a[0] - b[0]; return a[0] - b[0];
} }
function encode(decoded) { function encode(decoded) {
const state = new Int32Array(5); const writer = new StringWriter();
const bufLength = 1024 * 16; let sourcesIndex = 0;
const subLength = bufLength - 36; let sourceLine = 0;
const buf = new Uint8Array(bufLength); let sourceColumn = 0;
const sub = buf.subarray(0, subLength); let namesIndex = 0;
let pos = 0;
let out = '';
for (let i = 0; i < decoded.length; i++) { for (let i = 0; i < decoded.length; i++) {
const line = decoded[i]; const line = decoded[i];
if (i > 0) { if (i > 0)
if (pos === bufLength) { writer.write(semicolon);
out += td.decode(buf);
pos = 0;
}
buf[pos++] = semicolon;
}
if (line.length === 0) if (line.length === 0)
continue; continue;
state[0] = 0; let genColumn = 0;
for (let j = 0; j < line.length; j++) { for (let j = 0; j < line.length; j++) {
const segment = line[j]; const segment = line[j];
// We can push up to 5 ints, each int can take at most 7 chars, and we
// may push a comma.
if (pos > subLength) {
out += td.decode(sub);
buf.copyWithin(0, subLength, pos);
pos -= subLength;
}
if (j > 0) if (j > 0)
buf[pos++] = comma; writer.write(comma);
pos = encodeInteger(buf, pos, state, segment, 0); // genColumn genColumn = encodeInteger(writer, segment[0], genColumn);
if (segment.length === 1) if (segment.length === 1)
continue; continue;
pos = encodeInteger(buf, pos, state, segment, 1); // sourcesIndex sourcesIndex = encodeInteger(writer, segment[1], sourcesIndex);
pos = encodeInteger(buf, pos, state, segment, 2); // sourceLine sourceLine = encodeInteger(writer, segment[2], sourceLine);
pos = encodeInteger(buf, pos, state, segment, 3); // sourceColumn sourceColumn = encodeInteger(writer, segment[3], sourceColumn);
if (segment.length === 4) if (segment.length === 4)
continue; continue;
pos = encodeInteger(buf, pos, state, segment, 4); // namesIndex namesIndex = encodeInteger(writer, segment[4], namesIndex);
} }
} }
return out + td.decode(buf.subarray(0, pos)); return writer.flush();
}
function encodeInteger(buf, pos, state, segment, j) {
const next = segment[j];
let num = next - state[j];
state[j] = next;
num = num < 0 ? (-num << 1) | 1 : num << 1;
do {
let clamped = num & 0b011111;
num >>>= 5;
if (num > 0)
clamped |= 0b100000;
buf[pos++] = intToChar[clamped];
} while (num > 0);
return pos;
} }
exports.decode = decode; exports.decode = decode;
exports.decodeGeneratedRanges = decodeGeneratedRanges;
exports.decodeOriginalScopes = decodeOriginalScopes;
exports.encode = encode; exports.encode = encode;
exports.encodeGeneratedRanges = encodeGeneratedRanges;
exports.encodeOriginalScopes = encodeOriginalScopes;
Object.defineProperty(exports, '__esModule', { value: true }); Object.defineProperty(exports, '__esModule', { value: true });

View file

@ -1,6 +1,6 @@
{ {
"name": "@jridgewell/sourcemap-codec", "name": "@jridgewell/sourcemap-codec",
"version": "1.4.15", "version": "1.5.0",
"description": "Encode/decode sourcemap mappings", "description": "Encode/decode sourcemap mappings",
"keywords": [ "keywords": [
"sourcemap", "sourcemap",
@ -37,7 +37,6 @@
"prebuild": "rm -rf dist", "prebuild": "rm -rf dist",
"prepublishOnly": "npm run preversion", "prepublishOnly": "npm run preversion",
"preversion": "run-s test build", "preversion": "run-s test build",
"pretest": "run-s build:rollup",
"test": "run-s -n test:lint test:only", "test": "run-s -n test:lint test:only",
"test:debug": "mocha --inspect-brk", "test:debug": "mocha --inspect-brk",
"test:lint": "run-s -n test:lint:*", "test:lint": "run-s -n test:lint:*",
@ -55,6 +54,7 @@
"license": "MIT", "license": "MIT",
"devDependencies": { "devDependencies": {
"@rollup/plugin-typescript": "8.3.0", "@rollup/plugin-typescript": "8.3.0",
"@types/mocha": "10.0.6",
"@types/node": "17.0.15", "@types/node": "17.0.15",
"@typescript-eslint/eslint-plugin": "5.10.0", "@typescript-eslint/eslint-plugin": "5.10.0",
"@typescript-eslint/parser": "5.10.0", "@typescript-eslint/parser": "5.10.0",
@ -69,6 +69,7 @@
"source-map": "0.6.1", "source-map": "0.6.1",
"source-map-js": "1.0.2", "source-map-js": "1.0.2",
"sourcemap-codec": "1.4.8", "sourcemap-codec": "1.4.8",
"tsx": "4.7.1",
"typescript": "4.5.4" "typescript": "4.5.4"
} }
} }

View file

@ -1,21 +0,0 @@
MIT License
Copyright (c) 2019 typescript-eslint 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

@ -1,202 +0,0 @@
"use strict";
/**********************************************
* DO NOT MODIFY THIS FILE MANUALLY *
* *
* THIS FILE HAS BEEN COPIED FROM ast-spec. *
* ANY CHANGES WILL BE LOST ON THE NEXT BUILD *
* *
* MAKE CHANGES TO ast-spec AND THEN RUN *
* yarn build *
**********************************************/
Object.defineProperty(exports, "__esModule", { value: true });
exports.AST_TOKEN_TYPES = exports.AST_NODE_TYPES = void 0;
var AST_NODE_TYPES;
(function (AST_NODE_TYPES) {
AST_NODE_TYPES["AccessorProperty"] = "AccessorProperty";
AST_NODE_TYPES["ArrayExpression"] = "ArrayExpression";
AST_NODE_TYPES["ArrayPattern"] = "ArrayPattern";
AST_NODE_TYPES["ArrowFunctionExpression"] = "ArrowFunctionExpression";
AST_NODE_TYPES["AssignmentExpression"] = "AssignmentExpression";
AST_NODE_TYPES["AssignmentPattern"] = "AssignmentPattern";
AST_NODE_TYPES["AwaitExpression"] = "AwaitExpression";
AST_NODE_TYPES["BinaryExpression"] = "BinaryExpression";
AST_NODE_TYPES["BlockStatement"] = "BlockStatement";
AST_NODE_TYPES["BreakStatement"] = "BreakStatement";
AST_NODE_TYPES["CallExpression"] = "CallExpression";
AST_NODE_TYPES["CatchClause"] = "CatchClause";
AST_NODE_TYPES["ChainExpression"] = "ChainExpression";
AST_NODE_TYPES["ClassBody"] = "ClassBody";
AST_NODE_TYPES["ClassDeclaration"] = "ClassDeclaration";
AST_NODE_TYPES["ClassExpression"] = "ClassExpression";
AST_NODE_TYPES["ConditionalExpression"] = "ConditionalExpression";
AST_NODE_TYPES["ContinueStatement"] = "ContinueStatement";
AST_NODE_TYPES["DebuggerStatement"] = "DebuggerStatement";
AST_NODE_TYPES["Decorator"] = "Decorator";
AST_NODE_TYPES["DoWhileStatement"] = "DoWhileStatement";
AST_NODE_TYPES["EmptyStatement"] = "EmptyStatement";
AST_NODE_TYPES["ExportAllDeclaration"] = "ExportAllDeclaration";
AST_NODE_TYPES["ExportDefaultDeclaration"] = "ExportDefaultDeclaration";
AST_NODE_TYPES["ExportNamedDeclaration"] = "ExportNamedDeclaration";
AST_NODE_TYPES["ExportSpecifier"] = "ExportSpecifier";
AST_NODE_TYPES["ExpressionStatement"] = "ExpressionStatement";
AST_NODE_TYPES["ForInStatement"] = "ForInStatement";
AST_NODE_TYPES["ForOfStatement"] = "ForOfStatement";
AST_NODE_TYPES["ForStatement"] = "ForStatement";
AST_NODE_TYPES["FunctionDeclaration"] = "FunctionDeclaration";
AST_NODE_TYPES["FunctionExpression"] = "FunctionExpression";
AST_NODE_TYPES["Identifier"] = "Identifier";
AST_NODE_TYPES["IfStatement"] = "IfStatement";
AST_NODE_TYPES["ImportAttribute"] = "ImportAttribute";
AST_NODE_TYPES["ImportDeclaration"] = "ImportDeclaration";
AST_NODE_TYPES["ImportDefaultSpecifier"] = "ImportDefaultSpecifier";
AST_NODE_TYPES["ImportExpression"] = "ImportExpression";
AST_NODE_TYPES["ImportNamespaceSpecifier"] = "ImportNamespaceSpecifier";
AST_NODE_TYPES["ImportSpecifier"] = "ImportSpecifier";
AST_NODE_TYPES["JSXAttribute"] = "JSXAttribute";
AST_NODE_TYPES["JSXClosingElement"] = "JSXClosingElement";
AST_NODE_TYPES["JSXClosingFragment"] = "JSXClosingFragment";
AST_NODE_TYPES["JSXElement"] = "JSXElement";
AST_NODE_TYPES["JSXEmptyExpression"] = "JSXEmptyExpression";
AST_NODE_TYPES["JSXExpressionContainer"] = "JSXExpressionContainer";
AST_NODE_TYPES["JSXFragment"] = "JSXFragment";
AST_NODE_TYPES["JSXIdentifier"] = "JSXIdentifier";
AST_NODE_TYPES["JSXMemberExpression"] = "JSXMemberExpression";
AST_NODE_TYPES["JSXNamespacedName"] = "JSXNamespacedName";
AST_NODE_TYPES["JSXOpeningElement"] = "JSXOpeningElement";
AST_NODE_TYPES["JSXOpeningFragment"] = "JSXOpeningFragment";
AST_NODE_TYPES["JSXSpreadAttribute"] = "JSXSpreadAttribute";
AST_NODE_TYPES["JSXSpreadChild"] = "JSXSpreadChild";
AST_NODE_TYPES["JSXText"] = "JSXText";
AST_NODE_TYPES["LabeledStatement"] = "LabeledStatement";
AST_NODE_TYPES["Literal"] = "Literal";
AST_NODE_TYPES["LogicalExpression"] = "LogicalExpression";
AST_NODE_TYPES["MemberExpression"] = "MemberExpression";
AST_NODE_TYPES["MetaProperty"] = "MetaProperty";
AST_NODE_TYPES["MethodDefinition"] = "MethodDefinition";
AST_NODE_TYPES["NewExpression"] = "NewExpression";
AST_NODE_TYPES["ObjectExpression"] = "ObjectExpression";
AST_NODE_TYPES["ObjectPattern"] = "ObjectPattern";
AST_NODE_TYPES["PrivateIdentifier"] = "PrivateIdentifier";
AST_NODE_TYPES["Program"] = "Program";
AST_NODE_TYPES["Property"] = "Property";
AST_NODE_TYPES["PropertyDefinition"] = "PropertyDefinition";
AST_NODE_TYPES["RestElement"] = "RestElement";
AST_NODE_TYPES["ReturnStatement"] = "ReturnStatement";
AST_NODE_TYPES["SequenceExpression"] = "SequenceExpression";
AST_NODE_TYPES["SpreadElement"] = "SpreadElement";
AST_NODE_TYPES["StaticBlock"] = "StaticBlock";
AST_NODE_TYPES["Super"] = "Super";
AST_NODE_TYPES["SwitchCase"] = "SwitchCase";
AST_NODE_TYPES["SwitchStatement"] = "SwitchStatement";
AST_NODE_TYPES["TaggedTemplateExpression"] = "TaggedTemplateExpression";
AST_NODE_TYPES["TemplateElement"] = "TemplateElement";
AST_NODE_TYPES["TemplateLiteral"] = "TemplateLiteral";
AST_NODE_TYPES["ThisExpression"] = "ThisExpression";
AST_NODE_TYPES["ThrowStatement"] = "ThrowStatement";
AST_NODE_TYPES["TryStatement"] = "TryStatement";
AST_NODE_TYPES["UnaryExpression"] = "UnaryExpression";
AST_NODE_TYPES["UpdateExpression"] = "UpdateExpression";
AST_NODE_TYPES["VariableDeclaration"] = "VariableDeclaration";
AST_NODE_TYPES["VariableDeclarator"] = "VariableDeclarator";
AST_NODE_TYPES["WhileStatement"] = "WhileStatement";
AST_NODE_TYPES["WithStatement"] = "WithStatement";
AST_NODE_TYPES["YieldExpression"] = "YieldExpression";
/**
* TS-prefixed nodes
*/
AST_NODE_TYPES["TSAbstractAccessorProperty"] = "TSAbstractAccessorProperty";
AST_NODE_TYPES["TSAbstractKeyword"] = "TSAbstractKeyword";
AST_NODE_TYPES["TSAbstractMethodDefinition"] = "TSAbstractMethodDefinition";
AST_NODE_TYPES["TSAbstractPropertyDefinition"] = "TSAbstractPropertyDefinition";
AST_NODE_TYPES["TSAnyKeyword"] = "TSAnyKeyword";
AST_NODE_TYPES["TSArrayType"] = "TSArrayType";
AST_NODE_TYPES["TSAsExpression"] = "TSAsExpression";
AST_NODE_TYPES["TSAsyncKeyword"] = "TSAsyncKeyword";
AST_NODE_TYPES["TSBigIntKeyword"] = "TSBigIntKeyword";
AST_NODE_TYPES["TSBooleanKeyword"] = "TSBooleanKeyword";
AST_NODE_TYPES["TSCallSignatureDeclaration"] = "TSCallSignatureDeclaration";
AST_NODE_TYPES["TSClassImplements"] = "TSClassImplements";
AST_NODE_TYPES["TSConditionalType"] = "TSConditionalType";
AST_NODE_TYPES["TSConstructorType"] = "TSConstructorType";
AST_NODE_TYPES["TSConstructSignatureDeclaration"] = "TSConstructSignatureDeclaration";
AST_NODE_TYPES["TSDeclareFunction"] = "TSDeclareFunction";
AST_NODE_TYPES["TSDeclareKeyword"] = "TSDeclareKeyword";
AST_NODE_TYPES["TSEmptyBodyFunctionExpression"] = "TSEmptyBodyFunctionExpression";
AST_NODE_TYPES["TSEnumDeclaration"] = "TSEnumDeclaration";
AST_NODE_TYPES["TSEnumMember"] = "TSEnumMember";
AST_NODE_TYPES["TSExportAssignment"] = "TSExportAssignment";
AST_NODE_TYPES["TSExportKeyword"] = "TSExportKeyword";
AST_NODE_TYPES["TSExternalModuleReference"] = "TSExternalModuleReference";
AST_NODE_TYPES["TSFunctionType"] = "TSFunctionType";
AST_NODE_TYPES["TSInstantiationExpression"] = "TSInstantiationExpression";
AST_NODE_TYPES["TSImportEqualsDeclaration"] = "TSImportEqualsDeclaration";
AST_NODE_TYPES["TSImportType"] = "TSImportType";
AST_NODE_TYPES["TSIndexedAccessType"] = "TSIndexedAccessType";
AST_NODE_TYPES["TSIndexSignature"] = "TSIndexSignature";
AST_NODE_TYPES["TSInferType"] = "TSInferType";
AST_NODE_TYPES["TSInterfaceBody"] = "TSInterfaceBody";
AST_NODE_TYPES["TSInterfaceDeclaration"] = "TSInterfaceDeclaration";
AST_NODE_TYPES["TSInterfaceHeritage"] = "TSInterfaceHeritage";
AST_NODE_TYPES["TSIntersectionType"] = "TSIntersectionType";
AST_NODE_TYPES["TSIntrinsicKeyword"] = "TSIntrinsicKeyword";
AST_NODE_TYPES["TSLiteralType"] = "TSLiteralType";
AST_NODE_TYPES["TSMappedType"] = "TSMappedType";
AST_NODE_TYPES["TSMethodSignature"] = "TSMethodSignature";
AST_NODE_TYPES["TSModuleBlock"] = "TSModuleBlock";
AST_NODE_TYPES["TSModuleDeclaration"] = "TSModuleDeclaration";
AST_NODE_TYPES["TSNamedTupleMember"] = "TSNamedTupleMember";
AST_NODE_TYPES["TSNamespaceExportDeclaration"] = "TSNamespaceExportDeclaration";
AST_NODE_TYPES["TSNeverKeyword"] = "TSNeverKeyword";
AST_NODE_TYPES["TSNonNullExpression"] = "TSNonNullExpression";
AST_NODE_TYPES["TSNullKeyword"] = "TSNullKeyword";
AST_NODE_TYPES["TSNumberKeyword"] = "TSNumberKeyword";
AST_NODE_TYPES["TSObjectKeyword"] = "TSObjectKeyword";
AST_NODE_TYPES["TSOptionalType"] = "TSOptionalType";
AST_NODE_TYPES["TSParameterProperty"] = "TSParameterProperty";
AST_NODE_TYPES["TSPrivateKeyword"] = "TSPrivateKeyword";
AST_NODE_TYPES["TSPropertySignature"] = "TSPropertySignature";
AST_NODE_TYPES["TSProtectedKeyword"] = "TSProtectedKeyword";
AST_NODE_TYPES["TSPublicKeyword"] = "TSPublicKeyword";
AST_NODE_TYPES["TSQualifiedName"] = "TSQualifiedName";
AST_NODE_TYPES["TSReadonlyKeyword"] = "TSReadonlyKeyword";
AST_NODE_TYPES["TSRestType"] = "TSRestType";
AST_NODE_TYPES["TSSatisfiesExpression"] = "TSSatisfiesExpression";
AST_NODE_TYPES["TSStaticKeyword"] = "TSStaticKeyword";
AST_NODE_TYPES["TSStringKeyword"] = "TSStringKeyword";
AST_NODE_TYPES["TSSymbolKeyword"] = "TSSymbolKeyword";
AST_NODE_TYPES["TSTemplateLiteralType"] = "TSTemplateLiteralType";
AST_NODE_TYPES["TSThisType"] = "TSThisType";
AST_NODE_TYPES["TSTupleType"] = "TSTupleType";
AST_NODE_TYPES["TSTypeAliasDeclaration"] = "TSTypeAliasDeclaration";
AST_NODE_TYPES["TSTypeAnnotation"] = "TSTypeAnnotation";
AST_NODE_TYPES["TSTypeAssertion"] = "TSTypeAssertion";
AST_NODE_TYPES["TSTypeLiteral"] = "TSTypeLiteral";
AST_NODE_TYPES["TSTypeOperator"] = "TSTypeOperator";
AST_NODE_TYPES["TSTypeParameter"] = "TSTypeParameter";
AST_NODE_TYPES["TSTypeParameterDeclaration"] = "TSTypeParameterDeclaration";
AST_NODE_TYPES["TSTypeParameterInstantiation"] = "TSTypeParameterInstantiation";
AST_NODE_TYPES["TSTypePredicate"] = "TSTypePredicate";
AST_NODE_TYPES["TSTypeQuery"] = "TSTypeQuery";
AST_NODE_TYPES["TSTypeReference"] = "TSTypeReference";
AST_NODE_TYPES["TSUndefinedKeyword"] = "TSUndefinedKeyword";
AST_NODE_TYPES["TSUnionType"] = "TSUnionType";
AST_NODE_TYPES["TSUnknownKeyword"] = "TSUnknownKeyword";
AST_NODE_TYPES["TSVoidKeyword"] = "TSVoidKeyword";
})(AST_NODE_TYPES || (exports.AST_NODE_TYPES = AST_NODE_TYPES = {}));
var AST_TOKEN_TYPES;
(function (AST_TOKEN_TYPES) {
AST_TOKEN_TYPES["Boolean"] = "Boolean";
AST_TOKEN_TYPES["Identifier"] = "Identifier";
AST_TOKEN_TYPES["JSXIdentifier"] = "JSXIdentifier";
AST_TOKEN_TYPES["JSXText"] = "JSXText";
AST_TOKEN_TYPES["Keyword"] = "Keyword";
AST_TOKEN_TYPES["Null"] = "Null";
AST_TOKEN_TYPES["Numeric"] = "Numeric";
AST_TOKEN_TYPES["Punctuator"] = "Punctuator";
AST_TOKEN_TYPES["RegularExpression"] = "RegularExpression";
AST_TOKEN_TYPES["String"] = "String";
AST_TOKEN_TYPES["Template"] = "Template";
AST_TOKEN_TYPES["Block"] = "Block";
AST_TOKEN_TYPES["Line"] = "Line";
})(AST_TOKEN_TYPES || (exports.AST_TOKEN_TYPES = AST_TOKEN_TYPES = {}));
//# sourceMappingURL=ast-spec.js.map

View file

@ -1,24 +0,0 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.AST_TOKEN_TYPES = exports.AST_NODE_TYPES = void 0;
var ast_spec_1 = require("./generated/ast-spec");
Object.defineProperty(exports, "AST_NODE_TYPES", { enumerable: true, get: function () { return ast_spec_1.AST_NODE_TYPES; } });
Object.defineProperty(exports, "AST_TOKEN_TYPES", { enumerable: true, get: function () { return ast_spec_1.AST_TOKEN_TYPES; } });
__exportStar(require("./lib"), exports);
__exportStar(require("./parser-options"), exports);
__exportStar(require("./ts-estree"), exports);
//# sourceMappingURL=index.js.map

View file

@ -1,7 +0,0 @@
"use strict";
// THIS CODE WAS AUTOMATICALLY GENERATED
// DO NOT EDIT THIS CODE BY HAND
// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE:
// npx nx generate-lib @typescript-eslint/repo-tools
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=lib.js.map

View file

@ -1,3 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=parser-options.js.map

View file

@ -1,28 +0,0 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.TSESTree = void 0;
exports.TSESTree = __importStar(require("./generated/ast-spec"));
//# sourceMappingURL=ts-estree.js.map

View file

@ -1,88 +0,0 @@
{
"name": "@typescript-eslint/types",
"version": "7.14.1",
"description": "Types for the TypeScript-ESTree AST spec",
"files": [
"dist",
"_ts4.3",
"package.json",
"README.md",
"LICENSE"
],
"type": "commonjs",
"exports": {
".": {
"types": "./dist/index.d.ts",
"default": "./dist/index.js"
},
"./package.json": "./package.json"
},
"types": "./dist/index.d.ts",
"engines": {
"node": "^18.18.0 || >=20.0.0"
},
"repository": {
"type": "git",
"url": "https://github.com/typescript-eslint/typescript-eslint.git",
"directory": "packages/types"
},
"bugs": {
"url": "https://github.com/typescript-eslint/typescript-eslint/issues"
},
"homepage": "https://typescript-eslint.io",
"license": "MIT",
"keywords": [
"eslint",
"typescript",
"estree"
],
"scripts": {
"copy-ast-spec": "tsx ./tools/copy-ast-spec.ts",
"build": "tsc -b tsconfig.build.json",
"postbuild": "downlevel-dts dist _ts4.3/dist --to=4.3",
"clean": "tsc -b tsconfig.build.json --clean",
"postclean": "rimraf dist && rimraf src/generated && rimraf _ts3.4 && rimraf _ts4.3 && rimraf coverage",
"format": "prettier --write \"./**/*.{ts,mts,cts,tsx,js,mjs,cjs,jsx,json,md,css}\" --ignore-path ../../.prettierignore",
"generate-lib": "npx nx run scope-manager:generate-lib",
"lint": "npx nx lint",
"typecheck": "tsc --noEmit"
},
"nx": {
"targets": {
"copy-ast-spec": {
"dependsOn": [
"^build"
],
"outputs": [
"{projectRoot}/src/generated"
],
"cache": true
},
"build": {
"dependsOn": [
"^build",
"copy-ast-spec"
]
}
}
},
"devDependencies": {
"@jest/types": "29.6.3",
"downlevel-dts": "*",
"prettier": "^3.2.5",
"rimraf": "*",
"tsx": "*",
"typescript": "*"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/typescript-eslint"
},
"typesVersions": {
"<4.7": {
"*": [
"_ts4.3/*"
]
}
}
}

View file

@ -667,7 +667,7 @@
// ## Parser utilities // ## Parser utilities
var literal = /^(?:'((?:\\.|[^'\\])*?)'|"((?:\\.|[^"\\])*?)")/s; var literal = /^(?:'((?:\\[^]|[^'\\])*?)'|"((?:\\[^]|[^"\\])*?)")/;
pp$9.strictDirective = function(start) { pp$9.strictDirective = function(start) {
if (this.options.ecmaVersion < 5) { return false } if (this.options.ecmaVersion < 5) { return false }
for (;;) { for (;;) {
@ -5990,7 +5990,7 @@
// [walk]: util/walk.js // [walk]: util/walk.js
var version = "8.12.0"; var version = "8.12.1";
Parser.acorn = { Parser.acorn = {
Parser: Parser, Parser: Parser,

View file

@ -661,7 +661,7 @@ var pp$9 = Parser.prototype;
// ## Parser utilities // ## Parser utilities
var literal = /^(?:'((?:\\.|[^'\\])*?)'|"((?:\\.|[^"\\])*?)")/s; var literal = /^(?:'((?:\\[^]|[^'\\])*?)'|"((?:\\[^]|[^"\\])*?)")/;
pp$9.strictDirective = function(start) { pp$9.strictDirective = function(start) {
if (this.options.ecmaVersion < 5) { return false } if (this.options.ecmaVersion < 5) { return false }
for (;;) { for (;;) {
@ -5984,7 +5984,7 @@ pp.readWord = function() {
// [walk]: util/walk.js // [walk]: util/walk.js
var version = "8.12.0"; var version = "8.12.1";
Parser.acorn = { Parser.acorn = {
Parser: Parser, Parser: Parser,

View file

@ -16,7 +16,7 @@
], ],
"./package.json": "./package.json" "./package.json": "./package.json"
}, },
"version": "8.12.0", "version": "8.12.1",
"engines": { "engines": {
"node": ">=0.4.0" "node": ">=0.4.0"
}, },

View file

@ -1016,7 +1016,7 @@ var QUERIES = {
matches: [], matches: [],
regexp: /^(firefox|ff|fx)\s+esr$/i, regexp: /^(firefox|ff|fx)\s+esr$/i,
select: function () { select: function () {
return ['firefox 115'] return ['firefox 115', 'firefox 128']
} }
}, },
opera_mini_all: { opera_mini_all: {

View file

@ -1,6 +1,6 @@
{ {
"name": "browserslist", "name": "browserslist",
"version": "4.23.1", "version": "4.23.2",
"description": "Share target browsers between different front-end tools, like Autoprefixer, Stylelint and babel-env-preset", "description": "Share target browsers between different front-end tools, like Autoprefixer, Stylelint and babel-env-preset",
"keywords": [ "keywords": [
"caniuse", "caniuse",
@ -25,10 +25,10 @@
"license": "MIT", "license": "MIT",
"repository": "browserslist/browserslist", "repository": "browserslist/browserslist",
"dependencies": { "dependencies": {
"caniuse-lite": "^1.0.30001629", "caniuse-lite": "^1.0.30001640",
"electron-to-chromium": "^1.4.796", "electron-to-chromium": "^1.4.820",
"node-releases": "^2.0.14", "node-releases": "^2.0.14",
"update-browserslist-db": "^1.0.16" "update-browserslist-db": "^1.1.0"
}, },
"engines": { "engines": {
"node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7" "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7"

View file

@ -208,7 +208,7 @@ const getSymbol = function (node, globals, scope, opt) {
val.type = 'object'; val.type = 'object';
for (const prop of node.properties) { for (const prop of node.properties) {
if ([ if ([
// @typescript-eslint/parser, espree, acorn, etc. // typescript-eslint, espree, acorn, etc.
'SpreadElement', 'SpreadElement',
// @babel/eslint-parser // @babel/eslint-parser
'ExperimentalSpreadProperty'].includes(prop.type)) { 'ExperimentalSpreadProperty'].includes(prop.type)) {

View file

@ -97,7 +97,7 @@ export default iterateJsdoc(({
if (!(0, _fs.existsSync)(ruleTestPath)) { if (!(0, _fs.existsSync)(ruleTestPath)) {
await _promises.default.writeFile(ruleTestPath, ruleTestTemplate); await _promises.default.writeFile(ruleTestPath, ruleTestTemplate);
} }
const ruleReadmeTemplate = `### \`${ruleName}\` const ruleReadmeTemplate = `# \`${ruleName}\`
||| |||
|---|---| |---|---|

View file

@ -15,6 +15,7 @@ var _checkSyntax = _interopRequireDefault(require("./rules/checkSyntax.cjs"));
var _checkTagNames = _interopRequireDefault(require("./rules/checkTagNames.cjs")); var _checkTagNames = _interopRequireDefault(require("./rules/checkTagNames.cjs"));
var _checkTypes = _interopRequireDefault(require("./rules/checkTypes.cjs")); var _checkTypes = _interopRequireDefault(require("./rules/checkTypes.cjs"));
var _checkValues = _interopRequireDefault(require("./rules/checkValues.cjs")); var _checkValues = _interopRequireDefault(require("./rules/checkValues.cjs"));
var _convertToJsdocComments = _interopRequireDefault(require("./rules/convertToJsdocComments.cjs"));
var _emptyTags = _interopRequireDefault(require("./rules/emptyTags.cjs")); var _emptyTags = _interopRequireDefault(require("./rules/emptyTags.cjs"));
var _implementsOnClasses = _interopRequireDefault(require("./rules/implementsOnClasses.cjs")); var _implementsOnClasses = _interopRequireDefault(require("./rules/implementsOnClasses.cjs"));
var _importsAsDependencies = _interopRequireDefault(require("./rules/importsAsDependencies.cjs")); var _importsAsDependencies = _interopRequireDefault(require("./rules/importsAsDependencies.cjs"));
@ -50,6 +51,7 @@ var _requireReturns = _interopRequireDefault(require("./rules/requireReturns.cjs
var _requireReturnsCheck = _interopRequireDefault(require("./rules/requireReturnsCheck.cjs")); var _requireReturnsCheck = _interopRequireDefault(require("./rules/requireReturnsCheck.cjs"));
var _requireReturnsDescription = _interopRequireDefault(require("./rules/requireReturnsDescription.cjs")); var _requireReturnsDescription = _interopRequireDefault(require("./rules/requireReturnsDescription.cjs"));
var _requireReturnsType = _interopRequireDefault(require("./rules/requireReturnsType.cjs")); var _requireReturnsType = _interopRequireDefault(require("./rules/requireReturnsType.cjs"));
var _requireTemplate = _interopRequireDefault(require("./rules/requireTemplate.cjs"));
var _requireThrows = _interopRequireDefault(require("./rules/requireThrows.cjs")); var _requireThrows = _interopRequireDefault(require("./rules/requireThrows.cjs"));
var _requireYields = _interopRequireDefault(require("./rules/requireYields.cjs")); var _requireYields = _interopRequireDefault(require("./rules/requireYields.cjs"));
var _requireYieldsCheck = _interopRequireDefault(require("./rules/requireYieldsCheck.cjs")); var _requireYieldsCheck = _interopRequireDefault(require("./rules/requireYieldsCheck.cjs"));
@ -87,6 +89,7 @@ const index = {
'check-tag-names': _checkTagNames.default, 'check-tag-names': _checkTagNames.default,
'check-types': _checkTypes.default, 'check-types': _checkTypes.default,
'check-values': _checkValues.default, 'check-values': _checkValues.default,
'convert-to-jsdoc-comments': _convertToJsdocComments.default,
'empty-tags': _emptyTags.default, 'empty-tags': _emptyTags.default,
'implements-on-classes': _implementsOnClasses.default, 'implements-on-classes': _implementsOnClasses.default,
'imports-as-dependencies': _importsAsDependencies.default, 'imports-as-dependencies': _importsAsDependencies.default,
@ -122,6 +125,7 @@ const index = {
'require-returns-check': _requireReturnsCheck.default, 'require-returns-check': _requireReturnsCheck.default,
'require-returns-description': _requireReturnsDescription.default, 'require-returns-description': _requireReturnsDescription.default,
'require-returns-type': _requireReturnsType.default, 'require-returns-type': _requireReturnsType.default,
'require-template': _requireTemplate.default,
'require-throws': _requireThrows.default, 'require-throws': _requireThrows.default,
'require-yields': _requireYields.default, 'require-yields': _requireYields.default,
'require-yields-check': _requireYieldsCheck.default, 'require-yields-check': _requireYieldsCheck.default,
@ -158,6 +162,7 @@ const createRecommendedRuleset = (warnOrError, flatName) => {
'jsdoc/check-tag-names': warnOrError, 'jsdoc/check-tag-names': warnOrError,
'jsdoc/check-types': warnOrError, 'jsdoc/check-types': warnOrError,
'jsdoc/check-values': warnOrError, 'jsdoc/check-values': warnOrError,
'jsdoc/convert-to-jsdoc-comments': 'off',
'jsdoc/empty-tags': warnOrError, 'jsdoc/empty-tags': warnOrError,
'jsdoc/implements-on-classes': warnOrError, 'jsdoc/implements-on-classes': warnOrError,
'jsdoc/imports-as-dependencies': 'off', 'jsdoc/imports-as-dependencies': 'off',
@ -193,6 +198,7 @@ const createRecommendedRuleset = (warnOrError, flatName) => {
'jsdoc/require-returns-check': warnOrError, 'jsdoc/require-returns-check': warnOrError,
'jsdoc/require-returns-description': warnOrError, 'jsdoc/require-returns-description': warnOrError,
'jsdoc/require-returns-type': warnOrError, 'jsdoc/require-returns-type': warnOrError,
'jsdoc/require-template': 'off',
'jsdoc/require-throws': 'off', 'jsdoc/require-throws': 'off',
'jsdoc/require-yields': warnOrError, 'jsdoc/require-yields': warnOrError,
'jsdoc/require-yields-check': warnOrError, 'jsdoc/require-yields-check': warnOrError,

View file

@ -306,9 +306,16 @@ const getFunctionParameterNames = (functionNode, checkDefaultObjects) => {
return [undefined, flattenRoots(roots)]; return [undefined, flattenRoots(roots)];
} }
if (['RestElement', 'ExperimentalRestProperty'].includes(param.type)) { if (['RestElement', 'ExperimentalRestProperty'].includes(param.type)) {
var _param$argument;
return { return {
isRestProperty: isProperty, isRestProperty: isProperty,
name: /** @type {import('@typescript-eslint/types').TSESTree.Identifier} */( /** @type {import('@typescript-eslint/types').TSESTree.RestElement} */param.argument).name, name: /** @type {import('@typescript-eslint/types').TSESTree.Identifier} */( /** @type {import('@typescript-eslint/types').TSESTree.RestElement} */param
// @ts-expect-error Ok
.argument).name ?? (param === null || param === void 0 || (_param$argument = param.argument) === null || _param$argument === void 0 || (_param$argument = _param$argument.elements) === null || _param$argument === void 0 ? void 0 : _param$argument.map(({
name
}) => {
return name;
})),
restElement: true restElement: true
}; };
} }
@ -1042,7 +1049,7 @@ const parseClosureTemplateTag = tag => {
* @param {{ * @param {{
* contexts?: import('./iterateJsdoc.js').Context[] * contexts?: import('./iterateJsdoc.js').Context[]
* }} settings * }} settings
* @returns {string[]} * @returns {(string|import('./iterateJsdoc.js').ContextObject)[]}
*/ */
const enforcedContexts = (context, defaultContexts, settings) => { const enforcedContexts = (context, defaultContexts, settings) => {
var _context$options$; var _context$options$;

View file

@ -61,6 +61,16 @@ const validateParameterNames = (targetTagName, allowExtraTrailingParamDocs, chec
report(`@${targetTagName} "${tag.name}" does not match an existing function parameter.`, null, tag); report(`@${targetTagName} "${tag.name}" does not match an existing function parameter.`, null, tag);
return true; return true;
} }
if (typeof functionParameterName === 'object' && 'name' in functionParameterName && Array.isArray(functionParameterName.name)) {
const actualName = tag.name.trim();
const expectedName = functionParameterName.name[index];
if (actualName === expectedName) {
thisOffset--;
return false;
}
report(`Expected @${targetTagName} name to be "${expectedName}". Got "${actualName}".`, null, tag);
return true;
}
if (Array.isArray(functionParameterName)) { if (Array.isArray(functionParameterName)) {
if (!checkDestructured) { if (!checkDestructured) {
return false; return false;
@ -195,7 +205,9 @@ const validateParameterNames = (targetTagName, allowExtraTrailingParamDocs, chec
return false; return false;
} }
} }
report(`Expected @${targetTagName} names to be "${expectedNames.join(', ')}". Got "${actualNames.join(', ')}".`, null, tag); report(`Expected @${targetTagName} names to be "${expectedNames.map(expectedName => {
return typeof expectedName === 'object' && 'name' in expectedName && expectedName.restElement ? '...' + expectedName.name : expectedName;
}).join(', ')}". Got "${actualNames.join(', ')}".`, null, tag);
return true; return true;
} }
return false; return false;

View file

@ -0,0 +1,313 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _iterateJsdoc = _interopRequireWildcard(require("../iterateJsdoc.cjs"));
var _jsdocUtils = _interopRequireDefault(require("../jsdocUtils.cjs"));
var _jsdoccomment = require("@es-joy/jsdoccomment");
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); }
function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
/** @type {import('eslint').Rule.RuleModule} */
var _default = exports.default = {
create(context) {
/**
* @typedef {import('eslint').AST.Token | import('estree').Comment | {
* type: import('eslint').AST.TokenType|"Line"|"Block"|"Shebang",
* range: [number, number],
* value: string
* }} Token
*/
/**
* @callback AddComment
* @param {boolean|undefined} inlineCommentBlock
* @param {Token} comment
* @param {string} indent
* @param {number} lines
* @param {import('eslint').Rule.RuleFixer} fixer
*/
/* c8 ignore next -- Fallback to deprecated method */
const {
sourceCode = context.getSourceCode()
} = context;
const settings = (0, _iterateJsdoc.getSettings)(context);
if (!settings) {
return {};
}
const {
contexts = settings.contexts || [],
contextsAfter = ( /** @type {string[]} */[]),
contextsBeforeAndAfter = ['VariableDeclarator', 'TSPropertySignature', 'PropertyDefinition'],
enableFixer = true,
enforceJsdocLineStyle = 'multi',
lineOrBlockStyle = 'both',
allowedPrefixes = ['@ts-', 'istanbul ', 'c8 ', 'v8 ', 'eslint', 'prettier-']
} = context.options[0] ?? {};
let reportingNonJsdoc = false;
/**
* @param {string} messageId
* @param {import('estree').Comment|Token} comment
* @param {import('eslint').Rule.Node} node
* @param {import('eslint').Rule.ReportFixer} fixer
*/
const report = (messageId, comment, node, fixer) => {
var _comment$loc, _comment$loc2;
const loc = {
end: {
column: 0,
/* c8 ignore next 2 -- Guard */
// @ts-expect-error Ok
line: ((_comment$loc = comment.loc) === null || _comment$loc === void 0 || (_comment$loc = _comment$loc.start) === null || _comment$loc === void 0 ? void 0 : _comment$loc.line) ?? 1
},
start: {
column: 0,
/* c8 ignore next 2 -- Guard */
// @ts-expect-error Ok
line: ((_comment$loc2 = comment.loc) === null || _comment$loc2 === void 0 || (_comment$loc2 = _comment$loc2.start) === null || _comment$loc2 === void 0 ? void 0 : _comment$loc2.line) ?? 1
}
};
context.report({
fix: enableFixer ? fixer : null,
loc,
messageId,
node
});
};
/**
* @param {import('eslint').Rule.Node} node
* @param {import('eslint').AST.Token | import('estree').Comment | {
* type: import('eslint').AST.TokenType|"Line"|"Block"|"Shebang",
* range: [number, number],
* value: string
* }} comment
* @param {AddComment} addComment
* @param {import('../iterateJsdoc.js').Context[]} ctxts
*/
const getFixer = (node, comment, addComment, ctxts) => {
return /** @type {import('eslint').Rule.ReportFixer} */fixer => {
// Default to one line break if the `minLines`/`maxLines` settings allow
const lines = settings.minLines === 0 && settings.maxLines >= 1 ? 1 : settings.minLines;
let baseNode =
/**
* @type {import('@typescript-eslint/types').TSESTree.Node|import('eslint').Rule.Node}
*/
(0, _jsdoccomment.getReducedASTNode)(node, sourceCode);
const decorator = (0, _jsdoccomment.getDecorator)( /** @type {import('eslint').Rule.Node} */
baseNode);
if (decorator) {
baseNode = /** @type {import('@typescript-eslint/types').TSESTree.Decorator} */
decorator;
}
const indent = _jsdocUtils.default.getIndent({
text: sourceCode.getText( /** @type {import('eslint').Rule.Node} */baseNode, /** @type {import('eslint').AST.SourceLocation} */
( /** @type {import('eslint').Rule.Node} */baseNode.loc).start.column)
});
const {
inlineCommentBlock
} =
/**
* @type {{
* context: string,
* inlineCommentBlock: boolean,
* minLineCount: import('../iterateJsdoc.js').Integer
* }[]}
*/
ctxts.find(contxt => {
if (typeof contxt === 'string') {
return false;
}
const {
context: ctxt
} = contxt;
return ctxt === node.type;
}) || {};
return addComment(inlineCommentBlock, comment, indent, lines, fixer);
};
};
/**
* @param {import('eslint').AST.Token | import('estree').Comment | {
* type: import('eslint').AST.TokenType|"Line"|"Block"|"Shebang",
* range: [number, number],
* value: string
* }} comment
* @param {import('eslint').Rule.Node} node
* @param {AddComment} addComment
* @param {import('../iterateJsdoc.js').Context[]} ctxts
*/
const reportings = (comment, node, addComment, ctxts) => {
const fixer = getFixer(node, comment, addComment, ctxts);
if (comment.type === 'Block') {
if (lineOrBlockStyle === 'line') {
return;
}
report('blockCommentsJsdocStyle', comment, node, fixer);
return;
}
if (comment.type === 'Line') {
if (lineOrBlockStyle === 'block') {
return;
}
report('lineCommentsJsdocStyle', comment, node, fixer);
}
};
/**
* @type {import('../iterateJsdoc.js').CheckJsdoc}
*/
const checkNonJsdoc = (_info, _handler, node) => {
const comment = (0, _jsdoccomment.getNonJsdocComment)(sourceCode, node, settings);
if (!comment || /** @type {string[]} */
allowedPrefixes.some(prefix => {
return comment.value.trimStart().startsWith(prefix);
})) {
return;
}
reportingNonJsdoc = true;
/** @type {AddComment} */
const addComment = (inlineCommentBlock, comment, indent, lines, fixer) => {
const insertion = (inlineCommentBlock || enforceJsdocLineStyle === 'single' ? `/** ${comment.value.trim()} ` : `/**\n${indent}*${comment.value.trimEnd()}\n${indent}`) + `*/${'\n'.repeat((lines || 1) - 1)}`;
return fixer.replaceText( /** @type {import('eslint').AST.Token} */
comment, insertion);
};
reportings(comment, node, addComment, contexts);
};
/**
* @param {import('eslint').Rule.Node} node
* @param {import('../iterateJsdoc.js').Context[]} ctxts
*/
const checkNonJsdocAfter = (node, ctxts) => {
const comment = (0, _jsdoccomment.getFollowingComment)(sourceCode, node);
if (!comment || comment.value.startsWith('*') || /** @type {string[]} */
allowedPrefixes.some(prefix => {
return comment.value.trimStart().startsWith(prefix);
})) {
return;
}
/** @type {AddComment} */
const addComment = (inlineCommentBlock, comment, indent, lines, fixer) => {
const insertion = (inlineCommentBlock || enforceJsdocLineStyle === 'single' ? `/** ${comment.value.trim()} ` : `/**\n${indent}*${comment.value.trimEnd()}\n${indent}`) + `*/${'\n'.repeat((lines || 1) - 1)}${lines ? `\n${indent.slice(1)}` : ' '}`;
return [fixer.remove( /** @type {import('eslint').AST.Token} */
comment), fixer.insertTextBefore(node.type === 'VariableDeclarator' ? node.parent : node, insertion)];
};
reportings(comment, node, addComment, ctxts);
};
// Todo: add contexts to check after (and handle if want both before and after)
return {
..._jsdocUtils.default.getContextObject(_jsdocUtils.default.enforcedContexts(context, true, settings), checkNonJsdoc),
..._jsdocUtils.default.getContextObject(contextsAfter, (_info, _handler, node) => {
checkNonJsdocAfter(node, contextsAfter);
}),
..._jsdocUtils.default.getContextObject(contextsBeforeAndAfter, (_info, _handler, node) => {
checkNonJsdoc({}, null, node);
if (!reportingNonJsdoc) {
checkNonJsdocAfter(node, contextsBeforeAndAfter);
}
})
};
},
meta: {
fixable: 'code',
messages: {
blockCommentsJsdocStyle: 'Block comments should be JSDoc-style.',
lineCommentsJsdocStyle: 'Line comments should be JSDoc-style.'
},
docs: {
description: 'Converts non-JSDoc comments preceding or following nodes into JSDoc ones',
url: 'https://github.com/gajus/eslint-plugin-jsdoc/blob/main/docs/rules/convert-to-jsdoc-comments.md#repos-sticky-header'
},
schema: [{
additionalProperties: false,
properties: {
allowedPrefixes: {
type: 'array',
items: {
type: 'string'
}
},
contexts: {
items: {
anyOf: [{
type: 'string'
}, {
additionalProperties: false,
properties: {
context: {
type: 'string'
},
inlineCommentBlock: {
type: 'boolean'
}
},
type: 'object'
}]
},
type: 'array'
},
contextsAfter: {
items: {
anyOf: [{
type: 'string'
}, {
additionalProperties: false,
properties: {
context: {
type: 'string'
},
inlineCommentBlock: {
type: 'boolean'
}
},
type: 'object'
}]
},
type: 'array'
},
contextsBeforeAndAfter: {
items: {
anyOf: [{
type: 'string'
}, {
additionalProperties: false,
properties: {
context: {
type: 'string'
},
inlineCommentBlock: {
type: 'boolean'
}
},
type: 'object'
}]
},
type: 'array'
},
enableFixer: {
type: 'boolean'
},
enforceJsdocLineStyle: {
type: 'string',
enum: ['multi', 'single']
},
lineOrBlockStyle: {
type: 'string',
enum: ['block', 'line', 'both']
}
},
type: 'object'
}],
type: 'suggestion'
}
};
module.exports = exports.default;
//# sourceMappingURL=convertToJsdocComments.cjs.map

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