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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (124) 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/cjs/server-config/serverSource.js +18 -0
  17. package/dist/esm/localisedUrls/config.mjs +11 -0
  18. package/dist/esm/localisedUrls/index.mjs +8 -0
  19. package/dist/esm/localisedUrls/normalise.mjs +37 -0
  20. package/dist/esm/localisedUrls/pathname.mjs +24 -0
  21. package/dist/esm/localisedUrls/patterns.mjs +152 -0
  22. package/dist/esm/localisedUrls/redirect.mjs +57 -0
  23. package/dist/esm/localisedUrls/resolve.mjs +37 -0
  24. package/dist/esm/localisedUrls/routeIdentity.mjs +54 -0
  25. package/dist/esm/localisedUrls/routes.mjs +176 -0
  26. package/dist/esm/localisedUrls/types.mjs +0 -0
  27. package/dist/esm/rendererHead.mjs +14 -5
  28. package/dist/esm/request-policy/policyCore.mjs +1 -1
  29. package/dist/esm/request-policy/transport.mjs +2 -2
  30. package/dist/esm/routerState.mjs +81 -73
  31. package/dist/esm/routerStatePlugin.mjs +62 -11
  32. package/dist/esm/server-config/serverSource.mjs +0 -0
  33. package/dist/esm-node/localisedUrls/config.mjs +12 -0
  34. package/dist/esm-node/localisedUrls/index.mjs +9 -0
  35. package/dist/esm-node/localisedUrls/normalise.mjs +38 -0
  36. package/dist/esm-node/localisedUrls/pathname.mjs +25 -0
  37. package/dist/esm-node/localisedUrls/patterns.mjs +153 -0
  38. package/dist/esm-node/localisedUrls/redirect.mjs +58 -0
  39. package/dist/esm-node/localisedUrls/resolve.mjs +38 -0
  40. package/dist/esm-node/localisedUrls/routeIdentity.mjs +55 -0
  41. package/dist/esm-node/localisedUrls/routes.mjs +177 -0
  42. package/dist/esm-node/localisedUrls/types.mjs +1 -0
  43. package/dist/esm-node/rendererHead.mjs +14 -5
  44. package/dist/esm-node/request-policy/policyCore.mjs +1 -1
  45. package/dist/esm-node/request-policy/transport.mjs +2 -2
  46. package/dist/esm-node/routerState.mjs +81 -73
  47. package/dist/esm-node/routerStatePlugin.mjs +62 -11
  48. package/dist/esm-node/server-config/serverSource.mjs +1 -0
  49. package/dist/types/helmetCompat.d.ts +1 -1
  50. package/dist/types/localisedUrls/config.d.ts +9 -0
  51. package/dist/types/localisedUrls/index.d.ts +10 -0
  52. package/dist/types/localisedUrls/normalise.d.ts +10 -0
  53. package/dist/types/localisedUrls/pathname.d.ts +4 -0
  54. package/dist/types/localisedUrls/patterns.d.ts +11 -0
  55. package/dist/types/localisedUrls/redirect.d.ts +19 -0
  56. package/dist/types/localisedUrls/resolve.d.ts +7 -0
  57. package/dist/types/localisedUrls/routeIdentity.d.ts +22 -0
  58. package/dist/types/localisedUrls/routes.d.ts +3 -0
  59. package/dist/types/localisedUrls/types.d.ts +14 -0
  60. package/dist/types/rendererHead.d.ts +5 -3
  61. package/dist/types/request-policy/types.d.ts +1 -1
  62. package/dist/types/routeHydration.d.ts +2 -2
  63. package/dist/types/routerProvider.d.ts +1 -3
  64. package/dist/types/routerState.d.ts +11 -6
  65. package/dist/types/routerStatePlugin.d.ts +12 -0
  66. package/dist/types/routerStateTypes.d.ts +47 -17
  67. package/dist/types/server-config/index.d.ts +1 -0
  68. package/dist/types/server-config/serverSource.d.ts +16 -0
  69. package/package.json +42 -44
  70. package/src/helmetCompat.ts +1 -1
  71. package/src/localisedUrls/config.ts +18 -0
  72. package/src/localisedUrls/index.ts +25 -0
  73. package/src/localisedUrls/normalise.ts +62 -0
  74. package/src/localisedUrls/pathname.ts +60 -0
  75. package/src/localisedUrls/patterns.ts +283 -0
  76. package/src/localisedUrls/redirect.ts +110 -0
  77. package/src/localisedUrls/resolve.ts +106 -0
  78. package/src/localisedUrls/routeIdentity.ts +83 -0
  79. package/src/localisedUrls/routes.ts +451 -0
  80. package/src/localisedUrls/types.ts +18 -0
  81. package/src/rendererHead.ts +25 -8
  82. package/src/request-policy/policyCore.ts +1 -1
  83. package/src/request-policy/transport.ts +2 -2
  84. package/src/request-policy/types.ts +1 -1
  85. package/src/routeHydration.ts +2 -2
  86. package/src/routerProvider.ts +1 -1
  87. package/src/routerState.ts +127 -115
  88. package/src/routerStatePlugin.ts +106 -10
  89. package/src/routerStateTypes.ts +47 -17
  90. package/src/server-config/index.ts +1 -0
  91. package/src/server-config/serverSource.ts +23 -0
  92. package/dist/cjs/buildIdentity.js +0 -73
  93. package/dist/esm/buildIdentity.mjs +0 -35
  94. package/dist/esm/reactContext.mjs +0 -7
  95. package/dist/esm-node/buildIdentity.mjs +0 -36
  96. package/dist/esm-node/reactContext.mjs +0 -8
  97. package/dist/types/buildIdentity.d.ts +0 -37
  98. package/dist/types/reactContext.d.ts +0 -6
  99. package/rslib.config.mts +0 -19
  100. package/rstest.config.mts +0 -38
  101. package/src/buildIdentity.ts +0 -61
  102. package/src/reactContext.ts +0 -16
  103. package/tests/buildIdentity.test.ts +0 -51
  104. package/tests/contextExtensions.test.ts +0 -27
  105. package/tests/headRuntime.test.tsx +0 -229
  106. package/tests/rendererHead.test.ts +0 -187
  107. package/tests/request-policy/browser-policy.test.ts +0 -108
  108. package/tests/request-policy/client-isolation.test.ts +0 -109
  109. package/tests/request-policy/node-policy.test.ts +0 -447
  110. package/tests/request-policy/policyCore.test.ts +0 -129
  111. package/tests/request-policy/requestContext.test.ts +0 -66
  112. package/tests/request-policy/requestFactory.outbound-contract.test.ts +0 -290
  113. package/tests/request-policy/traceparent.test.ts +0 -52
  114. package/tests/request-policy/transport-retry.test.ts +0 -367
  115. package/tests/routeHydration.test.ts +0 -180
  116. package/tests/routerPrefetchPolicy.test.ts +0 -102
  117. package/tests/routerProvider.test.ts +0 -29
  118. package/tests/routerState.test.ts +0 -78
  119. package/tests/routerStatePlugin.test.ts +0 -63
  120. package/tests/runtimeContextProjection.test.ts +0 -83
  121. package/tests/safeFailure.test.ts +0 -136
  122. package/tests/shellStream.test.ts +0 -122
  123. package/tests/workspaceEvents.test.ts +0 -221
  124. package/tsconfig.json +0 -10
