@nestjs/core 12.0.0-alpha.4 → 12.0.0-alpha.6
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 +25 -45
- package/adapters/http-adapter.d.ts +2 -0
- package/adapters/http-adapter.js +3 -0
- package/application-config.d.ts +8 -2
- package/application-config.js +14 -0
- package/errors/exceptions/index.d.ts +1 -0
- package/errors/exceptions/index.js +1 -0
- package/errors/exceptions/invalid-class-module.exception.d.ts +1 -1
- package/errors/exceptions/invalid-class-module.exception.js +2 -2
- package/errors/exceptions/invalid-module.exception.d.ts +1 -1
- package/errors/exceptions/invalid-module.exception.js +2 -2
- package/errors/exceptions/route-conflict.exception.d.ts +4 -0
- package/errors/exceptions/route-conflict.exception.js +7 -0
- package/errors/messages.d.ts +5 -2
- package/errors/messages.js +37 -4
- package/exceptions/base-exception-filter.js +8 -3
- package/helpers/barrier.js +4 -1
- package/helpers/handler-metadata-storage.d.ts +1 -0
- package/helpers/router-method-factory.d.ts +1 -0
- package/helpers/router-method-factory.js +1 -0
- package/hooks/before-app-shutdown.hook.js +11 -2
- package/hooks/on-app-shutdown.hook.js +11 -2
- package/hooks/on-module-destroy.hook.js +11 -2
- package/injector/container.js +2 -2
- package/injector/helpers/transient-instances.d.ts +12 -0
- package/injector/helpers/transient-instances.js +28 -0
- package/injector/injector.d.ts +4 -3
- package/injector/injector.js +34 -13
- package/injector/instance-wrapper.d.ts +2 -0
- package/injector/instance-wrapper.js +25 -0
- package/injector/internal-core-module/internal-core-module-factory.js +1 -1
- package/injector/module.d.ts +6 -0
- package/injector/module.js +8 -0
- package/interceptors/interceptors-consumer.js +32 -7
- package/middleware/builder.js +5 -1
- package/nest-application-context.js +1 -1
- package/nest-application.d.ts +3 -1
- package/nest-application.js +96 -6
- package/package.json +3 -14
- package/router/interfaces/index.d.ts +3 -0
- package/router/interfaces/index.js +3 -0
- package/router/interfaces/resolved-route.interface.d.ts +32 -0
- package/router/interfaces/resolved-route.interface.js +1 -0
- package/router/interfaces/resolver.interface.d.ts +5 -1
- package/router/interfaces/route-conflict.interface.d.ts +14 -0
- package/router/interfaces/route-conflict.interface.js +1 -0
- package/router/interfaces/route-resolution-options.interface.d.ts +24 -0
- package/router/interfaces/route-resolution-options.interface.js +1 -0
- package/router/legacy-route-converter.d.ts +1 -1
- package/router/legacy-route-converter.js +24 -13
- package/router/route-conflict-detector.d.ts +71 -0
- package/router/route-conflict-detector.js +276 -0
- package/router/route-specificity-sorter.d.ts +23 -0
- package/router/route-specificity-sorter.js +59 -0
- package/router/router-execution-context.d.ts +1 -0
- package/router/router-execution-context.js +26 -3
- package/router/router-explorer.d.ts +11 -2
- package/router/router-explorer.js +61 -19
- package/router/router-response-controller.d.ts +1 -0
- package/router/router-response-controller.js +126 -49
- package/router/routes-resolver.d.ts +7 -4
- package/router/routes-resolver.js +9 -7
- package/router/sse-stream.d.ts +1 -0
- package/router/sse-stream.js +24 -13
- package/scanner.js +13 -6
|
@@ -21,37 +21,48 @@ export class LegacyRouteConverter {
|
|
|
21
21
|
? this.printWarning.bind(this)
|
|
22
22
|
: () => { };
|
|
23
23
|
if (normalizedRoute.endsWith('/(.*)/')) {
|
|
24
|
+
const convertedRoute = route.replace('(.*)', '{*path}');
|
|
24
25
|
// Skip printing warning for the "all" wildcard.
|
|
25
26
|
if (normalizedRoute !== '/(.*)/') {
|
|
26
|
-
printWarning(route);
|
|
27
|
+
printWarning(route, convertedRoute);
|
|
27
28
|
}
|
|
28
|
-
return
|
|
29
|
+
return convertedRoute;
|
|
29
30
|
}
|
|
30
31
|
if (normalizedRoute.endsWith('/*/')) {
|
|
32
|
+
const convertedRoute = route.replace('*', '{*path}');
|
|
31
33
|
// Skip printing warning for the "all" wildcard.
|
|
32
34
|
if (normalizedRoute !== '/*/') {
|
|
33
|
-
printWarning(route);
|
|
35
|
+
printWarning(route, convertedRoute);
|
|
34
36
|
}
|
|
35
|
-
return
|
|
37
|
+
return convertedRoute;
|
|
36
38
|
}
|
|
37
39
|
if (normalizedRoute.endsWith('/+/')) {
|
|
38
|
-
|
|
39
|
-
|
|
40
|
+
const convertedRoute = route.replace('/+', '/*path');
|
|
41
|
+
printWarning(route, convertedRoute);
|
|
42
|
+
return convertedRoute;
|
|
40
43
|
}
|
|
41
44
|
// When route includes any wildcard segments in the middle.
|
|
42
45
|
if (normalizedRoute.includes('/*/')) {
|
|
43
|
-
|
|
44
|
-
//
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
46
|
+
// Replace each "*" segment with a named parameter, using a different name
|
|
47
|
+
// for each. Match "/*" with a lookahead for the following "/" so the
|
|
48
|
+
// trailing slash is not consumed. Consuming it made two adjacent "/*/*/"
|
|
49
|
+
// segments share a slash, so only the first one got converted and the
|
|
50
|
+
// second was left as an unnamed "*" that path-to-regexp still rejects.
|
|
51
|
+
const convertedRoute = route.replaceAll(/\/\*(?=\/)/g, (match, offset) => `/*path${offset}`);
|
|
52
|
+
printWarning(route, convertedRoute);
|
|
53
|
+
return convertedRoute;
|
|
48
54
|
}
|
|
49
55
|
return route;
|
|
50
56
|
}
|
|
51
57
|
static printError(route) {
|
|
52
58
|
this.logger.error(UNSUPPORTED_PATH_MESSAGE `${route}`);
|
|
53
59
|
}
|
|
54
|
-
static printWarning(route) {
|
|
55
|
-
|
|
60
|
+
static printWarning(route, convertedRoute) {
|
|
61
|
+
// Surface the auto-converted result so users can map the flagged path to a
|
|
62
|
+
// concrete fix, instead of only seeing the (often prefixed) offending path.
|
|
63
|
+
const autoConvertMessage = convertedRoute
|
|
64
|
+
? ` Attempting to auto-convert to "${convertedRoute}"...`
|
|
65
|
+
: ' Attempting to auto-convert...';
|
|
66
|
+
this.logger.warn(UNSUPPORTED_PATH_MESSAGE `${route}` + autoConvertMessage);
|
|
56
67
|
}
|
|
57
68
|
}
|
|
@@ -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
|
+
}
|
|
@@ -48,4 +48,5 @@ export declare class RouterExecutionContext {
|
|
|
48
48
|
})[]): (<TRequest, TResponse>(args: any[], req: TRequest, res: TResponse, next: Function) => Promise<void>) | null;
|
|
49
49
|
createHandleResponseFn(callback: (...args: unknown[]) => unknown, isResponseHandled: boolean, redirectResponse?: RedirectResponse, httpStatusCode?: number): HandleResponseFn;
|
|
50
50
|
private isResponseHandled;
|
|
51
|
+
private attachSseAbortSignal;
|
|
51
52
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { ForbiddenException, } from '@nestjs/common';
|
|
1
|
+
import { ForbiddenException, SSE_ABORT_CONTROLLER, } from '@nestjs/common';
|
|
2
2
|
import { CUSTOM_ROUTE_ARGS_METADATA, HEADERS_METADATA, HTTP_CODE_METADATA, isEmptyArray, isString, REDIRECT_METADATA, RENDER_METADATA, ROUTE_ARGS_METADATA, RouteParamtypes, SSE_METADATA, } from '@nestjs/common/internal';
|
|
3
3
|
import { FORBIDDEN_MESSAGE, } from '../guards/index.js';
|
|
4
4
|
import { ContextUtils } from '../helpers/context-utils.js';
|
|
@@ -30,7 +30,7 @@ export class RouterExecutionContext {
|
|
|
30
30
|
}
|
|
31
31
|
create(instance, callback, methodName, moduleKey, requestMethod, contextId = STATIC_CONTEXT, inquirerId) {
|
|
32
32
|
const contextType = 'http';
|
|
33
|
-
const { argsLength, fnHandleResponse, paramtypes, getParamsMetadata, httpStatusCode, responseHeaders, hasCustomHeaders, } = this.getMetadata(instance, callback, methodName, moduleKey, requestMethod, contextType);
|
|
33
|
+
const { argsLength, fnHandleResponse, isSseHandler, paramtypes, getParamsMetadata, httpStatusCode, responseHeaders, hasCustomHeaders, } = this.getMetadata(instance, callback, methodName, moduleKey, requestMethod, contextType);
|
|
34
34
|
const paramsOptions = this.contextUtils.mergeParamsMetatypes(getParamsMetadata(moduleKey, contextId, inquirerId), paramtypes);
|
|
35
35
|
const pipes = this.pipesContextCreator.create(instance, callback, moduleKey, contextId, inquirerId);
|
|
36
36
|
const guards = this.guardsContextCreator.create(instance, callback, moduleKey, contextId, inquirerId);
|
|
@@ -47,7 +47,15 @@ export class RouterExecutionContext {
|
|
|
47
47
|
this.responseController.setStatus(res, httpStatusCode);
|
|
48
48
|
hasCustomHeaders &&
|
|
49
49
|
this.responseController.setHeaders(res, responseHeaders);
|
|
50
|
-
|
|
50
|
+
if (isSseHandler) {
|
|
51
|
+
// Attach a per-request AbortController before the handler runs so async
|
|
52
|
+
// @Sse() handlers can observe client disconnects via @SseSignal() during
|
|
53
|
+
// their setup. The controller is aborted in RouterResponseController.sse()
|
|
54
|
+
// when the underlying connection closes.
|
|
55
|
+
this.attachSseAbortSignal(req);
|
|
56
|
+
}
|
|
57
|
+
const resultOrDeferred = this.interceptorsConsumer.intercept(interceptors, [req, res, next], instance, callback, handler(args, req, res, next), contextType);
|
|
58
|
+
const result = isSseHandler ? resultOrDeferred : await resultOrDeferred;
|
|
51
59
|
await fnHandleResponse(result, res, req);
|
|
52
60
|
};
|
|
53
61
|
}
|
|
@@ -66,6 +74,7 @@ export class RouterExecutionContext {
|
|
|
66
74
|
const isResponseHandled = this.isResponseHandled(instance, methodName, paramsMetadata);
|
|
67
75
|
const httpRedirectResponse = this.reflectRedirect(callback);
|
|
68
76
|
const fnHandleResponse = this.createHandleResponseFn(callback, isResponseHandled, httpRedirectResponse);
|
|
77
|
+
const isSseHandler = !!this.reflectSse(callback);
|
|
69
78
|
const httpCode = this.reflectHttpStatusCode(callback);
|
|
70
79
|
const httpStatusCode = httpCode ?? this.responseController.getStatusByMethod(requestMethod);
|
|
71
80
|
const responseHeaders = this.reflectResponseHeaders(callback);
|
|
@@ -73,6 +82,7 @@ export class RouterExecutionContext {
|
|
|
73
82
|
const handlerMetadata = {
|
|
74
83
|
argsLength,
|
|
75
84
|
fnHandleResponse,
|
|
85
|
+
isSseHandler,
|
|
76
86
|
paramtypes,
|
|
77
87
|
getParamsMetadata,
|
|
78
88
|
httpStatusCode,
|
|
@@ -196,4 +206,17 @@ export class RouterExecutionContext {
|
|
|
196
206
|
const isPassthroughEnabled = this.contextUtils.reflectPassthrough(instance, methodName);
|
|
197
207
|
return hasResponseOrNextDecorator && !isPassthroughEnabled;
|
|
198
208
|
}
|
|
209
|
+
attachSseAbortSignal(req) {
|
|
210
|
+
const carrier = req;
|
|
211
|
+
// Attach to both the framework request and its raw form (when present), since
|
|
212
|
+
// @SseSignal() reads from the execution-context request while
|
|
213
|
+
// RouterResponseController.sse() operates on the raw request.
|
|
214
|
+
if (!carrier[SSE_ABORT_CONTROLLER]) {
|
|
215
|
+
carrier[SSE_ABORT_CONTROLLER] = new AbortController();
|
|
216
|
+
}
|
|
217
|
+
if (carrier.raw && !carrier.raw[SSE_ABORT_CONTROLLER]) {
|
|
218
|
+
carrier.raw[SSE_ABORT_CONTROLLER] =
|
|
219
|
+
carrier[SSE_ABORT_CONTROLLER];
|
|
220
|
+
}
|
|
221
|
+
}
|
|
199
222
|
}
|
|
@@ -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
|
|
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;
|