-
Notifications
You must be signed in to change notification settings - Fork 309
/
downlevel-ctor.ts
753 lines (697 loc) · 29.8 KB
/
downlevel-ctor.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
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*
* Copy from https://github.com/angular/angular/blob/master/packages/compiler-cli/src/transformers/downlevel_decorators_transform.ts
* This will make a bit more effort in maintaining but it will be easier to just copy to work with ESM
*/
import { Decorator, ReflectionHost, TypeScriptReflectionHost } from '@angular/compiler-cli/src/ngtsc/reflection';
import type { TsCompilerInstance } from 'ts-jest/dist/types';
import ts from 'typescript';
import { isAliasImportDeclaration, loadIsReferencedAliasDeclarationPatch } from './patch-alias-reference-resolution';
/**
* Transform for downleveling Angular decorators and Angular-decorated class constructor
* parameters for dependency injection. This transform can be used by the CLI for JIT-mode
* compilation where constructor parameters and associated Angular decorators should be
* downleveled so that apps are not exposed to the ES2015 temporal dead zone limitation
* in TypeScript. See https://github.com/angular/angular-cli/pull/14473 for more details.
*/
export function constructorDownlevelCtor({ program }: TsCompilerInstance): ts.TransformerFactory<ts.SourceFile> {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const typeChecker = program!.getTypeChecker();
const reflectionHost = new TypeScriptReflectionHost(typeChecker);
return getDownlevelDecoratorsTransform(
typeChecker,
reflectionHost,
[],
/* isCore */ false,
/* enableClosureCompiler */ false,
/* skipClassDecorators */ true,
);
}
/**
* Whether a given decorator should be treated as an Angular decorator.
* Either it's used in @angular/core, or it's imported from there.
*/
function isAngularDecorator(decorator: Decorator, isCore: boolean): boolean {
return isCore || (decorator.import !== null && decorator.import.from === '@angular/core');
}
/*
#####################################################################
Code below has been extracted from the tsickle decorator downlevel transformer
and a few local modifications have been applied:
1. Tsickle by default processed all decorators that had the `@Annotation` JSDoc.
We modified the transform to only be concerned with known Angular decorators.
2. Tsickle by default added `@nocollapse` to all generated `ctorParameters` properties.
We only do this when `annotateForClosureCompiler` is enabled.
3. Tsickle does not handle union types for dependency injection. i.e. if a injected type
is denoted with `@Optional`, the actual type could be set to `T | null`.
See: https://github.com/angular/angular-cli/commit/826803d0736b807867caff9f8903e508970ad5e4.
4. Tsickle relied on `emitDecoratorMetadata` to be set to `true`. This is due to a limitation
in TypeScript transformers that never has been fixed. We were able to work around this
limitation so that `emitDecoratorMetadata` doesn't need to be specified.
See: `patchAliasReferenceResolution` for more details.
Here is a link to the tsickle revision on which this transformer is based:
https://github.com/angular/tsickle/blob/fae06becb1570f491806060d83f29f2d50c43cdd/src/decorator_downlevel_transformer.ts
#####################################################################
*/
/**
* Creates the AST for the decorator field type annotation, which has the form
* { type: Function, args?: any[] }[]
*/
function createDecoratorInvocationType(): ts.TypeNode {
const typeElements: ts.TypeElement[] = [];
typeElements.push(
ts.createPropertySignature(
undefined,
'type',
undefined,
ts.createTypeReferenceNode(ts.createIdentifier('Function'), undefined),
undefined,
),
);
typeElements.push(
ts.createPropertySignature(
undefined,
'args',
ts.createToken(ts.SyntaxKind.QuestionToken),
ts.createArrayTypeNode(ts.createKeywordTypeNode(ts.SyntaxKind.AnyKeyword)),
undefined,
),
);
return ts.createArrayTypeNode(ts.createTypeLiteralNode(typeElements));
}
/**
* Extracts the type of the decorator (the function or expression invoked), as well as all the
* arguments passed to the decorator. Returns an AST with the form:
*
* // For @decorator(arg1, arg2)
* { type: decorator, args: [arg1, arg2] }
*/
function extractMetadataFromSingleDecorator(
decorator: ts.Decorator,
diagnostics: ts.Diagnostic[],
): ts.ObjectLiteralExpression {
const metadataProperties: ts.ObjectLiteralElementLike[] = [];
const expr = decorator.expression;
switch (expr.kind) {
case ts.SyntaxKind.Identifier:
// The decorator was a plain @Foo.
metadataProperties.push(ts.createPropertyAssignment('type', expr));
break;
case ts.SyntaxKind.CallExpression:
// The decorator was a call, like @Foo(bar).
// eslint-disable-next-line no-case-declarations
const call = expr as ts.CallExpression;
metadataProperties.push(ts.createPropertyAssignment('type', call.expression));
if (call.arguments.length) {
const args: ts.Expression[] = [];
for (const arg of call.arguments) {
args.push(arg);
}
const argsArrayLiteral = ts.createArrayLiteral(args);
argsArrayLiteral.elements.hasTrailingComma = true;
metadataProperties.push(ts.createPropertyAssignment('args', argsArrayLiteral));
}
break;
default:
diagnostics.push({
file: decorator.getSourceFile(),
start: decorator.getStart(),
length: decorator.getEnd() - decorator.getStart(),
messageText: `${ts.SyntaxKind[decorator.kind]} not implemented in gathering decorator metadata.`,
category: ts.DiagnosticCategory.Error,
code: 0,
});
break;
}
return ts.createObjectLiteral(metadataProperties);
}
/**
* Takes a list of decorator metadata object ASTs and produces an AST for a
* static class property of an array of those metadata objects.
*/
function createDecoratorClassProperty(decoratorList: ts.ObjectLiteralExpression[]) {
const modifier = ts.createToken(ts.SyntaxKind.StaticKeyword);
const type = createDecoratorInvocationType();
const initializer = ts.createArrayLiteral(decoratorList, true);
// NB: the .decorators property does not get a @nocollapse property. There is
// no good reason why - it means .decorators is not runtime accessible if you
// compile with collapse properties, whereas propDecorators is, which doesn't
// follow any stringent logic. However this has been the case previously, and
// adding it back in leads to substantial code size increases as Closure fails
// to tree shake these props without @nocollapse.
return ts.createProperty(undefined, [modifier], 'decorators', undefined, type, initializer);
}
/**
* Creates the AST for the 'ctorParameters' field type annotation:
* () => ({ type: any, decorators?: {type: Function, args?: any[]}[] }|null)[]
*/
function createCtorParametersClassPropertyType(): ts.TypeNode {
// Sorry about this. Try reading just the string literals below.
const typeElements: ts.TypeElement[] = [];
typeElements.push(
ts.createPropertySignature(
undefined,
'type',
undefined,
ts.createTypeReferenceNode(ts.createIdentifier('any'), undefined),
undefined,
),
);
typeElements.push(
ts.createPropertySignature(
undefined,
'decorators',
ts.createToken(ts.SyntaxKind.QuestionToken),
ts.createArrayTypeNode(
ts.createTypeLiteralNode([
ts.createPropertySignature(
undefined,
'type',
undefined,
ts.createTypeReferenceNode(ts.createIdentifier('Function'), undefined),
undefined,
),
ts.createPropertySignature(
undefined,
'args',
ts.createToken(ts.SyntaxKind.QuestionToken),
ts.createArrayTypeNode(ts.createTypeReferenceNode(ts.createIdentifier('any'), undefined)),
undefined,
),
]),
),
undefined,
),
);
return ts.createFunctionTypeNode(
undefined,
[],
ts.createArrayTypeNode(
ts.createUnionTypeNode([ts.createTypeLiteralNode(typeElements), ts.createLiteralTypeNode(ts.createNull())]),
),
);
}
/**
* Sets a Closure \@nocollapse synthetic comment on the given node. This prevents Closure Compiler
* from collapsing the apparently static property, which would make it impossible to find for code
* trying to detect it at runtime.
*/
function addNoCollapseComment(n: ts.Node) {
ts.setSyntheticLeadingComments(n, [
{
kind: ts.SyntaxKind.MultiLineCommentTrivia,
text: '* @nocollapse ',
pos: -1,
end: -1,
hasTrailingNewLine: true,
},
]);
}
/**
* createCtorParametersClassProperty creates a static 'ctorParameters' property containing
* downleveled decorator information.
*
* The property contains an arrow function that returns an array of object literals of the shape:
* static ctorParameters = () => [{
* type: SomeClass|undefined, // the type of the param that's decorated, if it's a value.
* decorators: [{
* type: DecoratorFn, // the type of the decorator that's invoked.
* args: [ARGS], // the arguments passed to the decorator.
* }]
* }];
*/
function createCtorParametersClassProperty(
diagnostics: ts.Diagnostic[],
entityNameToExpression: (n: ts.EntityName) => ts.Expression | undefined,
ctorParameters: ParameterDecorationInfo[],
isClosureCompilerEnabled: boolean,
): ts.PropertyDeclaration {
const params: ts.Expression[] = [];
for (const ctorParam of ctorParameters) {
if (!ctorParam.type && ctorParam.decorators.length === 0) {
params.push(ts.createNull());
continue;
}
const paramType = ctorParam.type ? typeReferenceToExpression(entityNameToExpression, ctorParam.type) : undefined;
const members = [ts.createPropertyAssignment('type', paramType || ts.createIdentifier('undefined'))];
const decorators: ts.ObjectLiteralExpression[] = [];
for (const deco of ctorParam.decorators) {
decorators.push(extractMetadataFromSingleDecorator(deco, diagnostics));
}
if (decorators.length) {
members.push(ts.createPropertyAssignment('decorators', ts.createArrayLiteral(decorators)));
}
params.push(ts.createObjectLiteral(members));
}
const initializer = ts.createArrowFunction(
undefined,
undefined,
[],
undefined,
ts.createToken(ts.SyntaxKind.EqualsGreaterThanToken),
ts.createArrayLiteral(params, true),
);
const type = createCtorParametersClassPropertyType();
const ctorProp = ts.createProperty(
undefined,
[ts.createToken(ts.SyntaxKind.StaticKeyword)],
'ctorParameters',
undefined,
type,
initializer,
);
if (isClosureCompilerEnabled) {
addNoCollapseComment(ctorProp);
}
return ctorProp;
}
/**
* createPropDecoratorsClassProperty creates a static 'propDecorators' property containing type
* information for every property that has a decorator applied.
*
* static propDecorators: {[key: string]: {type: Function, args?: any[]}[]} = {
* propA: [{type: MyDecorator, args: [1, 2]}, ...],
* ...
* };
*/
function createPropDecoratorsClassProperty(
diagnostics: ts.Diagnostic[],
properties: Map<string, ts.Decorator[]>,
): ts.PropertyDeclaration {
// `static propDecorators: {[key: string]: ` + {type: Function, args?: any[]}[] + `} = {\n`);
const entries: ts.ObjectLiteralElementLike[] = [];
for (const [name, decorators] of properties.entries()) {
entries.push(
ts.createPropertyAssignment(
name,
ts.createArrayLiteral(decorators.map((deco) => extractMetadataFromSingleDecorator(deco, diagnostics))),
),
);
}
const initializer = ts.createObjectLiteral(entries, true);
const type = ts.createTypeLiteralNode([
ts.createIndexSignature(
undefined,
undefined,
[
ts.createParameter(
undefined,
undefined,
undefined,
'key',
undefined,
ts.createTypeReferenceNode('string', undefined),
undefined,
),
],
createDecoratorInvocationType(),
),
]);
return ts.createProperty(
undefined,
[ts.createToken(ts.SyntaxKind.StaticKeyword)],
'propDecorators',
undefined,
type,
initializer,
);
}
/**
* Returns an expression representing the (potentially) value part for the given node.
*
* This is a partial re-implementation of TypeScript's serializeTypeReferenceNode. This is a
* workaround for https://github.com/Microsoft/TypeScript/issues/17516 (serializeTypeReferenceNode
* not being exposed). In practice this implementation is sufficient for Angular's use of type
* metadata.
*/
function typeReferenceToExpression(
entityNameToExpression: (n: ts.EntityName) => ts.Expression | undefined,
node: ts.TypeNode,
): ts.Expression | undefined {
let kind = node.kind;
if (ts.isLiteralTypeNode(node)) {
// Treat literal types like their base type (boolean, string, number).
kind = node.literal.kind;
}
switch (kind) {
case ts.SyntaxKind.FunctionType:
case ts.SyntaxKind.ConstructorType:
return ts.createIdentifier('Function');
case ts.SyntaxKind.ArrayType:
case ts.SyntaxKind.TupleType:
return ts.createIdentifier('Array');
case ts.SyntaxKind.TypePredicate:
case ts.SyntaxKind.TrueKeyword:
case ts.SyntaxKind.FalseKeyword:
case ts.SyntaxKind.BooleanKeyword:
return ts.createIdentifier('Boolean');
case ts.SyntaxKind.StringLiteral:
case ts.SyntaxKind.StringKeyword:
return ts.createIdentifier('String');
case ts.SyntaxKind.ObjectKeyword:
return ts.createIdentifier('Object');
case ts.SyntaxKind.NumberKeyword:
case ts.SyntaxKind.NumericLiteral:
return ts.createIdentifier('Number');
case ts.SyntaxKind.TypeReference:
// eslint-disable-next-line no-case-declarations
const typeRef = node as ts.TypeReferenceNode;
// Ignore any generic types, just return the base type.
return entityNameToExpression(typeRef.typeName);
case ts.SyntaxKind.UnionType:
// eslint-disable-next-line no-case-declarations
const childTypeNodes = (node as ts.UnionTypeNode).types.filter(
(t) => !(ts.isLiteralTypeNode(t) && t.literal.kind === ts.SyntaxKind.NullKeyword),
);
return childTypeNodes.length === 1
? typeReferenceToExpression(entityNameToExpression, childTypeNodes[0])
: undefined;
default:
return undefined;
}
}
/**
* Checks whether a given symbol refers to a value that exists at runtime (as distinct from a type).
*
* Expands aliases, which is important for the case where
* import * as x from 'some-module';
* and x is now a value (the module object).
*/
function symbolIsRuntimeValue(typeChecker: ts.TypeChecker, symbol: ts.Symbol): boolean {
if (symbol.flags & ts.SymbolFlags.Alias) {
symbol = typeChecker.getAliasedSymbol(symbol);
}
// Note that const enums are a special case, because
// while they have a value, they don't exist at runtime.
return (symbol.flags & ts.SymbolFlags.Value & ts.SymbolFlags.ConstEnumExcludes) !== 0;
}
/** ParameterDecorationInfo describes the information for a single constructor parameter. */
interface ParameterDecorationInfo {
/**
* The type declaration for the parameter. Only set if the type is a value (e.g. a class, not an
* interface).
*/
type: ts.TypeNode | null;
/** The list of decorators found on the parameter, null if none. */
decorators: ts.Decorator[];
}
/**
* Gets a transformer for downleveling Angular decorators.
* @param typeChecker Reference to the program's type checker.
* @param host Reflection host that is used for determining decorators.
* @param diagnostics List which will be populated with diagnostics if any.
* @param isCore Whether the current TypeScript program is for the `@angular/core` package.
* @param isClosureCompilerEnabled Whether closure annotations need to be added where needed.
* @param skipClassDecorators Whether class decorators should be skipped from downleveling.
* This is useful for JIT mode where class decorators should be preserved as they could rely
* on immediate execution. e.g. downleveling `@Injectable` means that the injectable factory
* is not created, and injecting the token will not work. If this decorator would not be
* downleveled, the `Injectable` decorator will execute immediately on file load, and
* Angular will generate the corresponding injectable factory.
*/
function getDownlevelDecoratorsTransform(
typeChecker: ts.TypeChecker,
host: ReflectionHost,
diagnostics: ts.Diagnostic[],
isCore: boolean,
isClosureCompilerEnabled: boolean,
skipClassDecorators: boolean,
): ts.TransformerFactory<ts.SourceFile> {
return (context: ts.TransformationContext) => {
// Ensure that referenced type symbols are not elided by TypeScript. Imports for
// such parameter type symbols previously could be type-only, but now might be also
// used in the `ctorParameters` static property as a value. We want to make sure
// that TypeScript does not elide imports for such type references. Read more
// about this in the description for `loadIsReferencedAliasDeclarationPatch`.
const referencedParameterTypes = loadIsReferencedAliasDeclarationPatch(context);
/**
* Converts an EntityName (from a type annotation) to an expression (accessing a value).
*
* For a given qualified name, this walks depth first to find the leftmost identifier,
* and then converts the path into a property access that can be used as expression.
*/
function entityNameToExpression(name: ts.EntityName): ts.Expression | undefined {
const symbol = typeChecker.getSymbolAtLocation(name);
// Check if the entity name references a symbol that is an actual value. If it is not, it
// cannot be referenced by an expression, so return undefined.
if (
!symbol ||
!symbolIsRuntimeValue(typeChecker, symbol) ||
!symbol.declarations ||
symbol.declarations.length === 0
) {
return undefined;
}
// If we deal with a qualified name, build up a property access expression
// that could be used in the JavaScript output.
if (ts.isQualifiedName(name)) {
const containerExpr = entityNameToExpression(name.left);
if (containerExpr === undefined) {
return undefined;
}
return ts.createPropertyAccess(containerExpr, name.right);
}
const decl = symbol.declarations[0];
// If the given entity name has been resolved to an alias import declaration,
// ensure that the alias declaration is not elided by TypeScript, and use its
// name identifier to reference it at runtime.
if (isAliasImportDeclaration(decl)) {
referencedParameterTypes.add(decl);
// If the entity name resolves to an alias import declaration, we reference the
// entity based on the alias import name. This ensures that TypeScript properly
// resolves the link to the import. Cloning the original entity name identifier
// could lead to an incorrect resolution at local scope. e.g. Consider the following
// snippet: `constructor(Dep: Dep) {}`. In such a case, the local `Dep` identifier
// would resolve to the actual parameter name, and not to the desired import.
// This happens because the entity name identifier symbol is internally considered
// as type-only and therefore TypeScript tries to resolve it as value manually.
// We can help TypeScript and avoid this non-reliable resolution by using an identifier
// that is not type-only and is directly linked to the import alias declaration.
if (decl.name !== undefined) {
return ts.getMutableClone(decl.name);
}
}
// Clone the original entity name identifier so that it can be used to reference
// its value at runtime. This is used when the identifier is resolving to a file
// local declaration (otherwise it would resolve to an alias import declaration).
return ts.getMutableClone(name);
}
/**
* Transforms a class element. Returns a three tuple of name, transformed element, and
* decorators found. Returns an undefined name if there are no decorators to lower on the
* element, or the element has an exotic name.
*/
function transformClassElement(element: ts.ClassElement): [string | undefined, ts.ClassElement, ts.Decorator[]] {
element = ts.visitEachChild(element, decoratorDownlevelVisitor, context);
const decoratorsToKeep: ts.Decorator[] = [];
const toLower: ts.Decorator[] = [];
const decorators = host.getDecoratorsOfDeclaration(element) || [];
for (const decorator of decorators) {
// We only deal with concrete nodes in TypeScript sources, so we don't
// need to handle synthetically created decorators.
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const decoratorNode = decorator.node! as ts.Decorator;
if (!isAngularDecorator(decorator, isCore)) {
decoratorsToKeep.push(decoratorNode);
continue;
}
toLower.push(decoratorNode);
}
if (!toLower.length) return [undefined, element, []];
if (!element.name || !ts.isIdentifier(element.name)) {
// Method has a weird name, e.g.
// [Symbol.foo]() {...}
diagnostics.push({
file: element.getSourceFile(),
start: element.getStart(),
length: element.getEnd() - element.getStart(),
messageText: `Cannot process decorators for class element with non-analyzable name.`,
category: ts.DiagnosticCategory.Error,
code: 0,
});
return [undefined, element, []];
}
const name = (element.name as ts.Identifier).text;
const mutable = ts.getMutableClone(element);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(mutable as any).decorators = decoratorsToKeep.length
? ts.setTextRange(ts.createNodeArray(decoratorsToKeep), mutable.decorators)
: undefined;
return [name, mutable, toLower];
}
/**
* Transforms a constructor. Returns the transformed constructor and the list of parameter
* information collected, consisting of decorators and optional type.
*/
function transformConstructor(
ctor: ts.ConstructorDeclaration,
): [ts.ConstructorDeclaration, ParameterDecorationInfo[]] {
ctor = ts.visitEachChild(ctor, decoratorDownlevelVisitor, context);
const newParameters: ts.ParameterDeclaration[] = [];
const oldParameters = ts.visitParameterList(ctor.parameters, decoratorDownlevelVisitor, context);
const parametersInfo: ParameterDecorationInfo[] = [];
for (const param of oldParameters) {
const decoratorsToKeep: ts.Decorator[] = [];
const paramInfo: ParameterDecorationInfo = { decorators: [], type: null };
const decorators = host.getDecoratorsOfDeclaration(param) || [];
for (const decorator of decorators) {
// We only deal with concrete nodes in TypeScript sources, so we don't
// need to handle synthetically created decorators.
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const decoratorNode = decorator.node! as ts.Decorator;
if (!isAngularDecorator(decorator, isCore)) {
decoratorsToKeep.push(decoratorNode);
continue;
}
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
paramInfo!.decorators.push(decoratorNode);
}
if (param.type) {
// param has a type provided, e.g. "foo: Bar".
// The type will be emitted as a value expression in entityNameToExpression, which takes
// care not to emit anything for types that cannot be expressed as a value (e.g.
// interfaces).
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
paramInfo!.type = param.type;
}
parametersInfo.push(paramInfo);
const newParam = ts.updateParameter(
param,
// Must pass 'undefined' to avoid emitting decorator metadata.
decoratorsToKeep.length ? decoratorsToKeep : undefined,
param.modifiers,
param.dotDotDotToken,
param.name,
param.questionToken,
param.type,
param.initializer,
);
newParameters.push(newParam);
}
const updated = ts.updateConstructor(
ctor,
ctor.decorators,
ctor.modifiers,
newParameters,
ts.visitFunctionBody(ctor.body, decoratorDownlevelVisitor, context),
);
return [updated, parametersInfo];
}
/**
* Transforms a single class declaration:
* - dispatches to strip decorators on members
* - converts decorators on the class to annotations
* - creates a ctorParameters property
* - creates a propDecorators property
*/
function transformClassDeclaration(classDecl: ts.ClassDeclaration): ts.ClassDeclaration {
classDecl = ts.getMutableClone(classDecl);
const newMembers: ts.ClassElement[] = [];
const decoratedProperties = new Map<string, ts.Decorator[]>();
let classParameters: ParameterDecorationInfo[] | null = null;
for (const member of classDecl.members) {
switch (member.kind) {
case ts.SyntaxKind.PropertyDeclaration:
case ts.SyntaxKind.GetAccessor:
case ts.SyntaxKind.SetAccessor:
case ts.SyntaxKind.MethodDeclaration: {
const [name, newMember, decorators] = transformClassElement(member);
newMembers.push(newMember);
if (name) decoratedProperties.set(name, decorators);
continue;
}
case ts.SyntaxKind.Constructor: {
const ctor = member as ts.ConstructorDeclaration;
if (!ctor.body) break;
const [newMember, parametersInfo] = transformConstructor(member as ts.ConstructorDeclaration);
classParameters = parametersInfo;
newMembers.push(newMember);
continue;
}
default:
break;
}
newMembers.push(ts.visitEachChild(member, decoratorDownlevelVisitor, context));
}
// The `ReflectionHost.getDecoratorsOfDeclaration()` method will not return certain kinds of
// decorators that will never be Angular decorators. So we cannot rely on it to capture all
// the decorators that should be kept. Instead we start off with a set of the raw decorators
// on the class, and only remove the ones that have been identified for downleveling.
const decoratorsToKeep = new Set<ts.Decorator>(classDecl.decorators);
const possibleAngularDecorators = host.getDecoratorsOfDeclaration(classDecl) || [];
let hasAngularDecorator = false;
const decoratorsToLower = [];
for (const decorator of possibleAngularDecorators) {
// We only deal with concrete nodes in TypeScript sources, so we don't
// need to handle synthetically created decorators.
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const decoratorNode = decorator.node! as ts.Decorator;
const isNgDecorator = isAngularDecorator(decorator, isCore);
// Keep track if we come across an Angular class decorator. This is used
// for to determine whether constructor parameters should be captured or not.
if (isNgDecorator) {
hasAngularDecorator = true;
}
if (isNgDecorator && !skipClassDecorators) {
decoratorsToLower.push(extractMetadataFromSingleDecorator(decoratorNode, diagnostics));
decoratorsToKeep.delete(decoratorNode);
}
}
if (decoratorsToLower.length) {
newMembers.push(createDecoratorClassProperty(decoratorsToLower));
}
if (classParameters) {
if (hasAngularDecorator || classParameters.some((p) => !!p.decorators.length)) {
// Capture constructor parameters if the class has Angular decorator applied,
// or if any of the parameters has decorators applied directly.
newMembers.push(
createCtorParametersClassProperty(
diagnostics,
entityNameToExpression,
classParameters,
isClosureCompilerEnabled,
),
);
}
}
if (decoratedProperties.size) {
newMembers.push(createPropDecoratorsClassProperty(diagnostics, decoratedProperties));
}
const members = ts.setTextRange(
ts.createNodeArray(newMembers, classDecl.members.hasTrailingComma),
classDecl.members,
);
return ts.updateClassDeclaration(
classDecl,
decoratorsToKeep.size ? Array.from(decoratorsToKeep) : undefined,
classDecl.modifiers,
classDecl.name,
classDecl.typeParameters,
classDecl.heritageClauses,
members,
);
}
/**
* Transformer visitor that looks for Angular decorators and replaces them with
* downleveled static properties. Also collects constructor type metadata for
* class declaration that are decorated with an Angular decorator.
*/
function decoratorDownlevelVisitor(node: ts.Node): ts.Node {
if (ts.isClassDeclaration(node)) {
return transformClassDeclaration(node);
}
return ts.visitEachChild(node, decoratorDownlevelVisitor, context);
}
return (sf: ts.SourceFile) => {
// Downlevel decorators and constructor parameter types. We will keep track of all
// referenced constructor parameter types so that we can instruct TypeScript to
// not elide their imports if they previously were only type-only.
return ts.visitEachChild(sf, decoratorDownlevelVisitor, context);
};
};
}