UNPKG

magicast

Version:

Modify a JS/TS file and write back magically just like JSON!

1,597 lines (1,592 loc) 293 kB
import { promises } from 'node:fs'; import 'fs'; import sourceMap from 'source-map-js'; import * as babelParser from '@babel/parser'; function sharedPlugin(fork) { var types = fork.use(typesPlugin); var Type = types.Type; var builtin = types.builtInTypes; var isNumber = builtin.number; function geq(than) { return Type.from( (value) => isNumber.check(value) && value >= than, isNumber + " >= " + than ); } const defaults = { // Functions were used because (among other reasons) that's the most // elegant way to allow for the emptyArray one always to give a new // array instance. "null": function() { return null; }, "emptyArray": function() { return []; }, "false": function() { return false; }, "true": function() { return true; }, "undefined": function() { }, "use strict": function() { return "use strict"; } }; var naiveIsPrimitive = Type.or( builtin.string, builtin.number, builtin.boolean, builtin.null, builtin.undefined ); const isPrimitive = Type.from( (value) => { if (value === null) return true; var type = typeof value; if (type === "object" || type === "function") { return false; } return true; }, naiveIsPrimitive.toString() ); return { geq, defaults, isPrimitive }; } function maybeSetModuleExports(moduleGetter) { try { var nodeModule = moduleGetter(); var originalExports = nodeModule.exports; var defaultExport = originalExports["default"]; } catch { return; } if (defaultExport && defaultExport !== originalExports && typeof originalExports === "object") { Object.assign(defaultExport, originalExports, { "default": defaultExport }); if (originalExports.__esModule) { Object.defineProperty(defaultExport, "__esModule", { value: true }); } nodeModule.exports = defaultExport; } } var __defProp$2 = Object.defineProperty; var __defNormalProp$2 = (obj, key, value) => key in obj ? __defProp$2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField$2 = (obj, key, value) => { __defNormalProp$2(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; const Op$1 = Object.prototype; const objToStr = Op$1.toString; const hasOwn$6 = Op$1.hasOwnProperty; class BaseType { assert(value, deep) { if (!this.check(value, deep)) { var str = shallowStringify(value); throw new Error(str + " does not match type " + this); } return true; } arrayOf() { const elemType = this; return new ArrayType(elemType); } } class ArrayType extends BaseType { constructor(elemType) { super(); this.elemType = elemType; __publicField$2(this, "kind", "ArrayType"); } toString() { return "[" + this.elemType + "]"; } check(value, deep) { return Array.isArray(value) && value.every((elem) => this.elemType.check(elem, deep)); } } class IdentityType extends BaseType { constructor(value) { super(); this.value = value; __publicField$2(this, "kind", "IdentityType"); } toString() { return String(this.value); } check(value, deep) { const result = value === this.value; if (!result && typeof deep === "function") { deep(this, value); } return result; } } class ObjectType extends BaseType { constructor(fields) { super(); this.fields = fields; __publicField$2(this, "kind", "ObjectType"); } toString() { return "{ " + this.fields.join(", ") + " }"; } check(value, deep) { return objToStr.call(value) === objToStr.call({}) && this.fields.every((field) => { return field.type.check(value[field.name], deep); }); } } class OrType extends BaseType { constructor(types) { super(); this.types = types; __publicField$2(this, "kind", "OrType"); } toString() { return this.types.join(" | "); } check(value, deep) { if (this.types.some((type) => type.check(value, !!deep))) { return true; } if (typeof deep === "function") { deep(this, value); } return false; } } class PredicateType extends BaseType { constructor(name, predicate) { super(); this.name = name; this.predicate = predicate; __publicField$2(this, "kind", "PredicateType"); } toString() { return this.name; } check(value, deep) { const result = this.predicate(value, deep); if (!result && typeof deep === "function") { deep(this, value); } return result; } } class Def { constructor(type, typeName) { this.type = type; this.typeName = typeName; __publicField$2(this, "baseNames", []); __publicField$2(this, "ownFields", /* @__PURE__ */ Object.create(null)); // Includes own typeName. Populated during finalization. __publicField$2(this, "allSupertypes", /* @__PURE__ */ Object.create(null)); // Linear inheritance hierarchy. Populated during finalization. __publicField$2(this, "supertypeList", []); // Includes inherited fields. __publicField$2(this, "allFields", /* @__PURE__ */ Object.create(null)); // Non-hidden keys of allFields. __publicField$2(this, "fieldNames", []); // This property will be overridden as true by individual Def instances // when they are finalized. __publicField$2(this, "finalized", false); // False by default until .build(...) is called on an instance. __publicField$2(this, "buildable", false); __publicField$2(this, "buildParams", []); } isSupertypeOf(that) { if (that instanceof Def) { if (this.finalized !== true || that.finalized !== true) { throw new Error(""); } return hasOwn$6.call(that.allSupertypes, this.typeName); } else { throw new Error(that + " is not a Def"); } } checkAllFields(value, deep) { var allFields = this.allFields; if (this.finalized !== true) { throw new Error("" + this.typeName); } function checkFieldByName(name) { var field = allFields[name]; var type = field.type; var child = field.getValue(value); return type.check(child, deep); } return value !== null && typeof value === "object" && Object.keys(allFields).every(checkFieldByName); } bases(...supertypeNames) { var bases = this.baseNames; if (this.finalized) { if (supertypeNames.length !== bases.length) { throw new Error(""); } for (var i = 0; i < supertypeNames.length; i++) { if (supertypeNames[i] !== bases[i]) { throw new Error(""); } } return this; } supertypeNames.forEach((baseName) => { if (bases.indexOf(baseName) < 0) { bases.push(baseName); } }); return this; } } class Field { constructor(name, type, defaultFn, hidden) { this.name = name; this.type = type; this.defaultFn = defaultFn; __publicField$2(this, "hidden"); this.hidden = !!hidden; } toString() { return JSON.stringify(this.name) + ": " + this.type; } getValue(obj) { var value = obj[this.name]; if (typeof value !== "undefined") { return value; } if (typeof this.defaultFn === "function") { value = this.defaultFn.call(obj); } return value; } } function shallowStringify(value) { if (Array.isArray(value)) { return "[" + value.map(shallowStringify).join(", ") + "]"; } if (value && typeof value === "object") { return "{ " + Object.keys(value).map(function(key) { return key + ": " + value[key]; }).join(", ") + " }"; } return JSON.stringify(value); } function typesPlugin(_fork) { const Type = { or(...types) { return new OrType(types.map((type) => Type.from(type))); }, from(value, name) { if (value instanceof ArrayType || value instanceof IdentityType || value instanceof ObjectType || value instanceof OrType || value instanceof PredicateType) { return value; } if (value instanceof Def) { return value.type; } if (isArray.check(value)) { if (value.length !== 1) { throw new Error("only one element type is permitted for typed arrays"); } return new ArrayType(Type.from(value[0])); } if (isObject.check(value)) { return new ObjectType(Object.keys(value).map((name2) => { return new Field(name2, Type.from(value[name2], name2)); })); } if (typeof value === "function") { var bicfIndex = builtInCtorFns.indexOf(value); if (bicfIndex >= 0) { return builtInCtorTypes[bicfIndex]; } if (typeof name !== "string") { throw new Error("missing name"); } return new PredicateType(name, value); } return new IdentityType(value); }, // Define a type whose name is registered in a namespace (the defCache) so // that future definitions will return the same type given the same name. // In particular, this system allows for circular and forward definitions. // The Def object d returned from Type.def may be used to configure the // type d.type by calling methods such as d.bases, d.build, and d.field. def(typeName) { return hasOwn$6.call(defCache, typeName) ? defCache[typeName] : defCache[typeName] = new DefImpl(typeName); }, hasDef(typeName) { return hasOwn$6.call(defCache, typeName); } }; var builtInCtorFns = []; var builtInCtorTypes = []; function defBuiltInType(name, example) { const objStr = objToStr.call(example); const type = new PredicateType( name, (value) => objToStr.call(value) === objStr ); if (example && typeof example.constructor === "function") { builtInCtorFns.push(example.constructor); builtInCtorTypes.push(type); } return type; } const isString = defBuiltInType("string", "truthy"); const isFunction = defBuiltInType("function", function() { }); const isArray = defBuiltInType("array", []); const isObject = defBuiltInType("object", {}); const isRegExp = defBuiltInType("RegExp", /./); const isDate = defBuiltInType("Date", /* @__PURE__ */ new Date()); const isNumber = defBuiltInType("number", 3); const isBoolean = defBuiltInType("boolean", true); const isNull = defBuiltInType("null", null); const isUndefined = defBuiltInType("undefined", void 0); const isBigInt = typeof BigInt === "function" ? defBuiltInType("BigInt", BigInt(1234)) : new PredicateType("BigInt", () => false); const builtInTypes = { string: isString, function: isFunction, array: isArray, object: isObject, RegExp: isRegExp, Date: isDate, number: isNumber, boolean: isBoolean, null: isNull, undefined: isUndefined, BigInt: isBigInt }; var defCache = /* @__PURE__ */ Object.create(null); function defFromValue(value) { if (value && typeof value === "object") { var type = value.type; if (typeof type === "string" && hasOwn$6.call(defCache, type)) { var d = defCache[type]; if (d.finalized) { return d; } } } return null; } class DefImpl extends Def { constructor(typeName) { super( new PredicateType(typeName, (value, deep) => this.check(value, deep)), typeName ); } check(value, deep) { if (this.finalized !== true) { throw new Error( "prematurely checking unfinalized type " + this.typeName ); } if (value === null || typeof value !== "object") { return false; } var vDef = defFromValue(value); if (!vDef) { if (this.typeName === "SourceLocation" || this.typeName === "Position") { return this.checkAllFields(value, deep); } return false; } if (deep && vDef === this) { return this.checkAllFields(value, deep); } if (!this.isSupertypeOf(vDef)) { return false; } if (!deep) { return true; } return vDef.checkAllFields(value, deep) && this.checkAllFields(value, false); } build(...buildParams) { this.buildParams = buildParams; if (this.buildable) { return this; } this.field("type", String, () => this.typeName); this.buildable = true; const addParam = (built, param, arg, isArgAvailable) => { if (hasOwn$6.call(built, param)) return; var all = this.allFields; if (!hasOwn$6.call(all, param)) { throw new Error("" + param); } var field = all[param]; var type = field.type; var value; if (isArgAvailable) { value = arg; } else if (field.defaultFn) { value = field.defaultFn.call(built); } else { var message = "no value or default function given for field " + JSON.stringify(param) + " of " + this.typeName + "(" + this.buildParams.map(function(name) { return all[name]; }).join(", ") + ")"; throw new Error(message); } if (!type.check(value)) { throw new Error( shallowStringify(value) + " does not match field " + field + " of type " + this.typeName ); } built[param] = value; }; const builder = (...args) => { var argc = args.length; if (!this.finalized) { throw new Error( "attempting to instantiate unfinalized type " + this.typeName ); } var built = Object.create(nodePrototype); this.buildParams.forEach(function(param, i) { if (i < argc) { addParam(built, param, args[i], true); } else { addParam(built, param, null, false); } }); Object.keys(this.allFields).forEach(function(param) { addParam(built, param, null, false); }); if (built.type !== this.typeName) { throw new Error(""); } return built; }; builder.from = (obj) => { if (!this.finalized) { throw new Error( "attempting to instantiate unfinalized type " + this.typeName ); } var built = Object.create(nodePrototype); Object.keys(this.allFields).forEach(function(param) { if (hasOwn$6.call(obj, param)) { addParam(built, param, obj[param], true); } else { addParam(built, param, null, false); } }); if (built.type !== this.typeName) { throw new Error(""); } return built; }; Object.defineProperty(builders, getBuilderName(this.typeName), { enumerable: true, value: builder }); return this; } // The reason fields are specified using .field(...) instead of an object // literal syntax is somewhat subtle: the object literal syntax would // support only one key and one value, but with .field(...) we can pass // any number of arguments to specify the field. field(name, type, defaultFn, hidden) { if (this.finalized) { console.error("Ignoring attempt to redefine field " + JSON.stringify(name) + " of finalized type " + JSON.stringify(this.typeName)); return this; } this.ownFields[name] = new Field(name, Type.from(type), defaultFn, hidden); return this; } finalize() { if (!this.finalized) { var allFields = this.allFields; var allSupertypes = this.allSupertypes; this.baseNames.forEach((name) => { var def = defCache[name]; if (def instanceof Def) { def.finalize(); extend(allFields, def.allFields); extend(allSupertypes, def.allSupertypes); } else { var message = "unknown supertype name " + JSON.stringify(name) + " for subtype " + JSON.stringify(this.typeName); throw new Error(message); } }); extend(allFields, this.ownFields); allSupertypes[this.typeName] = this; this.fieldNames.length = 0; for (var fieldName in allFields) { if (hasOwn$6.call(allFields, fieldName) && !allFields[fieldName].hidden) { this.fieldNames.push(fieldName); } } Object.defineProperty(namedTypes, this.typeName, { enumerable: true, value: this.type }); this.finalized = true; populateSupertypeList(this.typeName, this.supertypeList); if (this.buildable && this.supertypeList.lastIndexOf("Expression") >= 0) { wrapExpressionBuilderWithStatement(this.typeName); } } } } function getSupertypeNames(typeName) { if (!hasOwn$6.call(defCache, typeName)) { throw new Error(""); } var d = defCache[typeName]; if (d.finalized !== true) { throw new Error(""); } return d.supertypeList.slice(1); } function computeSupertypeLookupTable(candidates) { var table = {}; var typeNames = Object.keys(defCache); var typeNameCount = typeNames.length; for (var i = 0; i < typeNameCount; ++i) { var typeName = typeNames[i]; var d = defCache[typeName]; if (d.finalized !== true) { throw new Error("" + typeName); } for (var j = 0; j < d.supertypeList.length; ++j) { var superTypeName = d.supertypeList[j]; if (hasOwn$6.call(candidates, superTypeName)) { table[typeName] = superTypeName; break; } } } return table; } var builders = /* @__PURE__ */ Object.create(null); var nodePrototype = {}; function defineMethod(name, func) { var old = nodePrototype[name]; if (isUndefined.check(func)) { delete nodePrototype[name]; } else { isFunction.assert(func); Object.defineProperty(nodePrototype, name, { enumerable: true, // For discoverability. configurable: true, // For delete proto[name]. value: func }); } return old; } function getBuilderName(typeName) { return typeName.replace(/^[A-Z]+/, function(upperCasePrefix) { var len = upperCasePrefix.length; switch (len) { case 0: return ""; case 1: return upperCasePrefix.toLowerCase(); default: return upperCasePrefix.slice( 0, len - 1 ).toLowerCase() + upperCasePrefix.charAt(len - 1); } }); } function getStatementBuilderName(typeName) { typeName = getBuilderName(typeName); return typeName.replace(/(Expression)?$/, "Statement"); } var namedTypes = {}; function getFieldNames(object) { var d = defFromValue(object); if (d) { return d.fieldNames.slice(0); } if ("type" in object) { throw new Error( "did not recognize object of type " + JSON.stringify(object.type) ); } return Object.keys(object); } function getFieldValue(object, fieldName) { var d = defFromValue(object); if (d) { var field = d.allFields[fieldName]; if (field) { return field.getValue(object); } } return object && object[fieldName]; } function eachField(object, callback, context) { getFieldNames(object).forEach(function(name) { callback.call(this, name, getFieldValue(object, name)); }, context); } function someField(object, callback, context) { return getFieldNames(object).some(function(name) { return callback.call(this, name, getFieldValue(object, name)); }, context); } function wrapExpressionBuilderWithStatement(typeName) { var wrapperName = getStatementBuilderName(typeName); if (builders[wrapperName]) return; var wrapped = builders[getBuilderName(typeName)]; if (!wrapped) return; const builder = function(...args) { return builders.expressionStatement(wrapped.apply(builders, args)); }; builder.from = function(...args) { return builders.expressionStatement(wrapped.from.apply(builders, args)); }; builders[wrapperName] = builder; } function populateSupertypeList(typeName, list) { list.length = 0; list.push(typeName); var lastSeen = /* @__PURE__ */ Object.create(null); for (var pos = 0; pos < list.length; ++pos) { typeName = list[pos]; var d = defCache[typeName]; if (d.finalized !== true) { throw new Error(""); } if (hasOwn$6.call(lastSeen, typeName)) { delete list[lastSeen[typeName]]; } lastSeen[typeName] = pos; list.push.apply(list, d.baseNames); } for (var to = 0, from = to, len = list.length; from < len; ++from) { if (hasOwn$6.call(list, from)) { list[to++] = list[from]; } } list.length = to; } function extend(into, from) { Object.keys(from).forEach(function(name) { into[name] = from[name]; }); return into; } function finalize() { Object.keys(defCache).forEach(function(name) { defCache[name].finalize(); }); } return { Type, builtInTypes, getSupertypeNames, computeSupertypeLookupTable, builders, defineMethod, getBuilderName, getStatementBuilderName, namedTypes, getFieldNames, getFieldValue, eachField, someField, finalize }; } maybeSetModuleExports(() => module); var Op = Object.prototype; var hasOwn$5 = Op.hasOwnProperty; function pathPlugin(fork) { var types = fork.use(typesPlugin); var isArray = types.builtInTypes.array; var isNumber = types.builtInTypes.number; const Path = function Path2(value, parentPath, name) { if (!(this instanceof Path2)) { throw new Error("Path constructor cannot be invoked without 'new'"); } if (parentPath) { if (!(parentPath instanceof Path2)) { throw new Error(""); } } else { parentPath = null; name = null; } this.value = value; this.parentPath = parentPath; this.name = name; this.__childCache = null; }; var Pp = Path.prototype; function getChildCache(path) { return path.__childCache || (path.__childCache = /* @__PURE__ */ Object.create(null)); } function getChildPath(path, name) { var cache = getChildCache(path); var actualChildValue = path.getValueProperty(name); var childPath = cache[name]; if (!hasOwn$5.call(cache, name) || // Ensure consistency between cache and reality. childPath.value !== actualChildValue) { childPath = cache[name] = new path.constructor( actualChildValue, path, name ); } return childPath; } Pp.getValueProperty = function getValueProperty(name) { return this.value[name]; }; Pp.get = function get(...names) { var path = this; var count = names.length; for (var i = 0; i < count; ++i) { path = getChildPath(path, names[i]); } return path; }; Pp.each = function each(callback, context) { var childPaths = []; var len = this.value.length; var i = 0; for (var i = 0; i < len; ++i) { if (hasOwn$5.call(this.value, i)) { childPaths[i] = this.get(i); } } context = context || this; for (i = 0; i < len; ++i) { if (hasOwn$5.call(childPaths, i)) { callback.call(context, childPaths[i]); } } }; Pp.map = function map(callback, context) { var result = []; this.each(function(childPath) { result.push(callback.call(this, childPath)); }, context); return result; }; Pp.filter = function filter(callback, context) { var result = []; this.each(function(childPath) { if (callback.call(this, childPath)) { result.push(childPath); } }, context); return result; }; function emptyMoves() { } function getMoves(path, offset, start, end) { isArray.assert(path.value); if (offset === 0) { return emptyMoves; } var length = path.value.length; if (length < 1) { return emptyMoves; } var argc = arguments.length; if (argc === 2) { start = 0; end = length; } else if (argc === 3) { start = Math.max(start, 0); end = length; } else { start = Math.max(start, 0); end = Math.min(end, length); } isNumber.assert(start); isNumber.assert(end); var moves = /* @__PURE__ */ Object.create(null); var cache = getChildCache(path); for (var i = start; i < end; ++i) { if (hasOwn$5.call(path.value, i)) { var childPath = path.get(i); if (childPath.name !== i) { throw new Error(""); } var newIndex = i + offset; childPath.name = newIndex; moves[newIndex] = childPath; delete cache[i]; } } delete cache.length; return function() { for (var newIndex2 in moves) { var childPath2 = moves[newIndex2]; if (childPath2.name !== +newIndex2) { throw new Error(""); } cache[newIndex2] = childPath2; path.value[newIndex2] = childPath2.value; } }; } Pp.shift = function shift() { var move = getMoves(this, -1); var result = this.value.shift(); move(); return result; }; Pp.unshift = function unshift(...args) { var move = getMoves(this, args.length); var result = this.value.unshift.apply(this.value, args); move(); return result; }; Pp.push = function push(...args) { isArray.assert(this.value); delete getChildCache(this).length; return this.value.push.apply(this.value, args); }; Pp.pop = function pop() { isArray.assert(this.value); var cache = getChildCache(this); delete cache[this.value.length - 1]; delete cache.length; return this.value.pop(); }; Pp.insertAt = function insertAt(index) { var argc = arguments.length; var move = getMoves(this, argc - 1, index); if (move === emptyMoves && argc <= 1) { return this; } index = Math.max(index, 0); for (var i = 1; i < argc; ++i) { this.value[index + i - 1] = arguments[i]; } move(); return this; }; Pp.insertBefore = function insertBefore(...args) { var pp = this.parentPath; var argc = args.length; var insertAtArgs = [this.name]; for (var i = 0; i < argc; ++i) { insertAtArgs.push(args[i]); } return pp.insertAt.apply(pp, insertAtArgs); }; Pp.insertAfter = function insertAfter(...args) { var pp = this.parentPath; var argc = args.length; var insertAtArgs = [this.name + 1]; for (var i = 0; i < argc; ++i) { insertAtArgs.push(args[i]); } return pp.insertAt.apply(pp, insertAtArgs); }; function repairRelationshipWithParent(path) { if (!(path instanceof Path)) { throw new Error(""); } var pp = path.parentPath; if (!pp) { return path; } var parentValue = pp.value; var parentCache = getChildCache(pp); if (parentValue[path.name] === path.value) { parentCache[path.name] = path; } else if (isArray.check(parentValue)) { var i = parentValue.indexOf(path.value); if (i >= 0) { parentCache[path.name = i] = path; } } else { parentValue[path.name] = path.value; parentCache[path.name] = path; } if (parentValue[path.name] !== path.value) { throw new Error(""); } if (path.parentPath.get(path.name) !== path) { throw new Error(""); } return path; } Pp.replace = function replace(replacement) { var results = []; var parentValue = this.parentPath.value; var parentCache = getChildCache(this.parentPath); var count = arguments.length; repairRelationshipWithParent(this); if (isArray.check(parentValue)) { var originalLength = parentValue.length; var move = getMoves(this.parentPath, count - 1, this.name + 1); var spliceArgs = [this.name, 1]; for (var i = 0; i < count; ++i) { spliceArgs.push(arguments[i]); } var splicedOut = parentValue.splice.apply(parentValue, spliceArgs); if (splicedOut[0] !== this.value) { throw new Error(""); } if (parentValue.length !== originalLength - 1 + count) { throw new Error(""); } move(); if (count === 0) { delete this.value; delete parentCache[this.name]; this.__childCache = null; } else { if (parentValue[this.name] !== replacement) { throw new Error(""); } if (this.value !== replacement) { this.value = replacement; this.__childCache = null; } for (i = 0; i < count; ++i) { results.push(this.parentPath.get(this.name + i)); } if (results[0] !== this) { throw new Error(""); } } } else if (count === 1) { if (this.value !== replacement) { this.__childCache = null; } this.value = parentValue[this.name] = replacement; results.push(this); } else if (count === 0) { delete parentValue[this.name]; delete this.value; this.__childCache = null; } else { throw new Error("Could not replace path"); } return results; }; return Path; } maybeSetModuleExports(() => module); var hasOwn$4 = Object.prototype.hasOwnProperty; function scopePlugin(fork) { var types = fork.use(typesPlugin); var Type = types.Type; var namedTypes = types.namedTypes; var Node = namedTypes.Node; var Expression = namedTypes.Expression; var isArray = types.builtInTypes.array; var b = types.builders; const Scope = function Scope2(path, parentScope) { if (!(this instanceof Scope2)) { throw new Error("Scope constructor cannot be invoked without 'new'"); } if (!TypeParameterScopeType.check(path.value)) { ScopeType.assert(path.value); } var depth; if (parentScope) { if (!(parentScope instanceof Scope2)) { throw new Error(""); } depth = parentScope.depth + 1; } else { parentScope = null; depth = 0; } Object.defineProperties(this, { path: { value: path }, node: { value: path.value }, isGlobal: { value: !parentScope, enumerable: true }, depth: { value: depth }, parent: { value: parentScope }, bindings: { value: {} }, types: { value: {} } }); }; var ScopeType = Type.or( // Program nodes introduce global scopes. namedTypes.Program, // Function is the supertype of FunctionExpression, // FunctionDeclaration, ArrowExpression, etc. namedTypes.Function, // In case you didn't know, the caught parameter shadows any variable // of the same name in an outer scope. namedTypes.CatchClause ); var TypeParameterScopeType = Type.or( namedTypes.Function, namedTypes.ClassDeclaration, namedTypes.ClassExpression, namedTypes.InterfaceDeclaration, namedTypes.TSInterfaceDeclaration, namedTypes.TypeAlias, namedTypes.TSTypeAliasDeclaration ); var FlowOrTSTypeParameterType = Type.or( namedTypes.TypeParameter, namedTypes.TSTypeParameter ); Scope.isEstablishedBy = function(node) { return ScopeType.check(node) || TypeParameterScopeType.check(node); }; var Sp = Scope.prototype; Sp.didScan = false; Sp.declares = function(name) { this.scan(); return hasOwn$4.call(this.bindings, name); }; Sp.declaresType = function(name) { this.scan(); return hasOwn$4.call(this.types, name); }; Sp.declareTemporary = function(prefix) { if (prefix) { if (!/^[a-z$_]/i.test(prefix)) { throw new Error(""); } } else { prefix = "t$"; } prefix += this.depth.toString(36) + "$"; this.scan(); var index = 0; while (this.declares(prefix + index)) { ++index; } var name = prefix + index; return this.bindings[name] = types.builders.identifier(name); }; Sp.injectTemporary = function(identifier, init) { identifier || (identifier = this.declareTemporary()); var bodyPath = this.path.get("body"); if (namedTypes.BlockStatement.check(bodyPath.value)) { bodyPath = bodyPath.get("body"); } bodyPath.unshift( b.variableDeclaration( "var", [b.variableDeclarator(identifier, init || null)] ) ); return identifier; }; Sp.scan = function(force) { if (force || !this.didScan) { for (var name in this.bindings) { delete this.bindings[name]; } for (var name in this.types) { delete this.types[name]; } scanScope(this.path, this.bindings, this.types); this.didScan = true; } }; Sp.getBindings = function() { this.scan(); return this.bindings; }; Sp.getTypes = function() { this.scan(); return this.types; }; function scanScope(path, bindings, scopeTypes) { var node = path.value; if (TypeParameterScopeType.check(node)) { const params = path.get("typeParameters", "params"); if (isArray.check(params.value)) { params.each((childPath) => { addTypeParameter(childPath, scopeTypes); }); } } if (ScopeType.check(node)) { if (namedTypes.CatchClause.check(node)) { addPattern(path.get("param"), bindings); } else { recursiveScanScope(path, bindings, scopeTypes); } } } function recursiveScanScope(path, bindings, scopeTypes) { var node = path.value; if (path.parent && namedTypes.FunctionExpression.check(path.parent.node) && path.parent.node.id) { addPattern(path.parent.get("id"), bindings); } if (!node) ; else if (isArray.check(node)) { path.each((childPath) => { recursiveScanChild(childPath, bindings, scopeTypes); }); } else if (namedTypes.Function.check(node)) { path.get("params").each((paramPath) => { addPattern(paramPath, bindings); }); recursiveScanChild(path.get("body"), bindings, scopeTypes); recursiveScanScope(path.get("typeParameters"), bindings, scopeTypes); } else if (namedTypes.TypeAlias && namedTypes.TypeAlias.check(node) || namedTypes.InterfaceDeclaration && namedTypes.InterfaceDeclaration.check(node) || namedTypes.TSTypeAliasDeclaration && namedTypes.TSTypeAliasDeclaration.check(node) || namedTypes.TSInterfaceDeclaration && namedTypes.TSInterfaceDeclaration.check(node)) { addTypePattern(path.get("id"), scopeTypes); } else if (namedTypes.VariableDeclarator.check(node)) { addPattern(path.get("id"), bindings); recursiveScanChild(path.get("init"), bindings, scopeTypes); } else if (node.type === "ImportSpecifier" || node.type === "ImportNamespaceSpecifier" || node.type === "ImportDefaultSpecifier") { addPattern( // Esprima used to use the .name field to refer to the local // binding identifier for ImportSpecifier nodes, but .id for // ImportNamespaceSpecifier and ImportDefaultSpecifier nodes. // ESTree/Acorn/ESpree use .local for all three node types. path.get(node.local ? "local" : node.name ? "name" : "id"), bindings ); } else if (Node.check(node) && !Expression.check(node)) { types.eachField(node, function(name, child) { var childPath = path.get(name); if (!pathHasValue(childPath, child)) { throw new Error(""); } recursiveScanChild(childPath, bindings, scopeTypes); }); } } function pathHasValue(path, value) { if (path.value === value) { return true; } if (Array.isArray(path.value) && path.value.length === 0 && Array.isArray(value) && value.length === 0) { return true; } return false; } function recursiveScanChild(path, bindings, scopeTypes) { var node = path.value; if (!node || Expression.check(node)) ; else if (namedTypes.FunctionDeclaration.check(node) && node.id !== null) { addPattern(path.get("id"), bindings); } else if (namedTypes.ClassDeclaration && namedTypes.ClassDeclaration.check(node) && node.id !== null) { addPattern(path.get("id"), bindings); recursiveScanScope(path.get("typeParameters"), bindings, scopeTypes); } else if (namedTypes.InterfaceDeclaration && namedTypes.InterfaceDeclaration.check(node) || namedTypes.TSInterfaceDeclaration && namedTypes.TSInterfaceDeclaration.check(node)) { addTypePattern(path.get("id"), scopeTypes); } else if (ScopeType.check(node)) { if (namedTypes.CatchClause.check(node) && // TODO Broaden this to accept any pattern. namedTypes.Identifier.check(node.param)) { var catchParamName = node.param.name; var hadBinding = hasOwn$4.call(bindings, catchParamName); recursiveScanScope(path.get("body"), bindings, scopeTypes); if (!hadBinding) { delete bindings[catchParamName]; } } } else { recursiveScanScope(path, bindings, scopeTypes); } } function addPattern(patternPath, bindings) { var pattern = patternPath.value; namedTypes.Pattern.assert(pattern); if (namedTypes.Identifier.check(pattern)) { if (hasOwn$4.call(bindings, pattern.name)) { bindings[pattern.name].push(patternPath); } else { bindings[pattern.name] = [patternPath]; } } else if (namedTypes.AssignmentPattern && namedTypes.AssignmentPattern.check(pattern)) { addPattern(patternPath.get("left"), bindings); } else if (namedTypes.ObjectPattern && namedTypes.ObjectPattern.check(pattern)) { patternPath.get("properties").each(function(propertyPath) { var property = propertyPath.value; if (namedTypes.Pattern.check(property)) { addPattern(propertyPath, bindings); } else if (namedTypes.Property.check(property) || namedTypes.ObjectProperty && namedTypes.ObjectProperty.check(property)) { addPattern(propertyPath.get("value"), bindings); } else if (namedTypes.SpreadProperty && namedTypes.SpreadProperty.check(property)) { addPattern(propertyPath.get("argument"), bindings); } }); } else if (namedTypes.ArrayPattern && namedTypes.ArrayPattern.check(pattern)) { patternPath.get("elements").each(function(elementPath) { var element = elementPath.value; if (namedTypes.Pattern.check(element)) { addPattern(elementPath, bindings); } else if (namedTypes.SpreadElement && namedTypes.SpreadElement.check(element)) { addPattern(elementPath.get("argument"), bindings); } }); } else if (namedTypes.PropertyPattern && namedTypes.PropertyPattern.check(pattern)) { addPattern(patternPath.get("pattern"), bindings); } else if (namedTypes.SpreadElementPattern && namedTypes.SpreadElementPattern.check(pattern) || namedTypes.RestElement && namedTypes.RestElement.check(pattern) || namedTypes.SpreadPropertyPattern && namedTypes.SpreadPropertyPattern.check(pattern)) { addPattern(patternPath.get("argument"), bindings); } } function addTypePattern(patternPath, types2) { var pattern = patternPath.value; namedTypes.Pattern.assert(pattern); if (namedTypes.Identifier.check(pattern)) { if (hasOwn$4.call(types2, pattern.name)) { types2[pattern.name].push(patternPath); } else { types2[pattern.name] = [patternPath]; } } } function addTypeParameter(parameterPath, types2) { var parameter = parameterPath.value; FlowOrTSTypeParameterType.assert(parameter); if (hasOwn$4.call(types2, parameter.name)) { types2[parameter.name].push(parameterPath); } else { types2[parameter.name] = [parameterPath]; } } Sp.lookup = function(name) { for (var scope = this; scope; scope = scope.parent) if (scope.declares(name)) break; return scope; }; Sp.lookupType = function(name) { for (var scope = this; scope; scope = scope.parent) if (scope.declaresType(name)) break; return scope; }; Sp.getGlobalScope = function() { var scope = this; while (!scope.isGlobal) scope = scope.parent; return scope; }; return Scope; } maybeSetModuleExports(() => module); function nodePathPlugin(fork) { var types = fork.use(typesPlugin); var n = types.namedTypes; var b = types.builders; var isNumber = types.builtInTypes.number; var isArray = types.builtInTypes.array; var Path2 = fork.use(pathPlugin); var Scope2 = fork.use(scopePlugin); const NodePath = function NodePath2(value, parentPath, name) { if (!(this instanceof NodePath2)) { throw new Error("NodePath constructor cannot be invoked without 'new'"); } Path2.call(this, value, parentPath, name); }; var NPp = NodePath.prototype = Object.create(Path2.prototype, { constructor: { value: NodePath, enumerable: false, writable: true, configurable: true } }); Object.defineProperties(NPp, { node: { get: function() { Object.defineProperty(this, "node", { configurable: true, // Enable deletion. value: this._computeNode() }); return this.node; } }, parent: { get: function() { Object.defineProperty(this, "parent", { configurable: true, // Enable deletion. value: this._computeParent() }); return this.parent; } }, scope: { get: function() { Object.defineProperty(this, "scope", { configurable: true, // Enable deletion. value: this._computeScope() }); return this.scope; } } }); NPp.replace = function() { delete this.node; delete this.parent; delete this.scope; return Path2.prototype.replace.apply(this, arguments); }; NPp.prune = function() { var remainingNodePath = this.parent; this.replace(); return cleanUpNodesAfterPrune(remainingNodePath); }; NPp._computeNode = function() { var value = this.value; if (n.Node.check(value)) { return value; } var pp = this.parentPath; return pp && pp.node || null; }; NPp._computeParent = function() { var value = this.value; var pp = this.parentPath; if (!n.Node.check(value)) { while (pp && !n.Node.check(pp.value)) { pp = pp.parentPath; } if (pp) { pp = pp.parentPath; } } while (pp && !n.Node.check(pp.value)) { pp = pp.parentPath; } return pp || null; }; NPp._computeScope = function() { var value = this.value; var pp = this.parentPath; var scope = pp && pp.scope; if (n.Node.check(value) && Scope2.isEstablishedBy(value)) { scope = new Scope2(this, scope); } return scope || null; }; NPp.getValueProperty = function(name) { return types.getFieldValue(this.value, name); }; NPp.needsParens = function(assumeExpressionContext) { var pp = this.parentPath; if (!pp) { return false; } var node = this.value; if (!n.Expression.check(node)) { return false; } if (node.type === "Identifier") { return false; } while (!n.Node.check(pp.value)) { pp = pp.parentPath; if (!pp) { return false; } } var parent = pp.value; switch (node.type) { case "UnaryExpression": case "SpreadElement": case "SpreadProperty": return parent.type === "MemberExpression" && this.name === "object" && parent.object === node; case "BinaryExpression": case "LogicalExpression": switch (parent.type) { case "CallExpression": return this.name === "callee" && parent.callee === node; case "UnaryExpression": case "SpreadElement": case "SpreadProperty": return true; case "MemberExpression": return this.name === "object" && parent.object === node; case "BinaryExpression": case "LogicalExpression": { const n2 = node; const po = parent.operator; const pp2 = PRECEDENCE[po]; const no = n2.operator; const np = PRECEDENCE[no]; if (pp2 > np) { return true; } if (pp2 === np && this.name === "right") { if (parent.right !== n2) { throw new Error("Nodes must be equal"); } return true; } } default: return false; } case "SequenceExpression": switch (parent.type) { case "ForStatement": return false; case "ExpressionStatement": return this.name !== "expression"; default: return true; } case "YieldExpression": switch (parent.type) { case "BinaryExpression": case "LogicalExpression": case "UnaryExpression": case "SpreadElement": case "SpreadProperty": case "CallExpression": case "MemberExpression": case "NewExpression": case "ConditionalExpression": case "YieldExpression": return true; default: return false; } case "Literal": return parent.type === "MemberExpression" && isNumber.check(node.value) && this.name === "object" && parent.object === node; case "AssignmentExpression": case "ConditionalExpression": switch (parent.type) { case "UnaryExpression": case "SpreadElement": case "SpreadProperty": case "BinaryExpression": case "LogicalExpression": return true; case "CallExpression": return this.name === "callee" && parent.callee === node; case "ConditionalExpression": return this.name === "test" && parent.test === node; case "MemberExpression": return this.name === "object" && parent.object === node; default: return false; } default: if (parent.type === "NewExpression" && this.name === "callee" && parent.callee === node) { return containsCallExpression(node); } } if (assumeExpressionContext !== true && !this.canBeFirstInStatement() && this.firstInStatement()) return true; return false; }; function isBinary(node) { return n.BinaryExpression.check(node) || n.LogicalExpression.check(node); } var PRECEDENCE = {}; [ ["||"], ["&&"], ["|"], ["^"], ["&"], ["==", "===", "!=", "!=="], ["<", ">", "<=", ">=", "in", "instanceof"], [">>", "<<", ">>>"], ["+", "-"], ["*", "/", "%"] ].forEach(function(tier, i) { tier.forEach(function(op) { PRECEDENCE[op] = i; }); }); function containsCallExpression(node) { if (n.CallExpression.check(node)) { return true; } if (isArray.check(node)) { return node.some(containsCallExpression); } if (n.Node.check(node)) { return types.someField(node, function(_name, child) { return containsCallExpression(child); }); } return false; } NPp.canBeFirstInStatement = function() { var node = this.node; return !n.FunctionExpression.check(node) && !n.ObjectExpression.check(node); }; NPp.firstInStatement = function() { return firstInStatement(this); }; function firstInStatement(path) { for (var node, parent; path.parent; path = path.parent) { node = path.node; parent = path.parent.node; if (n.BlockStatement.check(parent) && path.parent.name === "body" && path.name === 0) { if (parent.body[0] !== node) { throw new Error("Nodes must be equal"); } return true; } if (n.ExpressionStatement.check(parent) && path.name === "expression") { if (parent.expression !== node) { throw new Error("Nodes must be equal"); } return true; } if (n.SequenceExpression.check(parent) && path.parent.name === "expressions" && path.name === 0) { if (parent.expressions[0] !== node) { throw new Error("Nodes must be equal"); } continue; } if (n.CallExpression.check(parent) && path.name === "callee") { if (parent.callee !== node) { throw new Error("Nodes must be equal"); } continue; } if (n.MemberExpression.check(parent) && path.name === "object") { if (parent.object !== node) { throw new Error("Nodes must be equal"); } continue; } if (n.ConditionalExpression.check(parent) && path.name === "test") { if (parent.test !== node) { throw new Error("Nodes must be equal"); } continue; } if (isBinary(parent) && path.name === "left") { if (parent.left !== node) { throw new Error("Nodes must be equal"); } continue; } if (n.UnaryExpression.check(parent) && !parent.prefix && path.name === "argument") { if (parent.argument !== node) { throw new Error("Nodes must be equal"); } continue; } return false; } return true; } function cleanUpNodesAfterPrune(remainingNodePath) { if (n.VariableDeclaration.check(remainingNodePath.node)) { var declarations = remainingNodePath.get("declarations").value; if (!declarations || declarations.length === 0) { return remainingNodePath.prune(); } } else if (n.ExpressionStatement.check(remainingNodePath.node)) { if (!remainingNodePath.get("expression").value) { return remaini