@bleedingdev/modern-js-runtime-extensions 3.9.0-ultramodern.9 → 3.9.3-ultramodern.1

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 (117) hide show
  1. package/dist/cjs/{reactContext.js → localisedUrls/config.js} +14 -10
  2. package/dist/cjs/localisedUrls/index.js +95 -0
  3. package/dist/cjs/localisedUrls/normalise.js +87 -0
  4. package/dist/cjs/localisedUrls/pathname.js +68 -0
  5. package/dist/cjs/localisedUrls/patterns.js +214 -0
  6. package/dist/cjs/localisedUrls/redirect.js +104 -0
  7. package/dist/cjs/localisedUrls/resolve.js +78 -0
  8. package/dist/cjs/localisedUrls/routeIdentity.js +92 -0
  9. package/dist/cjs/localisedUrls/routes.js +217 -0
  10. package/dist/cjs/localisedUrls/types.js +18 -0
  11. package/dist/cjs/rendererHead.js +18 -5
  12. package/dist/cjs/request-policy/policyCore.js +1 -1
  13. package/dist/cjs/request-policy/transport.js +2 -2
  14. package/dist/cjs/routerState.js +85 -77
  15. package/dist/cjs/routerStatePlugin.js +63 -9
  16. package/dist/esm/localisedUrls/config.mjs +11 -0
  17. package/dist/esm/localisedUrls/index.mjs +8 -0
  18. package/dist/esm/localisedUrls/normalise.mjs +37 -0
  19. package/dist/esm/localisedUrls/pathname.mjs +24 -0
  20. package/dist/esm/localisedUrls/patterns.mjs +152 -0
  21. package/dist/esm/localisedUrls/redirect.mjs +57 -0
  22. package/dist/esm/localisedUrls/resolve.mjs +37 -0
  23. package/dist/esm/localisedUrls/routeIdentity.mjs +54 -0
  24. package/dist/esm/localisedUrls/routes.mjs +176 -0
  25. package/dist/esm/localisedUrls/types.mjs +0 -0
  26. package/dist/esm/rendererHead.mjs +14 -5
  27. package/dist/esm/request-policy/policyCore.mjs +1 -1
  28. package/dist/esm/request-policy/transport.mjs +2 -2
  29. package/dist/esm/routerState.mjs +81 -73
  30. package/dist/esm/routerStatePlugin.mjs +62 -11
  31. package/dist/esm-node/localisedUrls/config.mjs +12 -0
  32. package/dist/esm-node/localisedUrls/index.mjs +9 -0
  33. package/dist/esm-node/localisedUrls/normalise.mjs +38 -0
  34. package/dist/esm-node/localisedUrls/pathname.mjs +25 -0
  35. package/dist/esm-node/localisedUrls/patterns.mjs +153 -0
  36. package/dist/esm-node/localisedUrls/redirect.mjs +58 -0
  37. package/dist/esm-node/localisedUrls/resolve.mjs +38 -0
  38. package/dist/esm-node/localisedUrls/routeIdentity.mjs +55 -0
  39. package/dist/esm-node/localisedUrls/routes.mjs +177 -0
  40. package/dist/esm-node/localisedUrls/types.mjs +1 -0
  41. package/dist/esm-node/rendererHead.mjs +14 -5
  42. package/dist/esm-node/request-policy/policyCore.mjs +1 -1
  43. package/dist/esm-node/request-policy/transport.mjs +2 -2
  44. package/dist/esm-node/routerState.mjs +81 -73
  45. package/dist/esm-node/routerStatePlugin.mjs +62 -11
  46. package/dist/types/helmetCompat.d.ts +1 -1
  47. package/dist/types/localisedUrls/config.d.ts +9 -0
  48. package/dist/types/localisedUrls/index.d.ts +10 -0
  49. package/dist/types/localisedUrls/normalise.d.ts +10 -0
  50. package/dist/types/localisedUrls/pathname.d.ts +4 -0
  51. package/dist/types/localisedUrls/patterns.d.ts +11 -0
  52. package/dist/types/localisedUrls/redirect.d.ts +19 -0
  53. package/dist/types/localisedUrls/resolve.d.ts +7 -0
  54. package/dist/types/localisedUrls/routeIdentity.d.ts +22 -0
  55. package/dist/types/localisedUrls/routes.d.ts +3 -0
  56. package/dist/types/localisedUrls/types.d.ts +14 -0
  57. package/dist/types/rendererHead.d.ts +5 -3
  58. package/dist/types/request-policy/types.d.ts +1 -1
  59. package/dist/types/routeHydration.d.ts +2 -2
  60. package/dist/types/routerProvider.d.ts +1 -3
  61. package/dist/types/routerState.d.ts +11 -6
  62. package/dist/types/routerStatePlugin.d.ts +12 -0
  63. package/dist/types/routerStateTypes.d.ts +47 -17
  64. package/package.json +42 -44
  65. package/src/helmetCompat.ts +1 -1
  66. package/src/localisedUrls/config.ts +18 -0
  67. package/src/localisedUrls/index.ts +25 -0
  68. package/src/localisedUrls/normalise.ts +62 -0
  69. package/src/localisedUrls/pathname.ts +60 -0
  70. package/src/localisedUrls/patterns.ts +283 -0
  71. package/src/localisedUrls/redirect.ts +110 -0
  72. package/src/localisedUrls/resolve.ts +106 -0
  73. package/src/localisedUrls/routeIdentity.ts +83 -0
  74. package/src/localisedUrls/routes.ts +451 -0
  75. package/src/localisedUrls/types.ts +18 -0
  76. package/src/rendererHead.ts +25 -8
  77. package/src/request-policy/policyCore.ts +1 -1
  78. package/src/request-policy/transport.ts +2 -2
  79. package/src/request-policy/types.ts +1 -1
  80. package/src/routeHydration.ts +2 -2
  81. package/src/routerProvider.ts +1 -1
  82. package/src/routerState.ts +127 -115
  83. package/src/routerStatePlugin.ts +106 -10
  84. package/src/routerStateTypes.ts +47 -17
  85. package/dist/cjs/buildIdentity.js +0 -73
  86. package/dist/esm/buildIdentity.mjs +0 -35
  87. package/dist/esm/reactContext.mjs +0 -7
  88. package/dist/esm-node/buildIdentity.mjs +0 -36
  89. package/dist/esm-node/reactContext.mjs +0 -8
  90. package/dist/types/buildIdentity.d.ts +0 -37
  91. package/dist/types/reactContext.d.ts +0 -6
  92. package/rslib.config.mts +0 -19
  93. package/rstest.config.mts +0 -38
  94. package/src/buildIdentity.ts +0 -61
  95. package/src/reactContext.ts +0 -16
  96. package/tests/buildIdentity.test.ts +0 -51
  97. package/tests/contextExtensions.test.ts +0 -27
  98. package/tests/headRuntime.test.tsx +0 -229
  99. package/tests/rendererHead.test.ts +0 -187
  100. package/tests/request-policy/browser-policy.test.ts +0 -108
  101. package/tests/request-policy/client-isolation.test.ts +0 -109
  102. package/tests/request-policy/node-policy.test.ts +0 -447
  103. package/tests/request-policy/policyCore.test.ts +0 -129
  104. package/tests/request-policy/requestContext.test.ts +0 -66
  105. package/tests/request-policy/requestFactory.outbound-contract.test.ts +0 -290
  106. package/tests/request-policy/traceparent.test.ts +0 -52
  107. package/tests/request-policy/transport-retry.test.ts +0 -367
  108. package/tests/routeHydration.test.ts +0 -180
  109. package/tests/routerPrefetchPolicy.test.ts +0 -102
  110. package/tests/routerProvider.test.ts +0 -29
  111. package/tests/routerState.test.ts +0 -78
  112. package/tests/routerStatePlugin.test.ts +0 -63
  113. package/tests/runtimeContextProjection.test.ts +0 -83
  114. package/tests/safeFailure.test.ts +0 -136
  115. package/tests/shellStream.test.ts +0 -122
  116. package/tests/workspaceEvents.test.ts +0 -221
  117. package/tsconfig.json +0 -10
