Changing front

This commit is contained in:
ewandor committed 2023-01-16 17:49:38 +01:00
1 parent 0b8a93b256
commit 4fe4be7730
48586 files changed
+4725790 -17464

No files matched your search

+74
View File
@@ -0,0 +1,74 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _helperPluginUtils = require("@babel/helper-plugin-utils");
var _helperCompilationTargets = require("@babel/helper-compilation-targets");
var _helperAnnotateAsPure = require("@babel/helper-annotate-as-pure");
var _helperFunctionName = require("@babel/helper-function-name");
var _helperSplitExportDeclaration = require("@babel/helper-split-export-declaration");
var _core = require("@babel/core");
var _globals = require("globals");
var _transformClass = require("./transformClass");
const getBuiltinClasses = category => Object.keys(_globals[category]).filter(name => /^[A-Z]/.test(name));
const builtinClasses = new Set([...getBuiltinClasses("builtin"), ...getBuiltinClasses("browser")]);
var _default = (0, _helperPluginUtils.declare)((api, options) => {
var _api$assumption, _api$assumption2, _api$assumption3, _api$assumption4;
api.assertVersion(7);
const {
loose = false
} = options;
const setClassMethods = (_api$assumption = api.assumption("setClassMethods")) != null ? _api$assumption : loose;
const constantSuper = (_api$assumption2 = api.assumption("constantSuper")) != null ? _api$assumption2 : loose;
const superIsCallableConstructor = (_api$assumption3 = api.assumption("superIsCallableConstructor")) != null ? _api$assumption3 : loose;
const noClassCalls = (_api$assumption4 = api.assumption("noClassCalls")) != null ? _api$assumption4 : loose;
const supportUnicodeId = !(0, _helperCompilationTargets.isRequired)("transform-unicode-escapes", api.targets());
const VISITED = new WeakSet();
return {
name: "transform-classes",
visitor: {
ExportDefaultDeclaration(path) {
if (!path.get("declaration").isClassDeclaration()) return;
(0, _helperSplitExportDeclaration.default)(path);
},
ClassDeclaration(path) {
const {
node
} = path;
const ref = node.id || path.scope.generateUidIdentifier("class");
path.replaceWith(_core.types.variableDeclaration("let", [_core.types.variableDeclarator(ref, _core.types.toExpression(node))]));
},
ClassExpression(path, state) {
const {
node
} = path;
if (VISITED.has(node)) return;
const inferred = (0, _helperFunctionName.default)(path, undefined, supportUnicodeId);
if (inferred && inferred !== node) {
path.replaceWith(inferred);
return;
}
VISITED.add(node);
const [replacedPath] = path.replaceWith((0, _transformClass.default)(path, state.file, builtinClasses, loose, {
setClassMethods,
constantSuper,
superIsCallableConstructor,
noClassCalls
}, supportUnicodeId));
if (replacedPath.isCallExpression()) {
(0, _helperAnnotateAsPure.default)(replacedPath);
const callee = replacedPath.get("callee");
if (callee.isArrowFunctionExpression()) {
callee.arrowFunctionToExpression();
}
}
}
}
};
});
exports.default = _default;
//# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
{"version":3,"names":["getBuiltinClasses","category","Object","keys","globals","filter","name","test","builtinClasses","Set","declare","api","options","assertVersion","loose","setClassMethods","assumption","constantSuper","superIsCallableConstructor","noClassCalls","supportUnicodeId","isRequired","targets","VISITED","WeakSet","visitor","ExportDefaultDeclaration","path","get","isClassDeclaration","splitExportDeclaration","ClassDeclaration","node","ref","id","scope","generateUidIdentifier","replaceWith","t","variableDeclaration","variableDeclarator","toExpression","ClassExpression","state","has","inferred","nameFunction","undefined","add","replacedPath","transformClass","file","isCallExpression","annotateAsPure","callee","isArrowFunctionExpression","arrowFunctionToExpression"],"sources":["../src/index.ts"],"sourcesContent":["import { declare } from \"@babel/helper-plugin-utils\";\nimport { isRequired } from \"@babel/helper-compilation-targets\";\nimport annotateAsPure from \"@babel/helper-annotate-as-pure\";\nimport nameFunction from \"@babel/helper-function-name\";\nimport splitExportDeclaration from \"@babel/helper-split-export-declaration\";\nimport { types as t } from \"@babel/core\";\nimport globals from \"globals\";\nimport transformClass from \"./transformClass\";\n\nconst getBuiltinClasses = (category: keyof typeof globals) =>\n Object.keys(globals[category]).filter(name => /^[A-Z]/.test(name));\n\nconst builtinClasses = new Set([\n ...getBuiltinClasses(\"builtin\"),\n ...getBuiltinClasses(\"browser\"),\n]);\n\nexport interface Options {\n loose?: boolean;\n}\n\nexport default declare((api, options: Options) => {\n api.assertVersion(7);\n\n const { loose = false } = options;\n\n const setClassMethods = (api.assumption(\"setClassMethods\") ??\n loose) as boolean;\n const constantSuper = (api.assumption(\"constantSuper\") ?? loose) as boolean;\n const superIsCallableConstructor = (api.assumption(\n \"superIsCallableConstructor\",\n ) ?? loose) as boolean;\n const noClassCalls = (api.assumption(\"noClassCalls\") ?? loose) as boolean;\n const supportUnicodeId = !isRequired(\n \"transform-unicode-escapes\",\n api.targets(),\n );\n\n // todo: investigate traversal requeueing\n const VISITED = new WeakSet();\n\n return {\n name: \"transform-classes\",\n\n visitor: {\n ExportDefaultDeclaration(path) {\n if (!path.get(\"declaration\").isClassDeclaration()) return;\n splitExportDeclaration(path);\n },\n\n ClassDeclaration(path) {\n const { node } = path;\n\n const ref = node.id || path.scope.generateUidIdentifier(\"class\");\n\n path.replaceWith(\n t.variableDeclaration(\"let\", [\n t.variableDeclarator(ref, t.toExpression(node)),\n ]),\n );\n },\n\n ClassExpression(path, state) {\n const { node } = path;\n if (VISITED.has(node)) return;\n\n const inferred = nameFunction(path, undefined, supportUnicodeId);\n if (inferred && inferred !== node) {\n path.replaceWith(inferred);\n return;\n }\n\n VISITED.add(node);\n\n const [replacedPath] = path.replaceWith(\n transformClass(\n path,\n state.file,\n builtinClasses,\n loose,\n {\n setClassMethods,\n constantSuper,\n superIsCallableConstructor,\n noClassCalls,\n },\n supportUnicodeId,\n ),\n );\n\n if (replacedPath.isCallExpression()) {\n annotateAsPure(replacedPath);\n const callee = replacedPath.get(\"callee\");\n if (callee.isArrowFunctionExpression()) {\n // This is an IIFE, so we don't need to worry about the noNewArrows assumption\n callee.arrowFunctionToExpression();\n }\n }\n },\n },\n };\n});\n"],"mappings":";;;;;;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA,MAAMA,iBAAiB,GAAIC,QAA8B,IACvDC,MAAM,CAACC,IAAI,CAACC,QAAO,CAACH,QAAQ,CAAC,CAAC,CAACI,MAAM,CAACC,IAAI,IAAI,QAAQ,CAACC,IAAI,CAACD,IAAI,CAAC,CAAC;AAEpE,MAAME,cAAc,GAAG,IAAIC,GAAG,CAAC,CAC7B,GAAGT,iBAAiB,CAAC,SAAS,CAAC,EAC/B,GAAGA,iBAAiB,CAAC,SAAS,CAAC,CAChC,CAAC;AAAC,eAMY,IAAAU,0BAAO,EAAC,CAACC,GAAG,EAAEC,OAAgB,KAAK;EAAA;EAChDD,GAAG,CAACE,aAAa,CAAC,CAAC,CAAC;EAEpB,MAAM;IAAEC,KAAK,GAAG;EAAM,CAAC,GAAGF,OAAO;EAEjC,MAAMG,eAAe,sBAAIJ,GAAG,CAACK,UAAU,CAAC,iBAAiB,CAAC,8BACxDF,KAAiB;EACnB,MAAMG,aAAa,uBAAIN,GAAG,CAACK,UAAU,CAAC,eAAe,CAAC,+BAAIF,KAAiB;EAC3E,MAAMI,0BAA0B,uBAAIP,GAAG,CAACK,UAAU,CAChD,4BAA4B,CAC7B,+BAAIF,KAAiB;EACtB,MAAMK,YAAY,uBAAIR,GAAG,CAACK,UAAU,CAAC,cAAc,CAAC,+BAAIF,KAAiB;EACzE,MAAMM,gBAAgB,GAAG,CAAC,IAAAC,oCAAU,EAClC,2BAA2B,EAC3BV,GAAG,CAACW,OAAO,EAAE,CACd;;EAGD,MAAMC,OAAO,GAAG,IAAIC,OAAO,EAAE;EAE7B,OAAO;IACLlB,IAAI,EAAE,mBAAmB;IAEzBmB,OAAO,EAAE;MACPC,wBAAwB,CAACC,IAAI,EAAE;QAC7B,IAAI,CAACA,IAAI,CAACC,GAAG,CAAC,aAAa,CAAC,CAACC,kBAAkB,EAAE,EAAE;QACnD,IAAAC,qCAAsB,EAACH,IAALine truncated
@@ -0,0 +1,69 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = addCreateSuperHelper;
var _core = require("@babel/core");
const helper = _core.template.statement`
function CREATE_SUPER(Derived) {
function isNativeReflectConstruct() {
if (typeof Reflect === "undefined" || !Reflect.construct) return false;
// core-js@3
if (Reflect.construct.sham) return false;
// Proxy can't be polyfilled. Every browser implemented
// proxies before or at the same time as Reflect.construct,
// so if they support Proxy they also support Reflect.construct.
if (typeof Proxy === "function") return true;
// Since Reflect.construct can't be properly polyfilled, some
// implementations (e.g. core-js@2) don't set the correct internal slots.
// Those polyfills don't allow us to subclass built-ins, so we need to
// use our fallback implementation.
try {
// If the internal slots aren't set, this throws an error similar to
// TypeError: this is not a Date object.
Date.prototype.toString.call(Reflect.construct(Date, [], function() {}));
return true;
} catch (e) {
return false;
}
}
return function () {
var Super = GET_PROTOTYPE_OF(Derived), result;
if (isNativeReflectConstruct()) {
// NOTE: This doesn't work if this.__proto__.constructor has been modified.
var NewTarget = GET_PROTOTYPE_OF(this).constructor;
result = Reflect.construct(Super, arguments, NewTarget);
} else {
result = Super.apply(this, arguments);
}
return POSSIBLE_CONSTRUCTOR_RETURN(this, result);
}
}
`;
const helperIDs = new WeakMap();
function addCreateSuperHelper(file) {
if (helperIDs.has(file)) {
return (_core.types.cloneNode || _core.types.clone)(helperIDs.get(file));
}
try {
return file.addHelper("createSuper");
} catch (_unused) {
}
const id = file.scope.generateUidIdentifier("createSuper");
helperIDs.set(file, id);
const fn = helper({
CREATE_SUPER: id,
GET_PROTOTYPE_OF: file.addHelper("getPrototypeOf"),
POSSIBLE_CONSTRUCTOR_RETURN: file.addHelper("possibleConstructorReturn")
});
file.path.unshiftContainer("body", [fn]);
file.scope.registerDeclaration(file.path.get("body.0"));
return _core.types.cloneNode(id);
}
//# sourceMappingURL=inline-createSuper-helpers.js.map
@@ -0,0 +1 @@
{"version":3,"names":["helper","template","statement","helperIDs","WeakMap","addCreateSuperHelper","file","has","t","cloneNode","clone","get","addHelper","id","scope","generateUidIdentifier","set","fn","CREATE_SUPER","GET_PROTOTYPE_OF","POSSIBLE_CONSTRUCTOR_RETURN","path","unshiftContainer","registerDeclaration"],"sources":["../src/inline-createSuper-helpers.ts"],"sourcesContent":["import { template, types as t, type File } from \"@babel/core\";\n\nconst helper = template.statement`\n function CREATE_SUPER(Derived) {\n function isNativeReflectConstruct() {\n if (typeof Reflect === \"undefined\" || !Reflect.construct) return false;\n\n // core-js@3\n if (Reflect.construct.sham) return false;\n\n // Proxy can't be polyfilled. Every browser implemented\n // proxies before or at the same time as Reflect.construct,\n // so if they support Proxy they also support Reflect.construct.\n if (typeof Proxy === \"function\") return true;\n\n // Since Reflect.construct can't be properly polyfilled, some\n // implementations (e.g. core-js@2) don't set the correct internal slots.\n // Those polyfills don't allow us to subclass built-ins, so we need to\n // use our fallback implementation.\n try {\n // If the internal slots aren't set, this throws an error similar to\n // TypeError: this is not a Date object.\n Date.prototype.toString.call(Reflect.construct(Date, [], function() {}));\n return true;\n } catch (e) {\n return false;\n }\n }\n\n return function () {\n var Super = GET_PROTOTYPE_OF(Derived), result;\n if (isNativeReflectConstruct()) {\n // NOTE: This doesn't work if this.__proto__.constructor has been modified.\n var NewTarget = GET_PROTOTYPE_OF(this).constructor;\n result = Reflect.construct(Super, arguments, NewTarget);\n } else {\n result = Super.apply(this, arguments);\n }\n return POSSIBLE_CONSTRUCTOR_RETURN(this, result);\n }\n }\n`;\n\nconst helperIDs = new WeakMap();\n\nexport default function addCreateSuperHelper(file: File) {\n if (helperIDs.has(file)) {\n // TODO: Only use t.cloneNode in Babel 8\n // t.cloneNode isn't supported in every version\n return (t.cloneNode || t.clone)(helperIDs.get(file));\n }\n\n try {\n return file.addHelper(\"createSuper\");\n } catch {\n // Babel <7.9.0 doesn't support the helper.\n }\n\n const id = file.scope.generateUidIdentifier(\"createSuper\");\n helperIDs.set(file, id);\n\n const fn = helper({\n CREATE_SUPER: id,\n GET_PROTOTYPE_OF: file.addHelper(\"getPrototypeOf\"),\n POSSIBLE_CONSTRUCTOR_RETURN: file.addHelper(\"possibleConstructorReturn\"),\n });\n\n file.path.unshiftContainer(\"body\", [fn]);\n file.scope.registerDeclaration(file.path.get(\"body.0\"));\n\n return t.cloneNode(id);\n}\n"],"mappings":";;;;;;AAAA;AAEA,MAAMA,MAAM,GAAGC,cAAQ,CAACC,SAAU;AAClC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,CAAC;AAED,MAAMC,SAAS,GAAG,IAAIC,OAAO,EAAE;AAEhB,SAASC,oBAAoB,CAACC,IAAU,EAAE;EACvD,IAAIH,SAAS,CAACI,GAAG,CAACD,IAAI,CAAC,EAAE;IAGvB,OAAO,CAACE,WAAC,CAACC,SAAS,IAAID,WAAC,CAACE,KAAK,EAAEP,SAAS,CAACQ,GAAG,CAACL,IAAI,CAAC,CAAC;EACtD;EAEA,IAAI;IACF,OAAOA,IAAI,CAACM,SAAS,CAAC,aAAa,CAAC;EACtC,CAAC,CAAC,gBAAM;EAER;EAEA,MAAMC,EAAE,GAAGP,IAAI,CAACQ,KAAK,CAACC,qBAAqB,CAAC,aAAa,CAAC;EAC1DZ,SAAS,CAACa,GAAG,CAACV,IAAI,EAAEO,EAAE,CAAC;EAEvB,MAAMI,EAAE,GAAGjB,MAAM,CAAC;IAChBkB,YAAY,EAAEL,EAAE;IAChBM,gBAAgB,EAAEb,IAAI,CAACM,SAAS,CAAC,gBAAgB,CAAC;IAClDQ,2BAA2B,EAAEd,IAAI,CAACM,SAAS,CAAC,2BAA2B;EACzE,CAAC,CAAC;EAEFN,IAAI,CAACe,IAAI,CAACC,gBAAgB,CAAC,MAAM,EAAE,CAACL,EAAE,CAAC,CAAC;EACxCX,IAAI,CAACQ,KAAK,CAACS,mBAAmB,CAACjB,IAAI,CAACe,IAAI,CAACV,GAAG,CAAC,QAAQ,CAAC,CAAC;EAEvD,OAAOH,WAAC,CAACC,SAAS,CAACI,EAAE,CAAC;AACxB"}
@@ -0,0 +1,525 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = transformClass;
var _helperFunctionName = require("@babel/helper-function-name");
var _helperReplaceSupers = require("@babel/helper-replace-supers");
var _helperEnvironmentVisitor = require("@babel/helper-environment-visitor");
var _helperOptimiseCallExpression = require("@babel/helper-optimise-call-expression");
var _core = require("@babel/core");
var _helperAnnotateAsPure = require("@babel/helper-annotate-as-pure");
var _inlineCreateSuperHelpers = require("./inline-createSuper-helpers");
function buildConstructor(classRef, constructorBody, node) {
const func = _core.types.functionDeclaration(_core.types.cloneNode(classRef), [], constructorBody);
_core.types.inherits(func, node);
return func;
}
function transformClass(path, file, builtinClasses, isLoose, assumptions, supportUnicodeId) {
const classState = {
parent: undefined,
scope: undefined,
node: undefined,
path: undefined,
file: undefined,
classId: undefined,
classRef: undefined,
superFnId: undefined,
superName: null,
superReturns: [],
isDerived: false,
extendsNative: false,
construct: undefined,
constructorBody: undefined,
userConstructor: undefined,
userConstructorPath: undefined,
hasConstructor: false,
body: [],
superThises: [],
pushedConstructor: false,
pushedInherits: false,
pushedCreateClass: false,
protoAlias: null,
isLoose: false,
dynamicKeys: new Map(),
methods: {
instance: {
hasComputed: false,
list: [],
map: new Map()
},
static: {
hasComputed: false,
list: [],
map: new Map()
}
}
};
const setState = newState => {
Object.assign(classState, newState);
};
const findThisesVisitor = _core.traverse.visitors.merge([_helperEnvironmentVisitor.default, {
ThisExpression(path) {
classState.superThises.push(path);
}
}]);
function createClassHelper(args) {
return _core.types.callExpression(classState.file.addHelper("createClass"), args);
}
function maybeCreateConstructor() {
let hasConstructor = false;
const paths = classState.path.get("body.body");
for (const path of paths) {
hasConstructor = path.equals("kind", "constructor");
if (hasConstructor) break;
}
if (hasConstructor) return;
let params, body;
if (classState.isDerived) {
const constructor = _core.template.expression.ast`
(function () {
super(...arguments);
})
`;
params = constructor.params;
body = constructor.body;
} else {
params = [];
body = _core.types.blockStatement([]);
}
classState.path.get("body").unshiftContainer("body", _core.types.classMethod("constructor", _core.types.identifier("constructor"), params, body));
}
function buildBody() {
maybeCreateConstructor();
pushBody();
verifyConstructor();
if (classState.userConstructor) {
const {
constructorBody,
userConstructor,
construct
} = classState;
constructorBody.body.push(...userConstructor.body.body);
_core.types.inherits(construct, userConstructor);
_core.types.inherits(constructorBody, userConstructor.body);
}
pushDescriptors();
}
function pushBody() {
const classBodyPaths = classState.path.get("body.body");
for (const path of classBodyPaths) {
const node = path.node;
if (path.isClassProperty()) {
throw path.buildCodeFrameError("Missing class properties transform.");
}
if (node.decorators) {
throw path.buildCodeFrameError("Method has decorators, put the decorator plugin before the classes one.");
}
if (_core.types.isClassMethod(node)) {
const isConstructor = node.kind === "constructor";
const replaceSupers = new _helperReplaceSupers.default({
methodPath: path,
objectRef: classState.classRef,
superRef: classState.superName,
constantSuper: assumptions.constantSuper,
file: classState.file,
refToPreserve: classState.classRef
});
replaceSupers.replace();
const superReturns = [];
path.traverse(_core.traverse.visitors.merge([_helperEnvironmentVisitor.default, {
ReturnStatement(path) {
if (!path.getFunctionParent().isArrowFunctionExpression()) {
superReturns.push(path);
}
}
}]));
if (isConstructor) {
pushConstructor(superReturns, node, path);
} else {
pushMethod(node, path);
}
}
}
}
function pushDescriptors() {
pushInheritsToBody();
const {
body
} = classState;
const props = {
instance: null,
static: null
};
for (const placement of ["static", "instance"]) {
if (classState.methods[placement].list.length) {
props[placement] = classState.methods[placement].list.map(desc => {
const obj = _core.types.objectExpression([_core.types.objectProperty(_core.types.identifier("key"), desc.key)]);
for (const kind of ["get", "set", "value"]) {
if (desc[kind] != null) {
obj.properties.push(_core.types.objectProperty(_core.types.identifier(kind), desc[kind]));
}
}
return obj;
});
}
}
if (props.instance || props.static) {
let args = [_core.types.cloneNode(classState.classRef),
props.instance ? _core.types.arrayExpression(props.instance) : _core.types.nullLiteral(),
props.static ? _core.types.arrayExpression(props.static) : _core.types.nullLiteral()];
let lastNonNullIndex = 0;
for (let i = 0; i < args.length; i++) {
if (!_core.types.isNullLiteral(args[i])) lastNonNullIndex = i;
}
args = args.slice(0, lastNonNullIndex + 1);
body.push(_core.types.expressionStatement(createClassHelper(args)));
classState.pushedCreateClass = true;
}
}
function wrapSuperCall(bareSuper, superRef, thisRef, body) {
const bareSuperNode = bareSuper.node;
let call;
if (assumptions.superIsCallableConstructor) {
bareSuperNode.arguments.unshift(_core.types.thisExpression());
if (bareSuperNode.arguments.length === 2 && _core.types.isSpreadElement(bareSuperNode.arguments[1]) && _core.types.isIdentifier(bareSuperNode.arguments[1].argument, {
name: "arguments"
})) {
bareSuperNode.arguments[1] = bareSuperNode.arguments[1].argument;
bareSuperNode.callee = _core.types.memberExpression(_core.types.cloneNode(superRef), _core.types.identifier("apply"));
} else {
bareSuperNode.callee = _core.types.memberExpression(_core.types.cloneNode(superRef), _core.types.identifier("call"));
}
call = _core.types.logicalExpression("||", bareSuperNode, _core.types.thisExpression());
} else {
call = (0, _helperOptimiseCallExpression.default)(_core.types.cloneNode(classState.superFnId), _core.types.thisExpression(), bareSuperNode.arguments, false);
}
if (bareSuper.parentPath.isExpressionStatement() && bareSuper.parentPath.container === body.node.body && body.node.body.length - 1 === bareSuper.parentPath.key) {
if (classState.superThises.length) {
call = _core.types.assignmentExpression("=", thisRef(), call);
}
bareSuper.parentPath.replaceWith(_core.types.returnStatement(call));
} else {
bareSuper.replaceWith(_core.types.assignmentExpression("=", thisRef(), call));
}
}
function verifyConstructor() {
if (!classState.isDerived) return;
const path = classState.userConstructorPath;
const body = path.get("body");
path.traverse(findThisesVisitor);
let thisRef = function () {
const ref = path.scope.generateDeclaredUidIdentifier("this");
thisRef = () => _core.types.cloneNode(ref);
return ref;
};
for (const thisPath of classState.superThises) {
const {
node,
parentPath
} = thisPath;
if (parentPath.isMemberExpression({
object: node
})) {
thisPath.replaceWith(thisRef());
continue;
}
thisPath.replaceWith(_core.types.callExpression(classState.file.addHelper("assertThisInitialized"), [thisRef()]));
}
const bareSupers = [];
path.traverse(_core.traverse.visitors.merge([_helperEnvironmentVisitor.default, {
Super(path) {
const {
node,
parentPath
} = path;
if (parentPath.isCallExpression({
callee: node
})) {
bareSupers.unshift(parentPath);
}
}
}]));
let guaranteedSuperBeforeFinish = !!bareSupers.length;
for (const bareSuper of bareSupers) {
wrapSuperCall(bareSuper, classState.superName, thisRef, body);
if (guaranteedSuperBeforeFinish) {
bareSuper.find(function (parentPath) {
if (parentPath === path) {
return true;
}
if (parentPath.isLoop() || parentPath.isConditional() || parentPath.isArrowFunctionExpression()) {
guaranteedSuperBeforeFinish = false;
return true;
}
});
}
}
let wrapReturn;
if (classState.isLoose) {
wrapReturn = returnArg => {
const thisExpr = _core.types.callExpression(classState.file.addHelper("assertThisInitialized"), [thisRef()]);
return returnArg ? _core.types.logicalExpression("||", returnArg, thisExpr) : thisExpr;
};
} else {
wrapReturn = returnArg => {
const returnParams = [thisRef()];
if (returnArg != null) {
returnParams.push(returnArg);
}
return _core.types.callExpression(classState.file.addHelper("possibleConstructorReturn"), returnParams);
};
}
const bodyPaths = body.get("body");
if (!bodyPaths.length || !bodyPaths.pop().isReturnStatement()) {
body.pushContainer("body", _core.types.returnStatement(guaranteedSuperBeforeFinish ? thisRef() : wrapReturn()));
}
for (const returnPath of classState.superReturns) {
returnPath.get("argument").replaceWith(wrapReturn(returnPath.node.argument));
}
}
function pushMethod(node, path) {
const scope = path ? path.scope : classState.scope;
if (node.kind === "method") {
if (processMethod(node, scope)) return;
}
const placement = node.static ? "static" : "instance";
const methods = classState.methods[placement];
const descKey = node.kind === "method" ? "value" : node.kind;
const key = _core.types.isNumericLiteral(node.key) || _core.types.isBigIntLiteral(node.key) ? _core.types.stringLiteral(String(node.key.value)) : _core.types.toComputedKey(node);
let fn = _core.types.toExpression(node);
if (_core.types.isStringLiteral(key)) {
if (node.kind === "method") {
var _nameFunction;
fn = (_nameFunction = (0, _helperFunctionName.default)(
{
id: key,
node: node,
scope
}, undefined, supportUnicodeId)) != null ? _nameFunction : fn;
}
} else {
methods.hasComputed = true;
}
let descriptor;
if (!methods.hasComputed && methods.map.has(key.value)) {
descriptor = methods.map.get(key.value);
descriptor[descKey] = fn;
if (descKey === "value") {
descriptor.get = null;
descriptor.set = null;
} else {
descriptor.value = null;
}
} else {
descriptor = {
key:
key,
[descKey]: fn
};
methods.list.push(descriptor);
if (!methods.hasComputed) {
methods.map.set(key.value, descriptor);
}
}
}
function processMethod(node, scope) {
if (assumptions.setClassMethods && !node.decorators) {
let {
classRef
} = classState;
if (!node.static) {
insertProtoAliasOnce();
classRef = classState.protoAlias;
}
const methodName = _core.types.memberExpression(_core.types.cloneNode(classRef), node.key, node.computed || _core.types.isLiteral(node.key));
let func = _core.types.functionExpression(null,
node.params, node.body, node.generator, node.async);
_core.types.inherits(func, node);
const key = _core.types.toComputedKey(node, node.key);
if (_core.types.isStringLiteral(key)) {
var _nameFunction2;
func = (_nameFunction2 = (0, _helperFunctionName.default)({
node: func,
id: key,
scope
}, undefined, supportUnicodeId)) != null ? _nameFunction2 : func;
}
const expr = _core.types.expressionStatement(_core.types.assignmentExpression("=", methodName, func));
_core.types.inheritsComments(expr, node);
classState.body.push(expr);
return true;
}
return false;
}
function insertProtoAliasOnce() {
if (classState.protoAlias === null) {
setState({
protoAlias: classState.scope.generateUidIdentifier("proto")
});
const classProto = _core.types.memberExpression(classState.classRef, _core.types.identifier("prototype"));
const protoDeclaration = _core.types.variableDeclaration("var", [_core.types.variableDeclarator(classState.protoAlias, classProto)]);
classState.body.push(protoDeclaration);
}
}
function pushConstructor(superReturns, method, path) {
setState({
userConstructorPath: path,
userConstructor: method,
hasConstructor: true,
superReturns
});
const {
construct
} = classState;
_core.types.inheritsComments(construct, method);
construct.params = method.params;
_core.types.inherits(construct.body, method.body);
construct.body.directives = method.body.directives;
pushConstructorToBody();
}
function pushConstructorToBody() {
if (classState.pushedConstructor) return;
classState.pushedConstructor = true;
if (classState.hasInstanceDescriptors || classState.hasStaticDescriptors) {
pushDescriptors();
}
classState.body.push(classState.construct);
pushInheritsToBody();
}
function pushInheritsToBody() {
if (!classState.isDerived || classState.pushedInherits) return;
const superFnId = path.scope.generateUidIdentifier("super");
setState({
pushedInherits: true,
superFnId
});
if (!assumptions.superIsCallableConstructor) {
classState.body.unshift(_core.types.variableDeclaration("var", [_core.types.variableDeclarator(superFnId, _core.types.callExpression((0, _inlineCreateSuperHelpers.default)(classState.file), [_core.types.cloneNode(classState.classRef)]))]));
}
classState.body.unshift(_core.types.expressionStatement(_core.types.callExpression(classState.file.addHelper(classState.isLoose ? "inheritsLoose" : "inherits"), [_core.types.cloneNode(classState.classRef), _core.types.cloneNode(classState.superName)])));
}
function extractDynamicKeys() {
const {
dynamicKeys,
node,
scope
} = classState;
for (const elem of node.body.body) {
if (!_core.types.isClassMethod(elem) || !elem.computed) continue;
if (scope.isPure(elem.key, true)) continue;
const id = scope.generateUidIdentifierBasedOnNode(elem.key);
dynamicKeys.set(id.name, elem.key);
elem.key = id;
}
}
function setupClosureParamsArgs() {
const {
superName,
dynamicKeys
} = classState;
const closureParams = [];
const closureArgs = [];
if (classState.isDerived) {
let arg = _core.types.cloneNode(superName);
if (classState.extendsNative) {
arg = _core.types.callExpression(classState.file.addHelper("wrapNativeSuper"), [arg]);
(0, _helperAnnotateAsPure.default)(arg);
}
const param = classState.scope.generateUidIdentifierBasedOnNode(superName);
closureParams.push(param);
closureArgs.push(arg);
setState({
superName: _core.types.cloneNode(param)
});
}
for (const [name, value] of dynamicKeys) {
closureParams.push(_core.types.identifier(name));
closureArgs.push(value);
}
return {
closureParams,
closureArgs
};
}
function classTransformer(path, file, builtinClasses, isLoose) {
setState({
parent: path.parent,
scope: path.scope,
node: path.node,
path,
file,
isLoose
});
setState({
classId: classState.node.id,
classRef: classState.node.id ? _core.types.identifier(classState.node.id.name) : classState.scope.generateUidIdentifier("class"),
superName: classState.node.superClass,
isDerived: !!classState.node.superClass,
constructorBody: _core.types.blockStatement([])
});
setState({
extendsNative: _core.types.isIdentifier(classState.superName) && builtinClasses.has(classState.superName.name) && !classState.scope.hasBinding(classState.superName.name, true)
});
const {
classRef,
node,
constructorBody
} = classState;
setState({
construct: buildConstructor(classRef, constructorBody, node)
});
extractDynamicKeys();
const {
body
} = classState;
const {
closureParams,
closureArgs
} = setupClosureParamsArgs();
buildBody();
if (!assumptions.noClassCalls) {
constructorBody.body.unshift(_core.types.expressionStatement(_core.types.callExpression(classState.file.addHelper("classCallCheck"), [_core.types.thisExpression(), _core.types.cloneNode(classState.classRef)])));
}
const isStrict = path.isInStrictMode();
let constructorOnly = classState.classId && body.length === 1;
if (constructorOnly && !isStrict) {
for (const param of classState.construct.params) {
if (!_core.types.isIdentifier(param)) {
constructorOnly = false;
break;
}
}
}
const directives = constructorOnly ? body[0].body.directives : [];
if (!isStrict) {
directives.push(_core.types.directive(_core.types.directiveLiteral("use strict")));
}
if (constructorOnly) {
const expr = _core.types.toExpression(body[0]);
return classState.isLoose ? expr : createClassHelper([expr]);
}
let returnArg = _core.types.cloneNode(classState.classRef);
if (!classState.pushedCreateClass && !classState.isLoose) {
returnArg = createClassHelper([returnArg]);
}
body.push(_core.types.returnStatement(returnArg));
const container = _core.types.arrowFunctionExpression(closureParams, _core.types.blockStatement(body, directives));
return _core.types.callExpression(container, closureArgs);
}
return classTransformer(path, file, builtinClasses, isLoose);
}
//# sourceMappingURL=transformClass.js.map
@@ -0,0 +1 @@
{"version":3,"names":["buildConstructor","classRef","constructorBody","node","func","t","functionDeclaration","cloneNode","inherits","transformClass","path","file","builtinClasses","isLoose","assumptions","supportUnicodeId","classState","parent","undefined","scope","classId","superFnId","superName","superReturns","isDerived","extendsNative","construct","userConstructor","userConstructorPath","hasConstructor","body","superThises","pushedConstructor","pushedInherits","pushedCreateClass","protoAlias","dynamicKeys","Map","methods","instance","hasComputed","list","map","static","setState","newState","Object","assign","findThisesVisitor","traverse","visitors","merge","environmentVisitor","ThisExpression","push","createClassHelper","args","callExpression","addHelper","maybeCreateConstructor","paths","get","equals","params","constructor","template","expression","ast","blockStatement","unshiftContainer","classMethod","identifier","buildBody","pushBody","verifyConstructor","pushDescriptors","classBodyPaths","isClassProperty","buildCodeFrameError","decorators","isClassMethod","isConstructor","kind","replaceSupers","ReplaceSupers","methodPath","objectRef","superRef","constantSuper","refToPreserve","replace","ReturnStatement","getFunctionParent","isArrowFunctionExpression","pushConstructor","pushMethod","pushInheritsToBody","props","placement","length","desc","obj","objectExpression","objectProperty","key","properties","arrayExpression","nullLiteral","lastNonNullIndex","i","isNullLiteral","slice","expressionStatement","wrapSuperCall","bareSuper","thisRef","bareSuperNode","call","superIsCallableConstructor","arguments","unshift","thisExpression","isSpreadElement","isIdentifier","argument","name","callee","memberExpression","logicalExpression","optimiseCall","parentPath","isExpressionStatement","container","assignmentExpression","replaceWith","returnStatement","ref","generateDeclaredUidIdentifier","thisPath","isMemberExpression","object","bareSupers","Super","isCallExpression","guaranteedSuperBeforeFinish","find","isLoop","isConditional","wrapReturn","returnArg","thisExpr","returnParams","bodyPaths","pop","isReturnStatement","pushContainer","returnPath","processMethod","descKey","isNumericLiteral","isBigIntLiteral","stringLiteral","String","value","toComputedKey","fn","toExpression","isStringLiteral","nameFunction","id","descriptor","has","set","setClassMethods","insertProtoAliasOnce","methodName","computed","isLiteral","functionExpression","generator","async","expr","inheritsComments","generateUidIdentifier","classProto","protoDeclaration","variableDeclaration","variableDeclarator","method","directives","pushConstructorToBody","hasInstanceDescriptors","hasStaticDescriptors","addCreateSuperHelper","extractDynamicKeys","elem","isPure","generateUidIdentifierBasedOnNode","setupClosureParamsArgs","closureParams","closureArgs","arg","annotateAsPure","param","classTransformer","superClass","hasBinding","noClassCalls","isStrict","isInStrictMode","constructorOnly","directive","directiveLiteral","arrowFunctionExpression"],"sources":["../src/transformClass.ts"],"sourcesContent":["import type { NodePath, Scope, Visitor } from \"@babel/traverse\";\nimport nameFunction from \"@babel/helper-function-name\";\nimport ReplaceSupers from \"@babel/helper-replace-supers\";\nimport environmentVisitor from \"@babel/helper-environment-visitor\";\nimport optimiseCall from \"@babel/helper-optimise-call-expression\";\nimport { traverse, template, types as t, type File } from \"@babel/core\";\nimport annotateAsPure from \"@babel/helper-annotate-as-pure\";\n\nimport addCreateSuperHelper from \"./inline-createSuper-helpers\";\n\ntype ClassAssumptions = {\n setClassMethods: boolean;\n constantSuper: boolean;\n superIsCallableConstructor: boolean;\n noClassCalls: boolean;\n};\n\ntype ClassConstructor = t.ClassMethod & { kind: \"constructor\" };\n\nfunction buildConstructor(\n classRef: t.Identifier,\n constructorBody: t.BlockStatement,\n node: t.Class,\n) {\n const func = t.functionDeclaration(\n t.cloneNode(classRef),\n [],\n constructorBody,\n );\n t.inherits(func, node);\n return func;\n}\n\ntype Descriptor = {\n key: t.Expression;\n get?: t.Expression | null;\n set?: t.Expression | null;\n value?: t.Expression | null;\n constructor?: t.Expression | null;\n};\n\ntype State = {\n parent: t.Node;\n scope: Scope;\n node: t.Class;\n path: NodePath<t.Class>;\n file: File;\n\n classId: t.Identifier | void;\n classRef: t.Identifier;\n superFnId: t.Identifier;\n superName: t.Expression | null;\n superReturns: NodePath<t.ReturnStatement>[];\n isDerived: boolean;\n extendsNative: boolean;\n\n construct: t.FunctionDeclaration;\n constructorBody: t.BlockStatement;\n userConstructor: ClassConstructor;\n userConstructorPath: NodePath<ClassConstructor>;\n hasConstructor: boolean;\n\n body: t.Statement[];\n superThises: NodePath<t.ThisExpression>[];\n pushedConstructor: boolean;\n pushedInherits: boolean;\n pushedCreaLine truncated