@@ -0,0 +1,37 @@
1
+ import { normalisePathname } from "./normalise.mjs";
2
+ import { buildPathFromPattern, matchPathPattern, sortPatternsBySpecificity } from "./patterns.mjs";
3
+ const getCanonicalCandidates = (localisedUrls)=>sortPatternsBySpecificity(Object.entries(localisedUrls).map(([canonicalPattern, localisedUrlEntry])=>({
4
+ pattern: canonicalPattern,
5
+ canonicalPattern,
6
+ localisedUrlEntry
7
+ })));
8
+ const resolveLocalisedUrlPath = (pathname, languages, localisedUrls, options)=>{
9
+ const normalizedPathname = normalisePathname(pathname);
10
+ const canonicalCandidates = getCanonicalCandidates(localisedUrls);
11
+ const candidates = sortPatternsBySpecificity(canonicalCandidates.flatMap(({ canonicalPattern, localisedUrlEntry })=>{
12
+ const targetPattern = 'localised' === options.mode ? localisedUrlEntry[options.targetLanguage] : canonicalPattern;
13
+ if (!targetPattern) return [];
14
+ const sourcePatterns = new Set([
15
+ canonicalPattern,
16
+ ...languages.map((language)=>localisedUrlEntry[language]).filter((sourcePattern)=>Boolean(sourcePattern))
17
+ ]);
18
+ return Array.from(sourcePatterns, (sourcePattern)=>({
19
+ pattern: sourcePattern,
20
+ sourcePattern,
21
+ targetPattern
22
+ }));
23
+ }));
24
+ for (const { sourcePattern, targetPattern } of candidates){
25
+ const params = matchPathPattern(normalizedPathname, sourcePattern);
26
+ if (params) return buildPathFromPattern(targetPattern, params);
27
+ }
28
+ return normalizedPathname;
29
+ };
30
+ const resolveLocalisedPath = (pathname, targetLanguage, languages, localisedUrls)=>resolveLocalisedUrlPath(pathname, languages, localisedUrls, {
31
+ mode: 'localised',
32
+ targetLanguage
33
+ });
34
+ const resolveCanonicalLocalisedPath = (pathname, languages, localisedUrls)=>resolveLocalisedUrlPath(pathname, languages, localisedUrls, {
35
+ mode: 'canonical'
36
+ });
37
+ export { resolveCanonicalLocalisedPath, resolveLocalisedPath };
@@ -0,0 +1,54 @@
1
+ import { normalisePathPattern } from "./normalise.mjs";
2
+ import { buildPathFromPattern, matchPathPattern } from "./patterns.mjs";
3
+ function rewritePath(url, mappings) {
4
+ for (const { from, to } of mappings){
5
+ const params = matchPathPattern(url.pathname, from);
6
+ if (params) {
7
+ url.pathname = buildPathFromPattern(to, params);
8
+ break;
9
+ }
10
+ }
11
+ return url;
12
+ }
13
+ function createLocalisedRouteRewrite(routes) {
14
+ const input = [];
15
+ const output = [];
16
+ const visit = (nodes, parent)=>{
17
+ for (const route of nodes){
18
+ const fullPath = normalisePathPattern(`${parent}/${route.path ?? ''}`);
19
+ const identity = route.modernLocalisedRoute;
20
+ if (identity?.paths && fullPath.endsWith(identity.canonicalPath)) {
21
+ const prefix = fullPath.slice(0, -identity.canonicalPath.length);
22
+ const hasLocale = prefix.split('/').some((segment)=>/^:(?:lang|locale|language)\??$/.test(segment));
23
+ for (const [language, localisedPath] of Object.entries(identity.paths)){
24
+ const localePrefix = prefix.split('/').map((segment)=>/^:(?:lang|locale|language)\??$/.test(segment) ? language : segment).join('/');
25
+ const canonical = normalisePathPattern(`${localePrefix}/${identity.canonicalPath}`);
26
+ const localised = normalisePathPattern(`${localePrefix}/${localisedPath}`);
27
+ if (canonical !== localised) {
28
+ input.push({
29
+ from: localised,
30
+ to: canonical
31
+ });
32
+ if (hasLocale) output.push({
33
+ from: canonical,
34
+ to: localised
35
+ });
36
+ }
37
+ }
38
+ }
39
+ if (route.children) visit(route.children, fullPath);
40
+ }
41
+ };
42
+ visit(routes, '');
43
+ if (0 === input.length) return;
44
+ const specificity = (pattern)=>pattern.split('/').filter((segment)=>segment && !segment.startsWith(':') && '*' !== segment).length;
45
+ for (const mappings of [
46
+ input,
47
+ output
48
+ ])mappings.sort((a, b)=>specificity(b.from) - specificity(a.from));
49
+ return {
50
+ input: ({ url })=>rewritePath(url, input),
51
+ output: ({ url })=>rewritePath(url, output)
52
+ };
53
+ }
54
+ export { createLocalisedRouteRewrite };
@@ -0,0 +1,176 @@
1
+ import { getLeadingLocaleParam, normalisePathPattern, normaliseRoutePath, stripLeadingLocaleParam } from "./normalise.mjs";
2
+ import { doPathPatternsOverlap, getOrderedPathParamSignature, getPathParamSignature, getPathPatternValidationIssue, getPhysicalPathPattern, haveEqualPatternSpecificity } from "./patterns.mjs";
3
+ const isLocalisableRoutePath = (path)=>{
4
+ const pathWithoutLocale = stripLeadingLocaleParam(path);
5
+ if (!pathWithoutLocale || '/' === pathWithoutLocale || '*' === pathWithoutLocale) return false;
6
+ return true;
7
+ };
8
+ const joinPath = (parentPath, routePath)=>{
9
+ if (!isLocalisableRoutePath(routePath)) return parentPath;
10
+ const segment = normaliseRoutePath(stripLeadingLocaleParam(routePath) || '');
11
+ return normalisePathPattern(`${parentPath}/${segment}`);
12
+ };
13
+ const isFrameworkInternalRoutePath = (canonicalPath)=>'/_mf' === canonicalPath || canonicalPath.startsWith('/_mf/');
14
+ const legalRouteIdPart = (value)=>value.replace(/[^a-zA-Z0-9_$-]+/g, '_').replace(/^_+|_+$/g, '') || 'index';
15
+ const formatParamSignature = (signature)=>signature.length > 0 ? signature.join(', ') : '(none)';
16
+ const validateLocalisedUrlPatterns = (languages, localisedUrls)=>{
17
+ const physicalPatterns = new Map();
18
+ const claimedPatterns = [];
19
+ const claimPhysicalPattern = (sourcePattern, canonicalPath, source)=>{
20
+ const physicalPattern = getPhysicalPathPattern(sourcePattern);
21
+ const existing = physicalPatterns.get(physicalPattern);
22
+ if (existing && existing.canonicalPath !== canonicalPath) throw new Error(`localisedUrls["${existing.canonicalPath}"] ${existing.source} and localisedUrls["${canonicalPath}"] ${source} generate the same physical route pattern "${physicalPattern}". Localised route patterns must identify exactly one canonical route.`);
23
+ const overlapping = claimedPatterns.find((claimed)=>claimed.canonicalPath !== canonicalPath && haveEqualPatternSpecificity(claimed.pattern, sourcePattern) && doPathPatternsOverlap(claimed.pattern, sourcePattern));
24
+ if (overlapping) throw new Error(`localisedUrls["${overlapping.canonicalPath}"] ${overlapping.source} pattern "${overlapping.pattern}" and localisedUrls["${canonicalPath}"] ${source} pattern "${sourcePattern}" are equal-specificity overlapping route patterns. Localised route patterns must identify exactly one canonical route.`);
25
+ physicalPatterns.set(physicalPattern, {
26
+ canonicalPath,
27
+ source
28
+ });
29
+ claimedPatterns.push({
30
+ canonicalPath,
31
+ pattern: sourcePattern,
32
+ source
33
+ });
34
+ };
35
+ for (const [canonicalPath, entry] of Object.entries(localisedUrls).sort(([left], [right])=>left < right ? -1 : left > right ? 1 : 0)){
36
+ const canonicalIssue = getPathPatternValidationIssue(canonicalPath);
37
+ if (canonicalIssue) throw new Error(`localisedUrls["${canonicalPath}"] canonical pattern has ${canonicalIssue}.`);
38
+ const expectedSignature = getPathParamSignature(canonicalPath);
39
+ const expectedOrderedSignature = getOrderedPathParamSignature(canonicalPath);
40
+ claimPhysicalPattern(canonicalPath, canonicalPath, 'canonical pattern');
41
+ for (const language of languages){
42
+ const localisedPattern = entry[language];
43
+ if (!localisedPattern) continue;
44
+ const localisedIssue = getPathPatternValidationIssue(localisedPattern);
45
+ if (localisedIssue) throw new Error(`localisedUrls["${canonicalPath}"].${language} has ${localisedIssue}.`);
46
+ const actualSignature = getPathParamSignature(localisedPattern);
47
+ if (actualSignature.length !== expectedSignature.length || actualSignature.some((parameter, index)=>parameter !== expectedSignature[index])) throw new Error(`localisedUrls["${canonicalPath}"].${language} must use the same parameter signature as "${canonicalPath}": expected ${formatParamSignature(expectedSignature)}; received ${formatParamSignature(actualSignature)}.`);
48
+ const actualOrderedSignature = getOrderedPathParamSignature(localisedPattern);
49
+ if (expectedOrderedSignature.some((parameter)=>'*' === parameter || parameter.endsWith('?')) && actualOrderedSignature.some((parameter, index)=>parameter !== expectedOrderedSignature[index])) throw new Error(`localisedUrls["${canonicalPath}"].${language} must keep optional and splat parameters in canonical order: expected ${formatParamSignature(expectedOrderedSignature)}; received ${formatParamSignature(actualOrderedSignature)}.`);
50
+ claimPhysicalPattern(localisedPattern, canonicalPath, `.${language}`);
51
+ }
52
+ }
53
+ };
54
+ const ensureLocalisedUrlsForPath = (canonicalPath, languages, localisedUrls)=>{
55
+ const entry = localisedUrls[canonicalPath];
56
+ if (!entry) throw new Error(`localisedUrls is enabled, but route "${canonicalPath}" does not define localised URLs for languages: ${languages.join(', ')}. Add localisedUrls["${canonicalPath}"] or set localeDetection.localisedUrls to false.`);
57
+ const missingLanguages = languages.filter((language)=>!entry[language]);
58
+ if (missingLanguages.length > 0) throw new Error(`localisedUrls["${canonicalPath}"] is missing languages: ${missingLanguages.join(', ')}. Every configured language must have a localised URL.`);
59
+ return entry;
60
+ };
61
+ const validateLocalisedUrls = (routes, languages, localisedUrls)=>{
62
+ validateLocalisedUrlPatterns(languages, localisedUrls);
63
+ const visit = (route, parentPath)=>{
64
+ const canonicalPath = joinPath(parentPath, route.path);
65
+ if (isLocalisableRoutePath(route.path) && !isFrameworkInternalRoutePath(canonicalPath)) ensureLocalisedUrlsForPath(canonicalPath, languages, localisedUrls);
66
+ if ('children' in route && route.children) route.children.forEach((child)=>visit(child, canonicalPath));
67
+ };
68
+ routes.forEach((route)=>visit(route, ''));
69
+ };
70
+ const getLocalisedRouteIdSuffixes = (paths)=>{
71
+ const usedSuffixes = new Set();
72
+ return paths.map((path, index)=>{
73
+ if (0 === index) return;
74
+ const baseSuffix = legalRouteIdPart(path);
75
+ let suffix = baseSuffix;
76
+ let disambiguator = 2;
77
+ while(usedSuffixes.has(suffix))suffix = `${baseSuffix}_${disambiguator++}`;
78
+ usedSuffixes.add(suffix);
79
+ return suffix;
80
+ });
81
+ };
82
+ const getLocalisedRoutePaths = (canonicalPath, parentLocalisedPaths, languages, entry)=>{
83
+ const paths = languages.map((language)=>{
84
+ const fullPath = normalisePathPattern(entry[language]);
85
+ const parentPath = normalisePathPattern(parentLocalisedPaths[language] || '/');
86
+ if ('/' === parentPath) return normaliseRoutePath(fullPath) || void 0;
87
+ const parentPrefix = `${parentPath}/`;
88
+ if (!fullPath.startsWith(parentPrefix)) throw new Error(`localisedUrls["${canonicalPath}"].${language} must be nested under "${parentPath}" because its parent route is localised there.`);
89
+ return normaliseRoutePath(fullPath.slice(parentPath.length));
90
+ });
91
+ const uniquePaths = Array.from(new Set(paths.filter(Boolean)));
92
+ return uniquePaths;
93
+ };
94
+ const transformLocalisedRoute = (route, parentCanonicalPath, parentLocalisedPaths, languages, localisedUrls, projection)=>{
95
+ const isSplat = '*' === stripLeadingLocaleParam(route.path);
96
+ const canonicalPath = isSplat ? normalisePathPattern(`${parentCanonicalPath}/*`) : joinPath(parentCanonicalPath, route.path);
97
+ const localisedUrlEntry = isLocalisableRoutePath(route.path) && !isFrameworkInternalRoutePath(canonicalPath) ? ensureLocalisedUrlsForPath(canonicalPath, languages, localisedUrls) : void 0;
98
+ const routeLocalisedPaths = localisedUrlEntry ? languages.reduce((acc, language)=>{
99
+ acc[language] = normalisePathPattern(localisedUrlEntry[language]);
100
+ return acc;
101
+ }, {}) : isSplat ? Object.fromEntries(Object.entries(parentLocalisedPaths).map(([language, path])=>[
102
+ language,
103
+ normalisePathPattern(`${path}/*`)
104
+ ])) : parentLocalisedPaths;
105
+ const children = 'children' in route && route.children ? route.children.flatMap((child)=>transformLocalisedRoute(child, canonicalPath, routeLocalisedPaths, languages, localisedUrls, projection)) : void 0;
106
+ const baseRoute = {
107
+ ...route,
108
+ ...!isFrameworkInternalRoutePath(canonicalPath) ? {
109
+ modernLocalisedRoute: {
110
+ id: route.id,
111
+ path: route.path,
112
+ canonicalPath,
113
+ paths: localisedUrlEntry ?? (isSplat ? routeLocalisedPaths : void 0)
114
+ }
115
+ } : {},
116
+ ...children ? {
117
+ children
118
+ } : {}
119
+ };
120
+ if (!localisedUrlEntry) return [
121
+ baseRoute
122
+ ];
123
+ const localisedPaths = getLocalisedRoutePaths(canonicalPath, parentLocalisedPaths, languages, localisedUrlEntry);
124
+ if ('canonical' === projection) return [
125
+ baseRoute
126
+ ];
127
+ const leadingLocaleParam = getLeadingLocaleParam(route.path);
128
+ const routeIdPaths = leadingLocaleParam ? localisedPaths.map((path)=>normaliseRoutePath(`${leadingLocaleParam}/${path}`)) : localisedPaths;
129
+ const routeIdSuffixes = getLocalisedRouteIdSuffixes(routeIdPaths);
130
+ return localisedPaths.map((localisedPath, index)=>cloneRouteWithLocalisedPath(baseRoute, localisedPath, routeIdSuffixes[index], canonicalPath));
131
+ };
132
+ const suffixRouteIds = (route, suffix)=>{
133
+ const children = 'children' in route && route.children ? route.children.map((child)=>suffixRouteIds(child, suffix)) : void 0;
134
+ return {
135
+ ...route,
136
+ ...route.id ? {
137
+ id: `${route.id}__localised_${suffix}`
138
+ } : {},
139
+ ...children ? {
140
+ children
141
+ } : {}
142
+ };
143
+ };
144
+ const collectRouteIdCounts = (routes, counts = new Map())=>{
145
+ for (const route of routes){
146
+ if (route.id) counts.set(route.id, (counts.get(route.id) ?? 0) + 1);
147
+ if ('children' in route && route.children) collectRouteIdCounts(route.children, counts);
148
+ }
149
+ return counts;
150
+ };
151
+ const validateNoNewRouteIdCollisions = (sourceRoutes, localisedRoutes)=>{
152
+ const sourceCounts = collectRouteIdCounts(sourceRoutes);
153
+ const localisedCounts = collectRouteIdCounts(localisedRoutes);
154
+ for (const [routeId, count] of localisedCounts)if (count > 1 && count > (sourceCounts.get(routeId) ?? 0)) throw new Error(`Localised route expansion generated duplicate route ID "${routeId}". Change the source route ID or localised path so every generated route remains identifiable.`);
155
+ };
156
+ const cloneRouteWithLocalisedPath = (route, path, routeIdSuffix, canonicalPath)=>{
157
+ const leadingLocaleParam = getLeadingLocaleParam(route.path);
158
+ const localisedPath = leadingLocaleParam ? normaliseRoutePath(`${leadingLocaleParam}/${path}`) : path;
159
+ const routeWithPath = {
160
+ ...route,
161
+ path: localisedPath
162
+ };
163
+ routeWithPath.modernCanonicalPath = canonicalPath;
164
+ return routeIdSuffix ? suffixRouteIds(routeWithPath, routeIdSuffix) : routeWithPath;
165
+ };
166
+ const applyLocalisedUrlsToRoutes = (routes, languages, localisedUrls, projection = 'physical')=>{
167
+ const rootLocalisedPaths = languages.reduce((acc, language)=>{
168
+ acc[language] = '/';
169
+ return acc;
170
+ }, {});
171
+ validateLocalisedUrls(routes, languages, localisedUrls);
172
+ const localisedRoutes = routes.flatMap((route)=>transformLocalisedRoute(route, '', rootLocalisedPaths, languages, localisedUrls, projection));
173
+ validateNoNewRouteIdCollisions(routes, localisedRoutes);
174
+ return localisedRoutes;
175
+ };
176
+ export { applyLocalisedUrlsToRoutes, validateLocalisedUrls };
File without changes
@@ -4,6 +4,7 @@ const MARKER_PREFIX = `<template ${MARKER_ATTRIBUTE}="`;
4
4
  const MARKER_SUFFIX = '"></template>';
