@nestjs/core 12.0.0-alpha.3 → 12.0.0-alpha.5

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 (38) hide show
  1. package/Readme.md +1 -0
  2. package/application-config.d.ts +8 -2
  3. package/application-config.js +14 -0
  4. package/errors/exceptions/index.d.ts +1 -0
  5. package/errors/exceptions/index.js +1 -0
  6. package/errors/exceptions/invalid-class-module.exception.d.ts +1 -1
  7. package/errors/exceptions/invalid-class-module.exception.js +2 -2
  8. package/errors/exceptions/invalid-module.exception.d.ts +1 -1
  9. package/errors/exceptions/invalid-module.exception.js +2 -2
  10. package/errors/exceptions/route-conflict.exception.d.ts +4 -0
  11. package/errors/exceptions/route-conflict.exception.js +7 -0
  12. package/errors/messages.d.ts +5 -2
  13. package/errors/messages.js +37 -4
  14. package/injector/injector.d.ts +4 -3
  15. package/injector/injector.js +28 -3
  16. package/injector/instance-wrapper.d.ts +2 -0
  17. package/injector/instance-wrapper.js +25 -0
  18. package/nest-application.d.ts +1 -0
  19. package/nest-application.js +77 -1
  20. package/package.json +3 -3
  21. package/router/interfaces/index.d.ts +3 -0
  22. package/router/interfaces/index.js +3 -0
  23. package/router/interfaces/resolved-route.interface.d.ts +32 -0
  24. package/router/interfaces/resolved-route.interface.js +1 -0
  25. package/router/interfaces/resolver.interface.d.ts +5 -1
  26. package/router/interfaces/route-conflict.interface.d.ts +14 -0
  27. package/router/interfaces/route-conflict.interface.js +1 -0
  28. package/router/interfaces/route-resolution-options.interface.d.ts +24 -0
  29. package/router/interfaces/route-resolution-options.interface.js +1 -0
  30. package/router/route-conflict-detector.d.ts +71 -0
  31. package/router/route-conflict-detector.js +276 -0
  32. package/router/route-specificity-sorter.d.ts +23 -0
  33. package/router/route-specificity-sorter.js +59 -0
  34. package/router/router-explorer.d.ts +11 -2
  35. package/router/router-explorer.js +61 -19
  36. package/router/routes-resolver.d.ts +7 -4
  37. package/router/routes-resolver.js +9 -7
  38. package/scanner.js +9 -5
