forked from angular/angular
-
Notifications
You must be signed in to change notification settings - Fork 0
/
injector_discovery_utils.ts
634 lines (557 loc) · 25 KB
/
injector_discovery_utils.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
/**
* @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 {InjectionToken} from '../../di/injection_token';
import {Injector} from '../../di/injector';
import {getInjectorDef, InjectorType} from '../../di/interface/defs';
import {InjectFlags, InternalInjectFlags} from '../../di/interface/injector';
import {NullInjector} from '../../di/null_injector';
import {SingleProvider, walkProviderTree} from '../../di/provider_collection';
import {EnvironmentInjector, R3Injector} from '../../di/r3_injector';
import {Type} from '../../interface/type';
import {NgModuleRef as viewEngine_NgModuleRef} from '../../linker/ng_module_factory';
import {deepForEach} from '../../util/array_utils';
import {assertDefined, throwError} from '../../util/assert';
import type {ChainedInjector} from '../component_ref';
import {getComponentDef} from '../definition';
import {getNodeInjectorLView, getNodeInjectorTNode, getParentInjectorLocation, NodeInjector} from '../di';
import {getFrameworkDIDebugData} from '../debug/framework_injector_profiler';
import {InjectedService, ProviderRecord} from '../debug/injector_profiler';
import {NodeInjectorOffset} from '../interfaces/injector';
import {TContainerNode, TElementContainerNode, TElementNode, TNode} from '../interfaces/node';
import {INJECTOR, LView, TVIEW} from '../interfaces/view';
import {getParentInjectorIndex, getParentInjectorView, hasParentInjector} from './injector_utils';
import {assertTNodeForLView, assertTNode} from '../assert';
import {RElement} from '../interfaces/renderer_dom';
import {getNativeByTNode} from './view_utils';
/**
* Discovers the dependencies of an injectable instance. Provides DI information about each
* dependency that the injectable was instantiated with, including where they were provided from.
*
* @param injector An injector instance
* @param token a DI token that was constructed by the given injector instance
* @returns an object that contains the created instance of token as well as all of the dependencies
* that it was instantiated with OR undefined if the token was not created within the given
* injector.
*/
export function getDependenciesFromInjectable<T>(
injector: Injector, token: Type<T>|InjectionToken<T>):
{instance: T; dependencies: Omit<InjectedService, 'injectedIn'>[]}|undefined {
// First we check to see if the token given maps to an actual instance in the injector given.
// We use `self: true` because we only want to look at the injector we were given.
// We use `optional: true` because it's possible that the token we were given was never
// constructed by the injector we were given.
const instance = injector.get(token, null, {self: true, optional: true});
if (instance === null) {
throw new Error(`Unable to determine instance of ${token} in given injector`);
}
const unformattedDependencies = getDependenciesForTokenInInjector(token, injector);
const resolutionPath = getInjectorResolutionPath(injector);
const dependencies = unformattedDependencies.map(dep => {
// injectedIn contains private fields, so we omit it from the response
const formattedDependency: Omit<InjectedService, 'injectedIn'> = {
value: dep.value,
};
// convert injection flags to booleans
const flags = dep.flags as InternalInjectFlags;
formattedDependency.flags = {
optional: (InternalInjectFlags.Optional & flags) === InternalInjectFlags.Optional,
host: (InternalInjectFlags.Host & flags) === InternalInjectFlags.Host,
self: (InternalInjectFlags.Self & flags) === InternalInjectFlags.Self,
skipSelf: (InternalInjectFlags.SkipSelf & flags) === InternalInjectFlags.SkipSelf,
};
// find the injector that provided the dependency
for (let i = 0; i < resolutionPath.length; i++) {
const injectorToCheck = resolutionPath[i];
// if skipSelf is true we skip the first injector
if (i === 0 && formattedDependency.flags.skipSelf) {
continue;
}
// host only applies to NodeInjectors
if (formattedDependency.flags.host && injectorToCheck instanceof EnvironmentInjector) {
break;
}
const instance =
injectorToCheck.get(dep.token as Type<unknown>, null, {self: true, optional: true});
if (instance !== null) {
// if host flag is true we double check that we can get the service from the first element
// in the resolution path by using the host flag. This is done to make sure that we've found
// the correct providing injector, and not a node injector that is connected to our path via
// a router outlet.
if (formattedDependency.flags.host) {
const firstInjector = resolutionPath[0];
const lookupFromFirstInjector = firstInjector.get(
dep.token as Type<unknown>, null, {...formattedDependency.flags, optional: true});
if (lookupFromFirstInjector !== null) {
formattedDependency.providedIn = injectorToCheck;
}
break;
}
formattedDependency.providedIn = injectorToCheck;
break;
}
// if self is true we stop after the first injector
if (i === 0 && formattedDependency.flags.self) {
break;
}
}
if (dep.token) formattedDependency.token = dep.token;
return formattedDependency;
});
return {instance, dependencies};
}
function getDependenciesForTokenInInjector<T>(
token: Type<T>|InjectionToken<T>, injector: Injector): InjectedService[] {
const {resolverToTokenToDependencies} = getFrameworkDIDebugData();
if (!(injector instanceof NodeInjector)) {
return resolverToTokenToDependencies.get(injector)?.get?.(token as Type<T>) ?? [];
}
const lView = getNodeInjectorLView(injector);
const tokenDependencyMap = resolverToTokenToDependencies.get(lView);
const dependencies = tokenDependencyMap?.get(token as Type<T>) ?? [];
// In the NodeInjector case, all injections for every node are stored in the same lView.
// We use the injectedIn field of the dependency to filter out the dependencies that
// do not come from the same node as the instance we're looking at.
return dependencies.filter(dependency => {
const dependencyNode = dependency.injectedIn?.tNode;
if (dependencyNode === undefined) {
return false;
}
const instanceNode = getNodeInjectorTNode(injector);
assertTNode(dependencyNode);
assertTNode(instanceNode!);
return dependencyNode === instanceNode;
});
}
/**
* Gets the class associated with an injector that contains a provider `imports` array in it's
* definition
*
* For Module Injectors this returns the NgModule constructor.
*
* For Standalone injectors this returns the standalone component constructor.
*
* @param injector Injector an injector instance
* @returns the constructor where the `imports` array that configures this injector is located
*/
function getProviderImportsContainer(injector: Injector): Type<unknown>|null {
const {standaloneInjectorToComponent} = getFrameworkDIDebugData();
// standalone components configure providers through a component def, so we have to
// use the standalone component associated with this injector if Injector represents
// a standalone components EnvironmentInjector
if (standaloneInjectorToComponent.has(injector)) {
return standaloneInjectorToComponent.get(injector)!;
}
// Module injectors configure providers through their NgModule def, so we use the
// injector to lookup its NgModuleRef and through that grab its instance
const defTypeRef = injector.get(viewEngine_NgModuleRef, null, {self: true, optional: true})!;
// If we can't find an associated imports container, return null.
// This could be the case if this function is called with an R3Injector that does not represent
// a standalone component or NgModule.
if (defTypeRef === null) {
return null;
}
// In standalone applications, the root environment injector created by bootstrapApplication
// may have no associated "instance".
if (defTypeRef.instance === null) {
return null;
}
return defTypeRef.instance.constructor;
}
/**
* Gets the providers configured on a NodeInjector
*
* @param injector A NodeInjector instance
* @returns ProviderRecord[] an array of objects representing the providers configured on this
* injector
*/
function getNodeInjectorProviders(injector: NodeInjector): ProviderRecord[] {
const diResolver = getNodeInjectorLView(injector);
const {resolverToProviders} = getFrameworkDIDebugData();
return resolverToProviders.get(diResolver) ?? [];
}
/**
* Gets a mapping of providers configured on an injector to their import paths
*
* ModuleA -> imports ModuleB
* ModuleB -> imports ModuleC
* ModuleB -> provides MyServiceA
* ModuleC -> provides MyServiceB
*
* getProviderImportPaths(ModuleA)
* > Map(2) {
* MyServiceA => [ModuleA, ModuleB]
* MyServiceB => [ModuleA, ModuleB, ModuleC]
* }
*
* @param providerImportsContainer constructor of class that contains an `imports` array in it's
* definition
* @returns A Map object that maps providers to an array of constructors representing it's import
* path
*
*/
function getProviderImportPaths(providerImportsContainer: Type<unknown>):
Map<SingleProvider, (Type<unknown>| InjectorType<unknown>)[]> {
const providerToPath = new Map<SingleProvider, (Type<unknown>| InjectorType<unknown>)[]>();
const visitedContainers = new Set<Type<unknown>>();
const visitor = walkProviderTreeToDiscoverImportPaths(providerToPath, visitedContainers);
walkProviderTree(providerImportsContainer, visitor, [], new Set());
return providerToPath;
}
/**
*
* Higher order function that returns a visitor for WalkProviderTree
*
* Takes in a Map and Set to keep track of the providers and containers
* visited, so that we can discover the import paths of these providers
* during the traversal.
*
* This visitor takes advantage of the fact that walkProviderTree performs a
* postorder traversal of the provider tree for the passed in container. Because postorder
* traversal recursively processes subtrees from leaf nodes until the traversal reaches the root,
* we write a visitor that constructs provider import paths in reverse.
*
*
* We use the visitedContainers set defined outside this visitor
* because we want to run some logic only once for
* each container in the tree. That logic can be described as:
*
*
* 1. for each discovered_provider and discovered_path in the incomplete provider paths we've
* already discovered
* 2. get the first container in discovered_path
* 3. if that first container is in the imports array of the container we're visiting
* Then the container we're visiting is also in the import path of discovered_provider, so we
* unshift discovered_path with the container we're currently visiting
*
*
* Example Run:
* ```
* ┌──────────┐
* │containerA│
* ┌─imports-─┤ ├──imports─┐
* │ │ provA │ │
* │ │ provB │ │
* │ └──────────┘ │
* │ │
* ┌▼─────────┐ ┌────────▼─┐
* │containerB│ │containerC│
* │ │ │ │
* │ provD │ │ provF │
* │ provE │ │ provG │
* └──────────┘ └──────────┘
* ```
*
* Each step of the traversal,
*
* ```
* visitor(provD, containerB)
* providerToPath === Map { provD => [containerB] }
* visitedContainers === Set { containerB }
*
* visitor(provE, containerB)
* providerToPath === Map { provD => [containerB], provE => [containerB] }
* visitedContainers === Set { containerB }
*
* visitor(provF, containerC)
* providerToPath === Map { provD => [containerB], provE => [containerB], provF => [containerC] }
* visitedContainers === Set { containerB, containerC }
*
* visitor(provG, containerC)
* providerToPath === Map {
* provD => [containerB], provE => [containerB], provF => [containerC], provG => [containerC]
* }
* visitedContainers === Set { containerB, containerC }
*
* visitor(provA, containerA)
* providerToPath === Map {
* provD => [containerA, containerB],
* provE => [containerA, containerB],
* provF => [containerA, containerC],
* provG => [containerA, containerC],
* provA => [containerA]
* }
* visitedContainers === Set { containerB, containerC, containerA }
*
* visitor(provB, containerA)
* providerToPath === Map {
* provD => [containerA, containerB],
* provE => [containerA, containerB],
* provF => [containerA, containerC],
* provG => [containerA, containerC],
* provA => [containerA]
* provB => [containerA]
* }
* visitedContainers === Set { containerB, containerC, containerA }
* ```
*
* @param providerToPath Map map of providers to paths that this function fills
* @param visitedContainers Set a set to keep track of the containers we've already visited
* @return function(provider SingleProvider, container: Type<unknown> | InjectorType<unknown>) =>
* void
*/
function walkProviderTreeToDiscoverImportPaths(
providerToPath: Map<SingleProvider, (Type<unknown>| InjectorType<unknown>)[]>,
visitedContainers: Set<Type<unknown>>):
(provider: SingleProvider, container: Type<unknown>|InjectorType<unknown>) => void {
return (provider: SingleProvider, container: Type<unknown>|InjectorType<unknown>) => {
// If the provider is not already in the providerToPath map,
// add an entry with the provider as the key and an array containing the current container as
// the value
if (!providerToPath.has(provider)) {
providerToPath.set(provider, [container]);
}
// This block will run exactly once for each container in the import tree.
// This is where we run the logic to check the imports array of the current
// container to see if it's the next container in the path for our currently
// discovered providers.
if (!visitedContainers.has(container)) {
// Iterate through the providers we've already seen
for (const prov of providerToPath.keys()) {
const existingImportPath = providerToPath.get(prov)!;
let containerDef = getInjectorDef(container);
if (!containerDef) {
const ngModule: Type<unknown>|undefined =
(container as any).ngModule as Type<unknown>| undefined;
containerDef = getInjectorDef(ngModule);
}
if (!containerDef) {
return;
}
const lastContainerAddedToPath = existingImportPath[0];
let isNextStepInPath = false;
deepForEach(containerDef.imports, (moduleImport) => {
if (isNextStepInPath) {
return;
}
isNextStepInPath = (moduleImport as any).ngModule === lastContainerAddedToPath ||
moduleImport === lastContainerAddedToPath;
if (isNextStepInPath) {
providerToPath.get(prov)?.unshift(container);
}
});
}
}
visitedContainers.add(container);
};
}
/**
* Gets the providers configured on an EnvironmentInjector
*
* @param injector EnvironmentInjector
* @returns an array of objects representing the providers of the given injector
*/
function getEnvironmentInjectorProviders(injector: EnvironmentInjector): ProviderRecord[] {
const providerRecords = getFrameworkDIDebugData().resolverToProviders.get(injector) ?? [];
// platform injector has no provider imports container so can we skip trying to
// find import paths
if (isPlatformInjector(injector)) {
return providerRecords;
}
const providerImportsContainer = getProviderImportsContainer(injector);
if (providerImportsContainer === null) {
// There is a special case where the bootstrapped component does not
// import any NgModules. In this case the environment injector connected to
// that component is the root injector, which does not have a provider imports
// container (and thus no concept of module import paths). Therefore we simply
// return the provider records as is.
if (isRootInjector(injector)) {
return providerRecords;
}
throwError('Could not determine where injector providers were configured.');
}
const providerToPath = getProviderImportPaths(providerImportsContainer);
return providerRecords.map(providerRecord => {
let importPath = providerToPath.get(providerRecord.provider) ?? [providerImportsContainer];
const def = getComponentDef(providerImportsContainer);
const isStandaloneComponent = !!def?.standalone;
// We prepend the component constructor in the standalone case
// because walkProviderTree does not visit this constructor during it's traversal
if (isStandaloneComponent) {
importPath = [providerImportsContainer, ...providerToPath.get(providerRecord.provider) ?? []];
}
return {...providerRecord, importPath};
});
}
function isPlatformInjector(injector: Injector) {
return injector instanceof R3Injector && injector.scopes.has('platform');
}
function isRootInjector(injector: Injector) {
return injector instanceof R3Injector && injector.scopes.has('root');
}
/**
* Gets the providers configured on an injector.
*
* @param injector the injector to lookup the providers of
* @returns ProviderRecord[] an array of objects representing the providers of the given injector
*/
export function getInjectorProviders(injector: Injector): ProviderRecord[] {
if (injector instanceof NodeInjector) {
return getNodeInjectorProviders(injector);
} else if (injector instanceof EnvironmentInjector) {
return getEnvironmentInjectorProviders(injector as EnvironmentInjector);
}
throwError('getInjectorProviders only supports NodeInjector and EnvironmentInjector');
}
/**
*
* Given an injector, this function will return
* an object containing the type and source of the injector.
*
* | | type | source |
* |--------------|-------------|-------------------------------------------------------------|
* | NodeInjector | element | DOM element that created this injector |
* | R3Injector | environment | `injector.source` |
* | NullInjector | null | null |
*
* @param injector the Injector to get metadata for
* @returns an object containing the type and source of the given injector. If the injector metadata
* cannot be determined, returns null.
*/
export function getInjectorMetadata(injector: Injector):
{type: string; source: RElement | string | null}|null {
if (injector instanceof NodeInjector) {
const lView = getNodeInjectorLView(injector);
const tNode = getNodeInjectorTNode(injector)!;
assertTNodeForLView(tNode, lView);
return {type: 'element', source: getNativeByTNode(tNode, lView) as RElement};
}
if (injector instanceof R3Injector) {
return {type: 'environment', source: injector.source ?? null};
}
if (injector instanceof NullInjector) {
return {type: 'null', source: null};
}
return null;
}
export function getInjectorResolutionPath(injector: Injector): Injector[] {
const resolutionPath: Injector[] = [injector];
getInjectorResolutionPathHelper(injector, resolutionPath);
return resolutionPath;
}
function getInjectorResolutionPathHelper(
injector: Injector, resolutionPath: Injector[]): Injector[] {
const parent = getInjectorParent(injector);
// if getInjectorParent can't find a parent, then we've either reached the end
// of the path, or we need to move from the Element Injector tree to the
// module injector tree using the first injector in our path as the connection point.
if (parent === null) {
if (injector instanceof NodeInjector) {
const firstInjector = resolutionPath[0];
if (firstInjector instanceof NodeInjector) {
const moduleInjector = getModuleInjectorOfNodeInjector(firstInjector);
if (moduleInjector === null) {
throwError('NodeInjector must have some connection to the module injector tree');
}
resolutionPath.push(moduleInjector);
getInjectorResolutionPathHelper(moduleInjector, resolutionPath);
}
return resolutionPath;
}
} else {
resolutionPath.push(parent);
getInjectorResolutionPathHelper(parent, resolutionPath);
}
return resolutionPath;
}
/**
* Gets the parent of an injector.
*
* This function is not able to make the jump from the Element Injector Tree to the Module
* injector tree. This is because the "parent" (the next step in the reoslution path)
* of a root NodeInjector is dependent on which NodeInjector ancestor initiated
* the DI lookup. See getInjectorResolutionPath for a function that can make this jump.
*
* In the below diagram:
* ```ts
* getInjectorParent(NodeInjectorB)
* > NodeInjectorA
* getInjectorParent(NodeInjectorA) // or getInjectorParent(getInjectorParent(NodeInjectorB))
* > null // cannot jump to ModuleInjector tree
* ```
*
* ```
* ┌───────┐ ┌───────────────────┐
* ┌───────────┤ModuleA├───Injector────►│EnvironmentInjector│
* │ └───┬───┘ └───────────────────┘
* │ │
* │ bootstraps
* │ │
* │ │
* │ ┌────▼─────┐ ┌─────────────┐
* declares │ComponentA├────Injector────►│NodeInjectorA│
* │ └────┬─────┘ └─────▲───────┘
* │ │ │
* │ renders parent
* │ │ │
* │ ┌────▼─────┐ ┌─────┴───────┐
* └─────────►│ComponentB├────Injector────►│NodeInjectorB│
* └──────────┘ └─────────────┘
*```
*
* @param injector an Injector to get the parent of
* @returns Injector the parent of the given injector
*/
function getInjectorParent(injector: Injector): Injector|null {
if (injector instanceof R3Injector) {
return injector.parent;
}
let tNode: TElementNode|TContainerNode|TElementContainerNode|null;
let lView: LView<unknown>;
if (injector instanceof NodeInjector) {
tNode = getNodeInjectorTNode(injector);
lView = getNodeInjectorLView(injector);
} else if (injector instanceof NullInjector) {
return null;
} else {
throwError(
'getInjectorParent only support injectors of type R3Injector, NodeInjector, NullInjector');
}
const parentLocation = getParentInjectorLocation(
tNode as TElementNode | TContainerNode | TElementContainerNode, lView);
if (hasParentInjector(parentLocation)) {
const parentInjectorIndex = getParentInjectorIndex(parentLocation);
const parentLView = getParentInjectorView(parentLocation, lView);
const parentTView = parentLView[TVIEW];
const parentTNode = parentTView.data[parentInjectorIndex + NodeInjectorOffset.TNODE] as TNode;
return new NodeInjector(
parentTNode as TElementNode | TContainerNode | TElementContainerNode, parentLView);
} else {
const chainedInjector = lView[INJECTOR] as ChainedInjector;
// Case where chainedInjector.injector is an OutletInjector and chainedInjector.injector.parent
// is a NodeInjector.
// todo(aleksanderbodurri): ideally nothing in packages/core should deal
// directly with router concerns. Refactor this so that we can make the jump from
// NodeInjector -> OutletInjector -> NodeInjector
// without explictly relying on types contracts from packages/router
const injectorParent = (chainedInjector.injector as any)?.parent as Injector;
if (injectorParent instanceof NodeInjector) {
return injectorParent;
}
}
return null;
}
/**
* Gets the module injector of a NodeInjector.
*
* @param injector NodeInjector to get module injector of
* @returns Injector representing module injector of the given NodeInjector
*/
function getModuleInjectorOfNodeInjector(injector: NodeInjector): Injector {
let lView: LView<unknown>;
if (injector instanceof NodeInjector) {
lView = getNodeInjectorLView(injector);
} else {
throwError('getModuleInjectorOfNodeInjector must be called with a NodeInjector');
}
const chainedInjector = lView[INJECTOR] as ChainedInjector;
const moduleInjector = chainedInjector.parentInjector;
if (!moduleInjector) {
throwError('NodeInjector must have some connection to the module injector tree');
}
return moduleInjector;
}