forked from angular/angular
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
776 lines (697 loc) · 26.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
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
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
/**
* @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
*/
import {CssSelector, ParseSourceFile, ParseSourceSpan, parseTemplate, R3TargetBinder, SchemaMetadata, SelectorMatcher, TmplAstElement, Type} from '@angular/compiler';
import ts from 'typescript';
import {absoluteFrom, AbsoluteFsPath, getSourceFileOrError, LogicalFileSystem} from '../../file_system';
import {TestFile} from '../../file_system/testing';
import {AbsoluteModuleStrategy, LocalIdentifierStrategy, LogicalProjectStrategy, ModuleResolver, Reexport, Reference, ReferenceEmitter, RelativePathStrategy} from '../../imports';
import {NOOP_INCREMENTAL_BUILD} from '../../incremental';
import {ClassPropertyMapping, CompoundMetadataReader, DirectiveMeta, HostDirectivesResolver, MatchSource, MetadataReader, MetadataReaderWithIndex, MetaKind} from '../../metadata';
import {NOOP_PERF_RECORDER} from '../../perf';
import {TsCreateProgramDriver} from '../../program_driver';
import {ClassDeclaration, isNamedClassDeclaration, TypeScriptReflectionHost} from '../../reflection';
import {ComponentScopeKind, ComponentScopeReader, LocalModuleScope, ScopeData, TypeCheckScopeRegistry} from '../../scope';
import {makeProgram} from '../../testing';
import {getRootDirs} from '../../util/src/typescript';
import {ProgramTypeCheckAdapter, TemplateDiagnostic, TemplateTypeChecker, TypeCheckContext} from '../api';
import {TemplateId, TemplateSourceMapping, TypeCheckableDirectiveMeta, TypeCheckBlockMetadata, TypeCheckingConfig} from '../api/api';
import {TemplateTypeCheckerImpl} from '../src/checker';
import {DomSchemaChecker} from '../src/dom';
import {OutOfBandDiagnosticRecorder} from '../src/oob';
import {TypeCheckShimGenerator} from '../src/shim';
import {TcbGenericContextBehavior} from '../src/type_check_block';
import {TypeCheckFile} from '../src/type_check_file';
export function typescriptLibDts(): TestFile {
return {
name: absoluteFrom('/lib.d.ts'),
contents: `
type Partial<T> = { [P in keyof T]?: T[P]; };
type Pick<T, K extends keyof T> = { [P in K]: T[P]; };
type NonNullable<T> = T extends null | undefined ? never : T;
// The following native type declarations are required for proper type inference
declare interface Function {
call(...args: any[]): any;
}
declare interface Array<T> {
[index: number]: T;
length: number;
}
declare interface Iterable<T> {}
declare interface String {
length: number;
}
declare interface Event {
preventDefault(): void;
}
declare interface MouseEvent extends Event {
readonly x: number;
readonly y: number;
}
declare interface HTMLElementEventMap {
"click": MouseEvent;
}
declare interface HTMLElement {
addEventListener<K extends keyof HTMLElementEventMap>(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any): void;
addEventListener(type: string, listener: (evt: Event) => void): void;
}
declare interface HTMLDivElement extends HTMLElement {}
declare interface HTMLImageElement extends HTMLElement {
src: string;
alt: string;
width: number;
height: number;
}
declare interface HTMLQuoteElement extends HTMLElement {
cite: string;
}
declare interface HTMLElementTagNameMap {
"blockquote": HTMLQuoteElement;
"div": HTMLDivElement;
"img": HTMLImageElement;
}
declare interface Document {
createElement<K extends keyof HTMLElementTagNameMap>(tagName: K): HTMLElementTagNameMap[K];
createElement(tagName: string): HTMLElement;
}
declare const document: Document;
`
};
}
export function angularCoreDts(): TestFile {
return {
name: absoluteFrom('/node_modules/@angular/core/index.d.ts'),
contents: `
export declare class TemplateRef<C> {
readonly elementRef: unknown;
createEmbeddedView(context: C): unknown;
}
export declare class EventEmitter<T> {
subscribe(next?: (value: T) => void, error?: (error: any) => void, complete?: () => void): unknown;
subscribe(observerOrNext?: any, error?: any, complete?: any): unknown;
}
export declare type NgIterable<T> = Array<T> | Iterable<T>;
`
};
}
export function angularAnimationsDts(): TestFile {
return {
name: absoluteFrom('/node_modules/@angular/animations/index.d.ts'),
contents: `
export declare class AnimationEvent {
element: any;
}
`
};
}
export function ngIfDeclaration(): TestDeclaration {
return {
type: 'directive',
file: absoluteFrom('/ngif.d.ts'),
selector: '[ngIf]',
name: 'NgIf',
inputs: {ngIf: 'ngIf'},
ngTemplateGuards: [{type: 'binding', inputName: 'ngIf'}],
hasNgTemplateContextGuard: true,
isGeneric: true,
};
}
export function ngIfDts(): TestFile {
return {
name: absoluteFrom('/ngif.d.ts'),
contents: `
export declare class NgIf<T> {
ngIf: T;
static ngTemplateContextGuard<T>(dir: NgIf<T>, ctx: any): ctx is NgIfContext<Exclude<T, false|0|''|null|undefined>>
}
export declare class NgIfContext<T> {
$implicit: T;
ngIf: T;
}`,
};
}
export function ngForDeclaration(): TestDeclaration {
return {
type: 'directive',
file: absoluteFrom('/ngfor.d.ts'),
selector: '[ngForOf]',
name: 'NgForOf',
inputs: {ngForOf: 'ngForOf', ngForTrackBy: 'ngForTrackBy', ngForTemplate: 'ngForTemplate'},
hasNgTemplateContextGuard: true,
isGeneric: true,
};
}
export function ngForDts(): TestFile {
return {
name: absoluteFrom('/ngfor.d.ts'),
contents: `
export declare class NgForOf<T> {
ngForOf: T[];
ngForTrackBy: TrackByFunction<T>;
static ngTemplateContextGuard<T>(dir: NgForOf<T>, ctx: any): ctx is NgForOfContext<T>;
}
export interface TrackByFunction<T> {
(index: number, item: T): any;
}
export declare class NgForOfContext<T> {
$implicit: T;
index: number;
count: number;
readonly odd: boolean;
readonly even: boolean;
readonly first: boolean;
readonly last: boolean;
}`,
};
}
export function ngForTypeCheckTarget(): TypeCheckingTarget {
const dts = ngForDts();
return {
...dts,
fileName: dts.name,
source: dts.contents,
templates: {},
};
}
export const ALL_ENABLED_CONFIG: Readonly<TypeCheckingConfig> = {
applyTemplateContextGuards: true,
checkQueries: false,
checkTemplateBodies: true,
alwaysCheckSchemaInTemplateBodies: true,
checkTypeOfInputBindings: true,
honorAccessModifiersForInputBindings: true,
strictNullInputBindings: true,
checkTypeOfAttributes: true,
// Feature is still in development.
// TODO(alxhub): enable when DOM checking via lib.dom.d.ts is further along.
checkTypeOfDomBindings: false,
checkTypeOfOutputEvents: true,
checkTypeOfAnimationEvents: true,
checkTypeOfDomEvents: true,
checkTypeOfDomReferences: true,
checkTypeOfNonDomReferences: true,
checkTypeOfPipes: true,
strictSafeNavigationTypes: true,
useContextGenericType: true,
strictLiteralTypes: true,
enableTemplateTypeChecker: false,
useInlineTypeConstructors: true,
suggestionsForSuboptimalTypeInference: false,
};
// Remove 'ref' from TypeCheckableDirectiveMeta and add a 'selector' instead.
export interface TestDirective extends Partial<Pick<
TypeCheckableDirectiveMeta,
Exclude<
keyof TypeCheckableDirectiveMeta,
'ref'|'coercedInputFields'|'restrictedInputFields'|'stringLiteralInputFields'|
'undeclaredInputFields'|'inputs'|'outputs'|'hostDirectives'>>> {
selector: string;
name: string;
file?: AbsoluteFsPath;
type: 'directive';
inputs?: {[fieldName: string]: string};
outputs?: {[fieldName: string]: string};
coercedInputFields?: string[];
restrictedInputFields?: string[];
stringLiteralInputFields?: string[];
undeclaredInputFields?: string[];
isGeneric?: boolean;
code?: string;
hostDirectives?: {
directive: TestDirective&{isStandalone: true},
inputs?: string[],
outputs?: string[],
}[];
}
export interface TestPipe {
name: string;
file?: AbsoluteFsPath;
isStandalone?: boolean;
pipeName: string;
type: 'pipe';
code?: string;
}
export type TestDeclaration = TestDirective|TestPipe;
export function tcb(
template: string, declarations: TestDeclaration[] = [], config?: Partial<TypeCheckingConfig>,
options?: {emitSpans?: boolean}): string {
const codeLines = [`export class Test<T extends string> {}`];
(function addCodeLines(currentDeclarations) {
for (const decl of currentDeclarations) {
if (decl.type === 'directive' && decl.hostDirectives) {
addCodeLines(decl.hostDirectives.map(hostDir => hostDir.directive));
}
codeLines.push(decl.code ?? `export class ${decl.name}<T extends string> {}`);
}
})(declarations);
const rootFilePath = absoluteFrom('/synthetic.ts');
const {program, host} = makeProgram([
{name: rootFilePath, contents: codeLines.join('\n'), isRoot: true},
]);
const sf = getSourceFileOrError(program, rootFilePath);
const clazz = getClass(sf, 'Test');
const templateUrl = 'synthetic.html';
const {nodes} = parseTemplate(template, templateUrl);
const {matcher, pipes} =
prepareDeclarations(declarations, decl => getClass(sf, decl.name), new Map());
const binder = new R3TargetBinder<DirectiveMeta>(matcher);
const boundTarget = binder.bind({template: nodes});
const id = 'tcb' as TemplateId;
const meta: TypeCheckBlockMetadata = {id, boundTarget, pipes, schemas: [], isStandalone: false};
const fullConfig: TypeCheckingConfig = {
applyTemplateContextGuards: true,
checkQueries: false,
checkTypeOfInputBindings: true,
honorAccessModifiersForInputBindings: false,
strictNullInputBindings: true,
checkTypeOfAttributes: true,
checkTypeOfDomBindings: false,
checkTypeOfOutputEvents: true,
checkTypeOfAnimationEvents: true,
checkTypeOfDomEvents: true,
checkTypeOfDomReferences: true,
checkTypeOfNonDomReferences: true,
checkTypeOfPipes: true,
checkTemplateBodies: true,
alwaysCheckSchemaInTemplateBodies: true,
strictSafeNavigationTypes: true,
useContextGenericType: true,
strictLiteralTypes: true,
enableTemplateTypeChecker: false,
useInlineTypeConstructors: true,
suggestionsForSuboptimalTypeInference: false,
...config
};
options = options || {
emitSpans: false,
};
const fileName = absoluteFrom('/type-check-file.ts');
const reflectionHost = new TypeScriptReflectionHost(program.getTypeChecker());
const refEmmiter: ReferenceEmitter = new ReferenceEmitter(
[new LocalIdentifierStrategy(), new RelativePathStrategy(reflectionHost)]);
const env = new TypeCheckFile(fileName, fullConfig, refEmmiter, reflectionHost, host);
env.addTypeCheckBlock(
new Reference(clazz), meta, new NoopSchemaChecker(), new NoopOobRecorder(),
TcbGenericContextBehavior.UseEmitter);
const rendered = env.render(!options.emitSpans /* removeComments */);
return rendered.replace(/\s+/g, ' ');
}
/**
* A file in the test program, along with any template information for components within the file.
*/
export interface TypeCheckingTarget {
/**
* Path to the file in the virtual test filesystem.
*/
fileName: AbsoluteFsPath;
/**
* Raw source code for the file.
*
* If this is omitted, source code for the file will be generated based on any expected component
* classes.
*/
source?: string;
/**
* A map of component class names to string templates for that component.
*/
templates: {[className: string]: string};
/**
* Any declarations (e.g. directives) which should be considered as part of the scope for the
* components in this file.
*/
declarations?: TestDeclaration[];
}
/**
* Create a testing environment for template type-checking which contains a number of given test
* targets.
*
* A full Angular environment is not necessary to exercise the template type-checking system.
* Components only need to be classes which exist, with templates specified in the target
* configuration. In many cases, it's not even necessary to include source code for test files, as
* that can be auto-generated based on the provided target configuration.
*/
export function setup(targets: TypeCheckingTarget[], overrides: {
config?: Partial<TypeCheckingConfig>,
options?: ts.CompilerOptions,
inlining?: boolean,
} = {}): {
templateTypeChecker: TemplateTypeChecker,
program: ts.Program,
programStrategy: TsCreateProgramDriver,
} {
const files = [
typescriptLibDts(),
angularCoreDts(),
angularAnimationsDts(),
];
const fakeMetadataRegistry = new Map();
for (const target of targets) {
let contents: string;
if (target.source !== undefined) {
contents = target.source;
} else {
contents = `// generated from templates\n\nexport const MODULE = true;\n\n`;
for (const className of Object.keys(target.templates)) {
contents += `export class ${className} {}\n`;
}
}
files.push({
name: target.fileName,
contents,
});
if (!target.fileName.endsWith('.d.ts')) {
files.push({
name: TypeCheckShimGenerator.shimFor(target.fileName),
contents: 'export const MODULE = true;',
});
}
}
const opts = overrides.options ?? {};
const config = overrides.config ?? {};
const {program, host, options} = makeProgram(
files, {strictNullChecks: true, noImplicitAny: true, ...opts}, /* host */ undefined,
/* checkForErrors */ false);
const checker = program.getTypeChecker();
const logicalFs = new LogicalFileSystem(getRootDirs(host, options), host);
const reflectionHost = new TypeScriptReflectionHost(checker);
const moduleResolver =
new ModuleResolver(program, options, host, /* moduleResolutionCache */ null);
const emitter = new ReferenceEmitter([
new LocalIdentifierStrategy(),
new AbsoluteModuleStrategy(
program, checker, moduleResolver, new TypeScriptReflectionHost(checker)),
new LogicalProjectStrategy(reflectionHost, logicalFs),
]);
const fullConfig = {
...ALL_ENABLED_CONFIG,
useInlineTypeConstructors: overrides.inlining !== undefined ?
overrides.inlining :
ALL_ENABLED_CONFIG.useInlineTypeConstructors,
...config
};
// Map out the scope of each target component, which is needed for the ComponentScopeReader.
const scopeMap = new Map<ClassDeclaration, ScopeData>();
for (const target of targets) {
const sf = getSourceFileOrError(program, target.fileName);
const scope = makeScope(program, sf, target.declarations ?? []);
for (const className of Object.keys(target.templates)) {
const classDecl = getClass(sf, className);
scopeMap.set(classDecl, scope);
}
}
const checkAdapter = createTypeCheckAdapter((sf, ctx) => {
for (const target of targets) {
if (getSourceFileOrError(program, target.fileName) !== sf) {
continue;
}
const declarations = target.declarations ?? [];
for (const className of Object.keys(target.templates)) {
const classDecl = getClass(sf, className);
const template = target.templates[className];
const templateUrl = `${className}.html`;
const templateFile = new ParseSourceFile(template, templateUrl);
const {nodes, errors} = parseTemplate(template, templateUrl);
if (errors !== null) {
throw new Error('Template parse errors: \n' + errors.join('\n'));
}
const {matcher, pipes} = prepareDeclarations(declarations, decl => {
let declFile = sf;
if (decl.file !== undefined) {
declFile = program.getSourceFile(decl.file)!;
if (declFile === undefined) {
throw new Error(`Unable to locate ${decl.file} for ${decl.type} ${decl.name}`);
}
}
return getClass(declFile, decl.name);
}, fakeMetadataRegistry);
const binder = new R3TargetBinder<DirectiveMeta>(matcher);
const classRef = new Reference(classDecl);
const sourceMapping: TemplateSourceMapping = {
type: 'external',
template,
templateUrl,
componentClass: classRef.node,
// Use the class's name for error mappings.
node: classRef.node.name,
};
ctx.addTemplate(
classRef, binder, nodes, pipes, [], sourceMapping, templateFile, errors, false);
}
}
});
const programStrategy = new TsCreateProgramDriver(program, host, options, ['ngtypecheck']);
if (overrides.inlining !== undefined) {
(programStrategy as any).supportsInlineOperations = overrides.inlining;
}
const fakeScopeReader: ComponentScopeReader = {
getRemoteScope(): null {
return null;
},
// If there is a module with [className] + 'Module' in the same source file, that will be
// returned as the NgModule for the class.
getScopeForComponent(clazz: ClassDeclaration): LocalModuleScope |
null {
try {
const ngModule = getClass(clazz.getSourceFile(), `${clazz.name.getText()}Module`);
if (!scopeMap.has(clazz)) {
// This class wasn't part of the target set of components with templates, but is
// probably a declaration used in one of them. Return an empty scope.
const emptyScope: ScopeData = {
dependencies: [],
isPoisoned: false,
};
return {
kind: ComponentScopeKind.NgModule,
ngModule,
compilation: emptyScope,
reexports: [],
schemas: [],
exported: emptyScope,
};
}
const scope = scopeMap.get(clazz)!;
return {
kind: ComponentScopeKind.NgModule,
ngModule,
compilation: scope,
reexports: [],
schemas: [],
exported: scope,
};
} catch (e) {
// No NgModule was found for this class, so it has no scope.
return null;
}
}
};
const fakeMetadataReader = getFakeMetadataReader(fakeMetadataRegistry);
const typeCheckScopeRegistry = new TypeCheckScopeRegistry(
fakeScopeReader, new CompoundMetadataReader([fakeMetadataReader]),
new HostDirectivesResolver(fakeMetadataReader));
const templateTypeChecker = new TemplateTypeCheckerImpl(
program, programStrategy, checkAdapter, fullConfig, emitter, reflectionHost, host,
NOOP_INCREMENTAL_BUILD, fakeMetadataReader, fakeMetadataReader, fakeScopeReader,
typeCheckScopeRegistry, NOOP_PERF_RECORDER);
return {
templateTypeChecker,
program,
programStrategy,
};
}
function createTypeCheckAdapter(fn: (sf: ts.SourceFile, ctx: TypeCheckContext) => void):
ProgramTypeCheckAdapter {
return {typeCheck: fn};
}
function getFakeMetadataReader(fakeMetadataRegistry: Map<any, DirectiveMeta|null>):
MetadataReaderWithIndex {
return {
getDirectiveMetadata(node: Reference<ClassDeclaration>): DirectiveMeta |
null {
return fakeMetadataRegistry.get(node.debugName) ?? null;
},
getKnown(kind: MetaKind): Iterable<ClassDeclaration> {
switch (kind) {
case MetaKind.Directive:
return fakeMetadataRegistry.keys();
default:
return [];
}
}
} as MetadataReaderWithIndex;
}
type DeclarationResolver = (decl: TestDeclaration) => ClassDeclaration<ts.ClassDeclaration>;
function prepareDeclarations(
declarations: TestDeclaration[], resolveDeclaration: DeclarationResolver,
metadataRegistry: Map<string, TypeCheckableDirectiveMeta>) {
const matcher = new SelectorMatcher<DirectiveMeta[]>();
const pipes = new Map<string, Reference<ClassDeclaration<ts.ClassDeclaration>>>();
const hostDirectiveResolder = new HostDirectivesResolver(
getFakeMetadataReader(metadataRegistry as Map<string, DirectiveMeta>));
const directives: DirectiveMeta[] = [];
const registerDirective = (decl: TestDirective) => {
const meta = getDirectiveMetaFromDeclaration(decl, resolveDeclaration);
directives.push(meta as DirectiveMeta);
metadataRegistry.set(decl.name, meta);
decl.hostDirectives?.forEach(hostDecl => registerDirective(hostDecl.directive));
};
for (const decl of declarations) {
if (decl.type === 'directive') {
registerDirective(decl);
} else if (decl.type === 'pipe') {
pipes.set(decl.pipeName, new Reference(resolveDeclaration(decl)));
}
}
// We need to make two passes over the directives so that all declarations
// have been registered by the time we resolve the host directives.
for (const meta of directives) {
const selector = CssSelector.parse(meta.selector || '');
const matches = [...hostDirectiveResolder.resolve(meta), meta] as DirectiveMeta[];
matcher.addSelectables(selector, matches);
}
return {matcher, pipes};
}
export function getClass(sf: ts.SourceFile, name: string): ClassDeclaration<ts.ClassDeclaration> {
for (const stmt of sf.statements) {
if (isNamedClassDeclaration(stmt) && stmt.name.text === name) {
return stmt;
}
}
throw new Error(`Class ${name} not found in file: ${sf.fileName}: ${sf.text}`);
}
function getDirectiveMetaFromDeclaration(
decl: TestDirective, resolveDeclaration: DeclarationResolver) {
return {
name: decl.name,
ref: new Reference(resolveDeclaration(decl)),
exportAs: decl.exportAs || null,
selector: decl.selector || null,
hasNgTemplateContextGuard: decl.hasNgTemplateContextGuard || false,
inputs: ClassPropertyMapping.fromMappedObject(decl.inputs || {}),
isComponent: decl.isComponent || false,
ngTemplateGuards: decl.ngTemplateGuards || [],
coercedInputFields: new Set<string>(decl.coercedInputFields || []),
restrictedInputFields: new Set<string>(decl.restrictedInputFields || []),
stringLiteralInputFields: new Set<string>(decl.stringLiteralInputFields || []),
undeclaredInputFields: new Set<string>(decl.undeclaredInputFields || []),
isGeneric: decl.isGeneric ?? false,
outputs: ClassPropertyMapping.fromMappedObject(decl.outputs || {}),
queries: decl.queries || [],
isStructural: false,
isStandalone: !!decl.isStandalone,
baseClass: null,
animationTriggerNames: null,
hostDirectives: decl.hostDirectives === undefined ? null : decl.hostDirectives.map(hostDecl => {
return {
directive: new Reference(resolveDeclaration(hostDecl.directive)),
inputs: parseInputOutputMappingArray(hostDecl.inputs || []),
outputs: parseInputOutputMappingArray(hostDecl.outputs || [])
};
}),
} as TypeCheckableDirectiveMeta;
}
/**
* Synthesize `ScopeData` metadata from an array of `TestDeclaration`s.
*/
function makeScope(program: ts.Program, sf: ts.SourceFile, decls: TestDeclaration[]): ScopeData {
const scope: ScopeData = {
dependencies: [],
isPoisoned: false,
};
for (const decl of decls) {
let declSf = sf;
if (decl.file !== undefined) {
declSf = getSourceFileOrError(program, decl.file);
}
const declClass = getClass(declSf, decl.name);
if (decl.type === 'directive') {
scope.dependencies.push({
kind: MetaKind.Directive,
matchSource: MatchSource.Selector,
ref: new Reference(declClass),
baseClass: null,
name: decl.name,
selector: decl.selector,
queries: [],
inputs: ClassPropertyMapping.fromMappedObject(decl.inputs || {}),
outputs: ClassPropertyMapping.fromMappedObject(decl.outputs || {}),
isComponent: decl.isComponent ?? false,
exportAs: decl.exportAs ?? null,
ngTemplateGuards: decl.ngTemplateGuards ?? [],
hasNgTemplateContextGuard: decl.hasNgTemplateContextGuard ?? false,
coercedInputFields: new Set(decl.coercedInputFields ?? []),
restrictedInputFields: new Set(decl.restrictedInputFields ?? []),
stringLiteralInputFields: new Set(decl.stringLiteralInputFields ?? []),
undeclaredInputFields: new Set(decl.undeclaredInputFields ?? []),
isGeneric: decl.isGeneric ?? false,
isPoisoned: false,
isStructural: false,
animationTriggerNames: null,
isStandalone: false,
imports: null,
schemas: null,
decorator: null,
hostDirectives:
decl.hostDirectives === undefined ? null : decl.hostDirectives.map(hostDecl => {
return {
directive: new Reference(getClass(
hostDecl.directive.file ?
getSourceFileOrError(program, hostDecl.directive.file) :
sf,
hostDecl.directive.name)),
origin: sf,
isForwardReference: false,
inputs: hostDecl.directive.inputs || {},
outputs: hostDecl.directive.outputs || {},
};
}),
});
} else if (decl.type === 'pipe') {
scope.dependencies.push({
kind: MetaKind.Pipe,
ref: new Reference(declClass),
name: decl.pipeName,
nameExpr: null,
isStandalone: false,
decorator: null,
});
}
}
return scope;
}
function parseInputOutputMappingArray(values: string[]) {
return values.reduce((results, value) => {
// Either the value is 'field' or 'field: property'. In the first case, `property` will
// be undefined, in which case the field name should also be used as the property name.
const [field, property] = value.split(':', 2).map(str => str.trim());
results[field] = property || field;
return results;
}, {} as {[field: string]: string});
}
export class NoopSchemaChecker implements DomSchemaChecker {
get diagnostics(): ReadonlyArray<TemplateDiagnostic> {
return [];
}
checkElement(
id: string, element: TmplAstElement, schemas: SchemaMetadata[],
hostIsStandalone: boolean): void {}
checkProperty(
id: string, element: TmplAstElement, name: string, span: ParseSourceSpan,
schemas: SchemaMetadata[], hostIsStandalone: boolean): void {}
}
export class NoopOobRecorder implements OutOfBandDiagnosticRecorder {
get diagnostics(): ReadonlyArray<TemplateDiagnostic> {
return [];
}
missingReferenceTarget(): void {}
missingPipe(): void {}
illegalAssignmentToTemplateVar(): void {}
duplicateTemplateVar(): void {}
requiresInlineTcb(): void {}
requiresInlineTypeConstructors(): void {}
suboptimalTypeInference(): void {}
splitTwoWayBinding(): void {}
}