package/package.json CHANGED
@@ -1,19 +1,19 @@
1
1
  {
2
2
  "name": "@bleedingdev/modern-js-runtime-extensions",
3
3
  "description": "Fork-owned UltraModern.js runtime transaction, streaming, and safe failure primitives.",
4
- "homepage": "https://github.com/BleedingDev/ultramodern.js#readme",
4
+ "homepage": "https://github.com/ultramodernjs/ultramodern.js#readme",
5
5
  "bugs": {
6
- "url": "https://github.com/BleedingDev/ultramodern.js/issues"
6
+ "url": "https://github.com/ultramodernjs/ultramodern.js/issues"
7
7
  },
8
8
  "repository": {
9
9
  "type": "git",
10
- "url": "git+https://github.com/BleedingDev/ultramodern.js.git",
10
+ "url": "git+https://github.com/ultramodernjs/ultramodern.js.git",
11
11
  "directory": "packages/runtime/runtime-extensions"
12
12
  },
13
13
  "license": "MIT",
14
- "version": "3.9.0-ultramodern.9",
14
+ "version": "3.9.3-ultramodern.1",
15
15
  "engines": {
16
- "node": ">=26.7.0"
16
+ "node": ">=26.10.0"
17
17
  },
18
18
  "types": "./dist/types/index.d.ts",
19
19
  "main": "./dist/cjs/index.js",
@@ -42,14 +42,6 @@
42
42
  },