@@ -0,0 +1,71 @@
1
+ import { Logger, type RouteConflictPolicy, type VersioningOptions } from '@nestjs/common';
2
+ import { ResolvedRoute } from './interfaces/resolved-route.interface.js';
3
+ import { RouteConflict } from './interfaces/route-conflict.interface.js';
4
+ type SegmentKind = 'literal' | 'param' | 'wildcard';
5
+ interface PathSegment {
6
+ kind: SegmentKind;
7
+ value: string;
8
+ }
9
+ /**
10
+ * Static utility class that detects overlapping HTTP routes and reports
11
+ * them according to a per-kind policy. Stateless — every method takes
12
+ * everything it needs as parameters.
13
+ */
14
+ export declare class RouteConflictDetector {
15
+ /**
16
+ * Strips the leading `:` / `*` marker (if present) and tags each
17
+ * segment as a literal, named param, or named wildcard. Supports both
18
+ * bare named wildcards (`*path`) and adapter-normalized path-to-regexp
19
+ * wildcard groups (`{*path}`).
20
+ */
21
+ static tokenizePath(rawPath: string): PathSegment[];
22
+ /**
23
+ * Decides whether two paths can match the same incoming request, given
24
+ * only their declared patterns (no host/method/version considered).
25
+ */
26
+ static pathsCanOverlap(leftPath: string, rightPath: string): boolean;
27
+ /**
28
+ * Walks every unique pair of resolved routes and produces a conflict
29
+ * record for each pair whose (method, host, version, path) tuples can
30
+ * collide at runtime.
31
+ */
32
+ static detect(routes: ResolvedRoute[], versioningOptions: VersioningOptions | undefined): RouteConflict[];
33
+ /**
34
+ * Applies the per-kind policy to a set of conflicts: silences `'off'`,
35
+ * logs `'warn'` once per conflict, and aggregates every `'error'`-level
36
+ * conflict into a single `RouteConflictException`.
37
+ */
38
+ static handle(conflicts: RouteConflict[], policy: RouteConflictPolicy | undefined, logger: Logger): void;
39
+ /**
40
+ * Removes shadow conflicts that specificity sorting has already resolved.
41
+ *
42
+ * When `routeResolutionStrategy: 'specificity'` is active, the sort
43
+ * promotes more-specific routes ahead of less-specific ones. A shadow
44
+ * where the sort promoted the winner (it was declared *later* but sorted
45
+ * *first*) is handled correctly at runtime — the more-specific route is
46
+ * registered first and handles its requests while the less-specific route
47
+ * handles the rest. Retaining such a conflict would cause `shadow: 'error'`
48
+ * to abort an application whose routes actually work as intended.
49
+ *
50
+ * Shadows where the winner was already first in declaration order (the
51
+ * sort did not swap them) are genuine and are kept unchanged. Duplicate
52
+ * conflicts are always kept.
53
+ *
54
+ * @param conflicts Conflicts detected on the sorted route list.
55
+ * @param declarationOrder Routes in their original declaration order
56
+ * (i.e. before specificity sorting was applied).
57
+ */
58
+ static filterSortResolvedShadows(conflicts: RouteConflict[], declarationOrder: ResolvedRoute[]): RouteConflict[];
59
+ private static segmentsCanOverlap;
60
+ private static methodsCanOverlap;
61
+ private static versionsCanOverlap;
62
+ private static hostsCanOverlap;
63
+ private static hostValuesCanMatchSameRequest;
64
+ private static routesAreIdentical;
65
+ private static hostsAreIdentical;
66
+ private static hostValuesAreIdentical;
67
+ private static versionsAreIdentical;
68
+ private static forEachUniquePair;
69
+ private static describeConflict;
70
+ }
71
+ export {};
@@ -0,0 +1,276 @@
1
+ import { RequestMethod, VERSION_NEUTRAL, VersioningType, } from '@nestjs/common';
2
+ import { RouteConflictException } from '../errors/exceptions/route-conflict.exception.js';
3
+ import { DUPLICATE_ROUTE_MESSAGE, SHADOWED_ROUTE_MESSAGE, } from '../errors/messages.js';
4
+ /**
5
+ * Static utility class that detects overlapping HTTP routes and reports
6
+ * them according to a per-kind policy. Stateless — every method takes
7
+ * everything it needs as parameters.
8
+ */
9
+ export class RouteConflictDetector {
10
+ /**
11
+ * Strips the leading `:` / `*` marker (if present) and tags each
12
+ * segment as a literal, named param, or named wildcard. Supports both
13
+ * bare named wildcards (`*path`) and adapter-normalized path-to-regexp
14
+ * wildcard groups (`{*path}`).
15
+ */
16
+ static tokenizePath(rawPath) {
17
+ const segments = [];
18
+ rawPath
19
+ .split('/')
20
+ .filter(rawSegment => rawSegment.length > 0)
21
+ .forEach(rawSegment => {
22
+ if (rawSegment.startsWith('*')) {
23
+ segments.push({ kind: 'wildcard', value: rawSegment.slice(1) });
24
+ return;
25
+ }
26
+ if (rawSegment.startsWith('{*') && rawSegment.endsWith('}')) {
27
+ segments.push({
28
+ kind: 'wildcard',
29
+ value: rawSegment.slice(2, -1),
30
+ });
31
+ return;
32
+ }
33
+ if (rawSegment.startsWith(':')) {
34
+ segments.push({ kind: 'param', value: rawSegment.slice(1) });
35
+ return;
36
+ }
37
+ segments.push({ kind: 'literal', value: rawSegment });
38
+ });
39
+ return segments;
40
+ }
41
+ /**
42
+ * Decides whether two paths can match the same incoming request, given
43
+ * only their declared patterns (no host/method/version considered).
44
+ */
45
+ static pathsCanOverlap(leftPath, rightPath) {
46
+ const leftSegments = RouteConflictDetector.tokenizePath(leftPath);
47
+ const rightSegments = RouteConflictDetector.tokenizePath(rightPath);
48
+ const leftEndsInWildcard = leftSegments[leftSegments.length - 1]?.kind === 'wildcard';
49
+ const rightEndsInWildcard = rightSegments[rightSegments.length - 1]?.kind === 'wildcard';
50
+ // A named wildcard like `*path` requires at least one matched segment,
51
+ // so only the *shorter* side's trailing wildcard can absorb the
52
+ // difference. If the longer side has the wildcard, the other side
53
+ // simply does not have enough segments to ever reach that position.
54
+ if (leftSegments.length !== rightSegments.length) {
55
+ const shorterEndsInWildcard = leftSegments.length < rightSegments.length
56
+ ? leftEndsInWildcard
57
+ : rightEndsInWildcard;
58
+ if (!shorterEndsInWildcard) {
59
+ return false;
60
+ }
61
+ }
62
+ const sharedLength = Math.min(leftSegments.length, rightSegments.length);
63
+ let canOverlap = true;
64
+ leftSegments.slice(0, sharedLength).forEach((leftSegment, segmentIndex) => {
65
+ if (!canOverlap)
66
+ return;
67
+ if (!RouteConflictDetector.segmentsCanOverlap(leftSegment, rightSegments[segmentIndex])) {
68
+ canOverlap = false;
69
+ }
70
+ });
71
+ return canOverlap;
72
+ }
73
+ /**
74
+ * Walks every unique pair of resolved routes and produces a conflict
75
+ * record for each pair whose (method, host, version, path) tuples can
76
+ * collide at runtime.
77
+ */
78
+ static detect(routes, versioningOptions) {
79
+ const conflicts = [];
80
+ RouteConflictDetector.forEachUniquePair(routes, (earlierRoute, laterRoute) => {
81
+ if (!RouteConflictDetector.methodsCanOverlap(earlierRoute.method, laterRoute.method)) {
82
+ return;
83
+ }
84
+ if (!RouteConflictDetector.versionsCanOverlap(earlierRoute.version, laterRoute.version, versioningOptions)) {
85
+ return;
86
+ }
87
+ if (!RouteConflictDetector.hostsCanOverlap(earlierRoute.host, laterRoute.host)) {
88
+ return;
89
+ }
90
+ if (!RouteConflictDetector.pathsCanOverlap(earlierRoute.path, laterRoute.path)) {
91
+ return;
92
+ }
93
+ const isIdentical = RouteConflictDetector.routesAreIdentical(earlierRoute, laterRoute, versioningOptions);
94
+ conflicts.push({
95
+ winner: earlierRoute,
96
+ shadowed: laterRoute,
97
+ kind: isIdentical ? 'duplicate' : 'shadow',
98
+ });
99
+ });
100
+ return conflicts;
101
+ }
102
+ /**
103
+ * Applies the per-kind policy to a set of conflicts: silences `'off'`,
104
+ * logs `'warn'` once per conflict, and aggregates every `'error'`-level
105
+ * conflict into a single `RouteConflictException`.
106
+ */
107
+ static handle(conflicts, policy, logger) {
108
+ if (conflicts.length === 0 || policy === undefined)
109
+ return;
110
+ const errorMessages = [];
111
+ conflicts.forEach(conflict => {
112
+ const policyForKind = policy[conflict.kind] ?? 'off';
113
+ if (policyForKind === 'off')
114
+ return;
115
+ const message = RouteConflictDetector.describeConflict(conflict);
116
+ if (policyForKind === 'warn') {
117
+ logger.warn(message);
118
+ return;
119
+ }
120
+ errorMessages.push(message);
121
+ });
122
+ if (errorMessages.length > 0) {
123
+ throw new RouteConflictException(errorMessages);
124
+ }
125
+ }
126
+ /**
127
+ * Removes shadow conflicts that specificity sorting has already resolved.
128
+ *
129
+ * When `routeResolutionStrategy: 'specificity'` is active, the sort
130
+ * promotes more-specific routes ahead of less-specific ones. A shadow
131
+ * where the sort promoted the winner (it was declared *later* but sorted
132
+ * *first*) is handled correctly at runtime — the more-specific route is
133
+ * registered first and handles its requests while the less-specific route
134
+ * handles the rest. Retaining such a conflict would cause `shadow: 'error'`
135
+ * to abort an application whose routes actually work as intended.
136
+ *
137
+ * Shadows where the winner was already first in declaration order (the
138
+ * sort did not swap them) are genuine and are kept unchanged. Duplicate
139
+ * conflicts are always kept.
140
+ *
141
+ * @param conflicts Conflicts detected on the sorted route list.
142
+ * @param declarationOrder Routes in their original declaration order
143
+ * (i.e. before specificity sorting was applied).
144
+ */
145
+ static filterSortResolvedShadows(conflicts, declarationOrder) {
146
+ const declarationIndex = new Map(declarationOrder.map((route, idx) => [route, idx]));
147
+ return conflicts.filter(conflict => {
148
+ if (conflict.kind !== 'shadow')
149
+ return true;
150
+ const winnerDeclIdx = declarationIndex.get(conflict.winner) ?? -1;
151
+ const shadowedDeclIdx = declarationIndex.get(conflict.shadowed) ?? -1;
152
+ // The sort promoted the winner (declared later, but sorted to the
153
+ // front because it is more specific). The shadow is resolved at
154
+ // runtime — drop it. Keep only genuine shadows where the winner was
155
+ // already first in declaration order.
156
+ return winnerDeclIdx < shadowedDeclIdx;
157
+ });
158
+ }
159
+ static segmentsCanOverlap(leftSegment, rightSegment) {
160
+ if (leftSegment.kind === 'wildcard' || rightSegment.kind === 'wildcard') {
161
+ return true;
162
+ }
163
+ if (leftSegment.kind === 'param' || rightSegment.kind === 'param') {
164
+ return true;
165
+ }
166
+ return leftSegment.value === rightSegment.value;
167
+ }
168
+ static methodsCanOverlap(leftMethod, rightMethod) {
169
+ if (leftMethod === RequestMethod.ALL || rightMethod === RequestMethod.ALL) {
170
+ return true;
171
+ }
172
+ return leftMethod === rightMethod;
173
+ }
174
+ static versionsCanOverlap(leftVersion, rightVersion, versioningOptions) {
175
+ if (!versioningOptions)
176
+ return true;
177
+ if (versioningOptions.type === VersioningType.URI)
178
+ return true;
179
+ const leftMatchesAnyVersion = leftVersion === undefined || leftVersion === VERSION_NEUTRAL;
180
+ const rightMatchesAnyVersion = rightVersion === undefined || rightVersion === VERSION_NEUTRAL;
181
+ if (leftMatchesAnyVersion || rightMatchesAnyVersion)
182
+ return true;
183
+ const leftValues = Array.isArray(leftVersion) ? leftVersion : [leftVersion];
184
+ const rightValues = Array.isArray(rightVersion)
185
+ ? rightVersion
186
+ : [rightVersion];
187
+ return leftValues.some(versionValue => rightValues.includes(versionValue));
188
+ }
189
+ static hostsCanOverlap(leftHost, rightHost) {
190
+ if (leftHost === undefined || rightHost === undefined)
191
+ return true;
192
+ const leftHosts = Array.isArray(leftHost) ? leftHost : [leftHost];
193
+ const rightHosts = Array.isArray(rightHost) ? rightHost : [rightHost];
194
+ return leftHosts.some(leftValue => rightHosts.some(rightValue => RouteConflictDetector.hostValuesCanMatchSameRequest(leftValue, rightValue)));
195
+ }
196
+ static hostValuesCanMatchSameRequest(leftValue, rightValue) {
197
+ const leftIsRegExp = leftValue instanceof RegExp;
198
+ const rightIsRegExp = rightValue instanceof RegExp;
199
+ if (leftIsRegExp && rightIsRegExp)
200
+ return true;
201
+ // Reset lastIndex before calling test() to guard against RegExps with the
202
+ // `g` or `y` flags: those are stateful and would produce inconsistent
203
+ // results (false negatives) when the same instance is reused across the
204
+ // multiple pair comparisons that a single detect() run performs.
205
+ if (leftIsRegExp) {
206
+ leftValue.lastIndex = 0;
207
+ return leftValue.test(rightValue);
208
+ }
209
+ if (rightIsRegExp) {
210
+ rightValue.lastIndex = 0;
211
+ return rightValue.test(leftValue);
212
+ }
213
+ return leftValue === rightValue;
214
+ }
215
+ static routesAreIdentical(leftRoute, rightRoute, versioningOptions) {
216
+ return (leftRoute.method === rightRoute.method &&
217
+ leftRoute.path === rightRoute.path &&
218
+ RouteConflictDetector.hostsAreIdentical(leftRoute.host, rightRoute.host) &&
219
+ RouteConflictDetector.versionsAreIdentical(leftRoute.version, rightRoute.version, versioningOptions));
220
+ }
221
+ static hostsAreIdentical(leftHost, rightHost) {
222
+ if (leftHost === undefined && rightHost === undefined)
223
+ return true;
224
+ if (leftHost === undefined || rightHost === undefined)
225
+ return false;
226
+ const leftHosts = Array.isArray(leftHost) ? leftHost : [leftHost];
227
+ const rightHosts = Array.isArray(rightHost) ? rightHost : [rightHost];
228
+ if (leftHosts.length !== rightHosts.length)
229
+ return false;
230
+ // Order-insensitive set comparison: ['a', 'b'] and ['b', 'a']
231
+ // describe the same allowed-host set, so they are identical for
232
+ // duplicate-classification purposes.
233
+ return leftHosts.every(leftValue => rightHosts.some(rightValue => RouteConflictDetector.hostValuesAreIdentical(leftValue, rightValue)));
234
+ }
235
+ static hostValuesAreIdentical(leftValue, rightValue) {
236
+ if (leftValue instanceof RegExp && rightValue instanceof RegExp) {
237
+ return (leftValue.source === rightValue.source &&
238
+ leftValue.flags === rightValue.flags);
239
+ }
240
+ return leftValue === rightValue;
241
+ }
242
+ static versionsAreIdentical(leftVersion, rightVersion, versioningOptions) {
243
+ // When versioning is not configured (or URI-based, where the
244
+ // version is encoded in the path), version metadata does not
245
+ // gate request matching at runtime, so two routes that differ
246
+ // only in their declared `version` are runtime duplicates.
247
+ if (!versioningOptions || versioningOptions.type === VersioningType.URI) {
248
+ return true;
249
+ }
250
+ if (leftVersion === rightVersion)
251
+ return true;
252
+ const leftValues = Array.isArray(leftVersion) ? leftVersion : [leftVersion];
253
+ const rightValues = Array.isArray(rightVersion)
254
+ ? rightVersion
255
+ : [rightVersion];
256
+ if (leftValues.length !== rightValues.length)
257
+ return false;
258
+ return leftValues.every(value => rightValues.includes(value));
259
+ }
260
+ static forEachUniquePair(items, visit) {
261
+ items.forEach((leftItem, leftIndex) => {
262
+ items.slice(leftIndex + 1).forEach(rightItem => {
263
+ visit(leftItem, rightItem);
264
+ });
265
+ });
266
+ }
267
+ static describeConflict(conflict) {
268
+ const method = RequestMethod[conflict.winner.method];
269
+ const winnerLabel = `${conflict.winner.instanceWrapper.name}#${conflict.winner.methodName}`;
270
+ const shadowedLabel = `${conflict.shadowed.instanceWrapper.name}#${conflict.shadowed.methodName}`;
271
+ if (conflict.kind === 'duplicate') {
272
+ return DUPLICATE_ROUTE_MESSAGE(method, conflict.winner.path, winnerLabel, shadowedLabel);
273
+ }
274
+ return SHADOWED_ROUTE_MESSAGE(method, conflict.shadowed.path, shadowedLabel, conflict.winner.path, winnerLabel);
275
+ }
276
+ }
@@ -0,0 +1,23 @@
1
+ import { ResolvedRoute } from './interfaces/resolved-route.interface.js';
2
+ /**
3
+ * Static utility class that orders resolved routes by specificity so the
4
+ * underlying HTTP adapter registers more specific patterns first.
5
+ * Stateless — every method takes everything it needs as parameters.
6
+ */
7
+ export declare class RouteSpecificitySorter {
8
+ /**
9
+ * Lower rank means more specific. A literal segment beats a named
10
+ * param, which beats a named wildcard. A position that is absent on
11
+ * one side is the least specific of all (it means the path is shorter
12
+ * at that point).
13
+ */
14
+ private static readonly SEGMENT_KIND_RANK;
15
+ /**
16
+ * Returns a new array of routes sorted from most-specific to
17
+ * least-specific. Routes that tie on specificity keep their original
18
+ * declaration order.
19
+ */
20
+ static sort(routes: ResolvedRoute[]): ResolvedRoute[];
21
+ private static comparePathSpecificity;
22
+ private static rankSegmentByKind;
23
+ }
@@ -0,0 +1,59 @@
1
+ import { RouteConflictDetector } from './route-conflict-detector.js';
2
+ /**
3
+ * Static utility class that orders resolved routes by specificity so the
4
+ * underlying HTTP adapter registers more specific patterns first.
5
+ * Stateless — every method takes everything it needs as parameters.
6
+ */
7
+ export class RouteSpecificitySorter {
8
+ /**
9
+ * Lower rank means more specific. A literal segment beats a named
10
+ * param, which beats a named wildcard. A position that is absent on
11
+ * one side is the least specific of all (it means the path is shorter
12
+ * at that point).
13
+ */
14
+ static SEGMENT_KIND_RANK = {
15
+ literal: 0,
16
+ param: 1,
17
+ wildcard: 2,
18
+ missing: 3,
19
+ };
20
+ /**
21
+ * Returns a new array of routes sorted from most-specific to
22
+ * least-specific. Routes that tie on specificity keep their original
23
+ * declaration order.
24
+ */
25
+ static sort(routes) {
26
+ const decoratedRoutes = routes.map((route, declarationIndex) => ({
27
+ route,
28
+ declarationIndex,
29
+ }));
30
+ decoratedRoutes.sort((leftEntry, rightEntry) => {
31
+ const specificityDelta = RouteSpecificitySorter.comparePathSpecificity(leftEntry.route.path, rightEntry.route.path);
32
+ if (specificityDelta !== 0)
33
+ return specificityDelta;
34
+ return leftEntry.declarationIndex - rightEntry.declarationIndex;
35
+ });
36
+ return decoratedRoutes.map(decoratedEntry => decoratedEntry.route);
37
+ }
38
+ static comparePathSpecificity(leftPath, rightPath) {
39
+ const leftSegments = RouteConflictDetector.tokenizePath(leftPath);
40
+ const rightSegments = RouteConflictDetector.tokenizePath(rightPath);
41
+ const longestPathLength = Math.max(leftSegments.length, rightSegments.length);
42
+ let specificityDelta = 0;
43
+ Array.from({ length: longestPathLength }).forEach((_, segmentIndex) => {
44
+ if (specificityDelta !== 0)
45
+ return;
46
+ const leftKind = leftSegments[segmentIndex]?.kind ?? 'missing';
47
+ const rightKind = rightSegments[segmentIndex]?.kind ?? 'missing';
48
+ const leftRank = RouteSpecificitySorter.rankSegmentByKind(leftKind);
49
+ const rightRank = RouteSpecificitySorter.rankSegmentByKind(rightKind);
50
+ if (leftRank !== rightRank) {
51
+ specificityDelta = leftRank - rightRank;
52
+ }
53
+ });
54
+ return specificityDelta;
55
+ }
56
+ static rankSegmentByKind(kind) {
57
+ return RouteSpecificitySorter.SEGMENT_KIND_RANK[kind];
58
+ }
59
+ }
@@ -7,7 +7,9 @@ import { Module } from '../injector/module.js';
7
7
  import { GraphInspector } from '../inspector/graph-inspector.js';
