@nestjs/core 10.4.11 → 11.0.0-next.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. package/adapters/http-adapter.d.ts +15 -2
  2. package/adapters/http-adapter.js +24 -1
  3. package/errors/exception-handler.d.ts +1 -2
  4. package/errors/exception-handler.js +1 -6
  5. package/errors/exceptions/undefined-dependency.exception.d.ts +2 -2
  6. package/errors/exceptions/undefined-dependency.exception.js +2 -2
  7. package/errors/exceptions/unknown-dependencies.exception.d.ts +2 -2
  8. package/errors/exceptions-zone.d.ts +2 -2
  9. package/errors/messages.d.ts +2 -2
  10. package/errors/messages.js +3 -3
  11. package/exceptions/base-exception-filter-context.js +1 -1
  12. package/exceptions/base-exception-filter.d.ts +2 -2
  13. package/exceptions/base-exception-filter.js +2 -3
  14. package/exceptions/exceptions-handler.d.ts +2 -2
  15. package/exceptions/exceptions-handler.js +2 -2
  16. package/exceptions/external-exception-filter-context.d.ts +1 -1
  17. package/exceptions/external-exception-filter-context.js +1 -1
  18. package/exceptions/external-exception-filter.js +3 -2
  19. package/exceptions/external-exceptions-handler.d.ts +2 -2
  20. package/exceptions/external-exceptions-handler.js +2 -2
  21. package/guards/guards-context-creator.d.ts +1 -1
  22. package/guards/guards-context-creator.js +2 -2
  23. package/helpers/execution-context-host.d.ts +1 -1
  24. package/helpers/external-context-creator.d.ts +1 -1
  25. package/helpers/external-context-creator.js +8 -8
  26. package/helpers/router-method-factory.js +7 -0
  27. package/injector/abstract-instance-resolver.js +2 -2
  28. package/injector/compiler.d.ts +9 -8
  29. package/injector/compiler.js +20 -14
  30. package/injector/container.d.ts +8 -7
  31. package/injector/container.js +13 -5
  32. package/injector/helpers/silent-logger.js +0 -1
  33. package/injector/injector.d.ts +5 -5
  34. package/injector/injector.js +7 -7
  35. package/injector/inquirer/inquirer-providers.js +0 -1
  36. package/injector/instance-wrapper.d.ts +4 -4
  37. package/injector/instance-wrapper.js +4 -4
  38. package/injector/lazy-module-loader/lazy-module-loader.d.ts +1 -1
  39. package/injector/module-ref.js +1 -0
  40. package/injector/module.d.ts +2 -2
  41. package/injector/module.js +7 -3
  42. package/injector/opaque-key-factory/by-reference-module-opaque-key-factory.d.ts +15 -0
  43. package/injector/opaque-key-factory/by-reference-module-opaque-key-factory.js +40 -0
  44. package/injector/opaque-key-factory/deep-hashed-module-opaque-key-factory.d.ts +15 -0
  45. package/injector/opaque-key-factory/deep-hashed-module-opaque-key-factory.js +83 -0
  46. package/injector/opaque-key-factory/interfaces/module-opaque-key-factory.interface.d.ts +18 -0
  47. package/injector/opaque-key-factory/interfaces/module-opaque-key-factory.interface.js +2 -0
  48. package/inspector/noop-graph-inspector.js +0 -1
  49. package/inspector/serialized-graph.d.ts +2 -2
  50. package/interceptors/interceptors-context-creator.d.ts +1 -1
  51. package/interceptors/interceptors-context-creator.js +2 -2
  52. package/metadata-scanner.d.ts +1 -1
  53. package/middleware/builder.d.ts +1 -1
  54. package/middleware/builder.js +2 -3
  55. package/middleware/middleware-module.js +1 -1
  56. package/middleware/route-info-path-extractor.js +6 -2
  57. package/middleware/utils.js +22 -11
  58. package/nest-application-context.d.ts +3 -3
  59. package/nest-application-context.js +16 -6
  60. package/nest-application.js +2 -2
  61. package/nest-factory.d.ts +7 -5
  62. package/nest-factory.js +1 -1
  63. package/package.json +3 -3
  64. package/pipes/pipes-context-creator.d.ts +1 -1
  65. package/pipes/pipes-context-creator.js +2 -2
  66. package/repl/assign-to-object.util.d.ts +1 -1
  67. package/router/interfaces/route-params-factory.interface.d.ts +1 -1
  68. package/router/legacy-route-converter.d.ts +13 -0
  69. package/router/legacy-route-converter.js +48 -0
  70. package/router/request/request-providers.js +0 -1
  71. package/router/route-params-factory.d.ts +2 -2
  72. package/router/route-params-factory.js +1 -0
  73. package/router/route-path-factory.d.ts +1 -1
  74. package/router/router-exception-filters.d.ts +1 -1
  75. package/router/router-exception-filters.js +1 -1
  76. package/router/router-execution-context.d.ts +2 -2
  77. package/router/router-execution-context.js +1 -1
  78. package/router/router-explorer.js +17 -5
  79. package/router/router-proxy.d.ts +3 -3
  80. package/router/sse-stream.js +1 -1
  81. package/router/utils/flatten-route-paths.util.d.ts +5 -1
  82. package/scanner.d.ts +2 -2
  83. package/scanner.js +6 -6
  84. package/services/reflector.service.d.ts +3 -3
  85. package/services/reflector.service.js +7 -0
