UNPKG

eslint-plugin-hyper-fetch

Version:
1,571 lines (1,569 loc) 611 kB
"use strict"; var __create = Object.create; var __defProp = Object.defineProperty; var __defProps = Object.defineProperties; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropDescs = Object.getOwnPropertyDescriptors; var __getOwnPropNames = Object.getOwnPropertyNames; var __getOwnPropSymbols = Object.getOwnPropertySymbols; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __propIsEnum = Object.prototype.propertyIsEnumerable; var __knownSymbol = (name, symbol) => (symbol = Symbol[name]) ? symbol : Symbol.for("Symbol." + name); var __typeError = (msg) => { throw TypeError(msg); }; var __pow = Math.pow; var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __spreadValues = (a, b) => { for (var prop in b || (b = {})) if (__hasOwnProp.call(b, prop)) __defNormalProp(a, prop, b[prop]); if (__getOwnPropSymbols) for (var prop of __getOwnPropSymbols(b)) { if (__propIsEnum.call(b, prop)) __defNormalProp(a, prop, b[prop]); } return a; }; var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b)); var __commonJS = (cb, mod) => function __require() { return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; }; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( // If the importer is in node compatibility mode or this is not an ESM // file that has been converted to a CommonJS file using a Babel- // compatible transform (i.e. "__esModule" has not been set), then set // "default" to the CommonJS "module.exports" for node compatibility. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod )); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); var __await = function(promise, isYieldStar) { this[0] = promise; this[1] = isYieldStar; }; var __yieldStar = (value) => { var obj = value[__knownSymbol("asyncIterator")], isAwait = false, method, it = {}; if (obj == null) { obj = value[__knownSymbol("iterator")](); method = (k) => it[k] = (x) => obj[k](x); } else { obj = obj.call(value); method = (k) => it[k] = (v) => { if (isAwait) { isAwait = false; if (k === "throw") throw v; return v; } isAwait = true; return { done: false, value: new __await(new Promise((resolve) => { var x = obj[k](v); if (!(x instanceof Object)) __typeError("Object expected"); resolve(x); }), 1) }; }; } return it[__knownSymbol("iterator")] = () => it, method("next"), "throw" in obj ? method("throw") : it.throw = (x) => { throw x; }, "return" in obj && method("return"), it; }; // ../../node_modules/eslint-visitor-keys/dist/eslint-visitor-keys.cjs var require_eslint_visitor_keys = __commonJS({ "../../node_modules/eslint-visitor-keys/dist/eslint-visitor-keys.cjs"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); var KEYS = { ArrayExpression: [ "elements" ], ArrayPattern: [ "elements" ], ArrowFunctionExpression: [ "params", "body" ], AssignmentExpression: [ "left", "right" ], AssignmentPattern: [ "left", "right" ], AwaitExpression: [ "argument" ], BinaryExpression: [ "left", "right" ], BlockStatement: [ "body" ], BreakStatement: [ "label" ], CallExpression: [ "callee", "arguments" ], CatchClause: [ "param", "body" ], ChainExpression: [ "expression" ], ClassBody: [ "body" ], ClassDeclaration: [ "id", "superClass", "body" ], ClassExpression: [ "id", "superClass", "body" ], ConditionalExpression: [ "test", "consequent", "alternate" ], ContinueStatement: [ "label" ], DebuggerStatement: [], DoWhileStatement: [ "body", "test" ], EmptyStatement: [], ExperimentalRestProperty: [ "argument" ], ExperimentalSpreadProperty: [ "argument" ], ExportAllDeclaration: [ "exported", "source" ], ExportDefaultDeclaration: [ "declaration" ], ExportNamedDeclaration: [ "declaration", "specifiers", "source" ], ExportSpecifier: [ "exported", "local" ], ExpressionStatement: [ "expression" ], ForInStatement: [ "left", "right", "body" ], ForOfStatement: [ "left", "right", "body" ], ForStatement: [ "init", "test", "update", "body" ], FunctionDeclaration: [ "id", "params", "body" ], FunctionExpression: [ "id", "params", "body" ], Identifier: [], IfStatement: [ "test", "consequent", "alternate" ], ImportDeclaration: [ "specifiers", "source" ], ImportDefaultSpecifier: [ "local" ], ImportExpression: [ "source" ], ImportNamespaceSpecifier: [ "local" ], ImportSpecifier: [ "imported", "local" ], JSXAttribute: [ "name", "value" ], JSXClosingElement: [ "name" ], JSXClosingFragment: [], JSXElement: [ "openingElement", "children", "closingElement" ], JSXEmptyExpression: [], JSXExpressionContainer: [ "expression" ], JSXFragment: [ "openingFragment", "children", "closingFragment" ], JSXIdentifier: [], JSXMemberExpression: [ "object", "property" ], JSXNamespacedName: [ "namespace", "name" ], JSXOpeningElement: [ "name", "attributes" ], JSXOpeningFragment: [], JSXSpreadAttribute: [ "argument" ], JSXSpreadChild: [ "expression" ], JSXText: [], LabeledStatement: [ "label", "body" ], Literal: [], LogicalExpression: [ "left", "right" ], MemberExpression: [ "object", "property" ], MetaProperty: [ "meta", "property" ], MethodDefinition: [ "key", "value" ], NewExpression: [ "callee", "arguments" ], ObjectExpression: [ "properties" ], ObjectPattern: [ "properties" ], PrivateIdentifier: [], Program: [ "body" ], Property: [ "key", "value" ], PropertyDefinition: [ "key", "value" ], RestElement: [ "argument" ], ReturnStatement: [ "argument" ], SequenceExpression: [ "expressions" ], SpreadElement: [ "argument" ], StaticBlock: [ "body" ], Super: [], SwitchCase: [ "test", "consequent" ], SwitchStatement: [ "discriminant", "cases" ], TaggedTemplateExpression: [ "tag", "quasi" ], TemplateElement: [], TemplateLiteral: [ "quasis", "expressions" ], ThisExpression: [], ThrowStatement: [ "argument" ], TryStatement: [ "block", "handler", "finalizer" ], UnaryExpression: [ "argument" ], UpdateExpression: [ "argument" ], VariableDeclaration: [ "declarations" ], VariableDeclarator: [ "id", "init" ], WhileStatement: [ "test", "body" ], WithStatement: [ "object", "body" ], YieldExpression: [ "argument" ] }; var NODE_TYPES = Object.keys(KEYS); for (const type of NODE_TYPES) { Object.freeze(KEYS[type]); } Object.freeze(KEYS); var KEY_BLACKLIST = /* @__PURE__ */ new Set([ "parent", "leadingComments", "trailingComments" ]); function filterKey(key) { return !KEY_BLACKLIST.has(key) && key[0] !== "_"; } function getKeys(node) { return Object.keys(node).filter(filterKey); } function unionWith(additionalKeys) { const retv = ( /** @type {{ [type: string]: ReadonlyArray<string> }} */ Object.assign({}, KEYS) ); for (const type of Object.keys(additionalKeys)) { if (Object.prototype.hasOwnProperty.call(retv, type)) { const keys = new Set(additionalKeys[type]); for (const key of retv[type]) { keys.add(key); } retv[type] = Object.freeze(Array.from(keys)); } else { retv[type] = Object.freeze(Array.from(additionalKeys[type])); } } return Object.freeze(retv); } exports2.KEYS = KEYS; exports2.getKeys = getKeys; exports2.unionWith = unionWith; } }); // ../../node_modules/@eslint-community/eslint-utils/index.js var require_eslint_utils = __commonJS({ "../../node_modules/@eslint-community/eslint-utils/index.js"(exports2) { "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); var eslintVisitorKeys = require_eslint_visitor_keys(); function getInnermostScope(initialScope, node) { const location = node.range[0]; let scope = initialScope; let found = false; do { found = false; for (const childScope of scope.childScopes) { const range = childScope.block.range; if (range[0] <= location && location < range[1]) { scope = childScope; found = true; break; } } } while (found); return scope; } function findVariable(initialScope, nameOrNode) { let name = ""; let scope = initialScope; if (typeof nameOrNode === "string") { name = nameOrNode; } else { name = nameOrNode.name; scope = getInnermostScope(scope, nameOrNode); } while (scope != null) { const variable = scope.set.get(name); if (variable != null) { return variable; } scope = scope.upper; } return null; } function negate(f) { return (token) => !f(token); } function isPunctuatorTokenWithValue(token, value) { return token.type === "Punctuator" && token.value === value; } function isArrowToken(token) { return isPunctuatorTokenWithValue(token, "=>"); } function isCommaToken(token) { return isPunctuatorTokenWithValue(token, ","); } function isSemicolonToken(token) { return isPunctuatorTokenWithValue(token, ";"); } function isColonToken(token) { return isPunctuatorTokenWithValue(token, ":"); } function isOpeningParenToken(token) { return isPunctuatorTokenWithValue(token, "("); } function isClosingParenToken(token) { return isPunctuatorTokenWithValue(token, ")"); } function isOpeningBracketToken(token) { return isPunctuatorTokenWithValue(token, "["); } function isClosingBracketToken(token) { return isPunctuatorTokenWithValue(token, "]"); } function isOpeningBraceToken(token) { return isPunctuatorTokenWithValue(token, "{"); } function isClosingBraceToken(token) { return isPunctuatorTokenWithValue(token, "}"); } function isCommentToken(token) { return ["Block", "Line", "Shebang"].includes(token.type); } var isNotArrowToken = negate(isArrowToken); var isNotCommaToken = negate(isCommaToken); var isNotSemicolonToken = negate(isSemicolonToken); var isNotColonToken = negate(isColonToken); var isNotOpeningParenToken = negate(isOpeningParenToken); var isNotClosingParenToken = negate(isClosingParenToken); var isNotOpeningBracketToken = negate(isOpeningBracketToken); var isNotClosingBracketToken = negate(isClosingBracketToken); var isNotOpeningBraceToken = negate(isOpeningBraceToken); var isNotClosingBraceToken = negate(isClosingBraceToken); var isNotCommentToken = negate(isCommentToken); function getOpeningParenOfParams(node, sourceCode) { return node.id ? sourceCode.getTokenAfter(node.id, isOpeningParenToken) : sourceCode.getFirstToken(node, isOpeningParenToken); } function getFunctionHeadLocation(node, sourceCode) { const parent = node.parent; let start = null; let end = null; if (node.type === "ArrowFunctionExpression") { const arrowToken = sourceCode.getTokenBefore(node.body, isArrowToken); start = arrowToken.loc.start; end = arrowToken.loc.end; } else if (parent.type === "Property" || parent.type === "MethodDefinition" || parent.type === "PropertyDefinition") { start = parent.loc.start; end = getOpeningParenOfParams(node, sourceCode).loc.start; } else { start = node.loc.start; end = getOpeningParenOfParams(node, sourceCode).loc.start; } return { start: __spreadValues({}, start), end: __spreadValues({}, end) }; } var globalObject = typeof globalThis !== "undefined" ? globalThis : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : {}; var builtinNames = Object.freeze( /* @__PURE__ */ new Set([ "Array", "ArrayBuffer", "BigInt", "BigInt64Array", "BigUint64Array", "Boolean", "DataView", "Date", "decodeURI", "decodeURIComponent", "encodeURI", "encodeURIComponent", "escape", "Float32Array", "Float64Array", "Function", "Infinity", "Int16Array", "Int32Array", "Int8Array", "isFinite", "isNaN", "isPrototypeOf", "JSON", "Map", "Math", "NaN", "Number", "Object", "parseFloat", "parseInt", "Promise", "Proxy", "Reflect", "RegExp", "Set", "String", "Symbol", "Uint16Array", "Uint32Array", "Uint8Array", "Uint8ClampedArray", "undefined", "unescape", "WeakMap", "WeakSet" ]) ); var callAllowed = new Set( [ Array.isArray, Array.of, Array.prototype.at, Array.prototype.concat, Array.prototype.entries, Array.prototype.every, Array.prototype.filter, Array.prototype.find, Array.prototype.findIndex, Array.prototype.flat, Array.prototype.includes, Array.prototype.indexOf, Array.prototype.join, Array.prototype.keys, Array.prototype.lastIndexOf, Array.prototype.slice, Array.prototype.some, Array.prototype.toString, Array.prototype.values, typeof BigInt === "function" ? BigInt : void 0, Boolean, Date, Date.parse, decodeURI, decodeURIComponent, encodeURI, encodeURIComponent, escape, isFinite, isNaN, isPrototypeOf, Map, Map.prototype.entries, Map.prototype.get, Map.prototype.has, Map.prototype.keys, Map.prototype.values, ...Object.getOwnPropertyNames(Math).filter((k) => k !== "random").map((k) => Math[k]).filter((f) => typeof f === "function"), Number, Number.isFinite, Number.isNaN, Number.parseFloat, Number.parseInt, Number.prototype.toExponential, Number.prototype.toFixed, Number.prototype.toPrecision, Number.prototype.toString, Object, Object.entries, Object.is, Object.isExtensible, Object.isFrozen, Object.isSealed, Object.keys, Object.values, parseFloat, parseInt, RegExp, Set, Set.prototype.entries, Set.prototype.has, Set.prototype.keys, Set.prototype.values, String, String.fromCharCode, String.fromCodePoint, String.raw, String.prototype.at, String.prototype.charAt, String.prototype.charCodeAt, String.prototype.codePointAt, String.prototype.concat, String.prototype.endsWith, String.prototype.includes, String.prototype.indexOf, String.prototype.lastIndexOf, String.prototype.normalize, String.prototype.padEnd, String.prototype.padStart, String.prototype.slice, String.prototype.startsWith, String.prototype.substr, String.prototype.substring, String.prototype.toLowerCase, String.prototype.toString, String.prototype.toUpperCase, String.prototype.trim, String.prototype.trimEnd, String.prototype.trimLeft, String.prototype.trimRight, String.prototype.trimStart, Symbol.for, Symbol.keyFor, unescape ].filter((f) => typeof f === "function") ); var callPassThrough = /* @__PURE__ */ new Set([ Object.freeze, Object.preventExtensions, Object.seal ]); var getterAllowed = [ [Map, /* @__PURE__ */ new Set(["size"])], [ RegExp, /* @__PURE__ */ new Set([ "dotAll", "flags", "global", "hasIndices", "ignoreCase", "multiline", "source", "sticky", "unicode" ]) ], [Set, /* @__PURE__ */ new Set(["size"])] ]; function getPropertyDescriptor(object, name) { let x = object; while ((typeof x === "object" || typeof x === "function") && x !== null) { const d = Object.getOwnPropertyDescriptor(x, name); if (d) { return d; } x = Object.getPrototypeOf(x); } return null; } function isGetter(object, name) { const d = getPropertyDescriptor(object, name); return d != null && d.get != null; } function getElementValues(nodeList, initialScope) { const valueList = []; for (let i = 0; i < nodeList.length; ++i) { const elementNode = nodeList[i]; if (elementNode == null) { valueList.length = i + 1; } else if (elementNode.type === "SpreadElement") { const argument = getStaticValueR(elementNode.argument, initialScope); if (argument == null) { return null; } valueList.push(...argument.value); } else { const element = getStaticValueR(elementNode, initialScope); if (element == null) { return null; } valueList.push(element.value); } } return valueList; } function isEffectivelyConst(variable) { const refs = variable.references; const inits = refs.filter((r) => r.init).length; const reads = refs.filter((r) => r.isReadOnly()).length; if (inits === 1 && reads + inits === refs.length) { return true; } return false; } var operations = Object.freeze({ ArrayExpression(node, initialScope) { const elements = getElementValues(node.elements, initialScope); return elements != null ? { value: elements } : null; }, AssignmentExpression(node, initialScope) { if (node.operator === "=") { return getStaticValueR(node.right, initialScope); } return null; }, //eslint-disable-next-line complexity BinaryExpression(node, initialScope) { if (node.operator === "in" || node.operator === "instanceof") { return null; } const left = getStaticValueR(node.left, initialScope); const right = getStaticValueR(node.right, initialScope); if (left != null && right != null) { switch (node.operator) { case "==": return { value: left.value == right.value }; //eslint-disable-line eqeqeq case "!=": return { value: left.value != right.value }; //eslint-disable-line eqeqeq case "===": return { value: left.value === right.value }; case "!==": return { value: left.value !== right.value }; case "<": return { value: left.value < right.value }; case "<=": return { value: left.value <= right.value }; case ">": return { value: left.value > right.value }; case ">=": return { value: left.value >= right.value }; case "<<": return { value: left.value << right.value }; case ">>": return { value: left.value >> right.value }; case ">>>": return { value: left.value >>> right.value }; case "+": return { value: left.value + right.value }; case "-": return { value: left.value - right.value }; case "*": return { value: left.value * right.value }; case "/": return { value: left.value / right.value }; case "%": return { value: left.value % right.value }; case "**": return { value: __pow(left.value, right.value) }; case "|": return { value: left.value | right.value }; case "^": return { value: left.value ^ right.value }; case "&": return { value: left.value & right.value }; } } return null; }, CallExpression(node, initialScope) { const calleeNode = node.callee; const args = getElementValues(node.arguments, initialScope); if (args != null) { if (calleeNode.type === "MemberExpression") { if (calleeNode.property.type === "PrivateIdentifier") { return null; } const object = getStaticValueR(calleeNode.object, initialScope); if (object != null) { if (object.value == null && (object.optional || node.optional)) { return { value: void 0, optional: true }; } const property = getStaticPropertyNameValue( calleeNode, initialScope ); if (property != null) { const receiver = object.value; const methodName = property.value; if (callAllowed.has(receiver[methodName])) { return { value: receiver[methodName](...args) }; } if (callPassThrough.has(receiver[methodName])) { return { value: args[0] }; } } } } else { const callee = getStaticValueR(calleeNode, initialScope); if (callee != null) { if (callee.value == null && node.optional) { return { value: void 0, optional: true }; } const func = callee.value; if (callAllowed.has(func)) { return { value: func(...args) }; } if (callPassThrough.has(func)) { return { value: args[0] }; } } } } return null; }, ConditionalExpression(node, initialScope) { const test = getStaticValueR(node.test, initialScope); if (test != null) { return test.value ? getStaticValueR(node.consequent, initialScope) : getStaticValueR(node.alternate, initialScope); } return null; }, ExpressionStatement(node, initialScope) { return getStaticValueR(node.expression, initialScope); }, Identifier(node, initialScope) { if (initialScope != null) { const variable = findVariable(initialScope, node); if (variable != null && variable.defs.length === 0 && builtinNames.has(variable.name) && variable.name in globalObject) { return { value: globalObject[variable.name] }; } if (variable != null && variable.defs.length === 1) { const def = variable.defs[0]; if (def.parent && def.type === "Variable" && (def.parent.kind === "const" || isEffectivelyConst(variable)) && // TODO(mysticatea): don't support destructuring here. def.node.id.type === "Identifier") { return getStaticValueR(def.node.init, initialScope); } } } return null; }, Literal(node) { if ((node.regex != null || node.bigint != null) && node.value == null) { return null; } return { value: node.value }; }, LogicalExpression(node, initialScope) { const left = getStaticValueR(node.left, initialScope); if (left != null) { if (node.operator === "||" && Boolean(left.value) === true || node.operator === "&&" && Boolean(left.value) === false || node.operator === "??" && left.value != null) { return left; } const right = getStaticValueR(node.right, initialScope); if (right != null) { return right; } } return null; }, MemberExpression(node, initialScope) { if (node.property.type === "PrivateIdentifier") { return null; } const object = getStaticValueR(node.object, initialScope); if (object != null) { if (object.value == null && (object.optional || node.optional)) { return { value: void 0, optional: true }; } const property = getStaticPropertyNameValue(node, initialScope); if (property != null) { if (!isGetter(object.value, property.value)) { return { value: object.value[property.value] }; } for (const [classFn, allowed] of getterAllowed) { if (object.value instanceof classFn && allowed.has(property.value)) { return { value: object.value[property.value] }; } } } } return null; }, ChainExpression(node, initialScope) { const expression = getStaticValueR(node.expression, initialScope); if (expression != null) { return { value: expression.value }; } return null; }, NewExpression(node, initialScope) { const callee = getStaticValueR(node.callee, initialScope); const args = getElementValues(node.arguments, initialScope); if (callee != null && args != null) { const Func = callee.value; if (callAllowed.has(Func)) { return { value: new Func(...args) }; } } return null; }, ObjectExpression(node, initialScope) { const object = {}; for (const propertyNode of node.properties) { if (propertyNode.type === "Property") { if (propertyNode.kind !== "init") { return null; } const key = getStaticPropertyNameValue( propertyNode, initialScope ); const value = getStaticValueR(propertyNode.value, initialScope); if (key == null || value == null) { return null; } object[key.value] = value.value; } else if (propertyNode.type === "SpreadElement" || propertyNode.type === "ExperimentalSpreadProperty") { const argument = getStaticValueR( propertyNode.argument, initialScope ); if (argument == null) { return null; } Object.assign(object, argument.value); } else { return null; } } return { value: object }; }, SequenceExpression(node, initialScope) { const last = node.expressions[node.expressions.length - 1]; return getStaticValueR(last, initialScope); }, TaggedTemplateExpression(node, initialScope) { const tag = getStaticValueR(node.tag, initialScope); const expressions = getElementValues( node.quasi.expressions, initialScope ); if (tag != null && expressions != null) { const func = tag.value; const strings = node.quasi.quasis.map((q) => q.value.cooked); strings.raw = node.quasi.quasis.map((q) => q.value.raw); if (func === String.raw) { return { value: func(strings, ...expressions) }; } } return null; }, TemplateLiteral(node, initialScope) { const expressions = getElementValues(node.expressions, initialScope); if (expressions != null) { let value = node.quasis[0].value.cooked; for (let i = 0; i < expressions.length; ++i) { value += expressions[i]; value += node.quasis[i + 1].value.cooked; } return { value }; } return null; }, UnaryExpression(node, initialScope) { if (node.operator === "delete") { return null; } if (node.operator === "void") { return { value: void 0 }; } const arg = getStaticValueR(node.argument, initialScope); if (arg != null) { switch (node.operator) { case "-": return { value: -arg.value }; case "+": return { value: +arg.value }; //eslint-disable-line no-implicit-coercion case "!": return { value: !arg.value }; case "~": return { value: ~arg.value }; case "typeof": return { value: typeof arg.value }; } } return null; } }); function getStaticValueR(node, initialScope) { if (node != null && Object.hasOwnProperty.call(operations, node.type)) { return operations[node.type](node, initialScope); } return null; } function getStaticPropertyNameValue(node, initialScope) { const nameNode = node.type === "Property" ? node.key : node.property; if (node.computed) { return getStaticValueR(nameNode, initialScope); } if (nameNode.type === "Identifier") { return { value: nameNode.name }; } if (nameNode.type === "Literal") { if (nameNode.bigint) { return { value: nameNode.bigint }; } return { value: String(nameNode.value) }; } return null; } function getStaticValue(node, initialScope = null) { try { return getStaticValueR(node, initialScope); } catch (_error) { return null; } } function getStringIfConstant(node, initialScope = null) { if (node && node.type === "Literal" && node.value === null) { if (node.regex) { return `/${node.regex.pattern}/${node.regex.flags}`; } if (node.bigint) { return node.bigint; } } const evaluated = getStaticValue(node, initialScope); return evaluated && String(evaluated.value); } function getPropertyName(node, initialScope) { switch (node.type) { case "MemberExpression": if (node.computed) { return getStringIfConstant(node.property, initialScope); } if (node.property.type === "PrivateIdentifier") { return null; } return node.property.name; case "Property": case "MethodDefinition": case "PropertyDefinition": if (node.computed) { return getStringIfConstant(node.key, initialScope); } if (node.key.type === "Literal") { return String(node.key.value); } if (node.key.type === "PrivateIdentifier") { return null; } return node.key.name; } return null; } function getFunctionNameWithKind(node, sourceCode) { const parent = node.parent; const tokens = []; const isObjectMethod = parent.type === "Property" && parent.value === node; const isClassMethod = parent.type === "MethodDefinition" && parent.value === node; const isClassFieldMethod = parent.type === "PropertyDefinition" && parent.value === node; if (isClassMethod || isClassFieldMethod) { if (parent.static) { tokens.push("static"); } if (parent.key.type === "PrivateIdentifier") { tokens.push("private"); } } if (node.async) { tokens.push("async"); } if (node.generator) { tokens.push("generator"); } if (isObjectMethod || isClassMethod) { if (parent.kind === "constructor") { return "constructor"; } if (parent.kind === "get") { tokens.push("getter"); } else if (parent.kind === "set") { tokens.push("setter"); } else { tokens.push("method"); } } else if (isClassFieldMethod) { tokens.push("method"); } else { if (node.type === "ArrowFunctionExpression") { tokens.push("arrow"); } tokens.push("function"); } if (isObjectMethod || isClassMethod || isClassFieldMethod) { if (parent.key.type === "PrivateIdentifier") { tokens.push(`#${parent.key.name}`); } else { const name = getPropertyName(parent); if (name) { tokens.push(`'${name}'`); } else if (sourceCode) { const keyText = sourceCode.getText(parent.key); if (!keyText.includes("\n")) { tokens.push(`[${keyText}]`); } } } } else if (node.id) { tokens.push(`'${node.id.name}'`); } else if (parent.type === "VariableDeclarator" && parent.id && parent.id.type === "Identifier") { tokens.push(`'${parent.id.name}'`); } else if ((parent.type === "AssignmentExpression" || parent.type === "AssignmentPattern") && parent.left && parent.left.type === "Identifier") { tokens.push(`'${parent.left.name}'`); } else if (parent.type === "ExportDefaultDeclaration" && parent.declaration === node) { tokens.push("'default'"); } return tokens.join(" "); } var typeConversionBinaryOps = Object.freeze( /* @__PURE__ */ new Set([ "==", "!=", "<", "<=", ">", ">=", "<<", ">>", ">>>", "+", "-", "*", "/", "%", "|", "^", "&", "in" ]) ); var typeConversionUnaryOps = Object.freeze(/* @__PURE__ */ new Set(["-", "+", "!", "~"])); function isNode(x) { return x !== null && typeof x === "object" && typeof x.type === "string"; } var visitor = Object.freeze( Object.assign(/* @__PURE__ */ Object.create(null), { $visit(node, options, visitorKeys) { const { type } = node; if (typeof this[type] === "function") { return this[type](node, options, visitorKeys); } return this.$visitChildren(node, options, visitorKeys); }, $visitChildren(node, options, visitorKeys) { const { type } = node; for (const key of visitorKeys[type] || eslintVisitorKeys.getKeys(node)) { const value = node[key]; if (Array.isArray(value)) { for (const element of value) { if (isNode(element) && this.$visit(element, options, visitorKeys)) { return true; } } } else if (isNode(value) && this.$visit(value, options, visitorKeys)) { return true; } } return false; }, ArrowFunctionExpression() { return false; }, AssignmentExpression() { return true; }, AwaitExpression() { return true; }, BinaryExpression(node, options, visitorKeys) { if (options.considerImplicitTypeConversion && typeConversionBinaryOps.has(node.operator) && (node.left.type !== "Literal" || node.right.type !== "Literal")) { return true; } return this.$visitChildren(node, options, visitorKeys); }, CallExpression() { return true; }, FunctionExpression() { return false; }, ImportExpression() { return true; }, MemberExpression(node, options, visitorKeys) { if (options.considerGetters) { return true; } if (options.considerImplicitTypeConversion && node.computed && node.property.type !== "Literal") { return true; } return this.$visitChildren(node, options, visitorKeys); }, MethodDefinition(node, options, visitorKeys) { if (options.considerImplicitTypeConversion && node.computed && node.key.type !== "Literal") { return true; } return this.$visitChildren(node, options, visitorKeys); }, NewExpression() { return true; }, Property(node, options, visitorKeys) { if (options.considerImplicitTypeConversion && node.computed && node.key.type !== "Literal") { return true; } return this.$visitChildren(node, options, visitorKeys); }, PropertyDefinition(node, options, visitorKeys) { if (options.considerImplicitTypeConversion && node.computed && node.key.type !== "Literal") { return true; } return this.$visitChildren(node, options, visitorKeys); }, UnaryExpression(node, options, visitorKeys) { if (node.operator === "delete") { return true; } if (options.considerImplicitTypeConversion && typeConversionUnaryOps.has(node.operator) && node.argument.type !== "Literal") { return true; } return this.$visitChildren(node, options, visitorKeys); }, UpdateExpression() { return true; }, YieldExpression() { return true; } }) ); function hasSideEffect(node, sourceCode, { considerGetters = false, considerImplicitTypeConversion = false } = {}) { return visitor.$visit( node, { considerGetters, considerImplicitTypeConversion }, sourceCode.visitorKeys || eslintVisitorKeys.KEYS ); } function getParentSyntaxParen(node, sourceCode) { const parent = node.parent; switch (parent.type) { case "CallExpression": case "NewExpression": if (parent.arguments.length === 1 && parent.arguments[0] === node) { return sourceCode.getTokenAfter( parent.callee, isOpeningParenToken ); } return null; case "DoWhileStatement": if (parent.test === node) { return sourceCode.getTokenAfter( parent.body, isOpeningParenToken ); } return null; case "IfStatement": case "WhileStatement": if (parent.test === node) { return sourceCode.getFirstToken(parent, 1); } return null; case "ImportExpression": if (parent.source === node) { return sourceCode.getFirstToken(parent, 1); } return null; case "SwitchStatement": if (parent.discriminant === node) { return sourceCode.getFirstToken(parent, 1); } return null; case "WithStatement": if (parent.object === node) { return sourceCode.getFirstToken(parent, 1); } return null; default: return null; } } function isParenthesized(timesOrNode, nodeOrSourceCode, optionalSourceCode) { let times, node, sourceCode, maybeLeftParen, maybeRightParen; if (typeof timesOrNode === "number") { times = timesOrNode | 0; node = nodeOrSourceCode; sourceCode = optionalSourceCode; if (!(times >= 1)) { throw new TypeError("'times' should be a positive integer."); } } else { times = 1; node = timesOrNode; sourceCode = nodeOrSourceCode; } if (node == null || // `Program` can't be parenthesized node.parent == null || // `CatchClause.param` can't be parenthesized, example `try {} catch (error) {}` node.parent.type === "CatchClause" && node.parent.param === node) { return false; } maybeLeftParen = maybeRightParen = node; do { maybeLeftParen = sourceCode.getTokenBefore(maybeLeftParen); maybeRightParen = sourceCode.getTokenAfter(maybeRightParen); } while (maybeLeftParen != null && maybeRightParen != null && isOpeningParenToken(maybeLeftParen) && isClosingParenToken(maybeRightParen) && // Avoid false positive such as `if (a) {}` maybeLeftParen !== getParentSyntaxParen(node, sourceCode) && --times > 0); return times === 0; } var placeholder = /\$(?:[$&`']|[1-9][0-9]?)/gu; var internal = /* @__PURE__ */ new WeakMap(); function isEscaped(str, index2) { let escaped = false; for (let i = index2 - 1; i >= 0 && str.charCodeAt(i) === 92; --i) { escaped = !escaped; } return escaped; } function replaceS(matcher, str, replacement) { const chunks = []; let index2 = 0; let match = null; function replacer(key) { switch (key) { case "$$": return "$"; case "$&": return match[0]; case "$`": return str.slice(0, match.index); case "$'": return str.slice(match.index + match[0].length); default: { const i = key.slice(1); if (i in match) { return match[i]; } return key; } } } for (match of matcher.execAll(str)) { chunks.push(str.slice(index2, match.index)); chunks.push(replacement.replace(placeholder, replacer)); index2 = match.index + match[0].length; } chunks.push(str.slice(index2)); return chunks.join(""); } function replaceF(matcher, str, replace) { const chunks = []; let index2 = 0; for (const match of matcher.execAll(str)) { chunks.push(str.slice(index2, match.index)); chunks.push(String(replace(...match, match.index, match.input))); index2 = match.index + match[0].length; } chunks.push(str.slice(index2)); return chunks.join(""); } var PatternMatcher = class { /** * Initialize this matcher. * @param {RegExp} pattern The pattern to match. * @param {{escaped:boolean}} options The options. */ constructor(pattern, { escaped = false } = {}) { if (!(pattern instanceof RegExp)) { throw new TypeError("'pattern' should be a RegExp instance."); } if (!pattern.flags.includes("g")) { throw new Error("'pattern' should contains 'g' flag."); } internal.set(this, { pattern: new RegExp(pattern.source, pattern.flags), escaped: Boolean(escaped) }); } /** * Find the pattern in a given string. * @param {string} str The string to find. * @returns {IterableIterator<RegExpExecArray>} The iterator which iterate the matched information. */ *execAll(str) { const { pattern, escaped } = internal.get(this); let match = null; let lastIndex = 0; pattern.lastIndex = 0; while ((match = pattern.exec(str)) != null) { if (escaped || !isEscaped(str, match.index)) { lastIndex = pattern.lastIndex; yield match; pattern.lastIndex = lastIndex; } } } /** * Check whether the pattern is found in a given string. * @param {string} str The string to check. * @returns {boolean} `true` if the pattern was found in the string. */ test(str) { const it = this.execAll(str); const ret = it.next(); return !ret.done; } /** * Replace a given string. * @param {string} str The string to be replaced. * @param {(string|((...strs:string[])=>string))} replacer The string or function to replace. This is the same as the 2nd argument of `String.prototype.replace`. * @returns {string} The replaced string. */ [Symbol.replace](str, replacer) { return typeof replacer === "function" ? replaceF(this, String(str), replacer) : replaceS(this, String(str), String(replacer)); } }; var IMPORT_TYPE = /^(?:Import|Export(?:All|Default|Named))Declaration$/u; var has = Function.call.bind(Object.hasOwnProperty); var READ = Symbol("read"); var CALL = Symbol("call"); var CONSTRUCT = Symbol("construct"); var ESM = Symbol("esm"); var requireCall = { require: { [CALL]: true } }; function isModifiedGlobal(variable) { return variable == null || variable.defs.length !== 0 || variable.references.some((r) => r.isWrite()); } function isPassThrough(node) { const parent = node.parent; switch (parent && parent.type) { case "ConditionalExpression": return parent.consequent === node || parent.alternate === node; case "LogicalExpression": return true; case "SequenceExpression": return parent.expressions[parent.expressions.length - 1] === node; case "ChainExpression": return true; default: return false; } } var ReferenceTracker = class { /** * Initialize this tracker. * @param {Scope} globalScope The global scope. * @param {object} [options] The options. * @param {"legacy"|"strict"} [options.mode="strict"] The mode to determine the ImportDeclaration's behavior for CJS modules. * @param {string[]} [options.globalObjectNames=["global","globalThis","self","window"]] The variable names for Global Object. */ constructor(globalScope, { mode = "strict", globalObjectNames = ["global", "globalThis", "self", "window"] } = {}) { this.variableStack = []; this.globalScope = globalScope; this.mode = mode; this.globalObjectNames = globalObjectNames.slice(0); } /** * Iterate the references of global variables. * @param {object} traceMap The trace map. * @returns {IterableIterator<{node:Node,path:string[],type:symbol,info:any}>} The iterator to iterate references. */ *iterateGlobalReferences(traceMap) { for (const key of Object.keys(traceMap)) { const nextTraceMap = traceMap[key]; const path = [key]; const variable = this.globalScope.set.get(key); if (isModifiedGlobal(variable)) { continue; } yield* __yieldStar(this._iterateVariableReferences( variable, path, nextTraceMap, true )); } for (const key of this.globalObjectNames) { const path = []; const variable = this.globalScope.set.get(key); if (isModifiedGlobal(variable)) { continue; } yield* __yieldStar(this._iterateVariableReferences( variable, path, traceMap, false )); } } /** * Iterate the references of CommonJS modules. * @param {object} traceMap The trace map. * @returns {IterableIterator<{node:Node,path:string[],type:symbol,info:any}>} The iterator to iterate references. */ *iterateCjsReferences(traceMap) { for (const { node } of this.iterateG