/
index.ts
557 lines (483 loc) 路 17.4 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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
import { declare } from "@babel/helper-plugin-utils";
import syntaxTypeScript from "@babel/plugin-syntax-typescript";
import { types as t, template } from "@babel/core";
import { injectInitialization } from "@babel/helper-create-class-features-plugin";
import transpileEnum from "./enum";
import transpileNamespace from "./namespace";
import type { NodePath } from "@babel/traverse";
function isInType(path) {
switch (path.parent.type) {
case "TSTypeReference":
case "TSQualifiedName":
case "TSExpressionWithTypeArguments":
case "TSTypeQuery":
return true;
case "ExportSpecifier":
return path.parentPath.parent.exportKind === "type";
default:
return false;
}
}
const GLOBAL_TYPES = new WeakMap();
// Track programs which contain imports/exports of values, so that we can include
// empty exports for programs that do not, but were parsed as modules. This allows
// tools to infer unamibiguously that results are ESM.
const NEEDS_EXPLICIT_ESM = new WeakMap();
const PARSED_PARAMS = new WeakSet();
function isGlobalType(path, name) {
const program = path.find(path => path.isProgram()).node;
if (path.scope.hasOwnBinding(name)) return false;
if (GLOBAL_TYPES.get(program).has(name)) return true;
console.warn(
`The exported identifier "${name}" is not declared in Babel's scope tracker\n` +
`as a JavaScript value binding, and "@babel/plugin-transform-typescript"\n` +
`never encountered it as a TypeScript type declaration.\n` +
`It will be treated as a JavaScript value.\n\n` +
`This problem is likely caused by another plugin injecting\n` +
`"${name}" without registering it in the scope tracker. If you are the author\n` +
` of that plugin, please use "scope.registerDeclaration(declarationPath)".`,
);
return false;
}
function registerGlobalType(programScope, name) {
GLOBAL_TYPES.get(programScope.path.node).add(name);
}
export default declare((api, opts) => {
api.assertVersion(7);
const JSX_PRAGMA_REGEX = /\*?\s*@jsx((?:Frag)?)\s+([^\s]+)/;
const {
allowNamespaces = true,
jsxPragma = "React.createElement",
jsxPragmaFrag = "React.Fragment",
onlyRemoveTypeImports = false,
} = opts;
if (!process.env.BABEL_8_BREAKING) {
// eslint-disable-next-line no-var
var { allowDeclareFields = false } = opts;
}
const classMemberVisitors = {
field(path) {
const { node } = path;
if (!process.env.BABEL_8_BREAKING) {
if (!allowDeclareFields && node.declare) {
throw path.buildCodeFrameError(
`The 'declare' modifier is only allowed when the 'allowDeclareFields' option of ` +
`@babel/plugin-transform-typescript or @babel/preset-typescript is enabled.`,
);
}
}
if (node.declare) {
if (node.value) {
throw path.buildCodeFrameError(
`Fields with the 'declare' modifier cannot be initialized here, but only in the constructor`,
);
}
if (!node.decorators) {
path.remove();
}
} else if (node.definite) {
if (node.value) {
throw path.buildCodeFrameError(
`Definitely assigned fields cannot be initialized here, but only in the constructor`,
);
}
if (!process.env.BABEL_8_BREAKING) {
// keep the definitely assigned fields only when `allowDeclareFields` (equivalent of
// Typescript's `useDefineForClassFields`) is true
if (!allowDeclareFields && !node.decorators) {
path.remove();
}
}
} else if (!process.env.BABEL_8_BREAKING) {
if (
!allowDeclareFields &&
!node.value &&
!node.decorators &&
!t.isClassPrivateProperty(node)
) {
path.remove();
}
}
if (node.accessibility) node.accessibility = null;
if (node.abstract) node.abstract = null;
if (node.readonly) node.readonly = null;
if (node.optional) node.optional = null;
if (node.typeAnnotation) node.typeAnnotation = null;
if (node.definite) node.definite = null;
if (node.declare) node.declare = null;
if (node.override) node.override = null;
},
method({ node }) {
if (node.accessibility) node.accessibility = null;
if (node.abstract) node.abstract = null;
if (node.optional) node.optional = null;
if (node.override) node.override = null;
// Rest handled by Function visitor
},
constructor(path, classPath) {
if (path.node.accessibility) path.node.accessibility = null;
// Collects parameter properties so that we can add an assignment
// for each of them in the constructor body
//
// We use a WeakSet to ensure an assignment for a parameter
// property is only added once. This is necessary for cases like
// using `transform-classes`, which causes this visitor to run
// twice.
const parameterProperties = [];
for (const param of path.node.params) {
if (
param.type === "TSParameterProperty" &&
!PARSED_PARAMS.has(param.parameter)
) {
PARSED_PARAMS.add(param.parameter);
parameterProperties.push(param.parameter);
}
}
if (parameterProperties.length) {
const assigns = parameterProperties.map(p => {
let id;
if (t.isIdentifier(p)) {
id = p;
} else if (t.isAssignmentPattern(p) && t.isIdentifier(p.left)) {
id = p.left;
} else {
throw path.buildCodeFrameError(
"Parameter properties can not be destructuring patterns.",
);
}
return template.statement.ast`
this.${t.cloneNode(id)} = ${t.cloneNode(id)}`;
});
injectInitialization(classPath, path, assigns);
}
},
};
return {
name: "transform-typescript",
inherits: syntaxTypeScript,
visitor: {
//"Pattern" alias doesn't include Identifier or RestElement.
Pattern: visitPattern,
Identifier: visitPattern,
RestElement: visitPattern,
Program: {
enter(path, state) {
const { file } = state;
let fileJsxPragma = null;
let fileJsxPragmaFrag = null;
if (!GLOBAL_TYPES.has(path.node)) {
GLOBAL_TYPES.set(path.node, new Set());
}
if (file.ast.comments) {
for (const comment of file.ast.comments) {
const jsxMatches = JSX_PRAGMA_REGEX.exec(comment.value);
if (jsxMatches) {
if (jsxMatches[1]) {
// isFragment
fileJsxPragmaFrag = jsxMatches[2];
} else {
fileJsxPragma = jsxMatches[2];
}
}
}
}
let pragmaImportName = fileJsxPragma || jsxPragma;
if (pragmaImportName) {
[pragmaImportName] = pragmaImportName.split(".");
}
let pragmaFragImportName = fileJsxPragmaFrag || jsxPragmaFrag;
if (pragmaFragImportName) {
[pragmaFragImportName] = pragmaFragImportName.split(".");
}
// remove type imports
for (let stmt of path.get("body")) {
if (stmt.isImportDeclaration()) {
if (!NEEDS_EXPLICIT_ESM.has(state.file.ast.program)) {
NEEDS_EXPLICIT_ESM.set(state.file.ast.program, true);
}
if (stmt.node.importKind === "type") {
stmt.remove();
continue;
}
// If onlyRemoveTypeImports is `true`, only remove type-only imports
// and exports introduced in TypeScript 3.8.
if (onlyRemoveTypeImports) {
NEEDS_EXPLICIT_ESM.set(path.node, false);
} else {
// Note: this will allow both `import { } from "m"` and `import "m";`.
// In TypeScript, the former would be elided.
if (stmt.node.specifiers.length === 0) {
NEEDS_EXPLICIT_ESM.set(path.node, false);
continue;
}
let allElided = true;
const importsToRemove: NodePath<t.Node>[] = [];
for (const specifier of stmt.node.specifiers) {
const binding = stmt.scope.getBinding(specifier.local.name);
// The binding may not exist if the import node was explicitly
// injected by another plugin. Currently core does not do a good job
// of keeping scope bindings synchronized with the AST. For now we
// just bail if there is no binding, since chances are good that if
// the import statement was injected then it wasn't a typescript type
// import anyway.
if (
binding &&
isImportTypeOnly({
binding,
programPath: path,
pragmaImportName,
pragmaFragImportName,
})
) {
importsToRemove.push(binding.path);
} else {
allElided = false;
NEEDS_EXPLICIT_ESM.set(path.node, false);
}
}
if (allElided) {
stmt.remove();
} else {
for (const importPath of importsToRemove) {
importPath.remove();
}
}
}
continue;
}
if (stmt.isExportDeclaration()) {
stmt = stmt.get("declaration");
}
if (stmt.isVariableDeclaration({ declare: true })) {
for (const name of Object.keys(stmt.getBindingIdentifiers())) {
registerGlobalType(path.scope, name);
}
} else if (
stmt.isTSTypeAliasDeclaration() ||
stmt.isTSDeclareFunction() ||
stmt.isTSInterfaceDeclaration() ||
stmt.isClassDeclaration({ declare: true }) ||
stmt.isTSEnumDeclaration({ declare: true }) ||
(stmt.isTSModuleDeclaration({ declare: true }) &&
stmt.get("id").isIdentifier())
) {
registerGlobalType(path.scope, stmt.node.id.name);
}
}
},
exit(path) {
if (
path.node.sourceType === "module" &&
NEEDS_EXPLICIT_ESM.get(path.node)
) {
// If there are no remaining value exports, this file can no longer
// be inferred to be ESM. Leave behind an empty export declaration
// so it can be.
path.pushContainer("body", t.exportNamedDeclaration());
}
},
},
ExportNamedDeclaration(path, state) {
if (!NEEDS_EXPLICIT_ESM.has(state.file.ast.program)) {
NEEDS_EXPLICIT_ESM.set(state.file.ast.program, true);
}
if (path.node.exportKind === "type") {
path.remove();
return;
}
// remove export declaration if it's exporting only types
// This logic is needed when exportKind is "value", because
// currently the "type" keyword is optional.
// TODO:
// Also, currently @babel/parser sets exportKind to "value" for
// export interface A {}
// etc.
if (
!path.node.source &&
path.node.specifiers.length > 0 &&
path.node.specifiers.every(({ local }) =>
isGlobalType(path, local.name),
)
) {
path.remove();
return;
}
NEEDS_EXPLICIT_ESM.set(state.file.ast.program, false);
},
ExportSpecifier(path) {
// remove type exports
if (!path.parent.source && isGlobalType(path, path.node.local.name)) {
path.remove();
}
},
ExportDefaultDeclaration(path, state) {
if (!NEEDS_EXPLICIT_ESM.has(state.file.ast.program)) {
NEEDS_EXPLICIT_ESM.set(state.file.ast.program, true);
}
// remove whole declaration if it's exporting a TS type
if (
t.isIdentifier(path.node.declaration) &&
isGlobalType(path, path.node.declaration.name)
) {
path.remove();
return;
}
NEEDS_EXPLICIT_ESM.set(state.file.ast.program, false);
},
TSDeclareFunction(path) {
path.remove();
},
TSDeclareMethod(path) {
path.remove();
},
VariableDeclaration(path) {
if (path.node.declare) {
path.remove();
}
},
VariableDeclarator({ node }) {
if (node.definite) node.definite = null;
},
TSIndexSignature(path) {
path.remove();
},
ClassDeclaration(path) {
const { node } = path;
if (node.declare) {
path.remove();
return;
}
},
Class(path) {
const { node } = path;
if (node.typeParameters) node.typeParameters = null;
if (node.superTypeParameters) node.superTypeParameters = null;
if (node.implements) node.implements = null;
if (node.abstract) node.abstract = null;
// Similar to the logic in `transform-flow-strip-types`, we need to
// handle `TSParameterProperty` and `ClassProperty` here because the
// class transform would transform the class, causing more specific
// visitors to not run.
path.get("body.body").forEach(child => {
if (child.isClassMethod() || child.isClassPrivateMethod()) {
if (child.node.kind === "constructor") {
classMemberVisitors.constructor(child, path);
} else {
classMemberVisitors.method(child);
}
} else if (
child.isClassProperty() ||
child.isClassPrivateProperty()
) {
classMemberVisitors.field(child);
}
});
},
Function(path) {
const { node, scope } = path;
if (node.typeParameters) node.typeParameters = null;
if (node.returnType) node.returnType = null;
const params = node.params;
if (params.length > 0 && t.isIdentifier(params[0], { name: "this" })) {
params.shift();
}
// We replace `TSParameterProperty` here so that transforms that
// rely on a `Function` visitor to deal with arguments, like
// `transform-parameters`, work properly.
const paramsPath = path.get("params");
for (const p of paramsPath) {
if (p.type === "TSParameterProperty") {
p.replaceWith(p.get("parameter"));
scope.registerBinding("param", p);
}
}
},
TSModuleDeclaration(path) {
transpileNamespace(path, t, allowNamespaces);
},
TSInterfaceDeclaration(path) {
path.remove();
},
TSTypeAliasDeclaration(path) {
path.remove();
},
TSEnumDeclaration(path) {
transpileEnum(path, t);
},
TSImportEqualsDeclaration(path) {
throw path.buildCodeFrameError(
"`import =` is not supported by @babel/plugin-transform-typescript\n" +
"Please consider using " +
"`import <moduleName> from '<moduleName>';` alongside " +
"Typescript's --allowSyntheticDefaultImports option.",
);
},
TSExportAssignment(path) {
throw path.buildCodeFrameError(
"`export =` is not supported by @babel/plugin-transform-typescript\n" +
"Please consider using `export <value>;`.",
);
},
TSTypeAssertion(path) {
path.replaceWith(path.node.expression);
},
TSAsExpression(path) {
let { node } = path;
do {
node = node.expression;
} while (t.isTSAsExpression(node));
path.replaceWith(node);
},
TSNonNullExpression(path) {
path.replaceWith(path.node.expression);
},
CallExpression(path) {
path.node.typeParameters = null;
},
OptionalCallExpression(path) {
path.node.typeParameters = null;
},
NewExpression(path) {
path.node.typeParameters = null;
},
JSXOpeningElement(path) {
path.node.typeParameters = null;
},
TaggedTemplateExpression(path) {
path.node.typeParameters = null;
},
},
};
function visitPattern({ node }) {
if (node.typeAnnotation) node.typeAnnotation = null;
if (t.isIdentifier(node) && node.optional) node.optional = null;
// 'access' and 'readonly' are only for parameter properties, so constructor visitor will handle them.
}
function isImportTypeOnly({
binding,
programPath,
pragmaImportName,
pragmaFragImportName,
}) {
for (const path of binding.referencePaths) {
if (!isInType(path)) {
return false;
}
}
if (
binding.identifier.name !== pragmaImportName &&
binding.identifier.name !== pragmaFragImportName
) {
return true;
}
// "React" or the JSX pragma is referenced as a value if there are any JSX elements/fragments in the code.
let sourceFileHasJsx = false;
programPath.traverse({
"JSXElement|JSXFragment"(path) {
sourceFileHasJsx = true;
path.stop();
},
});
return !sourceFileHasJsx;
}
});