-
-
Notifications
You must be signed in to change notification settings - Fork 5.6k
/
index.ts
333 lines (300 loc) · 10.9 KB
/
index.ts
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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
import { types as t } from "@babel/core";
import type { PluginAPI, PluginObject } from "@babel/core";
import type { NodePath } from "@babel/traverse";
import nameFunction from "@babel/helper-function-name";
import splitExportDeclaration from "@babel/helper-split-export-declaration";
import semver from "semver";
import {
buildPrivateNamesNodes,
buildPrivateNamesMap,
transformPrivateNamesUsage,
buildFieldsInitNodes,
buildCheckInRHS,
} from "./fields";
import type { PropPath } from "./fields";
import { buildDecoratedClass, hasDecorators } from "./decorators";
import { injectInitialization, extractComputedKeys } from "./misc";
import { enableFeature, FEATURES, isLoose, shouldTransform } from "./features";
import { assertFieldTransformed } from "./typescript";
export { FEATURES, enableFeature, injectInitialization, buildCheckInRHS };
declare const PACKAGE_JSON: { name: string; version: string };
const versionKey = "@babel/plugin-class-features/version";
interface Options {
name: string;
feature: number;
loose?: boolean;
inherits?: PluginObject["inherits"];
manipulateOptions?: PluginObject["manipulateOptions"];
api?: PluginAPI;
}
export function createClassFeaturePlugin({
name,
feature,
loose,
manipulateOptions,
api,
inherits,
}: Options): PluginObject {
if (!process.env.BABEL_8_BREAKING) {
api ??= { assumption: () => void 0 as any } as any;
}
const setPublicClassFields = api.assumption("setPublicClassFields");
const privateFieldsAsSymbols = api.assumption("privateFieldsAsSymbols");
const privateFieldsAsProperties = api.assumption("privateFieldsAsProperties");
const constantSuper = api.assumption("constantSuper");
const noDocumentAll = api.assumption("noDocumentAll");
if (privateFieldsAsProperties && privateFieldsAsSymbols) {
throw new Error(
`Cannot enable both the "privateFieldsAsProperties" and ` +
`"privateFieldsAsSymbols" assumptions as the same time.`,
);
}
const privateFieldsAsSymbolsOrProperties =
privateFieldsAsProperties || privateFieldsAsSymbols;
if (loose === true) {
type AssumptionName = Parameters<PluginAPI["assumption"]>[0];
const explicit: `"${AssumptionName}"`[] = [];
if (setPublicClassFields !== undefined) {
explicit.push(`"setPublicClassFields"`);
}
if (privateFieldsAsProperties !== undefined) {
explicit.push(`"privateFieldsAsProperties"`);
}
if (privateFieldsAsSymbols !== undefined) {
explicit.push(`"privateFieldsAsSymbols"`);
}
if (explicit.length !== 0) {
console.warn(
`[${name}]: You are using the "loose: true" option and you are` +
` explicitly setting a value for the ${explicit.join(" and ")}` +
` assumption${explicit.length > 1 ? "s" : ""}. The "loose" option` +
` can cause incompatibilities with the other class features` +
` plugins, so it's recommended that you replace it with the` +
` following top-level option:\n` +
`\t"assumptions": {\n` +
`\t\t"setPublicClassFields": true,\n` +
`\t\t"privateFieldsAsSymbols": true\n` +
`\t}`,
);
}
}
return {
name,
manipulateOptions,
inherits,
pre(file) {
enableFeature(file, feature, loose);
if (!process.env.BABEL_8_BREAKING) {
// Until 7.21.4, we used to encode the version as a number.
// If file.get(versionKey) is a number, it has thus been
// set by an older version of this plugin.
if (typeof file.get(versionKey) === "number") {
file.set(versionKey, PACKAGE_JSON.version);
return;
}
}
if (
!file.get(versionKey) ||
semver.lt(file.get(versionKey), PACKAGE_JSON.version)
) {
file.set(versionKey, PACKAGE_JSON.version);
}
},
visitor: {
Class(path, { file }) {
if (file.get(versionKey) !== PACKAGE_JSON.version) return;
if (!shouldTransform(path, file)) return;
if (path.isClassDeclaration()) assertFieldTransformed(path);
const loose = isLoose(file, feature);
let constructor: NodePath<t.ClassMethod>;
const isDecorated = hasDecorators(path.node);
const props: PropPath[] = [];
const elements = [];
const computedPaths: NodePath<t.ClassProperty | t.ClassMethod>[] = [];
const privateNames = new Set<string>();
const body = path.get("body");
for (const path of body.get("body")) {
if (
// check path.node.computed is enough, but ts will complain
(path.isClassProperty() || path.isClassMethod()) &&
path.node.computed
) {
computedPaths.push(path);
}
if (path.isPrivate()) {
const { name } = path.node.key.id;
const getName = `get ${name}`;
const setName = `set ${name}`;
if (path.isClassPrivateMethod()) {
if (path.node.kind === "get") {
if (
privateNames.has(getName) ||
(privateNames.has(name) && !privateNames.has(setName))
) {
throw path.buildCodeFrameError("Duplicate private field");
}
privateNames.add(getName).add(name);
} else if (path.node.kind === "set") {
if (
privateNames.has(setName) ||
(privateNames.has(name) && !privateNames.has(getName))
) {
throw path.buildCodeFrameError("Duplicate private field");
}
privateNames.add(setName).add(name);
}
} else {
if (
(privateNames.has(name) &&
!privateNames.has(getName) &&
!privateNames.has(setName)) ||
(privateNames.has(name) &&
(privateNames.has(getName) || privateNames.has(setName)))
) {
throw path.buildCodeFrameError("Duplicate private field");
}
privateNames.add(name);
}
}
if (path.isClassMethod({ kind: "constructor" })) {
constructor = path;
} else {
elements.push(path);
if (
path.isProperty() ||
path.isPrivate() ||
path.isStaticBlock?.()
) {
props.push(path as PropPath);
}
}
}
if (process.env.BABEL_8_BREAKING) {
if (!props.length) return;
} else {
if (!props.length && !isDecorated) return;
}
const innerBinding = path.node.id;
let ref: t.Identifier;
if (!innerBinding || path.isClassExpression()) {
nameFunction(path);
ref = path.scope.generateUidIdentifier("class");
} else {
ref = t.cloneNode(path.node.id);
}
// NODE: These three functions don't support decorators yet,
// but verifyUsedFeatures throws if there are both
// decorators and private fields.
const privateNamesMap = buildPrivateNamesMap(props);
const privateNamesNodes = buildPrivateNamesNodes(
privateNamesMap,
privateFieldsAsProperties ?? loose,
privateFieldsAsSymbols ?? false,
file,
);
transformPrivateNamesUsage(
ref,
path,
privateNamesMap,
{
privateFieldsAsProperties:
privateFieldsAsSymbolsOrProperties ?? loose,
noDocumentAll,
innerBinding,
},
file,
);
let keysNodes: t.Statement[],
staticNodes: t.Statement[],
instanceNodes: t.Statement[],
pureStaticNodes: t.FunctionDeclaration[],
wrapClass: (path: NodePath<t.Class>) => NodePath;
if (!process.env.BABEL_8_BREAKING) {
if (isDecorated) {
staticNodes = pureStaticNodes = keysNodes = [];
({ instanceNodes, wrapClass } = buildDecoratedClass(
ref,
path,
elements,
file,
));
} else {
keysNodes = extractComputedKeys(path, computedPaths, file);
({ staticNodes, pureStaticNodes, instanceNodes, wrapClass } =
buildFieldsInitNodes(
ref,
path.node.superClass,
props,
privateNamesMap,
file,
setPublicClassFields ?? loose,
privateFieldsAsSymbolsOrProperties ?? loose,
constantSuper ?? loose,
innerBinding,
));
}
} else {
keysNodes = extractComputedKeys(path, computedPaths, file);
({ staticNodes, pureStaticNodes, instanceNodes, wrapClass } =
buildFieldsInitNodes(
ref,
path.node.superClass,
props,
privateNamesMap,
file,
setPublicClassFields ?? loose,
privateFieldsAsSymbolsOrProperties ?? loose,
constantSuper ?? loose,
innerBinding,
));
}
if (instanceNodes.length > 0) {
injectInitialization(
path,
constructor,
instanceNodes,
(referenceVisitor, state) => {
if (!process.env.BABEL_8_BREAKING) {
if (isDecorated) return;
}
for (const prop of props) {
// @ts-expect-error: TS doesn't infer that prop.node is not a StaticBlock
if (t.isStaticBlock?.(prop.node) || prop.node.static) continue;
prop.traverse(referenceVisitor, state);
}
},
);
}
// rename to make ts happy
const wrappedPath = wrapClass(path);
wrappedPath.insertBefore([...privateNamesNodes, ...keysNodes]);
if (staticNodes.length > 0) {
wrappedPath.insertAfter(staticNodes);
}
if (pureStaticNodes.length > 0) {
wrappedPath
.find(parent => parent.isStatement() || parent.isDeclaration())
.insertAfter(pureStaticNodes);
}
},
ExportDefaultDeclaration(path, { file }) {
if (!process.env.BABEL_8_BREAKING) {
if (file.get(versionKey) !== PACKAGE_JSON.version) return;
const decl = path.get("declaration");
if (decl.isClassDeclaration() && hasDecorators(decl.node)) {
if (decl.node.id) {
// export default class Foo {}
// -->
// class Foo {} export { Foo as default }
splitExportDeclaration(path);
} else {
// @ts-expect-error Anonymous class declarations can be
// transformed as if they were expressions
decl.node.type = "ClassExpression";
}
}
}
},
},
};
}