/
r3_test_bed_compiler.ts
756 lines (642 loc) · 30.5 KB
/
r3_test_bed_compiler.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
/**
* @license
* Copyright Google Inc. 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 {ResourceLoader} from '@angular/compiler';
import {ApplicationInitStatus, COMPILER_OPTIONS, Compiler, Component, Directive, Injector, LOCALE_ID, ModuleWithComponentFactories, ModuleWithProviders, NgModule, NgModuleFactory, NgZone, Pipe, PlatformRef, Provider, Type, ɵDEFAULT_LOCALE_ID as DEFAULT_LOCALE_ID, ɵDirectiveDef as DirectiveDef, ɵNG_COMP_DEF as NG_COMP_DEF, ɵNG_DIR_DEF as NG_DIR_DEF, ɵNG_INJ_DEF as NG_INJ_DEF, ɵNG_MOD_DEF as NG_MOD_DEF, ɵNG_PIPE_DEF as NG_PIPE_DEF, ɵNgModuleFactory as R3NgModuleFactory, ɵNgModuleTransitiveScopes as NgModuleTransitiveScopes, ɵNgModuleType as NgModuleType, ɵRender3ComponentFactory as ComponentFactory, ɵRender3NgModuleRef as NgModuleRef, ɵcompileComponent as compileComponent, ɵcompileDirective as compileDirective, ɵcompileNgModuleDefs as compileNgModuleDefs, ɵcompilePipe as compilePipe, ɵgetInjectableDef as getInjectableDef, ɵpatchComponentDefWithScope as patchComponentDefWithScope, ɵsetLocaleId as setLocaleId, ɵtransitiveScopesFor as transitiveScopesFor, ɵɵInjectableDef as InjectableDef} from '@angular/core';
import {ModuleRegistrationMap, getRegisteredModulesState, restoreRegisteredModulesState} from '../../src/linker/ng_module_factory_registration';
import {clearResolutionOfComponentResourcesQueue, isComponentDefPendingResolution, resolveComponentResources, restoreComponentResolutionQueue} from '../../src/metadata/resource_loading';
import {MetadataOverride} from './metadata_override';
import {ComponentResolver, DirectiveResolver, NgModuleResolver, PipeResolver, Resolver} from './resolvers';
import {TestModuleMetadata} from './test_bed_common';
enum TestingModuleOverride {
DECLARATION,
OVERRIDE_TEMPLATE,
}
function isTestingModuleOverride(value: unknown): value is TestingModuleOverride {
return value === TestingModuleOverride.DECLARATION ||
value === TestingModuleOverride.OVERRIDE_TEMPLATE;
}
// Resolvers for Angular decorators
type Resolvers = {
module: Resolver<NgModule>,
component: Resolver<Directive>,
directive: Resolver<Component>,
pipe: Resolver<Pipe>,
};
interface CleanupOperation {
field: string;
def: any;
original: unknown;
}
export class R3TestBedCompiler {
private originalComponentResolutionQueue: Map<Type<any>, Component>|null = null;
private originalRegisteredModules: null|ModuleRegistrationMap = null;
// Testing module configuration
private declarations: Type<any>[] = [];
private imports: Type<any>[] = [];
private providers: Provider[] = [];
private schemas: any[] = [];
// Queues of components/directives/pipes that should be recompiled.
private pendingComponents = new Set<Type<any>>();
private pendingDirectives = new Set<Type<any>>();
private pendingPipes = new Set<Type<any>>();
// Keep track of all components and directives, so we can patch Providers onto defs later.
private seenComponents = new Set<Type<any>>();
private seenDirectives = new Set<Type<any>>();
// Store resolved styles for Components that have template overrides present and `styleUrls`
// defined at the same time.
private existingComponentStyles = new Map<Type<any>, string[]>();
private resolvers: Resolvers = initResolvers();
private componentToModuleScope = new Map<Type<any>, Type<any>|TestingModuleOverride>();
// Map that keeps initial version of component/directive/pipe defs in case
// we compile a Type again, thus overriding respective static fields. This is
// required to make sure we restore defs to their initial states between test runs
// TODO: we should support the case with multiple defs on a type
private initialNgDefs = new Map<Type<any>, [string, PropertyDescriptor|undefined]>();
// Array that keeps cleanup operations for initial versions of component/directive/pipe/module
// defs in case TestBed makes changes to the originals.
private defCleanupOps: CleanupOperation[] = [];
private _injector: Injector|null = null;
private compilerProviders: Provider[]|null = null;
private providerOverrides: Provider[] = [];
private rootProviderOverrides: Provider[] = [];
private providerOverridesByToken = new Map<any, Provider>();
private moduleProvidersOverridden = new Set<Type<any>>();
private testModuleType: NgModuleType<any>;
private testModuleRef: NgModuleRef<any>|null = null;
constructor(private platform: PlatformRef, private additionalModuleTypes: Type<any>|Type<any>[]) {
class DynamicTestModule {}
this.testModuleType = DynamicTestModule as any;
}
setCompilerProviders(providers: Provider[]|null): void {
this.compilerProviders = providers;
this._injector = null;
}
configureTestingModule(moduleDef: TestModuleMetadata): void {
// Enqueue any compilation tasks for the directly declared component.
if (moduleDef.declarations !== undefined) {
this.queueTypeArray(moduleDef.declarations, TestingModuleOverride.DECLARATION);
this.declarations.push(...moduleDef.declarations);
}
// Enqueue any compilation tasks for imported modules.
if (moduleDef.imports !== undefined) {
this.queueTypesFromModulesArray(moduleDef.imports);
this.imports.push(...moduleDef.imports);
}
if (moduleDef.providers !== undefined) {
this.providers.push(...moduleDef.providers);
}
if (moduleDef.schemas !== undefined) {
this.schemas.push(...moduleDef.schemas);
}
}
overrideModule(ngModule: Type<any>, override: MetadataOverride<NgModule>): void {
// Compile the module right away.
this.resolvers.module.addOverride(ngModule, override);
const metadata = this.resolvers.module.resolve(ngModule);
if (metadata === null) {
throw new Error(`${ngModule.name} is not an @NgModule or is missing metadata`);
}
this.recompileNgModule(ngModule);
// At this point, the module has a valid module def (ɵmod), but the override may have introduced
// new declarations or imported modules. Ingest any possible new types and add them to the
// current queue.
this.queueTypesFromModulesArray([ngModule]);
}
overrideComponent(component: Type<any>, override: MetadataOverride<Component>): void {
this.resolvers.component.addOverride(component, override);
this.pendingComponents.add(component);
}
overrideDirective(directive: Type<any>, override: MetadataOverride<Directive>): void {
this.resolvers.directive.addOverride(directive, override);
this.pendingDirectives.add(directive);
}
overridePipe(pipe: Type<any>, override: MetadataOverride<Pipe>): void {
this.resolvers.pipe.addOverride(pipe, override);
this.pendingPipes.add(pipe);
}
overrideProvider(
token: any,
provider: {useFactory?: Function, useValue?: any, deps?: any[], multi?: boolean}): void {
const providerDef = provider.useFactory ?
{
provide: token,
useFactory: provider.useFactory,
deps: provider.deps || [],
multi: provider.multi
} :
{provide: token, useValue: provider.useValue, multi: provider.multi};
let injectableDef: InjectableDef<any>|null;
const isRoot =
(typeof token !== 'string' && (injectableDef = getInjectableDef(token)) &&
injectableDef.providedIn === 'root');
const overridesBucket = isRoot ? this.rootProviderOverrides : this.providerOverrides;
overridesBucket.push(providerDef);
// Keep overrides grouped by token as well for fast lookups using token
this.providerOverridesByToken.set(token, providerDef);
}
overrideTemplateUsingTestingModule(type: Type<any>, template: string): void {
const def = (type as any)[NG_COMP_DEF];
const hasStyleUrls = (): boolean => {
const metadata = this.resolvers.component.resolve(type) !as Component;
return !!metadata.styleUrls && metadata.styleUrls.length > 0;
};
const overrideStyleUrls = !!def && !isComponentDefPendingResolution(type) && hasStyleUrls();
// In Ivy, compiling a component does not require knowing the module providing the
// component's scope, so overrideTemplateUsingTestingModule can be implemented purely via
// overrideComponent. Important: overriding template requires full Component re-compilation,
// which may fail in case styleUrls are also present (thus Component is considered as required
// resolution). In order to avoid this, we preemptively set styleUrls to an empty array,
// preserve current styles available on Component def and restore styles back once compilation
// is complete.
const override = overrideStyleUrls ? {template, styles: [], styleUrls: []} : {template};
this.overrideComponent(type, {set: override});
if (overrideStyleUrls && def.styles && def.styles.length > 0) {
this.existingComponentStyles.set(type, def.styles);
}
// Set the component's scope to be the testing module.
this.componentToModuleScope.set(type, TestingModuleOverride.OVERRIDE_TEMPLATE);
}
async compileComponents(): Promise<void> {
this.clearComponentResolutionQueue();
// Run compilers for all queued types.
let needsAsyncResources = this.compileTypesSync();
// compileComponents() should not be async unless it needs to be.
if (needsAsyncResources) {
let resourceLoader: ResourceLoader;
let resolver = (url: string): Promise<string> => {
if (!resourceLoader) {
resourceLoader = this.injector.get(ResourceLoader);
}
return Promise.resolve(resourceLoader.get(url));
};
await resolveComponentResources(resolver);
}
}
finalize(): NgModuleRef<any> {
// One last compile
this.compileTypesSync();
// Create the testing module itself.
this.compileTestModule();
this.applyTransitiveScopes();
this.applyProviderOverrides();
// Patch previously stored `styles` Component values (taken from ɵcmp), in case these
// Components have `styleUrls` fields defined and template override was requested.
this.patchComponentsWithExistingStyles();
// Clear the componentToModuleScope map, so that future compilations don't reset the scope of
// every component.
this.componentToModuleScope.clear();
const parentInjector = this.platform.injector;
this.testModuleRef = new NgModuleRef(this.testModuleType, parentInjector);
// Set the locale ID, it can be overridden for the tests
const localeId = this.testModuleRef.injector.get(LOCALE_ID, DEFAULT_LOCALE_ID);
setLocaleId(localeId);
// ApplicationInitStatus.runInitializers() is marked @internal to core.
// Cast it to any before accessing it.
(this.testModuleRef.injector.get(ApplicationInitStatus) as any).runInitializers();
return this.testModuleRef;
}
/**
* @internal
*/
_compileNgModuleSync(moduleType: Type<any>): void {
this.queueTypesFromModulesArray([moduleType]);
this.compileTypesSync();
this.applyProviderOverrides();
this.applyProviderOverridesToModule(moduleType);
this.applyTransitiveScopes();
}
/**
* @internal
*/
async _compileNgModuleAsync(moduleType: Type<any>): Promise<void> {
if (this.originalRegisteredModules === null) {
this.originalRegisteredModules = getRegisteredModulesState();
}
this.queueTypesFromModulesArray([moduleType]);
await this.compileComponents();
this.applyProviderOverrides();
this.applyProviderOverridesToModule(moduleType);
this.applyTransitiveScopes();
}
/**
* @internal
*/
_getModuleResolver(): Resolver<NgModule> { return this.resolvers.module; }
/**
* @internal
*/
_getComponentFactories(moduleType: NgModuleType): ComponentFactory<any>[] {
return maybeUnwrapFn(moduleType.ɵmod.declarations).reduce((factories, declaration) => {
const componentDef = (declaration as any).ɵcmp;
componentDef && factories.push(new ComponentFactory(componentDef, this.testModuleRef !));
return factories;
}, [] as ComponentFactory<any>[]);
}
private compileTypesSync(): boolean {
// Compile all queued components, directives, pipes.
let needsAsyncResources = false;
this.pendingComponents.forEach(declaration => {
needsAsyncResources = needsAsyncResources || isComponentDefPendingResolution(declaration);
const metadata = this.resolvers.component.resolve(declaration) !;
this.maybeStoreNgDef(NG_COMP_DEF, declaration);
compileComponent(declaration, metadata);
});
this.pendingComponents.clear();
this.pendingDirectives.forEach(declaration => {
const metadata = this.resolvers.directive.resolve(declaration);
this.maybeStoreNgDef(NG_DIR_DEF, declaration);
compileDirective(declaration, metadata);
});
this.pendingDirectives.clear();
this.pendingPipes.forEach(declaration => {
const metadata = this.resolvers.pipe.resolve(declaration) !;
this.maybeStoreNgDef(NG_PIPE_DEF, declaration);
compilePipe(declaration, metadata);
});
this.pendingPipes.clear();
return needsAsyncResources;
}
private applyTransitiveScopes(): void {
const moduleToScope = new Map<Type<any>|TestingModuleOverride, NgModuleTransitiveScopes>();
const getScopeOfModule =
(moduleType: Type<any>| TestingModuleOverride): NgModuleTransitiveScopes => {
if (!moduleToScope.has(moduleType)) {
const realType = isTestingModuleOverride(moduleType) ? this.testModuleType : moduleType;
moduleToScope.set(moduleType, transitiveScopesFor(realType));
}
return moduleToScope.get(moduleType) !;
};
this.componentToModuleScope.forEach((moduleType, componentType) => {
const moduleScope = getScopeOfModule(moduleType);
this.storeFieldOfDefOnType(componentType, NG_COMP_DEF, 'directiveDefs');
this.storeFieldOfDefOnType(componentType, NG_COMP_DEF, 'pipeDefs');
patchComponentDefWithScope((componentType as any).ɵcmp, moduleScope);
});
this.componentToModuleScope.clear();
}
private applyProviderOverrides(): void {
const maybeApplyOverrides = (field: string) => (type: Type<any>) => {
const resolver = field === NG_COMP_DEF ? this.resolvers.component : this.resolvers.directive;
const metadata = resolver.resolve(type) !;
if (this.hasProviderOverrides(metadata.providers)) {
this.patchDefWithProviderOverrides(type, field);
}
};
this.seenComponents.forEach(maybeApplyOverrides(NG_COMP_DEF));
this.seenDirectives.forEach(maybeApplyOverrides(NG_DIR_DEF));
this.seenComponents.clear();
this.seenDirectives.clear();
}
private applyProviderOverridesToModule(moduleType: Type<any>): void {
if (this.moduleProvidersOverridden.has(moduleType)) {
return;
}
this.moduleProvidersOverridden.add(moduleType);
const injectorDef: any = (moduleType as any)[NG_INJ_DEF];
if (this.providerOverridesByToken.size > 0) {
// Extract the list of providers from ModuleWithProviders, so we can define the final list of
// providers that might have overrides.
// Note: second `flatten` operation is needed to convert an array of providers
// (e.g. `[[], []]`) into one flat list, also eliminating empty arrays.
const providersFromModules = flatten(flatten(
injectorDef.imports, (imported: NgModuleType<any>| ModuleWithProviders<any>) =>
isModuleWithProviders(imported) ? imported.providers : []));
const providers = [...providersFromModules, ...injectorDef.providers];
if (this.hasProviderOverrides(providers)) {
this.maybeStoreNgDef(NG_INJ_DEF, moduleType);
this.storeFieldOfDefOnType(moduleType, NG_INJ_DEF, 'providers');
injectorDef.providers = this.getOverriddenProviders(providers);
}
// Apply provider overrides to imported modules recursively
const moduleDef: any = (moduleType as any)[NG_MOD_DEF];
for (const importedModule of moduleDef.imports) {
this.applyProviderOverridesToModule(importedModule);
}
// Also override the providers on any ModuleWithProviders imports since those don't appear in
// the moduleDef.
for (const importedModule of flatten(injectorDef.imports)) {
if (isModuleWithProviders(importedModule)) {
importedModule.providers = this.getOverriddenProviders(importedModule.providers);
}
}
}
}
private patchComponentsWithExistingStyles(): void {
this.existingComponentStyles.forEach(
(styles, type) => (type as any)[NG_COMP_DEF].styles = styles);
this.existingComponentStyles.clear();
}
private queueTypeArray(arr: any[], moduleType: Type<any>|TestingModuleOverride): void {
for (const value of arr) {
if (Array.isArray(value)) {
this.queueTypeArray(value, moduleType);
} else {
this.queueType(value, moduleType);
}
}
}
private recompileNgModule(ngModule: Type<any>): void {
const metadata = this.resolvers.module.resolve(ngModule);
if (metadata === null) {
throw new Error(`Unable to resolve metadata for NgModule: ${ngModule.name}`);
}
// Cache the initial ngModuleDef as it will be overwritten.
this.maybeStoreNgDef(NG_MOD_DEF, ngModule);
this.maybeStoreNgDef(NG_INJ_DEF, ngModule);
compileNgModuleDefs(ngModule as NgModuleType<any>, metadata);
}
private queueType(type: Type<any>, moduleType: Type<any>|TestingModuleOverride): void {
const component = this.resolvers.component.resolve(type);
if (component) {
// Check whether a give Type has respective NG def (ɵcmp) and compile if def is
// missing. That might happen in case a class without any Angular decorators extends another
// class where Component/Directive/Pipe decorator is defined.
if (isComponentDefPendingResolution(type) || !type.hasOwnProperty(NG_COMP_DEF)) {
this.pendingComponents.add(type);
}
this.seenComponents.add(type);
// Keep track of the module which declares this component, so later the component's scope
// can be set correctly. If the component has already been recorded here, then one of several
// cases is true:
// * the module containing the component was imported multiple times (common).
// * the component is declared in multiple modules (which is an error).
// * the component was in 'declarations' of the testing module, and also in an imported module
// in which case the module scope will be TestingModuleOverride.DECLARATION.
// * overrideTemplateUsingTestingModule was called for the component in which case the module
// scope will be TestingModuleOverride.OVERRIDE_TEMPLATE.
//
// If the component was previously in the testing module's 'declarations' (meaning the
// current value is TestingModuleOverride.DECLARATION), then `moduleType` is the component's
// real module, which was imported. This pattern is understood to mean that the component
// should use its original scope, but that the testing module should also contain the
// component in its scope.
if (!this.componentToModuleScope.has(type) ||
this.componentToModuleScope.get(type) === TestingModuleOverride.DECLARATION) {
this.componentToModuleScope.set(type, moduleType);
}
return;
}
const directive = this.resolvers.directive.resolve(type);
if (directive) {
if (!type.hasOwnProperty(NG_DIR_DEF)) {
this.pendingDirectives.add(type);
}
this.seenDirectives.add(type);
return;
}
const pipe = this.resolvers.pipe.resolve(type);
if (pipe && !type.hasOwnProperty(NG_PIPE_DEF)) {
this.pendingPipes.add(type);
return;
}
}
private queueTypesFromModulesArray(arr: any[]): void {
for (const value of arr) {
if (Array.isArray(value)) {
this.queueTypesFromModulesArray(value);
} else if (hasNgModuleDef(value)) {
const def = value.ɵmod;
// Look through declarations, imports, and exports, and queue everything found there.
this.queueTypeArray(maybeUnwrapFn(def.declarations), value);
this.queueTypesFromModulesArray(maybeUnwrapFn(def.imports));
this.queueTypesFromModulesArray(maybeUnwrapFn(def.exports));
}
}
}
private maybeStoreNgDef(prop: string, type: Type<any>) {
if (!this.initialNgDefs.has(type)) {
const currentDef = Object.getOwnPropertyDescriptor(type, prop);
this.initialNgDefs.set(type, [prop, currentDef]);
}
}
private storeFieldOfDefOnType(type: Type<any>, defField: string, field: string): void {
const def: any = (type as any)[defField];
const original: any = def[field];
this.defCleanupOps.push({field, def, original});
}
/**
* Clears current components resolution queue, but stores the state of the queue, so we can
* restore it later. Clearing the queue is required before we try to compile components (via
* `TestBed.compileComponents`), so that component defs are in sync with the resolution queue.
*/
private clearComponentResolutionQueue() {
if (this.originalComponentResolutionQueue === null) {
this.originalComponentResolutionQueue = new Map();
}
clearResolutionOfComponentResourcesQueue().forEach(
(value, key) => this.originalComponentResolutionQueue !.set(key, value));
}
/*
* Restores component resolution queue to the previously saved state. This operation is performed
* as a part of restoring the state after completion of the current set of tests (that might
* potentially mutate the state).
*/
private restoreComponentResolutionQueue() {
if (this.originalComponentResolutionQueue !== null) {
restoreComponentResolutionQueue(this.originalComponentResolutionQueue);
this.originalComponentResolutionQueue = null;
}
}
restoreOriginalState(): void {
// Process cleanup ops in reverse order so the field's original value is restored correctly (in
// case there were multiple overrides for the same field).
forEachRight(this.defCleanupOps, (op: CleanupOperation) => { op.def[op.field] = op.original; });
// Restore initial component/directive/pipe defs
this.initialNgDefs.forEach(
(value: [string, PropertyDescriptor | undefined], type: Type<any>) => {
const [prop, descriptor] = value;
if (!descriptor) {
// Delete operations are generally undesirable since they have performance implications
// on objects they were applied to. In this particular case, situations where this code
// is invoked should be quite rare to cause any noticeable impact, since it's applied
// only to some test cases (for example when class with no annotations extends some
// @Component) when we need to clear 'ɵcmp' field on a given class to restore
// its original state (before applying overrides and running tests).
delete (type as any)[prop];
} else {
Object.defineProperty(type, prop, descriptor);
}
});
this.initialNgDefs.clear();
this.moduleProvidersOverridden.clear();
this.restoreComponentResolutionQueue();
if (this.originalRegisteredModules) {
restoreRegisteredModulesState(this.originalRegisteredModules);
this.originalRegisteredModules = null;
}
// Restore the locale ID to the default value, this shouldn't be necessary but we never know
setLocaleId(DEFAULT_LOCALE_ID);
}
private compileTestModule(): void {
class RootScopeModule {}
compileNgModuleDefs(RootScopeModule as NgModuleType<any>, {
providers: [...this.rootProviderOverrides],
});
const ngZone = new NgZone({enableLongStackTrace: true});
const providers: Provider[] = [
{provide: NgZone, useValue: ngZone},
{provide: Compiler, useFactory: () => new R3TestCompiler(this)},
...this.providers,
...this.providerOverrides,
];
const imports = [RootScopeModule, this.additionalModuleTypes, this.imports || []];
// clang-format off
compileNgModuleDefs(this.testModuleType, {
declarations: this.declarations,
imports,
schemas: this.schemas,
providers,
}, /* allowDuplicateDeclarationsInRoot */ true);
// clang-format on
this.applyProviderOverridesToModule(this.testModuleType);
}
get injector(): Injector {
if (this._injector !== null) {
return this._injector;
}
const providers: Provider[] = [];
const compilerOptions = this.platform.injector.get(COMPILER_OPTIONS);
compilerOptions.forEach(opts => {
if (opts.providers) {
providers.push(opts.providers);
}
});
if (this.compilerProviders !== null) {
providers.push(...this.compilerProviders);
}
// TODO(ocombe): make this work with an Injector directly instead of creating a module for it
class CompilerModule {}
compileNgModuleDefs(CompilerModule as NgModuleType<any>, {providers});
const CompilerModuleFactory = new R3NgModuleFactory(CompilerModule);
this._injector = CompilerModuleFactory.create(this.platform.injector).injector;
return this._injector;
}
// get overrides for a specific provider (if any)
private getSingleProviderOverrides(provider: Provider): Provider|null {
const token = getProviderToken(provider);
return this.providerOverridesByToken.get(token) || null;
}
private getProviderOverrides(providers?: Provider[]): Provider[] {
if (!providers || !providers.length || this.providerOverridesByToken.size === 0) return [];
// There are two flattening operations here. The inner flatten() operates on the metadata's
// providers and applies a mapping function which retrieves overrides for each incoming
// provider. The outer flatten() then flattens the produced overrides array. If this is not
// done, the array can contain other empty arrays (e.g. `[[], []]`) which leak into the
// providers array and contaminate any error messages that might be generated.
return flatten(flatten(
providers, (provider: Provider) => this.getSingleProviderOverrides(provider) || []));
}
private getOverriddenProviders(providers?: Provider[]): Provider[] {
if (!providers || !providers.length || this.providerOverridesByToken.size === 0) return [];
const flattenedProviders = flatten<Provider[]>(providers);
const overrides = this.getProviderOverrides(flattenedProviders);
const overriddenProviders = [...flattenedProviders, ...overrides];
const final: Provider[] = [];
const seenMultiProviders = new Set<Provider>();
// We iterate through the list of providers in reverse order to make sure multi provider
// overrides take precedence over the values defined in provider list. We also filter out all
// multi providers that have overrides, keeping overridden values only.
forEachRight(overriddenProviders, (provider: any) => {
const token: any = getProviderToken(provider);
if (isMultiProvider(provider) && this.providerOverridesByToken.has(token)) {
// Don't add overridden multi-providers twice because when you override a multi-provider, we
// treat it as `{multi: false}` to avoid providing the same value multiple times.
if (!seenMultiProviders.has(token)) {
seenMultiProviders.add(token);
final.unshift({...provider, multi: false});
}
} else {
final.unshift(provider);
}
});
return final;
}
private hasProviderOverrides(providers?: Provider[]): boolean {
return this.getProviderOverrides(providers).length > 0;
}
private patchDefWithProviderOverrides(declaration: Type<any>, field: string): void {
const def = (declaration as any)[field];
if (def && def.providersResolver) {
this.maybeStoreNgDef(field, declaration);
const resolver = def.providersResolver;
const processProvidersFn = (providers: Provider[]) => this.getOverriddenProviders(providers);
this.storeFieldOfDefOnType(declaration, field, 'providersResolver');
def.providersResolver = (ngDef: DirectiveDef<any>) => resolver(ngDef, processProvidersFn);
}
}
}
function initResolvers(): Resolvers {
return {
module: new NgModuleResolver(),
component: new ComponentResolver(),
directive: new DirectiveResolver(),
pipe: new PipeResolver()
};
}
function hasNgModuleDef<T>(value: Type<T>): value is NgModuleType<T> {
return value.hasOwnProperty('ɵmod');
}
function maybeUnwrapFn<T>(maybeFn: (() => T) | T): T {
return maybeFn instanceof Function ? maybeFn() : maybeFn;
}
function flatten<T>(values: any[], mapFn?: (value: T) => any): T[] {
const out: T[] = [];
values.forEach(value => {
if (Array.isArray(value)) {
out.push(...flatten<T>(value, mapFn));
} else {
out.push(mapFn ? mapFn(value) : value);
}
});
return out;
}
function getProviderField(provider: Provider, field: string) {
return provider && typeof provider === 'object' && (provider as any)[field];
}
function getProviderToken(provider: Provider) {
return getProviderField(provider, 'provide') || provider;
}
function isMultiProvider(provider: Provider) {
return !!getProviderField(provider, 'multi');
}
function isModuleWithProviders(value: any): value is ModuleWithProviders<any> {
return value.hasOwnProperty('ngModule');
}
function forEachRight<T>(values: T[], fn: (value: T, idx: number) => void): void {
for (let idx = values.length - 1; idx >= 0; idx--) {
fn(values[idx], idx);
}
}
class R3TestCompiler implements Compiler {
constructor(private testBed: R3TestBedCompiler) {}
compileModuleSync<T>(moduleType: Type<T>): NgModuleFactory<T> {
this.testBed._compileNgModuleSync(moduleType);
return new R3NgModuleFactory(moduleType);
}
async compileModuleAsync<T>(moduleType: Type<T>): Promise<NgModuleFactory<T>> {
await this.testBed._compileNgModuleAsync(moduleType);
return new R3NgModuleFactory(moduleType);
}
compileModuleAndAllComponentsSync<T>(moduleType: Type<T>): ModuleWithComponentFactories<T> {
const ngModuleFactory = this.compileModuleSync(moduleType);
const componentFactories = this.testBed._getComponentFactories(moduleType as NgModuleType<T>);
return new ModuleWithComponentFactories(ngModuleFactory, componentFactories);
}
async compileModuleAndAllComponentsAsync<T>(moduleType: Type<T>):
Promise<ModuleWithComponentFactories<T>> {
const ngModuleFactory = await this.compileModuleAsync(moduleType);
const componentFactories = this.testBed._getComponentFactories(moduleType as NgModuleType<T>);
return new ModuleWithComponentFactories(ngModuleFactory, componentFactories);
}
clearCache(): void {}
clearCacheFor(type: Type<any>): void {}
getModuleId(moduleType: Type<any>): string|undefined {
const meta = this.testBed._getModuleResolver().resolve(moduleType);
return meta && meta.id || undefined;
}
}