decorators.js 55 KB

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