5
5
  const RECORD_ID_WIDTH = 12;
6
6
  const MARKER_LENGTH = MARKER_PREFIX.length + 1 + 36 + RECORD_ID_WIDTH + MARKER_SUFFIX.length;
7
+ const LATE_HEAD_MESSAGE = "<Helmet> rendered in a boundary that completed after the shell; head tags dropped. Move it above the Suspense boundary or set server.ssrByEntries[entry].mode to 'string'.";
7
8
  const HEAD_STATE = Symbol('modern.rendererHead');
8
9
  const getState = (context)=>{
9
10
  const headContext = context;
@@ -24,7 +25,12 @@ const createToken = (transaction)=>{
24
25
  transaction.nextRecordId += 1;
25
26
  return token;
26
27
  };
27
- const beginHeadRender = (context)=>{
28
+ const dropLateHead = (transaction)=>{
29
+ if (transaction.lateHeadReported) return;
30
+ transaction.lateHeadReported = true;
31
+ transaction.reportLateHead(LATE_HEAD_MESSAGE);
32
+ };
33
+ const beginHeadRender = (context, reportLateHead)=>{
28
34
  const state = getState(context);
29
35
  state.transaction = {
30
36
  recordsByToken: new Map(),
@@ -33,7 +39,9 @@ const beginHeadRender = (context)=>{
33
39
  nextRecordId: 0,
34
40
  nonce: globalThis.crypto.randomUUID(),
35
41
  previousRecords: state.publishedRecords,
36
- sealed: false
42
+ sealed: false,
43
+ reportLateHead,
44
+ lateHeadReported: false
37
45
  };
38
46
  state.publish?.([]);
39
47
  };
@@ -44,7 +52,6 @@ const collectHeadRecord = (context, createRecord, publish)=>{
44
52
  const hadPublisher = void 0 !== state.publish;
45
53
  state.publish = (records)=>publish(records);
46
54
  if (!hadPublisher) state.publish([]);
47
- if (transaction.sealed) return null;
48
55
  const token = createToken(transaction);
49
56
  transaction.recordsByToken.set(token, createRecord());
50
57
  return {
@@ -74,7 +81,9 @@ const consumeMarkers = (context, html)=>{
74
81
  const token = html.slice(tokenStart, end);
75
82
  if (transaction.recordsByToken.has(token)) {
76
83
  stripped += html.slice(cursor, start);
77
- if (!transaction.sealed && !transaction.committedTokens.has(token)) {
84
+ if (transaction.sealed) {
85
+ if (!transaction.committedTokens.has(token)) dropLateHead(transaction);
86
+ } else if (!transaction.committedTokens.has(token)) {
78
87
  transaction.committedTokens.add(token);
79
88
  transaction.committedRecords.push(transaction.recordsByToken.get(token));
80
89
  }
@@ -159,4 +168,4 @@ const createWebHeadMarkerStripper = (context)=>{
159
168
  }
160
169
  });
161
170
  };
162
- export { abortHeadRender, beginHeadRender, collectHeadRecord, collectHeadState, completeHeadRender, createHeadChunkProcessor, createWebHeadMarkerStripper, finishHeadRender, publishHeadRender };
171
+ export { LATE_HEAD_MESSAGE, abortHeadRender, beginHeadRender, collectHeadRecord, collectHeadState, completeHeadRender, createHeadChunkProcessor, createWebHeadMarkerStripper, finishHeadRender, publishHeadRender };
@@ -30,7 +30,7 @@ const toOrigin = (value)=>{
30
30
  if (!value) return;
31
31
  try {
32
32
  return new URL(value).origin;
33
- } catch (error) {
33
+ } catch {
34
34
  return;
35
35
  }
36
36
  };
@@ -58,7 +58,7 @@ const shouldRetryWithDefaults = (method, statusCode, error, retryableStatusCodes
58
58
  const shouldRetry = (retryOptions, context, retryableStatusCodes)=>{
59
59
  if ('function' == typeof retryOptions?.shouldRetry) try {
60
60
  return retryOptions.shouldRetry(context);
61
- } catch (error) {
61
+ } catch {
62
62
  return false;
63
63
  }
64
64
  return shouldRetryWithDefaults(context.method, context.statusCode, context.error, retryableStatusCodes);
@@ -75,7 +75,7 @@ const emitDegradedEvent = (transport, event)=>{
75
75
  if ('function' != typeof transport?.onDegraded) return;
76
76
  try {
77
77
  transport.onDegraded(event);
78
- } catch (error) {}
78
+ } catch {}
79
79
  };
80
80
  const withTimeout = async (promise, timeoutMs, signalBuilder)=>{
81
81
  if (!timeoutMs || timeoutMs <= 0) {
@@ -7,99 +7,107 @@ function getRouterRuntimeState(runtimeContext) {
7
7
  function getRouterServerSnapshot(runtimeContext) {
8
8
  return routerServerSnapshotExtension.get(runtimeContext);
9
9
  }
10
- function toHydrationScripts(state) {
11
- if (state.hydrationScripts?.length) return state.hydrationScripts;
12
- return state.hydrationScript ? [
13
- state.hydrationScript
14
- ] : void 0;
15
- }
16
- function getMatchedRouteIdsFromMatches(matches) {
17
- const routeIds = matches?.map((match)=>match.assetRouteId ?? match.routeId).filter((routeId)=>'string' == typeof routeId);
18
- return routeIds?.length ? routeIds : void 0;
19
- }
20
- function createRouterServerSnapshot(state) {
21
- const hydrationScripts = toHydrationScripts(state);
22
- const matchedRouteIds = state.matchedRouteIds ?? getMatchedRouteIdsFromMatches(state.matches);
23
- return {
24
- ...state,
25
- ...hydrationScripts?.length ? {
26
- hydrationScript: state.hydrationScript ?? hydrationScripts[0],
27
- hydrationScripts
10
+ function createRouterServerSnapshot(snapshot) {
11
+ const matches = snapshot.matches?.map((match)=>Object.freeze({
12
+ ...match,
13
+ ...match.params ? {
14
+ params: Object.freeze({
15
+ ...match.params
16
+ })
17
+ } : {}
18
+ }));
19
+ const matchedRouteIds = snapshot.matchedRouteIds ?? matches?.map((match)=>match.assetRouteId ?? match.routeId);
20
+ return Object.freeze({
21
+ ...snapshot,
22
+ ...snapshot.hydrationScripts ? {
23
+ hydrationScripts: Object.freeze([
24
+ ...snapshot.hydrationScripts
25
+ ])
28
26
  } : {},
29
27
  ...matchedRouteIds ? {
30
- matchedRouteIds
31
- } : {}
32
- };
33
- }
34
- function createRouterRuntimeState(state) {
35
- const hasSnapshotState = Boolean(state.serverSnapshot) || Boolean(state.hydrationScript) || Boolean(state.hydrationScripts?.length) || Boolean(state.matchedRouteIds?.length) || Boolean(state.matches?.length);
36
- const serverSnapshot = state.serverSnapshot ? createRouterServerSnapshot({
37
- ...state.serverSnapshot,
38
- framework: state.serverSnapshot.framework ?? state.framework,
39
- basename: state.serverSnapshot.basename ?? state.basename,
40
- hydrationScript: state.serverSnapshot.hydrationScript ?? state.hydrationScript,
41
- hydrationScripts: state.serverSnapshot.hydrationScripts ?? state.hydrationScripts,
42
- matchedRouteIds: state.serverSnapshot.matchedRouteIds ?? state.matchedRouteIds,
43
- matches: state.serverSnapshot.matches ?? state.matches
44
- }) : hasSnapshotState ? createRouterServerSnapshot({
45
- framework: state.framework,
46
- basename: state.basename,
47
- hydrationScript: state.hydrationScript,
48
- hydrationScripts: state.hydrationScripts,
49
- matchedRouteIds: state.matchedRouteIds,
50
- matches: state.matches
51
- }) : void 0;
52
- const hydrationScripts = toHydrationScripts({
53
- hydrationScript: state.hydrationScript ?? serverSnapshot?.hydrationScript,
54
- hydrationScripts: state.hydrationScripts ?? serverSnapshot?.hydrationScripts
55
- });
56
- const matchedRouteIds = state.matchedRouteIds ?? serverSnapshot?.matchedRouteIds ?? getMatchedRouteIdsFromMatches(state.matches);
57
- return {
58
- ...state,
59
- ...hydrationScripts?.length ? {
60
- hydrationScript: state.hydrationScript ?? hydrationScripts[0],
61
- hydrationScripts
28
+ matchedRouteIds: Object.freeze([
29
+ ...matchedRouteIds
30
+ ])
62
31
  } : {},
63
- ...matchedRouteIds ? {
64
- matchedRouteIds
32
+ ...matches ? {
33
+ matches: Object.freeze(matches)
65
34
  } : {},
66
- ...serverSnapshot ? {
67
- serverSnapshot
35
+ ...snapshot.errors ? {
36
+ errors: Object.freeze({
37
+ ...snapshot.errors
38
+ })
39
+ } : {},
40
+ ...snapshot.routerData ? {
41
+ routerData: Object.freeze({
42
+ ...snapshot.routerData,
43
+ ...snapshot.routerData.loaderData ? {
44
+ loaderData: Object.freeze({
45
+ ...snapshot.routerData.loaderData
46
+ })
47
+ } : {},
48
+ ...snapshot.routerData.errors ? {
49
+ errors: Object.freeze({
50
+ ...snapshot.routerData.errors
51
+ })
52
+ } : {}
53
+ })
68
54
  } : {}
55
+ });
56
+ }
57
+ const routerRuntimeStateListeners = new WeakMap();
58
+ function subscribeRouterRuntimeState(runtimeContext, listener) {
59
+ if (!runtimeContext || 'object' != typeof runtimeContext) return ()=>void 0;
60
+ let listeners = routerRuntimeStateListeners.get(runtimeContext);
61
+ if (!listeners) {
62
+ listeners = new Set();
63
+ routerRuntimeStateListeners.set(runtimeContext, listeners);
64
+ }
65
+ listeners.add(listener);
66
+ return ()=>{
67
+ listeners?.delete(listener);
69
68
  };
70
69
  }
70
+ const pendingRouterRuntimeStateNotifications = new WeakSet();
71
+ function notifyRouterRuntimeState(runtimeContext) {
72
+ const listeners = routerRuntimeStateListeners.get(runtimeContext);
73
+ if (!listeners?.size) return;
74
+ if (pendingRouterRuntimeStateNotifications.has(runtimeContext)) return;
75
+ pendingRouterRuntimeStateNotifications.add(runtimeContext);
76
+ const deliver = ()=>{
77
+ pendingRouterRuntimeStateNotifications.delete(runtimeContext);
78
+ const current = routerRuntimeStateListeners.get(runtimeContext);
79
+ if (!current?.size) return;
80
+ for (const listener of [
81
+ ...current
82
+ ])try {
83
+ listener();
84
+ } catch {}
85
+ };
86
+ if ('function' == typeof queueMicrotask) queueMicrotask(deliver);
87
+ else setTimeout(deliver, 0);
88
+ }
71
89
  function applyRouterRuntimeState(runtimeContext, state) {
72
- const normalized = createRouterRuntimeState(state);
73
- routerRuntimeStateExtension.set(runtimeContext, normalized);
74
- if (normalized.serverSnapshot) routerServerSnapshotExtension.set(runtimeContext, normalized.serverSnapshot);
90
+ const previous = routerRuntimeStateExtension.get(runtimeContext);
91
+ routerRuntimeStateExtension.set(runtimeContext, state);
92
+ if (previous?.instance !== state.instance || previous?.framework !== state.framework || previous?.navigation !== state.navigation) notifyRouterRuntimeState(runtimeContext);
75
93
  return runtimeContext;
76
94
  }
77
95
  function applyRouterServerPrepareResult(runtimeContext, result) {
78
- const state = createRouterRuntimeState({
96
+ if (result.snapshot) routerServerSnapshotExtension.set(runtimeContext, createRouterServerSnapshot(result.snapshot));
97
+ return applyRouterRuntimeState(runtimeContext, {
79
98
  ...result.state,
80
- cleanup: result.cleanup ?? result.state.cleanup,
81
- serverSnapshot: result.snapshot ?? result.state.serverSnapshot
99
+ cleanup: result.cleanup ?? result.state.cleanup
82
100
  });
83
- applyRouterRuntimeState(runtimeContext, state);
84
- return runtimeContext;
85
101
  }
86
102
  function getRouterHydrationScripts(runtimeContext) {
87
- const serverSnapshot = getRouterServerSnapshot(runtimeContext);
88
- const runtimeState = getRouterRuntimeState(runtimeContext);
89
- return serverSnapshot?.hydrationScripts ?? toHydrationScripts({
90
- hydrationScript: serverSnapshot?.hydrationScript
91
- }) ?? runtimeState?.hydrationScripts ?? toHydrationScripts({
92
- hydrationScript: runtimeState?.hydrationScript
93
- }) ?? [];
103
+ return getRouterServerSnapshot(runtimeContext)?.hydrationScripts ?? [];
94
104
  }
95
105
  function getRouterMatchedRouteIds(runtimeContext) {
96
- const serverSnapshot = getRouterServerSnapshot(runtimeContext);
97
- const runtimeState = getRouterRuntimeState(runtimeContext);
98
- return serverSnapshot?.matchedRouteIds ?? getMatchedRouteIdsFromMatches(serverSnapshot?.matches) ?? runtimeState?.matchedRouteIds ?? getMatchedRouteIdsFromMatches(runtimeState?.matches);
106
+ return getRouterServerSnapshot(runtimeContext)?.matchedRouteIds;
99
107
  }
100
108
  async function cleanupRouterRuntimeState(runtimeContext) {
101
109
  try {
102
110
  await getRouterRuntimeState(runtimeContext)?.cleanup?.();
103
111
  } catch {}
104
112
  }
105
- export { applyRouterRuntimeState, applyRouterServerPrepareResult, cleanupRouterRuntimeState, createRouterRuntimeState, createRouterServerSnapshot, getRouterHydrationScripts, getRouterMatchedRouteIds, getRouterRuntimeState, getRouterServerSnapshot };
113
+ export { applyRouterRuntimeState, applyRouterServerPrepareResult, cleanupRouterRuntimeState, createRouterServerSnapshot, getRouterHydrationScripts, getRouterMatchedRouteIds, getRouterRuntimeState, getRouterServerSnapshot, subscribeRouterRuntimeState };
@@ -1,20 +1,63 @@
1
1
  import { createRouterPrefetchPolicy } from "./routerPrefetchPolicy.mjs";
2
- import { applyRouterRuntimeState, createRouterServerSnapshot } from "./routerState.mjs";
2
+ import { applyRouterRuntimeState, applyRouterServerPrepareResult, getRouterRuntimeState, getRouterServerSnapshot } from "./routerState.mjs";
3
+ const ROUTER_CLEANUP_ERROR = 'An error occurs during router runtime cleanup';
4
+ const installedRouterPolicies = new WeakSet();
5
+ function createReactRouterNavigation(router, Link) {
6
+ let state;
7
+ let snapshot;
8
+ return {
9
+ Link,
10
+ getSnapshot () {
11
+ if (state !== router.state) {
12
+ state = router.state;
13
+ snapshot = {
14
+ location: state.location,
15
+ params: Object.assign({}, ...state.matches.map((match)=>match.params))
16
+ };
17
+ }
18
+ return snapshot;
19
+ },
20
+ subscribe: (listener)=>router.subscribe(listener),
21
+ navigate: (href, options)=>router.navigate(href, options)
22
+ };
23
+ }
3
24
  function createRouterStatePlugin({ registryHooks }) {
4
25
  return {
5
26
  name: '@modern-js/router-runtime-policy',
6
27
  registryHooks,
7
28
  setup (api) {
29
+ if (installedRouterPolicies.has(api)) return;
30
+ installedRouterPolicies.add(api);
8
31
  api.onBeforeRender((context)=>{
9
32
  const runtimeContext = context;
10
33
  runtimeContext.linkPrefetchPolicy ??= createRouterPrefetchPolicy();
11
34
  });
35
+ api.onRenderPrepared((info)=>{
36
+ const snapshot = getRouterServerSnapshot(info.runtimeContext);
37
+ if (!snapshot) return info;
38
+ return {
39
+ ...info,
40
+ routerResult: {
41
+ statusCode: snapshot.statusCode ?? info.routerResult?.statusCode,
42
+ errors: snapshot.errors ?? info.routerResult?.errors
43
+ }
44
+ };
45
+ });
46
+ api.onRequestEnd(async ({ runtimeContext })=>{
47
+ try {
48
+ await getRouterRuntimeState(runtimeContext)?.cleanup?.();
49
+ } catch (error) {
50
+ const { ssrContext } = runtimeContext;
51
+ if (!ssrContext) throw error;
52
+ ssrContext.onError(error, ROUTER_CLEANUP_ERROR);
53
+ }
54
+ });
12
55
  api.onAfterCreateRouter((event)=>{
13
56
  if ('react-router' !== event.framework) return;
14
57
  if ('ssr-prepare' === event.phase) {
15
58
  const { routerContext } = event.runtimeContext;
16
59
  if (!routerContext) return;
17
- const serverSnapshot = createRouterServerSnapshot({
60
+ const snapshot = {
18
61
  framework: event.framework,
19
62
  basename: event.basename,
20
63
  statusCode: routerContext.statusCode,
@@ -28,21 +71,29 @@ function createRouterStatePlugin({ registryHooks }) {
28
71
  routeId: match.route.id
29
72
  }
30
73
  ] : [])
74
+ };
75
+ applyRouterServerPrepareResult(event.runtimeContext, {
76
+ snapshot,
77
+ state: {
78
+ framework: event.framework,
79
+ basename: event.basename,
80
+ instance: event.router
81
+ }
31
82
  });
83
+ } else if ('client-create' === event.phase) {
84
+ const router = event.router;
85
+ const { router: api } = event.runtimeContext;
32
86
  applyRouterRuntimeState(event.runtimeContext, {
33
87
  framework: event.framework,
34
88
  basename: event.basename,
35
- instance: event.router,
36
- matchedRouteIds: serverSnapshot.matchedRouteIds,
37
- serverSnapshot
89
+ instance: router,
90
+ ...api?.Link ? {
91
+ navigation: createReactRouterNavigation(router, api.Link)
92
+ } : {}
38
93
  });
39
- } else if ('client-create' === event.phase) applyRouterRuntimeState(event.runtimeContext, {
40
- framework: event.framework,
41
- basename: event.basename,
42
- instance: event.router
43
- });
94
+ }
44
95
  });
45
96
  }
46
97
  };
47
98
  }
48
- export { createRouterStatePlugin };
99
+ export { ROUTER_CLEANUP_ERROR, createRouterStatePlugin };
File without changes
@@ -0,0 +1,12 @@
1
+ import "node:module";
2
+ const resolveLocalisedUrlsConfig = (option)=>{
3
+ if (option && 'object' == typeof option && Object.keys(option).length > 0) return {
4
+ enabled: true,
5
+ map: option
6
+ };
7
+ return {
8
+ enabled: false,
9
+ map: {}
10
+ };
11
+ };
12
+ export { resolveLocalisedUrlsConfig };