@nestjs/core
Version:
The core of NestJS, a TypeScript framework for Node.js backends: modules, dependency injection and the request pipeline, on Express, Fastify or node:http.
518 lines (517 loc) • 24.3 kB
JavaScript
import { iterate } from 'iterare';
import { ApplicationConfig } from './application-config.js';
import { APP_FILTER, APP_GUARD, APP_INTERCEPTOR, APP_PIPE, ENHANCER_TOKEN_TO_SUBTYPE_MAP, } from './constants.js';
import { CircularDependencyException } from './errors/exceptions/circular-dependency.exception.js';
import { InvalidClassModuleException } from './errors/exceptions/invalid-class-module.exception.js';
import { InvalidModuleException } from './errors/exceptions/invalid-module.exception.js';
import { RequestScopedGlobalEnhancerException } from './errors/exceptions/request-scoped-global-enhancer.exception.js';
import { UndefinedModuleEntryException } from './errors/exceptions/undefined-module-entry.exception.js';
import { UndefinedModuleException } from './errors/exceptions/undefined-module.exception.js';
import { UninstantiatedGlobalEnhancerException } from './errors/exceptions/uninstantiated-global-enhancer.exception.js';
import { assertEnhancer, describeEnhancer, warnOnInvalidFilter, } from './helpers/assert-enhancer.js';
import { getParamsHost } from './helpers/class-ref-registry.js';
import { getClassScope } from './helpers/get-class-scope.js';
import { STATIC_CONTEXT } from './injector/constants.js';
import { InternalCoreModuleFactory } from './injector/internal-core-module/internal-core-module-factory.js';
import { TopologyTree } from './injector/topology-tree/topology-tree.js';
import { UuidFactory } from './inspector/uuid-factory.js';
import { CATCH_WATERMARK, CONTROLLER_WATERMARK, ENHANCER_KEY_TO_SUBTYPE_MAP, EXCEPTION_FILTERS_METADATA, GUARDS_METADATA, INJECTABLE_WATERMARK, INTERCEPTORS_METADATA, MODULE_METADATA, PIPES_METADATA, ROUTE_ARGS_METADATA, isFunction, isNil, isUndefined, } from '@nestjs/common/internal';
import { Scope, } from '@nestjs/common';
const ENHANCER_KIND_BY_TOKEN = {
[APP_GUARD]: 'guard',
[APP_INTERCEPTOR]: 'interceptor',
[APP_PIPE]: 'pipe',
};
export class DependenciesScanner {
container;
metadataScanner;
graphInspector;
applicationConfig;
applicationProvidersApplyMap = [];
constructor(container, metadataScanner, graphInspector, applicationConfig = new ApplicationConfig()) {
this.container = container;
this.metadataScanner = metadataScanner;
this.graphInspector = graphInspector;
this.applicationConfig = applicationConfig;
}
async scan(module, options) {
await this.registerCoreModule(options?.overrides);
await this.scanForModules({
moduleDefinition: module,
overrides: options?.overrides,
});
await this.scanModulesForDependencies();
this.addScopedEnhancersMetadata();
// Modules distance calculation should be done after all modules are scanned
// but before global modules are registered (linked to all modules).
// Global modules have their distance set to MAX anyway.
this.calculateModulesDistance();
this.container.bindGlobalScope();
}
async scanForModules({ moduleDefinition, lazy, scope = [], ctxRegistry = [], overrides = [], insertedModules, }) {
const { moduleRef: moduleInstance, inserted: moduleInserted } = (await this.insertOrOverrideModule(moduleDefinition, overrides, scope, insertedModules)) ?? {};
if (lazy && !moduleInserted && moduleInstance?.isInstantiated) {
return [];
}
moduleDefinition =
this.getOverrideModuleByModule(moduleDefinition, overrides)?.newModule ??
moduleDefinition;
moduleDefinition =
moduleDefinition instanceof Promise
? await moduleDefinition
: moduleDefinition;
ctxRegistry.push(moduleDefinition);
if (this.isForwardReference(moduleDefinition)) {
moduleDefinition = this.resolveForwardReference(moduleDefinition);
}
const modules = !this.isDynamicModule(moduleDefinition)
? this.reflectMetadata(MODULE_METADATA.IMPORTS, moduleDefinition)
: [
...this.reflectMetadata(MODULE_METADATA.IMPORTS, moduleDefinition.module),
...(moduleDefinition.imports || []),
];
let registeredModuleRefs = [];
for (const [index, innerModule] of modules.entries()) {
// In case of a circular dependency (ES module system), JavaScript will resolve the type to `undefined`.
if (innerModule === undefined) {
throw new UndefinedModuleException(moduleDefinition, index, scope);
}
if (!innerModule) {
throw new InvalidModuleException(moduleDefinition, index, scope, innerModule);
}
if (ctxRegistry.includes(innerModule)) {
continue;
}
const moduleRefs = await this.scanForModules({
moduleDefinition: innerModule,
scope: [].concat(scope, moduleDefinition),
ctxRegistry,
overrides,
lazy,
insertedModules,
});
registeredModuleRefs = registeredModuleRefs.concat(moduleRefs);
}
if (!moduleInstance) {
return registeredModuleRefs;
}
if (lazy) {
this.container.bindGlobalsToImports(moduleInstance);
}
return [moduleInstance].concat(registeredModuleRefs);
}
async insertModule(moduleDefinition, scope, insertedModules) {
const moduleToAdd = this.isForwardReference(moduleDefinition)
? this.resolveForwardReference(moduleDefinition)
: moduleDefinition;
if (this.isInjectable(moduleToAdd)) {
throw new InvalidClassModuleException(moduleDefinition, scope, 'provider');
}
if (this.isController(moduleToAdd)) {
throw new InvalidClassModuleException(moduleDefinition, scope, 'controller');
}
if (this.isExceptionFilter(moduleToAdd)) {
throw new InvalidClassModuleException(moduleDefinition, scope, 'filter');
}
return this.container.addModule(moduleToAdd, scope, insertedModules);
}
removeModules(modules) {
this.container.removeModules(modules);
}
async scanModulesForDependencies(modules = this.container.getModules()) {
for (const [token, { metatype }] of modules) {
await this.reflectImports(metatype, token, metatype.name);
this.reflectProviders(metatype, token);
this.reflectControllers(metatype, token);
this.reflectExports(metatype, token);
}
}
async reflectImports(module, token, context) {
const modules = [
...this.reflectMetadata(MODULE_METADATA.IMPORTS, module),
...this.container.getDynamicMetadataByToken(token, MODULE_METADATA.IMPORTS),
];
for (const related of modules) {
await this.insertImport(related, token, context);
}
}
reflectProviders(module, token) {
const providers = [
...this.reflectMetadata(MODULE_METADATA.PROVIDERS, module),
...this.container.getDynamicMetadataByToken(token, MODULE_METADATA.PROVIDERS),
];
const applyProvidersKeys = Object.keys(this.getApplyProvidersMap());
providers.forEach((provider, index) => {
if (provider === undefined) {
throw new UndefinedModuleEntryException(module, 'providers', index);
}
this.insertProvider(provider, token);
if (!this.isCustomProvider(provider)) {
return this.reflectDynamicMetadata(provider, token);
}
// The enhancers of the class behind a class provider (e.g., a gateway
// registered as `{ provide, useClass }`) are bound to its token.
const { provide, useClass } = provider;
if (!applyProvidersKeys.includes(provide)) {
this.reflectDynamicMetadata(useClass, token, provide);
}
});
}
reflectControllers(module, token) {
const controllers = [
...this.reflectMetadata(MODULE_METADATA.CONTROLLERS, module),
...this.container.getDynamicMetadataByToken(token, MODULE_METADATA.CONTROLLERS),
];
controllers.forEach((item, index) => {
if (item === undefined) {
throw new UndefinedModuleEntryException(module, 'controllers', index);
}
this.insertController(item, token);
this.reflectDynamicMetadata(item, token);
});
}
reflectDynamicMetadata(cls, token, hostToken = cls) {
if (!cls || !cls.prototype) {
return;
}
this.reflectInjectables(cls, token, GUARDS_METADATA, hostToken);
this.reflectInjectables(cls, token, INTERCEPTORS_METADATA, hostToken);
this.reflectInjectables(cls, token, EXCEPTION_FILTERS_METADATA, hostToken);
this.reflectInjectables(cls, token, PIPES_METADATA, hostToken);
this.reflectParamInjectables(cls, token, ROUTE_ARGS_METADATA, hostToken);
}
reflectExports(module, token) {
const exports = [
...this.reflectMetadata(MODULE_METADATA.EXPORTS, module),
...this.container.getDynamicMetadataByToken(token, MODULE_METADATA.EXPORTS),
];
exports.forEach((exportedProvider, index) => {
if (exportedProvider === undefined) {
throw new UndefinedModuleEntryException(module, 'exports', index);
}
this.insertExportedProviderOrModule(exportedProvider, token);
});
}
reflectInjectables(component, token, metadataKey, hostToken = component) {
const controllerInjectables = this.reflectMetadata(metadataKey, component);
const methodInjectables = this.metadataScanner
.getAllMethodNames(component.prototype)
.reduce((acc, method) => {
const methodInjectable = this.reflectKeyMetadata(component, metadataKey, method);
if (methodInjectable) {
acc.push(methodInjectable);
}
return acc;
}, []);
controllerInjectables.forEach(injectable => this.insertInjectable(injectable, token, hostToken, ENHANCER_KEY_TO_SUBTYPE_MAP[metadataKey]));
methodInjectables.forEach(methodInjectable => {
methodInjectable.metadata.forEach(injectable => this.insertInjectable(injectable, token, hostToken, ENHANCER_KEY_TO_SUBTYPE_MAP[metadataKey], methodInjectable.methodKey));
});
}
reflectParamInjectables(component, token, metadataKey, hostToken = component) {
const paramsMethods = this.metadataScanner.getAllMethodNames(component.prototype);
paramsMethods.forEach(methodKey => {
const metadata = Reflect.getMetadata(metadataKey, getParamsHost(component, methodKey), methodKey);
if (!metadata) {
return;
}
const params = Object.values(metadata);
params
.map(item => item.pipes)
.flat(1)
.forEach(injectable => this.insertInjectable(injectable, token, hostToken, 'pipe', methodKey));
});
}
reflectKeyMetadata(component, key, methodKey) {
let prototype = component.prototype;
do {
const descriptor = Reflect.getOwnPropertyDescriptor(prototype, methodKey);
if (!descriptor) {
continue;
}
const metadata = Reflect.getMetadata(key, descriptor.value);
if (!metadata) {
return;
}
return { methodKey, metadata };
} while ((prototype = Reflect.getPrototypeOf(prototype)) &&
prototype !== Object.prototype &&
prototype);
return undefined;
}
calculateModulesDistance() {
const modulesGenerator = this.container.getModules().values();
// Skip "InternalCoreModule"
// The second element is the actual root module
modulesGenerator.next();
const rootModule = modulesGenerator.next().value;
if (!rootModule) {
return;
}
// Convert modules to an acyclic connected graph
const tree = new TopologyTree(rootModule);
tree.walk((moduleRef, depth) => {
if (moduleRef.isGlobal) {
return;
}
moduleRef.distance = depth;
});
}
async insertImport(related, token, context) {
if (isUndefined(related)) {
throw new CircularDependencyException(context);
}
if (this.isForwardReference(related)) {
return this.container.addImport(this.resolveForwardReference(related), token);
}
await this.container.addImport(related, token);
}
isCustomProvider(provider) {
return provider && !isNil(provider.provide);
}
insertProvider(provider, token) {
const isCustomProvider = this.isCustomProvider(provider);
if (!isCustomProvider) {
return this.container.addProvider(provider, token);
}
const applyProvidersMap = this.getApplyProvidersMap();
const providersKeys = Object.keys(applyProvidersMap);
const type = provider.provide;
if (!providersKeys.includes(type)) {
return this.container.addProvider(provider, token);
}
const uuid = UuidFactory.get(type.toString());
const providerToken = `${type} (UUID: ${uuid})`;
let scope = provider.scope;
if (isNil(scope) && provider.useClass) {
scope = getClassScope(provider.useClass);
}
// An alias of a class takes the scope of that class, as with `useClass`.
// Otherwise an alias of a request-scoped class is registered as a static
// enhancer that never gets an instance.
const existing = provider.useExisting;
if (isNil(scope) && isFunction(existing)) {
scope = getClassScope(existing);
}
this.applicationProvidersApplyMap.push({
type,
moduleKey: token,
providerKey: providerToken,
scope,
});
const newProvider = {
...provider,
provide: providerToken,
scope,
};
const enhancerSubtype = ENHANCER_TOKEN_TO_SUBTYPE_MAP[type];
const factoryOrClassProvider = newProvider;
if (this.isRequestOrTransient(factoryOrClassProvider.scope)) {
return this.container.addInjectable(newProvider, token, enhancerSubtype);
}
this.container.addProvider(newProvider, token, enhancerSubtype);
}
insertInjectable(injectable, token, host, subtype, methodKey) {
if (isFunction(injectable)) {
const instanceWrapper = this.container.addInjectable(injectable, token, subtype, host);
this.graphInspector.insertEnhancerMetadataCache({
moduleToken: token,
classRef: host,
enhancerInstanceWrapper: instanceWrapper,
targetNodeId: instanceWrapper.id,
subtype,
methodKey,
});
return instanceWrapper;
}
else {
this.graphInspector.insertEnhancerMetadataCache({
moduleToken: token,
classRef: host,
enhancerRef: injectable,
methodKey,
subtype,
});
}
}
insertExportedProviderOrModule(toExport, token) {
const fulfilledProvider = this.isForwardReference(toExport)
? this.resolveForwardReference(toExport)
: toExport;
this.container.addExportedProviderOrModule(fulfilledProvider, token);
}
insertController(controller, token) {
this.container.addController(controller, token);
}
insertOrOverrideModule(moduleDefinition, overrides, scope, insertedModules) {
const overrideModule = this.getOverrideModuleByModule(moduleDefinition, overrides);
if (overrideModule !== undefined) {
return this.overrideModule(moduleDefinition, overrideModule.newModule, scope, insertedModules);
}
return this.insertModule(moduleDefinition, scope, insertedModules);
}
getOverrideModuleByModule(module, overrides) {
if (this.isForwardReference(module)) {
const moduleRef = this.resolveForwardReference(module);
return overrides.find(({ moduleToReplace }) => {
return (moduleToReplace === moduleRef ||
(this.isForwardReference(moduleToReplace) &&
this.resolveForwardReference(moduleToReplace) === moduleRef));
});
}
return overrides.find(moduleToOverride => moduleToOverride.moduleToReplace === module);
}
async overrideModule(moduleToOverride, newModule, scope, insertedModules) {
return this.container.replaceModule(this.isForwardReference(moduleToOverride)
? this.resolveForwardReference(moduleToOverride)
: moduleToOverride, this.isForwardReference(newModule)
? this.resolveForwardReference(newModule)
: newModule, scope, insertedModules);
}
reflectMetadata(metadataKey, metatype) {
return Reflect.getMetadata(metadataKey, metatype) || [];
}
async registerCoreModule(overrides) {
const moduleDefinition = InternalCoreModuleFactory.create(this.container, this, this.container.getModuleCompiler(), this.container.getHttpAdapterHostRef(), this.graphInspector, overrides);
const [instance] = await this.scanForModules({
moduleDefinition,
overrides,
});
this.container.registerCoreModuleRef(instance);
}
/**
* Add either request or transient globally scoped enhancers
* to all controllers metadata storage
*/
addScopedEnhancersMetadata() {
iterate(this.applicationProvidersApplyMap)
.filter(wrapper => this.isRequestOrTransient(wrapper.scope))
.forEach(({ moduleKey, providerKey }) => {
const modulesContainer = this.container.getModules();
const { injectables } = modulesContainer.get(moduleKey);
const instanceWrapper = injectables.get(providerKey);
const iterableIterator = modulesContainer.values();
iterate(iterableIterator)
.map(moduleRef => Array.from(moduleRef.controllers.values()).concat(moduleRef.entryProviders))
.flatten()
.forEach(controllerOrEntryProvider => controllerOrEntryProvider.addEnhancerMetadata(instanceWrapper));
});
}
applyApplicationProviders() {
const applyProvidersMap = this.getApplyProvidersMap();
const applyRequestProvidersMap = this.getApplyRequestProvidersMap();
const getInstanceWrapper = (moduleKey, providerKey, collectionKey) => {
const modules = this.container.getModules();
const collection = modules.get(moduleKey)[collectionKey];
return collection.get(providerKey);
};
// Add global enhancers to the application config
this.applicationProvidersApplyMap.forEach(({ moduleKey, providerKey, type, scope }) => {
let instanceWrapper;
if (this.isRequestOrTransient(scope)) {
instanceWrapper = getInstanceWrapper(moduleKey, providerKey, 'injectables');
this.graphInspector.insertAttachedEnhancer(instanceWrapper);
return applyRequestProvidersMap[type](instanceWrapper);
}
instanceWrapper = getInstanceWrapper(moduleKey, providerKey, 'providers');
this.graphInspector.insertAttachedEnhancer(instanceWrapper);
// An enhancer registered as static whose dependency tree is
// request-scoped has no usable static instance: an alias or a factory
// has none, and a class has only a prototype whose constructor never
// ran. Fail at startup instead of dropping it or running it half-built.
// A static factory that returns nothing on purpose is still skipped.
if (!instanceWrapper.isDependencyTreeStatic()) {
const [kind, provider] = this.describeEnhancerProvider(instanceWrapper);
throw new RequestScopedGlobalEnhancerException(type, provider, kind);
}
// The same goes for a static enhancer that was never instantiated.
if (!instanceWrapper.getInstanceByContextId(STATIC_CONTEXT).isResolved) {
const [, provider] = this.describeEnhancerProvider(instanceWrapper);
throw new UninstantiatedGlobalEnhancerException(type, provider);
}
const instance = instanceWrapper.instance;
// A static factory that returns nothing on purpose is skipped
if (!isNil(instance)) {
const provider = instanceWrapper.metatype
? this.describeEnhancerProvider(instanceWrapper)[1]
: 'useValue';
const description = `${type} provider (${provider}) gives ${describeEnhancer(instance)}`;
const kind = ENHANCER_KIND_BY_TOKEN[type];
if (kind) {
assertEnhancer(instance, kind, description);
}
else if (type === APP_FILTER) {
warnOnInvalidFilter(instance, description);
}
}
applyProvidersMap[type](instance);
});
}
describeEnhancerProvider(wrapper) {
if (wrapper.isAlias) {
const [target] = wrapper.inject ?? [];
const name = isFunction(target) ? target.name : String(target);
return ['useExisting', `useExisting: ${name}`];
}
if (isNil(wrapper.inject)) {
return ['useClass', `useClass: ${wrapper.metatype.name}`];
}
return ['useFactory', 'useFactory'];
}
getApplyProvidersMap() {
return {
[APP_INTERCEPTOR]: (interceptor) => this.applicationConfig.addGlobalInterceptor(interceptor),
[APP_PIPE]: (pipe) => this.applicationConfig.addGlobalPipe(pipe),
[APP_GUARD]: (guard) => this.applicationConfig.addGlobalGuard(guard),
[APP_FILTER]: (filter) => this.applicationConfig.addGlobalFilter(filter),
};
}
getApplyRequestProvidersMap() {
return {
[APP_INTERCEPTOR]: (interceptor) => this.applicationConfig.addGlobalRequestInterceptor(interceptor),
[APP_PIPE]: (pipe) => this.applicationConfig.addGlobalRequestPipe(pipe),
[APP_GUARD]: (guard) => this.applicationConfig.addGlobalRequestGuard(guard),
[APP_FILTER]: (filter) => this.applicationConfig.addGlobalRequestFilter(filter),
};
}
isDynamicModule(module) {
return module && !!module.module;
}
/**
* @param metatype
* @returns `true` if `metatype` is annotated with the `@Injectable()` decorator.
*/
isInjectable(metatype) {
return !!Reflect.getMetadata(INJECTABLE_WATERMARK, metatype);
}
/**
* @param metatype
* @returns `true` if `metatype` is annotated with the `@Controller()` decorator.
*/
isController(metatype) {
return !!Reflect.getMetadata(CONTROLLER_WATERMARK, metatype);
}
/**
* @param metatype
* @returns `true` if `metatype` is annotated with the `@Catch()` decorator.
*/
isExceptionFilter(metatype) {
return !!Reflect.getMetadata(CATCH_WATERMARK, metatype);
}
isForwardReference(module) {
return module && !!module.forwardRef;
}
/**
* Resolves a forward reference once per container (see `ModuleCompiler`),
* so that the module that is scanned and imported is the one that was
* registered.
*/
resolveForwardReference(reference) {
return this.container
.getModuleCompiler()
.resolveForwardReference(reference);
}
isRequestOrTransient(scope) {
return scope === Scope.REQUEST || scope === Scope.TRANSIENT;
}
}