@nestjs/core 9.3.1 → 9.3.3

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.
package/Readme.md CHANGED
@@ -11,7 +11,6 @@
11
11
  <a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/l/@nestjs/core.svg" alt="Package License" /></a>
12
12
  <a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/dm/@nestjs/common.svg" alt="NPM Downloads" /></a>
13
13
  <a href="https://circleci.com/gh/nestjs/nest" target="_blank"><img src="https://img.shields.io/circleci/build/github/nestjs/nest/master" alt="CircleCI" /></a>
14
- <a href="https://coveralls.io/github/nestjs/nest?branch=master" target="_blank"><img src="https://coveralls.io/repos/github/nestjs/nest/badge.svg?branch=master#9" alt="Coverage" /></a>
15
14
  <a href="https://discord.gg/G7Qnnhy" target="_blank"><img src="https://img.shields.io/badge/discord-online-brightgreen.svg" alt="Discord"/></a>
16
15
  <a href="https://opencollective.com/nest#backer" target="_blank"><img src="https://opencollective.com/nest/backers/badge.svg" alt="Backers on Open Collective" /></a>
17
16
  <a href="https://opencollective.com/nest#sponsor" target="_blank"><img src="https://opencollective.com/nest/sponsors/badge.svg" alt="Sponsors on Open Collective" /></a>
package/index.js CHANGED
@@ -4,7 +4,7 @@ exports.NestFactory = exports.APP_PIPE = exports.APP_INTERCEPTOR = exports.APP_G
4
4
  const tslib_1 = require("tslib");
5
5
  /*
6
6
  * Nest @core
7
- * Copyright(c) 2017 - 2022 Kamil Mysliwiec
7
+ * Copyright(c) 2017 - 2023 Kamil Mysliwiec
8
8
  * https://nestjs.com
9
9
  * MIT Licensed
10
10
  */
@@ -1,4 +1,4 @@
1
- import { DynamicModule, Type } from '@nestjs/common/interfaces';
1
+ import { DynamicModule, ForwardReference, Type } from '@nestjs/common/interfaces';
2
2
  import { ModuleTokenFactory } from './module-token-factory';
