decorators.js 55 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322
  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. classPath.traverse({
  40. PrivateName(path) {
  41. privateNames.add(path.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. {
  373. try {
  374. _core.types.traverseFast(expression, node => {
  375. if (_core.types.isPrivateName(node)) {
  376. throw null;
  377. }
  378. });
  379. return false;
  380. } catch (_unused) {
  381. return true;
  382. }
  383. }
  384. }
  385. function convertToComputedKey(path) {
  386. const {
  387. node
  388. } = path;
  389. node.computed = true;
  390. if (_core.types.isIdentifier(node.key)) {
  391. node.key = _core.types.stringLiteral(node.key.name);
  392. }
  393. }
  394. function hasInstancePrivateAccess(path, privateNames) {
  395. let containsInstancePrivateAccess = false;
  396. if (privateNames.length > 0) {
  397. const privateNameVisitor = (0, _fields.privateNameVisitorFactory)({
  398. PrivateName(path, state) {
  399. if (state.privateNamesMap.has(path.node.id.name)) {
  400. containsInstancePrivateAccess = true;
  401. path.stop();
  402. }
  403. }
  404. });
  405. const privateNamesMap = new Map();
  406. for (const name of privateNames) {
  407. privateNamesMap.set(name, null);
  408. }
  409. path.traverse(privateNameVisitor, {
  410. privateNamesMap: privateNamesMap
  411. });
  412. }
  413. return containsInstancePrivateAccess;
  414. }
  415. function checkPrivateMethodUpdateError(path, decoratedPrivateMethods) {
  416. const privateNameVisitor = (0, _fields.privateNameVisitorFactory)({
  417. PrivateName(path, state) {
  418. if (!state.privateNamesMap.has(path.node.id.name)) return;
  419. const parentPath = path.parentPath;
  420. const parentParentPath = parentPath.parentPath;
  421. 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) {
  422. throw path.buildCodeFrameError(`Decorated private methods are read-only, but "#${path.node.id.name}" is updated via this expression.`);
  423. }
  424. }
  425. });
  426. const privateNamesMap = new Map();
  427. for (const name of decoratedPrivateMethods) {
  428. privateNamesMap.set(name, null);
  429. }
  430. path.traverse(privateNameVisitor, {
  431. privateNamesMap: privateNamesMap
  432. });
  433. }
  434. function transformClass(path, state, constantSuper, ignoreFunctionLength, className, propertyVisitor, version) {
  435. var _path$node$id;
  436. const body = path.get("body.body");
  437. const classDecorators = path.node.decorators;
  438. let hasElementDecorators = false;
  439. let hasComputedKeysSideEffects = false;
  440. let elemDecsUseFnContext = false;
  441. const generateClassPrivateUid = createLazyPrivateUidGeneratorForClass(path);
  442. const classAssignments = [];
  443. const scopeParent = path.scope.parent;
  444. const memoiseExpression = (expression, hint, assignments) => {
  445. const localEvaluatedId = generateLetUidIdentifier(scopeParent, hint);
  446. assignments.push(_core.types.assignmentExpression("=", localEvaluatedId, expression));
  447. return _core.types.cloneNode(localEvaluatedId);
  448. };
  449. let protoInitLocal;
  450. let staticInitLocal;
  451. const classIdName = (_path$node$id = path.node.id) == null ? void 0 : _path$node$id.name;
  452. const setClassName = typeof className === "object" ? className : undefined;
  453. const usesFunctionContextOrYieldAwait = decorator => {
  454. {
  455. try {
  456. _core.types.traverseFast(decorator, node => {
  457. if (_core.types.isThisExpression(node) || _core.types.isSuper(node) || _core.types.isYieldExpression(node) || _core.types.isAwaitExpression(node) || _core.types.isIdentifier(node, {
  458. name: "arguments"
  459. }) || classIdName && _core.types.isIdentifier(node, {
  460. name: classIdName
  461. }) || _core.types.isMetaProperty(node) && node.meta.name !== "import") {
  462. throw null;
  463. }
  464. });
  465. return false;
  466. } catch (_unused2) {
  467. return true;
  468. }
  469. }
  470. };
  471. const instancePrivateNames = [];
  472. for (const element of body) {
  473. if (!isClassDecoratableElementPath(element)) {
  474. continue;
  475. }
  476. const elementNode = element.node;
  477. if (!elementNode.static && _core.types.isPrivateName(elementNode.key)) {
  478. instancePrivateNames.push(elementNode.key.id.name);
  479. }
  480. if (isDecorated(elementNode)) {
  481. switch (elementNode.type) {
  482. case "ClassProperty":
  483. propertyVisitor.ClassProperty(element, state);
  484. break;
  485. case "ClassPrivateProperty":
  486. propertyVisitor.ClassPrivateProperty(element, state);
  487. break;
  488. case "ClassAccessorProperty":
  489. propertyVisitor.ClassAccessorProperty(element, state);
  490. if (version === "2023-11") {
  491. break;
  492. }
  493. default:
  494. if (elementNode.static) {
  495. staticInitLocal != null ? staticInitLocal : staticInitLocal = generateLetUidIdentifier(scopeParent, "initStatic");
  496. } else {
  497. protoInitLocal != null ? protoInitLocal : protoInitLocal = generateLetUidIdentifier(scopeParent, "initProto");
  498. }
  499. break;
  500. }
  501. hasElementDecorators = true;
  502. elemDecsUseFnContext || (elemDecsUseFnContext = elementNode.decorators.some(usesFunctionContextOrYieldAwait));
  503. } else if (elementNode.type === "ClassAccessorProperty") {
  504. propertyVisitor.ClassAccessorProperty(element, state);
  505. const {
  506. key,
  507. value,
  508. static: isStatic,
  509. computed
  510. } = elementNode;
  511. const newId = generateClassPrivateUid();
  512. const newField = generateClassProperty(newId, value, isStatic);
  513. const keyPath = element.get("key");
  514. const [newPath] = element.replaceWith(newField);
  515. let getterKey, setterKey;
  516. if (computed && !keyPath.isConstantExpression()) {
  517. getterKey = (0, _misc.memoiseComputedKey)(createToPropertyKeyCall(state, key), scopeParent, scopeParent.generateUid("computedKey"));
  518. setterKey = _core.types.cloneNode(getterKey.left);
  519. } else {
  520. getterKey = _core.types.cloneNode(key);
  521. setterKey = _core.types.cloneNode(key);
  522. }
  523. assignIdForAnonymousClass(path, className);
  524. addProxyAccessorsFor(path.node.id, newPath, getterKey, setterKey, newId, computed, isStatic, version);
  525. }
  526. if ("computed" in element.node && element.node.computed) {
  527. hasComputedKeysSideEffects || (hasComputedKeysSideEffects = !scopeParent.isStatic(element.node.key));
  528. }
  529. }
  530. if (!classDecorators && !hasElementDecorators) {
  531. if (!path.node.id && typeof className === "string") {
  532. path.node.id = _core.types.identifier(className);
  533. }
  534. if (setClassName) {
  535. path.node.body.body.unshift(createStaticBlockFromExpressions([createSetFunctionNameCall(state, setClassName)]));
  536. }
  537. return;
  538. }
  539. const elementDecoratorInfo = [];
  540. let constructorPath;
  541. const decoratedPrivateMethods = new Set();
  542. let classInitLocal, classIdLocal;
  543. let decoratorReceiverId = null;
  544. function handleDecorators(decorators) {
  545. let hasSideEffects = false;
  546. let usesFnContext = false;
  547. const decoratorsThis = [];
  548. for (const decorator of decorators) {
  549. const {
  550. expression
  551. } = decorator;
  552. let object;
  553. if ((version === "2023-11" || version === "2023-05") && _core.types.isMemberExpression(expression)) {
  554. if (_core.types.isSuper(expression.object)) {
  555. object = _core.types.thisExpression();
  556. } else if (scopeParent.isStatic(expression.object)) {
  557. object = _core.types.cloneNode(expression.object);
  558. } else {
  559. decoratorReceiverId != null ? decoratorReceiverId : decoratorReceiverId = generateLetUidIdentifier(scopeParent, "obj");
  560. object = _core.types.assignmentExpression("=", _core.types.cloneNode(decoratorReceiverId), expression.object);
  561. expression.object = _core.types.cloneNode(decoratorReceiverId);
  562. }
  563. }
  564. decoratorsThis.push(object);
  565. hasSideEffects || (hasSideEffects = !scopeParent.isStatic(expression));
  566. usesFnContext || (usesFnContext = usesFunctionContextOrYieldAwait(decorator));
  567. }
  568. return {
  569. hasSideEffects,
  570. usesFnContext,
  571. decoratorsThis
  572. };
  573. }
  574. const willExtractSomeElemDecs = hasComputedKeysSideEffects || elemDecsUseFnContext || version !== "2023-11";
  575. let needsDeclarationForClassBinding = false;
  576. let classDecorationsFlag = 0;
  577. let classDecorations = [];
  578. let classDecorationsId;
  579. let computedKeyAssignments = [];
  580. if (classDecorators) {
  581. classInitLocal = generateLetUidIdentifier(scopeParent, "initClass");
  582. needsDeclarationForClassBinding = path.isClassDeclaration();
  583. ({
  584. id: classIdLocal,
  585. path
  586. } = replaceClassWithVar(path, className));
  587. path.node.decorators = null;
  588. const classDecsUsePrivateName = classDecorators.some(usesPrivateField);
  589. const {
  590. hasSideEffects,
  591. usesFnContext,
  592. decoratorsThis
  593. } = handleDecorators(classDecorators);
  594. const {
  595. haveThis,
  596. decs
  597. } = generateDecorationList(classDecorators, decoratorsThis, version);
  598. classDecorationsFlag = haveThis ? 1 : 0;
  599. classDecorations = decs;
  600. if (usesFnContext || hasSideEffects && willExtractSomeElemDecs || classDecsUsePrivateName) {
  601. classDecorationsId = memoiseExpression(_core.types.arrayExpression(classDecorations), "classDecs", classAssignments);
  602. }
  603. if (!hasElementDecorators) {
  604. for (const element of path.get("body.body")) {
  605. const {
  606. node
  607. } = element;
  608. const isComputed = "computed" in node && node.computed;
  609. if (isComputed) {
  610. if (element.isClassProperty({
  611. static: true
  612. })) {
  613. if (!element.get("key").isConstantExpression()) {
  614. const key = node.key;
  615. const maybeAssignment = (0, _misc.memoiseComputedKey)(key, scopeParent, scopeParent.generateUid("computedKey"));
  616. if (maybeAssignment != null) {
  617. node.key = _core.types.cloneNode(maybeAssignment.left);
  618. computedKeyAssignments.push(maybeAssignment);
  619. }
  620. }
  621. } else if (computedKeyAssignments.length > 0) {
  622. prependExpressionsToComputedKey(computedKeyAssignments, element);
  623. computedKeyAssignments = [];
  624. }
  625. }
  626. }
  627. }
  628. } else {
  629. assignIdForAnonymousClass(path, className);
  630. classIdLocal = _core.types.cloneNode(path.node.id);
  631. }
  632. let lastInstancePrivateName;
  633. let needsInstancePrivateBrandCheck = false;
  634. let fieldInitializerExpressions = [];
  635. let staticFieldInitializerExpressions = [];
  636. if (hasElementDecorators) {
  637. if (protoInitLocal) {
  638. const protoInitCall = _core.types.callExpression(_core.types.cloneNode(protoInitLocal), [_core.types.thisExpression()]);
  639. fieldInitializerExpressions.push(protoInitCall);
  640. }
  641. for (const element of body) {
  642. if (!isClassDecoratableElementPath(element)) {
  643. if (staticFieldInitializerExpressions.length > 0 && element.isStaticBlock()) {
  644. prependExpressionsToStaticBlock(staticFieldInitializerExpressions, element);
  645. staticFieldInitializerExpressions = [];
  646. }
  647. continue;
  648. }
  649. const {
  650. node
  651. } = element;
  652. const decorators = node.decorators;
  653. const hasDecorators = !!(decorators != null && decorators.length);
  654. const isComputed = "computed" in node && node.computed;
  655. let name = "computedKey";
  656. if (node.key.type === "PrivateName") {
  657. name = node.key.id.name;
  658. } else if (!isComputed && node.key.type === "Identifier") {
  659. name = node.key.name;
  660. }
  661. let decoratorsArray;
  662. let decoratorsHaveThis;
  663. if (hasDecorators) {
  664. const {
  665. hasSideEffects,
  666. usesFnContext,
  667. decoratorsThis
  668. } = handleDecorators(decorators);
  669. const {
  670. decs,
  671. haveThis
  672. } = generateDecorationList(decorators, decoratorsThis, version);
  673. decoratorsHaveThis = haveThis;
  674. decoratorsArray = decs.length === 1 ? decs[0] : _core.types.arrayExpression(decs);
  675. if (usesFnContext || hasSideEffects && willExtractSomeElemDecs) {
  676. decoratorsArray = memoiseExpression(decoratorsArray, name + "Decs", computedKeyAssignments);
  677. }
  678. }
  679. if (isComputed) {
  680. if (!element.get("key").isConstantExpression()) {
  681. const key = node.key;
  682. const maybeAssignment = (0, _misc.memoiseComputedKey)(hasDecorators ? createToPropertyKeyCall(state, key) : key, scopeParent, scopeParent.generateUid("computedKey"));
  683. if (maybeAssignment != null) {
  684. if (classDecorators && element.isClassProperty({
  685. static: true
  686. })) {
  687. node.key = _core.types.cloneNode(maybeAssignment.left);
  688. computedKeyAssignments.push(maybeAssignment);
  689. } else {
  690. node.key = maybeAssignment;
  691. }
  692. }
  693. }
  694. }
  695. const {
  696. key,
  697. static: isStatic
  698. } = node;
  699. const isPrivate = key.type === "PrivateName";
  700. const kind = getElementKind(element);
  701. if (isPrivate && !isStatic) {
  702. if (hasDecorators) {
  703. needsInstancePrivateBrandCheck = true;
  704. }
  705. if (_core.types.isClassPrivateProperty(node) || !lastInstancePrivateName) {
  706. lastInstancePrivateName = key;
  707. }
  708. }
  709. if (element.isClassMethod({
  710. kind: "constructor"
  711. })) {
  712. constructorPath = element;
  713. }
  714. let locals;
  715. if (hasDecorators) {
  716. let privateMethods;
  717. let nameExpr;
  718. if (isComputed) {
  719. nameExpr = getComputedKeyMemoiser(element.get("key"));
  720. } else if (key.type === "PrivateName") {
  721. nameExpr = _core.types.stringLiteral(key.id.name);
  722. } else if (key.type === "Identifier") {
  723. nameExpr = _core.types.stringLiteral(key.name);
  724. } else {
  725. nameExpr = _core.types.cloneNode(key);
  726. }
  727. if (kind === ACCESSOR) {
  728. const {
  729. value
  730. } = element.node;
  731. const params = version === "2023-11" && isStatic ? [] : [_core.types.thisExpression()];
  732. if (value) {
  733. params.push(_core.types.cloneNode(value));
  734. }
  735. const newId = generateClassPrivateUid();
  736. const newFieldInitId = generateLetUidIdentifier(scopeParent, `init_${name}`);
  737. const newValue = _core.types.callExpression(_core.types.cloneNode(newFieldInitId), params);
  738. const newField = generateClassProperty(newId, newValue, isStatic);
  739. const [newPath] = element.replaceWith(newField);
  740. if (isPrivate) {
  741. privateMethods = extractProxyAccessorsFor(newId, version);
  742. const getId = generateLetUidIdentifier(scopeParent, `get_${name}`);
  743. const setId = generateLetUidIdentifier(scopeParent, `set_${name}`);
  744. addCallAccessorsFor(version, newPath, key, getId, setId, isStatic);
  745. locals = [newFieldInitId, getId, setId];
  746. } else {
  747. assignIdForAnonymousClass(path, className);
  748. 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);
  749. locals = [newFieldInitId];
  750. }
  751. } else if (kind === FIELD) {
  752. const initId = generateLetUidIdentifier(scopeParent, `init_${name}`);
  753. const valuePath = element.get("value");
  754. const args = version === "2023-11" && isStatic ? [] : [_core.types.thisExpression()];
  755. if (valuePath.node) args.push(valuePath.node);
  756. valuePath.replaceWith(_core.types.callExpression(_core.types.cloneNode(initId), args));
  757. locals = [initId];
  758. if (isPrivate) {
  759. privateMethods = extractProxyAccessorsFor(key, version);
  760. }
  761. } else if (isPrivate) {
  762. const callId = generateLetUidIdentifier(scopeParent, `call_${name}`);
  763. locals = [callId];
  764. const replaceSupers = new _helperReplaceSupers.default({
  765. constantSuper,
  766. methodPath: element,
  767. objectRef: classIdLocal,
  768. superRef: path.node.superClass,
  769. file: state.file,
  770. refToPreserve: classIdLocal
  771. });
  772. replaceSupers.replace();
  773. privateMethods = [createFunctionExpressionFromPrivateMethod(element.node)];
  774. if (kind === GETTER || kind === SETTER) {
  775. movePrivateAccessor(element, _core.types.cloneNode(key), _core.types.cloneNode(callId), isStatic);
  776. } else {
  777. const node = element.node;
  778. path.node.body.body.unshift(_core.types.classPrivateProperty(key, _core.types.cloneNode(callId), [], node.static));
  779. decoratedPrivateMethods.add(key.id.name);
  780. element.remove();
  781. }
  782. }
  783. elementDecoratorInfo.push({
  784. kind,
  785. decoratorsArray,
  786. decoratorsHaveThis,
  787. name: nameExpr,
  788. isStatic,
  789. privateMethods,
  790. locals
  791. });
  792. if (element.node) {
  793. element.node.decorators = null;
  794. }
  795. }
  796. if (isComputed && computedKeyAssignments.length > 0) {
  797. if (classDecorators && element.isClassProperty({
  798. static: true
  799. })) {} else {
  800. prependExpressionsToComputedKey(computedKeyAssignments, kind === ACCESSOR ? element.getNextSibling() : element);
  801. computedKeyAssignments = [];
  802. }
  803. }
  804. if (fieldInitializerExpressions.length > 0 && !isStatic && (kind === FIELD || kind === ACCESSOR)) {
  805. prependExpressionsToFieldInitializer(fieldInitializerExpressions, element);
  806. fieldInitializerExpressions = [];
  807. }
  808. if (staticFieldInitializerExpressions.length > 0 && isStatic && (kind === FIELD || kind === ACCESSOR)) {
  809. prependExpressionsToFieldInitializer(staticFieldInitializerExpressions, element);
  810. staticFieldInitializerExpressions = [];
  811. }
  812. if (hasDecorators && version === "2023-11") {
  813. if (kind === FIELD || kind === ACCESSOR) {
  814. const initExtraId = generateLetUidIdentifier(scopeParent, `init_extra_${name}`);
  815. locals.push(initExtraId);
  816. const initExtraCall = _core.types.callExpression(_core.types.cloneNode(initExtraId), isStatic ? [] : [_core.types.thisExpression()]);
  817. if (!isStatic) {
  818. fieldInitializerExpressions.push(initExtraCall);
  819. } else {
  820. staticFieldInitializerExpressions.push(initExtraCall);
  821. }
  822. }
  823. }
  824. }
  825. }
  826. if (computedKeyAssignments.length > 0) {
  827. const elements = path.get("body.body");
  828. let lastComputedElement;
  829. for (let i = elements.length - 1; i >= 0; i--) {
  830. const path = elements[i];
  831. const node = path.node;
  832. if (node.computed) {
  833. if (classDecorators && _core.types.isClassProperty(node, {
  834. static: true
  835. })) {
  836. continue;
  837. }
  838. lastComputedElement = path;
  839. break;
  840. }
  841. }
  842. if (lastComputedElement != null) {
  843. appendExpressionsToComputedKey(computedKeyAssignments, lastComputedElement);
  844. computedKeyAssignments = [];
  845. } else {}
  846. }
  847. if (fieldInitializerExpressions.length > 0) {
  848. const isDerivedClass = !!path.node.superClass;
  849. if (constructorPath) {
  850. if (isDerivedClass) {
  851. insertExpressionsAfterSuperCallAndOptimize(fieldInitializerExpressions, constructorPath, protoInitLocal);
  852. } else {
  853. prependExpressionsToConstructor(fieldInitializerExpressions, constructorPath);
  854. }
  855. } else {
  856. path.node.body.body.unshift(createConstructorFromExpressions(fieldInitializerExpressions, isDerivedClass));
  857. }
  858. fieldInitializerExpressions = [];
  859. }
  860. if (staticFieldInitializerExpressions.length > 0) {
  861. path.node.body.body.push(createStaticBlockFromExpressions(staticFieldInitializerExpressions));
  862. staticFieldInitializerExpressions = [];
  863. }
  864. const sortedElementDecoratorInfo = toSortedDecoratorInfo(elementDecoratorInfo);
  865. const elementDecorations = generateDecorationExprs(version === "2023-11" ? elementDecoratorInfo : sortedElementDecoratorInfo, version);
  866. const elementLocals = extractElementLocalAssignments(sortedElementDecoratorInfo);
  867. if (protoInitLocal) {
  868. elementLocals.push(protoInitLocal);
  869. }
  870. if (staticInitLocal) {
  871. elementLocals.push(staticInitLocal);
  872. }
  873. const classLocals = [];
  874. let classInitInjected = false;
  875. const classInitCall = classInitLocal && _core.types.callExpression(_core.types.cloneNode(classInitLocal), []);
  876. let originalClassPath = path;
  877. const originalClass = path.node;
  878. const staticClosures = [];
  879. if (classDecorators) {
  880. classLocals.push(classIdLocal, classInitLocal);
  881. const statics = [];
  882. path.get("body.body").forEach(element => {
  883. if (element.isStaticBlock()) {
  884. if (hasInstancePrivateAccess(element, instancePrivateNames)) {
  885. const staticBlockClosureId = memoiseExpression(staticBlockToFunctionClosure(element.node), "staticBlock", staticClosures);
  886. staticFieldInitializerExpressions.push(_core.types.callExpression(_core.types.memberExpression(staticBlockClosureId, _core.types.identifier("call")), [_core.types.thisExpression()]));
  887. } else {
  888. staticFieldInitializerExpressions.push(staticBlockToIIFE(element.node));
  889. }
  890. element.remove();
  891. return;
  892. }
  893. if ((element.isClassProperty() || element.isClassPrivateProperty()) && element.node.static) {
  894. const valuePath = element.get("value");
  895. if (hasInstancePrivateAccess(valuePath, instancePrivateNames)) {
  896. const fieldValueClosureId = memoiseExpression(fieldInitializerToClosure(valuePath.node), "fieldValue", staticClosures);
  897. valuePath.replaceWith(_core.types.callExpression(_core.types.memberExpression(fieldValueClosureId, _core.types.identifier("call")), [_core.types.thisExpression()]));
  898. }
  899. if (staticFieldInitializerExpressions.length > 0) {
  900. prependExpressionsToFieldInitializer(staticFieldInitializerExpressions, element);
  901. staticFieldInitializerExpressions = [];
  902. }
  903. element.node.static = false;
  904. statics.push(element.node);
  905. element.remove();
  906. } else if (element.isClassPrivateMethod({
  907. static: true
  908. })) {
  909. if (hasInstancePrivateAccess(element, instancePrivateNames)) {
  910. const replaceSupers = new _helperReplaceSupers.default({
  911. constantSuper,
  912. methodPath: element,
  913. objectRef: classIdLocal,
  914. superRef: path.node.superClass,
  915. file: state.file,
  916. refToPreserve: classIdLocal
  917. });
  918. replaceSupers.replace();
  919. const privateMethodDelegateId = memoiseExpression(createFunctionExpressionFromPrivateMethod(element.node), element.get("key.id").node.name, staticClosures);
  920. if (ignoreFunctionLength) {
  921. element.node.params = [_core.types.restElement(_core.types.identifier("arg"))];
  922. 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")]))]);
  923. } else {
  924. element.node.params = element.node.params.map((p, i) => {
  925. if (_core.types.isRestElement(p)) {
  926. return _core.types.restElement(_core.types.identifier("arg"));
  927. } else {
  928. return _core.types.identifier("_" + i);
  929. }
  930. });
  931. 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")]))]);
  932. }
  933. }
  934. element.node.static = false;
  935. statics.push(element.node);
  936. element.remove();
  937. }
  938. });
  939. if (statics.length > 0 || staticFieldInitializerExpressions.length > 0) {
  940. const staticsClass = _core.template.expression.ast`
  941. class extends ${state.addHelper("identity")} {}
  942. `;
  943. staticsClass.body.body = [_core.types.classProperty(_core.types.toExpression(originalClass), undefined, undefined, undefined, true, true), ...statics];
  944. const constructorBody = [];
  945. const newExpr = _core.types.newExpression(staticsClass, []);
  946. if (staticFieldInitializerExpressions.length > 0) {
  947. constructorBody.push(...staticFieldInitializerExpressions);
  948. }
  949. if (classInitCall) {
  950. classInitInjected = true;
  951. constructorBody.push(classInitCall);
  952. }
  953. if (constructorBody.length > 0) {
  954. constructorBody.unshift(_core.types.callExpression(_core.types.super(), [_core.types.cloneNode(classIdLocal)]));
  955. staticsClass.body.body.push(createConstructorFromExpressions(constructorBody, false));
  956. } else {
  957. newExpr.arguments.push(_core.types.cloneNode(classIdLocal));
  958. }
  959. const [newPath] = path.replaceWith(newExpr);
  960. originalClassPath = newPath.get("callee").get("body").get("body.0.key");
  961. }
  962. }
  963. if (!classInitInjected && classInitCall) {
  964. path.node.body.body.push(_core.types.staticBlock([_core.types.expressionStatement(classInitCall)]));
  965. }
  966. let {
  967. superClass
  968. } = originalClass;
  969. if (superClass && (version === "2023-11" || version === "2023-05")) {
  970. const id = path.scope.maybeGenerateMemoised(superClass);
  971. if (id) {
  972. originalClass.superClass = _core.types.assignmentExpression("=", id, superClass);
  973. superClass = id;
  974. }
  975. }
  976. const applyDecoratorWrapper = _core.types.staticBlock([]);
  977. originalClass.body.body.unshift(applyDecoratorWrapper);
  978. const applyDecsBody = applyDecoratorWrapper.body;
  979. if (computedKeyAssignments.length > 0) {
  980. const elements = originalClassPath.get("body.body");
  981. let firstPublicElement;
  982. for (const path of elements) {
  983. if ((path.isClassProperty() || path.isClassMethod()) && path.node.kind !== "constructor") {
  984. firstPublicElement = path;
  985. break;
  986. }
  987. }
  988. if (firstPublicElement != null) {
  989. convertToComputedKey(firstPublicElement);
  990. prependExpressionsToComputedKey(computedKeyAssignments, firstPublicElement);
  991. } else {
  992. originalClass.body.body.unshift(_core.types.classProperty(_core.types.sequenceExpression([...computedKeyAssignments, _core.types.stringLiteral("_")]), undefined, undefined, undefined, true, true));
  993. applyDecsBody.push(_core.types.expressionStatement(_core.types.unaryExpression("delete", _core.types.memberExpression(_core.types.thisExpression(), _core.types.identifier("_")))));
  994. }
  995. computedKeyAssignments = [];
  996. }
  997. 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)));
  998. if (staticInitLocal) {
  999. applyDecsBody.push(_core.types.expressionStatement(_core.types.callExpression(_core.types.cloneNode(staticInitLocal), [_core.types.thisExpression()])));
  1000. }
  1001. if (staticClosures.length > 0) {
  1002. applyDecsBody.push(...staticClosures.map(expr => _core.types.expressionStatement(expr)));
  1003. }
  1004. path.insertBefore(classAssignments.map(expr => _core.types.expressionStatement(expr)));
  1005. if (needsDeclarationForClassBinding) {
  1006. const classBindingInfo = scopeParent.getBinding(classIdLocal.name);
  1007. if (!classBindingInfo.constantViolations.length) {
  1008. path.insertBefore(_core.types.variableDeclaration("let", [_core.types.variableDeclarator(_core.types.cloneNode(classIdLocal))]));
  1009. } else {
  1010. const classOuterBindingDelegateLocal = scopeParent.generateUidIdentifier("t" + classIdLocal.name);
  1011. const classOuterBindingLocal = classIdLocal;
  1012. 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)))]);
  1013. }
  1014. }
  1015. if (decoratedPrivateMethods.size > 0) {
  1016. checkPrivateMethodUpdateError(path, decoratedPrivateMethods);
  1017. }
  1018. path.scope.crawl();
  1019. return path;
  1020. }
  1021. function createLocalsAssignment(elementLocals, classLocals, elementDecorations, classDecorations, classDecorationsFlag, maybePrivateBrandName, setClassName, superClass, state, version) {
  1022. let lhs, rhs;
  1023. const args = [setClassName ? createSetFunctionNameCall(state, setClassName) : _core.types.thisExpression(), classDecorations, elementDecorations];
  1024. {
  1025. if (version !== "2023-11") {
  1026. args.splice(1, 2, elementDecorations, classDecorations);
  1027. }
  1028. if (version === "2021-12" || version === "2022-03" && !state.availableHelper("applyDecs2203R")) {
  1029. lhs = _core.types.arrayPattern([...elementLocals, ...classLocals]);
  1030. rhs = _core.types.callExpression(state.addHelper(version === "2021-12" ? "applyDecs" : "applyDecs2203"), args);
  1031. return _core.types.assignmentExpression("=", lhs, rhs);
  1032. } else if (version === "2022-03") {
  1033. rhs = _core.types.callExpression(state.addHelper("applyDecs2203R"), args);
  1034. } else if (version === "2023-01") {
  1035. if (maybePrivateBrandName) {
  1036. args.push(createPrivateBrandCheckClosure(maybePrivateBrandName));
  1037. }
  1038. rhs = _core.types.callExpression(state.addHelper("applyDecs2301"), args);
  1039. } else if (version === "2023-05") {
  1040. if (maybePrivateBrandName || superClass || classDecorationsFlag.value !== 0) {
  1041. args.push(classDecorationsFlag);
  1042. }
  1043. if (maybePrivateBrandName) {
  1044. args.push(createPrivateBrandCheckClosure(maybePrivateBrandName));
  1045. } else if (superClass) {
  1046. args.push(_core.types.unaryExpression("void", _core.types.numericLiteral(0)));
  1047. }
  1048. if (superClass) args.push(superClass);
  1049. rhs = _core.types.callExpression(state.addHelper("applyDecs2305"), args);
  1050. }
  1051. }
  1052. if (version === "2023-11") {
  1053. if (maybePrivateBrandName || superClass || classDecorationsFlag.value !== 0) {
  1054. args.push(classDecorationsFlag);
  1055. }
  1056. if (maybePrivateBrandName) {
  1057. args.push(createPrivateBrandCheckClosure(maybePrivateBrandName));
  1058. } else if (superClass) {
  1059. args.push(_core.types.unaryExpression("void", _core.types.numericLiteral(0)));
  1060. }
  1061. if (superClass) args.push(superClass);
  1062. rhs = _core.types.callExpression(state.addHelper("applyDecs2311"), args);
  1063. }
  1064. if (elementLocals.length > 0) {
  1065. if (classLocals.length > 0) {
  1066. 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))]);
  1067. } else {
  1068. lhs = _core.types.arrayPattern(elementLocals);
  1069. rhs = _core.types.memberExpression(rhs, _core.types.identifier("e"), false, false);
  1070. }
  1071. } else {
  1072. lhs = _core.types.arrayPattern(classLocals);
  1073. rhs = _core.types.memberExpression(rhs, _core.types.identifier("c"), false, false);
  1074. }
  1075. return _core.types.assignmentExpression("=", lhs, rhs);
  1076. }
  1077. function isProtoKey(node) {
  1078. return node.type === "Identifier" ? node.name === "__proto__" : node.value === "__proto__";
  1079. }
  1080. function isDecorated(node) {
  1081. return node.decorators && node.decorators.length > 0;
  1082. }
  1083. function shouldTransformElement(node) {
  1084. switch (node.type) {
  1085. case "ClassAccessorProperty":
  1086. return true;
  1087. case "ClassMethod":
  1088. case "ClassProperty":
  1089. case "ClassPrivateMethod":
  1090. case "ClassPrivateProperty":
  1091. return isDecorated(node);
  1092. default:
  1093. return false;
  1094. }
  1095. }
  1096. function shouldTransformClass(node) {
  1097. return isDecorated(node) || node.body.body.some(shouldTransformElement);
  1098. }
  1099. function buildNamedEvaluationVisitor(needsName, visitor) {
  1100. function handleComputedProperty(propertyPath, key, state) {
  1101. switch (key.type) {
  1102. case "StringLiteral":
  1103. return _core.types.stringLiteral(key.value);
  1104. case "NumericLiteral":
  1105. case "BigIntLiteral":
  1106. {
  1107. const keyValue = key.value + "";
  1108. propertyPath.get("key").replaceWith(_core.types.stringLiteral(keyValue));
  1109. return _core.types.stringLiteral(keyValue);
  1110. }
  1111. default:
  1112. {
  1113. const ref = propertyPath.scope.maybeGenerateMemoised(key);
  1114. propertyPath.get("key").replaceWith(_core.types.assignmentExpression("=", ref, createToPropertyKeyCall(state, key)));
  1115. return _core.types.cloneNode(ref);
  1116. }
  1117. }
  1118. }
  1119. return {
  1120. VariableDeclarator(path, state) {
  1121. const id = path.node.id;
  1122. if (id.type === "Identifier") {
  1123. const initializer = (0, _helperSkipTransparentExpressionWrappers.skipTransparentExprWrappers)(path.get("init"));
  1124. if (needsName(initializer)) {
  1125. const name = id.name;
  1126. visitor(initializer, state, name);
  1127. }
  1128. }
  1129. },
  1130. AssignmentExpression(path, state) {
  1131. const id = path.node.left;
  1132. if (id.type === "Identifier") {
  1133. const initializer = (0, _helperSkipTransparentExpressionWrappers.skipTransparentExprWrappers)(path.get("right"));
  1134. if (needsName(initializer)) {
  1135. switch (path.node.operator) {
  1136. case "=":
  1137. case "&&=":
  1138. case "||=":
  1139. case "??=":
  1140. visitor(initializer, state, id.name);
  1141. }
  1142. }
  1143. }
  1144. },
  1145. AssignmentPattern(path, state) {
  1146. const id = path.node.left;
  1147. if (id.type === "Identifier") {
  1148. const initializer = (0, _helperSkipTransparentExpressionWrappers.skipTransparentExprWrappers)(path.get("right"));
  1149. if (needsName(initializer)) {
  1150. const name = id.name;
  1151. visitor(initializer, state, name);
  1152. }
  1153. }
  1154. },
  1155. ObjectExpression(path, state) {
  1156. for (const propertyPath of path.get("properties")) {
  1157. if (!propertyPath.isObjectProperty()) continue;
  1158. const {
  1159. node
  1160. } = propertyPath;
  1161. const id = node.key;
  1162. const initializer = (0, _helperSkipTransparentExpressionWrappers.skipTransparentExprWrappers)(propertyPath.get("value"));
  1163. if (needsName(initializer)) {
  1164. if (!node.computed) {
  1165. if (!isProtoKey(id)) {
  1166. if (id.type === "Identifier") {
  1167. visitor(initializer, state, id.name);
  1168. } else {
  1169. const className = _core.types.stringLiteral(id.value + "");
  1170. visitor(initializer, state, className);
  1171. }
  1172. }
  1173. } else {
  1174. const ref = handleComputedProperty(propertyPath, id, state);
  1175. visitor(initializer, state, ref);
  1176. }
  1177. }
  1178. }
  1179. },
  1180. ClassPrivateProperty(path, state) {
  1181. const {
  1182. node
  1183. } = path;
  1184. const initializer = (0, _helperSkipTransparentExpressionWrappers.skipTransparentExprWrappers)(path.get("value"));
  1185. if (needsName(initializer)) {
  1186. const className = _core.types.stringLiteral("#" + node.key.id.name);
  1187. visitor(initializer, state, className);
  1188. }
  1189. },
  1190. ClassAccessorProperty(path, state) {
  1191. const {
  1192. node
  1193. } = path;
  1194. const id = node.key;
  1195. const initializer = (0, _helperSkipTransparentExpressionWrappers.skipTransparentExprWrappers)(path.get("value"));
  1196. if (needsName(initializer)) {
  1197. if (!node.computed) {
  1198. if (id.type === "Identifier") {
  1199. visitor(initializer, state, id.name);
  1200. } else if (id.type === "PrivateName") {
  1201. const className = _core.types.stringLiteral("#" + id.id.name);
  1202. visitor(initializer, state, className);
  1203. } else {
  1204. const className = _core.types.stringLiteral(id.value + "");
  1205. visitor(initializer, state, className);
  1206. }
  1207. } else {
  1208. const ref = handleComputedProperty(path, id, state);
  1209. visitor(initializer, state, ref);
  1210. }
  1211. }
  1212. },
  1213. ClassProperty(path, state) {
  1214. const {
  1215. node
  1216. } = path;
  1217. const id = node.key;
  1218. const initializer = (0, _helperSkipTransparentExpressionWrappers.skipTransparentExprWrappers)(path.get("value"));
  1219. if (needsName(initializer)) {
  1220. if (!node.computed) {
  1221. if (id.type === "Identifier") {
  1222. visitor(initializer, state, id.name);
  1223. } else {
  1224. const className = _core.types.stringLiteral(id.value + "");
  1225. visitor(initializer, state, className);
  1226. }
  1227. } else {
  1228. const ref = handleComputedProperty(path, id, state);
  1229. visitor(initializer, state, ref);
  1230. }
  1231. }
  1232. }
  1233. };
  1234. }
  1235. function isDecoratedAnonymousClassExpression(path) {
  1236. return path.isClassExpression({
  1237. id: null
  1238. }) && shouldTransformClass(path.node);
  1239. }
  1240. function generateLetUidIdentifier(scope, name) {
  1241. const id = scope.generateUidIdentifier(name);
  1242. scope.push({
  1243. id,
  1244. kind: "let"
  1245. });
  1246. return _core.types.cloneNode(id);
  1247. }
  1248. function _default({
  1249. assertVersion,
  1250. assumption
  1251. }, {
  1252. loose
  1253. }, version, inherits) {
  1254. var _assumption, _assumption2;
  1255. {
  1256. if (version === "2023-11" || version === "2023-05" || version === "2023-01") {
  1257. assertVersion("^7.21.0");
  1258. } else if (version === "2021-12") {
  1259. assertVersion("^7.16.0");
  1260. } else {
  1261. assertVersion("^7.19.0");
  1262. }
  1263. }
  1264. const VISITED = new WeakSet();
  1265. const constantSuper = (_assumption = assumption("constantSuper")) != null ? _assumption : loose;
  1266. const ignoreFunctionLength = (_assumption2 = assumption("ignoreFunctionLength")) != null ? _assumption2 : loose;
  1267. const namedEvaluationVisitor = buildNamedEvaluationVisitor(isDecoratedAnonymousClassExpression, visitClass);
  1268. function visitClass(path, state, className) {
  1269. var _node$id;
  1270. if (VISITED.has(path)) return;
  1271. const {
  1272. node
  1273. } = path;
  1274. className != null ? className : className = (_node$id = node.id) == null ? void 0 : _node$id.name;
  1275. const newPath = transformClass(path, state, constantSuper, ignoreFunctionLength, className, namedEvaluationVisitor, version);
  1276. if (newPath) {
  1277. VISITED.add(newPath);
  1278. return;
  1279. }
  1280. VISITED.add(path);
  1281. }
  1282. return {
  1283. name: "proposal-decorators",
  1284. inherits: inherits,
  1285. visitor: Object.assign({
  1286. ExportDefaultDeclaration(path, state) {
  1287. const {
  1288. declaration
  1289. } = path.node;
  1290. if ((declaration == null ? void 0 : declaration.type) === "ClassDeclaration" && isDecorated(declaration)) {
  1291. const isAnonymous = !declaration.id;
  1292. {
  1293. var _path$splitExportDecl;
  1294. (_path$splitExportDecl = path.splitExportDeclaration) != null ? _path$splitExportDecl : path.splitExportDeclaration = require("@babel/traverse").NodePath.prototype.splitExportDeclaration;
  1295. }
  1296. const updatedVarDeclarationPath = path.splitExportDeclaration();
  1297. if (isAnonymous) {
  1298. visitClass(updatedVarDeclarationPath, state, _core.types.stringLiteral("default"));
  1299. }
  1300. }
  1301. },
  1302. ExportNamedDeclaration(path) {
  1303. const {
  1304. declaration
  1305. } = path.node;
  1306. if ((declaration == null ? void 0 : declaration.type) === "ClassDeclaration" && isDecorated(declaration)) {
  1307. {
  1308. var _path$splitExportDecl2;
  1309. (_path$splitExportDecl2 = path.splitExportDeclaration) != null ? _path$splitExportDecl2 : path.splitExportDeclaration = require("@babel/traverse").NodePath.prototype.splitExportDeclaration;
  1310. }
  1311. path.splitExportDeclaration();
  1312. }
  1313. },
  1314. Class(path, state) {
  1315. visitClass(path, state, undefined);
  1316. }
  1317. }, namedEvaluationVisitor)
  1318. };
  1319. }
  1320. //# sourceMappingURL=decorators.js.map