-
Notifications
You must be signed in to change notification settings - Fork 439
Expand file tree
/
Copy pathindex.ts
More file actions
307 lines (283 loc) · 11.2 KB
/
index.ts
File metadata and controls
307 lines (283 loc) · 11.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
/*
* Copyright (c) 2024, salesforce.com, inc.
* All rights reserved.
* SPDX-License-Identifier: MIT
* For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/MIT
*/
import { generate } from 'astring';
import { traverse, builders as b, is } from 'estree-toolkit';
import { parseModule } from 'meriyah';
import { DecoratorErrors } from '@lwc/errors';
import { transmogrify } from '../transmogrify';
import { ImportManager } from '../imports';
import { replaceLwcImport, replaceNamedLwcExport, replaceAllLwcExport } from './lwc-import';
import { catalogTmplImport } from './catalog-tmpls';
import { catalogStaticStylesheets, catalogAndReplaceStyleImports } from './stylesheets';
import { addGenerateMarkupFunction } from './generate-markup';
import { catalogWireAdapters } from './wire';
import { removeDecoratorImport } from './remove-decorator-import';
import { generateError } from './errors';
import type { ComponentTransformOptions } from '../shared';
import type {
Identifier as EsIdentifier,
Program as EsProgram,
Decorator as EsDecorator,
} from 'estree';
import type { Visitors, ComponentMetaState } from './types';
import type { CompilationMode } from '@lwc/shared';
const visitors: Visitors = {
$: { scope: true },
ExportNamedDeclaration(path) {
replaceNamedLwcExport(path);
},
ExportAllDeclaration(path) {
replaceAllLwcExport(path);
},
ImportDeclaration(path, state) {
if (!path.node || !path.node.source.value || typeof path.node.source.value !== 'string') {
return;
}
replaceLwcImport(path, state);
catalogTmplImport(path, state);
catalogAndReplaceStyleImports(path, state);
removeDecoratorImport(path);
},
ImportExpression(path, state) {
const { experimentalDynamicComponent, importManager } = state;
if (!experimentalDynamicComponent) {
// if no `experimentalDynamicComponent` config, then leave dynamic `import()`s as-is
return;
}
if (experimentalDynamicComponent.strictSpecifier) {
if (!is.literal(path.node?.source) || typeof path.node.source.value !== 'string') {
// TODO [#5032]: Harmonize errors thrown in `@lwc/ssr-compiler`
throw new Error('todo - LWCClassErrors.INVALID_DYNAMIC_IMPORT_SOURCE_STRICT');
}
}
const loader = experimentalDynamicComponent.loader;
if (!loader) {
// if no `loader` defined, then leave dynamic `import()`s as-is
return;
}
const source = path.node!.source!;
// 1. insert `import { load as __load } from '${loader}'` at top of program
importManager.add({ load: '__load' }, loader);
// 2. replace this import with `__load(${source})`
path.replaceWith(b.callExpression(b.identifier('__load'), [structuredClone(source)]));
},
ClassDeclaration(path, state) {
const { node } = path;
if (
node?.superClass &&
// export default class extends LightningElement {}
(is.exportDefaultDeclaration(path.parentPath) ||
// class Cmp extends LightningElement {}; export default Cmp
path.scope
?.getBinding(node.id.name)
?.references.some((ref) => is.exportDefaultDeclaration(ref.parent)))
) {
// If it's a default-exported class with a superclass, then it's an LWC component!
state.isLWC = true;
if (node.id) {
state.lwcClassName = node.id.name;
} else {
node.id = b.identifier('DefaultComponentName');
state.lwcClassName = 'DefaultComponentName';
}
}
},
PropertyDefinition(path, state) {
const node = path.node;
if (!is.identifier(node?.key)) {
return;
}
const { decorators } = node;
validateUniqueDecorator(decorators);
const decoratedExpression = decorators?.[0]?.expression;
if (is.identifier(decoratedExpression) && decoratedExpression.name === 'api') {
state.publicProperties.push(node.key.name);
} else if (
is.callExpression(decoratedExpression) &&
is.identifier(decoratedExpression.callee) &&
decoratedExpression.callee.name === 'wire'
) {
catalogWireAdapters(path, state);
state.privateProperties.push(node.key.name);
} else {
state.privateProperties.push(node.key.name);
}
if (
node.static &&
node.key.name === 'stylesheets' &&
is.arrayExpression(node.value) &&
node.value.elements.every((el) => is.identifier(el))
) {
catalogStaticStylesheets(
node.value.elements.map((el) => (el as EsIdentifier).name),
state
);
}
},
MethodDefinition(path, state) {
const node = path.node;
if (!is.identifier(node?.key)) {
return;
}
// If we mutate any class-methods that are piped through this compiler, then we'll be
// inadvertently mutating things like Wire adapters.
if (!state.isLWC) {
return;
}
const { decorators } = node;
validateUniqueDecorator(decorators);
// The real type is a subset of `Expression`, which doesn't work with the `is` validators
const decoratedExpression = decorators?.[0]?.expression;
if (
is.callExpression(decoratedExpression) &&
is.identifier(decoratedExpression.callee) &&
decoratedExpression.callee.name === 'wire'
) {
// Getters and setters are methods in the AST, but treated as properties by @wire
// Note that this means that their implementations are ignored!
if (node.kind === 'get' || node.kind === 'set') {
const methodAsProp = b.propertyDefinition(
structuredClone(node.key),
null,
node.computed,
node.static
);
methodAsProp.decorators = structuredClone(decorators);
path.replaceWith(methodAsProp);
// We do not need to call `catalogWireAdapters()` because, by replacing the current
// node, `traverse()` will visit it again automatically, so we will just call
// `catalogWireAdapters()` later anyway.
return;
} else {
catalogWireAdapters(path, state);
}
} else if (is.identifier(decoratedExpression) && decoratedExpression.name === 'api') {
if (state.publicProperties.includes(node.key.name)) {
// TODO [#5032]: Harmonize errors thrown in `@lwc/ssr-compiler`
throw new Error(
`LWC1112: @api get ${node.key.name} and @api set ${node.key.name} detected in class declaration. Only one of the two needs to be decorated with @api.`
);
}
state.publicProperties.push(node.key.name);
}
switch (node.key.name) {
case 'constructor':
// add our own custom arg after any pre-existing constructor args
node.value.params = [
...structuredClone(node.value.params),
b.identifier('propsAvailableAtConstruction'),
];
break;
case 'connectedCallback':
state.hasConnectedCallback = true;
break;
case 'renderedCallback':
state.hadRenderedCallback = true;
path.remove();
break;
case 'disconnectedCallback':
state.hadDisconnectedCallback = true;
path.remove();
break;
case 'errorCallback':
state.hadErrorCallback = true;
path.remove();
break;
}
},
Super(path, _state) {
const parentFn = path.getFunctionParent();
if (
parentFn &&
parentFn.parentPath?.node?.type === 'MethodDefinition' &&
parentFn.parentPath?.node?.kind === 'constructor' &&
path.parentPath &&
path.parentPath.node?.type === 'CallExpression'
) {
// add our own custom arg after any pre-existing super() args
path.parentPath.node.arguments = [
...structuredClone(path.parentPath.node.arguments),
b.identifier('propsAvailableAtConstruction'),
];
}
},
Program: {
leave(path, state) {
// After parsing the whole tree, insert needed imports
const importDeclarations = state.importManager.getImportDeclarations();
if (importDeclarations.length > 0) {
path.node?.body.unshift(...importDeclarations);
}
},
},
};
function validateUniqueDecorator(decorators: EsDecorator[]) {
if (decorators.length < 2) {
return;
}
const expressions = decorators.map(({ expression }) => expression);
const wire = expressions.find(
(expr) => is.callExpression(expr) && is.identifier(expr.callee, { name: 'wire' })
);
const api = expressions.find((expr) => is.identifier(expr, { name: 'api' }));
if (wire && api) {
throw generateError(wire, DecoratorErrors.CONFLICT_WITH_ANOTHER_DECORATOR, 'api');
}
const track = expressions.find((expr) => is.identifier(expr, { name: 'track' }));
if (wire && track) {
throw generateError(wire, DecoratorErrors.CONFLICT_WITH_ANOTHER_DECORATOR, 'track');
}
}
export default function compileJS(
src: string,
filename: string,
tagName: string,
options: ComponentTransformOptions,
compilationMode: CompilationMode
) {
let ast = parseModule(src, {
module: true,
next: true,
loc: true,
source: filename,
ranges: true,
}) as EsProgram;
const state: ComponentMetaState = {
isLWC: false,
hasConstructor: false,
hasConnectedCallback: false,
hadRenderedCallback: false,
hadDisconnectedCallback: false,
hadErrorCallback: false,
lightningElementIdentifier: null,
lwcClassName: null,
tmplExplicitImports: null,
cssExplicitImports: null,
staticStylesheetIds: null,
publicProperties: [],
privateProperties: [],
wireAdapters: [],
experimentalDynamicComponent: options.experimentalDynamicComponent,
importManager: new ImportManager(),
};
traverse(ast, visitors, state);
if (!state.isLWC) {
// If an `extends LightningElement` is not detected in the JS, the
// file in question is likely not an LWC. With this v1 implementation,
// we'll just return the original source.
return {
code: generate(ast, {}),
};
}
addGenerateMarkupFunction(ast, state, tagName, filename);
if (compilationMode === 'async' || compilationMode === 'sync') {
ast = transmogrify(ast, compilationMode);
}
return {
code: generate(ast, {}),
};
}