Updated the files.

This commit is contained in:
Batuhan Berk Başoğlu 2024-02-08 19:38:41 -05:00
parent 1553e6b971
commit 753967d4f5
23418 changed files with 3784666 additions and 0 deletions

View file

@ -0,0 +1,137 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.buildDecoratedClass = buildDecoratedClass;
exports.hasDecorators = hasDecorators;
exports.hasOwnDecorators = hasOwnDecorators;
var _core = require("@babel/core");
var _helperReplaceSupers = require("@babel/helper-replace-supers");
var _helperFunctionName = require("@babel/helper-function-name");
function hasOwnDecorators(node) {
var _node$decorators;
return !!((_node$decorators = node.decorators) != null && _node$decorators.length);
}
function hasDecorators(node) {
return hasOwnDecorators(node) || node.body.body.some(hasOwnDecorators);
}
function prop(key, value) {
if (!value) return null;
return _core.types.objectProperty(_core.types.identifier(key), value);
}
function method(key, body) {
return _core.types.objectMethod("method", _core.types.identifier(key), [], _core.types.blockStatement(body));
}
function takeDecorators(node) {
let result;
if (node.decorators && node.decorators.length > 0) {
result = _core.types.arrayExpression(node.decorators.map(decorator => decorator.expression));
}
node.decorators = undefined;
return result;
}
function getKey(node) {
if (node.computed) {
return node.key;
} else if (_core.types.isIdentifier(node.key)) {
return _core.types.stringLiteral(node.key.name);
} else {
return _core.types.stringLiteral(String(node.key.value));
}
}
function extractElementDescriptor(file, classRef, superRef, path) {
const isMethod = path.isClassMethod();
if (path.isPrivate()) {
throw path.buildCodeFrameError(`Private ${isMethod ? "methods" : "fields"} in decorated classes are not supported yet.`);
}
if (path.node.type === "ClassAccessorProperty") {
throw path.buildCodeFrameError(`Accessor properties are not supported in 2018-09 decorator transform, please specify { "version": "2021-12" } instead.`);
}
if (path.node.type === "StaticBlock") {
throw path.buildCodeFrameError(`Static blocks are not supported in 2018-09 decorator transform, please specify { "version": "2021-12" } instead.`);
}
const {
node,
scope
} = path;
if (!path.isTSDeclareMethod()) {
new _helperReplaceSupers.default({
methodPath: path,
objectRef: classRef,
superRef,
file,
refToPreserve: classRef
}).replace();
}
const properties = [prop("kind", _core.types.stringLiteral(_core.types.isClassMethod(node) ? node.kind : "field")), prop("decorators", takeDecorators(node)), prop("static", node.static && _core.types.booleanLiteral(true)), prop("key", getKey(node))].filter(Boolean);
if (_core.types.isClassMethod(node)) {
const id = node.computed ? null : node.key;
const transformed = _core.types.toExpression(node);
properties.push(prop("value", (0, _helperFunctionName.default)({
node: transformed,
id,
scope
}) || transformed));
} else if (_core.types.isClassProperty(node) && node.value) {
properties.push(method("value", _core.template.statements.ast`return ${node.value}`));
} else {
properties.push(prop("value", scope.buildUndefinedNode()));
}
path.remove();
return _core.types.objectExpression(properties);
}
function addDecorateHelper(file) {
return file.addHelper("decorate");
}
function buildDecoratedClass(ref, path, elements, file) {
const {
node,
scope
} = path;
const initializeId = scope.generateUidIdentifier("initialize");
const isDeclaration = node.id && path.isDeclaration();
const isStrict = path.isInStrictMode();
const {
superClass
} = node;
node.type = "ClassDeclaration";
if (!node.id) node.id = _core.types.cloneNode(ref);
let superId;
if (superClass) {
superId = scope.generateUidIdentifierBasedOnNode(node.superClass, "super");
node.superClass = superId;
}
const classDecorators = takeDecorators(node);
const definitions = _core.types.arrayExpression(elements.filter(element => !element.node.abstract && element.node.type !== "TSIndexSignature").map(path => extractElementDescriptor(file, node.id, superId, path)));
const wrapperCall = _core.template.expression.ast`
${addDecorateHelper(file)}(
${classDecorators || _core.types.nullLiteral()},
function (${initializeId}, ${superClass ? _core.types.cloneNode(superId) : null}) {
${node}
return { F: ${_core.types.cloneNode(node.id)}, d: ${definitions} };
},
${superClass}
)
`;
if (!isStrict) {
wrapperCall.arguments[1].body.directives.push(_core.types.directive(_core.types.directiveLiteral("use strict")));
}
let replacement = wrapperCall;
let classPathDesc = "arguments.1.body.body.0";
if (isDeclaration) {
replacement = _core.template.statement.ast`let ${ref} = ${wrapperCall}`;
classPathDesc = "declarations.0.init." + classPathDesc;
}
return {
instanceNodes: [_core.template.statement.ast`
${_core.types.cloneNode(initializeId)}(this)
`],
wrapClass(path) {
path.replaceWith(replacement);
return path.get(classPathDesc);
}
};
}
//# sourceMappingURL=decorators-2018-09.js.map

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,950 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = _default;
var _core = require("@babel/core");
var _helperReplaceSupers = require("@babel/helper-replace-supers");
var _helperSplitExportDeclaration = require("@babel/helper-split-export-declaration");
var _helperSkipTransparentExpressionWrappers = require("@babel/helper-skip-transparent-expression-wrappers");
var _fields = require("./fields.js");
function incrementId(id, idx = id.length - 1) {
if (idx === -1) {
id.unshift(65);
return;
}
const current = id[idx];
if (current === 90) {
id[idx] = 97;
} else if (current === 122) {
id[idx] = 65;
incrementId(id, idx - 1);
} else {
id[idx] = current + 1;
}
}
function createPrivateUidGeneratorForClass(classPath) {
const currentPrivateId = [];
const privateNames = new Set();
classPath.traverse({
PrivateName(path) {
privateNames.add(path.node.id.name);
}
});
return () => {
let reifiedId;
do {
incrementId(currentPrivateId);
reifiedId = String.fromCharCode(...currentPrivateId);
} while (privateNames.has(reifiedId));
return _core.types.privateName(_core.types.identifier(reifiedId));
};
}
function createLazyPrivateUidGeneratorForClass(classPath) {
let generator;
return () => {
if (!generator) {
generator = createPrivateUidGeneratorForClass(classPath);
}
return generator();
};
}
function replaceClassWithVar(path, className) {
if (path.type === "ClassDeclaration") {
const id = path.node.id;
const className = id.name;
const varId = path.scope.generateUidIdentifierBasedOnNode(id);
const classId = _core.types.identifier(className);
path.scope.rename(className, varId.name);
path.get("id").replaceWith(classId);
return {
id: _core.types.cloneNode(varId),
path
};
} else {
let varId;
if (path.node.id) {
className = path.node.id.name;
varId = path.scope.parent.generateDeclaredUidIdentifier(className);
path.scope.rename(className, varId.name);
} else {
varId = path.scope.parent.generateDeclaredUidIdentifier(typeof className === "string" ? className : "decorated_class");
}
const newClassExpr = _core.types.classExpression(typeof className === "string" ? _core.types.identifier(className) : null, path.node.superClass, path.node.body);
const [newPath] = path.replaceWith(_core.types.sequenceExpression([newClassExpr, varId]));
return {
id: _core.types.cloneNode(varId),
path: newPath.get("expressions.0")
};
}
}
function generateClassProperty(key, value, isStatic) {
if (key.type === "PrivateName") {
return _core.types.classPrivateProperty(key, value, undefined, isStatic);
} else {
return _core.types.classProperty(key, value, undefined, undefined, isStatic);
}
}
function addProxyAccessorsFor(className, element, originalKey, targetKey, version, isComputed = false) {
const {
static: isStatic
} = element.node;
const thisArg = version === "2023-05" && isStatic ? className : _core.types.thisExpression();
const getterBody = _core.types.blockStatement([_core.types.returnStatement(_core.types.memberExpression(_core.types.cloneNode(thisArg), _core.types.cloneNode(targetKey)))]);
const setterBody = _core.types.blockStatement([_core.types.expressionStatement(_core.types.assignmentExpression("=", _core.types.memberExpression(_core.types.cloneNode(thisArg), _core.types.cloneNode(targetKey)), _core.types.identifier("v")))]);
let getter, setter;
if (originalKey.type === "PrivateName") {
getter = _core.types.classPrivateMethod("get", _core.types.cloneNode(originalKey), [], getterBody, isStatic);
setter = _core.types.classPrivateMethod("set", _core.types.cloneNode(originalKey), [_core.types.identifier("v")], setterBody, isStatic);
} else {
getter = _core.types.classMethod("get", _core.types.cloneNode(originalKey), [], getterBody, isComputed, isStatic);
setter = _core.types.classMethod("set", _core.types.cloneNode(originalKey), [_core.types.identifier("v")], setterBody, isComputed, isStatic);
}
element.insertAfter(setter);
element.insertAfter(getter);
}
function extractProxyAccessorsFor(targetKey, version) {
if (version !== "2023-05" && version !== "2023-01") {
return [_core.template.expression.ast`
function () {
return this.${_core.types.cloneNode(targetKey)};
}
`, _core.template.expression.ast`
function (value) {
this.${_core.types.cloneNode(targetKey)} = value;
}
`];
}
return [_core.template.expression.ast`
o => o.${_core.types.cloneNode(targetKey)}
`, _core.template.expression.ast`
(o, v) => o.${_core.types.cloneNode(targetKey)} = v
`];
}
function prependExpressionsToFieldInitializer(expressions, fieldPath) {
const initializer = fieldPath.get("value");
if (initializer.node) {
expressions.push(initializer.node);
} else if (expressions.length > 0) {
expressions[expressions.length - 1] = _core.types.unaryExpression("void", expressions[expressions.length - 1]);
}
initializer.replaceWith(maybeSequenceExpression(expressions));
}
function prependExpressionsToConstructor(expressions, constructorPath) {
constructorPath.node.body.body.unshift(_core.types.expressionStatement(maybeSequenceExpression(expressions)));
}
function isProtoInitCallExpression(expression, protoInitCall) {
return _core.types.isCallExpression(expression) && _core.types.isIdentifier(expression.callee, {
name: protoInitCall.name
});
}
function optimizeSuperCallAndExpressions(expressions, protoInitLocal) {
if (expressions.length >= 2 && isProtoInitCallExpression(expressions[1], protoInitLocal)) {
const mergedSuperCall = _core.types.callExpression(_core.types.cloneNode(protoInitLocal), [expressions[0]]);
expressions.splice(0, 2, mergedSuperCall);
}
if (expressions.length >= 2 && _core.types.isThisExpression(expressions[expressions.length - 1]) && isProtoInitCallExpression(expressions[expressions.length - 2], protoInitLocal)) {
expressions.splice(expressions.length - 1, 1);
}
return maybeSequenceExpression(expressions);
}
function insertExpressionsAfterSuperCallAndOptimize(expressions, constructorPath, protoInitLocal) {
constructorPath.traverse({
CallExpression: {
exit(path) {
if (!path.get("callee").isSuper()) return;
const newNodes = [path.node, ...expressions.map(expr => _core.types.cloneNode(expr))];
if (path.isCompletionRecord()) {
newNodes.push(_core.types.thisExpression());
}
path.replaceWith(optimizeSuperCallAndExpressions(newNodes, protoInitLocal));
path.skip();
}
},
ClassMethod(path) {
if (path.node.kind === "constructor") {
path.skip();
}
}
});
}
function createConstructorFromExpressions(expressions, isDerivedClass) {
const body = [_core.types.expressionStatement(maybeSequenceExpression(expressions))];
if (isDerivedClass) {
body.unshift(_core.types.expressionStatement(_core.types.callExpression(_core.types.super(), [_core.types.spreadElement(_core.types.identifier("args"))])));
}
return _core.types.classMethod("constructor", _core.types.identifier("constructor"), isDerivedClass ? [_core.types.restElement(_core.types.identifier("args"))] : [], _core.types.blockStatement(body));
}
const FIELD = 0;
const ACCESSOR = 1;
const METHOD = 2;
const GETTER = 3;
const SETTER = 4;
const STATIC_OLD_VERSION = 5;
const STATIC = 8;
const DECORATORS_HAVE_THIS = 16;
function getElementKind(element) {
switch (element.node.type) {
case "ClassProperty":
case "ClassPrivateProperty":
return FIELD;
case "ClassAccessorProperty":
return ACCESSOR;
case "ClassMethod":
case "ClassPrivateMethod":
if (element.node.kind === "get") {
return GETTER;
} else if (element.node.kind === "set") {
return SETTER;
} else {
return METHOD;
}
}
}
function isDecoratorInfo(info) {
return "decorators" in info;
}
function filteredOrderedDecoratorInfo(info) {
const filtered = info.filter(isDecoratorInfo);
return [...filtered.filter(el => el.isStatic && el.kind >= ACCESSOR && el.kind <= SETTER), ...filtered.filter(el => !el.isStatic && el.kind >= ACCESSOR && el.kind <= SETTER), ...filtered.filter(el => el.isStatic && el.kind === FIELD), ...filtered.filter(el => !el.isStatic && el.kind === FIELD)];
}
function generateDecorationList(decorators, decoratorsThis, version) {
const decsCount = decorators.length;
const hasOneThis = decoratorsThis.some(Boolean);
const decs = [];
for (let i = 0; i < decsCount; i++) {
if (version === "2023-05" && hasOneThis) {
decs.push(decoratorsThis[i] || _core.types.unaryExpression("void", _core.types.numericLiteral(0)));
}
decs.push(decorators[i]);
}
return {
hasThis: hasOneThis,
decs
};
}
function generateDecorationExprs(info, version) {
return _core.types.arrayExpression(filteredOrderedDecoratorInfo(info).map(el => {
const {
decs,
hasThis
} = generateDecorationList(el.decorators, el.decoratorsThis, version);
let flag = el.kind;
if (el.isStatic) {
flag += version === "2023-05" ? STATIC : STATIC_OLD_VERSION;
}
if (hasThis) flag += DECORATORS_HAVE_THIS;
return _core.types.arrayExpression([decs.length === 1 ? decs[0] : _core.types.arrayExpression(decs), _core.types.numericLiteral(flag), el.name, ...(el.privateMethods || [])]);
}));
}
function extractElementLocalAssignments(decorationInfo) {
const localIds = [];
for (const el of filteredOrderedDecoratorInfo(decorationInfo)) {
const {
locals
} = el;
if (Array.isArray(locals)) {
localIds.push(...locals);
} else if (locals !== undefined) {
localIds.push(locals);
}
}
return localIds;
}
function addCallAccessorsFor(element, key, getId, setId) {
element.insertAfter(_core.types.classPrivateMethod("get", _core.types.cloneNode(key), [], _core.types.blockStatement([_core.types.returnStatement(_core.types.callExpression(_core.types.cloneNode(getId), [_core.types.thisExpression()]))])));
element.insertAfter(_core.types.classPrivateMethod("set", _core.types.cloneNode(key), [_core.types.identifier("v")], _core.types.blockStatement([_core.types.expressionStatement(_core.types.callExpression(_core.types.cloneNode(setId), [_core.types.thisExpression(), _core.types.identifier("v")]))])));
}
function isNotTsParameter(node) {
return node.type !== "TSParameterProperty";
}
function movePrivateAccessor(element, key, methodLocalVar, isStatic) {
let params;
let block;
if (element.node.kind === "set") {
params = [_core.types.identifier("v")];
block = [_core.types.expressionStatement(_core.types.callExpression(methodLocalVar, [_core.types.thisExpression(), _core.types.identifier("v")]))];
} else {
params = [];
block = [_core.types.returnStatement(_core.types.callExpression(methodLocalVar, [_core.types.thisExpression()]))];
}
element.replaceWith(_core.types.classPrivateMethod(element.node.kind, _core.types.cloneNode(key), params, _core.types.blockStatement(block), isStatic));
}
function isClassDecoratableElementPath(path) {
const {
type
} = path;
return type !== "TSDeclareMethod" && type !== "TSIndexSignature" && type !== "StaticBlock";
}
function staticBlockToIIFE(block) {
return _core.types.callExpression(_core.types.arrowFunctionExpression([], _core.types.blockStatement(block.body)), []);
}
function maybeSequenceExpression(exprs) {
if (exprs.length === 0) return _core.types.unaryExpression("void", _core.types.numericLiteral(0));
if (exprs.length === 1) return exprs[0];
return _core.types.sequenceExpression(exprs);
}
function createSetFunctionNameCall(state, className) {
return _core.types.callExpression(state.addHelper("setFunctionName"), [_core.types.thisExpression(), className]);
}
function createToPropertyKeyCall(state, propertyKey) {
return _core.types.callExpression(state.addHelper("toPropertyKey"), [propertyKey]);
}
function checkPrivateMethodUpdateError(path, decoratedPrivateMethods) {
const privateNameVisitor = (0, _fields.privateNameVisitorFactory)({
PrivateName(path, state) {
if (!state.privateNamesMap.has(path.node.id.name)) return;
const parentPath = path.parentPath;
const parentParentPath = parentPath.parentPath;
if (parentParentPath.node.type === "AssignmentExpression" && parentParentPath.node.left === parentPath.node || parentParentPath.node.type === "UpdateExpression" || parentParentPath.node.type === "RestElement" || parentParentPath.node.type === "ArrayPattern" || parentParentPath.node.type === "ObjectProperty" && parentParentPath.node.value === parentPath.node && parentParentPath.parentPath.type === "ObjectPattern" || parentParentPath.node.type === "ForOfStatement" && parentParentPath.node.left === parentPath.node) {
throw path.buildCodeFrameError(`Decorated private methods are read-only, but "#${path.node.id.name}" is updated via this expression.`);
}
}
});
const privateNamesMap = new Map();
for (const name of decoratedPrivateMethods) {
privateNamesMap.set(name, null);
}
path.traverse(privateNameVisitor, {
privateNamesMap: privateNamesMap
});
}
function transformClass(path, state, constantSuper, version, className, propertyVisitor) {
const body = path.get("body.body");
const classDecorators = path.node.decorators;
let hasElementDecorators = false;
const generateClassPrivateUid = createLazyPrivateUidGeneratorForClass(path);
const assignments = [];
const scopeParent = path.scope.parent;
const memoiseExpression = (expression, hint) => {
const localEvaluatedId = scopeParent.generateDeclaredUidIdentifier(hint);
assignments.push(_core.types.assignmentExpression("=", localEvaluatedId, expression));
return _core.types.cloneNode(localEvaluatedId);
};
let protoInitLocal;
let staticInitLocal;
for (const element of body) {
if (!isClassDecoratableElementPath(element)) {
continue;
}
if (isDecorated(element.node)) {
switch (element.node.type) {
case "ClassProperty":
propertyVisitor.ClassProperty(element, state);
break;
case "ClassPrivateProperty":
propertyVisitor.ClassPrivateProperty(element, state);
break;
case "ClassAccessorProperty":
propertyVisitor.ClassAccessorProperty(element, state);
default:
if (element.node.static) {
var _staticInitLocal;
(_staticInitLocal = staticInitLocal) != null ? _staticInitLocal : staticInitLocal = scopeParent.generateDeclaredUidIdentifier("initStatic");
} else {
var _protoInitLocal;
(_protoInitLocal = protoInitLocal) != null ? _protoInitLocal : protoInitLocal = scopeParent.generateDeclaredUidIdentifier("initProto");
}
break;
}
hasElementDecorators = true;
} else if (element.node.type === "ClassAccessorProperty") {
propertyVisitor.ClassAccessorProperty(element, state);
const {
key,
value,
static: isStatic,
computed
} = element.node;
const newId = generateClassPrivateUid();
const newField = generateClassProperty(newId, value, isStatic);
const keyPath = element.get("key");
const [newPath] = element.replaceWith(newField);
addProxyAccessorsFor(path.node.id, newPath, computed && !keyPath.isConstantExpression() ? memoiseExpression(createToPropertyKeyCall(state, key), "computedKey") : key, newId, version, computed);
}
}
if (!classDecorators && !hasElementDecorators) {
if (assignments.length > 0) {
path.insertBefore(assignments.map(expr => _core.types.expressionStatement(expr)));
path.scope.crawl();
}
return;
}
const elementDecoratorInfo = [];
let constructorPath;
const decoratedPrivateMethods = new Set();
let classInitLocal, classIdLocal;
const decoratorsThis = new Map();
const maybeExtractDecorators = (decorators, memoiseInPlace) => {
let needMemoise = false;
for (const decorator of decorators) {
const {
expression
} = decorator;
if (version === "2023-05" && _core.types.isMemberExpression(expression)) {
let object;
if (_core.types.isSuper(expression.object) || _core.types.isThisExpression(expression.object)) {
needMemoise = true;
if (memoiseInPlace) {
object = memoiseExpression(_core.types.thisExpression(), "obj");
} else {
object = _core.types.thisExpression();
}
} else {
if (!scopeParent.isStatic(expression.object)) {
needMemoise = true;
if (memoiseInPlace) {
expression.object = memoiseExpression(expression.object, "obj");
}
}
object = _core.types.cloneNode(expression.object);
}
decoratorsThis.set(decorator, object);
}
if (!scopeParent.isStatic(expression)) {
needMemoise = true;
if (memoiseInPlace) {
decorator.expression = memoiseExpression(expression, "dec");
}
}
}
return needMemoise && !memoiseInPlace;
};
let needsDeclaraionForClassBinding = false;
let classDecorationsFlag = 0;
let classDecorations = [];
let classDecorationsId;
if (classDecorators) {
classInitLocal = scopeParent.generateDeclaredUidIdentifier("initClass");
needsDeclaraionForClassBinding = path.isClassDeclaration();
({
id: classIdLocal,
path
} = replaceClassWithVar(path, className));
path.node.decorators = null;
const needMemoise = maybeExtractDecorators(classDecorators, false);
const {
hasThis,
decs
} = generateDecorationList(classDecorators.map(el => el.expression), classDecorators.map(dec => decoratorsThis.get(dec)), version);
classDecorationsFlag = hasThis ? 1 : 0;
classDecorations = decs;
if (needMemoise) {
classDecorationsId = memoiseExpression(_core.types.arrayExpression(classDecorations), "classDecs");
}
} else {
if (!path.node.id) {
path.node.id = path.scope.generateUidIdentifier("Class");
}
classIdLocal = _core.types.cloneNode(path.node.id);
}
let lastInstancePrivateName;
let needsInstancePrivateBrandCheck = false;
let fieldInitializerAssignments = [];
if (hasElementDecorators) {
if (protoInitLocal) {
const protoInitCall = _core.types.callExpression(_core.types.cloneNode(protoInitLocal), [_core.types.thisExpression()]);
fieldInitializerAssignments.push(protoInitCall);
}
for (const element of body) {
if (!isClassDecoratableElementPath(element)) {
continue;
}
const {
node
} = element;
const decorators = element.node.decorators;
const hasDecorators = !!(decorators != null && decorators.length);
if (hasDecorators) {
maybeExtractDecorators(decorators, true);
}
const isComputed = "computed" in element.node && element.node.computed;
if (isComputed) {
if (!element.get("key").isConstantExpression()) {
node.key = memoiseExpression(createToPropertyKeyCall(state, node.key), "computedKey");
}
}
const kind = getElementKind(element);
const {
key
} = node;
const isPrivate = key.type === "PrivateName";
const isStatic = element.node.static;
let name = "computedKey";
if (isPrivate) {
name = key.id.name;
} else if (!isComputed && key.type === "Identifier") {
name = key.name;
}
if (isPrivate && !isStatic) {
if (hasDecorators) {
needsInstancePrivateBrandCheck = true;
}
if (_core.types.isClassPrivateProperty(node) || !lastInstancePrivateName) {
lastInstancePrivateName = key;
}
}
if (element.isClassMethod({
kind: "constructor"
})) {
constructorPath = element;
}
if (hasDecorators) {
let locals;
let privateMethods;
if (kind === ACCESSOR) {
const {
value
} = element.node;
const params = [_core.types.thisExpression()];
if (value) {
params.push(_core.types.cloneNode(value));
}
const newId = generateClassPrivateUid();
const newFieldInitId = element.scope.parent.generateDeclaredUidIdentifier(`init_${name}`);
const newValue = _core.types.callExpression(_core.types.cloneNode(newFieldInitId), params);
const newField = generateClassProperty(newId, newValue, isStatic);
const [newPath] = element.replaceWith(newField);
if (isPrivate) {
privateMethods = extractProxyAccessorsFor(newId, version);
const getId = newPath.scope.parent.generateDeclaredUidIdentifier(`get_${name}`);
const setId = newPath.scope.parent.generateDeclaredUidIdentifier(`set_${name}`);
addCallAccessorsFor(newPath, key, getId, setId);
locals = [newFieldInitId, getId, setId];
} else {
addProxyAccessorsFor(path.node.id, newPath, key, newId, version, isComputed);
locals = newFieldInitId;
}
} else if (kind === FIELD) {
const initId = element.scope.parent.generateDeclaredUidIdentifier(`init_${name}`);
const valuePath = element.get("value");
valuePath.replaceWith(_core.types.callExpression(_core.types.cloneNode(initId), [_core.types.thisExpression(), valuePath.node].filter(v => v)));
locals = initId;
if (isPrivate) {
privateMethods = extractProxyAccessorsFor(key, version);
}
} else if (isPrivate) {
locals = element.scope.parent.generateDeclaredUidIdentifier(`call_${name}`);
const replaceSupers = new _helperReplaceSupers.default({
constantSuper,
methodPath: element,
objectRef: classIdLocal,
superRef: path.node.superClass,
file: state.file,
refToPreserve: classIdLocal
});
replaceSupers.replace();
const {
params,
body,
async: isAsync
} = element.node;
privateMethods = [_core.types.functionExpression(undefined, params.filter(isNotTsParameter), body, isAsync)];
if (kind === GETTER || kind === SETTER) {
movePrivateAccessor(element, _core.types.cloneNode(key), _core.types.cloneNode(locals), isStatic);
} else {
const node = element.node;
path.node.body.body.unshift(_core.types.classPrivateProperty(key, _core.types.cloneNode(locals), [], node.static));
decoratedPrivateMethods.add(key.id.name);
element.remove();
}
}
let nameExpr;
if (isComputed) {
nameExpr = _core.types.cloneNode(key);
} else if (key.type === "PrivateName") {
nameExpr = _core.types.stringLiteral(key.id.name);
} else if (key.type === "Identifier") {
nameExpr = _core.types.stringLiteral(key.name);
} else {
nameExpr = _core.types.cloneNode(key);
}
elementDecoratorInfo.push({
kind,
decorators: decorators.map(d => d.expression),
decoratorsThis: decorators.map(d => decoratorsThis.get(d)),
name: nameExpr,
isStatic,
privateMethods,
locals
});
if (element.node) {
element.node.decorators = null;
}
}
if (fieldInitializerAssignments.length > 0 && !isStatic && (kind === FIELD || kind === ACCESSOR)) {
prependExpressionsToFieldInitializer(fieldInitializerAssignments, element);
fieldInitializerAssignments = [];
}
}
}
if (fieldInitializerAssignments.length > 0) {
const isDerivedClass = !!path.node.superClass;
if (constructorPath) {
if (isDerivedClass) {
insertExpressionsAfterSuperCallAndOptimize(fieldInitializerAssignments, constructorPath, protoInitLocal);
} else {
prependExpressionsToConstructor(fieldInitializerAssignments, constructorPath);
}
} else {
path.node.body.body.unshift(createConstructorFromExpressions(fieldInitializerAssignments, isDerivedClass));
}
fieldInitializerAssignments = [];
}
const elementDecorations = generateDecorationExprs(elementDecoratorInfo, version);
const elementLocals = extractElementLocalAssignments(elementDecoratorInfo);
if (protoInitLocal) {
elementLocals.push(protoInitLocal);
}
if (staticInitLocal) {
elementLocals.push(staticInitLocal);
}
const classLocals = [];
let classInitInjected = false;
const classInitCall = classInitLocal && _core.types.callExpression(_core.types.cloneNode(classInitLocal), []);
const originalClass = path.node;
if (classDecorators) {
classLocals.push(classIdLocal, classInitLocal);
const statics = [];
let staticBlocks = [];
path.get("body.body").forEach(element => {
if (element.isStaticBlock()) {
staticBlocks.push(element.node);
element.remove();
return;
}
const isProperty = element.isClassProperty() || element.isClassPrivateProperty();
if ((isProperty || element.isClassPrivateMethod()) && element.node.static) {
if (isProperty && staticBlocks.length > 0) {
const allValues = staticBlocks.map(staticBlockToIIFE);
if (element.node.value) allValues.push(element.node.value);
element.node.value = maybeSequenceExpression(allValues);
staticBlocks = [];
}
element.node.static = false;
statics.push(element.node);
element.remove();
}
});
if (statics.length > 0 || staticBlocks.length > 0) {
const staticsClass = _core.template.expression.ast`
class extends ${state.addHelper("identity")} {}
`;
staticsClass.body.body = [_core.types.staticBlock([_core.types.toStatement(originalClass, true) || _core.types.expressionStatement(originalClass)]), ...statics];
const constructorBody = [];
const newExpr = _core.types.newExpression(staticsClass, []);
if (staticBlocks.length > 0) {
constructorBody.push(...staticBlocks.map(staticBlockToIIFE));
}
if (classInitCall) {
classInitInjected = true;
constructorBody.push(classInitCall);
}
if (constructorBody.length > 0) {
constructorBody.unshift(_core.types.callExpression(_core.types.super(), [_core.types.cloneNode(classIdLocal)]));
staticsClass.body.body.push(_core.types.classMethod("constructor", _core.types.identifier("constructor"), [], _core.types.blockStatement([_core.types.expressionStatement(_core.types.sequenceExpression(constructorBody))])));
} else {
newExpr.arguments.push(_core.types.cloneNode(classIdLocal));
}
path.replaceWith(newExpr);
}
}
if (!classInitInjected && classInitCall) {
path.node.body.body.push(_core.types.staticBlock([_core.types.expressionStatement(classInitCall)]));
}
let {
superClass
} = originalClass;
if (superClass && version === "2023-05") {
const id = path.scope.maybeGenerateMemoised(superClass);
if (id) {
originalClass.superClass = _core.types.assignmentExpression("=", id, superClass);
superClass = id;
}
}
originalClass.body.body.unshift(_core.types.staticBlock([_core.types.expressionStatement(createLocalsAssignment(elementLocals, classLocals, elementDecorations, classDecorationsId ? _core.types.cloneNode(classDecorationsId) : _core.types.arrayExpression(classDecorations), _core.types.numericLiteral(classDecorationsFlag), needsInstancePrivateBrandCheck ? lastInstancePrivateName : null, typeof className === "object" ? className : undefined, _core.types.cloneNode(superClass), state, version)), staticInitLocal && _core.types.expressionStatement(_core.types.callExpression(_core.types.cloneNode(staticInitLocal), [_core.types.thisExpression()]))].filter(Boolean)));
path.insertBefore(assignments.map(expr => _core.types.expressionStatement(expr)));
if (needsDeclaraionForClassBinding) {
path.insertBefore(_core.types.variableDeclaration("let", [_core.types.variableDeclarator(_core.types.cloneNode(classIdLocal))]));
}
if (decoratedPrivateMethods.size > 0) {
checkPrivateMethodUpdateError(path, decoratedPrivateMethods);
}
path.scope.crawl();
return path;
}
function createLocalsAssignment(elementLocals, classLocals, elementDecorations, classDecorations, classDecorationsFlag, maybePrivateBranName, setClassName, superClass, state, version) {
let lhs, rhs;
const args = [setClassName ? createSetFunctionNameCall(state, setClassName) : _core.types.thisExpression(), elementDecorations, classDecorations];
{
if (version === "2021-12" || version === "2022-03" && !state.availableHelper("applyDecs2203R")) {
const lhs = _core.types.arrayPattern([...elementLocals, ...classLocals]);
const rhs = _core.types.callExpression(state.addHelper(version === "2021-12" ? "applyDecs" : "applyDecs2203"), args);
return _core.types.assignmentExpression("=", lhs, rhs);
}
}
if (version === "2023-05") {
if (maybePrivateBranName || superClass || classDecorationsFlag.value !== 0) {
args.push(classDecorationsFlag);
}
if (maybePrivateBranName) {
args.push(_core.template.expression.ast`
_ => ${_core.types.cloneNode(maybePrivateBranName)} in _
`);
} else if (superClass) {
args.push(_core.types.unaryExpression("void", _core.types.numericLiteral(0)));
}
if (superClass) args.push(superClass);
rhs = _core.types.callExpression(state.addHelper("applyDecs2305"), args);
} else if (version === "2023-01") {
if (maybePrivateBranName) {
args.push(_core.template.expression.ast`
_ => ${_core.types.cloneNode(maybePrivateBranName)} in _
`);
}
rhs = _core.types.callExpression(state.addHelper("applyDecs2301"), args);
} else {
rhs = _core.types.callExpression(state.addHelper("applyDecs2203R"), args);
}
if (elementLocals.length > 0) {
if (classLocals.length > 0) {
lhs = _core.types.objectPattern([_core.types.objectProperty(_core.types.identifier("e"), _core.types.arrayPattern(elementLocals)), _core.types.objectProperty(_core.types.identifier("c"), _core.types.arrayPattern(classLocals))]);
} else {
lhs = _core.types.arrayPattern(elementLocals);
rhs = _core.types.memberExpression(rhs, _core.types.identifier("e"), false, false);
}
} else {
lhs = _core.types.arrayPattern(classLocals);
rhs = _core.types.memberExpression(rhs, _core.types.identifier("c"), false, false);
}
return _core.types.assignmentExpression("=", lhs, rhs);
}
function isProtoKey(node) {
return node.type === "Identifier" ? node.name === "__proto__" : node.value === "__proto__";
}
function isDecorated(node) {
return node.decorators && node.decorators.length > 0;
}
function shouldTransformElement(node) {
switch (node.type) {
case "ClassAccessorProperty":
return true;
case "ClassMethod":
case "ClassProperty":
case "ClassPrivateMethod":
case "ClassPrivateProperty":
return isDecorated(node);
default:
return false;
}
}
function shouldTransformClass(node) {
return isDecorated(node) || node.body.body.some(shouldTransformElement);
}
function NamedEvaluationVisitoryFactory(isAnonymous, visitor) {
function handleComputedProperty(propertyPath, key, state) {
switch (key.type) {
case "StringLiteral":
return _core.types.stringLiteral(key.value);
case "NumericLiteral":
case "BigIntLiteral":
{
const keyValue = key.value + "";
propertyPath.get("key").replaceWith(_core.types.stringLiteral(keyValue));
return _core.types.stringLiteral(keyValue);
}
default:
{
const ref = propertyPath.scope.maybeGenerateMemoised(key);
propertyPath.get("key").replaceWith(_core.types.assignmentExpression("=", ref, createToPropertyKeyCall(state, key)));
return _core.types.cloneNode(ref);
}
}
}
return {
VariableDeclarator(path, state) {
const id = path.node.id;
if (id.type === "Identifier") {
const initializer = (0, _helperSkipTransparentExpressionWrappers.skipTransparentExprWrappers)(path.get("init"));
if (isAnonymous(initializer)) {
const name = id.name;
visitor(initializer, state, name);
}
}
},
AssignmentExpression(path, state) {
const id = path.node.left;
if (id.type === "Identifier") {
const initializer = (0, _helperSkipTransparentExpressionWrappers.skipTransparentExprWrappers)(path.get("right"));
if (isAnonymous(initializer)) {
switch (path.node.operator) {
case "=":
case "&&=":
case "||=":
case "??=":
visitor(initializer, state, id.name);
}
}
}
},
AssignmentPattern(path, state) {
const id = path.node.left;
if (id.type === "Identifier") {
const initializer = (0, _helperSkipTransparentExpressionWrappers.skipTransparentExprWrappers)(path.get("right"));
if (isAnonymous(initializer)) {
const name = id.name;
visitor(initializer, state, name);
}
}
},
ObjectExpression(path, state) {
for (const propertyPath of path.get("properties")) {
const {
node
} = propertyPath;
if (node.type !== "ObjectProperty") continue;
const id = node.key;
const initializer = (0, _helperSkipTransparentExpressionWrappers.skipTransparentExprWrappers)(propertyPath.get("value"));
if (isAnonymous(initializer)) {
if (!node.computed) {
if (!isProtoKey(id)) {
if (id.type === "Identifier") {
visitor(initializer, state, id.name);
} else {
const className = _core.types.stringLiteral(id.value + "");
visitor(initializer, state, className);
}
}
} else {
const ref = handleComputedProperty(propertyPath, id, state);
visitor(initializer, state, ref);
}
}
}
},
ClassPrivateProperty(path, state) {
const {
node
} = path;
const initializer = (0, _helperSkipTransparentExpressionWrappers.skipTransparentExprWrappers)(path.get("value"));
if (isAnonymous(initializer)) {
const className = _core.types.stringLiteral("#" + node.key.id.name);
visitor(initializer, state, className);
}
},
ClassAccessorProperty(path, state) {
const {
node
} = path;
const id = node.key;
const initializer = (0, _helperSkipTransparentExpressionWrappers.skipTransparentExprWrappers)(path.get("value"));
if (isAnonymous(initializer)) {
if (!node.computed) {
if (id.type === "Identifier") {
visitor(initializer, state, id.name);
} else if (id.type === "PrivateName") {
const className = _core.types.stringLiteral("#" + id.id.name);
visitor(initializer, state, className);
} else {
const className = _core.types.stringLiteral(id.value + "");
visitor(initializer, state, className);
}
} else {
const ref = handleComputedProperty(path, id, state);
visitor(initializer, state, ref);
}
}
},
ClassProperty(path, state) {
const {
node
} = path;
const id = node.key;
const initializer = (0, _helperSkipTransparentExpressionWrappers.skipTransparentExprWrappers)(path.get("value"));
if (isAnonymous(initializer)) {
if (!node.computed) {
if (id.type === "Identifier") {
visitor(initializer, state, id.name);
} else {
const className = _core.types.stringLiteral(id.value + "");
visitor(initializer, state, className);
}
} else {
const ref = handleComputedProperty(path, id, state);
visitor(initializer, state, ref);
}
}
}
};
}
function isDecoratedAnonymousClassExpression(path) {
return path.isClassExpression({
id: null
}) && shouldTransformClass(path.node);
}
function _default({
assertVersion,
assumption
}, {
loose
}, version, inherits) {
var _assumption;
{
if (version === "2023-05" || version === "2023-01") {
assertVersion("^7.21.0");
} else if (version === "2021-12") {
assertVersion("^7.16.0");
} else {
assertVersion("^7.19.0");
}
}
const VISITED = new WeakSet();
const constantSuper = (_assumption = assumption("constantSuper")) != null ? _assumption : loose;
const namedEvaluationVisitor = NamedEvaluationVisitoryFactory(isDecoratedAnonymousClassExpression, visitClass);
function visitClass(path, state, className) {
var _className, _node$id;
if (VISITED.has(path)) return;
const {
node
} = path;
(_className = className) != null ? _className : className = (_node$id = node.id) == null ? void 0 : _node$id.name;
const newPath = transformClass(path, state, constantSuper, version, className, namedEvaluationVisitor);
if (newPath) {
VISITED.add(newPath);
return;
}
VISITED.add(path);
}
return {
name: "proposal-decorators",
inherits: inherits,
visitor: Object.assign({
ExportDefaultDeclaration(path, state) {
const {
declaration
} = path.node;
if ((declaration == null ? void 0 : declaration.type) === "ClassDeclaration" && isDecorated(declaration)) {
const isAnonymous = !declaration.id;
const updatedVarDeclarationPath = (0, _helperSplitExportDeclaration.default)(path);
if (isAnonymous) {
visitClass(updatedVarDeclarationPath, state, _core.types.stringLiteral("default"));
}
}
},
ExportNamedDeclaration(path) {
const {
declaration
} = path.node;
if ((declaration == null ? void 0 : declaration.type) === "ClassDeclaration" && isDecorated(declaration)) {
(0, _helperSplitExportDeclaration.default)(path);
}
},
Class(path, state) {
visitClass(path, state, undefined);
}
}, namedEvaluationVisitor)
};
}
//# sourceMappingURL=decorators.js.map

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,132 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.FEATURES = void 0;
exports.enableFeature = enableFeature;
exports.isLoose = isLoose;
exports.shouldTransform = shouldTransform;
var _decorators = require("./decorators-2018-09.js");
const FEATURES = exports.FEATURES = Object.freeze({
fields: 1 << 1,
privateMethods: 1 << 2,
decorators: 1 << 3,
privateIn: 1 << 4,
staticBlocks: 1 << 5
});
const featuresSameLoose = new Map([[FEATURES.fields, "@babel/plugin-transform-class-properties"], [FEATURES.privateMethods, "@babel/plugin-transform-private-methods"], [FEATURES.privateIn, "@babel/plugin-transform-private-property-in-object"]]);
const featuresKey = "@babel/plugin-class-features/featuresKey";
const looseKey = "@babel/plugin-class-features/looseKey";
{
var looseLowPriorityKey = "@babel/plugin-class-features/looseLowPriorityKey/#__internal__@babel/preset-env__please-overwrite-loose-instead-of-throwing";
}
{
var canIgnoreLoose = function (file, feature) {
return !!(file.get(looseLowPriorityKey) & feature);
};
}
function enableFeature(file, feature, loose) {
if (!hasFeature(file, feature) || canIgnoreLoose(file, feature)) {
file.set(featuresKey, file.get(featuresKey) | feature);
if (loose === "#__internal__@babel/preset-env__prefer-true-but-false-is-ok-if-it-prevents-an-error") {
setLoose(file, feature, true);
file.set(looseLowPriorityKey, file.get(looseLowPriorityKey) | feature);
} else if (loose === "#__internal__@babel/preset-env__prefer-false-but-true-is-ok-if-it-prevents-an-error") {
setLoose(file, feature, false);
file.set(looseLowPriorityKey, file.get(looseLowPriorityKey) | feature);
} else {
setLoose(file, feature, loose);
}
}
let resolvedLoose;
for (const [mask, name] of featuresSameLoose) {
if (!hasFeature(file, mask)) continue;
{
if (canIgnoreLoose(file, mask)) continue;
}
const loose = isLoose(file, mask);
if (resolvedLoose === !loose) {
throw new Error("'loose' mode configuration must be the same for @babel/plugin-transform-class-properties, " + "@babel/plugin-transform-private-methods and " + "@babel/plugin-transform-private-property-in-object (when they are enabled).");
} else {
resolvedLoose = loose;
{
var higherPriorityPluginName = name;
}
}
}
if (resolvedLoose !== undefined) {
for (const [mask, name] of featuresSameLoose) {
if (hasFeature(file, mask) && isLoose(file, mask) !== resolvedLoose) {
setLoose(file, mask, resolvedLoose);
console.warn(`Though the "loose" option was set to "${!resolvedLoose}" in your @babel/preset-env ` + `config, it will not be used for ${name} since the "loose" mode option was set to ` + `"${resolvedLoose}" for ${higherPriorityPluginName}.\nThe "loose" option must be the ` + `same for @babel/plugin-transform-class-properties, @babel/plugin-transform-private-methods ` + `and @babel/plugin-transform-private-property-in-object (when they are enabled): you can ` + `silence this warning by explicitly adding\n` + `\t["${name}", { "loose": ${resolvedLoose} }]\n` + `to the "plugins" section of your Babel config.`);
}
}
}
}
function hasFeature(file, feature) {
return !!(file.get(featuresKey) & feature);
}
function isLoose(file, feature) {
return !!(file.get(looseKey) & feature);
}
function setLoose(file, feature, loose) {
if (loose) file.set(looseKey, file.get(looseKey) | feature);else file.set(looseKey, file.get(looseKey) & ~feature);
{
file.set(looseLowPriorityKey, file.get(looseLowPriorityKey) & ~feature);
}
}
function shouldTransform(path, file) {
let decoratorPath = null;
let publicFieldPath = null;
let privateFieldPath = null;
let privateMethodPath = null;
let staticBlockPath = null;
if ((0, _decorators.hasOwnDecorators)(path.node)) {
decoratorPath = path.get("decorators.0");
}
for (const el of path.get("body.body")) {
if (!decoratorPath && (0, _decorators.hasOwnDecorators)(el.node)) {
decoratorPath = el.get("decorators.0");
}
if (!publicFieldPath && el.isClassProperty()) {
publicFieldPath = el;
}
if (!privateFieldPath && el.isClassPrivateProperty()) {
privateFieldPath = el;
}
if (!privateMethodPath && el.isClassPrivateMethod != null && el.isClassPrivateMethod()) {
privateMethodPath = el;
}
if (!staticBlockPath && el.isStaticBlock != null && el.isStaticBlock()) {
staticBlockPath = el;
}
}
if (decoratorPath && privateFieldPath) {
throw privateFieldPath.buildCodeFrameError("Private fields in decorated classes are not supported yet.");
}
if (decoratorPath && privateMethodPath) {
throw privateMethodPath.buildCodeFrameError("Private methods in decorated classes are not supported yet.");
}
if (decoratorPath && !hasFeature(file, FEATURES.decorators)) {
throw path.buildCodeFrameError("Decorators are not enabled." + "\nIf you are using " + '["@babel/plugin-proposal-decorators", { "version": "legacy" }], ' + 'make sure it comes *before* "@babel/plugin-transform-class-properties" ' + "and enable loose mode, like so:\n" + '\t["@babel/plugin-proposal-decorators", { "version": "legacy" }]\n' + '\t["@babel/plugin-transform-class-properties", { "loose": true }]');
}
if (privateMethodPath && !hasFeature(file, FEATURES.privateMethods)) {
throw privateMethodPath.buildCodeFrameError("Class private methods are not enabled. " + "Please add `@babel/plugin-transform-private-methods` to your configuration.");
}
if ((publicFieldPath || privateFieldPath) && !hasFeature(file, FEATURES.fields) && !hasFeature(file, FEATURES.privateMethods)) {
throw path.buildCodeFrameError("Class fields are not enabled. " + "Please add `@babel/plugin-transform-class-properties` to your configuration.");
}
if (staticBlockPath && !hasFeature(file, FEATURES.staticBlocks)) {
throw path.buildCodeFrameError("Static class blocks are not enabled. " + "Please add `@babel/plugin-transform-class-static-block` to your configuration.");
}
if (decoratorPath || privateMethodPath || staticBlockPath) {
return true;
}
if ((publicFieldPath || privateFieldPath) && hasFeature(file, FEATURES.fields)) {
return true;
}
return false;
}
//# sourceMappingURL=features.js.map

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,845 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.buildCheckInRHS = buildCheckInRHS;
exports.buildFieldsInitNodes = buildFieldsInitNodes;
exports.buildPrivateNamesMap = buildPrivateNamesMap;
exports.buildPrivateNamesNodes = buildPrivateNamesNodes;
exports.privateNameVisitorFactory = privateNameVisitorFactory;
exports.transformPrivateNamesUsage = transformPrivateNamesUsage;
var _core = require("@babel/core");
var _helperReplaceSupers = require("@babel/helper-replace-supers");
var _helperEnvironmentVisitor = require("@babel/helper-environment-visitor");
var _helperMemberExpressionToFunctions = require("@babel/helper-member-expression-to-functions");
var _helperOptimiseCallExpression = require("@babel/helper-optimise-call-expression");
var _helperAnnotateAsPure = require("@babel/helper-annotate-as-pure");
var _helperSkipTransparentExpressionWrappers = require("@babel/helper-skip-transparent-expression-wrappers");
var ts = require("./typescript.js");
function buildPrivateNamesMap(props) {
const privateNamesMap = new Map();
for (const prop of props) {
if (prop.isPrivate()) {
const {
name
} = prop.node.key.id;
const update = privateNamesMap.has(name) ? privateNamesMap.get(name) : {
id: prop.scope.generateUidIdentifier(name),
static: prop.node.static,
method: !prop.isProperty()
};
if (prop.isClassPrivateMethod()) {
if (prop.node.kind === "get") {
update.getId = prop.scope.generateUidIdentifier(`get_${name}`);
} else if (prop.node.kind === "set") {
update.setId = prop.scope.generateUidIdentifier(`set_${name}`);
} else if (prop.node.kind === "method") {
update.methodId = prop.scope.generateUidIdentifier(name);
}
}
privateNamesMap.set(name, update);
}
}
return privateNamesMap;
}
function buildPrivateNamesNodes(privateNamesMap, privateFieldsAsProperties, privateFieldsAsSymbols, state) {
const initNodes = [];
for (const [name, value] of privateNamesMap) {
const {
static: isStatic,
method: isMethod,
getId,
setId
} = value;
const isAccessor = getId || setId;
const id = _core.types.cloneNode(value.id);
let init;
if (privateFieldsAsProperties) {
init = _core.types.callExpression(state.addHelper("classPrivateFieldLooseKey"), [_core.types.stringLiteral(name)]);
} else if (privateFieldsAsSymbols) {
init = _core.types.callExpression(_core.types.identifier("Symbol"), [_core.types.stringLiteral(name)]);
} else if (!isStatic) {
init = _core.types.newExpression(_core.types.identifier(!isMethod || isAccessor ? "WeakMap" : "WeakSet"), []);
}
if (init) {
(0, _helperAnnotateAsPure.default)(init);
initNodes.push(_core.template.statement.ast`var ${id} = ${init}`);
}
}
return initNodes;
}
function privateNameVisitorFactory(visitor) {
const nestedVisitor = _core.traverse.visitors.merge([Object.assign({}, visitor), _helperEnvironmentVisitor.default]);
const privateNameVisitor = Object.assign({}, visitor, {
Class(path) {
const {
privateNamesMap
} = this;
const body = path.get("body.body");
const visiblePrivateNames = new Map(privateNamesMap);
const redeclared = [];
for (const prop of body) {
if (!prop.isPrivate()) continue;
const {
name
} = prop.node.key.id;
visiblePrivateNames.delete(name);
redeclared.push(name);
}
if (!redeclared.length) {
return;
}
path.get("body").traverse(nestedVisitor, Object.assign({}, this, {
redeclared
}));
path.traverse(privateNameVisitor, Object.assign({}, this, {
privateNamesMap: visiblePrivateNames
}));
path.skipKey("body");
}
});
return privateNameVisitor;
}
const privateNameVisitor = privateNameVisitorFactory({
PrivateName(path, {
noDocumentAll
}) {
const {
privateNamesMap,
redeclared
} = this;
const {
node,
parentPath
} = path;
if (!parentPath.isMemberExpression({
property: node
}) && !parentPath.isOptionalMemberExpression({
property: node
})) {
return;
}
const {
name
} = node.id;
if (!privateNamesMap.has(name)) return;
if (redeclared && redeclared.includes(name)) return;
this.handle(parentPath, noDocumentAll);
}
});
function unshadow(name, scope, innerBinding) {
while ((_scope = scope) != null && _scope.hasBinding(name) && !scope.bindingIdentifierEquals(name, innerBinding)) {
var _scope;
scope.rename(name);
scope = scope.parent;
}
}
function buildCheckInRHS(rhs, file, inRHSIsObject) {
if (inRHSIsObject || !(file.availableHelper != null && file.availableHelper("checkInRHS"))) return rhs;
return _core.types.callExpression(file.addHelper("checkInRHS"), [rhs]);
}
const privateInVisitor = privateNameVisitorFactory({
BinaryExpression(path, {
file
}) {
const {
operator,
left,
right
} = path.node;
if (operator !== "in") return;
if (!_core.types.isPrivateName(left)) return;
const {
privateFieldsAsProperties,
privateNamesMap,
redeclared
} = this;
const {
name
} = left.id;
if (!privateNamesMap.has(name)) return;
if (redeclared && redeclared.includes(name)) return;
unshadow(this.classRef.name, path.scope, this.innerBinding);
if (privateFieldsAsProperties) {
const {
id
} = privateNamesMap.get(name);
path.replaceWith(_core.template.expression.ast`
Object.prototype.hasOwnProperty.call(${buildCheckInRHS(right, file)}, ${_core.types.cloneNode(id)})
`);
return;
}
const {
id,
static: isStatic
} = privateNamesMap.get(name);
if (isStatic) {
path.replaceWith(_core.template.expression.ast`${buildCheckInRHS(right, file)} === ${_core.types.cloneNode(this.classRef)}`);
return;
}
path.replaceWith(_core.template.expression.ast`${_core.types.cloneNode(id)}.has(${buildCheckInRHS(right, file)})`);
}
});
const privateNameHandlerSpec = {
memoise(member, count) {
const {
scope
} = member;
const {
object
} = member.node;
const memo = scope.maybeGenerateMemoised(object);
if (!memo) {
return;
}
this.memoiser.set(object, memo, count);
},
receiver(member) {
const {
object
} = member.node;
if (this.memoiser.has(object)) {
return _core.types.cloneNode(this.memoiser.get(object));
}
return _core.types.cloneNode(object);
},
get(member) {
const {
classRef,
privateNamesMap,
file,
innerBinding
} = this;
const {
name
} = member.node.property.id;
const {
id,
static: isStatic,
method: isMethod,
methodId,
getId,
setId
} = privateNamesMap.get(name);
const isAccessor = getId || setId;
if (isStatic) {
const helperName = isMethod && !isAccessor ? "classStaticPrivateMethodGet" : "classStaticPrivateFieldSpecGet";
unshadow(classRef.name, member.scope, innerBinding);
return _core.types.callExpression(file.addHelper(helperName), [this.receiver(member), _core.types.cloneNode(classRef), _core.types.cloneNode(id)]);
}
if (isMethod) {
if (isAccessor) {
if (!getId && setId) {
if (file.availableHelper("writeOnlyError")) {
return _core.types.sequenceExpression([this.receiver(member), _core.types.callExpression(file.addHelper("writeOnlyError"), [_core.types.stringLiteral(`#${name}`)])]);
}
console.warn(`@babel/helpers is outdated, update it to silence this warning.`);
}
return _core.types.callExpression(file.addHelper("classPrivateFieldGet"), [this.receiver(member), _core.types.cloneNode(id)]);
}
return _core.types.callExpression(file.addHelper("classPrivateMethodGet"), [this.receiver(member), _core.types.cloneNode(id), _core.types.cloneNode(methodId)]);
}
return _core.types.callExpression(file.addHelper("classPrivateFieldGet"), [this.receiver(member), _core.types.cloneNode(id)]);
},
boundGet(member) {
this.memoise(member, 1);
return _core.types.callExpression(_core.types.memberExpression(this.get(member), _core.types.identifier("bind")), [this.receiver(member)]);
},
set(member, value) {
const {
classRef,
privateNamesMap,
file
} = this;
const {
name
} = member.node.property.id;
const {
id,
static: isStatic,
method: isMethod,
setId,
getId
} = privateNamesMap.get(name);
const isAccessor = getId || setId;
if (isStatic) {
const helperName = isMethod && !isAccessor ? "classStaticPrivateMethodSet" : "classStaticPrivateFieldSpecSet";
return _core.types.callExpression(file.addHelper(helperName), [this.receiver(member), _core.types.cloneNode(classRef), _core.types.cloneNode(id), value]);
}
if (isMethod) {
if (setId) {
return _core.types.callExpression(file.addHelper("classPrivateFieldSet"), [this.receiver(member), _core.types.cloneNode(id), value]);
}
return _core.types.sequenceExpression([this.receiver(member), value, _core.types.callExpression(file.addHelper("readOnlyError"), [_core.types.stringLiteral(`#${name}`)])]);
}
return _core.types.callExpression(file.addHelper("classPrivateFieldSet"), [this.receiver(member), _core.types.cloneNode(id), value]);
},
destructureSet(member) {
const {
classRef,
privateNamesMap,
file
} = this;
const {
name
} = member.node.property.id;
const {
id,
static: isStatic
} = privateNamesMap.get(name);
if (isStatic) {
try {
var helper = file.addHelper("classStaticPrivateFieldDestructureSet");
} catch (_unused) {
throw new Error("Babel can not transpile `[C.#p] = [0]` with @babel/helpers < 7.13.10, \n" + "please update @babel/helpers to the latest version.");
}
return _core.types.memberExpression(_core.types.callExpression(helper, [this.receiver(member), _core.types.cloneNode(classRef), _core.types.cloneNode(id)]), _core.types.identifier("value"));
}
return _core.types.memberExpression(_core.types.callExpression(file.addHelper("classPrivateFieldDestructureSet"), [this.receiver(member), _core.types.cloneNode(id)]), _core.types.identifier("value"));
},
call(member, args) {
this.memoise(member, 1);
return (0, _helperOptimiseCallExpression.default)(this.get(member), this.receiver(member), args, false);
},
optionalCall(member, args) {
this.memoise(member, 1);
return (0, _helperOptimiseCallExpression.default)(this.get(member), this.receiver(member), args, true);
},
delete() {
throw new Error("Internal Babel error: deleting private elements is a parsing error.");
}
};
const privateNameHandlerLoose = {
get(member) {
const {
privateNamesMap,
file
} = this;
const {
object
} = member.node;
const {
name
} = member.node.property.id;
return _core.template.expression`BASE(REF, PROP)[PROP]`({
BASE: file.addHelper("classPrivateFieldLooseBase"),
REF: _core.types.cloneNode(object),
PROP: _core.types.cloneNode(privateNamesMap.get(name).id)
});
},
set() {
throw new Error("private name handler with loose = true don't need set()");
},
boundGet(member) {
return _core.types.callExpression(_core.types.memberExpression(this.get(member), _core.types.identifier("bind")), [_core.types.cloneNode(member.node.object)]);
},
simpleSet(member) {
return this.get(member);
},
destructureSet(member) {
return this.get(member);
},
call(member, args) {
return _core.types.callExpression(this.get(member), args);
},
optionalCall(member, args) {
return _core.types.optionalCallExpression(this.get(member), args, true);
},
delete() {
throw new Error("Internal Babel error: deleting private elements is a parsing error.");
}
};
function transformPrivateNamesUsage(ref, path, privateNamesMap, {
privateFieldsAsProperties,
noDocumentAll,
innerBinding
}, state) {
if (!privateNamesMap.size) return;
const body = path.get("body");
const handler = privateFieldsAsProperties ? privateNameHandlerLoose : privateNameHandlerSpec;
(0, _helperMemberExpressionToFunctions.default)(body, privateNameVisitor, Object.assign({
privateNamesMap,
classRef: ref,
file: state
}, handler, {
noDocumentAll,
innerBinding
}));
body.traverse(privateInVisitor, {
privateNamesMap,
classRef: ref,
file: state,
privateFieldsAsProperties,
innerBinding
});
}
function buildPrivateFieldInitLoose(ref, prop, privateNamesMap) {
const {
id
} = privateNamesMap.get(prop.node.key.id.name);
const value = prop.node.value || prop.scope.buildUndefinedNode();
return inheritPropComments(_core.template.statement.ast`
Object.defineProperty(${ref}, ${_core.types.cloneNode(id)}, {
// configurable is false by default
// enumerable is false by default
writable: true,
value: ${value}
});
`, prop);
}
function buildPrivateInstanceFieldInitSpec(ref, prop, privateNamesMap, state) {
const {
id
} = privateNamesMap.get(prop.node.key.id.name);
const value = prop.node.value || prop.scope.buildUndefinedNode();
{
if (!state.availableHelper("classPrivateFieldInitSpec")) {
return inheritPropComments(_core.template.statement.ast`${_core.types.cloneNode(id)}.set(${ref}, {
// configurable is always false for private elements
// enumerable is always false for private elements
writable: true,
value: ${value},
})`, prop);
}
}
const helper = state.addHelper("classPrivateFieldInitSpec");
return inheritPropComments(_core.template.statement.ast`${helper}(
${_core.types.thisExpression()},
${_core.types.cloneNode(id)},
{
writable: true,
value: ${value}
},
)`, prop);
}
function buildPrivateStaticFieldInitSpec(prop, privateNamesMap) {
const privateName = privateNamesMap.get(prop.node.key.id.name);
const {
id,
getId,
setId,
initAdded
} = privateName;
const isAccessor = getId || setId;
if (!prop.isProperty() && (initAdded || !isAccessor)) return;
if (isAccessor) {
privateNamesMap.set(prop.node.key.id.name, Object.assign({}, privateName, {
initAdded: true
}));
return inheritPropComments(_core.template.statement.ast`
var ${_core.types.cloneNode(id)} = {
// configurable is false by default
// enumerable is false by default
// writable is false by default
get: ${getId ? getId.name : prop.scope.buildUndefinedNode()},
set: ${setId ? setId.name : prop.scope.buildUndefinedNode()}
}
`, prop);
}
const value = prop.node.value || prop.scope.buildUndefinedNode();
return inheritPropComments(_core.template.statement.ast`
var ${_core.types.cloneNode(id)} = {
// configurable is false by default
// enumerable is false by default
writable: true,
value: ${value}
};
`, prop);
}
function buildPrivateMethodInitLoose(ref, prop, privateNamesMap) {
const privateName = privateNamesMap.get(prop.node.key.id.name);
const {
methodId,
id,
getId,
setId,
initAdded
} = privateName;
if (initAdded) return;
if (methodId) {
return inheritPropComments(_core.template.statement.ast`
Object.defineProperty(${ref}, ${id}, {
// configurable is false by default
// enumerable is false by default
// writable is false by default
value: ${methodId.name}
});
`, prop);
}
const isAccessor = getId || setId;
if (isAccessor) {
privateNamesMap.set(prop.node.key.id.name, Object.assign({}, privateName, {
initAdded: true
}));
return inheritPropComments(_core.template.statement.ast`
Object.defineProperty(${ref}, ${id}, {
// configurable is false by default
// enumerable is false by default
// writable is false by default
get: ${getId ? getId.name : prop.scope.buildUndefinedNode()},
set: ${setId ? setId.name : prop.scope.buildUndefinedNode()}
});
`, prop);
}
}
function buildPrivateInstanceMethodInitSpec(ref, prop, privateNamesMap, state) {
const privateName = privateNamesMap.get(prop.node.key.id.name);
const {
getId,
setId,
initAdded
} = privateName;
if (initAdded) return;
const isAccessor = getId || setId;
if (isAccessor) {
return buildPrivateAccessorInitialization(ref, prop, privateNamesMap, state);
}
return buildPrivateInstanceMethodInitialization(ref, prop, privateNamesMap, state);
}
function buildPrivateAccessorInitialization(ref, prop, privateNamesMap, state) {
const privateName = privateNamesMap.get(prop.node.key.id.name);
const {
id,
getId,
setId
} = privateName;
privateNamesMap.set(prop.node.key.id.name, Object.assign({}, privateName, {
initAdded: true
}));
{
if (!state.availableHelper("classPrivateFieldInitSpec")) {
return inheritPropComments(_core.template.statement.ast`
${id}.set(${ref}, {
get: ${getId ? getId.name : prop.scope.buildUndefinedNode()},
set: ${setId ? setId.name : prop.scope.buildUndefinedNode()}
});
`, prop);
}
}
const helper = state.addHelper("classPrivateFieldInitSpec");
return inheritPropComments(_core.template.statement.ast`${helper}(
${_core.types.thisExpression()},
${_core.types.cloneNode(id)},
{
get: ${getId ? getId.name : prop.scope.buildUndefinedNode()},
set: ${setId ? setId.name : prop.scope.buildUndefinedNode()}
},
)`, prop);
}
function buildPrivateInstanceMethodInitialization(ref, prop, privateNamesMap, state) {
const privateName = privateNamesMap.get(prop.node.key.id.name);
const {
id
} = privateName;
{
if (!state.availableHelper("classPrivateMethodInitSpec")) {
return inheritPropComments(_core.template.statement.ast`${id}.add(${ref})`, prop);
}
}
const helper = state.addHelper("classPrivateMethodInitSpec");
return inheritPropComments(_core.template.statement.ast`${helper}(
${_core.types.thisExpression()},
${_core.types.cloneNode(id)}
)`, prop);
}
function buildPublicFieldInitLoose(ref, prop) {
const {
key,
computed
} = prop.node;
const value = prop.node.value || prop.scope.buildUndefinedNode();
return inheritPropComments(_core.types.expressionStatement(_core.types.assignmentExpression("=", _core.types.memberExpression(ref, key, computed || _core.types.isLiteral(key)), value)), prop);
}
function buildPublicFieldInitSpec(ref, prop, state) {
const {
key,
computed
} = prop.node;
const value = prop.node.value || prop.scope.buildUndefinedNode();
return inheritPropComments(_core.types.expressionStatement(_core.types.callExpression(state.addHelper("defineProperty"), [ref, computed || _core.types.isLiteral(key) ? key : _core.types.stringLiteral(key.name), value])), prop);
}
function buildPrivateStaticMethodInitLoose(ref, prop, state, privateNamesMap) {
const privateName = privateNamesMap.get(prop.node.key.id.name);
const {
id,
methodId,
getId,
setId,
initAdded
} = privateName;
if (initAdded) return;
const isAccessor = getId || setId;
if (isAccessor) {
privateNamesMap.set(prop.node.key.id.name, Object.assign({}, privateName, {
initAdded: true
}));
return inheritPropComments(_core.template.statement.ast`
Object.defineProperty(${ref}, ${id}, {
// configurable is false by default
// enumerable is false by default
// writable is false by default
get: ${getId ? getId.name : prop.scope.buildUndefinedNode()},
set: ${setId ? setId.name : prop.scope.buildUndefinedNode()}
})
`, prop);
}
return inheritPropComments(_core.template.statement.ast`
Object.defineProperty(${ref}, ${id}, {
// configurable is false by default
// enumerable is false by default
// writable is false by default
value: ${methodId.name}
});
`, prop);
}
function buildPrivateMethodDeclaration(prop, privateNamesMap, privateFieldsAsProperties = false) {
const privateName = privateNamesMap.get(prop.node.key.id.name);
const {
id,
methodId,
getId,
setId,
getterDeclared,
setterDeclared,
static: isStatic
} = privateName;
const {
params,
body,
generator,
async
} = prop.node;
const isGetter = getId && !getterDeclared && params.length === 0;
const isSetter = setId && !setterDeclared && params.length > 0;
let declId = methodId;
if (isGetter) {
privateNamesMap.set(prop.node.key.id.name, Object.assign({}, privateName, {
getterDeclared: true
}));
declId = getId;
} else if (isSetter) {
privateNamesMap.set(prop.node.key.id.name, Object.assign({}, privateName, {
setterDeclared: true
}));
declId = setId;
} else if (isStatic && !privateFieldsAsProperties) {
declId = id;
}
return inheritPropComments(_core.types.functionDeclaration(_core.types.cloneNode(declId), params, body, generator, async), prop);
}
const thisContextVisitor = _core.traverse.visitors.merge([{
UnaryExpression(path) {
const {
node
} = path;
if (node.operator === "delete") {
const argument = (0, _helperSkipTransparentExpressionWrappers.skipTransparentExprWrapperNodes)(node.argument);
if (_core.types.isThisExpression(argument)) {
path.replaceWith(_core.types.booleanLiteral(true));
}
}
},
ThisExpression(path, state) {
state.needsClassRef = true;
path.replaceWith(_core.types.cloneNode(state.classRef));
},
MetaProperty(path) {
const {
node,
scope
} = path;
if (node.meta.name === "new" && node.property.name === "target") {
path.replaceWith(scope.buildUndefinedNode());
}
}
}, _helperEnvironmentVisitor.default]);
const innerReferencesVisitor = {
ReferencedIdentifier(path, state) {
if (path.scope.bindingIdentifierEquals(path.node.name, state.innerBinding)) {
state.needsClassRef = true;
path.node.name = state.classRef.name;
}
}
};
function replaceThisContext(path, ref, innerBindingRef) {
var _state$classRef;
const state = {
classRef: ref,
needsClassRef: false,
innerBinding: innerBindingRef
};
if (!path.isMethod()) {
path.traverse(thisContextVisitor, state);
}
if (innerBindingRef != null && (_state$classRef = state.classRef) != null && _state$classRef.name && state.classRef.name !== innerBindingRef.name) {
path.traverse(innerReferencesVisitor, state);
}
return state.needsClassRef;
}
function isNameOrLength({
key,
computed
}) {
if (key.type === "Identifier") {
return !computed && (key.name === "name" || key.name === "length");
}
if (key.type === "StringLiteral") {
return key.value === "name" || key.value === "length";
}
return false;
}
function inheritPropComments(node, prop) {
_core.types.inheritLeadingComments(node, prop.node);
_core.types.inheritInnerComments(node, prop.node);
return node;
}
function buildFieldsInitNodes(ref, superRef, props, privateNamesMap, file, setPublicClassFields, privateFieldsAsProperties, constantSuper, innerBindingRef) {
var _ref, _ref2;
let classRefFlags = 0;
let injectSuperRef;
const staticNodes = [];
const instanceNodes = [];
let lastInstanceNodeReturnsThis = false;
const pureStaticNodes = [];
let classBindingNode = null;
const getSuperRef = _core.types.isIdentifier(superRef) ? () => superRef : () => {
var _injectSuperRef;
(_injectSuperRef = injectSuperRef) != null ? _injectSuperRef : injectSuperRef = props[0].scope.generateUidIdentifierBasedOnNode(superRef);
return injectSuperRef;
};
const classRefForInnerBinding = (_ref = ref) != null ? _ref : props[0].scope.generateUidIdentifier((innerBindingRef == null ? void 0 : innerBindingRef.name) || "Class");
(_ref2 = ref) != null ? _ref2 : ref = _core.types.cloneNode(innerBindingRef);
for (const prop of props) {
prop.isClassProperty() && ts.assertFieldTransformed(prop);
const isStatic = !(_core.types.isStaticBlock != null && _core.types.isStaticBlock(prop.node)) && prop.node.static;
const isInstance = !isStatic;
const isPrivate = prop.isPrivate();
const isPublic = !isPrivate;
const isField = prop.isProperty();
const isMethod = !isField;
const isStaticBlock = prop.isStaticBlock == null ? void 0 : prop.isStaticBlock();
if (isStatic) classRefFlags |= 1;
if (isStatic || isMethod && isPrivate || isStaticBlock) {
new _helperReplaceSupers.default({
methodPath: prop,
constantSuper,
file: file,
refToPreserve: innerBindingRef,
getSuperRef,
getObjectRef() {
classRefFlags |= 2;
if (isStatic || isStaticBlock) {
return classRefForInnerBinding;
} else {
return _core.types.memberExpression(classRefForInnerBinding, _core.types.identifier("prototype"));
}
}
}).replace();
const replaced = replaceThisContext(prop, classRefForInnerBinding, innerBindingRef);
if (replaced) {
classRefFlags |= 2;
}
}
lastInstanceNodeReturnsThis = false;
switch (true) {
case isStaticBlock:
{
const blockBody = prop.node.body;
if (blockBody.length === 1 && _core.types.isExpressionStatement(blockBody[0])) {
staticNodes.push(inheritPropComments(blockBody[0], prop));
} else {
staticNodes.push(_core.types.inheritsComments(_core.template.statement.ast`(() => { ${blockBody} })()`, prop.node));
}
break;
}
case isStatic && isPrivate && isField && privateFieldsAsProperties:
staticNodes.push(buildPrivateFieldInitLoose(_core.types.cloneNode(ref), prop, privateNamesMap));
break;
case isStatic && isPrivate && isField && !privateFieldsAsProperties:
staticNodes.push(buildPrivateStaticFieldInitSpec(prop, privateNamesMap));
break;
case isStatic && isPublic && isField && setPublicClassFields:
if (!isNameOrLength(prop.node)) {
staticNodes.push(buildPublicFieldInitLoose(_core.types.cloneNode(ref), prop));
break;
}
case isStatic && isPublic && isField && !setPublicClassFields:
staticNodes.push(buildPublicFieldInitSpec(_core.types.cloneNode(ref), prop, file));
break;
case isInstance && isPrivate && isField && privateFieldsAsProperties:
instanceNodes.push(buildPrivateFieldInitLoose(_core.types.thisExpression(), prop, privateNamesMap));
break;
case isInstance && isPrivate && isField && !privateFieldsAsProperties:
instanceNodes.push(buildPrivateInstanceFieldInitSpec(_core.types.thisExpression(), prop, privateNamesMap, file));
break;
case isInstance && isPrivate && isMethod && privateFieldsAsProperties:
instanceNodes.unshift(buildPrivateMethodInitLoose(_core.types.thisExpression(), prop, privateNamesMap));
pureStaticNodes.push(buildPrivateMethodDeclaration(prop, privateNamesMap, privateFieldsAsProperties));
break;
case isInstance && isPrivate && isMethod && !privateFieldsAsProperties:
instanceNodes.unshift(buildPrivateInstanceMethodInitSpec(_core.types.thisExpression(), prop, privateNamesMap, file));
pureStaticNodes.push(buildPrivateMethodDeclaration(prop, privateNamesMap, privateFieldsAsProperties));
break;
case isStatic && isPrivate && isMethod && !privateFieldsAsProperties:
staticNodes.unshift(buildPrivateStaticFieldInitSpec(prop, privateNamesMap));
pureStaticNodes.push(buildPrivateMethodDeclaration(prop, privateNamesMap, privateFieldsAsProperties));
break;
case isStatic && isPrivate && isMethod && privateFieldsAsProperties:
staticNodes.unshift(buildPrivateStaticMethodInitLoose(_core.types.cloneNode(ref), prop, file, privateNamesMap));
pureStaticNodes.push(buildPrivateMethodDeclaration(prop, privateNamesMap, privateFieldsAsProperties));
break;
case isInstance && isPublic && isField && setPublicClassFields:
instanceNodes.push(buildPublicFieldInitLoose(_core.types.thisExpression(), prop));
break;
case isInstance && isPublic && isField && !setPublicClassFields:
lastInstanceNodeReturnsThis = true;
instanceNodes.push(buildPublicFieldInitSpec(_core.types.thisExpression(), prop, file));
break;
default:
throw new Error("Unreachable.");
}
}
if (classRefFlags & 2 && innerBindingRef != null) {
classBindingNode = _core.types.expressionStatement(_core.types.assignmentExpression("=", _core.types.cloneNode(classRefForInnerBinding), _core.types.cloneNode(innerBindingRef)));
}
return {
staticNodes: staticNodes.filter(Boolean),
instanceNodes: instanceNodes.filter(Boolean),
lastInstanceNodeReturnsThis,
pureStaticNodes: pureStaticNodes.filter(Boolean),
classBindingNode,
wrapClass(path) {
for (const prop of props) {
prop.node.leadingComments = null;
prop.remove();
}
if (injectSuperRef) {
path.scope.push({
id: _core.types.cloneNode(injectSuperRef)
});
path.set("superClass", _core.types.assignmentExpression("=", injectSuperRef, path.node.superClass));
}
if (classRefFlags !== 0) {
if (path.isClassExpression()) {
path.scope.push({
id: ref
});
path.replaceWith(_core.types.assignmentExpression("=", _core.types.cloneNode(ref), path.node));
} else {
if (innerBindingRef == null) {
path.node.id = ref;
}
if (classBindingNode != null) {
path.scope.push({
id: classRefForInnerBinding
});
}
}
}
return path;
}
};
}
//# sourceMappingURL=fields.js.map

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,242 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "FEATURES", {
enumerable: true,
get: function () {
return _features.FEATURES;
}
});
Object.defineProperty(exports, "buildCheckInRHS", {
enumerable: true,
get: function () {
return _fields.buildCheckInRHS;
}
});
exports.createClassFeaturePlugin = createClassFeaturePlugin;
Object.defineProperty(exports, "enableFeature", {
enumerable: true,
get: function () {
return _features.enableFeature;
}
});
Object.defineProperty(exports, "injectInitialization", {
enumerable: true,
get: function () {
return _misc.injectInitialization;
}
});
var _core = require("@babel/core");
var _helperFunctionName = require("@babel/helper-function-name");
var _helperSplitExportDeclaration = require("@babel/helper-split-export-declaration");
var _decorators = require("./decorators.js");
var _semver = require("semver");
var _fields = require("./fields.js");
var _decorators2 = require("./decorators-2018-09.js");
var _misc = require("./misc.js");
var _features = require("./features.js");
var _typescript = require("./typescript.js");
const versionKey = "@babel/plugin-class-features/version";
function createClassFeaturePlugin({
name,
feature,
loose,
manipulateOptions,
api,
inherits,
decoratorVersion
}) {
if (feature & _features.FEATURES.decorators) {
{
if (decoratorVersion === "2021-12" || decoratorVersion === "2022-03" || decoratorVersion === "2023-01" || decoratorVersion === "2023-05") {
return (0, _decorators.default)(api, {
loose
}, decoratorVersion, inherits);
}
}
}
{
var _api;
(_api = api) != null ? _api : api = {
assumption: () => void 0
};
}
const setPublicClassFields = api.assumption("setPublicClassFields");
const privateFieldsAsSymbols = api.assumption("privateFieldsAsSymbols");
const privateFieldsAsProperties = api.assumption("privateFieldsAsProperties");
const constantSuper = api.assumption("constantSuper");
const noDocumentAll = api.assumption("noDocumentAll");
if (privateFieldsAsProperties && privateFieldsAsSymbols) {
throw new Error(`Cannot enable both the "privateFieldsAsProperties" and ` + `"privateFieldsAsSymbols" assumptions as the same time.`);
}
const privateFieldsAsSymbolsOrProperties = privateFieldsAsProperties || privateFieldsAsSymbols;
if (loose === true) {
const explicit = [];
if (setPublicClassFields !== undefined) {
explicit.push(`"setPublicClassFields"`);
}
if (privateFieldsAsProperties !== undefined) {
explicit.push(`"privateFieldsAsProperties"`);
}
if (privateFieldsAsSymbols !== undefined) {
explicit.push(`"privateFieldsAsSymbols"`);
}
if (explicit.length !== 0) {
console.warn(`[${name}]: You are using the "loose: true" option and you are` + ` explicitly setting a value for the ${explicit.join(" and ")}` + ` assumption${explicit.length > 1 ? "s" : ""}. The "loose" option` + ` can cause incompatibilities with the other class features` + ` plugins, so it's recommended that you replace it with the` + ` following top-level option:\n` + `\t"assumptions": {\n` + `\t\t"setPublicClassFields": true,\n` + `\t\t"privateFieldsAsSymbols": true\n` + `\t}`);
}
}
return {
name,
manipulateOptions,
inherits,
pre(file) {
(0, _features.enableFeature)(file, feature, loose);
{
if (typeof file.get(versionKey) === "number") {
file.set(versionKey, "7.23.10");
return;
}
}
if (!file.get(versionKey) || _semver.lt(file.get(versionKey), "7.23.10")) {
file.set(versionKey, "7.23.10");
}
},
visitor: {
Class(path, {
file
}) {
var _ref;
if (file.get(versionKey) !== "7.23.10") return;
if (!(0, _features.shouldTransform)(path, file)) return;
const pathIsClassDeclaration = path.isClassDeclaration();
if (pathIsClassDeclaration) (0, _typescript.assertFieldTransformed)(path);
const loose = (0, _features.isLoose)(file, feature);
let constructor;
const isDecorated = (0, _decorators2.hasDecorators)(path.node);
const props = [];
const elements = [];
const computedPaths = [];
const privateNames = new Set();
const body = path.get("body");
for (const path of body.get("body")) {
if ((path.isClassProperty() || path.isClassMethod()) && path.node.computed) {
computedPaths.push(path);
}
if (path.isPrivate()) {
const {
name
} = path.node.key.id;
const getName = `get ${name}`;
const setName = `set ${name}`;
if (path.isClassPrivateMethod()) {
if (path.node.kind === "get") {
if (privateNames.has(getName) || privateNames.has(name) && !privateNames.has(setName)) {
throw path.buildCodeFrameError("Duplicate private field");
}
privateNames.add(getName).add(name);
} else if (path.node.kind === "set") {
if (privateNames.has(setName) || privateNames.has(name) && !privateNames.has(getName)) {
throw path.buildCodeFrameError("Duplicate private field");
}
privateNames.add(setName).add(name);
}
} else {
if (privateNames.has(name) && !privateNames.has(getName) && !privateNames.has(setName) || privateNames.has(name) && (privateNames.has(getName) || privateNames.has(setName))) {
throw path.buildCodeFrameError("Duplicate private field");
}
privateNames.add(name);
}
}
if (path.isClassMethod({
kind: "constructor"
})) {
constructor = path;
} else {
elements.push(path);
if (path.isProperty() || path.isPrivate() || path.isStaticBlock != null && path.isStaticBlock()) {
props.push(path);
}
}
}
{
if (!props.length && !isDecorated) return;
}
const innerBinding = path.node.id;
let ref;
if (!innerBinding || !pathIsClassDeclaration) {
(0, _helperFunctionName.default)(path);
ref = path.scope.generateUidIdentifier((innerBinding == null ? void 0 : innerBinding.name) || "Class");
}
const classRefForDefine = (_ref = ref) != null ? _ref : _core.types.cloneNode(innerBinding);
const privateNamesMap = (0, _fields.buildPrivateNamesMap)(props);
const privateNamesNodes = (0, _fields.buildPrivateNamesNodes)(privateNamesMap, privateFieldsAsProperties != null ? privateFieldsAsProperties : loose, privateFieldsAsSymbols != null ? privateFieldsAsSymbols : false, file);
(0, _fields.transformPrivateNamesUsage)(classRefForDefine, path, privateNamesMap, {
privateFieldsAsProperties: privateFieldsAsSymbolsOrProperties != null ? privateFieldsAsSymbolsOrProperties : loose,
noDocumentAll,
innerBinding
}, file);
let keysNodes, staticNodes, instanceNodes, lastInstanceNodeReturnsThis, pureStaticNodes, classBindingNode, wrapClass;
{
if (isDecorated) {
staticNodes = pureStaticNodes = keysNodes = [];
({
instanceNodes,
wrapClass
} = (0, _decorators2.buildDecoratedClass)(classRefForDefine, path, elements, file));
} else {
keysNodes = (0, _misc.extractComputedKeys)(path, computedPaths, file);
({
staticNodes,
pureStaticNodes,
instanceNodes,
lastInstanceNodeReturnsThis,
classBindingNode,
wrapClass
} = (0, _fields.buildFieldsInitNodes)(ref, path.node.superClass, props, privateNamesMap, file, setPublicClassFields != null ? setPublicClassFields : loose, privateFieldsAsSymbolsOrProperties != null ? privateFieldsAsSymbolsOrProperties : loose, constantSuper != null ? constantSuper : loose, innerBinding));
}
}
if (instanceNodes.length > 0) {
(0, _misc.injectInitialization)(path, constructor, instanceNodes, (referenceVisitor, state) => {
{
if (isDecorated) return;
}
for (const prop of props) {
if (_core.types.isStaticBlock != null && _core.types.isStaticBlock(prop.node) || prop.node.static) continue;
prop.traverse(referenceVisitor, state);
}
}, lastInstanceNodeReturnsThis);
}
const wrappedPath = wrapClass(path);
wrappedPath.insertBefore([...privateNamesNodes, ...keysNodes]);
if (staticNodes.length > 0) {
wrappedPath.insertAfter(staticNodes);
}
if (pureStaticNodes.length > 0) {
wrappedPath.find(parent => parent.isStatement() || parent.isDeclaration()).insertAfter(pureStaticNodes);
}
if (classBindingNode != null && pathIsClassDeclaration) {
wrappedPath.insertAfter(classBindingNode);
}
},
ExportDefaultDeclaration(path, {
file
}) {
{
if (file.get(versionKey) !== "7.23.10") return;
const decl = path.get("declaration");
if (decl.isClassDeclaration() && (0, _decorators2.hasDecorators)(decl.node)) {
if (decl.node.id) {
(0, _helperSplitExportDeclaration.default)(path);
} else {
decl.node.type = "ClassExpression";
}
}
}
}
}
};
}
//# sourceMappingURL=index.js.map

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,124 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.extractComputedKeys = extractComputedKeys;
exports.injectInitialization = injectInitialization;
var _core = require("@babel/core");
var _helperEnvironmentVisitor = require("@babel/helper-environment-visitor");
const findBareSupers = _core.traverse.visitors.merge([{
Super(path) {
const {
node,
parentPath
} = path;
if (parentPath.isCallExpression({
callee: node
})) {
this.push(parentPath);
}
}
}, _helperEnvironmentVisitor.default]);
const referenceVisitor = {
"TSTypeAnnotation|TypeAnnotation"(path) {
path.skip();
},
ReferencedIdentifier(path, {
scope
}) {
if (scope.hasOwnBinding(path.node.name)) {
scope.rename(path.node.name);
path.skip();
}
}
};
function handleClassTDZ(path, state) {
if (state.classBinding && state.classBinding === path.scope.getBinding(path.node.name)) {
const classNameTDZError = state.file.addHelper("classNameTDZError");
const throwNode = _core.types.callExpression(classNameTDZError, [_core.types.stringLiteral(path.node.name)]);
path.replaceWith(_core.types.sequenceExpression([throwNode, path.node]));
path.skip();
}
}
const classFieldDefinitionEvaluationTDZVisitor = {
ReferencedIdentifier: handleClassTDZ
};
function injectInitialization(path, constructor, nodes, renamer, lastReturnsThis) {
if (!nodes.length) return;
const isDerived = !!path.node.superClass;
if (!constructor) {
const newConstructor = _core.types.classMethod("constructor", _core.types.identifier("constructor"), [], _core.types.blockStatement([]));
if (isDerived) {
newConstructor.params = [_core.types.restElement(_core.types.identifier("args"))];
newConstructor.body.body.push(_core.template.statement.ast`super(...args)`);
}
[constructor] = path.get("body").unshiftContainer("body", newConstructor);
}
if (renamer) {
renamer(referenceVisitor, {
scope: constructor.scope
});
}
if (isDerived) {
const bareSupers = [];
constructor.traverse(findBareSupers, bareSupers);
let isFirst = true;
for (const bareSuper of bareSupers) {
if (isFirst) {
isFirst = false;
} else {
nodes = nodes.map(n => _core.types.cloneNode(n));
}
if (!bareSuper.parentPath.isExpressionStatement()) {
const allNodes = [bareSuper.node, ...nodes.map(n => _core.types.toExpression(n))];
if (!lastReturnsThis) allNodes.push(_core.types.thisExpression());
bareSuper.replaceWith(_core.types.sequenceExpression(allNodes));
} else {
bareSuper.insertAfter(nodes);
}
}
} else {
constructor.get("body").unshiftContainer("body", nodes);
}
}
function extractComputedKeys(path, computedPaths, file) {
const declarations = [];
const state = {
classBinding: path.node.id && path.scope.getBinding(path.node.id.name),
file
};
for (const computedPath of computedPaths) {
const computedKey = computedPath.get("key");
if (computedKey.isReferencedIdentifier()) {
handleClassTDZ(computedKey, state);
} else {
computedKey.traverse(classFieldDefinitionEvaluationTDZVisitor, state);
}
const computedNode = computedPath.node;
if (!computedKey.isConstantExpression()) {
const scope = path.scope;
const isUidReference = _core.types.isIdentifier(computedKey.node) && scope.hasUid(computedKey.node.name);
const isMemoiseAssignment = computedKey.isAssignmentExpression({
operator: "="
}) && _core.types.isIdentifier(computedKey.node.left) && scope.hasUid(computedKey.node.left.name);
if (isUidReference) {
continue;
} else if (isMemoiseAssignment) {
declarations.push(_core.types.expressionStatement(_core.types.cloneNode(computedNode.key)));
computedNode.key = _core.types.cloneNode(computedNode.key.left);
} else {
const ident = path.scope.generateUidIdentifierBasedOnNode(computedNode.key);
scope.push({
id: ident,
kind: "let"
});
declarations.push(_core.types.expressionStatement(_core.types.assignmentExpression("=", _core.types.cloneNode(ident), computedNode.key)));
computedNode.key = _core.types.cloneNode(ident);
}
}
}
return declarations;
}
//# sourceMappingURL=misc.js.map

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,13 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.assertFieldTransformed = assertFieldTransformed;
function assertFieldTransformed(path) {
if (path.node.declare || false) {
throw path.buildCodeFrameError(`TypeScript 'declare' fields must first be transformed by ` + `@babel/plugin-transform-typescript.\n` + `If you have already enabled that plugin (or '@babel/preset-typescript'), make sure ` + `that it runs before any plugin related to additional class features:\n` + ` - @babel/plugin-transform-class-properties\n` + ` - @babel/plugin-transform-private-methods\n` + ` - @babel/plugin-proposal-decorators`);
}
}
//# sourceMappingURL=typescript.js.map