@@ -2,7 +2,6 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.SilentLogger = void 0;
4
4
  const common_1 = require("@nestjs/common");
5
- // eslint-disable-next-line @typescript-eslint/no-empty-function
6
5
  const noop = () => { };
7
6
  class SilentLogger extends common_1.Logger {
8
7
  constructor() {
@@ -1,5 +1,5 @@
1
1
  import { InjectionToken } from '@nestjs/common';
2
- import { Controller, Injectable, Type } from '@nestjs/common/interfaces';
2
+ import { Controller, ForwardReference, Injectable, Type } from '@nestjs/common/interfaces';
3
3
  import { ContextId, InstancePerContext, InstanceWrapper, PropertyMetadata } from './instance-wrapper';
4
4
  import { Module } from './module';
5
5
  import { SettlementSignal } from './settlement-signal';
@@ -44,7 +44,7 @@ export declare class Injector {
44
44
  private logger;
45
45
  constructor(options?: {
46
46
  preview: boolean;
47
- });
47
+ } | undefined);
48
48
  loadPrototype<T>({ token }: InstanceWrapper<T>, collection: Map<InjectionToken, InstanceWrapper<T>>, contextId?: ContextId): void;
49
49
  loadInstance<T>(wrapper: InstanceWrapper<T>, collection: Map<InjectionToken, InstanceWrapper>, moduleRef: Module, contextId?: ContextId, inquirer?: InstanceWrapper): Promise<void>;
50
50
  loadMiddleware(wrapper: InstanceWrapper, collection: Map<InjectionToken, InstanceWrapper>, moduleRef: Module, contextId?: ContextId, inquirer?: InstanceWrapper): Promise<void>;
@@ -52,14 +52,14 @@ export declare class Injector {
52
52
  loadInjectable<T = any>(wrapper: InstanceWrapper<T>, moduleRef: Module, contextId?: ContextId, inquirer?: InstanceWrapper): Promise<void>;
53
53
  loadProvider(wrapper: InstanceWrapper<Injectable>, moduleRef: Module, contextId?: ContextId, inquirer?: InstanceWrapper): Promise<void>;
54
54
  applySettlementSignal<T>(instancePerContext: InstancePerContext<T>, host: InstanceWrapper<T>): SettlementSignal;
55
- resolveConstructorParams<T>(wrapper: InstanceWrapper<T>, moduleRef: Module, inject: InjectorDependency[], callback: (args: unknown[]) => void | Promise<void>, contextId?: ContextId, inquirer?: InstanceWrapper, parentInquirer?: InstanceWrapper): Promise<void>;
55
+ resolveConstructorParams<T>(wrapper: InstanceWrapper<T>, moduleRef: Module, inject: InjectorDependency[] | undefined, callback: (args: unknown[]) => void | Promise<void>, contextId?: ContextId, inquirer?: InstanceWrapper, parentInquirer?: InstanceWrapper): Promise<void>;
56
56
  getClassDependencies<T>(wrapper: InstanceWrapper<T>): [InjectorDependency[], number[]];
57
57
  getFactoryProviderDependencies<T>(wrapper: InstanceWrapper<T>): [InjectorDependency[], number[]];
58
58
  reflectConstructorParams<T>(type: Type<T>): any[];
59
59
  reflectOptionalParams<T>(type: Type<T>): any[];
60
60
  reflectSelfParams<T>(type: Type<T>): any[];
61
- resolveSingleParam<T>(wrapper: InstanceWrapper<T>, param: Type<any> | string | symbol | any, dependencyContext: InjectorDependencyContext, moduleRef: Module, contextId?: ContextId, inquirer?: InstanceWrapper, keyOrIndex?: symbol | string | number): Promise<InstanceWrapper<any>>;
62
- resolveParamToken<T>(wrapper: InstanceWrapper<T>, param: Type<any> | string | symbol | any): any;
61
+ resolveSingleParam<T>(wrapper: InstanceWrapper<T>, param: Type<any> | string | symbol, dependencyContext: InjectorDependencyContext, moduleRef: Module, contextId?: ContextId, inquirer?: InstanceWrapper, keyOrIndex?: symbol | string | number): Promise<InstanceWrapper<any>>;
62
+ resolveParamToken<T>(wrapper: InstanceWrapper<T>, param: Type<any> | string | symbol | ForwardReference): any;
63
63
  resolveComponentInstance<T>(moduleRef: Module, token: InjectionToken, dependencyContext: InjectorDependencyContext, wrapper: InstanceWrapper<T>, contextId?: ContextId, inquirer?: InstanceWrapper, keyOrIndex?: symbol | string | number): Promise<InstanceWrapper>;
64
64
  resolveComponentHost<T>(moduleRef: Module, instanceWrapper: InstanceWrapper<T | Promise<T>>, contextId?: ContextId, inquirer?: InstanceWrapper): Promise<InstanceWrapper>;
65
65
  lookupComponent<T = any>(providers: Map<Function | string | symbol, InstanceWrapper>, moduleRef: Module, dependencyContext: InjectorDependencyContext, wrapper: InstanceWrapper<T>, contextId?: ContextId, inquirer?: InstanceWrapper, keyOrIndex?: symbol | string | number): Promise<InstanceWrapper<T>>;
@@ -202,11 +202,11 @@ class Injector {
202
202
  return this.resolveComponentInstance(moduleRef, token, dependencyContext, wrapper, contextId, inquirer, keyOrIndex);
203
203
  }
204
204
  resolveParamToken(wrapper, param) {
205
- if (!param.forwardRef) {
206
- return param;
205
+ if (typeof param === 'object' && 'forwardRef' in param) {
206
+ wrapper.forwardRef = true;
207
+ return param.forwardRef();
207
208
  }
208
- wrapper.forwardRef = true;
209
- return param.forwardRef();
209
+ return param;
210
210
  }
211
211
  async resolveComponentInstance(moduleRef, token, dependencyContext, wrapper, contextId = constants_2.STATIC_CONTEXT, inquirer, keyOrIndex) {
212
212
  this.printResolvingDependenciesLog(token, inquirer);
@@ -233,7 +233,7 @@ class Injector {
233
233
  * instantiated beforehand.
234
234
  */
235
235
  instanceHost.donePromise &&
236
- instanceHost.donePromise.then(() => this.loadProvider(instanceWrapper, moduleRef, contextId, inquirer));
236
+ void instanceHost.donePromise.then(() => this.loadProvider(instanceWrapper, moduleRef, contextId, inquirer));
237
237
  }
238
238
  if (instanceWrapper.async) {
239
239
  const host = instanceWrapper.getInstanceByContextId(this.getContextId(contextId, instanceWrapper), inquirerId);
@@ -248,7 +248,7 @@ class Injector {
248
248
  if (wrapper && token === name) {
249
249
  throw new unknown_dependencies_exception_1.UnknownDependenciesException(wrapper.name, dependencyContext, moduleRef, { id: wrapper.id });
250
250
  }
251
- if (providers.has(name)) {
251
+ if (name && providers.has(name)) {
252
252
  const instanceWrapper = providers.get(name);
253
253
  this.printFoundInModuleLog(name, moduleRef);
254
254
  this.addDependencyMetadata(keyOrIndex, wrapper, instanceWrapper);
@@ -415,7 +415,7 @@ class Injector {
415
415
  }));
416
416
  }
417
417
  getInquirerId(inquirer) {
418
- return inquirer && inquirer.id;
418
+ return inquirer ? inquirer.id : undefined;
419
419
  }
420
420
  resolveScopedComponentHost(item, contextId, inquirer, parentInquirer) {
421
421
  return this.isInquirerRequest(item, parentInquirer)
@@ -3,7 +3,6 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.inquirerProvider = void 0;
4
4
  const common_1 = require("@nestjs/common");
5
5
  const inquirer_constants_1 = require("./inquirer-constants");
6
- // eslint-disable-next-line @typescript-eslint/no-empty-function
7
6
  const noop = () => { };
8
7
  exports.inquirerProvider = {
9
8
  provide: inquirer_constants_1.INQUIRER,
@@ -38,8 +38,8 @@ export declare class InstanceWrapper<T = any> {
38
38
  readonly isAlias: boolean;
39
39
  readonly subtype?: EnhancerSubtype;
40
40
  scope?: Scope;
41
- metatype: Type<T> | Function;
42
- inject?: FactoryProvider['inject'];
41
+ metatype: Type<T> | Function | null;
42
+ inject?: FactoryProvider['inject'] | null;
43
43
  forwardRef?: boolean;
44
44
  durable?: boolean;
45
45
  initTime?: number;
@@ -76,11 +76,11 @@ export declare class InstanceWrapper<T = any> {
76
76
  cloneStaticInstance(contextId: ContextId): InstancePerContext<T>;
77
77
  cloneTransientInstance(contextId: ContextId, inquirerId: string): InstancePerContext<T>;
78
78
  createPrototype(contextId: ContextId): any;
79
- isInRequestScope(contextId: ContextId, inquirer?: InstanceWrapper | undefined): boolean;
79
+ isInRequestScope(contextId: ContextId, inquirer?: InstanceWrapper): boolean;
80
80
  isLazyTransient(contextId: ContextId, inquirer: InstanceWrapper | undefined): boolean;
81
81
  isExplicitlyRequested(contextId: ContextId, inquirer?: InstanceWrapper): boolean;
82
82
  isStatic(contextId: ContextId, inquirer: InstanceWrapper | undefined): boolean;
83
- getStaticTransientInstances(): InstancePerContext<T>[];
83
+ getStaticTransientInstances(): (InstancePerContext<T> | undefined)[];
84
84
  mergeWith(provider: Provider): void;
85
85
  private isNewable;
86
86
  private initialize;
@@ -36,7 +36,7 @@ class InstanceWrapper {
36
36
  return !this.metatype || this.isFactory;
37
37
  }
38
38
  get isFactory() {
39
- return this.metatype && !(0, shared_utils_1.isNil)(this.inject);
39
+ return !!this.metatype && !(0, shared_utils_1.isNil)(this.inject);
40
40
  }
41
41
  get isTransient() {
42
42
  return this.scope === common_1.Scope.TRANSIENT;
@@ -221,7 +221,7 @@ class InstanceWrapper {
221
221
  (!this.isTransient || (this.isTransient && !!inquirer)));
222
222
  }
223
223
  isLazyTransient(contextId, inquirer) {
224
- const isInquirerRequestScoped = inquirer && !inquirer.isDependencyTreeStatic();
224
+ const isInquirerRequestScoped = !!(inquirer && !inquirer.isDependencyTreeStatic());
225
225
  return (this.isDependencyTreeStatic() &&
226
226
  contextId !== constants_1.STATIC_CONTEXT &&
227
227
  this.isTransient &&
@@ -231,7 +231,7 @@ class InstanceWrapper {
231
231
  const isSelfRequested = inquirer === this;
232
232
  return (this.isDependencyTreeStatic() &&
233
233
  contextId !== constants_1.STATIC_CONTEXT &&
234
- (isSelfRequested || (inquirer && inquirer.scope === common_1.Scope.TRANSIENT)));
234
+ (isSelfRequested || !!(inquirer && inquirer.scope === common_1.Scope.TRANSIENT)));
235
235
  }
236
236
  isStatic(contextId, inquirer) {
237
237
  const isInquirerRequestScoped = inquirer && !inquirer.isDependencyTreeStatic();
@@ -278,7 +278,7 @@ class InstanceWrapper {
278
278
  const { instance, isResolved, ...wrapperPartial } = metadata;
279
279
  Object.assign(this, wrapperPartial);
280
280
  this.setInstanceByContextId(constants_1.STATIC_CONTEXT, {
281
- instance,
281
+ instance: instance,
282
282
  isResolved,
283
283
  });
284
284
  this.scope === common_1.Scope.TRANSIENT && (this.transientMap = new Map());
@@ -12,7 +12,7 @@ export declare class LazyModuleLoader {
12
12
  private readonly moduleCompiler;
13
13
  private readonly modulesContainer;
14
14
  private readonly moduleOverrides?;
15
- constructor(dependenciesScanner: DependenciesScanner, instanceLoader: InstanceLoader, moduleCompiler: ModuleCompiler, modulesContainer: ModulesContainer, moduleOverrides?: ModuleOverride[]);
15
+ constructor(dependenciesScanner: DependenciesScanner, instanceLoader: InstanceLoader, moduleCompiler: ModuleCompiler, modulesContainer: ModulesContainer, moduleOverrides?: ModuleOverride[] | undefined);
16
16
  load(loaderFn: () => Promise<Type<unknown> | DynamicModule> | Type<unknown> | DynamicModule, loadOpts?: LazyModuleLoaderLoadOptions): Promise<ModuleRef>;
17
17
  private registerLoggerConfiguration;
18
18
  private createLazyModulesContainer;
@@ -43,6 +43,7 @@ class ModuleRef extends abstract_instance_resolver_1.AbstractInstanceResolver {
43
43
  durable: (0, is_durable_1.isDurable)(type),
44
44
  host: moduleRef,
45
45
  });
46
+ /* eslint-disable-next-line no-async-promise-executor */
46
47
  return new Promise(async (resolve, reject) => {
47
48
  try {
48
49
  const callback = async (instances) => {
@@ -56,8 +56,8 @@ export declare class Module {
56
56
  addCustomValue(provider: ValueProvider, collection: Map<Function | string | symbol, InstanceWrapper>, enhancerSubtype?: EnhancerSubtype): void;
57
57
  addCustomFactory(provider: FactoryProvider, collection: Map<Function | string | symbol, InstanceWrapper>, enhancerSubtype?: EnhancerSubtype): void;
58
58
  addCustomUseExisting(provider: ExistingProvider, collection: Map<Function | string | symbol, InstanceWrapper>, enhancerSubtype?: EnhancerSubtype): void;
59
- addExportedProvider(provider: Provider | string | symbol | DynamicModule): Set<InjectionToken>;
60
- addCustomExportedProvider(provider: FactoryProvider | ValueProvider | ClassProvider | ExistingProvider): Set<InjectionToken>;
59
+ addExportedProvider(provider: Provider | string | symbol | DynamicModule): Set<InjectionToken> | undefined;
60
+ addCustomExportedProvider(provider: FactoryProvider | ValueProvider | ClassProvider | ExistingProvider): Set<InjectionToken> | undefined;
61
61
  validateExportedProvider(token: InjectionToken): InjectionToken;
62
62
  addController(controller: Type<Controller>): void;
63
63
  assignControllerUniqueId(controller: Type<Controller>): void;
@@ -81,8 +81,8 @@ class Module {
81
81
  if (!this._providers.has(this._metatype)) {
82
82
  throw new exceptions_1.RuntimeException();
83
83
  }
84
- const module = this._providers.get(this._metatype);
85
- return module.instance;
84
+ const moduleRef = this._providers.get(this._metatype);
85
+ return moduleRef.instance;
86
86
  }
87
87
  get metatype() {
88
88
  return this._metatype;
@@ -418,7 +418,11 @@ class Module {
418
418
  }
419
419
  generateUuid() {
420
420
  const prefix = 'M_';
421
- const key = this.name?.toString() ?? this.token?.toString();
421
+ const key = this.token
422
+ ? this.token.includes(':')
423
+ ? this.token.split(':')[1]
424
+ : this.token
425
+ : this.name;
422
426
  return key ? uuid_factory_1.UuidFactory.get(`${prefix}_${key}`) : (0, random_string_generator_util_1.randomStringGenerator)();
423
427
  }
424
428
  isTransientProvider(provider) {
@@ -0,0 +1,15 @@
1
+ import { DynamicModule } from '@nestjs/common/interfaces/modules/dynamic-module.interface';
2
+ import { ForwardReference } from '@nestjs/common/interfaces/modules/forward-reference.interface';
3
+ import { Type } from '@nestjs/common/interfaces/type.interface';
4
+ import { ModuleOpaqueKeyFactory } from './interfaces/module-opaque-key-factory.interface';
5
+ export declare class ByReferenceModuleOpaqueKeyFactory implements ModuleOpaqueKeyFactory {
6
+ private readonly keyGenerationStrategy;
7
+ constructor(options?: {
8
+ keyGenerationStrategy: 'random' | 'shallow';
9
+ });
10
+ createForStatic(moduleCls: Type, originalRef?: Type | ForwardReference): string;
11
+ createForDynamic(moduleCls: Type<unknown>, dynamicMetadata: Omit<DynamicModule, 'module'>, originalRef: DynamicModule | ForwardReference): string;
12
+ private getOrCreateModuleId;
13
+ private hashString;
14
+ private generateRandomString;
15
+ }
@@ -0,0 +1,40 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ByReferenceModuleOpaqueKeyFactory = void 0;
4
+ const random_string_generator_util_1 = require("@nestjs/common/utils/random-string-generator.util");
5
+ const crypto_1 = require("crypto");
6
+ const K_MODULE_ID = Symbol('K_MODULE_ID');
7
+ class ByReferenceModuleOpaqueKeyFactory {
8
+ constructor(options) {
9
+ this.keyGenerationStrategy = options?.keyGenerationStrategy ?? 'random';
10
+ }
11
+ createForStatic(moduleCls, originalRef = moduleCls) {
12
+ return this.getOrCreateModuleId(moduleCls, undefined, originalRef);
13
+ }
14
+ createForDynamic(moduleCls, dynamicMetadata, originalRef) {
15
+ return this.getOrCreateModuleId(moduleCls, dynamicMetadata, originalRef);
16
+ }
17
+ getOrCreateModuleId(moduleCls, dynamicMetadata, originalRef) {
18
+ if (originalRef[K_MODULE_ID]) {
19
+ return originalRef[K_MODULE_ID];
20
+ }
21
+ let moduleId;
22
+ if (this.keyGenerationStrategy === 'random') {
23
+ moduleId = this.generateRandomString();
24
+ }
25
+ else {
26
+ moduleId = dynamicMetadata
27
+ ? `${this.generateRandomString()}:${this.hashString(moduleCls.name + JSON.stringify(dynamicMetadata))}`
28
+ : `${this.generateRandomString()}:${this.hashString(moduleCls.toString())}`;
29
+ }
30
+ originalRef[K_MODULE_ID] = moduleId;
31
+ return moduleId;
32
+ }
33
+ hashString(value) {
34
+ return (0, crypto_1.createHash)('sha256').update(value).digest('hex');
35
+ }
36
+ generateRandomString() {
37
+ return (0, random_string_generator_util_1.randomStringGenerator)();
38
+ }
39
+ }
40
+ exports.ByReferenceModuleOpaqueKeyFactory = ByReferenceModuleOpaqueKeyFactory;
@@ -0,0 +1,15 @@
1
+ import { DynamicModule } from '@nestjs/common/interfaces/modules/dynamic-module.interface';
2
+ import { Type } from '@nestjs/common/interfaces/type.interface';
3
+ import { ModuleOpaqueKeyFactory } from './interfaces/module-opaque-key-factory.interface';
4
+ export declare class DeepHashedModuleOpaqueKeyFactory implements ModuleOpaqueKeyFactory {
5
+ private readonly moduleIdsCache;
6
+ private readonly moduleTokenCache;
7
+ private readonly logger;
8
+ createForStatic(moduleCls: Type): string;
9
+ createForDynamic(moduleCls: Type<unknown>, dynamicMetadata: Omit<DynamicModule, 'module'>): string;
10
+ getStringifiedOpaqueToken(opaqueToken: object | undefined): string;
11
+ getModuleId(metatype: Type<unknown>): string;
12
+ getModuleName(metatype: Type<any>): string;
13
+ private hashString;
14
+ private replacer;
15
+ }
@@ -0,0 +1,83 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DeepHashedModuleOpaqueKeyFactory = void 0;
4
+ const logger_service_1 = require("@nestjs/common/services/logger.service");
5
+ const random_string_generator_util_1 = require("@nestjs/common/utils/random-string-generator.util");
6
+ const shared_utils_1 = require("@nestjs/common/utils/shared.utils");
7
+ const crypto_1 = require("crypto");
8
+ const fast_safe_stringify_1 = require("fast-safe-stringify");
9
+ const CLASS_STR = 'class ';
10
+ const CLASS_STR_LEN = CLASS_STR.length;
11
+ class DeepHashedModuleOpaqueKeyFactory {
12
+ constructor() {
13
+ this.moduleIdsCache = new WeakMap();
14
+ this.moduleTokenCache = new Map();
15
+ this.logger = new logger_service_1.Logger(DeepHashedModuleOpaqueKeyFactory.name, {
16
+ timestamp: true,
17
+ });
18
+ }
19
+ createForStatic(moduleCls) {
20
+ const moduleId = this.getModuleId(moduleCls);
21
+ const moduleName = this.getModuleName(moduleCls);
22
+ const key = `${moduleId}_${moduleName}`;
23
+ if (this.moduleTokenCache.has(key)) {
24
+ return this.moduleTokenCache.get(key);
25
+ }
26
+ const hash = this.hashString(key);
27
+ this.moduleTokenCache.set(key, hash);
28
+ return hash;
29
+ }
30
+ createForDynamic(moduleCls, dynamicMetadata) {
31
+ const moduleId = this.getModuleId(moduleCls);
32
+ const moduleName = this.getModuleName(moduleCls);
33
+ const opaqueToken = {
34
+ id: moduleId,
35
+ module: moduleName,
36
+ dynamic: dynamicMetadata,
37
+ };
38
+ const start = performance.now();
39
+ const opaqueTokenString = this.getStringifiedOpaqueToken(opaqueToken);
40
+ const timeSpentInMs = performance.now() - start;
41
+ if (timeSpentInMs > 10) {
42
+ const formattedTimeSpent = timeSpentInMs.toFixed(2);
43
+ this.logger.warn(`The module "${opaqueToken.module}" is taking ${formattedTimeSpent}ms to serialize, this may be caused by larger objects statically assigned to the module. Consider changing the "moduleIdGeneratorAlgorithm" option to "reference" to improve the performance.`);
44
+ }
45
+ return this.hashString(opaqueTokenString);
46
+ }
47
+ getStringifiedOpaqueToken(opaqueToken) {
48
+ // Uses safeStringify instead of JSON.stringify to support circular dynamic modules
49
+ // The replacer function is also required in order to obtain real class names
50
+ // instead of the unified "Function" key
51
+ return opaqueToken ? (0, fast_safe_stringify_1.default)(opaqueToken, this.replacer) : '';
52
+ }
53
+ getModuleId(metatype) {
54
+ let moduleId = this.moduleIdsCache.get(metatype);
55
+ if (moduleId) {
56
+ return moduleId;
57
+ }
58
+ moduleId = (0, random_string_generator_util_1.randomStringGenerator)();
59
+ this.moduleIdsCache.set(metatype, moduleId);
60
+ return moduleId;
61
+ }
62
+ getModuleName(metatype) {
63
+ return metatype.name;
64
+ }
65
+ hashString(value) {
66
+ return (0, crypto_1.createHash)('sha256').update(value).digest('hex');
67
+ }
68
+ replacer(key, value) {
69
+ if ((0, shared_utils_1.isFunction)(value)) {
70
+ const funcAsString = value.toString();
71
+ const isClass = funcAsString.slice(0, CLASS_STR_LEN) === CLASS_STR;
72
+ if (isClass) {
73
+ return value.name;
74
+ }
75
+ return funcAsString;
76
+ }
77
+ if ((0, shared_utils_1.isSymbol)(value)) {
78
+ return value.toString();
79
+ }
80
+ return value;
81
+ }
82
+ }
83
+ exports.DeepHashedModuleOpaqueKeyFactory = DeepHashedModuleOpaqueKeyFactory;
@@ -0,0 +1,18 @@
1
+ import { DynamicModule } from '@nestjs/common/interfaces/modules/dynamic-module.interface';
2
+ import { ForwardReference } from '@nestjs/common/interfaces/modules/forward-reference.interface';
3
+ import { Type } from '@nestjs/common/interfaces/type.interface';
4
+ export interface ModuleOpaqueKeyFactory {
5
+ /**
6
+ * Creates a unique opaque key for the given static module.
7
+ * @param moduleCls A static module class.
8
+ * @param originalRef Original object reference. In most cases, it's the same as `moduleCls`.
9
+ */
10
+ createForStatic(moduleCls: Type, originalRef: Type | ForwardReference): string;
11
+ /**
12
+ * Creates a unique opaque key for the given dynamic module.
13
+ * @param moduleCls A dynamic module class reference.
14
+ * @param dynamicMetadata Dynamic module metadata.
15
+ * @param originalRef Original object reference.
16
+ */
17
+ createForDynamic(moduleCls: Type<unknown>, dynamicMetadata: Omit<DynamicModule, 'module'>, originalRef: DynamicModule | ForwardReference): string;
18
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -2,7 +2,6 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.NoopGraphInspector = void 0;
4
4
  const graph_inspector_1 = require("./graph-inspector");
5
- // eslint-disable-next-line @typescript-eslint/no-empty-function
6
5
  const noop = () => { };
7
6
  exports.NoopGraphInspector = new Proxy(graph_inspector_1.GraphInspector.prototype, {
8
7
  get: () => noop,
@@ -17,7 +17,7 @@ export declare class SerializedGraph {
17
17
  private static readonly INTERNAL_PROVIDERS;
18
18
  set status(status: SerializedGraphStatus);
19
19
  set metadata(metadata: SerializedGraphMetadata);
20
- insertNode(nodeDefinition: Node): Node;
20
+ insertNode(nodeDefinition: Node): Node | undefined;
21
21
  insertEdge(edgeDefinition: WithOptionalId<Edge>): {
22
22
  id: string;
23
23
  source: string;
@@ -44,7 +44,7 @@ export declare class SerializedGraph {
44
44
  insertEntrypoint<T>(definition: Entrypoint<T>, parentId: string): void;
45
45
  insertOrphanedEnhancer(entry: OrphanedEnhancerDefinition): void;
46
46
  insertAttachedEnhancer(nodeId: string): void;
47
- getNodeById(id: string): Node;
47
+ getNodeById(id: string): Node | undefined;
48
48
  toJSON(): SerializedGraphJson;
49
49
  toString(): string;
50
50
  private generateUuidByEdgeDefinition;
@@ -7,7 +7,7 @@ export declare class InterceptorsContextCreator extends ContextCreator {
7
7
  private readonly container;
8
8
  private readonly config?;
9
9
  private moduleContext;
10
- constructor(container: NestContainer, config?: ApplicationConfig);
10
+ constructor(container: NestContainer, config?: ApplicationConfig | undefined);
11
11
  create(instance: Controller, callback: (...args: unknown[]) => unknown, module: string, contextId?: import("../injector/instance-wrapper").ContextId, inquirerId?: string): NestInterceptor[];
12
12
  createConcreteContext<T extends any[], R extends any[]>(metadata: T, contextId?: import("../injector/instance-wrapper").ContextId, inquirerId?: string): R;
13
13
  getInterceptorInstance(metatype: Function | NestInterceptor, contextId?: import("../injector/instance-wrapper").ContextId, inquirerId?: string): NestInterceptor | null;
@@ -23,11 +23,11 @@ class InterceptorsContextCreator extends context_creator_1.ContextCreator {
23
23
  return (0, iterare_1.iterate)(metadata)
24
24
  .filter(interceptor => interceptor && (interceptor.name || interceptor.intercept))
25
25
  .map(interceptor => this.getInterceptorInstance(interceptor, contextId, inquirerId))
26
- .filter((interceptor) => interceptor && (0, shared_utils_1.isFunction)(interceptor.intercept))
26
+ .filter((interceptor) => interceptor ? (0, shared_utils_1.isFunction)(interceptor.intercept) : false)
27
27
  .toArray();
28
28
  }
29
29
  getInterceptorInstance(metatype, contextId = constants_2.STATIC_CONTEXT, inquirerId) {
30
- const isObject = metatype.intercept;
30
+ const isObject = !!metatype.intercept;
31
31
  if (isObject) {
32
32
  return metatype;
33
33
  }
@@ -6,7 +6,7 @@ export declare class MetadataScanner {
6
6
  * @see {@link getAllMethodNames}
7
7
  * @see getAllMethodNames
8
8
  */
9
- scanFromPrototype<T extends Injectable, R = any>(instance: T, prototype: object, callback: (name: string) => R): R[];
9
+ scanFromPrototype<T extends Injectable, R = any>(instance: T, prototype: object | null, callback: (name: string) => R): R[];
10
10
  /**
11
11
  * @deprecated
12
12
  * @see {@link getAllMethodNames}
@@ -8,7 +8,7 @@ export declare class MiddlewareBuilder implements MiddlewareConsumer {
8
8
  private readonly routeInfoPathExtractor;
9
9
  private readonly middlewareCollection;
10
10
  constructor(routesMapper: RoutesMapper, httpAdapter: HttpServer, routeInfoPathExtractor: RouteInfoPathExtractor);
11
- apply(...middleware: Array<Type<any> | Function | any>): MiddlewareConfigProxy;
11
+ apply(...middleware: Array<Type<any> | Function | Array<Type<any> | Function>>): MiddlewareConfigProxy;
12
12
  build(): MiddlewareConfiguration[];
13
13
  getHttpAdapter(): HttpServer;
14
14
  private static readonly ConfigProxy;
@@ -1,7 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.MiddlewareBuilder = void 0;
4
- const dependencies_decorator_1 = require("@nestjs/common/decorators/core/dependencies.decorator");
5
4
  const shared_utils_1 = require("@nestjs/common/utils/shared.utils");
6
5
  const iterare_1 = require("iterare");
7
6
  const utils_1 = require("./utils");
@@ -13,7 +12,7 @@ class MiddlewareBuilder {
13
12
  this.middlewareCollection = new Set();
14
13
  }
15
14
  apply(...middleware) {
16
- return new MiddlewareBuilder.ConfigProxy(this, (0, dependencies_decorator_1.flatten)(middleware), this.routeInfoPathExtractor);
15
+ return new MiddlewareBuilder.ConfigProxy(this, middleware.flat(), this.routeInfoPathExtractor);
17
16
  }
18
17
  build() {
19
18
  return [...this.middlewareCollection];
@@ -67,7 +66,7 @@ MiddlewareBuilder.ConfigProxy = class {
67
66
  .toArray();
68
67
  }
69
68
  removeOverlappedRoutes(routes) {
70
- const regexMatchParams = /(:[^\/]*)/g;
69
+ const regexMatchParams = /(:[^/]*)/g;
71
70
  const wildcard = '([^/]*)';
72
71
  const routesWithRegex = routes
73
72
  .filter(route => route.path.includes(':'))
@@ -162,7 +162,7 @@ class MiddlewareModule {
162
162
  const middlewareFunction = isMethodAll
163
163
  ? proxy
164
164
  : (req, res, next) => {
165
- if (applicationRef.getRequestMethod(req) === requestMethod) {
165
+ if (applicationRef.getRequestMethod?.(req) === requestMethod) {
166
166
  return proxy(req, res, next);
167
167
  }
168
168
  return next();
@@ -30,7 +30,11 @@ class RouteInfoPathExtractor {
30
30
  return Array.isArray(this.excludedGlobalPrefixRoutes)
31
31
  ? [
32
32
  ...entries,
33
- ...this.excludedGlobalPrefixRoutes.map(route => versionPaths + (0, shared_utils_1.addLeadingSlash)(route.path)),
33
+ ...this.excludedGlobalPrefixRoutes
34
+ .map(route => Array.isArray(versionPaths) && versionPaths.length > 0
35
+ ? versionPaths.map(v => v + (0, shared_utils_1.addLeadingSlash)(route.path))
36
+ : (0, shared_utils_1.addLeadingSlash)(route.path))
37
+ .flat(),
34
38
  ]
35
39
  : entries;
36
40
  }
@@ -43,7 +47,7 @@ class RouteInfoPathExtractor {
43
47
  return this.extractNonWildcardPathsFrom(route);
44
48
  }
45
49
  isAWildcard(path) {
46
- return ['*', '/*', '/*/', '(.*)', '/(.*)'].includes(path);
50
+ return ['*', '/*', '/*/', '*path', '/*path', '(.*)', '/(.*)'].includes(path);
47
51
  }
48
52
  extractNonWildcardPathsFrom({ path, method, version, }) {
49
53
  const versionPaths = this.extractVersionPathFrom(version);
@@ -7,23 +7,34 @@ exports.isMiddlewareRouteExcluded = isMiddlewareRouteExcluded;
7
7
  const common_1 = require("@nestjs/common");
8
8
  const shared_utils_1 = require("@nestjs/common/utils/shared.utils");
9
9
  const iterare_1 = require("iterare");
10
- const pathToRegexp = require("path-to-regexp");
10
+ const path_to_regexp_1 = require("path-to-regexp");
11
11
  const uid_1 = require("uid");
12
+ const legacy_route_converter_1 = require("../router/legacy-route-converter");
12
13
  const utils_1 = require("../router/utils");
13
14
  const mapToExcludeRoute = (routes) => {
14
15
  return routes.map(route => {
15
- if ((0, shared_utils_1.isString)(route)) {
16
+ const originalPath = (0, shared_utils_1.isString)(route) ? route : route.path;
17
+ const path = legacy_route_converter_1.LegacyRouteConverter.tryConvert(originalPath);
18
+ try {
19
+ if ((0, shared_utils_1.isString)(route)) {
20
+ return {
21
+ path,
22
+ requestMethod: common_1.RequestMethod.ALL,
23
+ pathRegex: (0, path_to_regexp_1.pathToRegexp)((0, shared_utils_1.addLeadingSlash)(path)).regexp,
24
+ };
25
+ }
16
26
  return {
17
- path: route,
18
- requestMethod: common_1.RequestMethod.ALL,
19
- pathRegex: pathToRegexp((0, shared_utils_1.addLeadingSlash)(route)),
27
+ path,
28
+ requestMethod: route.method,
29
+ pathRegex: (0, path_to_regexp_1.pathToRegexp)((0, shared_utils_1.addLeadingSlash)(path)).regexp,
20
30
  };
21
31
  }
22
- return {
23
- path: route.path,
24
- requestMethod: route.method,
25
- pathRegex: pathToRegexp((0, shared_utils_1.addLeadingSlash)(route.path)),
26
- };
32
+ catch (e) {
33
+ if (e instanceof TypeError) {
34
+ legacy_route_converter_1.LegacyRouteConverter.printError(originalPath);
35
+ }
36
+ throw e;
37
+ }
27
38
  });
28
39
  };
29
40
  exports.mapToExcludeRoute = mapToExcludeRoute;
@@ -87,7 +98,7 @@ function isMiddlewareRouteExcluded(req, excludedRoutes, httpAdapter) {
87
98
  }
88
99
  const reqMethod = httpAdapter.getRequestMethod(req);
89
100
  const originalUrl = httpAdapter.getRequestUrl(req);
90
- const queryParamsIndex = originalUrl && originalUrl.indexOf('?');
101
+ const queryParamsIndex = originalUrl ? originalUrl.indexOf('?') : -1;
91
102
  const pathname = queryParamsIndex >= 0
92
103
  ? originalUrl.slice(0, queryParamsIndex)
93
104
  : originalUrl;
@@ -1,5 +1,5 @@
1
1
  import { INestApplicationContext, Logger, LoggerService, LogLevel, ShutdownSignal } from '@nestjs/common';
2
- import { DynamicModule, Type } from '@nestjs/common/interfaces';
2
+ import { DynamicModule, SelectOptions, Type } from '@nestjs/common/interfaces';
3
3
  import { NestApplicationContextOptions } from '@nestjs/common/interfaces/nest-application-context-options.interface';
4
4
  import { AbstractInstanceResolver } from './injector/abstract-instance-resolver';
5
5
  import { NestContainer } from './injector/container';
@@ -26,13 +26,13 @@ export declare class NestApplicationContext<TOptions extends NestApplicationCont
26
26
  private _moduleRefsForHooksByDistance?;
27
27
  private initializationPromise?;
28
28
  protected get instanceLinksHost(): InstanceLinksHost;
29
- constructor(container: NestContainer, appOptions?: TOptions, contextModule?: Module, scope?: Type<any>[]);
29
+ constructor(container: NestContainer, appOptions?: TOptions, contextModule?: Module | null, scope?: Type<any>[]);
30
30
  selectContextModule(): void;
31
31
  /**
32
32
  * Allows navigating through the modules tree, for example, to pull out a specific instance from the selected module.
33
33
  * @returns {INestApplicationContext}
34
34
  */
35
- select<T>(moduleType: Type<T> | DynamicModule): INestApplicationContext;
35
+ select<T>(moduleType: Type<T> | DynamicModule, selectOptions?: SelectOptions): INestApplicationContext;
36
36
  /**
37
37
  * Retrieves an instance of either injectable or controller, otherwise, throws exception.
38
38
  * @returns {TResult}