@babel/plugin-proposal-decorators 7.22.6 → 8.0.0-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js CHANGED
@@ -1,42 +1,795 @@
1
- "use strict";
1
+ import { declare } from '@babel/helper-plugin-utils';
2
+ import syntaxDecorators from '@babel/plugin-syntax-decorators';
3
+ import '@babel/helper-create-class-features-plugin';
4
+ import { template, types } from '@babel/core';
5
+ import ReplaceSupers from '@babel/helper-replace-supers';
6
+ import splitExportDeclaration from '@babel/helper-split-export-declaration';
2
7
 
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.default = void 0;
7
- var _helperPluginUtils = require("@babel/helper-plugin-utils");
8
- var _pluginSyntaxDecorators = require("@babel/plugin-syntax-decorators");
9
- var _helperCreateClassFeaturesPlugin = require("@babel/helper-create-class-features-plugin");
10
- var _transformerLegacy = require("./transformer-legacy");
11
- var _transformer = require("./transformer-2023-05");
12
- var _default = (0, _helperPluginUtils.declare)((api, options) => {
13
- api.assertVersion(7);
8
+ const buildClassDecorator = template.statement(`
9
+ DECORATOR(CLASS_REF = INNER) || CLASS_REF;
10
+ `);
11
+ const buildClassPrototype = template(`
12
+ CLASS_REF.prototype;
13
+ `);
14
+ const buildGetDescriptor = template(`
15
+ Object.getOwnPropertyDescriptor(TARGET, PROPERTY);
16
+ `);
17
+ const buildGetObjectInitializer = template(`
18
+ (TEMP = Object.getOwnPropertyDescriptor(TARGET, PROPERTY), (TEMP = TEMP ? TEMP.value : undefined), {
19
+ enumerable: true,
20
+ configurable: true,
21
+ writable: true,
22
+ initializer: function(){
23
+ return TEMP;
24
+ }
25
+ })
26
+ `);
27
+ const WARNING_CALLS = new WeakSet();
28
+ function applyEnsureOrdering(path) {
29
+ const decorators = (path.isClass() ? [path, ...path.get("body.body")] : path.get("properties")).reduce((acc, prop) => acc.concat(prop.node.decorators || []), []);
30
+ const identDecorators = decorators.filter(decorator => !types.isIdentifier(decorator.expression));
31
+ if (identDecorators.length === 0) return;
32
+ return types.sequenceExpression(identDecorators.map(decorator => {
33
+ const expression = decorator.expression;
34
+ const id = decorator.expression = path.scope.generateDeclaredUidIdentifier("dec");
35
+ return types.assignmentExpression("=", id, expression);
36
+ }).concat([path.node]));
37
+ }
38
+ function applyClassDecorators(classPath) {
39
+ if (!hasClassDecorators(classPath.node)) return;
40
+ const decorators = classPath.node.decorators || [];
41
+ classPath.node.decorators = null;
42
+ const name = classPath.scope.generateDeclaredUidIdentifier("class");
43
+ return decorators.map(dec => dec.expression).reverse().reduce(function (acc, decorator) {
44
+ return buildClassDecorator({
45
+ CLASS_REF: types.cloneNode(name),
46
+ DECORATOR: types.cloneNode(decorator),
47
+ INNER: acc
48
+ }).expression;
49
+ }, classPath.node);
50
+ }
51
+ function hasClassDecorators(classNode) {
52
+ return !!classNode.decorators?.length;
53
+ }
54
+ function applyMethodDecorators(path, state) {
55
+ if (!hasMethodDecorators(path.node.body.body)) return;
56
+ return applyTargetDecorators(path, state, path.node.body.body);
57
+ }
58
+ function hasMethodDecorators(body) {
59
+ return body.some(node => node.decorators?.length);
60
+ }
61
+ function applyObjectDecorators(path, state) {
62
+ if (!hasMethodDecorators(path.node.properties)) return;
63
+ return applyTargetDecorators(path, state, path.node.properties.filter(prop => prop.type !== "SpreadElement"));
64
+ }
65
+ function applyTargetDecorators(path, state, decoratedProps) {
66
+ const name = path.scope.generateDeclaredUidIdentifier(path.isClass() ? "class" : "obj");
67
+ const exprs = decoratedProps.reduce(function (acc, node) {
68
+ let decorators = [];
69
+ if (node.decorators != null) {
70
+ decorators = node.decorators;
71
+ node.decorators = null;
72
+ }
73
+ if (decorators.length === 0) return acc;
74
+ if (node.computed) {
75
+ throw path.buildCodeFrameError("Computed method/property decorators are not yet supported.");
76
+ }
77
+ const property = types.isLiteral(node.key) ? node.key : types.stringLiteral(node.key.name);
78
+ const target = path.isClass() && !node.static ? buildClassPrototype({
79
+ CLASS_REF: name
80
+ }).expression : name;
81
+ if (types.isClassProperty(node, {
82
+ static: false
83
+ })) {
84
+ const descriptor = path.scope.generateDeclaredUidIdentifier("descriptor");
85
+ const initializer = node.value ? types.functionExpression(null, [], types.blockStatement([types.returnStatement(node.value)])) : types.nullLiteral();
86
+ node.value = types.callExpression(state.addHelper("initializerWarningHelper"), [descriptor, types.thisExpression()]);
87
+ WARNING_CALLS.add(node.value);
88
+ acc.push(types.assignmentExpression("=", types.cloneNode(descriptor), types.callExpression(state.addHelper("applyDecoratedDescriptor"), [types.cloneNode(target), types.cloneNode(property), types.arrayExpression(decorators.map(dec => types.cloneNode(dec.expression))), types.objectExpression([types.objectProperty(types.identifier("configurable"), types.booleanLiteral(true)), types.objectProperty(types.identifier("enumerable"), types.booleanLiteral(true)), types.objectProperty(types.identifier("writable"), types.booleanLiteral(true)), types.objectProperty(types.identifier("initializer"), initializer)])])));
89
+ } else {
90
+ acc.push(types.callExpression(state.addHelper("applyDecoratedDescriptor"), [types.cloneNode(target), types.cloneNode(property), types.arrayExpression(decorators.map(dec => types.cloneNode(dec.expression))), types.isObjectProperty(node) || types.isClassProperty(node, {
91
+ static: true
92
+ }) ? buildGetObjectInitializer({
93
+ TEMP: path.scope.generateDeclaredUidIdentifier("init"),
94
+ TARGET: types.cloneNode(target),
95
+ PROPERTY: types.cloneNode(property)
96
+ }).expression : buildGetDescriptor({
97
+ TARGET: types.cloneNode(target),
98
+ PROPERTY: types.cloneNode(property)
99
+ }).expression, types.cloneNode(target)]));
100
+ }
101
+ return acc;
102
+ }, []);
103
+ return types.sequenceExpression([types.assignmentExpression("=", types.cloneNode(name), path.node), types.sequenceExpression(exprs), types.cloneNode(name)]);
104
+ }
105
+ function decoratedClassToExpression({
106
+ node,
107
+ scope
108
+ }) {
109
+ if (!hasClassDecorators(node) && !hasMethodDecorators(node.body.body)) {
110
+ return;
111
+ }
112
+ const ref = node.id ? types.cloneNode(node.id) : scope.generateUidIdentifier("class");
113
+ return types.variableDeclaration("let", [types.variableDeclarator(ref, types.toExpression(node))]);
114
+ }
115
+ const visitor = {
116
+ ExportDefaultDeclaration(path) {
117
+ const decl = path.get("declaration");
118
+ if (!decl.isClassDeclaration()) return;
119
+ const replacement = decoratedClassToExpression(decl);
120
+ if (replacement) {
121
+ const [varDeclPath] = path.replaceWithMultiple([replacement, types.exportNamedDeclaration(null, [types.exportSpecifier(types.cloneNode(replacement.declarations[0].id), types.identifier("default"))])]);
122
+ if (!decl.node.id) {
123
+ path.scope.registerDeclaration(varDeclPath);
124
+ }
125
+ }
126
+ },
127
+ ClassDeclaration(path) {
128
+ const replacement = decoratedClassToExpression(path);
129
+ if (replacement) {
130
+ const [newPath] = path.replaceWith(replacement);
131
+ const decl = newPath.get("declarations.0");
132
+ const id = decl.node.id;
133
+ const binding = path.scope.getOwnBinding(id.name);
134
+ binding.identifier = id;
135
+ binding.path = decl;
136
+ }
137
+ },
138
+ ClassExpression(path, state) {
139
+ const decoratedClass = applyEnsureOrdering(path) || applyClassDecorators(path) || applyMethodDecorators(path, state);
140
+ if (decoratedClass) path.replaceWith(decoratedClass);
141
+ },
142
+ ObjectExpression(path, state) {
143
+ const decoratedObject = applyEnsureOrdering(path) || applyObjectDecorators(path, state);
144
+ if (decoratedObject) path.replaceWith(decoratedObject);
145
+ },
146
+ AssignmentExpression(path, state) {
147
+ if (!WARNING_CALLS.has(path.node.right)) return;
148
+ path.replaceWith(types.callExpression(state.addHelper("initializerDefineProperty"), [types.cloneNode(path.get("left.object").node), types.stringLiteral(path.get("left.property").node.name || path.get("left.property").node.value), types.cloneNode(path.get("right.arguments")[0].node), types.cloneNode(path.get("right.arguments")[1].node)]));
149
+ },
150
+ CallExpression(path, state) {
151
+ if (path.node.arguments.length !== 3) return;
152
+ if (!WARNING_CALLS.has(path.node.arguments[2])) return;
153
+ if (path.node.callee.name !== state.addHelper("defineProperty").name) {
154
+ return;
155
+ }
156
+ path.replaceWith(types.callExpression(state.addHelper("initializerDefineProperty"), [types.cloneNode(path.get("arguments")[0].node), types.cloneNode(path.get("arguments")[1].node), types.cloneNode(path.get("arguments.2.arguments")[0].node), types.cloneNode(path.get("arguments.2.arguments")[1].node)]));
157
+ }
158
+ };
159
+
160
+ function incrementId(id, idx = id.length - 1) {
161
+ if (idx === -1) {
162
+ id.unshift(65);
163
+ return;
164
+ }
165
+ const current = id[idx];
166
+ if (current === 90) {
167
+ id[idx] = 97;
168
+ } else if (current === 122) {
169
+ id[idx] = 65;
170
+ incrementId(id, idx - 1);
171
+ } else {
172
+ id[idx] = current + 1;
173
+ }
174
+ }
175
+ function createPrivateUidGeneratorForClass(classPath) {
176
+ const currentPrivateId = [];
177
+ const privateNames = new Set();
178
+ classPath.traverse({
179
+ PrivateName(path) {
180
+ privateNames.add(path.node.id.name);
181
+ }
182
+ });
183
+ return () => {
184
+ let reifiedId;
185
+ do {
186
+ incrementId(currentPrivateId);
187
+ reifiedId = String.fromCharCode(...currentPrivateId);
188
+ } while (privateNames.has(reifiedId));
189
+ return types.privateName(types.identifier(reifiedId));
190
+ };
191
+ }
192
+ function createLazyPrivateUidGeneratorForClass(classPath) {
193
+ let generator;
194
+ return () => {
195
+ if (!generator) {
196
+ generator = createPrivateUidGeneratorForClass(classPath);
197
+ }
198
+ return generator();
199
+ };
200
+ }
201
+ function replaceClassWithVar(path) {
202
+ if (path.type === "ClassDeclaration") {
203
+ const varId = path.scope.generateUidIdentifierBasedOnNode(path.node.id);
204
+ const classId = types.identifier(path.node.id.name);
205
+ path.scope.rename(classId.name, varId.name);
206
+ path.insertBefore(types.variableDeclaration("let", [types.variableDeclarator(varId)]));
207
+ path.get("id").replaceWith(classId);
208
+ return [types.cloneNode(varId), path];
209
+ } else {
210
+ let className;
211
+ let varId;
212
+ if (path.node.id) {
213
+ className = path.node.id.name;
214
+ varId = path.scope.parent.generateDeclaredUidIdentifier(className);
215
+ path.scope.rename(className, varId.name);
216
+ } else if (path.parentPath.node.type === "VariableDeclarator" && path.parentPath.node.id.type === "Identifier") {
217
+ className = path.parentPath.node.id.name;
218
+ varId = path.scope.parent.generateDeclaredUidIdentifier(className);
219
+ } else {
220
+ varId = path.scope.parent.generateDeclaredUidIdentifier("decorated_class");
221
+ }
222
+ const newClassExpr = types.classExpression(className && types.identifier(className), path.node.superClass, path.node.body);
223
+ const [newPath] = path.replaceWith(types.sequenceExpression([newClassExpr, varId]));
224
+ return [types.cloneNode(varId), newPath.get("expressions.0")];
225
+ }
226
+ }
227
+ function generateClassProperty(key, value, isStatic) {
228
+ if (key.type === "PrivateName") {
229
+ return types.classPrivateProperty(key, value, undefined, isStatic);
230
+ } else {
231
+ return types.classProperty(key, value, undefined, undefined, isStatic);
232
+ }
233
+ }
234
+ function addProxyAccessorsFor(className, element, originalKey, targetKey, version, isComputed = false) {
235
+ const {
236
+ static: isStatic
237
+ } = element.node;
238
+ const thisArg = version === "2023-05" && isStatic ? className : types.thisExpression();
239
+ const getterBody = types.blockStatement([types.returnStatement(types.memberExpression(types.cloneNode(thisArg), types.cloneNode(targetKey)))]);
240
+ const setterBody = types.blockStatement([types.expressionStatement(types.assignmentExpression("=", types.memberExpression(types.cloneNode(thisArg), types.cloneNode(targetKey)), types.identifier("v")))]);
241
+ let getter, setter;
242
+ if (originalKey.type === "PrivateName") {
243
+ getter = types.classPrivateMethod("get", types.cloneNode(originalKey), [], getterBody, isStatic);
244
+ setter = types.classPrivateMethod("set", types.cloneNode(originalKey), [types.identifier("v")], setterBody, isStatic);
245
+ } else {
246
+ getter = types.classMethod("get", types.cloneNode(originalKey), [], getterBody, isComputed, isStatic);
247
+ setter = types.classMethod("set", types.cloneNode(originalKey), [types.identifier("v")], setterBody, isComputed, isStatic);
248
+ }
249
+ element.insertAfter(setter);
250
+ element.insertAfter(getter);
251
+ }
252
+ function extractProxyAccessorsFor(targetKey, version) {
253
+ if (version !== "2023-05" && version !== "2023-01") {
254
+ return [template.expression.ast`
255
+ function () {
256
+ return this.${types.cloneNode(targetKey)};
257
+ }
258
+ `, template.expression.ast`
259
+ function (value) {
260
+ this.${types.cloneNode(targetKey)} = value;
261
+ }
262
+ `];
263
+ }
264
+ return [template.expression.ast`
265
+ o => o.${types.cloneNode(targetKey)}
266
+ `, template.expression.ast`
267
+ (o, v) => o.${types.cloneNode(targetKey)} = v
268
+ `];
269
+ }
270
+ const FIELD = 0;
271
+ const ACCESSOR = 1;
272
+ const METHOD = 2;
273
+ const GETTER = 3;
274
+ const SETTER = 4;
275
+ const STATIC_OLD_VERSION = 5;
276
+ const STATIC = 8;
277
+ const DECORATORS_HAVE_THIS = 16;
278
+ function getElementKind(element) {
279
+ switch (element.node.type) {
280
+ case "ClassProperty":
281
+ case "ClassPrivateProperty":
282
+ return FIELD;
283
+ case "ClassAccessorProperty":
284
+ return ACCESSOR;
285
+ case "ClassMethod":
286
+ case "ClassPrivateMethod":
287
+ if (element.node.kind === "get") {
288
+ return GETTER;
289
+ } else if (element.node.kind === "set") {
290
+ return SETTER;
291
+ } else {
292
+ return METHOD;
293
+ }
294
+ }
295
+ }
296
+ function isDecoratorInfo(info) {
297
+ return "decorators" in info;
298
+ }
299
+ function filteredOrderedDecoratorInfo(info) {
300
+ const filtered = info.filter(isDecoratorInfo);
301
+ return [...filtered.filter(el => el.isStatic && el.kind >= ACCESSOR && el.kind <= SETTER), ...filtered.filter(el => !el.isStatic && el.kind >= ACCESSOR && el.kind <= SETTER), ...filtered.filter(el => el.isStatic && el.kind === FIELD), ...filtered.filter(el => !el.isStatic && el.kind === FIELD)];
302
+ }
303
+ function generateDecorationList(decorators, decoratorsThis, version) {
304
+ const decsCount = decorators.length;
305
+ const hasOneThis = decoratorsThis.some(Boolean);
306
+ const decs = [];
307
+ for (let i = 0; i < decsCount; i++) {
308
+ if (version === "2023-05" && hasOneThis) {
309
+ decs.push(decoratorsThis[i] || types.unaryExpression("void", types.numericLiteral(0)));
310
+ }
311
+ decs.push(decorators[i]);
312
+ }
313
+ return {
314
+ hasThis: hasOneThis,
315
+ decs
316
+ };
317
+ }
318
+ function generateDecorationExprs(info, version) {
319
+ return types.arrayExpression(filteredOrderedDecoratorInfo(info).map(el => {
320
+ const {
321
+ decs,
322
+ hasThis
323
+ } = generateDecorationList(el.decorators, el.decoratorsThis, version);
324
+ let flag = el.kind;
325
+ if (el.isStatic) {
326
+ flag += version === "2023-05" ? STATIC : STATIC_OLD_VERSION;
327
+ }
328
+ if (hasThis) flag += DECORATORS_HAVE_THIS;
329
+ return types.arrayExpression([decs.length === 1 ? decs[0] : types.arrayExpression(decs), types.numericLiteral(flag), el.name, ...(el.privateMethods || [])]);
330
+ }));
331
+ }
332
+ function extractElementLocalAssignments(decorationInfo) {
333
+ const localIds = [];
334
+ for (const el of filteredOrderedDecoratorInfo(decorationInfo)) {
335
+ const {
336
+ locals
337
+ } = el;
338
+ if (Array.isArray(locals)) {
339
+ localIds.push(...locals);
340
+ } else if (locals !== undefined) {
341
+ localIds.push(locals);
342
+ }
343
+ }
344
+ return localIds;
345
+ }
346
+ function addCallAccessorsFor(element, key, getId, setId) {
347
+ element.insertAfter(types.classPrivateMethod("get", types.cloneNode(key), [], types.blockStatement([types.returnStatement(types.callExpression(types.cloneNode(getId), [types.thisExpression()]))])));
348
+ element.insertAfter(types.classPrivateMethod("set", types.cloneNode(key), [types.identifier("v")], types.blockStatement([types.expressionStatement(types.callExpression(types.cloneNode(setId), [types.thisExpression(), types.identifier("v")]))])));
349
+ }
350
+ function isNotTsParameter(node) {
351
+ return node.type !== "TSParameterProperty";
352
+ }
353
+ function movePrivateAccessor(element, key, methodLocalVar, isStatic) {
354
+ let params;
355
+ let block;
356
+ if (element.node.kind === "set") {
357
+ params = [types.identifier("v")];
358
+ block = [types.expressionStatement(types.callExpression(methodLocalVar, [types.thisExpression(), types.identifier("v")]))];
359
+ } else {
360
+ params = [];
361
+ block = [types.returnStatement(types.callExpression(methodLocalVar, [types.thisExpression()]))];
362
+ }
363
+ element.replaceWith(types.classPrivateMethod(element.node.kind, types.cloneNode(key), params, types.blockStatement(block), isStatic));
364
+ }
365
+ function isClassDecoratableElementPath(path) {
366
+ const {
367
+ type
368
+ } = path;
369
+ return type !== "TSDeclareMethod" && type !== "TSIndexSignature" && type !== "StaticBlock";
370
+ }
371
+ function staticBlockToIIFE(block) {
372
+ return types.callExpression(types.arrowFunctionExpression([], types.blockStatement(block.body)), []);
373
+ }
374
+ function maybeSequenceExpression(exprs) {
375
+ if (exprs.length === 0) return types.unaryExpression("void", types.numericLiteral(0));
376
+ if (exprs.length === 1) return exprs[0];
377
+ return types.sequenceExpression(exprs);
378
+ }
379
+ function transformClass(path, state, constantSuper, version) {
380
+ const body = path.get("body.body");
381
+ const classDecorators = path.node.decorators;
382
+ let hasElementDecorators = false;
383
+ const generateClassPrivateUid = createLazyPrivateUidGeneratorForClass(path);
384
+ for (const element of body) {
385
+ if (!isClassDecoratableElementPath(element)) {
386
+ continue;
387
+ }
388
+ if (element.node.decorators && element.node.decorators.length > 0) {
389
+ hasElementDecorators = true;
390
+ } else if (element.node.type === "ClassAccessorProperty") {
391
+ const {
392
+ key,
393
+ value,
394
+ static: isStatic,
395
+ computed
396
+ } = element.node;
397
+ const newId = generateClassPrivateUid();
398
+ const valueNode = value ? types.cloneNode(value) : undefined;
399
+ const newField = generateClassProperty(newId, valueNode, isStatic);
400
+ const [newPath] = element.replaceWith(newField);
401
+ addProxyAccessorsFor(path.node.id, newPath, key, newId, version, computed);
402
+ }
403
+ }
404
+ if (!classDecorators && !hasElementDecorators) return;
405
+ const elementDecoratorInfo = [];
406
+ let firstFieldPath;
407
+ let constructorPath;
408
+ let requiresProtoInit = false;
409
+ let requiresStaticInit = false;
410
+ const decoratedPrivateMethods = new Set();
411
+ let protoInitLocal, staticInitLocal, classInitLocal, classIdLocal;
412
+ const assignments = [];
413
+ const scopeParent = path.scope.parent;
414
+ const memoiseExpression = (expression, hint) => {
415
+ const localEvaluatedId = scopeParent.generateDeclaredUidIdentifier(hint);
416
+ assignments.push(types.assignmentExpression("=", localEvaluatedId, expression));
417
+ return types.cloneNode(localEvaluatedId);
418
+ };
419
+ const decoratorsThis = new Map();
420
+ const maybeExtractDecorator = decorator => {
421
+ const {
422
+ expression
423
+ } = decorator;
424
+ if (version === "2023-05" && types.isMemberExpression(expression)) {
425
+ let object;
426
+ if (types.isSuper(expression.object) || types.isThisExpression(expression.object)) {
427
+ object = memoiseExpression(types.thisExpression(), "obj");
428
+ } else if (!scopeParent.isStatic(expression.object)) {
429
+ object = memoiseExpression(expression.object, "obj");
430
+ expression.object = object;
431
+ } else {
432
+ object = expression.object;
433
+ }
434
+ decoratorsThis.set(decorator, types.cloneNode(object));
435
+ }
436
+ if (!scopeParent.isStatic(expression)) {
437
+ decorator.expression = memoiseExpression(expression, "dec");
438
+ }
439
+ };
440
+ if (classDecorators) {
441
+ classInitLocal = scopeParent.generateDeclaredUidIdentifier("initClass");
442
+ const [classId, classPath] = replaceClassWithVar(path);
443
+ path = classPath;
444
+ classIdLocal = classId;
445
+ path.node.decorators = null;
446
+ for (const classDecorator of classDecorators) {
447
+ maybeExtractDecorator(classDecorator);
448
+ }
449
+ } else {
450
+ if (!path.node.id) {
451
+ path.node.id = path.scope.generateUidIdentifier("Class");
452
+ }
453
+ classIdLocal = types.cloneNode(path.node.id);
454
+ }
455
+ let lastInstancePrivateName;
456
+ let needsInstancePrivateBrandCheck = false;
457
+ if (hasElementDecorators) {
458
+ for (const element of body) {
459
+ if (!isClassDecoratableElementPath(element)) {
460
+ continue;
461
+ }
462
+ const {
463
+ node
464
+ } = element;
465
+ const decorators = element.get("decorators");
466
+ const hasDecorators = Array.isArray(decorators) && decorators.length > 0;
467
+ if (hasDecorators) {
468
+ for (const decoratorPath of decorators) {
469
+ maybeExtractDecorator(decoratorPath.node);
470
+ }
471
+ }
472
+ const isComputed = "computed" in element.node && element.node.computed === true;
473
+ if (isComputed) {
474
+ if (!scopeParent.isStatic(node.key)) {
475
+ node.key = memoiseExpression(node.key, "computedKey");
476
+ }
477
+ }
478
+ const kind = getElementKind(element);
479
+ const {
480
+ key
481
+ } = node;
482
+ const isPrivate = key.type === "PrivateName";
483
+ const isStatic = !!element.node.static;
484
+ let name = "computedKey";
485
+ if (isPrivate) {
486
+ name = key.id.name;
487
+ } else if (!isComputed && key.type === "Identifier") {
488
+ name = key.name;
489
+ }
490
+ if (isPrivate && !isStatic) {
491
+ if (hasDecorators) {
492
+ needsInstancePrivateBrandCheck = true;
493
+ }
494
+ if (types.isClassPrivateProperty(node) || !lastInstancePrivateName) {
495
+ lastInstancePrivateName = key;
496
+ }
497
+ }
498
+ if (element.isClassMethod({
499
+ kind: "constructor"
500
+ })) {
501
+ constructorPath = element;
502
+ }
503
+ if (hasDecorators) {
504
+ let locals;
505
+ let privateMethods;
506
+ if (kind === ACCESSOR) {
507
+ const {
508
+ value
509
+ } = element.node;
510
+ const params = [types.thisExpression()];
511
+ if (value) {
512
+ params.push(types.cloneNode(value));
513
+ }
514
+ const newId = generateClassPrivateUid();
515
+ const newFieldInitId = element.scope.parent.generateDeclaredUidIdentifier(`init_${name}`);
516
+ const newValue = types.callExpression(types.cloneNode(newFieldInitId), params);
517
+ const newField = generateClassProperty(newId, newValue, isStatic);
518
+ const [newPath] = element.replaceWith(newField);
519
+ if (isPrivate) {
520
+ privateMethods = extractProxyAccessorsFor(newId, version);
521
+ const getId = newPath.scope.parent.generateDeclaredUidIdentifier(`get_${name}`);
522
+ const setId = newPath.scope.parent.generateDeclaredUidIdentifier(`set_${name}`);
523
+ addCallAccessorsFor(newPath, key, getId, setId);
524
+ locals = [newFieldInitId, getId, setId];
525
+ } else {
526
+ addProxyAccessorsFor(path.node.id, newPath, key, newId, version, isComputed);
527
+ locals = newFieldInitId;
528
+ }
529
+ } else if (kind === FIELD) {
530
+ const initId = element.scope.parent.generateDeclaredUidIdentifier(`init_${name}`);
531
+ const valuePath = element.get("value");
532
+ valuePath.replaceWith(types.callExpression(types.cloneNode(initId), [types.thisExpression(), valuePath.node].filter(v => v)));
533
+ locals = initId;
534
+ if (isPrivate) {
535
+ privateMethods = extractProxyAccessorsFor(key, version);
536
+ }
537
+ } else if (isPrivate) {
538
+ locals = element.scope.parent.generateDeclaredUidIdentifier(`call_${name}`);
539
+ const replaceSupers = new ReplaceSupers({
540
+ constantSuper,
541
+ methodPath: element,
542
+ objectRef: classIdLocal,
543
+ superRef: path.node.superClass,
544
+ file: state.file,
545
+ refToPreserve: classIdLocal
546
+ });
547
+ replaceSupers.replace();
548
+ const {
549
+ params,
550
+ body,
551
+ async: isAsync
552
+ } = element.node;
553
+ privateMethods = [types.functionExpression(undefined, params.filter(isNotTsParameter), body, isAsync)];
554
+ if (kind === GETTER || kind === SETTER) {
555
+ movePrivateAccessor(element, types.cloneNode(key), types.cloneNode(locals), isStatic);
556
+ } else {
557
+ const node = element.node;
558
+ path.node.body.body.unshift(types.classPrivateProperty(key, types.cloneNode(locals), [], node.static));
559
+ decoratedPrivateMethods.add(key.id.name);
560
+ element.remove();
561
+ }
562
+ }
563
+ let nameExpr;
564
+ if (isComputed) {
565
+ nameExpr = types.cloneNode(key);
566
+ } else if (key.type === "PrivateName") {
567
+ nameExpr = types.stringLiteral(key.id.name);
568
+ } else if (key.type === "Identifier") {
569
+ nameExpr = types.stringLiteral(key.name);
570
+ } else {
571
+ nameExpr = types.cloneNode(key);
572
+ }
573
+ elementDecoratorInfo.push({
574
+ kind,
575
+ decorators: decorators.map(d => d.node.expression),
576
+ decoratorsThis: decorators.map(d => decoratorsThis.get(d.node)),
577
+ name: nameExpr,
578
+ isStatic,
579
+ privateMethods,
580
+ locals
581
+ });
582
+ if (kind !== FIELD) {
583
+ if (isStatic) {
584
+ requiresStaticInit = true;
585
+ } else {
586
+ requiresProtoInit = true;
587
+ }
588
+ }
589
+ if (element.node) {
590
+ element.node.decorators = null;
591
+ }
592
+ if (!firstFieldPath && !isStatic && (kind === FIELD || kind === ACCESSOR)) {
593
+ firstFieldPath = element;
594
+ }
595
+ }
596
+ }
597
+ }
598
+ const elementDecorations = generateDecorationExprs(elementDecoratorInfo, version);
599
+ let classDecorationsFlag = 0;
600
+ let classDecorations = [];
601
+ if (classDecorators) {
602
+ const {
603
+ hasThis,
604
+ decs
605
+ } = generateDecorationList(classDecorators.map(el => el.expression), classDecorators.map(dec => decoratorsThis.get(dec)), version);
606
+ classDecorationsFlag = hasThis ? 1 : 0;
607
+ classDecorations = decs;
608
+ }
609
+ const elementLocals = extractElementLocalAssignments(elementDecoratorInfo);
610
+ if (requiresProtoInit) {
611
+ protoInitLocal = scopeParent.generateDeclaredUidIdentifier("initProto");
612
+ elementLocals.push(protoInitLocal);
613
+ const protoInitCall = types.callExpression(types.cloneNode(protoInitLocal), [types.thisExpression()]);
614
+ if (firstFieldPath) {
615
+ const value = firstFieldPath.get("value");
616
+ const body = [protoInitCall];
617
+ if (value.node) {
618
+ body.push(value.node);
619
+ }
620
+ value.replaceWith(types.sequenceExpression(body));
621
+ } else if (constructorPath) {
622
+ if (path.node.superClass) {
623
+ path.traverse({
624
+ CallExpression: {
625
+ exit(path) {
626
+ if (!path.get("callee").isSuper()) return;
627
+ path.replaceWith(types.callExpression(types.cloneNode(protoInitLocal), [path.node]));
628
+ path.skip();
629
+ }
630
+ }
631
+ });
632
+ } else {
633
+ constructorPath.node.body.body.unshift(types.expressionStatement(protoInitCall));
634
+ }
635
+ } else {
636
+ const body = [types.expressionStatement(protoInitCall)];
637
+ if (path.node.superClass) {
638
+ body.unshift(types.expressionStatement(types.callExpression(types.super(), [types.spreadElement(types.identifier("args"))])));
639
+ }
640
+ path.node.body.body.unshift(types.classMethod("constructor", types.identifier("constructor"), [types.restElement(types.identifier("args"))], types.blockStatement(body)));
641
+ }
642
+ }
643
+ if (requiresStaticInit) {
644
+ staticInitLocal = scopeParent.generateDeclaredUidIdentifier("initStatic");
645
+ elementLocals.push(staticInitLocal);
646
+ }
647
+ if (decoratedPrivateMethods.size > 0) {
648
+ path.traverse({
649
+ PrivateName(path) {
650
+ if (!decoratedPrivateMethods.has(path.node.id.name)) return;
651
+ const parentPath = path.parentPath;
652
+ const parentParentPath = parentPath.parentPath;
653
+ 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) {
654
+ throw path.buildCodeFrameError(`Decorated private methods are not updatable, but "#${path.node.id.name}" is updated via this expression.`);
655
+ }
656
+ }
657
+ });
658
+ }
659
+ const classLocals = [];
660
+ let classInitInjected = false;
661
+ const classInitCall = classInitLocal && types.callExpression(types.cloneNode(classInitLocal), []);
662
+ const originalClass = path.node;
663
+ if (classDecorators) {
664
+ classLocals.push(classIdLocal, classInitLocal);
665
+ const statics = [];
666
+ let staticBlocks = [];
667
+ path.get("body.body").forEach(element => {
668
+ if (element.isStaticBlock()) {
669
+ staticBlocks.push(element.node);
670
+ element.remove();
671
+ return;
672
+ }
673
+ const isProperty = element.isClassProperty() || element.isClassPrivateProperty();
674
+ if ((isProperty || element.isClassPrivateMethod()) && element.node.static) {
675
+ if (isProperty && staticBlocks.length > 0) {
676
+ const allValues = staticBlocks.map(staticBlockToIIFE);
677
+ if (element.node.value) allValues.push(element.node.value);
678
+ element.node.value = maybeSequenceExpression(allValues);
679
+ staticBlocks = [];
680
+ }
681
+ element.node.static = false;
682
+ statics.push(element.node);
683
+ element.remove();
684
+ }
685
+ });
686
+ if (statics.length > 0 || staticBlocks.length > 0) {
687
+ const staticsClass = template.expression.ast`
688
+ class extends ${state.addHelper("identity")} {}
689
+ `;
690
+ staticsClass.body.body = [types.staticBlock([types.toStatement(originalClass, true) || types.expressionStatement(originalClass)]), ...statics];
691
+ const constructorBody = [];
692
+ const newExpr = types.newExpression(staticsClass, []);
693
+ if (staticBlocks.length > 0) {
694
+ constructorBody.push(...staticBlocks.map(staticBlockToIIFE));
695
+ }
696
+ if (classInitCall) {
697
+ classInitInjected = true;
698
+ constructorBody.push(classInitCall);
699
+ }
700
+ if (constructorBody.length > 0) {
701
+ constructorBody.unshift(types.callExpression(types.super(), [types.cloneNode(classIdLocal)]));
702
+ staticsClass.body.body.push(types.classMethod("constructor", types.identifier("constructor"), [], types.blockStatement([types.expressionStatement(types.sequenceExpression(constructorBody))])));
703
+ } else {
704
+ newExpr.arguments.push(types.cloneNode(classIdLocal));
705
+ }
706
+ path.replaceWith(newExpr);
707
+ }
708
+ }
709
+ if (!classInitInjected && classInitCall) {
710
+ path.node.body.body.push(types.staticBlock([types.expressionStatement(classInitCall)]));
711
+ }
712
+ originalClass.body.body.unshift(types.staticBlock([types.expressionStatement(createLocalsAssignment(elementLocals, classLocals, elementDecorations, types.arrayExpression(classDecorations), types.numericLiteral(classDecorationsFlag), needsInstancePrivateBrandCheck ? lastInstancePrivateName : null, state)), requiresStaticInit && types.expressionStatement(types.callExpression(types.cloneNode(staticInitLocal), [types.thisExpression()]))].filter(Boolean)));
713
+ path.insertBefore(assignments.map(expr => types.expressionStatement(expr)));
714
+ path.scope.crawl();
715
+ return path;
716
+ }
717
+ function createLocalsAssignment(elementLocals, classLocals, elementDecorations, classDecorations, classDecorationsFlag, maybePrivateBranName, state, version) {
718
+ let lhs, rhs;
719
+ const args = [types.thisExpression(), elementDecorations, classDecorations];
720
+ {
721
+ if (maybePrivateBranName || classDecorationsFlag.value !== 0) {
722
+ args.push(classDecorationsFlag);
723
+ }
724
+ if (maybePrivateBranName) {
725
+ args.push(template.expression.ast`
726
+ _ => ${types.cloneNode(maybePrivateBranName)} in _
727
+ `);
728
+ }
729
+ rhs = types.callExpression(state.addHelper("applyDecs2305"), args);
730
+ }
731
+ if (elementLocals.length > 0) {
732
+ if (classLocals.length > 0) {
733
+ lhs = types.objectPattern([types.objectProperty(types.identifier("e"), types.arrayPattern(elementLocals)), types.objectProperty(types.identifier("c"), types.arrayPattern(classLocals))]);
734
+ } else {
735
+ lhs = types.arrayPattern(elementLocals);
736
+ rhs = types.memberExpression(rhs, types.identifier("e"), false, false);
737
+ }
738
+ } else {
739
+ lhs = types.arrayPattern(classLocals);
740
+ rhs = types.memberExpression(rhs, types.identifier("c"), false, false);
741
+ }
742
+ return types.assignmentExpression("=", lhs, rhs);
743
+ }
744
+ function transformer2023_05 ({
745
+ assertVersion,
746
+ assumption
747
+ }, {
748
+ loose
749
+ }, version) {
14
750
  {
15
- var {
16
- legacy
17
- } = options;
751
+ assertVersion("^7.21.0");
18
752
  }
753
+ const VISITED = new WeakSet();
754
+ const constantSuper = assumption("constantSuper") ?? loose;
755
+ return {
756
+ name: "proposal-decorators",
757
+ inherits: syntaxDecorators,
758
+ visitor: {
759
+ "ExportNamedDeclaration|ExportDefaultDeclaration"(path) {
760
+ const {
761
+ declaration
762
+ } = path.node;
763
+ if (declaration?.type === "ClassDeclaration" && declaration.decorators?.length > 0) {
764
+ splitExportDeclaration(path);
765
+ }
766
+ },
767
+ Class(path, state) {
768
+ if (VISITED.has(path)) return;
769
+ const newPath = transformClass(path, state, constantSuper, version);
770
+ if (newPath) VISITED.add(newPath);
771
+ }
772
+ }
773
+ };
774
+ }
775
+
776
+ var index = declare((api, options) => {
777
+ api.assertVersion(7);
19
778
  const {
20
779
  version
21
780
  } = options;
22
- if (legacy || version === "legacy") {
781
+ if (version === "legacy") {
23
782
  return {
24
783
  name: "proposal-decorators",
25
- inherits: _pluginSyntaxDecorators.default,
26
- visitor: _transformerLegacy.default
784
+ inherits: syntaxDecorators,
785
+ visitor: visitor
27
786
  };
28
787
  } else if (version === "2021-12" || version === "2022-03" || version === "2023-01" || version === "2023-05") {
29
- return (0, _transformer.default)(api, options, version);
788
+ return transformer2023_05(api, options, version);
30
789
  } else {
31
- api.assertVersion("^7.0.2");
32
- return (0, _helperCreateClassFeaturesPlugin.createClassFeaturePlugin)({
33
- name: "proposal-decorators",
34
- api,
35
- feature: _helperCreateClassFeaturesPlugin.FEATURES.decorators,
36
- inherits: _pluginSyntaxDecorators.default
37
- });
790
+ throw new Error("The '.version' option must be one of 'legacy', '2021-12', '2022-03', or '2023-01'.");
38
791
  }
39
792
  });
40
- exports.default = _default;
41
793
 
794
+ export { index as default };
42
795
  //# sourceMappingURL=index.js.map