@lwc/babel-plugin-component 2.41.3 → 2.43.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.
Files changed (45) hide show
  1. package/README.md +37 -0
  2. package/dist/index.cjs.js +1145 -0
  3. package/dist/index.cjs.js.map +1 -0
  4. package/dist/index.js +1143 -0
  5. package/dist/index.js.map +1 -0
  6. package/package.json +25 -8
  7. package/types/compiler-version-number.d.ts +3 -0
  8. package/types/component.d.ts +3 -0
  9. package/types/constants.d.ts +26 -0
  10. package/types/decorators/api/index.d.ts +8 -0
  11. package/types/decorators/api/shared.d.ts +3 -0
  12. package/types/decorators/api/transform.d.ts +6 -0
  13. package/types/decorators/api/validate.d.ts +2 -0
  14. package/types/decorators/index.d.ts +21 -0
  15. package/types/decorators/track/index.d.ts +10 -0
  16. package/types/decorators/types.d.ts +20 -0
  17. package/types/decorators/wire/index.d.ts +8 -0
  18. package/types/decorators/wire/shared.d.ts +3 -0
  19. package/types/decorators/wire/transform.d.ts +4 -0
  20. package/types/decorators/wire/validate.d.ts +2 -0
  21. package/types/dedupe-imports.d.ts +4 -0
  22. package/types/dynamic-imports.d.ts +3 -0
  23. package/types/index.d.ts +9 -0
  24. package/types/scope-css-imports.d.ts +3 -0
  25. package/types/types.d.ts +18 -0
  26. package/types/utils.d.ts +21 -0
  27. package/src/compiler-version-number.js +0 -33
  28. package/src/component.js +0 -89
  29. package/src/constants.js +0 -67
  30. package/src/decorators/api/index.js +0 -18
  31. package/src/decorators/api/shared.js +0 -17
  32. package/src/decorators/api/transform.js +0 -95
  33. package/src/decorators/api/validate.js +0 -160
  34. package/src/decorators/index.js +0 -271
  35. package/src/decorators/track/index.js +0 -49
  36. package/src/decorators/wire/index.js +0 -18
  37. package/src/decorators/wire/shared.js +0 -17
  38. package/src/decorators/wire/transform.js +0 -261
  39. package/src/decorators/wire/validate.js +0 -100
  40. package/src/dedupe-imports.js +0 -56
  41. package/src/dynamic-imports.js +0 -70
  42. package/src/index.d.ts +0 -10
  43. package/src/index.js +0 -77
  44. package/src/scope-css-imports.js +0 -23
  45. package/src/utils.js +0 -116