3
3
  export interface ModuleFactory {
4
4
  type: Type<any>;
@@ -9,9 +9,9 @@ export declare class ModuleCompiler {
9
9
  private readonly moduleTokenFactory;
10
10
  constructor(moduleTokenFactory?: ModuleTokenFactory);
11
11
  compile(metatype: Type<any> | DynamicModule | Promise<DynamicModule>): Promise<ModuleFactory>;
12
- extractMetadata(metatype: Type<any> | DynamicModule): {
12
+ extractMetadata(metatype: Type<any> | ForwardReference | DynamicModule): {
13
13
  type: Type<any>;
14
14
  dynamicMetadata?: Partial<DynamicModule> | undefined;
15
15
  };
16
- isDynamicModule(module: Type<any> | DynamicModule): module is DynamicModule;
16
+ isDynamicModule(module: Type<any> | DynamicModule | ForwardReference): module is DynamicModule;
17
17
  }
@@ -14,7 +14,11 @@ class ModuleCompiler {
14
14
  }
15
15
  extractMetadata(metatype) {
16
16
  if (!this.isDynamicModule(metatype)) {
17
- return { type: metatype };
17
+ return {
18
+ type: (metatype === null || metatype === void 0 ? void 0 : metatype.forwardRef)
19
+ ? metatype.forwardRef()
20
+ : metatype,
21
+ };
18
22
  }
19
23
  const { module: type } = metatype, dynamicMetadata = tslib_1.__rest(metatype, ["module"]);
20
24
  return { type, dynamicMetadata };
@@ -162,7 +162,9 @@ class Injector {
162
162
  ];
163
163
  }
164
164
  reflectConstructorParams(type) {
165
- const paramtypes = [...(Reflect.getMetadata(constants_1.PARAMTYPES_METADATA, type) || [])];
165
+ const paramtypes = [
166
+ ...(Reflect.getMetadata(constants_1.PARAMTYPES_METADATA, type) || []),
167
+ ];
166
168
  const selfParams = this.reflectSelfParams(type);
167
169
  selfParams.forEach(({ index, param }) => (paramtypes[index] = param));
168
170
  return paramtypes;
@@ -109,9 +109,11 @@ class InstanceWrapper {
109
109
  if (!(0, shared_utils_1.isUndefined)(this.isTreeDurable)) {
110
110
  return this.isTreeDurable;
111
111
  }
112
- if (this.durable === true) {
113
- this.isTreeDurable = true;
114
- this.printIntrospectedAsDurable();
112
+ if (this.scope === common_1.Scope.REQUEST) {
113
+ this.isTreeDurable = this.durable === undefined ? false : this.durable;
114
+ if (this.isTreeDurable) {
115
+ this.printIntrospectedAsDurable();
116
+ }
115
117
  return this.isTreeDurable;
116
118
  }
117
119
  const isStatic = this.isDependencyTreeStatic();
@@ -120,7 +122,7 @@ class InstanceWrapper {
120
122
  }
121
123
  const isTreeNonDurable = this.introspectDepsAttribute((collection, registry) => collection.some((item) => !item.isDependencyTreeStatic() &&
122
124
  !item.isDependencyTreeDurable(registry)), lookupRegistry);
123
- this.isTreeDurable = !isTreeNonDurable && this.durable !== false;
125
+ this.isTreeDurable = !isTreeNonDurable;
124
126
  if (this.isTreeDurable) {
125
127
  this.printIntrospectedAsDurable();
126
128
  }
@@ -128,24 +130,23 @@ class InstanceWrapper {
128
130
  }
129
131
  introspectDepsAttribute(callback, lookupRegistry = []) {
130
132
  if (lookupRegistry.includes(this[exports.INSTANCE_ID_SYMBOL])) {
131
- return true;
133
+ return false;
132
134
  }
133
135
  lookupRegistry = lookupRegistry.concat(this[exports.INSTANCE_ID_SYMBOL]);
134
136
  const { dependencies, properties, enhancers } = this[exports.INSTANCE_METADATA_SYMBOL];
135
- let introspectionResult = (dependencies && callback(dependencies, lookupRegistry)) || !dependencies;
136
- if (!introspectionResult || !(properties || enhancers)) {
137
+ let introspectionResult = dependencies
138
+ ? callback(dependencies, lookupRegistry)
139
+ : false;
140
+ if (introspectionResult || !(properties || enhancers)) {
137
141
  return introspectionResult;
138
142
  }
139
- const propertiesHosts = (properties || []).map(item => item.wrapper);
140
- introspectionResult =
141
- introspectionResult &&
142
- ((properties &&
143
- callback(properties.map(item => item.wrapper), lookupRegistry)) ||
144
- !properties);
145
- if (!introspectionResult || !enhancers) {
143
+ introspectionResult = properties
144
+ ? callback(properties.map(item => item.wrapper), lookupRegistry)
145
+ : false;
146
+ if (introspectionResult || !enhancers) {
146
147
  return introspectionResult;
147
148
  }
148
- return callback(enhancers, lookupRegistry);
149
+ return enhancers ? callback(enhancers, lookupRegistry) : false;
149
150
  }
150
151
  isDependencyTreeStatic(lookupRegistry = []) {
151
152
  if (!(0, shared_utils_1.isUndefined)(this.isTreeStatic)) {
@@ -156,7 +157,7 @@ class InstanceWrapper {
156
157
  this.printIntrospectedAsRequestScoped();
157
158
  return this.isTreeStatic;
158
159
  }
159
- this.isTreeStatic = this.introspectDepsAttribute((collection, registry) => collection.every((item) => item.isDependencyTreeStatic(registry)), lookupRegistry);
160
+ this.isTreeStatic = !this.introspectDepsAttribute((collection, registry) => collection.some((item) => !item.isDependencyTreeStatic(registry)), lookupRegistry);
160
161
  if (!this.isTreeStatic) {
161
162
  this.printIntrospectedAsRequestScoped();
162
163
  }
@@ -1,10 +1,13 @@
1
1
  import { DynamicModule } from '@nestjs/common';
2
2
  import { Type } from '@nestjs/common/interfaces/type.interface';
3
3
  export declare class ModuleTokenFactory {
4
+ private readonly moduleTokenCache;
4
5
  private readonly moduleIdsCache;
5
6
  create(metatype: Type<unknown>, dynamicModuleMetadata?: Partial<DynamicModule> | undefined): string;
6
- getDynamicMetadataToken(dynamicModuleMetadata: Partial<DynamicModule> | undefined): string;
7
+ getStaticModuleToken(moduleId: string, moduleName: string): string;
8
+ getStringifiedOpaqueToken(opaqueToken: object | undefined): string;
7
9
  getModuleId(metatype: Type<unknown>): string;
8
10
  getModuleName(metatype: Type<any>): string;
11
+ private hashString;
9
12
  private replacer;
10
13
  }
@@ -3,28 +3,42 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.ModuleTokenFactory = void 0;
4
4
  const random_string_generator_util_1 = require("@nestjs/common/utils/random-string-generator.util");
5
5
  const shared_utils_1 = require("@nestjs/common/utils/shared.utils");
6
+ const xxhash_1 = require("@node-rs/xxhash");
6
7
  const fast_safe_stringify_1 = require("fast-safe-stringify");
7
- const hash = require("object-hash");
8
+ const CLASS_STR = 'class ';
9
+ const CLASS_STR_LEN = CLASS_STR.length;
8
10
  class ModuleTokenFactory {
9
11
  constructor() {
12
+ this.moduleTokenCache = new Map();
10
13
  this.moduleIdsCache = new WeakMap();
11
14
  }
12
15
  create(metatype, dynamicModuleMetadata) {
13
16
  const moduleId = this.getModuleId(metatype);
17
+ if (!dynamicModuleMetadata) {
18
+ return this.getStaticModuleToken(moduleId, this.getModuleName(metatype));
19
+ }
14
20
  const opaqueToken = {
15
21
  id: moduleId,
16
22
  module: this.getModuleName(metatype),
17
- dynamic: this.getDynamicMetadataToken(dynamicModuleMetadata),
23
+ dynamic: dynamicModuleMetadata,
18
24
  };
19
- return hash(opaqueToken, { ignoreUnknown: true });
25
+ const opaqueTokenString = this.getStringifiedOpaqueToken(opaqueToken);
26
+ return this.hashString(opaqueTokenString);
27
+ }
28
+ getStaticModuleToken(moduleId, moduleName) {
29
+ const key = `${moduleId}_${moduleName}`;
30
+ if (this.moduleTokenCache.has(key)) {
31
+ return this.moduleTokenCache.get(key);
32
+ }
33
+ const hash = this.hashString(key);
34
+ this.moduleTokenCache.set(key, hash);
35
+ return hash;
20
36
  }
21
- getDynamicMetadataToken(dynamicModuleMetadata) {
37
+ getStringifiedOpaqueToken(opaqueToken) {
22
38
  // Uses safeStringify instead of JSON.stringify to support circular dynamic modules
23
39
  // The replacer function is also required in order to obtain real class names
24
40
  // instead of the unified "Function" key
25
- return dynamicModuleMetadata
26
- ? (0, fast_safe_stringify_1.default)(dynamicModuleMetadata, this.replacer)
27
- : '';
41
+ return opaqueToken ? (0, fast_safe_stringify_1.default)(opaqueToken, this.replacer) : '';
28
42
  }
29
43
  getModuleId(metatype) {
30
44
  let moduleId = this.moduleIdsCache.get(metatype);
@@ -38,14 +52,17 @@ class ModuleTokenFactory {
38
52
  getModuleName(metatype) {
39
53
  return metatype.name;
40
54
  }
55
+ hashString(value) {
56
+ return (0, xxhash_1.xxh32)(value).toString();
57
+ }
41
58
  replacer(key, value) {
42
59
  if ((0, shared_utils_1.isFunction)(value)) {
43
60
  const funcAsString = value.toString();
44
- const isClass = /^class\s/.test(funcAsString);
61
+ const isClass = funcAsString.slice(0, CLASS_STR_LEN) === CLASS_STR;
45
62
  if (isClass) {
46
63
  return value.name;
47
64
  }
48
- return hash(funcAsString, { ignoreUnknown: true });
65
+ return funcAsString;
49
66
  }
50
67
  if ((0, shared_utils_1.isSymbol)(value)) {
51
68
  return value.toString();
@@ -1,11 +1,11 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.ModulesContainer = void 0;
4
- const uuid_1 = require("uuid");
4
+ const uid_1 = require("uid");
5
5
  class ModulesContainer extends Map {
6
6
  constructor() {
7
7
  super(...arguments);
8
- this._applicationId = (0, uuid_1.v4)();
8
+ this._applicationId = (0, uid_1.uid)(21);
9
9
  }
10
10
  get applicationId() {
11
11
  return this._applicationId;
@@ -1,16 +1,19 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.DeterministicUuidRegistry = void 0;
4
- const uuid_1 = require("uuid");
4
+ const xxhash_1 = require("@node-rs/xxhash");
5
5
  const DEFAULT_UUID_NAMESPACE = 'efa0df42-88af-474f-9cad-4206a2319f07';
6
6
  class DeterministicUuidRegistry {
7
7
  static get(str, namespace = DEFAULT_UUID_NAMESPACE, inc = 0) {
8
- const id = inc ? (0, uuid_1.v5)(str + `${inc}`, namespace) : (0, uuid_1.v5)(str, namespace);
9
- if (this.registry.has(id)) {
8
+ const id = inc
9
+ ? (0, xxhash_1.xxh32)(`${namespace}_${str}_${inc}`)
10
+ : (0, xxhash_1.xxh32)(`${namespace}_${str}`);
11
+ const idAsString = `${id}`;
12
+ if (this.registry.has(idAsString)) {
10
13
  return this.get(str, namespace, inc + 1);
11
14
  }
12
- this.registry.add(id);
13
- return id;
15
+ this.registry.add(idAsString);
16
+ return idAsString;
14
17
  }
15
18
  static clear() {
16
19
  this.registry.clear();
@@ -1,7 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.UuidFactory = exports.UuidFactoryMode = void 0;
4
- const random_string_generator_util_1 = require("../../common/utils/random-string-generator.util");
4
+ const random_string_generator_util_1 = require("@nestjs/common/utils/random-string-generator.util");
5
5
  const deterministic_uuid_registry_1 = require("./deterministic-uuid-registry");
6
6
  var UuidFactoryMode;
7
7
  (function (UuidFactoryMode) {
@@ -1,5 +1,13 @@
1
1
  import { Injectable } from '@nestjs/common/interfaces/injectable.interface';
2
2
  export declare class MetadataScanner {
3
+ private readonly cachedScannedPrototypes;
4
+ /**
5
+ * @deprecated Use {@link getAllMethodNames} instead.
6
+ */
3
7
  scanFromPrototype<T extends Injectable, R = any>(instance: T, prototype: object, callback: (name: string) => R): R[];
8
+ /**
9
+ * @deprecated Use {@link getAllMethodNames} instead.
10
+ */
4
11
  getAllFilteredMethodNames(prototype: object): IterableIterator<string>;
12
+ getAllMethodNames(prototype: object | null): string[];
5
13
  }
@@ -2,29 +2,78 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.MetadataScanner = void 0;
4
4
  const shared_utils_1 = require("@nestjs/common/utils/shared.utils");
5
- const iterare_1 = require("iterare");
6
5
  class MetadataScanner {
6
+ constructor() {
7
+ this.cachedScannedPrototypes = new Map();
8
+ }
9
+ /**
10
+ * @deprecated Use {@link getAllMethodNames} instead.
11
+ */
7
12
  scanFromPrototype(instance, prototype, callback) {
8
- const methodNames = new Set(this.getAllFilteredMethodNames(prototype));
9
- return (0, iterare_1.iterate)(methodNames)
10
- .map(callback)
11
- .filter(metadata => !(0, shared_utils_1.isNil)(metadata))
12
- .toArray();
13
+ if (!prototype) {
14
+ return [];
15
+ }
16
+ const visitedNames = new Map();
17
+ const result = [];
18
+ do {
19
+ for (const property of Object.getOwnPropertyNames(prototype)) {
20
+ if (visitedNames.has(property)) {
21
+ continue;
22
+ }
23
+ visitedNames.set(property, true);
24
+ // reason: https://github.com/nestjs/nest/pull/10821#issuecomment-1411916533
25
+ const descriptor = Object.getOwnPropertyDescriptor(prototype, property);
26
+ if (descriptor.set ||
27
+ descriptor.get ||
28
+ (0, shared_utils_1.isConstructor)(property) ||
29
+ !(0, shared_utils_1.isFunction)(prototype[property])) {
30
+ continue;
31
+ }
32
+ const value = callback(property);
33
+ if ((0, shared_utils_1.isNil)(value)) {
34
+ continue;
35
+ }
36
+ result.push(value);
37
+ }
38
+ } while ((prototype = Reflect.getPrototypeOf(prototype)) &&
39
+ prototype !== Object.prototype);
40
+ return result;
13
41
  }
42
+ /**
43
+ * @deprecated Use {@link getAllMethodNames} instead.
44
+ */
14
45
  *getAllFilteredMethodNames(prototype) {
15
- const isMethod = (prop) => {
16
- const descriptor = Object.getOwnPropertyDescriptor(prototype, prop);
17
- if (descriptor.set || descriptor.get) {
18
- return false;
19
- }
20
- return !(0, shared_utils_1.isConstructor)(prop) && (0, shared_utils_1.isFunction)(prototype[prop]);
21
- };
46
+ yield* this.getAllMethodNames(prototype);
47
+ }
48
+ getAllMethodNames(prototype) {
49
+ if (!prototype) {
50
+ return [];
51
+ }
52
+ if (this.cachedScannedPrototypes.has(prototype)) {
53
+ return this.cachedScannedPrototypes.get(prototype);
54
+ }
55
+ const visitedNames = new Map();
56
+ const result = [];
57
+ this.cachedScannedPrototypes.set(prototype, result);
22
58
  do {
23
- yield* (0, iterare_1.iterate)(Object.getOwnPropertyNames(prototype))
24
- .filter(isMethod)
25
- .toArray();
59
+ for (const property of Object.getOwnPropertyNames(prototype)) {
60
+ if (visitedNames.has(property)) {
61
+ continue;
62
+ }
63
+ visitedNames.set(property, true);
64
+ // reason: https://github.com/nestjs/nest/pull/10821#issuecomment-1411916533
65
+ const descriptor = Object.getOwnPropertyDescriptor(prototype, property);
66
+ if (descriptor.set ||
67
+ descriptor.get ||
68
+ (0, shared_utils_1.isConstructor)(property) ||
69
+ !(0, shared_utils_1.isFunction)(prototype[property])) {
70
+ continue;
71
+ }
72
+ result.push(property);
73
+ }
26
74
  } while ((prototype = Reflect.getPrototypeOf(prototype)) &&
27
75
  prototype !== Object.prototype);
76
+ return result;
28
77
  }
29
78
  }
30
79
  exports.MetadataScanner = MetadataScanner;
@@ -1,11 +1,13 @@
1
1
  import { HttpServer, MiddlewareConsumer, Type } from '@nestjs/common/interfaces';
2
2
  import { MiddlewareConfigProxy, MiddlewareConfiguration } from '@nestjs/common/interfaces/middleware';
3
+ import { RouteInfoPathExtractor } from './route-info-path-extractor';
3
4
  import { RoutesMapper } from './routes-mapper';
4
5
  export declare class MiddlewareBuilder implements MiddlewareConsumer {
5
6
  private readonly routesMapper;
6
7
  private readonly httpAdapter;
8
+ private readonly routeInfoPathExtractor;
7
9
  private readonly middlewareCollection;
8
- constructor(routesMapper: RoutesMapper, httpAdapter: HttpServer);
10
+ constructor(routesMapper: RoutesMapper, httpAdapter: HttpServer, routeInfoPathExtractor: RouteInfoPathExtractor);
9
11
  apply(...middleware: Array<Type<any> | Function | any>): MiddlewareConfigProxy;
10
12
  build(): MiddlewareConfiguration[];
11
13
  getHttpAdapter(): HttpServer;
@@ -5,13 +5,14 @@ const dependencies_decorator_1 = require("@nestjs/common/decorators/core/depende
5
5
  const iterare_1 = require("iterare");
6
6
  const utils_1 = require("./utils");
7
7
  class MiddlewareBuilder {
8
- constructor(routesMapper, httpAdapter) {
8
+ constructor(routesMapper, httpAdapter, routeInfoPathExtractor) {
9
9
  this.routesMapper = routesMapper;
10
10
  this.httpAdapter = httpAdapter;
11
+ this.routeInfoPathExtractor = routeInfoPathExtractor;
11
12
  this.middlewareCollection = new Set();
12
13
  }
13
14
  apply(...middleware) {
14
- return new MiddlewareBuilder.ConfigProxy(this, (0, dependencies_decorator_1.flatten)(middleware));
15
+ return new MiddlewareBuilder.ConfigProxy(this, (0, dependencies_decorator_1.flatten)(middleware), this.routeInfoPathExtractor);
15
16
  }
16
17
  build() {
17
18
  return [...this.middlewareCollection];
@@ -22,16 +23,17 @@ class MiddlewareBuilder {
22
23
  }
23
24
  exports.MiddlewareBuilder = MiddlewareBuilder;
24
25
  MiddlewareBuilder.ConfigProxy = class {
25
- constructor(builder, middleware) {
26
+ constructor(builder, middleware, routeInfoPathExtractor) {
26
27
  this.builder = builder;
27
28
  this.middleware = middleware;
29
+ this.routeInfoPathExtractor = routeInfoPathExtractor;
28
30
  this.excludedRoutes = [];
29
31
  }
30
32
  getExcludedRoutes() {
31
33
  return this.excludedRoutes;
32
34
  }
33
35
  exclude(...routes) {
34
- this.excludedRoutes = this.getRoutesFlatList(routes);
36
+ this.excludedRoutes = this.getRoutesFlatList(routes).map(route => (Object.assign(Object.assign({}, route), { path: this.routeInfoPathExtractor.extractPathFrom(route) })));
35
37
  return this;
36
38
  }
37
39
  forRoutes(...routes) {
@@ -6,10 +6,8 @@ import { NestContainer } from '../injector/container';
6
6
  import { Injector } from '../injector/injector';
7
7
  import { Module } from '../injector/module';
8
8
  import { GraphInspector } from '../inspector/graph-inspector';
9
- import { RoutePathFactory } from '../router/route-path-factory';
10
9
  import { MiddlewareContainer } from './container';
11
10
  export declare class MiddlewareModule<TAppOptions extends NestApplicationContextOptions = NestApplicationContextOptions> {
12
- private readonly routePathFactory;
13
11
  private readonly routerProxy;
14
12
  private readonly exceptionFiltersCache;
15
13
  private readonly logger;
@@ -17,12 +15,11 @@ export declare class MiddlewareModule<TAppOptions extends NestApplicationContext
17
15
  private routerExceptionFilter;
18
16
  private routesMapper;
19
17
  private resolver;
20
- private config;
21
18
  private container;
22
19
  private httpAdapter;
23
20
  private graphInspector;
24
21
  private appOptions;
25
- constructor(routePathFactory: RoutePathFactory);
22
+ private routeInfoPathExtractor;
26
23
  register(middlewareContainer: MiddlewareContainer, container: NestContainer, config: ApplicationConfig, injector: Injector, httpAdapter: HttpServer, graphInspector: GraphInspector, options: TAppOptions): Promise<void>;
27
24
  resolveMiddleware(middlewareContainer: MiddlewareContainer, modules: Map<string, Module>): Promise<void>;
28
25
  loadConfiguration(middlewareContainer: MiddlewareContainer, moduleRef: Module, moduleKey: string): Promise<void>;
@@ -15,10 +15,10 @@ const router_proxy_1 = require("../router/router-proxy");
15
15
  const utils_1 = require("../router/utils");
16
16
  const builder_1 = require("./builder");
17
17
  const resolver_1 = require("./resolver");
18
+ const route_info_path_extractor_1 = require("./route-info-path-extractor");
18
19
  const routes_mapper_1 = require("./routes-mapper");
19
20
  class MiddlewareModule {
20
- constructor(routePathFactory) {
21
- this.routePathFactory = routePathFactory;
21
+ constructor() {
22
22
  this.routerProxy = new router_proxy_1.RouterProxy();
23
23
  this.exceptionFiltersCache = new WeakMap();
24
24
  this.logger = new common_1.Logger(MiddlewareModule.name);
@@ -29,7 +29,7 @@ class MiddlewareModule {
29
29
  this.routerExceptionFilter = new router_exception_filters_1.RouterExceptionFilters(container, config, appRef);
30
30
  this.routesMapper = new routes_mapper_1.RoutesMapper(container);
31
31
  this.resolver = new resolver_1.MiddlewareResolver(middlewareContainer, injector);
32
- this.config = config;
32
+ this.routeInfoPathExtractor = new route_info_path_extractor_1.RouteInfoPathExtractor(config);
33
33
  this.injector = injector;
34
34
  this.container = container;
35
35
  this.httpAdapter = httpAdapter;
@@ -50,7 +50,7 @@ class MiddlewareModule {
50
50
  if (!instance.configure) {
51
51
  return;
52
52
  }
53
- const middlewareBuilder = new builder_1.MiddlewareBuilder(this.routesMapper, this.httpAdapter);
53
+ const middlewareBuilder = new builder_1.MiddlewareBuilder(this.routesMapper, this.httpAdapter, this.routeInfoPathExtractor);
54
54
  try {
55
55
  await instance.configure(middlewareBuilder);
56
56
  }
@@ -153,29 +153,9 @@ class MiddlewareModule {
153
153
  const middleware = instance.use.bind(instance);
154
154
  return this.routerProxy.createProxy(middleware, exceptionsHandler);
155
155
  }
156
- async registerHandler(applicationRef, { path, method, version }, proxy) {
157
- const prefix = this.config.getGlobalPrefix();
158
- const excludedRoutes = this.config.getGlobalPrefixOptions().exclude;
159
- const isAWildcard = ['*', '/*', '(.*)', '/(.*)'].includes(path);
160
- if ((Array.isArray(excludedRoutes) &&
161
- (0, utils_1.isRouteExcluded)(excludedRoutes, path, method)) ||
162
- isAWildcard) {
163
- path = (0, shared_utils_1.addLeadingSlash)(path);
164
- }
165
- else {
166
- const basePath = (0, shared_utils_1.addLeadingSlash)(prefix);
167
- if ((basePath === null || basePath === void 0 ? void 0 : basePath.endsWith('/')) && (path === null || path === void 0 ? void 0 : path.startsWith('/'))) {
168
- // strip slash when a wildcard is being used
169
- // and global prefix has been set
170
- path = path === null || path === void 0 ? void 0 : path.slice(1);
171
- }
172
- path = basePath + path;
173
- }
174
- const applicationVersioningConfig = this.config.getVersioning();
175
- if (version && applicationVersioningConfig.type === common_1.VersioningType.URI) {
176
- const versionPrefix = this.routePathFactory.getVersionPrefix(applicationVersioningConfig);
177
- path = `/${versionPrefix}${version.toString()}${path}`;
178
- }
156
+ async registerHandler(applicationRef, routeInfo, proxy) {
157
+ const { method } = routeInfo;
158
+ const paths = this.routeInfoPathExtractor.extractPathsFrom(routeInfo);
179
159
  const isMethodAll = (0, utils_1.isRequestMethodAll)(method);
180
160
  const requestMethod = request_method_enum_1.RequestMethod[method];
181
161
  const router = await applicationRef.createMiddlewareFactory(method);
@@ -187,7 +167,7 @@ class MiddlewareModule {
187
167
  }
188
168
  return next();
189
169
  };
190
- router(path, middlewareFunction);
170
+ paths.forEach(path => router(path, middlewareFunction));
191
171
  }
192
172
  getContextId(request, isTreeDurable) {
193
173
  const contextId = context_id_factory_1.ContextIdFactory.getByRequest(request);
@@ -0,0 +1,15 @@
1
+ import { RouteInfo } from '@nestjs/common/interfaces';
2
+ import { ApplicationConfig } from '../application-config';
3
+ export declare class RouteInfoPathExtractor {
4
+ private readonly applicationConfig;
5
+ private routePathFactory;
6
+ private readonly prefixPath;
7
+ private readonly excludedGlobalPrefixRoutes;
8
+ private readonly versioningConfig?;
9
+ constructor(applicationConfig: ApplicationConfig);
10
+ extractPathsFrom({ path, method, version }: RouteInfo): string[];
11
+ extractPathFrom(route: RouteInfo): string;
12
+ private isAWildcard;
13
+ private extractNonWildcardPathFrom;
14
+ private extractVersionPathFrom;
15
+ }
@@ -0,0 +1,54 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.RouteInfoPathExtractor = void 0;
4
+ const common_1 = require("@nestjs/common");
5
+ const shared_utils_1 = require("@nestjs/common/utils/shared.utils");
6
+ const utils_1 = require("../router/utils");
7
+ const route_path_factory_1 = require("./../router/route-path-factory");
8
+ class RouteInfoPathExtractor {
9
+ constructor(applicationConfig) {
10
+ this.applicationConfig = applicationConfig;
11
+ this.routePathFactory = new route_path_factory_1.RoutePathFactory(applicationConfig);
12
+ this.prefixPath = (0, shared_utils_1.stripEndSlash)((0, shared_utils_1.addLeadingSlash)(this.applicationConfig.getGlobalPrefix()));
13
+ this.excludedGlobalPrefixRoutes =
14
+ this.applicationConfig.getGlobalPrefixOptions().exclude;
15
+ this.versioningConfig = this.applicationConfig.getVersioning();
16
+ }
17
+ extractPathsFrom({ path, method, version }) {
18
+ const versionPath = this.extractVersionPathFrom(version);
19
+ if (this.isAWildcard(path)) {
20
+ return Array.isArray(this.excludedGlobalPrefixRoutes)
21
+ ? [
22
+ this.prefixPath + versionPath + (0, shared_utils_1.addLeadingSlash)(path),
23
+ ...this.excludedGlobalPrefixRoutes.map(route => versionPath + (0, shared_utils_1.addLeadingSlash)(route.path)),
24
+ ]
25
+ : [this.prefixPath + versionPath + (0, shared_utils_1.addLeadingSlash)(path)];
26
+ }
27
+ return [this.extractNonWildcardPathFrom({ path, method, version })];
28
+ }
29
+ extractPathFrom(route) {
30
+ if (this.isAWildcard(route.path) && !route.version) {
31
+ return (0, shared_utils_1.addLeadingSlash)(route.path);
32
+ }
33
+ return this.extractNonWildcardPathFrom(route);
34
+ }
35
+ isAWildcard(path) {
36
+ return ['*', '/*', '/*/', '(.*)', '/(.*)'].includes(path);
37
+ }
38
+ extractNonWildcardPathFrom({ path, method, version, }) {
39
+ const versionPath = this.extractVersionPathFrom(version);
40
+ if (Array.isArray(this.excludedGlobalPrefixRoutes) &&
41
+ (0, utils_1.isRouteExcluded)(this.excludedGlobalPrefixRoutes, path, method)) {
42
+ return versionPath + (0, shared_utils_1.addLeadingSlash)(path);
43
+ }
44
+ return this.prefixPath + versionPath + (0, shared_utils_1.addLeadingSlash)(path);
45
+ }
46
+ extractVersionPathFrom(version) {
47
+ var _a;
48
+ if (!version || ((_a = this.versioningConfig) === null || _a === void 0 ? void 0 : _a.type) !== common_1.VersioningType.URI)
49
+ return '';
50
+ const versionPrefix = this.routePathFactory.getVersionPrefix(this.versioningConfig);
51
+ return (0, shared_utils_1.addLeadingSlash)(versionPrefix + version.toString());
52
+ }
53
+ }
54
+ exports.RouteInfoPathExtractor = RouteInfoPathExtractor;
@@ -1,8 +1,8 @@
1
1
  import { HttpServer, RouteInfo, Type } from '@nestjs/common/interfaces';
2
2
  import { ExcludeRouteMetadata } from '../router/interfaces/exclude-route-metadata.interface';
3
- export declare const mapToExcludeRoute: (routes: RouteInfo[]) => ExcludeRouteMetadata[];
3
+ export declare const mapToExcludeRoute: (routes: (string | RouteInfo)[]) => ExcludeRouteMetadata[];
4
4
  export declare const filterMiddleware: <T extends Function | Type<any> = any>(middleware: T[], routes: RouteInfo[], httpAdapter: HttpServer) => Type<any>[];
5
5
  export declare const mapToClass: <T extends Function | Type<any>>(middleware: T, excludedRoutes: ExcludeRouteMetadata[], httpAdapter: HttpServer) => Type<any>;
6
6
  export declare function isMiddlewareClass(middleware: any): middleware is Type<any>;
7
- export declare function assignToken(metatype: Type<any>, token?: any): Type<any>;
7
+ export declare function assignToken(metatype: Type<any>, token?: string): Type<any>;
8
8
  export declare function isMiddlewareRouteExcluded(req: Record<string, any>, excludedRoutes: ExcludeRouteMetadata[], httpAdapter: HttpServer): boolean;
@@ -5,14 +5,23 @@ const common_1 = require("@nestjs/common");
5
5
  const shared_utils_1 = require("@nestjs/common/utils/shared.utils");
6
6
  const iterare_1 = require("iterare");
7
7
  const pathToRegexp = require("path-to-regexp");
8
- const uuid_1 = require("uuid");
8
+ const uid_1 = require("uid");
9
9
  const utils_1 = require("../router/utils");
10
10
  const mapToExcludeRoute = (routes) => {
11
- return routes.map(({ path, method }) => ({
12
- pathRegex: pathToRegexp(path),
13
- requestMethod: method,
14
- path,
15
- }));
11
+ return routes.map(route => {
12
+ if ((0, shared_utils_1.isString)(route)) {
13
+ return {
14
+ path: route,
15
+ requestMethod: common_1.RequestMethod.ALL,
16
+ pathRegex: pathToRegexp((0, shared_utils_1.addLeadingSlash)(route)),
17
+ };
18
+ }
19
+ return {
20
+ path: route.path,
21
+ requestMethod: route.method,
22
+ pathRegex: pathToRegexp((0, shared_utils_1.addLeadingSlash)(route.path)),
23
+ };
24
+ });
16
25
  };
17
26
  exports.mapToExcludeRoute = mapToExcludeRoute;
18
27
  const filterMiddleware = (middleware, routes, httpAdapter) => {
@@ -67,7 +76,7 @@ function isMiddlewareClass(middleware) {
67
76
  (0, shared_utils_1.isFunction)((_b = middleware.prototype) === null || _b === void 0 ? void 0 : _b.use));
68
77
  }
69
78
  exports.isMiddlewareClass = isMiddlewareClass;
70
- function assignToken(metatype, token = (0, uuid_1.v4)()) {
79
+ function assignToken(metatype, token = (0, uid_1.uid)(21)) {
71
80
  Object.defineProperty(metatype, 'name', { value: token });
72
81
  return metatype;
73
82
  }
@@ -7,15 +7,14 @@ const load_package_util_1 = require("@nestjs/common/utils/load-package.util");
7
7
  const shared_utils_1 = require("@nestjs/common/utils/shared.utils");
8
8
  const iterare_1 = require("iterare");
9
9
  const os_1 = require("os");
10
- const pathToRegexp = require("path-to-regexp");
11
10
  const application_config_1 = require("./application-config");
12
11
  const constants_1 = require("./constants");
13
12
  const optional_require_1 = require("./helpers/optional-require");
14
13
  const injector_1 = require("./injector/injector");
15
14
  const container_1 = require("./middleware/container");
16
15
  const middleware_module_1 = require("./middleware/middleware-module");
16
+ const utils_1 = require("./middleware/utils");
17
17
  const nest_application_context_1 = require("./nest-application-context");
18
- const route_path_factory_1 = require("./router/route-path-factory");
19
18
  const routes_resolver_1 = require("./router/routes-resolver");
20
19
  const { SocketModule } = (0, optional_require_1.optionalRequire)('@nestjs/websockets/socket-module', () => require('@nestjs/websockets/socket-module'));
21
20
  const { MicroservicesModule } = (0, optional_require_1.optionalRequire)('@nestjs/microservices/microservices-module', () => require('@nestjs/microservices/microservices-module'));
@@ -39,7 +38,7 @@ class NestApplication extends nest_application_context_1.NestApplicationContext
39
38
  this.selectContextModule();
40
39
  this.registerHttpServer();
41
40
  this.injector = new injector_1.Injector({ preview: this.appOptions.preview });
42
- this.middlewareModule = new middleware_module_1.MiddlewareModule(new route_path_factory_1.RoutePathFactory(config));
41
+ this.middlewareModule = new middleware_module_1.MiddlewareModule();
43
42
  this.routesResolver = new routes_resolver_1.RoutesResolver(this.container, this.config, this.injector, this.graphInspector);
44
43
  }
45
44
  async dispose() {
@@ -234,20 +233,9 @@ class NestApplication extends nest_application_context_1.NestApplicationContext
234
233
  setGlobalPrefix(prefix, options) {
235
234
  this.config.setGlobalPrefix(prefix);
236
235
  if (options) {
237
- const exclude = options === null || options === void 0 ? void 0 : options.exclude.map((route) => {
238
- if ((0, shared_utils_1.isString)(route)) {
239
- return {
240
- requestMethod: common_1.RequestMethod.ALL,
241
- pathRegex: pathToRegexp((0, shared_utils_1.addLeadingSlash)(route)),
242
- path: route,
243
- };
244
- }
245
- return {
246
- requestMethod: route.method,
247
- pathRegex: pathToRegexp((0, shared_utils_1.addLeadingSlash)(route.path)),
248
- path: route.path,
249
- };
250
- });
236
+ const exclude = (options === null || options === void 0 ? void 0 : options.exclude)
237
+ ? (0, utils_1.mapToExcludeRoute)(options.exclude)
238
+ : [];
251
239
  this.config.setGlobalPrefixOptions(Object.assign(Object.assign({}, options), { exclude }));
252
240
  }
253
241
  return this;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nestjs/core",
3
- "version": "9.3.1",
3
+ "version": "9.3.3",
4
4
  "description": "Nest - modern, fast, powerful node.js web framework (@core)",
5
5
  "author": "Kamil Mysliwiec",
6
6
  "license": "MIT",
@@ -27,16 +27,15 @@
27
27
  }
28
28
  },
29
29
  "dependencies": {
30
+ "@node-rs/xxhash": "^1.3.0",
30
31
  "@nuxtjs/opencollective": "0.3.2",
31
32
  "fast-safe-stringify": "2.1.1",
32
33
  "iterare": "1.2.1",
33
- "object-hash": "3.0.0",
34
34
  "path-to-regexp": "3.2.0",
35
- "tslib": "2.4.1",
36
- "uuid": "9.0.0"
35
+ "tslib": "2.5.0"
37
36
  },
38
37
  "devDependencies": {
39
- "@nestjs/common": "9.3.1"
38
+ "@nestjs/common": "9.3.3"
40
39
  },
41
40
  "peerDependencies": {
42
41
  "@nestjs/common": "^9.0.0",
@@ -18,7 +18,7 @@ class MethodsReplFn extends repl_function_1.ReplFunction {
18
18
  const proto = typeof token !== 'function'
19
19
  ? Object.getPrototypeOf(this.ctx.app.get(token))
20
20
  : token === null || token === void 0 ? void 0 : token.prototype;
21
- const methods = new Set(this.metadataScanner.getAllFilteredMethodNames(proto));
21
+ const methods = this.metadataScanner.getAllMethodNames(proto);
22
22
  this.ctx.writeToStdout('\n');
23
23
  this.ctx.writeToStdout(`${cli_colors_util_1.clc.green('Methods')}:\n`);
24
24
  methods.forEach(methodName => this.ctx.writeToStdout(` ${cli_colors_util_1.clc.yellow('◻')} ${methodName}\n`));
@@ -1,5 +1,8 @@
1
1
  import { RequestMethod } from '@nestjs/common';
2
2
  export interface ExcludeRouteMetadata {
3
+ /**
4
+ * Route path.
5
+ */
3
6
  path: string;
4
7
  /**
5
8
  * Regular expression representing the route path.
@@ -14,5 +14,5 @@ export declare class PathsExplorer {
14
14
  private readonly metadataScanner;
15
15
  constructor(metadataScanner: MetadataScanner);
16
16
  scanForPaths(instance: Controller, prototype?: object): RouteDefinition[];
17
- exploreMethodMetadata(instance: Controller, prototype: object, methodName: string): RouteDefinition;
17
+ exploreMethodMetadata(instance: Controller, prototype: object, methodName: string): RouteDefinition | null;
18
18
  }
@@ -11,7 +11,15 @@ class PathsExplorer {
11
11
  const instancePrototype = (0, shared_utils_1.isUndefined)(prototype)
12
12
  ? Object.getPrototypeOf(instance)
13
13
  : prototype;
14
- return this.metadataScanner.scanFromPrototype(instance, instancePrototype, method => this.exploreMethodMetadata(instance, instancePrototype, method));
14
+ return this.metadataScanner
15
+ .getAllMethodNames(instancePrototype)
16
+ .reduce((acc, method) => {
17
+ const route = this.exploreMethodMetadata(instance, instancePrototype, method);
18
+ if (route) {
19
+ acc.push(route);
20
+ }
21
+ return acc;
22
+ }, []);
15
23
  }
16
24
  exploreMethodMetadata(instance, prototype, methodName) {
17
25
  const instanceCallback = instance[methodName];
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.isRouteExcluded = exports.isRequestMethodAll = void 0;
4
4
  const common_1 = require("@nestjs/common");
5
+ const shared_utils_1 = require("@nestjs/common/utils/shared.utils");
5
6
  const isRequestMethodAll = (method) => {
6
7
  return common_1.RequestMethod.ALL === method || method === -1;
7
8
  };
@@ -10,7 +11,7 @@ function isRouteExcluded(excludedRoutes, path, requestMethod) {
10
11
  return excludedRoutes.some(route => {
11
12
  if ((0, exports.isRequestMethodAll)(route.requestMethod) ||
12
13
  route.requestMethod === requestMethod) {
13
- return route.pathRegex.exec(path);
14
+ return route.pathRegex.exec((0, shared_utils_1.addLeadingSlash)(path));
14
15
  }
15
16
  return false;
16
17
  });
package/scanner.d.ts CHANGED
@@ -28,7 +28,7 @@ export declare class DependenciesScanner {
28
28
  reflectKeyMetadata(component: Type<Injectable>, key: string, methodKey: string): {
29
29
  methodKey: string;
30
30
  metadata: any;
31
- };
31
+ } | undefined;
32
32
  calculateModulesDistance(): void;
33
33
  insertImport(related: any, token: string, context: string): Promise<void>;
34
34
  isCustomProvider(provider: Provider): provider is ClassProvider | ValueProvider | FactoryProvider | ExistingProvider;
package/scanner.js CHANGED
@@ -133,19 +133,27 @@ class DependenciesScanner {
133
133
  }
134
134
  reflectInjectables(component, token, metadataKey) {
135
135
  const controllerInjectables = this.reflectMetadata(metadataKey, component);
136
- const methodInjectables = this.metadataScanner.scanFromPrototype(null, component.prototype, this.reflectKeyMetadata.bind(this, component, metadataKey));
136
+ const methodInjectables = this.metadataScanner
137
+ .getAllMethodNames(component.prototype)
138
+ .reduce((acc, method) => {
139
+ const methodInjectable = this.reflectKeyMetadata(component, metadataKey, method);
140
+ if (methodInjectable) {
141
+ acc.push(methodInjectable);
142
+ }
143
+ return acc;
144
+ }, []);
137
145
  controllerInjectables.forEach(injectable => this.insertInjectable(injectable, token, component, constants_1.ENHANCER_KEY_TO_SUBTYPE_MAP[metadataKey]));
138
- methodInjectables.forEach(({ methodKey, metadata }) => metadata.forEach(injectable => this.insertInjectable(injectable, token, component, constants_1.ENHANCER_KEY_TO_SUBTYPE_MAP[metadataKey], methodKey)));
146
+ methodInjectables.forEach(methodInjectable => {
147
+ methodInjectable.metadata.forEach(injectable => this.insertInjectable(injectable, token, component, constants_1.ENHANCER_KEY_TO_SUBTYPE_MAP[metadataKey], methodInjectable.methodKey));
148
+ });
139
149
  }
140
150
  reflectParamInjectables(component, token, metadataKey) {
141
- const paramsMetadata = this.metadataScanner.scanFromPrototype(null, component.prototype, methodKey => {
151
+ const paramsMethods = this.metadataScanner.getAllMethodNames(component.prototype);
152
+ paramsMethods.forEach(methodKey => {
142
153
  const metadata = Reflect.getMetadata(metadataKey, component, methodKey);
143
154
  if (!metadata) {
144
155
  return;
145
156
  }
146
- return { methodKey, metadata };
147
- });
148
- paramsMetadata.forEach(({ methodKey, metadata }) => {
149
157
  const params = Object.values(metadata);
150
158
  params
151
159
  .map(item => item.pipes)