decorators.js 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.buildNamedEvaluationVisitor = buildNamedEvaluationVisitor;
  6. exports.default = _default;
  7. exports.hasDecorators = hasDecorators;
  8. exports.hasOwnDecorators = hasOwnDecorators;
  9. var _core = require("@babel/core");
  10. var _helperReplaceSupers = require("@babel/helper-replace-supers");
  11. var _helperSkipTransparentExpressionWrappers = require("@babel/helper-skip-transparent-expression-wrappers");
  12. var _fields = require("./fields.js");
  13. var _misc = require("./misc.js");
  14. function hasOwnDecorators(node) {
  15. var _node$decorators;
  16. return !!((_node$decorators = node.decorators) != null && _node$decorators.length);
  17. }
  18. function hasDecorators(node) {
  19. return hasOwnDecorators(node) || node.body.body.some(hasOwnDecorators);
  20. }
  21. function incrementId(id, idx = id.length - 1) {
  22. if (idx === -1) {
  23. id.unshift(65);
  24. return;
  25. }
  26. const current = id[idx];
  27. if (current === 90) {
  28. id[idx] = 97;
  29. } else if (current === 122) {
  30. id[idx] = 65;
  31. incrementId(id, idx - 1);
  32. } else {
  33. id[idx] = current + 1;
  34. }
  35. }
  36. function createPrivateUidGeneratorForClass(classPath) {
  37. const currentPrivateId = [];
  38. const privateNames = new Set();
  39. _core.types.traverseFast(classPath.node, node => {
  40. if (_core.types.isPrivateName(node)) {
  41. privateNames.add(node.id.name);
  42. }
  43. });
  44. return () => {
  45. let reifiedId;
  46. do {
  47. incrementId(currentPrivateId);
  48. reifiedId = String.fromCharCode(...currentPrivateId);
  49. } while (privateNames.has(reifiedId));
  50. return _core.types.privateName(_core.types.identifier(reifiedId));
  51. };
  52. }
  53. function createLazyPrivateUidGeneratorForClass(classPath) {
  54. let generator;
  55. return () => {
  56. if (!generator) {
  57. generator = createPrivateUidGeneratorForClass(classPath);
  58. }
  59. return generator();
  60. };
  61. }
  62. function replaceClassWithVar(path, className) {
  63. const id = path.node.id;
  64. const scope = path.scope;
  65. if (path.type === "ClassDeclaration") {
  66. const className = id.name;
  67. const varId = scope.generateUidIdentifierBasedOnNode(id);
  68. const classId = _core.types.identifier(className);
  69. scope.rename(className, varId.name);
  70. path.get("id").replaceWith(classId);
  71. return {
  72. id: _core.types.cloneNode(varId),
  73. path
  74. };
  75. } else {
  76. let varId;
  77. if (id) {
  78. className = id.name;
  79. varId = generateLetUidIdentifier(scope.parent, className);
  80. scope.rename(className, varId.name);
  81. } else {
  82. varId = generateLetUidIdentifier(scope.parent, typeof className === "string" ? className : "decorated_class");
  83. }
  84. const newClassExpr = _core.types.classExpression(typeof className === "string" ? _core.types.identifier(className) : null, path.node.superClass, path.node.body);
  85. const [newPath] = path.replaceWith(_core.types.sequenceExpression([newClassExpr, varId]));
  86. return {
  87. id: _core.types.cloneNode(varId),
  88. path: newPath.get("expressions.0")
  89. };
  90. }
  91. }
  92. function generateClassProperty(key, value, isStatic) {
  93. if (key.type === "PrivateName") {
  94. return _core.types.classPrivateProperty(key, value, undefined, isStatic);
  95. } else {
  96. return _core.types.classProperty(key, value, undefined, undefined, isStatic);
  97. }
  98. }
  99. function assignIdForAnonymousClass(path, className) {
  100. if (!path.node.id) {
  101. path.node.id = typeof className === "string" ? _core.types.identifier(className) : path.scope.generateUidIdentifier("Class");
  102. }
  103. }
  104. function addProxyAccessorsFor(className, element, getterKey, setterKey, targetKey, isComputed, isStatic, version) {
  105. const thisArg = (version === "2023-11" || version === "2023-05") && isStatic ? className : _core.types.thisExpression();
  106. const getterBody = _core.types.blockStatement([_core.types.returnStatement(_core.types.memberExpression(_core.types.cloneNode(thisArg), _core.types.cloneNode(targetKey)))]);
  107. 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")))]);
  108. let getter, setter;
  109. if (getterKey.type === "PrivateName") {
  110. getter = _core.types.classPrivateMethod("get", getterKey, [], getterBody, isStatic);
  111. setter = _core.types.classPrivateMethod("set", setterKey, [_core.types.identifier("v")], setterBody, isStatic);
  112. } else {
  113. getter = _core.types.classMethod("get", getterKey, [], getterBody, isComputed, isStatic);
  114. setter = _core.types.classMethod("set", setterKey, [_core.types.identifier("v")], setterBody, isComputed, isStatic);
  115. }
  116. element.insertAfter(setter);
  117. element.insertAfter(getter);
  118. }
  119. function extractProxyAccessorsFor(targetKey, version) {
  120. if (version !== "2023-11" && version !== "2023-05" && version !== "2023-01") {
  121. return [_core.template.expression.ast`
  122. function () {
  123. return this.${_core.types.cloneNode(targetKey)};
  124. }
  125. `, _core.template.expression.ast`
  126. function (value) {
  127. this.${_core.types.cloneNode(targetKey)} = value;
  128. }
  129. `];
  130. }
  131. return [_core.template.expression.ast`
  132. o => o.${_core.types.cloneNode(targetKey)}
  133. `, _core.template.expression.ast`
  134. (o, v) => o.${_core.types.cloneNode(targetKey)} = v
  135. `];
  136. }
  137. function getComputedKeyLastElement(path) {
  138. path = (0, _helperSkipTransparentExpressionWrappers.skipTransparentExprWrappers)(path);
  139. if (path.isSequenceExpression()) {
  140. const expressions = path.get("expressions");
  141. return getComputedKeyLastElement(expressions[expressions.length - 1]);
  142. }
  143. return path;
  144. }
  145. function getComputedKeyMemoiser(path) {
  146. const element = getComputedKeyLastElement(path);
  147. if (element.isConstantExpression()) {
  148. return _core.types.cloneNode(path.node);
  149. } else if (element.isIdentifier() && path.scope.hasUid(element.node.name)) {
  150. return _core.types.cloneNode(path.node);
  151. } else if (element.isAssignmentExpression() && element.get("left").isIdentifier()) {
  152. return _core.types.cloneNode(element.node.left);
  153. } else {
  154. throw new Error(`Internal Error: the computed key ${path.toString()} has not yet been memoised.`);
  155. }
  156. }
  157. function prependExpressionsToComputedKey(expressions, fieldPath) {
  158. const key = fieldPath.get("key");
  159. if (key.isSequenceExpression()) {
  160. expressions.push(...key.node.expressions);
  161. } else {
  162. expressions.push(key.node);
  163. }
  164. key.replaceWith(maybeSequenceExpression(expressions));
  165. }
  166. function appendExpressionsToComputedKey(expressions, fieldPath) {
  167. const key = fieldPath.get("key");
  168. const completion = getComputedKeyLastElement(key);
  169. if (completion.isConstantExpression()) {
  170. prependExpressionsToComputedKey(expressions, fieldPath);
  171. } else {
  172. const scopeParent = key.scope.parent;
  173. const maybeAssignment = (0, _misc.memoiseComputedKey)(completion.node, scopeParent, scopeParent.generateUid("computedKey"));
  174. if (!maybeAssignment) {
  175. prependExpressionsToComputedKey(expressions, fieldPath);
  176. } else {
  177. const expressionSequence = [...expressions, _core.types.cloneNode(maybeAssignment.left)];
  178. const completionParent = completion.parentPath;
  179. if (completionParent.isSequenceExpression()) {
  180. completionParent.pushContainer("expressions", expressionSequence);
  181. } else {
  182. completion.replaceWith(maybeSequenceExpression([_core.types.cloneNode(maybeAssignment), ...expressionSequence]));
  183. }
  184. }
  185. }
  186. }
  187. function prependExpressionsToFieldInitializer(expressions, fieldPath) {
  188. const initializer = fieldPath.get("value");
  189. if (initializer.node) {
  190. expressions.push(initializer.node);
  191. } else if (expressions.length > 0) {
  192. expressions[expressions.length - 1] = _core.types.unaryExpression("void", expressions[expressions.length - 1]);
  193. }
  194. initializer.replaceWith(maybeSequenceExpression(expressions));
  195. }
  196. function prependExpressionsToStaticBlock(expressions, blockPath) {
  197. blockPath.unshiftContainer("body", _core.types.expressionStatement(maybeSequenceExpression(expressions)));
  198. }
  199. function prependExpressionsToConstructor(expressions, constructorPath) {
  200. constructorPath.node.body.body.unshift(_core.types.expressionStatement(maybeSequenceExpression(expressions)));
  201. }
  202. function isProtoInitCallExpression(expression, protoInitCall) {
  203. return _core.types.isCallExpression(expression) && _core.types.isIdentifier(expression.callee, {
  204. name: protoInitCall.name
  205. });
  206. }
  207. function optimizeSuperCallAndExpressions(expressions, protoInitLocal) {
  208. if (protoInitLocal) {
  209. if (expressions.length >= 2 && isProtoInitCallExpression(expressions[1], protoInitLocal)) {
  210. const mergedSuperCall = _core.types.callExpression(_core.types.cloneNode(protoInitLocal), [expressions[0]]);
  211. expressions.splice(0, 2, mergedSuperCall);
  212. }
  213. if (expressions.length >= 2 && _core.types.isThisExpression(expressions[expressions.length - 1]) && isProtoInitCallExpression(expressions[expressions.length - 2], protoInitLocal)) {
  214. expressions.splice(expressions.length - 1, 1);
  215. }
  216. }
  217. return maybeSequenceExpression(expressions);
  218. }
  219. function insertExpressionsAfterSuperCallAndOptimize(expressions, constructorPath, protoInitLocal) {
  220. constructorPath.traverse({
  221. CallExpression: {
  222. exit(path) {
  223. if (!path.get("callee").isSuper()) return;
  224. const newNodes = [path.node, ...expressions.map(expr => _core.types.cloneNode(expr))];
  225. if (path.isCompletionRecord()) {
  226. newNodes.push(_core.types.thisExpression());
  227. }
  228. path.replaceWith(optimizeSuperCallAndExpressions(newNodes, protoInitLocal));
  229. path.skip();
  230. }
  231. },
  232. ClassMethod(path) {
  233. if (path.node.kind === "constructor") {
  234. path.skip();
  235. }
  236. }
  237. });
  238. }
  239. function createConstructorFromExpressions(expressions, isDerivedClass) {
  240. const body = [_core.types.expressionStatement(maybeSequenceExpression(expressions))];
  241. if (isDerivedClass) {
  242. body.unshift(_core.types.expressionStatement(_core.types.callExpression(_core.types.super(), [_core.types.spreadElement(_core.types.identifier("args"))])));
  243. }
  244. return _core.types.classMethod("constructor", _core.types.identifier("constructor"), isDerivedClass ? [_core.types.restElement(_core.types.identifier("args"))] : [], _core.types.blockStatement(body));
  245. }
  246. function createStaticBlockFromExpressions(expressions) {
  247. return _core.types.staticBlock([_core.types.expressionStatement(maybeSequenceExpression(expressions))]);
  248. }
  249. const FIELD = 0;
  250. const ACCESSOR = 1;
  251. const METHOD = 2;
  252. const GETTER = 3;
  253. const SETTER = 4;
  254. const STATIC_OLD_VERSION = 5;
  255. const STATIC = 8;
  256. const DECORATORS_HAVE_THIS = 16;
  257. function getElementKind(element) {
  258. switch (element.node.type) {
  259. case "ClassProperty":
  260. case "ClassPrivateProperty":
  261. return FIELD;
  262. case "ClassAccessorProperty":
  263. return ACCESSOR;
  264. case "ClassMethod":
  265. case "ClassPrivateMethod":
  266. if (element.node.kind === "get") {
  267. return GETTER;
  268. } else if (element.node.kind === "set") {
  269. return SETTER;
  270. } else {
  271. return METHOD;
  272. }
  273. }
  274. }
  275. function toSortedDecoratorInfo(info) {
  276. return [...info.filter(el => el.isStatic && el.kind >= ACCESSOR && el.kind <= SETTER), ...info.filter(el => !el.isStatic && el.kind >= ACCESSOR && el.kind <= SETTER), ...info.filter(el => el.isStatic && el.kind === FIELD), ...info.filter(el => !el.isStatic && el.kind === FIELD)];
  277. }
  278. function generateDecorationList(decorators, decoratorsThis, version) {
  279. const decsCount = decorators.length;
  280. const haveOneThis = decoratorsThis.some(Boolean);
  281. const decs = [];
  282. for (let i = 0; i < decsCount; i++) {
  283. if ((version === "2023-11" || version === "2023-05") && haveOneThis) {
  284. decs.push(decoratorsThis[i] || _core.types.unaryExpression("void", _core.types.numericLiteral(0)));
  285. }
  286. decs.push(decorators[i].expression);
  287. }
  288. return {
  289. haveThis: haveOneThis,
  290. decs
  291. };
  292. }
  293. function generateDecorationExprs(decorationInfo, version) {
  294. return _core.types.arrayExpression(decorationInfo.map(el => {
  295. let flag = el.kind;
  296. if (el.isStatic) {
  297. flag += version === "2023-11" || version === "2023-05" ? STATIC : STATIC_OLD_VERSION;
  298. }
  299. if (el.decoratorsHaveThis) flag += DECORATORS_HAVE_THIS;
  300. return _core.types.arrayExpression([el.decoratorsArray, _core.types.numericLiteral(flag), el.name, ...(el.privateMethods || [])]);
  301. }));
  302. }
  303. function extractElementLocalAssignments(decorationInfo) {
  304. const localIds = [];
  305. for (const el of decorationInfo) {
  306. const {
  307. locals
  308. } = el;
  309. if (Array.isArray(locals)) {
  310. localIds.push(...locals);
  311. } else if (locals !== undefined) {
  312. localIds.push(locals);
  313. }
  314. }
  315. return localIds;
  316. }
  317. function addCallAccessorsFor(version, element, key, getId, setId, isStatic) {
  318. element.insertAfter(_core.types.classPrivateMethod("get", _core.types.cloneNode(key), [], _core.types.blockStatement([_core.types.returnStatement(_core.types.callExpression(_core.types.cloneNode(getId), version === "2023-11" && isStatic ? [] : [_core.types.thisExpression()]))]), isStatic));
  319. 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), version === "2023-11" && isStatic ? [_core.types.identifier("v")] : [_core.types.thisExpression(), _core.types.identifier("v")]))]), isStatic));
  320. }
  321. function movePrivateAccessor(element, key, methodLocalVar, isStatic) {
  322. let params;
  323. let block;
  324. if (element.node.kind === "set") {
  325. params = [_core.types.identifier("v")];
  326. block = [_core.types.expressionStatement(_core.types.callExpression(methodLocalVar, [_core.types.thisExpression(), _core.types.identifier("v")]))];
  327. } else {
  328. params = [];
  329. block = [_core.types.returnStatement(_core.types.callExpression(methodLocalVar, [_core.types.thisExpression()]))];
  330. }
  331. element.replaceWith(_core.types.classPrivateMethod(element.node.kind, _core.types.cloneNode(key), params, _core.types.blockStatement(block), isStatic));
  332. }
  333. function isClassDecoratableElementPath(path) {
  334. const {
  335. type
  336. } = path;
  337. return type !== "TSDeclareMethod" && type !== "TSIndexSignature" && type !== "StaticBlock";
  338. }
  339. function staticBlockToIIFE(block) {
  340. return _core.types.callExpression(_core.types.arrowFunctionExpression([], _core.types.blockStatement(block.body)), []);
  341. }
  342. function staticBlockToFunctionClosure(block) {
  343. return _core.types.functionExpression(null, [], _core.types.blockStatement(block.body));
  344. }
  345. function fieldInitializerToClosure(value) {
  346. return _core.types.functionExpression(null, [], _core.types.blockStatement([_core.types.returnStatement(value)]));
  347. }
  348. function maybeSequenceExpression(exprs) {
  349. if (exprs.length === 0) return _core.types.unaryExpression("void", _core.types.numericLiteral(0));
  350. if (exprs.length === 1) return exprs[0];
  351. return _core.types.sequenceExpression(exprs);
  352. }
  353. function createFunctionExpressionFromPrivateMethod(node) {
  354. const {
  355. params,
  356. body,
  357. generator: isGenerator,
  358. async: isAsync
  359. } = node;
  360. return _core.types.functionExpression(undefined, params, body, isGenerator, isAsync);
  361. }
  362. function createSetFunctionNameCall(state, className) {
  363. return _core.types.callExpression(state.addHelper("setFunctionName"), [_core.types.thisExpression(), className]);
  364. }
  365. function createToPropertyKeyCall(state, propertyKey) {
  366. return _core.types.callExpression(state.addHelper("toPropertyKey"), [propertyKey]);
  367. }
  368. function createPrivateBrandCheckClosure(brandName) {
  369. return _core.types.arrowFunctionExpression([_core.types.identifier("_")], _core.types.binaryExpression("in", _core.types.cloneNode(brandName), _core.types.identifier("_")));
  370. }
  371. function usesPrivateField(expression) {
  372. try {
  373. _core.types.traverseFast(expression, node => {
  374. if (_core.types.isPrivateName(node)) {
  375. throw null;
  376. }
  377. });
  378. return false;
  379. } catch (_unused) {
  380. return true;
  381. }
  382. }
  383. function convertToComputedKey(path) {
  384. const {
  385. node
  386. } = path;
  387. node.computed = true;
  388. if (_core.types.isIdentifier(node.key)) {
  389. node.key = _core.types.stringLiteral(node.key.name);
  390. }
  391. }
  392. function hasInstancePrivateAccess(path, privateNames) {
  393. let containsInstancePrivateAccess = false;
  394. if (privateNames.length > 0) {
  395. const privateNameVisitor = (0, _fields.privateNameVisitorFactory)({
  396. PrivateName(path, state) {
  397. if (state.privateNamesMap.has(path.node.id.name)) {
  398. containsInstancePrivateAccess = true;
  399. path.stop();
  400. }
  401. }
  402. });
  403. const privateNamesMap = new Map();
  404. for (const name of privateNames) {
  405. privateNamesMap.set(name, null);
  406. }
  407. path.traverse(privateNameVisitor, {
  408. privateNamesMap: privateNamesMap
  409. });
  410. }
  411. return containsInstancePrivateAccess;
  412. }
  413. function checkPrivateMethodUpdateError(path, decoratedPrivateMethods) {
  414. const privateNameVisitor = (0, _fields.privateNameVisitorFactory)({
  415. PrivateName(path, state) {
  416. if (!state.privateNamesMap.has(path.node.id.name)) return;
  417. const parentPath = path.parentPath;
  418. const parentParentPath = parentPath.parentPath;
  419. 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) {
  420. throw path.buildCodeFrameError(`Decorated private methods are read-only, but "#${path.node.id.name}" is updated via this expression.`);
  421. }
  422. }
  423. });
  424. const privateNamesMap = new Map();
  425. for (const name of decoratedPrivateMethods) {
  426. privateNamesMap.set(name, null);
  427. }
  428. path.traverse(privateNameVisitor, {
  429. privateNamesMap: privateNamesMap
  430. });
  431. }
  432. function transformClass(path, state, constantSuper, ignoreFunctionLength, className, propertyVisitor, version) {
  433. var _path$node$id;
  434. const body = path.get("body.body");
  435. const classDecorators = path.node.decorators;
  436. let hasElementDecorators = false;
  437. let hasComputedKeysSideEffects = false;
  438. let elemDecsUseFnContext = false;
  439. const generateClassPrivateUid = createLazyPrivateUidGeneratorForClass(path);
  440. const classAssignments = [];
  441. const scopeParent = path.scope.parent;
  442. const memoiseExpression = (expression, hint, assignments) => {
  443. const localEvaluatedId = generateLetUidIdentifier(scopeParent, hint);
  444. assignments.push(_core.types.assignmentExpression("=", localEvaluatedId, expression));
  445. return _core.types.cloneNode(localEvaluatedId);
  446. };
  447. let protoInitLocal;
  448. let staticInitLocal;
  449. const classIdName = (_path$node$id = path.node.id) == null ? void 0 : _path$node$id.name;
  450. const setClassName = typeof className === "object" ? className : undefined;
  451. const usesFunctionContextOrYieldAwait = decorator => {
  452. try {
  453. _core.types.traverseFast(decorator, node => {
  454. if (_core.types.isThisExpression(node) || _core.types.isSuper(node) || _core.types.isYieldExpression(node) || _core.types.isAwaitExpression(node) || _core.types.isIdentifier(node, {
  455. name: "arguments"
  456. }) || classIdName && _core.types.isIdentifier(node, {
  457. name: classIdName
  458. }) || _core.types.isMetaProperty(node) && node.meta.name !== "import") {
  459. throw null;
  460. }
  461. });
  462. return false;
  463. } catch (_unused2) {
  464. return true;
  465. }
  466. };
  467. const instancePrivateNames = [];
  468. for (const element of body) {
  469. if (!isClassDecoratableElementPath(element)) {
  470. continue;
  471. }
  472. const elementNode = element.node;
  473. if (!elementNode.static && _core.types.isPrivateName(elementNode.key)) {
  474. instancePrivateNames.push(elementNode.key.id.name);
  475. }
  476. if (isDecorated(elementNode)) {
  477. switch (elementNode.type) {
  478. case "ClassProperty":
  479. propertyVisitor.ClassProperty(element, state);
  480. break;
  481. case "ClassPrivateProperty":
  482. propertyVisitor.ClassPrivateProperty(element, state);
  483. break;
  484. case "ClassAccessorProperty":
  485. propertyVisitor.ClassAccessorProperty(element, state);
  486. if (version === "2023-11") {
  487. break;
  488. }
  489. default:
  490. if (elementNode.static) {
  491. staticInitLocal != null ? staticInitLocal : staticInitLocal = generateLetUidIdentifier(scopeParent, "initStatic");
  492. } else {
  493. protoInitLocal != null ? protoInitLocal : protoInitLocal = generateLetUidIdentifier(scopeParent, "initProto");
  494. }
  495. break;
  496. }
  497. hasElementDecorators = true;
  498. elemDecsUseFnContext || (elemDecsUseFnContext = elementNode.decorators.some(usesFunctionContextOrYieldAwait));
  499. } else if (elementNode.type === "ClassAccessorProperty") {
  500. propertyVisitor.ClassAccessorProperty(element, state);
  501. const {
  502. key,
  503. value,
  504. static: isStatic,
  505. computed
  506. } = elementNode;
  507. const newId = generateClassPrivateUid();
  508. const newField = generateClassProperty(newId, value, isStatic);
  509. const keyPath = element.get("key");
  510. const [newPath] = element.replaceWith(newField);
  511. let getterKey, setterKey;
  512. if (computed && !keyPath.isConstantExpression()) {
  513. getterKey = (0, _misc.memoiseComputedKey)(createToPropertyKeyCall(state, key), scopeParent, scopeParent.generateUid("computedKey"));
  514. setterKey = _core.types.cloneNode(getterKey.left);
  515. } else {
  516. getterKey = _core.types.cloneNode(key);
  517. setterKey = _core.types.cloneNode(key);
  518. }
  519. assignIdForAnonymousClass(path, className);
  520. addProxyAccessorsFor(path.node.id, newPath, getterKey, setterKey, newId, computed, isStatic, version);
  521. }
  522. if ("computed" in element.node && element.node.computed) {
  523. hasComputedKeysSideEffects || (hasComputedKeysSideEffects = !scopeParent.isStatic(element.node.key));
  524. }
  525. }
  526. if (!classDecorators && !hasElementDecorators) {
  527. if (!path.node.id && typeof className === "string") {
  528. path.node.id = _core.types.identifier(className);
  529. }
  530. if (setClassName) {
  531. path.node.body.body.unshift(createStaticBlockFromExpressions([createSetFunctionNameCall(state, setClassName)]));
  532. }
  533. return;
  534. }
  535. const elementDecoratorInfo = [];
  536. let constructorPath;
  537. const decoratedPrivateMethods = new Set();
  538. let classInitLocal, classIdLocal;
  539. let decoratorReceiverId = null;
  540. function handleDecorators(decorators) {
  541. let hasSideEffects = false;
  542. let usesFnContext = false;
  543. const decoratorsThis = [];
  544. for (const decorator of decorators) {
  545. const {
  546. expression
  547. } = decorator;
  548. let object;
  549. if ((version === "2023-11" || version === "2023-05") && _core.types.isMemberExpression(expression)) {
  550. if (_core.types.isSuper(expression.object)) {
  551. object = _core.types.thisExpression();
  552. } else if (scopeParent.isStatic(expression.object)) {
  553. object = _core.types.cloneNode(expression.object);
  554. } else {
  555. decoratorReceiverId != null ? decoratorReceiverId : decoratorReceiverId = generateLetUidIdentifier(scopeParent, "obj");
  556. object = _core.types.assignmentExpression("=", _core.types.cloneNode(decoratorReceiverId), expression.object);
  557. expression.object = _core.types.cloneNode(decoratorReceiverId);
  558. }
  559. }
  560. decoratorsThis.push(object);
  561. hasSideEffects || (hasSideEffects = !scopeParent.isStatic(expression));
  562. usesFnContext || (usesFnContext = usesFunctionContextOrYieldAwait(decorator));
  563. }
  564. return {
  565. hasSideEffects,
  566. usesFnContext,
  567. decoratorsThis
  568. };
  569. }
  570. const willExtractSomeElemDecs = hasComputedKeysSideEffects || elemDecsUseFnContext || version !== "2023-11";
  571. let needsDeclarationForClassBinding = false;
  572. let classDecorationsFlag = 0;
  573. let classDecorations = [];
  574. let classDecorationsId;
  575. let computedKeyAssignments = [];
  576. if (classDecorators) {
  577. classInitLocal = generateLetUidIdentifier(scopeParent, "initClass");
  578. needsDeclarationForClassBinding = path.isClassDeclaration();
  579. ({
  580. id: classIdLocal,
  581. path
  582. } = replaceClassWithVar(path, className));
  583. path.node.decorators = null;
  584. const classDecsUsePrivateName = classDecorators.some(usesPrivateField);
  585. const {
  586. hasSideEffects,
  587. usesFnContext,
  588. decoratorsThis
  589. } = handleDecorators(classDecorators);
  590. const {
  591. haveThis,
  592. decs
  593. } = generateDecorationList(classDecorators, decoratorsThis, version);
  594. classDecorationsFlag = haveThis ? 1 : 0;
  595. classDecorations = decs;
  596. if (usesFnContext || hasSideEffects && willExtractSomeElemDecs || classDecsUsePrivateName) {
  597. classDecorationsId = memoiseExpression(_core.types.arrayExpression(classDecorations), "classDecs", classAssignments);
  598. }
  599. if (!hasElementDecorators) {
  600. for (const element of path.get("body.body")) {
  601. const {
  602. node
  603. } = element;
  604. const isComputed = "computed" in node && node.computed;
  605. if (isComputed) {
  606. if (element.isClassProperty({
  607. static: true
  608. })) {
  609. if (!element.get("key").isConstantExpression()) {
  610. const key = node.key;
  611. const maybeAssignment = (0, _misc.memoiseComputedKey)(key, scopeParent, scopeParent.generateUid("computedKey"));
  612. if (maybeAssignment != null) {
  613. node.key = _core.types.cloneNode(maybeAssignment.left);
  614. computedKeyAssignments.push(maybeAssignment);
  615. }
  616. }
  617. } else if (computedKeyAssignments.length > 0) {
  618. prependExpressionsToComputedKey(computedKeyAssignments, element);
  619. computedKeyAssignments = [];
  620. }
  621. }
  622. }
  623. }
  624. } else {
  625. assignIdForAnonymousClass(path, className);
  626. classIdLocal = _core.types.cloneNode(path.node.id);
  627. }
  628. let lastInstancePrivateName;
  629. let needsInstancePrivateBrandCheck = false;
  630. let fieldInitializerExpressions = [];
  631. let staticFieldInitializerExpressions = [];
  632. if (hasElementDecorators) {
  633. if (protoInitLocal) {
  634. const protoInitCall = _core.types.callExpression(_core.types.cloneNode(protoInitLocal), [_core.types.thisExpression()]);
  635. fieldInitializerExpressions.push(protoInitCall);
  636. }
  637. for (const element of body) {
  638. if (!isClassDecoratableElementPath(element)) {
  639. if (staticFieldInitializerExpressions.length > 0 && element.isStaticBlock()) {
  640. prependExpressionsToStaticBlock(staticFieldInitializerExpressions, element);
  641. staticFieldInitializerExpressions = [];
  642. }
  643. continue;
  644. }
  645. const {
  646. node
  647. } = element;
  648. const decorators = node.decorators;
  649. const hasDecorators = !!(decorators != null && decorators.length);
  650. const isComputed = "computed" in node && node.computed;
  651. let name = "computedKey";
  652. if (node.key.type === "PrivateName") {
  653. name = node.key.id.name;
  654. } else if (!isComputed && node.key.type === "Identifier") {
  655. name = node.key.name;
  656. }
  657. let decoratorsArray;
  658. let decoratorsHaveThis;
  659. if (hasDecorators) {
  660. const {
  661. hasSideEffects,
  662. usesFnContext,
  663. decoratorsThis
  664. } = handleDecorators(decorators);
  665. const {
  666. decs,
  667. haveThis
  668. } = generateDecorationList(decorators, decoratorsThis, version);
  669. decoratorsHaveThis = haveThis;
  670. decoratorsArray = decs.length === 1 ? decs[0] : _core.types.arrayExpression(decs);
  671. if (usesFnContext || hasSideEffects && willExtractSomeElemDecs) {
  672. decoratorsArray = memoiseExpression(decoratorsArray, name + "Decs", computedKeyAssignments);
  673. }
  674. }
  675. if (isComputed) {
  676. if (!element.get("key").isConstantExpression()) {
  677. const key = node.key;
  678. const maybeAssignment = (0, _misc.memoiseComputedKey)(hasDecorators ? createToPropertyKeyCall(state, key) : key, scopeParent, scopeParent.generateUid("computedKey"));
  679. if (maybeAssignment != null) {
  680. if (classDecorators && element.isClassProperty({
  681. static: true
  682. })) {
  683. node.key = _core.types.cloneNode(maybeAssignment.left);
  684. computedKeyAssignments.push(maybeAssignment);
  685. } else {
  686. node.key = maybeAssignment;
  687. }
  688. }
  689. }
  690. }
  691. const {
  692. key,
  693. static: isStatic
  694. } = node;
  695. const isPrivate = key.type === "PrivateName";
  696. const kind = getElementKind(element);
  697. if (isPrivate && !isStatic) {
  698. if (hasDecorators) {
  699. needsInstancePrivateBrandCheck = true;
  700. }
  701. if (_core.types.isClassPrivateProperty(node) || !lastInstancePrivateName) {
  702. lastInstancePrivateName = key;
  703. }
  704. }
  705. if (element.isClassMethod({
  706. kind: "constructor"
  707. })) {
  708. constructorPath = element;
  709. }
  710. let locals;
  711. if (hasDecorators) {
  712. let privateMethods;
  713. let nameExpr;
  714. if (isComputed) {
  715. nameExpr = getComputedKeyMemoiser(element.get("key"));
  716. } else if (key.type === "PrivateName") {
  717. nameExpr = _core.types.stringLiteral(key.id.name);
  718. } else if (key.type === "Identifier") {
  719. nameExpr = _core.types.stringLiteral(key.name);
  720. } else {
  721. nameExpr = _core.types.cloneNode(key);
  722. }
  723. if (kind === ACCESSOR) {
  724. const {
  725. value
  726. } = element.node;
  727. const params = version === "2023-11" && isStatic ? [] : [_core.types.thisExpression()];
  728. if (value) {
  729. params.push(_core.types.cloneNode(value));
  730. }
  731. const newId = generateClassPrivateUid();
  732. const newFieldInitId = generateLetUidIdentifier(scopeParent, `init_${name}`);
  733. const newValue = _core.types.callExpression(_core.types.cloneNode(newFieldInitId), params);
  734. const newField = generateClassProperty(newId, newValue, isStatic);
  735. const [newPath] = element.replaceWith(newField);
  736. if (isPrivate) {
  737. privateMethods = extractProxyAccessorsFor(newId, version);
  738. const getId = generateLetUidIdentifier(scopeParent, `get_${name}`);
  739. const setId = generateLetUidIdentifier(scopeParent, `set_${name}`);
  740. addCallAccessorsFor(version, newPath, key, getId, setId, isStatic);
  741. locals = [newFieldInitId, getId, setId];
  742. } else {
  743. assignIdForAnonymousClass(path, className);
  744. addProxyAccessorsFor(path.node.id, newPath, _core.types.cloneNode(key), _core.types.isAssignmentExpression(key) ? _core.types.cloneNode(key.left) : _core.types.cloneNode(key), newId, isComputed, isStatic, version);
  745. locals = [newFieldInitId];
  746. }
  747. } else if (kind === FIELD) {
  748. const initId = generateLetUidIdentifier(scopeParent, `init_${name}`);
  749. const valuePath = element.get("value");
  750. const args = version === "2023-11" && isStatic ? [] : [_core.types.thisExpression()];
  751. if (valuePath.node) args.push(valuePath.node);
  752. valuePath.replaceWith(_core.types.callExpression(_core.types.cloneNode(initId), args));
  753. locals = [initId];
  754. if (isPrivate) {
  755. privateMethods = extractProxyAccessorsFor(key, version);
  756. }
  757. } else if (isPrivate) {
  758. const callId = generateLetUidIdentifier(scopeParent, `call_${name}`);
  759. locals = [callId];
  760. const replaceSupers = new _helperReplaceSupers.default({
  761. constantSuper,
  762. methodPath: element,
  763. objectRef: classIdLocal,
  764. superRef: path.node.superClass,
  765. file: state.file,
  766. refToPreserve: classIdLocal
  767. });
  768. replaceSupers.replace();
  769. privateMethods = [createFunctionExpressionFromPrivateMethod(element.node)];
  770. if (kind === GETTER || kind === SETTER) {
  771. movePrivateAccessor(element, _core.types.cloneNode(key), _core.types.cloneNode(callId), isStatic);
  772. } else {
  773. const node = element.node;
  774. path.node.body.body.unshift(_core.types.classPrivateProperty(key, _core.types.cloneNode(callId), [], node.static));
  775. decoratedPrivateMethods.add(key.id.name);
  776. element.remove();
  777. }
  778. }
  779. elementDecoratorInfo.push({
  780. kind,
  781. decoratorsArray,
  782. decoratorsHaveThis,
  783. name: nameExpr,
  784. isStatic,
  785. privateMethods,
  786. locals
  787. });
  788. if (element.node) {
  789. element.node.decorators = null;
  790. }
  791. }
  792. if (isComputed && computedKeyAssignments.length > 0) {
  793. if (classDecorators && element.isClassProperty({
  794. static: true
  795. })) {} else {
  796. prependExpressionsToComputedKey(computedKeyAssignments, kind === ACCESSOR ? element.getNextSibling() : element);
  797. computedKeyAssignments = [];
  798. }
  799. }
  800. if (fieldInitializerExpressions.length > 0 && !isStatic && (kind === FIELD || kind === ACCESSOR)) {
  801. prependExpressionsToFieldInitializer(fieldInitializerExpressions, element);
  802. fieldInitializerExpressions = [];
  803. }
  804. if (staticFieldInitializerExpressions.length > 0 && isStatic && (kind === FIELD || kind === ACCESSOR)) {
  805. prependExpressionsToFieldInitializer(staticFieldInitializerExpressions, element);
  806. staticFieldInitializerExpressions = [];
  807. }
  808. if (hasDecorators && version === "2023-11") {
  809. if (kind === FIELD || kind === ACCESSOR) {
  810. const initExtraId = generateLetUidIdentifier(scopeParent, `init_extra_${name}`);
  811. locals.push(initExtraId);
  812. const initExtraCall = _core.types.callExpression(_core.types.cloneNode(initExtraId), isStatic ? [] : [_core.types.thisExpression()]);
  813. if (!isStatic) {
  814. fieldInitializerExpressions.push(initExtraCall);
  815. } else {
  816. staticFieldInitializerExpressions.push(initExtraCall);
  817. }
  818. }
  819. }
  820. }
  821. }
  822. if (computedKeyAssignments.length > 0) {
  823. const elements = path.get("body.body");
  824. let lastComputedElement;
  825. for (let i = elements.length - 1; i >= 0; i--) {
  826. const path = elements[i];
  827. const node = path.node;
  828. if (node.computed) {
  829. if (classDecorators && _core.types.isClassProperty(node, {
  830. static: true
  831. })) {
  832. continue;
  833. }
  834. lastComputedElement = path;
  835. break;
  836. }
  837. }
  838. if (lastComputedElement != null) {
  839. appendExpressionsToComputedKey(computedKeyAssignments, lastComputedElement);
  840. computedKeyAssignments = [];
  841. } else {}
  842. }
  843. if (fieldInitializerExpressions.length > 0) {
  844. const isDerivedClass = !!path.node.superClass;
  845. if (constructorPath) {
  846. if (isDerivedClass) {
  847. insertExpressionsAfterSuperCallAndOptimize(fieldInitializerExpressions, constructorPath, protoInitLocal);
  848. } else {
  849. prependExpressionsToConstructor(fieldInitializerExpressions, constructorPath);
  850. }
  851. } else {
  852. path.node.body.body.unshift(createConstructorFromExpressions(fieldInitializerExpressions, isDerivedClass));
  853. }
  854. fieldInitializerExpressions = [];
  855. }
  856. if (staticFieldInitializerExpressions.length > 0) {
  857. path.node.body.body.push(createStaticBlockFromExpressions(staticFieldInitializerExpressions));
  858. staticFieldInitializerExpressions = [];
  859. }
  860. const sortedElementDecoratorInfo = toSortedDecoratorInfo(elementDecoratorInfo);
  861. const elementDecorations = generateDecorationExprs(version === "2023-11" ? elementDecoratorInfo : sortedElementDecoratorInfo, version);
  862. const elementLocals = extractElementLocalAssignments(sortedElementDecoratorInfo);
  863. if (protoInitLocal) {
  864. elementLocals.push(protoInitLocal);
  865. }
  866. if (staticInitLocal) {
  867. elementLocals.push(staticInitLocal);
  868. }
  869. const classLocals = [];
  870. let classInitInjected = false;
  871. const classInitCall = classInitLocal && _core.types.callExpression(_core.types.cloneNode(classInitLocal), []);
  872. let originalClassPath = path;
  873. const originalClass = path.node;
  874. const staticClosures = [];
  875. if (classDecorators) {
  876. classLocals.push(classIdLocal, classInitLocal);
  877. const statics = [];
  878. path.get("body.body").forEach(element => {
  879. if (element.isStaticBlock()) {
  880. if (hasInstancePrivateAccess(element, instancePrivateNames)) {
  881. const staticBlockClosureId = memoiseExpression(staticBlockToFunctionClosure(element.node), "staticBlock", staticClosures);
  882. staticFieldInitializerExpressions.push(_core.types.callExpression(_core.types.memberExpression(staticBlockClosureId, _core.types.identifier("call")), [_core.types.thisExpression()]));
  883. } else {
  884. staticFieldInitializerExpressions.push(staticBlockToIIFE(element.node));
  885. }
  886. element.remove();
  887. return;
  888. }
  889. if ((element.isClassProperty() || element.isClassPrivateProperty()) && element.node.static) {
  890. const valuePath = element.get("value");
  891. if (hasInstancePrivateAccess(valuePath, instancePrivateNames)) {
  892. const fieldValueClosureId = memoiseExpression(fieldInitializerToClosure(valuePath.node), "fieldValue", staticClosures);
  893. valuePath.replaceWith(_core.types.callExpression(_core.types.memberExpression(fieldValueClosureId, _core.types.identifier("call")), [_core.types.thisExpression()]));
  894. }
  895. if (staticFieldInitializerExpressions.length > 0) {
  896. prependExpressionsToFieldInitializer(staticFieldInitializerExpressions, element);
  897. staticFieldInitializerExpressions = [];
  898. }
  899. element.node.static = false;
  900. statics.push(element.node);
  901. element.remove();
  902. } else if (element.isClassPrivateMethod({
  903. static: true
  904. })) {
  905. if (hasInstancePrivateAccess(element, instancePrivateNames)) {
  906. const replaceSupers = new _helperReplaceSupers.default({
  907. constantSuper,
  908. methodPath: element,
  909. objectRef: classIdLocal,
  910. superRef: path.node.superClass,
  911. file: state.file,
  912. refToPreserve: classIdLocal
  913. });
  914. replaceSupers.replace();
  915. const privateMethodDelegateId = memoiseExpression(createFunctionExpressionFromPrivateMethod(element.node), element.get("key.id").node.name, staticClosures);
  916. if (ignoreFunctionLength) {
  917. element.node.params = [_core.types.restElement(_core.types.identifier("arg"))];
  918. element.node.body = _core.types.blockStatement([_core.types.returnStatement(_core.types.callExpression(_core.types.memberExpression(privateMethodDelegateId, _core.types.identifier("apply")), [_core.types.thisExpression(), _core.types.identifier("arg")]))]);
  919. } else {
  920. element.node.params = element.node.params.map((p, i) => {
  921. if (_core.types.isRestElement(p)) {
  922. return _core.types.restElement(_core.types.identifier("arg"));
  923. } else {
  924. return _core.types.identifier("_" + i);
  925. }
  926. });
  927. element.node.body = _core.types.blockStatement([_core.types.returnStatement(_core.types.callExpression(_core.types.memberExpression(privateMethodDelegateId, _core.types.identifier("apply")), [_core.types.thisExpression(), _core.types.identifier("arguments")]))]);
  928. }
  929. }
  930. element.node.static = false;
  931. statics.push(element.node);
  932. element.remove();
  933. }
  934. });
  935. if (statics.length > 0 || staticFieldInitializerExpressions.length > 0) {
  936. const staticsClass = _core.template.expression.ast`
  937. class extends ${state.addHelper("identity")} {}
  938. `;
  939. staticsClass.body.body = [_core.types.classProperty(_core.types.toExpression(originalClass), undefined, undefined, undefined, true, true), ...statics];
  940. const constructorBody = [];
  941. const newExpr = _core.types.newExpression(staticsClass, []);
  942. if (staticFieldInitializerExpressions.length > 0) {
  943. constructorBody.push(...staticFieldInitializerExpressions);
  944. }
  945. if (classInitCall) {
  946. classInitInjected = true;
  947. constructorBody.push(classInitCall);
  948. }
  949. if (constructorBody.length > 0) {
  950. constructorBody.unshift(_core.types.callExpression(_core.types.super(), [_core.types.cloneNode(classIdLocal)]));
  951. staticsClass.body.body.push(createConstructorFromExpressions(constructorBody, false));
  952. } else {
  953. newExpr.arguments.push(_core.types.cloneNode(classIdLocal));
  954. }
  955. const [newPath] = path.replaceWith(newExpr);
  956. originalClassPath = newPath.get("callee").get("body").get("body.0.key");
  957. }
  958. }
  959. if (!classInitInjected && classInitCall) {
  960. path.node.body.body.push(_core.types.staticBlock([_core.types.expressionStatement(classInitCall)]));
  961. }
  962. let {
  963. superClass
  964. } = originalClass;
  965. if (superClass && (version === "2023-11" || version === "2023-05")) {
  966. const id = path.scope.maybeGenerateMemoised(superClass);
  967. if (id) {
  968. originalClass.superClass = _core.types.assignmentExpression("=", id, superClass);
  969. superClass = id;
  970. }
  971. }
  972. const applyDecoratorWrapper = _core.types.staticBlock([]);
  973. originalClass.body.body.unshift(applyDecoratorWrapper);
  974. const applyDecsBody = applyDecoratorWrapper.body;
  975. if (computedKeyAssignments.length > 0) {
  976. const elements = originalClassPath.get("body.body");
  977. let firstPublicElement;
  978. for (const path of elements) {
  979. if ((path.isClassProperty() || path.isClassMethod()) && path.node.kind !== "constructor") {
  980. firstPublicElement = path;
  981. break;
  982. }
  983. }
  984. if (firstPublicElement != null) {
  985. convertToComputedKey(firstPublicElement);
  986. prependExpressionsToComputedKey(computedKeyAssignments, firstPublicElement);
  987. } else {
  988. originalClass.body.body.unshift(_core.types.classProperty(_core.types.sequenceExpression([...computedKeyAssignments, _core.types.stringLiteral("_")]), undefined, undefined, undefined, true, true));
  989. applyDecsBody.push(_core.types.expressionStatement(_core.types.unaryExpression("delete", _core.types.memberExpression(_core.types.thisExpression(), _core.types.identifier("_")))));
  990. }
  991. computedKeyAssignments = [];
  992. }
  993. applyDecsBody.push(_core.types.expressionStatement(createLocalsAssignment(elementLocals, classLocals, elementDecorations, classDecorationsId != null ? classDecorationsId : _core.types.arrayExpression(classDecorations), _core.types.numericLiteral(classDecorationsFlag), needsInstancePrivateBrandCheck ? lastInstancePrivateName : null, setClassName, _core.types.cloneNode(superClass), state, version)));
  994. if (staticInitLocal) {
  995. applyDecsBody.push(_core.types.expressionStatement(_core.types.callExpression(_core.types.cloneNode(staticInitLocal), [_core.types.thisExpression()])));
  996. }
  997. if (staticClosures.length > 0) {
  998. applyDecsBody.push(...staticClosures.map(expr => _core.types.expressionStatement(expr)));
  999. }
  1000. path.insertBefore(classAssignments.map(expr => _core.types.expressionStatement(expr)));
  1001. if (needsDeclarationForClassBinding) {
  1002. const classBindingInfo = scopeParent.getBinding(classIdLocal.name);
  1003. if (!classBindingInfo.constantViolations.length) {
  1004. path.insertBefore(_core.types.variableDeclaration("let", [_core.types.variableDeclarator(_core.types.cloneNode(classIdLocal))]));
  1005. } else {
  1006. const classOuterBindingDelegateLocal = scopeParent.generateUidIdentifier("t" + classIdLocal.name);
  1007. const classOuterBindingLocal = classIdLocal;
  1008. path.replaceWithMultiple([_core.types.variableDeclaration("let", [_core.types.variableDeclarator(_core.types.cloneNode(classOuterBindingLocal)), _core.types.variableDeclarator(classOuterBindingDelegateLocal)]), _core.types.blockStatement([_core.types.variableDeclaration("let", [_core.types.variableDeclarator(_core.types.cloneNode(classIdLocal))]), path.node, _core.types.expressionStatement(_core.types.assignmentExpression("=", _core.types.cloneNode(classOuterBindingDelegateLocal), _core.types.cloneNode(classIdLocal)))]), _core.types.expressionStatement(_core.types.assignmentExpression("=", _core.types.cloneNode(classOuterBindingLocal), _core.types.cloneNode(classOuterBindingDelegateLocal)))]);
  1009. }
  1010. }
  1011. if (decoratedPrivateMethods.size > 0) {
  1012. checkPrivateMethodUpdateError(path, decoratedPrivateMethods);
  1013. }
  1014. path.scope.crawl();
  1015. return path;
  1016. }
  1017. function createLocalsAssignment(elementLocals, classLocals, elementDecorations, classDecorations, classDecorationsFlag, maybePrivateBrandName, setClassName, superClass, state, version) {
  1018. let lhs, rhs;
  1019. const args = [setClassName ? createSetFunctionNameCall(state, setClassName) : _core.types.thisExpression(), classDecorations, elementDecorations];
  1020. if (version !== "2023-11") {
  1021. args.splice(1, 2, elementDecorations, classDecorations);
  1022. }
  1023. if (version === "2021-12" || version === "2022-03" && !state.availableHelper("applyDecs2203R")) {
  1024. lhs = _core.types.arrayPattern([...elementLocals, ...classLocals]);
  1025. rhs = _core.types.callExpression(state.addHelper(version === "2021-12" ? "applyDecs" : "applyDecs2203"), args);
  1026. return _core.types.assignmentExpression("=", lhs, rhs);
  1027. } else if (version === "2022-03") {
  1028. rhs = _core.types.callExpression(state.addHelper("applyDecs2203R"), args);
  1029. } else if (version === "2023-01") {
  1030. if (maybePrivateBrandName) {
  1031. args.push(createPrivateBrandCheckClosure(maybePrivateBrandName));
  1032. }
  1033. rhs = _core.types.callExpression(state.addHelper("applyDecs2301"), args);
  1034. } else if (version === "2023-05") {
  1035. if (maybePrivateBrandName || superClass || classDecorationsFlag.value !== 0) {
  1036. args.push(classDecorationsFlag);
  1037. }
  1038. if (maybePrivateBrandName) {
  1039. args.push(createPrivateBrandCheckClosure(maybePrivateBrandName));
  1040. } else if (superClass) {
  1041. args.push(_core.types.unaryExpression("void", _core.types.numericLiteral(0)));
  1042. }
  1043. if (superClass) args.push(superClass);
  1044. rhs = _core.types.callExpression(state.addHelper("applyDecs2305"), args);
  1045. }
  1046. if (version === "2023-11") {
  1047. if (maybePrivateBrandName || superClass || classDecorationsFlag.value !== 0) {
  1048. args.push(classDecorationsFlag);
  1049. }
  1050. if (maybePrivateBrandName) {
  1051. args.push(createPrivateBrandCheckClosure(maybePrivateBrandName));
  1052. } else if (superClass) {
  1053. args.push(_core.types.unaryExpression("void", _core.types.numericLiteral(0)));
  1054. }
  1055. if (superClass) args.push(superClass);
  1056. rhs = _core.types.callExpression(state.addHelper("applyDecs2311"), args);
  1057. }
  1058. if (elementLocals.length > 0) {
  1059. if (classLocals.length > 0) {
  1060. 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))]);
  1061. } else {
  1062. lhs = _core.types.arrayPattern(elementLocals);
  1063. rhs = _core.types.memberExpression(rhs, _core.types.identifier("e"), false, false);
  1064. }
  1065. } else {
  1066. lhs = _core.types.arrayPattern(classLocals);
  1067. rhs = _core.types.memberExpression(rhs, _core.types.identifier("c"), false, false);
  1068. }
  1069. return _core.types.assignmentExpression("=", lhs, rhs);
  1070. }
  1071. function isProtoKey(node) {
  1072. return node.type === "Identifier" ? node.name === "__proto__" : node.value === "__proto__";
  1073. }
  1074. function isDecorated(node) {
  1075. return node.decorators && node.decorators.length > 0;
  1076. }
  1077. function shouldTransformElement(node) {
  1078. switch (node.type) {
  1079. case "ClassAccessorProperty":
  1080. return true;
  1081. case "ClassMethod":
  1082. case "ClassProperty":
  1083. case "ClassPrivateMethod":
  1084. case "ClassPrivateProperty":
  1085. return isDecorated(node);
  1086. default:
  1087. return false;
  1088. }
  1089. }
  1090. function shouldTransformClass(node) {
  1091. return isDecorated(node) || node.body.body.some(shouldTransformElement);
  1092. }
  1093. function buildNamedEvaluationVisitor(needsName, visitor) {
  1094. function handleComputedProperty(propertyPath, key, state) {
  1095. switch (key.type) {
  1096. case "StringLiteral":
  1097. return _core.types.stringLiteral(key.value);
  1098. case "NumericLiteral":
  1099. case "BigIntLiteral":
  1100. {
  1101. const keyValue = key.value + "";
  1102. propertyPath.get("key").replaceWith(_core.types.stringLiteral(keyValue));
  1103. return _core.types.stringLiteral(keyValue);
  1104. }
  1105. default:
  1106. {
  1107. const ref = propertyPath.scope.maybeGenerateMemoised(key);
  1108. propertyPath.get("key").replaceWith(_core.types.assignmentExpression("=", ref, createToPropertyKeyCall(state, key)));
  1109. return _core.types.cloneNode(ref);
  1110. }
  1111. }
  1112. }
  1113. return {
  1114. VariableDeclarator(path, state) {
  1115. const id = path.node.id;
  1116. if (id.type === "Identifier") {
  1117. const initializer = (0, _helperSkipTransparentExpressionWrappers.skipTransparentExprWrappers)(path.get("init"));
  1118. if (needsName(initializer)) {
  1119. const name = id.name;
  1120. visitor(initializer, state, name);
  1121. }
  1122. }
  1123. },
  1124. AssignmentExpression(path, state) {
  1125. const id = path.node.left;
  1126. if (id.type === "Identifier") {
  1127. const initializer = (0, _helperSkipTransparentExpressionWrappers.skipTransparentExprWrappers)(path.get("right"));
  1128. if (needsName(initializer)) {
  1129. switch (path.node.operator) {
  1130. case "=":
  1131. case "&&=":
  1132. case "||=":
  1133. case "??=":
  1134. visitor(initializer, state, id.name);
  1135. }
  1136. }
  1137. }
  1138. },
  1139. AssignmentPattern(path, state) {
  1140. const id = path.node.left;
  1141. if (id.type === "Identifier") {
  1142. const initializer = (0, _helperSkipTransparentExpressionWrappers.skipTransparentExprWrappers)(path.get("right"));
  1143. if (needsName(initializer)) {
  1144. const name = id.name;
  1145. visitor(initializer, state, name);
  1146. }
  1147. }
  1148. },
  1149. ObjectExpression(path, state) {
  1150. for (const propertyPath of path.get("properties")) {
  1151. if (!propertyPath.isObjectProperty()) continue;
  1152. const {
  1153. node
  1154. } = propertyPath;
  1155. const id = node.key;
  1156. const initializer = (0, _helperSkipTransparentExpressionWrappers.skipTransparentExprWrappers)(propertyPath.get("value"));
  1157. if (needsName(initializer)) {
  1158. if (!node.computed) {
  1159. if (!isProtoKey(id)) {
  1160. if (id.type === "Identifier") {
  1161. visitor(initializer, state, id.name);
  1162. } else {
  1163. const className = _core.types.stringLiteral(id.value + "");
  1164. visitor(initializer, state, className);
  1165. }
  1166. }
  1167. } else {
  1168. const ref = handleComputedProperty(propertyPath, id, state);
  1169. visitor(initializer, state, ref);
  1170. }
  1171. }
  1172. }
  1173. },
  1174. ClassPrivateProperty(path, state) {
  1175. const {
  1176. node
  1177. } = path;
  1178. const initializer = (0, _helperSkipTransparentExpressionWrappers.skipTransparentExprWrappers)(path.get("value"));
  1179. if (needsName(initializer)) {
  1180. const className = _core.types.stringLiteral("#" + node.key.id.name);
  1181. visitor(initializer, state, className);
  1182. }
  1183. },
  1184. ClassAccessorProperty(path, state) {
  1185. const {
  1186. node
  1187. } = path;
  1188. const id = node.key;
  1189. const initializer = (0, _helperSkipTransparentExpressionWrappers.skipTransparentExprWrappers)(path.get("value"));
  1190. if (needsName(initializer)) {
  1191. if (!node.computed) {
  1192. if (id.type === "Identifier") {
  1193. visitor(initializer, state, id.name);
  1194. } else if (id.type === "PrivateName") {
  1195. const className = _core.types.stringLiteral("#" + id.id.name);
  1196. visitor(initializer, state, className);
  1197. } else {
  1198. const className = _core.types.stringLiteral(id.value + "");
  1199. visitor(initializer, state, className);
  1200. }
  1201. } else {
  1202. const ref = handleComputedProperty(path, id, state);
  1203. visitor(initializer, state, ref);
  1204. }
  1205. }
  1206. },
  1207. ClassProperty(path, state) {
  1208. const {
  1209. node
  1210. } = path;
  1211. const id = node.key;
  1212. const initializer = (0, _helperSkipTransparentExpressionWrappers.skipTransparentExprWrappers)(path.get("value"));
  1213. if (needsName(initializer)) {
  1214. if (!node.computed) {
  1215. if (id.type === "Identifier") {
  1216. visitor(initializer, state, id.name);
  1217. } else {
  1218. const className = _core.types.stringLiteral(id.value + "");
  1219. visitor(initializer, state, className);
  1220. }
  1221. } else {
  1222. const ref = handleComputedProperty(path, id, state);
  1223. visitor(initializer, state, ref);
  1224. }
  1225. }
  1226. }
  1227. };
  1228. }
  1229. function isDecoratedAnonymousClassExpression(path) {
  1230. return path.isClassExpression({
  1231. id: null
  1232. }) && shouldTransformClass(path.node);
  1233. }
  1234. function generateLetUidIdentifier(scope, name) {
  1235. const id = scope.generateUidIdentifier(name);
  1236. scope.push({
  1237. id,
  1238. kind: "let"
  1239. });
  1240. return _core.types.cloneNode(id);
  1241. }
  1242. function _default({
  1243. assertVersion,
  1244. assumption
  1245. }, {
  1246. loose
  1247. }, version, inherits) {
  1248. var _assumption, _assumption2;
  1249. if (version === "2023-11" || version === "2023-05" || version === "2023-01") {
  1250. assertVersion("^7.21.0");
  1251. } else if (version === "2021-12") {
  1252. assertVersion("^7.16.0");
  1253. } else {
  1254. assertVersion("^7.19.0");
  1255. }
  1256. const VISITED = new WeakSet();
  1257. const constantSuper = (_assumption = assumption("constantSuper")) != null ? _assumption : loose;
  1258. const ignoreFunctionLength = (_assumption2 = assumption("ignoreFunctionLength")) != null ? _assumption2 : loose;
  1259. const namedEvaluationVisitor = buildNamedEvaluationVisitor(isDecoratedAnonymousClassExpression, visitClass);
  1260. function visitClass(path, state, className) {
  1261. var _node$id;
  1262. if (VISITED.has(path)) return;
  1263. const {
  1264. node
  1265. } = path;
  1266. className != null ? className : className = (_node$id = node.id) == null ? void 0 : _node$id.name;
  1267. const newPath = transformClass(path, state, constantSuper, ignoreFunctionLength, className, namedEvaluationVisitor, version);
  1268. if (newPath) {
  1269. VISITED.add(newPath);
  1270. return;
  1271. }
  1272. VISITED.add(path);
  1273. }
  1274. return {
  1275. name: "proposal-decorators",
  1276. inherits: inherits,
  1277. visitor: Object.assign({
  1278. ExportDefaultDeclaration(path, state) {
  1279. const {
  1280. declaration
  1281. } = path.node;
  1282. if ((declaration == null ? void 0 : declaration.type) === "ClassDeclaration" && isDecorated(declaration)) {
  1283. var _path$splitExportDecl;
  1284. const isAnonymous = !declaration.id;
  1285. (_path$splitExportDecl = path.splitExportDeclaration) != null ? _path$splitExportDecl : path.splitExportDeclaration = require("@babel/traverse").NodePath.prototype.splitExportDeclaration;
  1286. const updatedVarDeclarationPath = path.splitExportDeclaration();
  1287. if (isAnonymous) {
  1288. visitClass(updatedVarDeclarationPath, state, _core.types.stringLiteral("default"));
  1289. }
  1290. }
  1291. },
  1292. ExportNamedDeclaration(path) {
  1293. const {
  1294. declaration
  1295. } = path.node;
  1296. if ((declaration == null ? void 0 : declaration.type) === "ClassDeclaration" && isDecorated(declaration)) {
  1297. var _path$splitExportDecl2;
  1298. (_path$splitExportDecl2 = path.splitExportDeclaration) != null ? _path$splitExportDecl2 : path.splitExportDeclaration = require("@babel/traverse").NodePath.prototype.splitExportDeclaration;
  1299. path.splitExportDeclaration();
  1300. }
  1301. },
  1302. Class(path, state) {
  1303. visitClass(path, state, undefined);
  1304. }
  1305. }, namedEvaluationVisitor)
  1306. };
  1307. }
  1308. //# sourceMappingURL=decorators.js.map