8
8
  import { MetadataScanner } from '../metadata-scanner.js';
9
9
  import { ExceptionsFilter } from './interfaces/exceptions-filter.interface.js';
10
+ import { ResolvedRoute } from './interfaces/resolved-route.interface.js';
10
11
  import { RoutePathMetadata } from './interfaces/route-path-metadata.interface.js';
12
+ import { RouteResolutionOptions } from './interfaces/route-resolution-options.interface.js';
11
13
  import { RoutePathFactory } from './route-path-factory.js';
12
14
  import { RouterProxy, RouterProxyCallback } from './router-proxy.js';
13
15
  import { type Controller, type VersionValue } from '@nestjs/common/internal';
@@ -32,10 +34,17 @@ export declare class RouterExplorer {
32
34
  private readonly logger;
33
35
  private readonly exceptionFiltersCache;
34
36
  constructor(metadataScanner: MetadataScanner, container: NestContainer, injector: Injector, routerProxy: RouterProxy, exceptionsFilter: ExceptionsFilter, config: ApplicationConfig, routePathFactory: RoutePathFactory, graphInspector: GraphInspector);
35
- explore<T extends HttpServer = any>(instanceWrapper: InstanceWrapper, moduleKey: string, httpAdapterRef: T, host: string | RegExp | Array<string | RegExp>, routePathMetadata: RoutePathMetadata): void;
37
+ explore<T extends HttpServer = any>(instanceWrapper: InstanceWrapper, moduleKey: string, httpAdapterRef: T, host: string | RegExp | Array<string | RegExp>, routePathMetadata: RoutePathMetadata, options?: RouteResolutionOptions): void;
36
38
  extractRouterPath(metatype: Type<Controller>): string[];
37
- applyPathsToRouterProxy<T extends HttpServer>(router: T, routeDefinitions: RouteDefinition[], instanceWrapper: InstanceWrapper, moduleKey: string, routePathMetadata: RoutePathMetadata, host: string | RegExp | Array<string | RegExp>): void;
39
+ applyPathsToRouterProxy<T extends HttpServer>(router: T, routeDefinitions: RouteDefinition[], instanceWrapper: InstanceWrapper, moduleKey: string, routePathMetadata: RoutePathMetadata, host: string | RegExp | Array<string | RegExp>, options?: RouteResolutionOptions): void;
38
40
  private applyCallbackToRouter;
41
+ /**
42
+ * Registers a previously resolved route on the underlying HTTP adapter.
43
+ * Used when route registration has been deferred (e.g. when sorting
44
+ * routes by specificity) so the caller can choose the order in which
45
+ * routes are installed on the adapter.
46
+ */
47
+ registerResolvedRoute<T extends HttpServer>(router: T, route: ResolvedRoute): void;
39
48
  private applyHostFilter;
40
49
  private applyVersionFilter;
41
50
  private createCallbackProxy;
@@ -45,10 +45,10 @@ export class RouterExplorer {
45
45
  const interceptorsConsumer = new InterceptorsConsumer();
46
46
  this.executionContextCreator = new RouterExecutionContext(routeParamsFactory, pipesContextCreator, pipesConsumer, guardsContextCreator, guardsConsumer, interceptorsContextCreator, interceptorsConsumer, container.getHttpAdapterRef());
47
47
  }
48
- explore(instanceWrapper, moduleKey, httpAdapterRef, host, routePathMetadata) {
48
+ explore(instanceWrapper, moduleKey, httpAdapterRef, host, routePathMetadata, options = {}) {
49
49
  const { instance } = instanceWrapper;
50
50
  const routerPaths = this.pathsExplorer.scanForPaths(instance);
51
- this.applyPathsToRouterProxy(httpAdapterRef, routerPaths, instanceWrapper, moduleKey, routePathMetadata, host);
51
+ this.applyPathsToRouterProxy(httpAdapterRef, routerPaths, instanceWrapper, moduleKey, routePathMetadata, host, options);
52
52
  }
53
53
  extractRouterPath(metatype) {
54
54
  const path = Reflect.getMetadata(PATH_METADATA, metatype);
@@ -60,14 +60,15 @@ export class RouterExplorer {
60
60
  }
61
61
  return [addLeadingSlash(path)];
62
62
  }
63
- applyPathsToRouterProxy(router, routeDefinitions, instanceWrapper, moduleKey, routePathMetadata, host) {
63
+ applyPathsToRouterProxy(router, routeDefinitions, instanceWrapper, moduleKey, routePathMetadata, host, options = {}) {
64
64
  (routeDefinitions || []).forEach(routeDefinition => {
65
65
  const { version: methodVersion } = routeDefinition;
66
66
  routePathMetadata.methodVersion = methodVersion;
67
- this.applyCallbackToRouter(router, routeDefinition, instanceWrapper, moduleKey, routePathMetadata, host);
67
+ this.applyCallbackToRouter(router, routeDefinition, instanceWrapper, moduleKey, routePathMetadata, host, options);
68
68
  });
69
69
  }
70
- applyCallbackToRouter(router, routeDefinition, instanceWrapper, moduleKey, routePathMetadata, host) {
70
+ applyCallbackToRouter(router, routeDefinition, instanceWrapper, moduleKey, routePathMetadata, host, options = {}) {
71
+ const { onRouteResolved, deferRegistration = false } = options;
71
72
  const { path: paths, requestMethod, targetCallback, methodName, } = routeDefinition;
72
73
  const { instance } = instanceWrapper;
73
74
  const routerMethodRef = this.routerMethodFactory
@@ -90,6 +91,9 @@ export class RouterExplorer {
90
91
  routePathMetadata.methodPath = path;
91
92
  const pathsToRegister = this.routePathFactory.create(routePathMetadata, requestMethod);
92
93
  pathsToRegister.forEach(path => {
94
+ const normalizedPath = router.normalizePath
95
+ ? router.normalizePath(path)
96
+ : path;
93
97
  const entrypointDefinition = {
94
98
  type: 'http-endpoint',
95
99
  methodName,
@@ -103,21 +107,34 @@ export class RouterExplorer {
103
107
  controllerVersion: routePathMetadata.controllerVersion,
104
108
  },
105
109
  };
106
- this.copyMetadataToCallback(targetCallback, routeHandler);
107
- const normalizedPath = router.normalizePath
108
- ? router.normalizePath(path)
109
- : path;
110
- const httpAdapter = this.container.getHttpAdapterRef();
111
- const onRouteTriggered = httpAdapter.getOnRouteTriggered?.();
112
- if (onRouteTriggered) {
113
- routerMethodRef(normalizedPath, (...args) => {
114
- onRouteTriggered(requestMethod, path);
115
- return routeHandler(...args);
116
- });
117
- }
118
- else {
119
- routerMethodRef(normalizedPath, routeHandler);
110
+ if (!deferRegistration) {
111
+ this.copyMetadataToCallback(targetCallback, routeHandler);
112
+ const httpAdapter = this.container.getHttpAdapterRef();
113
+ const onRouteTriggered = httpAdapter.getOnRouteTriggered?.();
114
+ if (onRouteTriggered) {
115
+ routerMethodRef(normalizedPath, (...args) => {
116
+ onRouteTriggered(requestMethod, path);
117
+ return routeHandler(...args);
118
+ });
119
+ }
120
+ else {
121
+ routerMethodRef(normalizedPath, routeHandler);
122
+ }
120
123
  }
124
+ onRouteResolved?.({
125
+ method: requestMethod,
126
+ path: normalizedPath,
127
+ rawPath: path,
128
+ host,
129
+ version: routePathMetadata.methodVersion ??
130
+ routePathMetadata.controllerVersion,
131
+ methodVersion: routePathMetadata.methodVersion,
132
+ controllerVersion: routePathMetadata.controllerVersion,
133
+ handler: routeHandler,
134
+ targetCallback,
135
+ methodName,
136
+ instanceWrapper,
137
+ });
121
138
  this.graphInspector.insertEntrypointDefinition(entrypointDefinition, instanceWrapper.id);
122
139
  });
123
140
  const pathsToLog = this.routePathFactory.create({
@@ -135,6 +152,31 @@ export class RouterExplorer {
135
152
  });
136
153
  });
137
154
  }
155
+ /**
156
+ * Registers a previously resolved route on the underlying HTTP adapter.
157
+ * Used when route registration has been deferred (e.g. when sorting
158
+ * routes by specificity) so the caller can choose the order in which
159
+ * routes are installed on the adapter.
160
+ */
161
+ registerResolvedRoute(router, route) {
162
+ const routerMethodRef = this.routerMethodFactory
163
+ .get(router, route.method)
164
+ .bind(router);
165
+ this.copyMetadataToCallback(route.targetCallback, route.handler);
166
+ const normalizedPath = route.path;
167
+ const rawPath = route.rawPath ?? route.path;
168
+ const httpAdapter = this.container.getHttpAdapterRef();
169
+ const onRouteTriggered = httpAdapter.getOnRouteTriggered?.();
170
+ if (onRouteTriggered) {
171
+ routerMethodRef(normalizedPath, (...args) => {
172
+ onRouteTriggered(route.method, rawPath);
173
+ return route.handler(...args);
174
+ });
175
+ }
176
+ else {
177
+ routerMethodRef(normalizedPath, route.handler);
178
+ }
179
+ }
138
180
  applyHostFilter(host, handler) {
139
181
  if (!host) {
140
182
  return handler;
@@ -1,11 +1,13 @@
1
+ import { type HttpServer } from '@nestjs/common';
2
+ import { type Controller } from '@nestjs/common/internal';
1
3
  import { ApplicationConfig } from '../application-config.js';
2
4
  import { NestContainer } from '../injector/container.js';
3
5
  import { Injector } from '../injector/injector.js';
4
6
  import { InstanceWrapper } from '../injector/instance-wrapper.js';
5
7
  import { GraphInspector } from '../inspector/graph-inspector.js';
8
+ import { ResolvedRoute } from './interfaces/resolved-route.interface.js';
6
9
  import { Resolver } from './interfaces/resolver.interface.js';
7
- import { type Controller } from '@nestjs/common/internal';
8
- import { type HttpServer } from '@nestjs/common';
10
+ import { RouteResolutionOptions } from './interfaces/route-resolution-options.interface.js';
9
11
  export declare class RoutesResolver implements Resolver {
10
12
  private readonly container;
11
13
  private readonly applicationConfig;
@@ -16,8 +18,9 @@ export declare class RoutesResolver implements Resolver {
16
18
  private readonly routerExceptionsFilter;
17
19
  private readonly routerExplorer;
18
20
  constructor(container: NestContainer, applicationConfig: ApplicationConfig, injector: Injector, graphInspector: GraphInspector);
19
- resolve<T extends HttpServer>(applicationRef: T, globalPrefix: string): void;
20
- registerRouters(routes: Map<string | symbol | Function, InstanceWrapper<Controller>>, moduleName: string, globalPrefix: string, modulePath: string, applicationRef: HttpServer): void;
21
+ resolve<T extends HttpServer>(applicationRef: T, globalPrefix: string, options?: RouteResolutionOptions): void;
22
+ registerResolvedRoute<T extends HttpServer>(applicationRef: T, route: ResolvedRoute): void;
23
+ registerRouters(routes: Map<string | symbol | Function, InstanceWrapper<Controller>>, moduleName: string, globalPrefix: string, modulePath: string, applicationRef: HttpServer, options?: RouteResolutionOptions): void;
21
24
  registerNotFoundHandler(): void;
22
25
  registerExceptionHandler(): void;
23
26
  private getModulePathMetadata;
@@ -1,12 +1,11 @@
1
- import { NotFoundException, } from '@nestjs/common';
1
+ import { Logger, NotFoundException, } from '@nestjs/common';
2
+ import { HOST_METADATA, MODULE_PATH, VERSION_METADATA, } from '@nestjs/common/internal';
2
3
  import { CONTROLLER_MAPPING_MESSAGE, VERSIONED_CONTROLLER_MAPPING_MESSAGE, } from '../helpers/messages.js';
3
4
  import { MetadataScanner } from '../metadata-scanner.js';
4
5
  import { RoutePathFactory } from './route-path-factory.js';
5
6
  import { RouterExceptionFilters } from './router-exception-filters.js';
6
7
  import { RouterExplorer } from './router-explorer.js';
7
8
  import { RouterProxy } from './router-proxy.js';
8
- import { HOST_METADATA, MODULE_PATH, VERSION_METADATA, } from '@nestjs/common/internal';
9
- import { Logger } from '@nestjs/common';
10
9
  export class RoutesResolver {
11
10
  container;
12
11
  applicationConfig;
@@ -28,14 +27,17 @@ export class RoutesResolver {
28
27
  const metadataScanner = new MetadataScanner();
29
28
  this.routerExplorer = new RouterExplorer(metadataScanner, this.container, this.injector, this.routerProxy, this.routerExceptionsFilter, this.applicationConfig, this.routePathFactory, graphInspector);
30
29
  }
31
- resolve(applicationRef, globalPrefix) {
30
+ resolve(applicationRef, globalPrefix, options = {}) {
32
31
  const modules = this.container.getModules();
33
32
  modules.forEach(({ controllers, metatype }, moduleName) => {
34
33
  const modulePath = this.getModulePathMetadata(metatype);
35
- this.registerRouters(controllers, moduleName, globalPrefix, modulePath, applicationRef);
34
+ this.registerRouters(controllers, moduleName, globalPrefix, modulePath, applicationRef, options);
36
35
  });
37
36
  }
38
- registerRouters(routes, moduleName, globalPrefix, modulePath, applicationRef) {
37
+ registerResolvedRoute(applicationRef, route) {
38
+ this.routerExplorer.registerResolvedRoute(applicationRef, route);
39
+ }
40
+ registerRouters(routes, moduleName, globalPrefix, modulePath, applicationRef, options = {}) {
39
41
  routes.forEach(instanceWrapper => {
40
42
  const { metatype } = instanceWrapper;
41
43
  const host = this.getHostMetadata(metatype);
@@ -68,7 +70,7 @@ export class RoutesResolver {
68
70
  controllerVersion,
69
71
  versioningOptions,
70
72
  };
71
- this.routerExplorer.explore(instanceWrapper, moduleName, applicationRef, host, routePathMetadata);
73
+ this.routerExplorer.explore(instanceWrapper, moduleName, applicationRef, host, routePathMetadata, options);
72
74
  });
73
75
  });
74
76
  }