43
43
  "default": "./dist/esm/safeFailure.mjs"
44
44
  },
45
- "./build-identity": {
46
- "types": "./dist/types/buildIdentity.d.ts",
47
- "node": {
48
- "import": "./dist/esm-node/buildIdentity.mjs",
49
- "require": "./dist/cjs/buildIdentity.js"
50
- },
51
- "default": "./dist/esm/buildIdentity.mjs"
52
- },
53
45
  "./workspace-events": {
54
46
  "types": "./dist/types/workspaceEvents.d.ts",
55
47
  "node": {
@@ -70,14 +62,6 @@
70
62
  },
71
63
  "default": "./dist/esm/localisedLoaderIdentity.mjs"
72
64
  },
73
- "./react-context": {
74
- "types": "./dist/types/reactContext.d.ts",
75
- "node": {
76
- "import": "./dist/esm-node/reactContext.mjs",
77
- "require": "./dist/cjs/reactContext.js"
78
- },
79
- "default": "./dist/esm/reactContext.mjs"
80
- },
81
65
  "./context-extensions": {
82
66
  "types": "./dist/types/contextExtensions.d.ts",
83
67
  "node": {
@@ -186,6 +170,14 @@
186
170
  "require": "./dist/cjs/routerPrefetchPolicy.js"
187
171
  },
188
172
  "default": "./dist/esm/routerPrefetchPolicy.mjs"
173
+ },
174
+ "./localised-urls": {
175
+ "types": "./dist/types/localisedUrls/index.d.ts",
176
+ "node": {
177
+ "import": "./dist/esm-node/localisedUrls/index.mjs",
178
+ "require": "./dist/cjs/localisedUrls/index.js"
179
+ },
180
+ "default": "./dist/esm/localisedUrls/index.mjs"
189
181
  }
190
182
  },
191
183
  "typesVersions": {
@@ -202,10 +194,6 @@
202
194
  "./dist/types/safeFailure.d.ts",
203
195
  "./src/safeFailure.ts"
204
196
  ],
205
- "build-identity": [
206
- "./dist/types/buildIdentity.d.ts",
207
- "./src/buildIdentity.ts"
208
- ],
209
197
  "workspace-events": [
210
198
  "./dist/types/workspaceEvents.d.ts",
211
199
  "./src/workspaceEvents.ts"
@@ -214,10 +202,6 @@
214
202
  "./dist/types/localisedLoaderIdentity.d.ts",
215
203
  "./src/localisedLoaderIdentity.ts"
216
204
  ],
217
- "react-context": [
218
- "./dist/types/reactContext.d.ts",
219
- "./src/reactContext.ts"
220
- ],
221
205
  "context-extensions": [
222
206
  "./dist/types/contextExtensions.d.ts",
223
207
  "./src/contextExtensions.ts"
@@ -269,47 +253,61 @@
269
253
  "router-prefetch-policy": [
270
254
  "./dist/types/routerPrefetchPolicy.d.ts",
271
255
  "./src/routerPrefetchPolicy.ts"
256
+ ],
257
+ "localised-urls": [
258
+ "./dist/types/localisedUrls/index.d.ts",
259
+ "./src/localisedUrls/index.ts"
272
260
  ]
273
261
  }