@@ -0,0 +1,1145 @@
1
+ /**
2
+ * Copyright (C) 2023 salesforce.com, inc.
3
+ */
4
+ 'use strict';
5
+
6
+ var path = require('path');
7
+ var helperModuleImports = require('@babel/helper-module-imports');
8
+ var errors = require('@lwc/errors');
9
+ var lineColumn = require('line-column');
10
+ var shared = require('@lwc/shared');
11
+
12
+ /*
13
+ * Copyright (c) 2023, salesforce.com, inc.
14
+ * All rights reserved.
15
+ * SPDX-License-Identifier: MIT
16
+ * For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/MIT
17
+ */
18
+ // This set is for attributes that have a camel cased property name
19
+ // For example, div.tabIndex.
20
+ // We do not want users to define @api properties with these names
21
+ // Because the template will never call them. It'll always call the camel
22
+ // cased version.
23
+ const AMBIGUOUS_PROP_SET = new Map([
24
+ ['bgcolor', 'bgColor'],
25
+ ['accesskey', 'accessKey'],
26
+ ['contenteditable', 'contentEditable'],
27
+ ['contextmenu', 'contextMenu'],
28
+ ['tabindex', 'tabIndex'],
29
+ ['maxlength', 'maxLength'],
30
+ ['maxvalue', 'maxValue'],
31
+ ]);
32
+ // This set is for attributes that can never be defined
33
+ // by users on their components.
34
+ // We throw for these.
35
+ const DISALLOWED_PROP_SET = new Set(['is', 'class', 'slot', 'style']);
36
+ const LWC_PACKAGE_ALIAS = 'lwc';
37
+ const LWC_PACKAGE_EXPORTS = {
38
+ BASE_COMPONENT: 'LightningElement',
39
+ API_DECORATOR: 'api',
40
+ TRACK_DECORATOR: 'track',
41
+ WIRE_DECORATOR: 'wire',
42
+ };
43
+ const LWC_COMPONENT_PROPERTIES = {
44
+ PUBLIC_PROPS: 'publicProps',
45
+ PUBLIC_METHODS: 'publicMethods',
46
+ WIRE: 'wire',
47
+ TRACK: 'track',
48
+ };
49
+ const DECORATOR_TYPES = {
50
+ PROPERTY: 'property',
51
+ GETTER: 'getter',
52
+ SETTER: 'setter',
53
+ METHOD: 'method',
54
+ };
55
+ const REGISTER_COMPONENT_ID = 'registerComponent';
56
+ const REGISTER_DECORATORS_ID = 'registerDecorators';
57
+ const TEMPLATE_KEY = 'tmpl';
58
+ const COMPONENT_NAME_KEY = 'sel';
59
+
60
+ /*
61
+ * Copyright (c) 2023, salesforce.com, inc.
62
+ * All rights reserved.
63
+ * SPDX-License-Identifier: MIT
64
+ * For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/MIT
65
+ */
66
+ function getBaseName(classPath) {
67
+ const ext = path.extname(classPath);
68
+ return path.basename(classPath, ext);
69
+ }
70
+ function importDefaultTemplate(path, state) {
71
+ const { filename } = state.file.opts;
72
+ const componentName = getBaseName(filename);
73
+ return helperModuleImports.addDefault(path, `./${componentName}.html`, {
74
+ nameHint: TEMPLATE_KEY,
75
+ });
76
+ }
77
+ function needsComponentRegistration(path) {
78
+ return ((path.isIdentifier() && path.node.name !== 'undefined' && path.node.name !== 'null') ||
79
+ path.isCallExpression() ||
80
+ path.isClassDeclaration() ||
81
+ path.isConditionalExpression());
82
+ }
83
+ function getComponentRegisteredName(t, state) {
84
+ const { namespace, name } = state.opts;
85
+ const componentName = namespace && name ? `${namespace}-${name}` : '';
86
+ return t.stringLiteral(componentName);
87
+ }
88
+ function component ({ types: t }) {
89
+ function createRegisterComponent(declarationPath, state) {
90
+ const registerComponentId = helperModuleImports.addNamed(declarationPath, REGISTER_COMPONENT_ID, LWC_PACKAGE_ALIAS);
91
+ const templateIdentifier = importDefaultTemplate(declarationPath, state);
92
+ const statementPath = declarationPath.getStatementParent();
93
+ const componentRegisteredName = getComponentRegisteredName(t, state);
94
+ let node = declarationPath.node;
95
+ if (declarationPath.isClassDeclaration()) {
96
+ const hasIdentifier = t.isIdentifier(node.id);
97
+ if (hasIdentifier) {
98
+ statementPath.insertBefore(node);
99
+ node = node.id;
100
+ }
101
+ else {
102
+ // if it does not have an id, we can treat it as a ClassExpression
103
+ t.toExpression(node);
104
+ }
105
+ }
106
+ return t.callExpression(registerComponentId, [
107
+ node,
108
+ t.objectExpression([
109
+ t.objectProperty(t.identifier(TEMPLATE_KEY), templateIdentifier),
110
+ t.objectProperty(t.identifier(COMPONENT_NAME_KEY), componentRegisteredName),
111
+ ]),
112
+ ]);
113
+ }
114
+ return {
115
+ ExportDefaultDeclaration(path, state) {
116
+ const implicitResolution = !state.opts.isExplicitImport;
117
+ if (implicitResolution) {
118
+ const declaration = path.get('declaration');
119
+ if (needsComponentRegistration(declaration)) {
120
+ declaration.replaceWith(createRegisterComponent(declaration, state));
121
+ }
122
+ }
123
+ },
124
+ };
125
+ }
126
+
127
+ /*
128
+ * Copyright (c) 2023, salesforce.com, inc.
129
+ * All rights reserved.
130
+ * SPDX-License-Identifier: MIT
131
+ * For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/MIT
132
+ */
133
+ function isClassMethod(classMethod, properties = {}) {
134
+ const { kind = 'method', name } = properties;
135
+ return (classMethod.isClassMethod({ kind }) &&
136
+ (!name || classMethod.get('key').isIdentifier({ name })) &&
137
+ (properties.static === undefined || classMethod.node.static === properties.static));
138
+ }
139
+ function isGetterClassMethod(classMethod, properties = {}) {
140
+ return isClassMethod(classMethod, {
141
+ kind: 'get',
142
+ name: properties.name,
143
+ static: properties.static,
144
+ });
145
+ }
146
+ function isSetterClassMethod(classMethod, properties = {}) {
147
+ return isClassMethod(classMethod, {
148
+ kind: 'set',
149
+ name: properties.name,
150
+ static: properties.static,
151
+ });
152
+ }
153
+ function getEngineImportsStatements(path) {
154
+ const programPath = path.isProgram()
155
+ ? path
156
+ : path.findParent((node) => node.isProgram());
157
+ return programPath.get('body').filter((node) => {
158
+ const source = node.get('source');
159
+ return node.isImportDeclaration() && source.isStringLiteral({ value: LWC_PACKAGE_ALIAS });
160
+ });
161
+ }
162
+ function getEngineImportSpecifiers(path) {
163
+ const imports = getEngineImportsStatements(path);
164
+ return (imports
165
+ // Flat-map the specifier list for each import statement
166
+ .flatMap((importStatement) => importStatement.get('specifiers'))
167
+ // Skip ImportDefaultSpecifier and ImportNamespaceSpecifier
168
+ .filter((specifier) => specifier.type === 'ImportSpecifier')
169
+ // Get the list of specifiers with their name
170
+ .map((specifier) => {
171
+ const imported = specifier.get('imported').node
172
+ .name;
173
+ return { name: imported, path: specifier };
174
+ }));
175
+ }
176
+ function normalizeFilename(source) {
177
+ return (
178
+ // TODO [#3444]: use `this.filename` to get the filename
179
+ (source.hub &&
180
+ source.hub.file &&
181
+ source.hub.file.opts &&
182
+ source.hub.file.opts.filename) ||
183
+ null);
184
+ }
185
+ function normalizeLocation(source) {
186
+ const location = (source.node && (source.node.loc || source.node._loc)) || null;
187
+ if (!location) {
188
+ return null;
189
+ }
190
+ const code = source.hub.getCode();
191
+ if (!code) {
192
+ return {
193
+ line: location.start.line,
194
+ column: location.start.column,
195
+ };
196
+ }
197
+ const lineFinder = lineColumn(code);
198
+ const startOffset = lineFinder.toIndex(location.start.line, location.start.column + 1);
199
+ const endOffset = lineFinder.toIndex(location.end.line, location.end.column) + 1;
200
+ const length = endOffset - startOffset;
201
+ return {
202
+ line: location.start.line,
203
+ column: location.start.column,
204
+ start: startOffset,
205
+ length,
206
+ };
207
+ }
208
+ function generateError(source, { errorInfo, messageArgs }) {
209
+ const message = errors.generateErrorMessage(errorInfo, messageArgs);
210
+ const error = source.buildCodeFrameError(message);
211
+ error.filename = normalizeFilename(source);
212
+ error.loc = normalizeLocation(source);
213
+ error.lwcCode = errorInfo && errorInfo.code;
214
+ return error;
215
+ }
216
+
217
+ /*
218
+ * Copyright (c) 2023, salesforce.com, inc.
219
+ * All rights reserved.
220
+ * SPDX-License-Identifier: MIT
221
+ * For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/MIT
222
+ */
223
+ const { API_DECORATOR: API_DECORATOR$2 } = LWC_PACKAGE_EXPORTS;
224
+ function isApiDecorator(decorator) {
225
+ return decorator.name === API_DECORATOR$2;
226
+ }
227
+
228
+ /*
229
+ * Copyright (c) 2023, salesforce.com, inc.
230
+ * All rights reserved.
231
+ * SPDX-License-Identifier: MIT
232
+ * For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/MIT
233
+ */
234
+ const { TRACK_DECORATOR: TRACK_DECORATOR$2 } = LWC_PACKAGE_EXPORTS;
235
+ function validateConflict(path, decorators) {
236
+ const isPublicFieldTracked = decorators.some((decorator) => decorator.name === TRACK_DECORATOR$2 &&
237
+ decorator.path.parentPath.node === path.parentPath.node);
238
+ if (isPublicFieldTracked) {
239
+ throw generateError(path, {
240
+ errorInfo: errors.DecoratorErrors.API_AND_TRACK_DECORATOR_CONFLICT,
241
+ });
242
+ }
243
+ }
244
+ function isBooleanPropDefaultTrue(property) {
245
+ const propertyValue = property.node.value;
246
+ return propertyValue && propertyValue.type === 'BooleanLiteral' && propertyValue.value;
247
+ }
248
+ function validatePropertyValue(property) {
249
+ if (isBooleanPropDefaultTrue(property)) {
250
+ throw generateError(property, {
251
+ errorInfo: errors.DecoratorErrors.INVALID_BOOLEAN_PUBLIC_PROPERTY,
252
+ });
253
+ }
254
+ }
255
+ function validatePropertyName(property) {
256
+ if (property.node.computed) {
257
+ throw generateError(property, {
258
+ errorInfo: errors.DecoratorErrors.PROPERTY_CANNOT_BE_COMPUTED,
259
+ });
260
+ }
261
+ const propertyName = property.get('key.name').node;
262
+ if (propertyName === 'part') {
263
+ throw generateError(property, {
264
+ errorInfo: errors.DecoratorErrors.PROPERTY_NAME_PART_IS_RESERVED,
265
+ messageArgs: [propertyName],
266
+ });
267
+ }
268
+ else if (propertyName.startsWith('on')) {
269
+ throw generateError(property, {
270
+ errorInfo: errors.DecoratorErrors.PROPERTY_NAME_CANNOT_START_WITH_ON,
271
+ messageArgs: [propertyName],
272
+ });
273
+ }
274
+ else if (propertyName.startsWith('data') && propertyName.length > 4) {
275
+ throw generateError(property, {
276
+ errorInfo: errors.DecoratorErrors.PROPERTY_NAME_CANNOT_START_WITH_DATA,
277
+ messageArgs: [propertyName],
278
+ });
279
+ }
280
+ else if (DISALLOWED_PROP_SET.has(propertyName)) {
281
+ throw generateError(property, {
282
+ errorInfo: errors.DecoratorErrors.PROPERTY_NAME_IS_RESERVED,
283
+ messageArgs: [propertyName],
284
+ });
285
+ }
286
+ else if (AMBIGUOUS_PROP_SET.has(propertyName)) {
287
+ const camelCased = AMBIGUOUS_PROP_SET.get(propertyName);
288
+ throw generateError(property, {
289
+ errorInfo: errors.DecoratorErrors.PROPERTY_NAME_IS_AMBIGUOUS,
290
+ messageArgs: [propertyName, camelCased],
291
+ });
292
+ }
293
+ }
294
+ function validateSingleApiDecoratorOnSetterGetterPair(decorators) {
295
+ // keep track of visited class methods
296
+ const visitedMethods = new Set();
297
+ decorators.forEach((decorator) => {
298
+ const { path, decoratedNodeType } = decorator;
299
+ // since we are validating get/set we only look at @api methods
300
+ if (isApiDecorator(decorator) &&
301
+ (decoratedNodeType === DECORATOR_TYPES.GETTER ||
302
+ decoratedNodeType === DECORATOR_TYPES.SETTER)) {
303
+ const methodPath = path.parentPath;
304
+ const methodName = methodPath.get('key.name').node;
305
+ if (visitedMethods.has(methodName)) {
306
+ throw generateError(methodPath, {
307
+ errorInfo: errors.DecoratorErrors.SINGLE_DECORATOR_ON_SETTER_GETTER_PAIR,
308
+ messageArgs: [methodName],
309
+ });
310
+ }
311
+ visitedMethods.add(methodName);
312
+ }
313
+ });
314
+ }
315
+ function validateUniqueness(decorators) {
316
+ const apiDecorators = decorators.filter(isApiDecorator);
317
+ for (let i = 0; i < apiDecorators.length; i++) {
318
+ const { path: currentPath, type: currentType } = apiDecorators[i];
319
+ const currentPropertyName = currentPath.parentPath.get('key.name').node;
320
+ for (let j = 0; j < apiDecorators.length; j++) {
321
+ const { path: comparePath, type: compareType } = apiDecorators[j];
322
+ const comparePropertyName = comparePath.parentPath.get('key.name')
323
+ .node;
324
+ // We will throw if the considered properties have the same name, and when their
325
+ // are not part of a pair of getter/setter.
326
+ const haveSameName = currentPropertyName === comparePropertyName;
327
+ const isDifferentProperty = currentPath !== comparePath;
328
+ const isGetterSetterPair = (currentType === DECORATOR_TYPES.GETTER &&
329
+ compareType === DECORATOR_TYPES.SETTER) ||
330
+ (currentType === DECORATOR_TYPES.SETTER && compareType === DECORATOR_TYPES.GETTER);
331
+ if (haveSameName && isDifferentProperty && !isGetterSetterPair) {
332
+ throw generateError(comparePath, {
333
+ errorInfo: errors.DecoratorErrors.DUPLICATE_API_PROPERTY,
334
+ messageArgs: [currentPropertyName],
335
+ });
336
+ }
337
+ }
338
+ }
339
+ }
340
+ function validate$3(decorators) {
341
+ const apiDecorators = decorators.filter(isApiDecorator);
342
+ if (apiDecorators.length === 0) {
343
+ return;
344
+ }
345
+ apiDecorators.forEach(({ path, decoratedNodeType }) => {
346
+ validateConflict(path, decorators);
347
+ if (decoratedNodeType !== DECORATOR_TYPES.METHOD) {
348
+ const property = path.parentPath;
349
+ validatePropertyName(property);
350
+ validatePropertyValue(property);
351
+ }
352
+ });
353
+ validateSingleApiDecoratorOnSetterGetterPair(decorators);
354
+ validateUniqueness(decorators);
355
+ }
356
+
357
+ const { PUBLIC_PROPS, PUBLIC_METHODS } = LWC_COMPONENT_PROPERTIES;
358
+ const PUBLIC_PROP_BIT_MASK = {
359
+ PROPERTY: 0,
360
+ GETTER: 1,
361
+ SETTER: 2,
362
+ };
363
+ function getPropertyBitmask(type) {
364
+ switch (type) {
365
+ case DECORATOR_TYPES.GETTER:
366
+ return PUBLIC_PROP_BIT_MASK.GETTER;
367
+ case DECORATOR_TYPES.SETTER:
368
+ return PUBLIC_PROP_BIT_MASK.SETTER;
369
+ default:
370
+ return PUBLIC_PROP_BIT_MASK.PROPERTY;
371
+ }
372
+ }
373
+ function getSiblingGetSetPairType(propertyName, type, classBodyItems) {
374
+ const siblingKind = type === DECORATOR_TYPES.GETTER ? 'set' : 'get';
375
+ const siblingNode = classBodyItems.find((classBodyItem) => {
376
+ const isClassMethod = classBodyItem.isClassMethod({ kind: siblingKind });
377
+ const isSamePropertyName = classBodyItem.node.key.name ===
378
+ propertyName;
379
+ return isClassMethod && isSamePropertyName;
380
+ });
381
+ if (siblingNode) {
382
+ return siblingKind === 'get' ? DECORATOR_TYPES.GETTER : DECORATOR_TYPES.SETTER;
383
+ }
384
+ }
385
+ function computePublicPropsConfig(publicPropertyMetas, classBodyItems) {
386
+ return publicPropertyMetas.reduce((acc, { propertyName, decoratedNodeType }) => {
387
+ if (!(propertyName in acc)) {
388
+ acc[propertyName] = {};
389
+ }
390
+ acc[propertyName].config |= getPropertyBitmask(decoratedNodeType);
391
+ if (decoratedNodeType === DECORATOR_TYPES.GETTER ||
392
+ decoratedNodeType === DECORATOR_TYPES.SETTER) {
393
+ // With the latest decorator spec, only one of the getter/setter pair needs a decorator.
394
+ // We need to add the proper bitmask for the sibling getter/setter if it exists.
395
+ const pairType = getSiblingGetSetPairType(propertyName, decoratedNodeType, classBodyItems);
396
+ if (pairType) {
397
+ acc[propertyName].config |= getPropertyBitmask(pairType);
398
+ }
399
+ }
400
+ return acc;
401
+ }, {});
402
+ }
403
+ function transform$2(t, decoratorMetas, classBodyItems) {
404
+ const objectProperties = [];
405
+ const apiDecoratorMetas = decoratorMetas.filter(isApiDecorator);
406
+ const publicPropertyMetas = apiDecoratorMetas.filter(({ decoratedNodeType }) => decoratedNodeType !== DECORATOR_TYPES.METHOD);
407
+ if (publicPropertyMetas.length) {
408
+ const propsConfig = computePublicPropsConfig(publicPropertyMetas, classBodyItems);
409
+ objectProperties.push(t.objectProperty(t.identifier(PUBLIC_PROPS), t.valueToNode(propsConfig)));
410
+ }
411
+ const publicMethodMetas = apiDecoratorMetas.filter(({ decoratedNodeType }) => decoratedNodeType === DECORATOR_TYPES.METHOD);
412
+ if (publicMethodMetas.length) {
413
+ const methodNames = publicMethodMetas.map(({ propertyName }) => propertyName);
414
+ objectProperties.push(t.objectProperty(t.identifier(PUBLIC_METHODS), t.valueToNode(methodNames)));
415
+ }
416
+ return objectProperties;
417
+ }
418
+
419
+ /*
420
+ * Copyright (c) 2023, salesforce.com, inc.
421
+ * All rights reserved.
422
+ * SPDX-License-Identifier: MIT
423
+ * For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/MIT
424
+ */
425
+ const { API_DECORATOR: API_DECORATOR$1 } = LWC_PACKAGE_EXPORTS;
426
+ var api = {
427
+ name: API_DECORATOR$1,
428
+ validate: validate$3,
429
+ transform: transform$2,
430
+ };
431
+
432
+ /*
433
+ * Copyright (c) 2023, salesforce.com, inc.
434
+ * All rights reserved.
435
+ * SPDX-License-Identifier: MIT
436
+ * For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/MIT
437
+ */
438
+ const { WIRE_DECORATOR: WIRE_DECORATOR$2 } = LWC_PACKAGE_EXPORTS;
439
+ function isWireDecorator(decorator) {
440
+ return decorator.name === WIRE_DECORATOR$2;
441
+ }
442
+
443
+ const { TRACK_DECORATOR: TRACK_DECORATOR$1, WIRE_DECORATOR: WIRE_DECORATOR$1, API_DECORATOR } = LWC_PACKAGE_EXPORTS;
444
+ function validateWireParameters(path) {
445
+ const [id, config] = path.get('expression.arguments');
446
+ if (!id) {
447
+ throw generateError(path, {
448
+ errorInfo: errors.DecoratorErrors.ADAPTER_SHOULD_BE_FIRST_PARAMETER,
449
+ });
450
+ }
451
+ const isIdentifier = id.isIdentifier();
452
+ const isMemberExpression = id.isMemberExpression();
453
+ if (!isIdentifier && !isMemberExpression) {
454
+ throw generateError(id, {
455
+ errorInfo: errors.DecoratorErrors.FUNCTION_IDENTIFIER_SHOULD_BE_FIRST_PARAMETER,
456
+ });
457
+ }
458
+ if (id.isMemberExpression({ computed: true })) {
459
+ throw generateError(id, {
460
+ errorInfo: errors.DecoratorErrors.FUNCTION_IDENTIFIER_CANNOT_HAVE_COMPUTED_PROPS,
461
+ });
462
+ }
463
+ // TODO [#3444]: improve member expression computed typechecking
464
+ // @ts-ignore
465
+ if (isMemberExpression && !id.get('object').isIdentifier()) {
466
+ throw generateError(id, {
467
+ errorInfo: errors.DecoratorErrors.FUNCTION_IDENTIFIER_CANNOT_HAVE_NESTED_MEMBER_EXRESSIONS,
468
+ });
469
+ }
470
+ // TODO [#3444]: improve member expression computed typechecking
471
+ // Ensure wire adapter is imported (check for member expression or identifier)
472
+ // @ts-ignore
473
+ const wireBinding = isMemberExpression ? id.node.object.name : id.node.name;
474
+ if (!path.scope.getBinding(wireBinding)) {
475
+ throw generateError(id, {
476
+ errorInfo: errors.DecoratorErrors.WIRE_ADAPTER_SHOULD_BE_IMPORTED,
477
+ messageArgs: [id.node.name],
478
+ });
479
+ }
480
+ // ensure wire adapter is a first parameter
481
+ if (wireBinding &&
482
+ !path.scope.getBinding(wireBinding).path.isImportSpecifier() &&
483
+ !path.scope.getBinding(wireBinding).path.isImportDefaultSpecifier()) {
484
+ throw generateError(id, {
485
+ errorInfo: errors.DecoratorErrors.IMPORTED_FUNCTION_IDENTIFIER_SHOULD_BE_FIRST_PARAMETER,
486
+ });
487
+ }
488
+ if (config && !config.isObjectExpression()) {
489
+ throw generateError(config, {
490
+ errorInfo: errors.DecoratorErrors.CONFIG_OBJECT_SHOULD_BE_SECOND_PARAMETER,
491
+ });
492
+ }
493
+ }
494
+ function validateUsageWithOtherDecorators(path, decorators) {
495
+ decorators.forEach((decorator) => {
496
+ if (path !== decorator.path &&
497
+ decorator.name === WIRE_DECORATOR$1 &&
498
+ decorator.path.parentPath.node === path.parentPath.node) {
499
+ throw generateError(path, {
500
+ errorInfo: errors.DecoratorErrors.ONE_WIRE_DECORATOR_ALLOWED,
501
+ });
502
+ }
503
+ if ((decorator.name === API_DECORATOR || decorator.name === TRACK_DECORATOR$1) &&
504
+ decorator.path.parentPath.node === path.parentPath.node) {
505
+ throw generateError(path, {
506
+ errorInfo: errors.DecoratorErrors.CONFLICT_WITH_ANOTHER_DECORATOR,
507
+ messageArgs: [decorator.name],
508
+ });
509
+ }
510
+ });
511
+ }
512
+ function validate$2(decorators) {
513
+ decorators.filter(isWireDecorator).forEach(({ path }) => {
514
+ validateUsageWithOtherDecorators(path, decorators);
515
+ validateWireParameters(path);
516
+ });
517
+ }
518
+
519
+ const WIRE_PARAM_PREFIX = '$';
520
+ const WIRE_CONFIG_ARG_NAME = '$cmp';
521
+ function isObservedProperty(configProperty) {
522
+ const propertyValue = configProperty.get('value');
523
+ return (propertyValue.isStringLiteral() && propertyValue.node.value.startsWith(WIRE_PARAM_PREFIX));
524
+ }
525
+ function getWiredStatic(wireConfig) {
526
+ return wireConfig
527
+ .get('properties')
528
+ .filter((property) => !isObservedProperty(property))
529
+ .map((path) => path.node);
530
+ }
531
+ function getWiredParams(t, wireConfig) {
532
+ return wireConfig
533
+ .get('properties')
534
+ .filter((property) => isObservedProperty(property))
535
+ .map((path) => {
536
+ // Need to clone deep the observed property to remove the param prefix
537
+ const clonedProperty = t.cloneDeep(path.node);
538
+ clonedProperty.value.value = clonedProperty.value.value.slice(1);
539
+ return clonedProperty;
540
+ });
541
+ }
542
+ function getGeneratedConfig(t, wiredValue) {
543
+ let counter = 0;
544
+ const configBlockBody = [];
545
+ const configProps = [];
546
+ const generateParameterConfigValue = (memberExprPaths) => {
547
+ // Note: When memberExprPaths ($foo.bar) has an invalid identifier (eg: foo..bar, foo.bar[3])
548
+ // it should (ideally) resolve in a compilation error during validation phase.
549
+ // This is not possible due that platform components may have a param definition which is invalid
550
+ // but passes compilation, and throwing at compile time would break such components.
551
+ // In such cases where the param does not have proper notation, the config generated will use the bracket
552
+ // notation to match the current behavior (that most likely end up resolving that param as undefined).
553
+ const isInvalidMemberExpr = memberExprPaths.some((maybeIdentifier) => !(t.isValidES3Identifier(maybeIdentifier) && maybeIdentifier.length > 0));
554
+ const memberExprPropertyGen = !isInvalidMemberExpr
555
+ ? t.identifier
556
+ : t.StringLiteral;
557
+ if (memberExprPaths.length === 1) {
558
+ return {
559
+ configValueExpression: t.memberExpression(t.identifier(WIRE_CONFIG_ARG_NAME), memberExprPropertyGen(memberExprPaths[0])),
560
+ };
561
+ }
562
+ const varName = 'v' + ++counter;
563
+ const varDeclaration = t.variableDeclaration('let', [
564
+ t.variableDeclarator(t.identifier(varName), t.memberExpression(t.identifier(WIRE_CONFIG_ARG_NAME), memberExprPropertyGen(memberExprPaths[0]), isInvalidMemberExpr)),
565
+ ]);
566
+ // Results in: v != null && ... (v = v.i) != null && ... (v = v.(n-1)) != null
567
+ let conditionTest = t.binaryExpression('!=', t.identifier(varName), t.nullLiteral());
568
+ for (let i = 1, n = memberExprPaths.length; i < n - 1; i++) {
569
+ const nextPropValue = t.assignmentExpression('=', t.identifier(varName), t.memberExpression(t.identifier(varName), memberExprPropertyGen(memberExprPaths[i]), isInvalidMemberExpr));
570
+ conditionTest = t.logicalExpression('&&', conditionTest, t.binaryExpression('!=', nextPropValue, t.nullLiteral()));
571
+ }
572
+ // conditionTest ? v.n : undefined
573
+ const configValueExpression = t.conditionalExpression(conditionTest, t.memberExpression(t.identifier(varName), memberExprPropertyGen(memberExprPaths[memberExprPaths.length - 1]), isInvalidMemberExpr), t.identifier('undefined'));
574
+ return {
575
+ varDeclaration,
576
+ configValueExpression,
577
+ };
578
+ };
579
+ if (wiredValue.static) {
580
+ Array.prototype.push.apply(configProps, wiredValue.static);
581
+ }
582
+ if (wiredValue.params) {
583
+ wiredValue.params.forEach((param) => {
584
+ const memberExprPaths = param.value.value.split('.');
585
+ const paramConfigValue = generateParameterConfigValue(memberExprPaths);
586
+ configProps.push(t.objectProperty(param.key, paramConfigValue.configValueExpression));
587
+ if (paramConfigValue.varDeclaration) {
588
+ configBlockBody.push(paramConfigValue.varDeclaration);
589
+ }
590
+ });
591
+ }
592
+ configBlockBody.push(t.returnStatement(t.objectExpression(configProps)));
593
+ const fnExpression = t.functionExpression(null, [t.identifier(WIRE_CONFIG_ARG_NAME)], t.blockStatement(configBlockBody));
594
+ return t.objectProperty(t.identifier('config'), fnExpression);
595
+ }
596
+ function buildWireConfigValue(t, wiredValues) {
597
+ return t.objectExpression(wiredValues.map((wiredValue) => {
598
+ const wireConfig = [];
599
+ if (wiredValue.adapter) {
600
+ wireConfig.push(t.objectProperty(t.identifier('adapter'), wiredValue.adapter.expression));
601
+ }
602
+ if (wiredValue.params) {
603
+ const dynamicParamNames = wiredValue.params.map((p) => {
604
+ return t.stringLiteral(t.isIdentifier(p.key) ? p.key.name : p.key.value);
605
+ });
606
+ wireConfig.push(t.objectProperty(t.identifier('dynamic'), t.arrayExpression(dynamicParamNames)));
607
+ }
608
+ if (wiredValue.isClassMethod) {
609
+ wireConfig.push(t.objectProperty(t.identifier('method'), t.numericLiteral(1)));
610
+ }
611
+ wireConfig.push(getGeneratedConfig(t, wiredValue));
612
+ return t.objectProperty(t.identifier(wiredValue.propertyName), t.objectExpression(wireConfig));
613
+ }));
614
+ }
615
+ const SUPPORTED_VALUE_TO_TYPE_MAP = {
616
+ StringLiteral: 'string',
617
+ NumericLiteral: 'number',
618
+ BooleanLiteral: 'boolean',
619
+ };
620
+ const scopedReferenceLookup = (scope) => (name) => {
621
+ const binding = scope.getBinding(name);
622
+ let type;
623
+ let value;
624
+ if (binding) {
625
+ if (binding.kind === 'module') {
626
+ // Resolves module import to the name of the module imported
627
+ // e.g. import { foo } from 'bar' gives value 'bar' for `name == 'foo'
628
+ const parentPathNode = binding.path.parentPath.node;
629
+ if (parentPathNode && parentPathNode.source) {
630
+ type = 'module';
631
+ value = parentPathNode.source.value;
632
+ }
633
+ }
634
+ else if (binding.kind === 'const') {
635
+ // Resolves `const foo = 'text';` references to value 'text', where `name == 'foo'`
636
+ const init = binding.path.node.init;
637
+ if (init &&
638
+ SUPPORTED_VALUE_TO_TYPE_MAP[init.type]) {
639
+ type =
640
+ SUPPORTED_VALUE_TO_TYPE_MAP[init.type];
641
+ value = init
642
+ .value;
643
+ }
644
+ }
645
+ }
646
+ return {
647
+ type,
648
+ value,
649
+ };
650
+ };
651
+ function transform$1(t, decoratorMetas) {
652
+ const objectProperties = [];
653
+ const wiredValues = decoratorMetas.filter(isWireDecorator).map(({ path }) => {
654
+ const [id, config] = path.get('expression.arguments');
655
+ const propertyName = path.parentPath.get('key.name').node;
656
+ const isClassMethod = path.parentPath.isClassMethod({
657
+ kind: 'method',
658
+ });
659
+ const wiredValue = {
660
+ propertyName,
661
+ isClassMethod,
662
+ };
663
+ if (config) {
664
+ wiredValue.static = getWiredStatic(config);
665
+ wiredValue.params = getWiredParams(t, config);
666
+ }
667
+ const referenceLookup = scopedReferenceLookup(path.scope);
668
+ const isMemberExpression = id.isMemberExpression();
669
+ const isIdentifier = id.isIdentifier();
670
+ if (isIdentifier || isMemberExpression) {
671
+ const referenceName = isMemberExpression ? id.node.object.name : id.node.name;
672
+ const reference = referenceLookup(referenceName);
673
+ wiredValue.adapter = {
674
+ name: referenceName,
675
+ expression: t.cloneDeep(id.node),
676
+ reference: reference.type === 'module' ? reference.value : undefined,
677
+ };
678
+ }
679
+ return wiredValue;
680
+ });
681
+ if (wiredValues.length) {
682
+ objectProperties.push(t.objectProperty(t.identifier(LWC_COMPONENT_PROPERTIES.WIRE), buildWireConfigValue(t, wiredValues)));
683
+ }
684
+ return objectProperties;
685
+ }
686
+
687
+ /*
688
+ * Copyright (c) 2023, salesforce.com, inc.
689
+ * All rights reserved.
690
+ * SPDX-License-Identifier: MIT
691
+ * For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/MIT
692
+ */
693
+ const { WIRE_DECORATOR } = LWC_PACKAGE_EXPORTS;
694
+ var wire = {
695
+ name: WIRE_DECORATOR,
696
+ validate: validate$2,
697
+ transform: transform$1,
698
+ };
699
+
700
+ /*
701
+ * Copyright (c) 2023, salesforce.com, inc.
702
+ * All rights reserved.
703
+ * SPDX-License-Identifier: MIT
704
+ * For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/MIT
705
+ */
706
+ const { TRACK_DECORATOR } = LWC_PACKAGE_EXPORTS;
707
+ const TRACK_PROPERTY_VALUE = 1;
708
+ function isTrackDecorator(decorator) {
709
+ return decorator.name === TRACK_DECORATOR;
710
+ }
711
+ function validate$1(decorators) {
712
+ decorators.filter(isTrackDecorator).forEach(({ path }) => {
713
+ if (!path.parentPath.isClassProperty()) {
714
+ throw generateError(path, {
715
+ errorInfo: errors.DecoratorErrors.TRACK_ONLY_ALLOWED_ON_CLASS_PROPERTIES,
716
+ });
717
+ }
718
+ });
719
+ }
720
+ function transform(t, decoratorMetas) {
721
+ const objectProperties = [];
722
+ const trackDecoratorMetas = decoratorMetas.filter(isTrackDecorator);
723
+ if (trackDecoratorMetas.length) {
724
+ const config = trackDecoratorMetas.reduce((acc, meta) => {
725
+ acc[meta.propertyName] = TRACK_PROPERTY_VALUE;
726
+ return acc;
727
+ }, {});
728
+ objectProperties.push(t.objectProperty(t.identifier(LWC_COMPONENT_PROPERTIES.TRACK), t.valueToNode(config)));
729
+ }
730
+ return objectProperties;
731
+ }
732
+ var track = {
733
+ name: TRACK_DECORATOR,
734
+ transform,
735
+ validate: validate$1,
736
+ };
737
+
738
+ const DECORATOR_TRANSFORMS = [api, wire, track];
739
+ const AVAILABLE_DECORATORS = DECORATOR_TRANSFORMS.map((transform) => transform.name).join(', ');
740
+ function isLwcDecoratorName(name) {
741
+ return DECORATOR_TRANSFORMS.some((transform) => transform.name === name);
742
+ }
743
+ /** Returns a list of all the references to an identifier */
744
+ function getReferences(identifier) {
745
+ return identifier.scope.getBinding(identifier.node.name).referencePaths;
746
+ }
747
+ /** Returns the type of decorator depdending on the property or method if get applied to */
748
+ function getDecoratedNodeType(decoratorPath) {
749
+ const propertyOrMethod = decoratorPath.parentPath;
750
+ if (isClassMethod(propertyOrMethod)) {
751
+ return DECORATOR_TYPES.METHOD;
752
+ }
753
+ else if (isGetterClassMethod(propertyOrMethod)) {
754
+ return DECORATOR_TYPES.GETTER;
755
+ }
756
+ else if (isSetterClassMethod(propertyOrMethod)) {
757
+ return DECORATOR_TYPES.SETTER;
758
+ }
759
+ else if (propertyOrMethod.isClassProperty()) {
760
+ return DECORATOR_TYPES.PROPERTY;
761
+ }
762
+ else {
763
+ throw generateError(propertyOrMethod, {
764
+ errorInfo: errors.DecoratorErrors.INVALID_DECORATOR_TYPE,
765
+ });
766
+ }
767
+ }
768
+ function validateImportedLwcDecoratorUsage(engineImportSpecifiers) {
769
+ engineImportSpecifiers
770
+ .filter(({ name }) => isLwcDecoratorName(name))
771
+ .reduce((acc, { name, path }) => {
772
+ // Get a list of all the local references
773
+ const local = path.get('imported');
774
+ const references = getReferences(local).map((reference) => ({
775
+ name,
776
+ reference,
777
+ }));
778
+ return [...acc, ...references];
779
+ }, [])
780
+ .forEach(({ name, reference }) => {
781
+ // Get the decorator from the identifier
782
+ // If the the decorator is:
783
+ // - an identifier @track : the decorator is the parent of the identifier
784
+ // - a call expression @wire("foo") : the decorator is the grand-parent of the identifier
785
+ const decorator = reference.parentPath.isDecorator()
786
+ ? reference.parentPath
787
+ : reference.parentPath.parentPath;
788
+ if (!decorator.isDecorator()) {
789
+ throw generateError(decorator, {
790
+ errorInfo: errors.DecoratorErrors.IS_NOT_DECORATOR,
791
+ messageArgs: [name],
792
+ });
793
+ }
794
+ const propertyOrMethod = decorator.parentPath;
795
+ if (!propertyOrMethod.isClassProperty() && !propertyOrMethod.isClassMethod()) {
796
+ throw generateError(propertyOrMethod, {
797
+ errorInfo: errors.DecoratorErrors.IS_NOT_CLASS_PROPERTY_OR_CLASS_METHOD,
798
+ messageArgs: [name],
799
+ });
800
+ }
801
+ });
802
+ }
803
+ function isImportedFromLwcSource(decoratorBinding) {
804
+ const bindingPath = decoratorBinding.path;
805
+ return (bindingPath.isImportSpecifier() &&
806
+ bindingPath.parent.source.value === 'lwc');
807
+ }
808
+ /** Validate the usage of decorator by calling each validation function */
809
+ function validate(decorators) {
810
+ for (const { name, path } of decorators) {
811
+ const binding = path.scope.getBinding(name);
812
+ if (binding === undefined || !isImportedFromLwcSource(binding)) {
813
+ throw generateInvalidDecoratorError(path);
814
+ }
815
+ }
816
+ DECORATOR_TRANSFORMS.forEach(({ validate }) => validate(decorators));
817
+ }
818
+ /** Remove import specifiers. It also removes the import statement if the specifier list becomes empty */
819
+ function removeImportedDecoratorSpecifiers(engineImportSpecifiers) {
820
+ engineImportSpecifiers
821
+ .filter(({ name }) => isLwcDecoratorName(name))
822
+ .forEach(({ path }) => {
823
+ const importStatement = path.parentPath;
824
+ path.remove();
825
+ if (importStatement.get('specifiers').length === 0) {
826
+ importStatement.remove();
827
+ }
828
+ });
829
+ }
830
+ function generateInvalidDecoratorError(path) {
831
+ const expressionPath = path.get('expression');
832
+ const { node } = path;
833
+ const { expression } = node;
834
+ let name;
835
+ if (expressionPath.isIdentifier()) {
836
+ name = expression.name;
837
+ }
838
+ else if (expressionPath.isCallExpression()) {
839
+ name = expression.callee.name;
840
+ }
841
+ if (name) {
842
+ return generateError(path.parentPath, {
843
+ errorInfo: errors.DecoratorErrors.INVALID_DECORATOR_WITH_NAME,
844
+ messageArgs: [name, AVAILABLE_DECORATORS, LWC_PACKAGE_ALIAS],
845
+ });
846
+ }
847
+ else {
848
+ return generateError(path.parentPath, {
849
+ errorInfo: errors.DecoratorErrors.INVALID_DECORATOR,
850
+ messageArgs: [AVAILABLE_DECORATORS, LWC_PACKAGE_ALIAS],
851
+ });
852
+ }
853
+ }
854
+ function collectDecoratorPaths(bodyItems) {
855
+ return bodyItems.reduce((acc, bodyItem) => {
856
+ const decorators = bodyItem.get('decorators');
857
+ if (decorators && decorators.length) {
858
+ acc.push(...decorators);
859
+ }
860
+ return acc;
861
+ }, []);
862
+ }
863
+ function getDecoratorMetadata(decoratorPath) {
864
+ const expressionPath = decoratorPath.get('expression');
865
+ let name;
866
+ if (expressionPath.isIdentifier()) {
867
+ name = expressionPath.node.name;
868
+ }
869
+ else if (expressionPath.isCallExpression()) {
870
+ name = expressionPath.node.callee.name;
871
+ }
872
+ else {
873
+ throw generateInvalidDecoratorError(decoratorPath);
874
+ }
875
+ const propertyName = decoratorPath.parent.key.name;
876
+ const decoratedNodeType = getDecoratedNodeType(decoratorPath);
877
+ return {
878
+ name,
879
+ propertyName,
880
+ path: decoratorPath,
881
+ decoratedNodeType,
882
+ };
883
+ }
884
+ function getMetadataObjectPropertyList(t, decoratorMetas, classBodyItems) {
885
+ const list = [
886
+ ...api.transform(t, decoratorMetas, classBodyItems),
887
+ ...track.transform(t, decoratorMetas),
888
+ ...wire.transform(t, decoratorMetas),
889
+ ];
890
+ const fieldNames = classBodyItems
891
+ .filter((field) => field.isClassProperty({ computed: false, static: false }))
892
+ .filter((field) => !field.node.decorators)
893
+ .map((field) => field.node.key.name);
894
+ if (fieldNames.length) {
895
+ list.push(t.objectProperty(t.identifier('fields'), t.valueToNode(fieldNames)));
896
+ }
897
+ return list;
898
+ }
899
+ function decorators({ types: t }) {
900
+ function createRegisterDecoratorsCallExpression(path, classExpression, props) {
901
+ const id = helperModuleImports.addNamed(path, REGISTER_DECORATORS_ID, LWC_PACKAGE_ALIAS);
902
+ return t.callExpression(id, [classExpression, t.objectExpression(props)]);
903
+ }
904
+ // Babel reinvokes visitors for node reinsertion so we use this to avoid an infinite loop.
905
+ const visitedClasses = new WeakSet();
906
+ return {
907
+ Class(path) {
908
+ const { node } = path;
909
+ if (visitedClasses.has(node)) {
910
+ return;
911
+ }
912
+ visitedClasses.add(node);
913
+ const classBodyItems = path.get('body.body');
914
+ if (classBodyItems.length === 0) {
915
+ return;
916
+ }
917
+ const decoratorPaths = collectDecoratorPaths(classBodyItems);
918
+ const decoratorMetas = decoratorPaths.map(getDecoratorMetadata);
919
+ validate(decoratorMetas);
920
+ const metaPropertyList = getMetadataObjectPropertyList(t, decoratorMetas, classBodyItems);
921
+ if (metaPropertyList.length === 0) {
922
+ return;
923
+ }
924
+ decoratorPaths.forEach((path) => path.remove());
925
+ const isAnonymousClassDeclaration = path.isClassDeclaration() && !path.get('id').isIdentifier();
926
+ const shouldTransformAsClassExpression = path.isClassExpression() || isAnonymousClassDeclaration;
927
+ if (shouldTransformAsClassExpression) {
928
+ // Example:
929
+ // export default class extends LightningElement {}
930
+ // Output:
931
+ // export default registerDecorators(class extends LightningElement {});
932
+ // if it does not have an id, we can treat it as a ClassExpression
933
+ const classExpression = t.toExpression(node);
934
+ path.replaceWith(createRegisterDecoratorsCallExpression(path, classExpression, metaPropertyList));
935
+ }
936
+ else {
937
+ // Example: export default class NamedClass extends LightningElement {}
938
+ // Output:
939
+ // export default class NamedClass extends LightningElement {}
940
+ // registerDecorators(NamedClass);
941
+ // Note: This will be further transformed
942
+ const statementPath = path.getStatementParent();
943
+ statementPath.insertAfter(t.expressionStatement(createRegisterDecoratorsCallExpression(path, node.id, metaPropertyList)));
944
+ }
945
+ },
946
+ };
947
+ }
948
+
949
+ /*
950
+ * Copyright (c) 2023, salesforce.com, inc.
951
+ * All rights reserved.
952
+ * SPDX-License-Identifier: MIT
953
+ * For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/MIT
954
+ */
955
+ function defaultImport(t, specifiers) {
956
+ const defaultImport = specifiers.find((s) => t.isImportDefaultSpecifier(s));
957
+ return defaultImport && defaultImport.local.name;
958
+ }
959
+ function dedupeImports ({ types: t }) {
960
+ return function (path) {
961
+ const body = path.get('body');
962
+ const importStatements = body.filter((s) => s.isImportDeclaration());
963
+ const visited = new Map();
964
+ importStatements.forEach((importPath) => {
965
+ const sourceLiteral = importPath.node.source;
966
+ // If the import is of the type import * as X, just ignore it since we can't dedupe
967
+ if (importPath.node.specifiers.some((_) => t.isImportNamespaceSpecifier(_))) {
968
+ return;
969
+ }
970
+ // If we have seen the same source, we will try to dedupe it
971
+ if (visited.has(sourceLiteral.value)) {
972
+ const visitedImport = visited.get(sourceLiteral.value);
973
+ const visitedSpecifiers = visitedImport.node.specifiers;
974
+ const visitedDefaultImport = defaultImport(t, visitedSpecifiers);
975
+ // We merge all the named imports unless is a default with the same name
976
+ let canImportBeRemoved = true;
977
+ importPath.node.specifiers.forEach((s) => {
978
+ if (visitedDefaultImport && t.isImportDefaultSpecifier(s)) {
979
+ if (visitedDefaultImport !== s.local.name) {
980
+ canImportBeRemoved = false;
981
+ }
982
+ }
983
+ else {
984
+ visitedSpecifiers.push(s);
985
+ }
986
+ });
987
+ if (canImportBeRemoved) {
988
+ importPath.remove();
989
+ }
990
+ // We need to sort the imports due to a bug in babel where default must be first
991
+ visitedSpecifiers.sort((a) => (t.isImportDefaultSpecifier(a) ? -1 : 1));
992
+ }
993
+ else {
994
+ visited.set(sourceLiteral.value, importPath);
995
+ }
996
+ });
997
+ };
998
+ }
999
+
1000
+ function getImportSource(path) {
1001
+ return path.parentPath.get('arguments.0');
1002
+ }
1003
+ function validateImport(sourcePath) {
1004
+ if (!sourcePath.isStringLiteral()) {
1005
+ throw generateError(sourcePath, {
1006
+ errorInfo: errors.LWCClassErrors.INVALID_DYNAMIC_IMPORT_SOURCE_STRICT,
1007
+ messageArgs: [String(sourcePath)],
1008
+ });
1009
+ }
1010
+ }
1011
+ /*
1012
+ * Expected API for this plugin:
1013
+ * { dynamicImports: { loader: string, strictSpecifier: boolean } }
1014
+ */
1015
+ function dynamicImports () {
1016
+ function getLoaderRef(path, loaderName, state) {
1017
+ if (!state.loaderRef) {
1018
+ state.loaderRef = helperModuleImports.addNamed(path, 'load', loaderName);
1019
+ }
1020
+ return state.loaderRef;
1021
+ }
1022
+ function addDynamicImportDependency(dependency, state) {
1023
+ // TODO [#3444]: state.dynamicImports seems unused and can probably be deleted
1024
+ if (!state.dynamicImports) {
1025
+ state.dynamicImports = [];
1026
+ }
1027
+ if (!state.dynamicImports.includes(dependency)) {
1028
+ state.dynamicImports.push(dependency);
1029
+ }
1030
+ }
1031
+ return {
1032
+ Import(path, state) {
1033
+ const { dynamicImports } = state.opts;
1034
+ if (!dynamicImports) {
1035
+ return;
1036
+ }
1037
+ const { loader, strictSpecifier } = dynamicImports;
1038
+ const sourcePath = getImportSource(path);
1039
+ if (strictSpecifier) {
1040
+ validateImport(sourcePath);
1041
+ }
1042
+ if (loader) {
1043
+ const loaderId = getLoaderRef(path, loader, state);
1044
+ path.replaceWith(loaderId);
1045
+ }
1046
+ if (sourcePath.isStringLiteral()) {
1047
+ addDynamicImportDependency(sourcePath.node.value, state);
1048
+ }
1049
+ },
1050
+ };
1051
+ }
1052
+
1053
+ /*
1054
+ * Copyright (c) 2023, salesforce.com, inc.
1055
+ * All rights reserved.
1056
+ * SPDX-License-Identifier: MIT
1057
+ * For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/MIT
1058
+ */
1059
+ function scopeCssImports ({ types: t }, path) {
1060
+ const programPath = path.isProgram() ? path : path.findParent((node) => node.isProgram());
1061
+ programPath.get('body').forEach((node) => {
1062
+ if (node.isImportDeclaration()) {
1063
+ const source = node.get('source');
1064
+ if (source.type === 'StringLiteral' && source.node.value.endsWith('.scoped.css')) {
1065
+ source.replaceWith(t.stringLiteral(source.node.value + '?scoped=true'));
1066
+ }
1067
+ }
1068
+ });
1069
+ }
1070
+
1071
+ function compilerVersionNumber({ types: t }) {
1072
+ return {
1073
+ ClassBody(path) {
1074
+ if (path.parent.superClass === null) {
1075
+ // Components *must* extend from either LightningElement or some other superclass (e.g. a mixin).
1076
+ // We can skip classes without a superclass to avoid adding unnecessary comments.
1077
+ return;
1078
+ }
1079
+ // If the class body is empty, we want an inner comment. Otherwise we want it after the last child
1080
+ // of the class body. In either case, we want it right before the `}` at the end of the function body.
1081
+ if (path.node.body.length > 0) {
1082
+ // E.g. `class Foo extends Lightning Element { /*LWC compiler v1.2.3*/ }`
1083
+ t.addComment(path.node.body[path.node.body.length - 1], 'trailing', shared.LWC_VERSION_COMMENT,
1084
+ /* line */ false);
1085
+ }
1086
+ else {
1087
+ // E.g. `class Foo extends Lightning Element { bar = 'baz'; /*LWC compiler v1.2.3*/ }`
1088
+ t.addComment(path.node, 'inner', shared.LWC_VERSION_COMMENT, /* line */ false);
1089
+ }
1090
+ },
1091
+ };
1092
+ }
1093
+
1094
+ /*
1095
+ * Copyright (c) 2023, salesforce.com, inc.
1096
+ * All rights reserved.
1097
+ * SPDX-License-Identifier: MIT
1098
+ * For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/MIT
1099
+ */
1100
+ /**
1101
+ * The transform is done in 2 passes:
1102
+ * - First, apply in a single AST traversal the decorators and the component transformation.
1103
+ * - Then, in a second path transform class properties using the official babel plugin "babel-plugin-transform-class-properties".
1104
+ */
1105
+ function LwcClassTransform(api) {
1106
+ const { ExportDefaultDeclaration: transformCreateRegisterComponent } = component(api);
1107
+ const { Class: transformDecorators } = decorators(api);
1108
+ const { Import: transformDynamicImports } = dynamicImports();
1109
+ const { ClassBody: addCompilerVersionNumber } = compilerVersionNumber(api);
1110
+ return {
1111
+ manipulateOptions(opts, parserOpts) {
1112
+ parserOpts.plugins.push('classProperties', [
1113
+ 'decorators',
1114
+ { decoratorsBeforeExport: true },
1115
+ ]);
1116
+ },
1117
+ visitor: {
1118
+ // The LWC babel plugin is incompatible with other plugins. To get around this, we run the LWC babel plugin
1119
+ // first by running all its traversals from this Program visitor.
1120
+ Program: {
1121
+ enter(path) {
1122
+ const engineImportSpecifiers = getEngineImportSpecifiers(path);
1123
+ // Validate the usage of LWC decorators.
1124
+ validateImportedLwcDecoratorUsage(engineImportSpecifiers);
1125
+ // Add ?scoped=true to *.scoped.css imports
1126
+ scopeCssImports(api, path);
1127
+ },
1128
+ exit(path) {
1129
+ const engineImportSpecifiers = getEngineImportSpecifiers(path);
1130
+ removeImportedDecoratorSpecifiers(engineImportSpecifiers);
1131
+ // Will eventually be removed to eliminate unnecessary complexity. Rollup already does this for us.
1132
+ dedupeImports(api)(path);
1133
+ },
1134
+ },
1135
+ Import: transformDynamicImports,
1136
+ Class: transformDecorators,
1137
+ ClassBody: addCompilerVersionNumber,
1138
+ ExportDefaultDeclaration: transformCreateRegisterComponent,
1139
+ },
1140
+ };
1141
+ }
1142
+
1143
+ module.exports = LwcClassTransform;
1144
+ /** version: 2.43.0 */
1145
+ //# sourceMappingURL=index.cjs.js.map