View file

@ -0,0 +1 @@
{"version":3,"names":["assertFieldTransformed","path","node","declare","buildCodeFrameError"],"sources":["../src/typescript.ts"],"sourcesContent":["import type { NodePath } from \"@babel/traverse\";\nimport type * as t from \"@babel/types\";\n\nexport function assertFieldTransformed(\n path: NodePath<t.ClassProperty | t.ClassDeclaration>,\n) {\n if (\n path.node.declare ||\n (process.env.BABEL_8_BREAKING\n ? path.isClassProperty({ definite: true })\n : false)\n ) {\n throw path.buildCodeFrameError(\n `TypeScript 'declare' fields must first be transformed by ` +\n `@babel/plugin-transform-typescript.\\n` +\n `If you have already enabled that plugin (or '@babel/preset-typescript'), make sure ` +\n `that it runs before any plugin related to additional class features:\\n` +\n ` - @babel/plugin-transform-class-properties\\n` +\n ` - @babel/plugin-transform-private-methods\\n` +\n ` - @babel/plugin-proposal-decorators`,\n );\n }\n}\n"],"mappings":";;;;;;AAGO,SAASA,sBAAsBA,CACpCC,IAAoD,EACpD;EACA,IACEA,IAAI,CAACC,IAAI,CAACC,OAAO,IAGb,KAAM,EACV;IACA,MAAMF,IAAI,CAACG,mBAAmB,CAC3B,2DAA0D,GACxD,uCAAsC,GACtC,qFAAoF,GACpF,wEAAuE,GACvE,+CAA8C,GAC9C,8CAA6C,GAC7C,sCACL,CAAC;EACH;AACF"}