274
262
  },
275
263
  "devDependencies": {
276
264
  "@loadable/component": "5.16.7",
277
- "@modern-js/utils": "npm:@bleedingdev/modern-js-utils@3.9.0-ultramodern.9",
278
- "@rsbuild/core": "2.2.3",
279
- "@rslib/core": "1.0.0",
265
+ "@modern-js/utils": "npm:@bleedingdev/modern-js-utils@3.9.3-ultramodern.1",
266
+ "@rsbuild/core": "2.2.11",
267
+ "@rslib/core": "1.0.3",
280
268
  "@scripts/rstest-config": "2.66.0",
281
- "@testing-library/dom": "^10.4.1",
269
+ "@testing-library/dom": "^10.4.2",
282
270
  "@testing-library/react": "^16.3.3",
283
- "@types/node": "^26.4.1",
284
- "@types/react": "^19.2.18",
285
- "@types/react-dom": "^19.2.7",
286
- "@typescript/native-preview": "7.0.0-dev.20260707.2",
271
+ "@types/node": "^26.6.3",
272
+ "@types/react": "^19.3.0",
273
+ "@types/react-dom": "^19.3.0",
287
274
  "esbuild": "^0.28.2",
288
275
  "nock": "^14.0.17",
289
- "react": "^19.2.8",
290
- "react-dom": "^19.2.8",
291
- "typescript": "^7.0.2"
276
+ "react": "^19.3.0",
277
+ "react-dom": "^19.3.0",
278
+ "react-helmet-async": "3.0.0",
279
+ "typescript": "7.0.2"
292
280
  },
293
281
  "sideEffects": false,
294
282
  "publishConfig": {
295
283
  "access": "public"
296
284
  },
297
285
  "peerDependencies": {
298
- "react": "^19.2.8"
286
+ "react": "^19.2.8",
287
+ "react-helmet-async": "3.0.0"
299
288
  },
300
289
  "peerDependenciesMeta": {
301
290
  "react": {
302
291
  "optional": true
292
+ },
293
+ "react-helmet-async": {
294
+ "optional": true
303
295
  }
304
296
  },
305
297
  "dependencies": {
306
- "@modern-js/create-request": "npm:@bleedingdev/modern-js-create-request@3.9.0-ultramodern.9",
307
- "@modern-js/runtime-utils": "npm:@bleedingdev/modern-js-runtime-utils@3.9.0-ultramodern.9",
308
- "react-helmet-async": "3.0.0"
298
+ "@modern-js/create-request": "npm:@bleedingdev/modern-js-create-request@3.9.3-ultramodern.1",
299
+ "@modern-js/runtime-utils": "npm:@bleedingdev/modern-js-runtime-utils@3.9.3-ultramodern.1"
309
300
  },
301
+ "files": [
302
+ "dist",
303
+ "src"
304
+ ],
310
305
  "scripts": {
311
306
  "dev": "rslib build --watch",
312
307
  "build": "rslib build",
313
308
  "test": "rstest"
309
+ },
310
+ "ultramodern": {
311
+ "sourceName": "@modern-js/runtime-extensions"
314
312
  }
315
313
  }
@@ -149,7 +149,7 @@ const createElementFactory = <Element>(react: ElementFactory<Element>) =>
149
149
 
150
150
  export const renderHeadMarker = <Element>(
151
151
  react: ElementFactory<Element>,
152
- marker: MarkerProps | null | undefined,
152
+ marker: MarkerProps | undefined,
153
153
  ): Element | null =>
154
154
  marker ? createElementFactory(react)('template', marker) : null;
155
155
 
@@ -0,0 +1,18 @@
1
+ import type { LocalisedUrlsOption, ResolvedLocalisedUrlsConfig } from './types';
2
+
3
+ /**
4
+ * Localised URLs are strictly opt-in: only an explicit, non-empty map enables
5
+ * route expansion and validation. `true`, `false`, an empty map and absence
6
+ * all resolve to disabled, so upstream-style configs (`localePathRedirect` +
7
+ * `languages` without a map) keep plain locale-prefix behavior instead of
8
+ * failing the build for every route missing from a map they never wrote.
9
+ */
10
+ export const resolveLocalisedUrlsConfig = (
11
+ option: LocalisedUrlsOption | undefined,
12
+ ): ResolvedLocalisedUrlsConfig => {
13
+ if (option && typeof option === 'object' && Object.keys(option).length > 0) {
14
+ return { enabled: true, map: option };
15
+ }
16
+
17
+ return { enabled: false, map: {} };
18
+ };
@@ -0,0 +1,25 @@
1
+ export { resolveLocalisedUrlsConfig } from './config';
2
+ export { normalisePathname, normalisePathPattern } from './normalise';
3
+ export {
4
+ canonicalTargetPathname,
5
+ localiseTargetPathname,
6
+ stripLanguagePrefix,
7
+ } from './pathname';
8
+ export { buildPathFromPattern, matchPathPattern } from './patterns';
9
+ export type { LocaleRedirectSkipRule } from './redirect';
10
+ export {
11
+ DEFAULT_LOCALE_REDIRECT_SKIP_RULES,
12
+ isDefaultLocaleRedirectSkipPath,
13
+ matchesPathPrefix,
14
+ shouldSkipLocaleRedirect,
15
+ } from './redirect';
16
+ export { resolveCanonicalLocalisedPath, resolveLocalisedPath } from './resolve';
17
+ export { createLocalisedRouteRewrite } from './routeIdentity';
18
+ export { applyLocalisedUrlsToRoutes, validateLocalisedUrls } from './routes';
19
+ export type {
20
+ LocalisedRoute,
21
+ LocalisedUrlPathMap,
22
+ LocalisedUrlsMap,
23
+ LocalisedUrlsOption,
24
+ ResolvedLocalisedUrlsConfig,
25
+ } from './types';
@@ -0,0 +1,62 @@
1
+ const LOCALE_PARAM_NAMES = new Set(['lang', 'locale', 'language']);
2
+
3
+ const normaliseSlashes = (path: string): string => {
4
+ const withoutDuplicateSlashes = path.replace(/\/+/g, '/');
5
+ const withLeadingSlash = withoutDuplicateSlashes.startsWith('/')
6
+ ? withoutDuplicateSlashes
7
+ : `/${withoutDuplicateSlashes}`;
8
+
9
+ return withLeadingSlash.length > 1
10
+ ? withLeadingSlash.replace(/\/+$/, '')
11
+ : withLeadingSlash;
12
+ };
13
+
14
+ export const normalisePathPattern = (path: string): string =>
15
+ normaliseSlashes(path).replace(/\[(.+?)\]/g, ':$1');
16
+
17
+ /**
18
+ * Normalise a concrete request pathname: slash cleanup only. Unlike
19
+ * {@link normalisePathPattern} it must not rewrite literal `[x]` segments to
20
+ * `:x` params — pathnames are values, not patterns.
21
+ */
22
+ export const normalisePathname = (pathname: string): string =>
23
+ normaliseSlashes(pathname);
24
+
25
+ export const normaliseRoutePath = (path: string): string => {
26
+ const normalized = normalisePathPattern(path);
27
+ return normalized === '/' ? '' : normalized.slice(1);
28
+ };
29
+
30
+ const getLocaleParamSegment = (segment: string): string | null => {
31
+ if (!segment.startsWith(':')) {
32
+ return null;
33
+ }
34
+
35
+ const paramName = segment.slice(1).replace(/\?$/, '');
36
+ return LOCALE_PARAM_NAMES.has(paramName) ? segment : null;
37
+ };
38
+
39
+ const splitPathSegments = (path?: string): string[] => {
40
+ if (!path) {
41
+ return [];
42
+ }
43
+
44
+ return normalisePathPattern(path).split('/').filter(Boolean);
45
+ };
46
+
47
+ export const stripLeadingLocaleParam = (path?: string): string | undefined => {
48
+ const segments = splitPathSegments(path);
49
+ const leadingLocaleParam = getLocaleParamSegment(segments[0] || '');
50
+
51
+ if (!leadingLocaleParam) {
52
+ return path;
53
+ }
54
+
55
+ const remainingPath = segments.slice(1).join('/');
56
+ return remainingPath ? `/${remainingPath}` : undefined;
57
+ };
58
+
59
+ export const getLeadingLocaleParam = (path?: string): string | null => {
60
+ const segments = splitPathSegments(path);
61
+ return getLocaleParamSegment(segments[0] || '');
62
+ };
@@ -0,0 +1,60 @@
1
+ import { resolveLocalisedUrlsConfig } from './config';
2
+
3
+ import { resolveCanonicalLocalisedPath, resolveLocalisedPath } from './resolve';
4
+
5
+ import type { LocalisedUrlsOption } from './types';
6
+
7
+ export const stripLanguagePrefix = (
8
+ pathname: string,
9
+ languages: string[],
10
+ ): string => {
11
+ const segments = pathname.split('/').filter(Boolean);
12
+ const firstSegment = segments[0]?.toLowerCase();
13
+
14
+ if (
15
+ firstSegment &&
16
+ languages.some(language => language.toLowerCase() === firstSegment)
17
+ ) {
18
+ return `/${segments.slice(1).join('/')}`;
19
+ }
20
+
21
+ return pathname || '/';
22
+ };
23
+
24
+ export const localiseTargetPathname = (
25
+ pathname: string,
26
+ language: string,
27
+ languages: string[],
28
+ localisedUrls?: LocalisedUrlsOption,
29
+ ): string => {
30
+ const pathWithoutLanguage = stripLanguagePrefix(pathname, languages);
31
+ const localisedUrlsConfig = resolveLocalisedUrlsConfig(localisedUrls);
32
+ const resolvedPath = localisedUrlsConfig.enabled
33
+ ? resolveLocalisedPath(
34
+ pathWithoutLanguage,
35
+ language,
36
+ languages,
37
+ localisedUrlsConfig.map,
38
+ )
39
+ : pathWithoutLanguage;
40
+ const resolvedSegments = resolvedPath.split('/').filter(Boolean);
41
+
42
+ return `/${[language, ...resolvedSegments].join('/')}`;
43
+ };
44
+
45
+ export const canonicalTargetPathname = (
46
+ pathname: string,
47
+ languages: string[],
48
+ localisedUrls?: LocalisedUrlsOption,
49
+ ): string => {
50
+ const pathWithoutLanguage = stripLanguagePrefix(pathname, languages);
51
+ const localisedUrlsConfig = resolveLocalisedUrlsConfig(localisedUrls);
52
+
53
+ return localisedUrlsConfig.enabled
54
+ ? resolveCanonicalLocalisedPath(
55
+ pathWithoutLanguage,
56
+ languages,
57
+ localisedUrlsConfig.map,
58
+ )
59
+ : pathWithoutLanguage;
60
+ };
@@ -0,0 +1,283 @@
1
+ import { normalisePathname, normalisePathPattern } from './normalise';
2
+
3
+ const escapeRegExp = (value: string): string =>
4
+ value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
5
+
6
+ const getParamName = (segment: string): string =>
7
+ segment.slice(1).replace(/\?$/, '');
8
+
9
+ export const getOrderedPathParamSignature = (pattern: string): string[] =>
10
+ normalisePathPattern(pattern)
11
+ .split('/')
12
+ .filter(Boolean)
13
+ .flatMap(segment => {
14
+ if (segment === '*') {
15
+ return ['*'];
16
+ }
17
+ if (!segment.startsWith(':')) {
18
+ return [];
19
+ }
20
+
21
+ return [`:${getParamName(segment)}${segment.endsWith('?') ? '?' : ''}`];
22
+ });
23
+
24
+ export const getPathParamSignature = (pattern: string): string[] =>
25
+ getOrderedPathParamSignature(pattern).sort((left, right) =>
26
+ left < right ? -1 : left > right ? 1 : 0,
27
+ );
28
+
29
+ export const getPathPatternValidationIssue = (
30
+ pattern: string,
31
+ ): string | undefined => {
32
+ const segments = normalisePathPattern(pattern).split('/').filter(Boolean);
33
+ const seenParams = new Set<string>();
34
+
35
+ for (const [index, segment] of segments.entries()) {
36
+ if (segment === '*') {
37
+ if (index !== segments.length - 1) {
38
+ return 'splat parameter "*" must be the final segment';
39
+ }
40
+ if (seenParams.has('*')) {
41
+ return 'duplicate splat parameter "*"';
42
+ }
43
+ seenParams.add('*');
44
+ continue;
45
+ }
46
+ if (!segment.startsWith(':')) {
47
+ continue;
48
+ }
49
+
50
+ const paramName = getParamName(segment);
51
+ if (seenParams.has(paramName)) {
52
+ return `duplicate path parameter ":${paramName}"`;
53
+ }
54
+ seenParams.add(paramName);
55
+ }
56
+
57
+ return undefined;
58
+ };
59
+
60
+ export const getPhysicalPathPattern = (pattern: string): string => {
61
+ const segments = normalisePathPattern(pattern).split('/').filter(Boolean);
62
+ const physicalSegments = segments.map(segment => {
63
+ if (segment === '*') {
64
+ return '*';
65
+ }
66
+ if (segment.startsWith(':')) {
67
+ return segment.endsWith('?') ? ':param?' : ':param';
68
+ }
69
+ return segment;
70
+ });
71
+
72
+ return `/${physicalSegments.join('/')}`;
73
+ };
74
+
75
+ interface CompiledPathPattern {
76
+ names: string[];
77
+ regexp: RegExp;
78
+ }
79
+
80
+ const compiledPathPatternCache = new Map<string, CompiledPathPattern>();
81
+
82
+ const compilePathPattern = (pattern: string): CompiledPathPattern => {
83
+ const normalizedPattern = normalisePathPattern(pattern);
84
+ const cached = compiledPathPatternCache.get(normalizedPattern);
85
+ if (cached) {
86
+ return cached;
87
+ }
88
+
89
+ const names: string[] = [];
90
+ const segments = normalizedPattern.split('/').filter(Boolean);
91
+ const source = segments
92
+ .map(segment => {
93
+ if (segment.startsWith(':')) {
94
+ names.push(getParamName(segment));
95
+ const paramPattern = '([^/]+)';
96
+ return segment.endsWith('?')
97
+ ? `(?:/${paramPattern})?`
98
+ : `/${paramPattern}`;
99
+ }
100
+ if (segment === '*') {
101
+ names.push('*');
102
+ return '(?:/(.*))?';
103
+ }
104
+ return `/${escapeRegExp(segment)}`;
105
+ })
106
+ .join('');
107
+
108
+ const compiled = {
109
+ names,
110
+ regexp: new RegExp(`^${source || '/'}$`),
111
+ };
112
+ compiledPathPatternCache.set(normalizedPattern, compiled);
113
+
114
+ return compiled;
115
+ };
116
+
117
+ const getPatternSpecificity = (pattern: string) => {
118
+ const segments = normalisePathPattern(pattern).split('/').filter(Boolean);
119
+ let staticSegments = 0;
120
+ let dynamicSegments = 0;
121
+ let optionalSegments = 0;
122
+ let splatSegments = 0;
123
+
124
+ for (const segment of segments) {
125
+ if (segment === '*') {
126
+ splatSegments++;
127
+ } else if (segment.startsWith(':')) {
128
+ dynamicSegments++;
129
+ if (segment.endsWith('?')) {
130
+ optionalSegments++;
131
+ }
132
+ } else {
133
+ staticSegments++;
134
+ }
135
+ }
136
+
137
+ return {
138
+ staticSegments,
139
+ dynamicSegments,
140
+ optionalSegments,
141
+ splatSegments,
142
+ totalSegments: segments.length,
143
+ };
144
+ };
145
+
146
+ const comparePatternSpecificity = (left: string, right: string): number => {
147
+ const a = getPatternSpecificity(left);
148
+ const b = getPatternSpecificity(right);
149
+
150
+ return (
151
+ b.staticSegments - a.staticSegments ||
152
+ a.splatSegments - b.splatSegments ||
153
+ a.optionalSegments - b.optionalSegments ||
154
+ b.totalSegments - a.totalSegments ||
155
+ a.dynamicSegments - b.dynamicSegments
156
+ );
157
+ };
158
+
159
+ export const haveEqualPatternSpecificity = (
160
+ left: string,
161
+ right: string,
162
+ ): boolean => comparePatternSpecificity(left, right) === 0;
163
+
164
+ export const doPathPatternsOverlap = (left: string, right: string): boolean => {
165
+ const leftSegments = normalisePathPattern(left).split('/').filter(Boolean);
166
+ const rightSegments = normalisePathPattern(right).split('/').filter(Boolean);
167
+ if (leftSegments.length !== rightSegments.length) {
168
+ return false;
169
+ }
170
+
171
+ return leftSegments.every((leftSegment, index) => {
172
+ const rightSegment = rightSegments[index];
173
+ const leftIsDynamic = leftSegment === '*' || leftSegment.startsWith(':');
174
+ const rightIsDynamic = rightSegment === '*' || rightSegment.startsWith(':');
175
+ return leftIsDynamic || rightIsDynamic || leftSegment === rightSegment;
176
+ });
177
+ };
178
+
179
+ const comparePatternNames = (left: string, right: string): number => {
180
+ const normalizedLeft = normalisePathPattern(left);
181
+ const normalizedRight = normalisePathPattern(right);
182
+
183
+ return normalizedLeft < normalizedRight
184
+ ? -1
185
+ : normalizedLeft > normalizedRight
186
+ ? 1
187
+ : 0;
188
+ };
189
+
190
+ export const sortPatternsBySpecificity = <T extends { pattern: string }>(
191
+ patterns: T[],
192
+ ): T[] =>
193
+ patterns
194
+ .map((pattern, index) => ({ pattern, index }))
195
+ .sort(
196
+ (left, right) =>
197
+ comparePatternSpecificity(
198
+ left.pattern.pattern,
199
+ right.pattern.pattern,
200
+ ) ||
201
+ comparePatternNames(left.pattern.pattern, right.pattern.pattern) ||
202
+ left.index - right.index,
203
+ )
204
+ .map(({ pattern }) => pattern);
205
+
206
+ /**
207
+ * `decodeURIComponent` throws `URIError` on malformed percent-encoding
208
+ * (e.g. `%E0%A4%A`), which attacker-controlled request URLs can carry.
209
+ * Treat such segments as undecodable instead of throwing.
210
+ */
211
+ const decodePathParam = (value: string): string | null => {
212
+ try {
213
+ return decodeURIComponent(value);
214
+ } catch {
215
+ return null;
216
+ }
217
+ };
218
+
219
+ const encodeSplatParam = (value: string): string =>
220
+ value.split('/').map(encodeURIComponent).join('/');
221
+
222
+ export const matchPathPattern = (
223
+ pathname: string,
224
+ pattern: string,
225
+ ): Record<string, string> | null => {
226
+ const { names, regexp } = compilePathPattern(pattern);
227
+ const match = regexp.exec(normalisePathname(pathname));
228
+ if (!match) {
229
+ return null;
230
+ }
231
+
232
+ const params: Record<string, string> = {};
233
+ for (let index = 0; index < names.length; index++) {
234
+ const decoded = decodePathParam(match[index + 1] || '');
235
+ if (decoded === null) {
236
+ // Malformed encoding cannot identify a localised route: no match.
237
+ return null;
238
+ }
239
+ Object.defineProperty(params, names[index], {
240
+ configurable: true,
241
+ enumerable: true,
242
+ value: decoded,
243
+ writable: true,
244
+ });
245
+ }
246
+
247
+ return params;
248
+ };
249
+
250
+ export const buildPathFromPattern = (
251
+ pattern: string,
252
+ params: Record<string, string>,
253
+ ): string => {
254
+ const segments = normalisePathPattern(pattern).split('/').filter(Boolean);
255
+ const path = segments
256
+ .map(segment => {
257
+ if (segment.startsWith(':')) {
258
+ const paramName = getParamName(segment);
259
+ const param = Object.hasOwn(params, paramName)
260
+ ? params[paramName]
261
+ : undefined;
262
+ if (param === undefined || param === '') {
263
+ if (segment.endsWith('?')) {
264
+ return '';
265
+ }
266
+ throw new Error(
267
+ `Missing required path parameter "${paramName}" for pattern "${normalisePathPattern(
268
+ pattern,
269
+ )}".`,
270
+ );
271
+ }
272
+ return encodeURIComponent(param);
273
+ }
274
+ if (segment === '*') {
275
+ return encodeSplatParam(params['*'] || '');
276
+ }
277
+ return segment;
278
+ })
279
+ .filter(Boolean)
280
+ .join('/');
281
+
282
+ return `/${path}`;
283
+ };