@bleedingdev/modern-js-runtime-extensions 3.9.0-ultramodern.1 → 3.9.0-ultramodern.10
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/dist/cjs/buildIdentity.js +73 -0
- package/dist/cjs/contextExtensions.js +74 -0
- package/dist/cjs/headRuntime.js +91 -0
- package/dist/cjs/helmetContext.js +54 -0
- package/dist/cjs/index.js +18 -4
- package/dist/cjs/localisedLoaderIdentity.js +51 -0
- package/dist/cjs/prefetchPolicy.js +52 -0
- package/dist/cjs/reactContext.js +45 -0
- package/dist/cjs/request-policy/browser.js +139 -0
- package/dist/cjs/request-policy/client.js +234 -0
- package/dist/cjs/request-policy/node.js +149 -0
- package/dist/cjs/request-policy/policyCore.js +266 -0
- package/dist/cjs/request-policy/requestContext.js +137 -0
- package/dist/cjs/request-policy/traceparent.js +56 -0
- package/dist/cjs/request-policy/transport.js +234 -0
- package/dist/cjs/request-policy/types.js +57 -0
- package/dist/cjs/routeHydration.js +127 -0
- package/dist/cjs/routerPrefetchPolicy.js +153 -0
- package/dist/cjs/routerProvider.js +105 -0
- package/dist/cjs/routerState.js +204 -0
- package/dist/cjs/routerStatePlugin.js +86 -0
- package/dist/cjs/routerStateTypes.js +18 -0
- package/dist/cjs/rsc-disabled/rscDisabledClientBrowserRuntime.js +69 -0
- package/dist/cjs/rsc-disabled/rscDisabledClientEdgeRuntime.js +61 -0
- package/dist/cjs/rsc-disabled/rscDisabledClientNodeRuntime.js +65 -0
- package/dist/cjs/rsc-disabled/rscDisabledRuntimeError.js +42 -0
- package/dist/cjs/rsc-disabled/rscDisabledServerEdgeRuntime.js +93 -0
- package/dist/cjs/rsc-disabled/rscDisabledServerNodeRuntime.js +101 -0
- package/dist/cjs/runtimeContextProjection.js +112 -0
- package/dist/cjs/server-config/bffRuntime.js +18 -0
- package/dist/cjs/server-config/index.js +18 -0
- package/dist/cjs/server-config/serverTelemetry.js +18 -0
- package/dist/cjs/shellStream.js +34 -2
- package/dist/cjs/workspaceEvents.js +159 -0
- package/dist/esm/buildIdentity.mjs +35 -0
- package/dist/esm/contextExtensions.mjs +33 -0
- package/dist/esm/headRuntime.mjs +43 -0
- package/dist/esm/helmetContext.mjs +13 -0
- package/dist/esm/index.mjs +2 -0
- package/dist/esm/localisedLoaderIdentity.mjs +13 -0
- package/dist/esm/prefetchPolicy.mjs +11 -0
- package/dist/esm/reactContext.mjs +7 -0
- package/dist/esm/request-policy/browser.mjs +11 -0
- package/dist/esm/request-policy/client.mjs +195 -0
- package/dist/esm/request-policy/policyCore.mjs +171 -0
- package/dist/esm/request-policy/requestContext.mjs +75 -0
- package/dist/esm/request-policy/traceparent.mjs +18 -0
- package/dist/esm/request-policy/transport.mjs +196 -0
- package/dist/esm/request-policy/types.mjs +10 -0
- package/dist/esm/routeHydration.mjs +77 -0
- package/dist/esm/routerPrefetchPolicy.mjs +115 -0
- package/dist/esm/routerProvider.mjs +58 -0
- package/dist/esm/routerState.mjs +139 -0
- package/dist/esm/routerStatePlugin.mjs +48 -0
- package/dist/esm/routerStateTypes.mjs +0 -0
- package/dist/esm/rsc-disabled/rscDisabledClientBrowserRuntime.mjs +10 -0
- package/dist/esm/rsc-disabled/rscDisabledClientEdgeRuntime.mjs +8 -0
- package/dist/esm/rsc-disabled/rscDisabledClientNodeRuntime.mjs +9 -0
- package/dist/esm/rsc-disabled/rscDisabledRuntimeError.mjs +4 -0
- package/dist/esm/rsc-disabled/rscDisabledServerEdgeRuntime.mjs +16 -0
- package/dist/esm/rsc-disabled/rscDisabledServerNodeRuntime.mjs +18 -0
- package/dist/esm/runtimeContextProjection.mjs +74 -0
- package/dist/esm/server-config/bffRuntime.mjs +0 -0
- package/dist/esm/server-config/index.mjs +0 -0
- package/dist/esm/server-config/serverTelemetry.mjs +0 -0
- package/dist/esm/shellStream.mjs +34 -2
- package/dist/esm/workspaceEvents.mjs +66 -0
- package/dist/esm-node/buildIdentity.mjs +36 -0
- package/dist/esm-node/contextExtensions.mjs +34 -0
- package/dist/esm-node/headRuntime.mjs +44 -0
- package/dist/esm-node/helmetContext.mjs +14 -0
- package/dist/esm-node/index.mjs +2 -0
- package/dist/esm-node/localisedLoaderIdentity.mjs +14 -0
- package/dist/esm-node/prefetchPolicy.mjs +12 -0
- package/dist/esm-node/reactContext.mjs +8 -0
- package/dist/esm-node/request-policy/browser.mjs +12 -0
- package/dist/esm-node/request-policy/client.mjs +196 -0
- package/dist/esm-node/request-policy/node.mjs +22 -0
- package/dist/esm-node/request-policy/policyCore.mjs +172 -0
- package/dist/esm-node/request-policy/requestContext.mjs +76 -0
- package/dist/esm-node/request-policy/traceparent.mjs +19 -0
- package/dist/esm-node/request-policy/transport.mjs +197 -0
- package/dist/esm-node/request-policy/types.mjs +11 -0
- package/dist/esm-node/routeHydration.mjs +78 -0
- package/dist/esm-node/routerPrefetchPolicy.mjs +116 -0
- package/dist/esm-node/routerProvider.mjs +59 -0
- package/dist/esm-node/routerState.mjs +140 -0
- package/dist/esm-node/routerStatePlugin.mjs +49 -0
- package/dist/esm-node/routerStateTypes.mjs +1 -0
- package/dist/esm-node/rsc-disabled/rscDisabledClientBrowserRuntime.mjs +11 -0
- package/dist/esm-node/rsc-disabled/rscDisabledClientEdgeRuntime.mjs +9 -0
- package/dist/esm-node/rsc-disabled/rscDisabledClientNodeRuntime.mjs +10 -0
- package/dist/esm-node/rsc-disabled/rscDisabledRuntimeError.mjs +5 -0
- package/dist/esm-node/rsc-disabled/rscDisabledServerEdgeRuntime.mjs +17 -0
- package/dist/esm-node/rsc-disabled/rscDisabledServerNodeRuntime.mjs +19 -0
- package/dist/esm-node/runtimeContextProjection.mjs +75 -0
- package/dist/esm-node/server-config/bffRuntime.mjs +1 -0
- package/dist/esm-node/server-config/index.mjs +1 -0
- package/dist/esm-node/server-config/serverTelemetry.mjs +1 -0
- package/dist/esm-node/shellStream.mjs +34 -2
- package/dist/esm-node/workspaceEvents.mjs +67 -0
- package/dist/types/buildIdentity.d.ts +37 -0
- package/dist/types/contextExtensions.d.ts +34 -0
- package/dist/types/headRuntime.d.ts +12 -0
- package/dist/types/helmetContext.d.ts +10 -0
- package/dist/types/index.d.ts +2 -0
- package/dist/types/localisedLoaderIdentity.d.ts +10 -0
- package/dist/types/prefetchPolicy.d.ts +4 -0
- package/dist/types/reactContext.d.ts +6 -0
- package/dist/types/request-policy/browser.d.ts +10 -0
- package/dist/types/request-policy/client.d.ts +14 -0
- package/dist/types/request-policy/node.d.ts +10 -0
- package/dist/types/request-policy/policyCore.d.ts +107 -0
- package/dist/types/request-policy/requestContext.d.ts +22 -0
- package/dist/types/request-policy/traceparent.d.ts +10 -0
- package/dist/types/request-policy/transport.d.ts +12 -0
- package/dist/types/request-policy/types.d.ts +144 -0
- package/dist/types/routeHydration.d.ts +24 -0
- package/dist/types/routerPrefetchPolicy.d.ts +28 -0
- package/dist/types/routerProvider.d.ts +55 -0
- package/dist/types/routerState.d.ts +18 -0
- package/dist/types/routerStatePlugin.d.ts +19 -0
- package/dist/types/routerStateTypes.d.ts +40 -0
- package/dist/types/rsc-disabled/rscDisabledClientBrowserRuntime.d.ts +9 -0
- package/dist/types/rsc-disabled/rscDisabledClientEdgeRuntime.d.ts +7 -0
- package/dist/types/rsc-disabled/rscDisabledClientNodeRuntime.d.ts +8 -0
- package/dist/types/rsc-disabled/rscDisabledRuntimeError.d.ts +1 -0
- package/dist/types/rsc-disabled/rscDisabledServerEdgeRuntime.d.ts +15 -0
- package/dist/types/rsc-disabled/rscDisabledServerNodeRuntime.d.ts +17 -0
- package/dist/types/runtimeContextProjection.d.ts +30 -0
- package/dist/types/server-config/bffRuntime.d.ts +122 -0
- package/dist/types/server-config/index.d.ts +2 -0
- package/dist/types/server-config/serverTelemetry.d.ts +322 -0
- package/dist/types/workspaceEvents.d.ts +62 -0
- package/package.json +239 -14
- package/rslib.config.mts +17 -2
- package/rstest.config.mts +33 -2
- package/src/buildIdentity.ts +61 -0
- package/src/contextExtensions.ts +81 -0
- package/src/headRuntime.tsx +77 -0
- package/src/helmetContext.ts +31 -0
- package/src/index.ts +2 -0
- package/src/localisedLoaderIdentity.ts +30 -0
- package/src/prefetchPolicy.ts +33 -0
- package/src/reactContext.ts +16 -0
- package/src/request-policy/browser.ts +22 -0
- package/src/request-policy/client.ts +404 -0
- package/src/request-policy/node.ts +41 -0
- package/src/request-policy/policyCore.ts +424 -0
- package/src/request-policy/requestContext.ts +149 -0
- package/src/request-policy/traceparent.ts +43 -0
- package/src/request-policy/transport.ts +349 -0
- package/src/request-policy/types.ts +229 -0
- package/src/routeHydration.ts +208 -0
- package/src/routerPrefetchPolicy.ts +195 -0
- package/src/routerProvider.ts +160 -0
- package/src/routerState.ts +290 -0
- package/src/routerStatePlugin.ts +86 -0
- package/src/routerStateTypes.ts +46 -0
- package/src/rsc-disabled/rscDisabledClientBrowserRuntime.ts +10 -0
- package/src/rsc-disabled/rscDisabledClientEdgeRuntime.ts +8 -0
- package/src/rsc-disabled/rscDisabledClientNodeRuntime.ts +9 -0
- package/src/rsc-disabled/rscDisabledRuntimeError.ts +3 -0
- package/src/rsc-disabled/rscDisabledServerEdgeRuntime.ts +16 -0
- package/src/rsc-disabled/rscDisabledServerNodeRuntime.ts +18 -0
- package/src/runtimeContextProjection.ts +105 -0
- package/src/server-config/bffRuntime.ts +136 -0
- package/src/server-config/index.ts +2 -0
- package/src/server-config/serverTelemetry.ts +337 -0
- package/src/shellStream.ts +55 -25
- package/src/workspaceEvents.ts +324 -0
- package/tests/buildIdentity.test.ts +51 -0
- package/tests/contextExtensions.test.ts +27 -0
- package/tests/headRuntime.test.tsx +229 -0
- package/tests/rendererHead.test.ts +1 -113
- package/tests/request-policy/browser-policy.test.ts +108 -0
- package/tests/request-policy/client-isolation.test.ts +109 -0
- package/tests/request-policy/node-policy.test.ts +447 -0
- package/tests/request-policy/policyCore.test.ts +129 -0
- package/tests/request-policy/requestContext.test.ts +66 -0
- package/tests/request-policy/requestFactory.outbound-contract.test.ts +290 -0
- package/tests/request-policy/traceparent.test.ts +52 -0
- package/tests/request-policy/transport-retry.test.ts +367 -0
- package/tests/routeHydration.test.ts +180 -0
- package/tests/routerPrefetchPolicy.test.ts +102 -0
- package/tests/routerProvider.test.ts +29 -0
- package/tests/routerState.test.ts +78 -0
- package/tests/routerStatePlugin.test.ts +63 -0
- package/tests/runtimeContextProjection.test.ts +83 -0
- package/tests/safeFailure.test.ts +10 -28
- package/tests/shellStream.test.ts +37 -0
- package/tests/workspaceEvents.test.ts +221 -0
- package/dist/cjs/rscHtmlStream.js +0 -128
- package/dist/esm/rscHtmlStream.mjs +0 -86
- package/dist/esm-node/rscHtmlStream.mjs +0 -87
- package/dist/types/rscHtmlStream.d.ts +0 -4
- package/src/rscHtmlStream.ts +0 -142
- package/tests/rscHtmlStream.test.ts +0 -153
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
import "node:module";
|
|
2
|
+
const DEFAULT_RETRYABLE_STATUS_CODES = [
|
|
3
|
+
408,
|
|
4
|
+
425,
|
|
5
|
+
429,
|
|
6
|
+
500,
|
|
7
|
+
502,
|
|
8
|
+
503,
|
|
9
|
+
504
|
|
10
|
+
];
|
|
11
|
+
const DEFAULT_BASE_DELAY_MS = 100;
|
|
12
|
+
const DEFAULT_MAX_DELAY_MS = 1000;
|
|
13
|
+
const DEFAULT_JITTER_RATIO = 0.1;
|
|
14
|
+
const DEFAULT_RETRYABLE_METHODS = new Set([
|
|
15
|
+
'DELETE',
|
|
16
|
+
'GET',
|
|
17
|
+
'HEAD',
|
|
18
|
+
'OPTIONS',
|
|
19
|
+
'PUT',
|
|
20
|
+
'TRACE'
|
|
21
|
+
]);
|
|
22
|
+
const createTimeoutError = (timeoutMs)=>{
|
|
23
|
+
const error = new Error(`Request timed out after ${timeoutMs}ms`);
|
|
24
|
+
error.name = 'TimeoutError';
|
|
25
|
+
return error;
|
|
26
|
+
};
|
|
27
|
+
const unrefTimer = (timer)=>{
|
|
28
|
+
if ('object' == typeof timer && null !== timer && 'unref' in timer && 'function' == typeof timer.unref) timer.unref();
|
|
29
|
+
};
|
|
30
|
+
const wait = (ms)=>new Promise((resolve)=>{
|
|
31
|
+
const timer = setTimeout(()=>resolve(), ms);
|
|
32
|
+
unrefTimer(timer);
|
|
33
|
+
});
|
|
34
|
+
const toStatusCode = (error)=>{
|
|
35
|
+
if (!error || 'object' != typeof error) return;
|
|
36
|
+
const status = error.status;
|
|
37
|
+
if ('number' == typeof status) return status;
|
|
38
|
+
const responseStatus = error.response?.status;
|
|
39
|
+
if ('number' == typeof responseStatus) return responseStatus;
|
|
40
|
+
};
|
|
41
|
+
const isRetryableNetworkError = (error)=>{
|
|
42
|
+
if (!error || 'object' != typeof error) return false;
|
|
43
|
+
const name = error.name;
|
|
44
|
+
if ('FetchError' === name || 'TimeoutError' === name || 'TypeError' === name) return true;
|
|
45
|
+
const code = error.code;
|
|
46
|
+
return 'ECONNRESET' === code || 'ETIMEDOUT' === code || 'ECONNREFUSED' === code || 'EPIPE' === code;
|
|
47
|
+
};
|
|
48
|
+
const normalizePositiveNumber = (value, fallback)=>'number' == typeof value && Number.isFinite(value) && value > 0 ? value : fallback;
|
|
49
|
+
const normalizeNonNegativeInt = (value, fallback)=>'number' == typeof value && Number.isFinite(value) && value >= 0 ? Math.floor(value) : fallback;
|
|
50
|
+
const normalizeJitterRatio = (value)=>{
|
|
51
|
+
if ('number' != typeof value || !Number.isFinite(value)) return DEFAULT_JITTER_RATIO;
|
|
52
|
+
return Math.max(0, Math.min(1, value));
|
|
53
|
+
};
|
|
54
|
+
const shouldRetryWithDefaults = (method, statusCode, error, retryableStatusCodes)=>{
|
|
55
|
+
if (!DEFAULT_RETRYABLE_METHODS.has(method.toUpperCase())) return false;
|
|
56
|
+
if ('number' == typeof statusCode) return retryableStatusCodes.includes(statusCode);
|
|
57
|
+
return isRetryableNetworkError(error);
|
|
58
|
+
};
|
|
59
|
+
const shouldRetry = (retryOptions, context, retryableStatusCodes)=>{
|
|
60
|
+
if ('function' == typeof retryOptions?.shouldRetry) try {
|
|
61
|
+
return retryOptions.shouldRetry(context);
|
|
62
|
+
} catch (error) {
|
|
63
|
+
return false;
|
|
64
|
+
}
|
|
65
|
+
return shouldRetryWithDefaults(context.method, context.statusCode, context.error, retryableStatusCodes);
|
|
66
|
+
};
|
|
67
|
+
const getBackoffMs = (retryOptions, attempt)=>{
|
|
68
|
+
const baseDelayMs = normalizePositiveNumber(retryOptions?.baseDelayMs, DEFAULT_BASE_DELAY_MS);
|
|
69
|
+
const maxDelayMs = normalizePositiveNumber(retryOptions?.maxDelayMs, DEFAULT_MAX_DELAY_MS);
|
|
70
|
+
const jitterRatio = normalizeJitterRatio(retryOptions?.jitterRatio);
|
|
71
|
+
const exponentialDelay = Math.min(maxDelayMs, baseDelayMs * 2 ** Math.max(0, attempt - 1));
|
|
72
|
+
const jitterFactor = 0 === jitterRatio ? 1 : 1 + (2 * Math.random() - 1) * jitterRatio;
|
|
73
|
+
return Math.max(0, Math.floor(exponentialDelay * jitterFactor));
|
|
74
|
+
};
|
|
75
|
+
const emitDegradedEvent = (transport, event)=>{
|
|
76
|
+
if ('function' != typeof transport?.onDegraded) return;
|
|
77
|
+
try {
|
|
78
|
+
transport.onDegraded(event);
|
|
79
|
+
} catch (error) {}
|
|
80
|
+
};
|
|
81
|
+
const withTimeout = async (promise, timeoutMs, signalBuilder)=>{
|
|
82
|
+
if (!timeoutMs || timeoutMs <= 0) {
|
|
83
|
+
const result = await promise;
|
|
84
|
+
return {
|
|
85
|
+
result
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
const controller = signalBuilder?.();
|
|
89
|
+
let timeoutTriggered = false;
|
|
90
|
+
let rejectTimeout;
|
|
91
|
+
const timeoutPromise = new Promise((_, reject)=>{
|
|
92
|
+
rejectTimeout = reject;
|
|
93
|
+
});
|
|
94
|
+
const timer = setTimeout(()=>{
|
|
95
|
+
timeoutTriggered = true;
|
|
96
|
+
if (controller) controller.abort();
|
|
97
|
+
rejectTimeout?.(createTimeoutError(timeoutMs));
|
|
98
|
+
}, timeoutMs);
|
|
99
|
+
unrefTimer(timer);
|
|
100
|
+
try {
|
|
101
|
+
const result = await Promise.race([
|
|
102
|
+
promise,
|
|
103
|
+
timeoutPromise
|
|
104
|
+
]);
|
|
105
|
+
return {
|
|
106
|
+
result,
|
|
107
|
+
timeoutTriggered
|
|
108
|
+
};
|
|
109
|
+
} catch (error) {
|
|
110
|
+
if (timeoutTriggered && error?.name === 'AbortError') throw createTimeoutError(timeoutMs);
|
|
111
|
+
throw error;
|
|
112
|
+
} finally{
|
|
113
|
+
clearTimeout(timer);
|
|
114
|
+
}
|
|
115
|
+
};
|
|
116
|
+
const executeWithResilience = async ({ requestId, target, method, url, init, fetcher, transport })=>{
|
|
117
|
+
const retries = normalizeNonNegativeInt(transport?.retry?.retries, 0);
|
|
118
|
+
const timeoutMs = 'number' == typeof transport?.timeoutMs && transport.timeoutMs > 0 ? transport.timeoutMs : void 0;
|
|
119
|
+
const maxAttempts = retries + 1;
|
|
120
|
+
const retryableStatusCodes = transport?.retry?.retryableStatusCodes && transport.retry.retryableStatusCodes.length > 0 ? transport.retry.retryableStatusCodes : DEFAULT_RETRYABLE_STATUS_CODES;
|
|
121
|
+
let attempt = 0;
|
|
122
|
+
while(attempt < maxAttempts){
|
|
123
|
+
attempt += 1;
|
|
124
|
+
const canUseAbortController = "u" > typeof AbortController;
|
|
125
|
+
let controller;
|
|
126
|
+
if (timeoutMs && canUseAbortController) controller = new AbortController();
|
|
127
|
+
const callerSignal = init.signal;
|
|
128
|
+
const requestSignal = controller ? callerSignal && !callerSignal.aborted ? AbortSignal.any([
|
|
129
|
+
callerSignal,
|
|
130
|
+
controller.signal
|
|
131
|
+
]) : callerSignal || controller.signal : callerSignal;
|
|
132
|
+
const nextInit = requestSignal ? {
|
|
133
|
+
...init,
|
|
134
|
+
signal: requestSignal
|
|
135
|
+
} : init;
|
|
136
|
+
try {
|
|
137
|
+
const { result } = await withTimeout(fetcher(url, nextInit), timeoutMs, ()=>controller);
|
|
138
|
+
return result;
|
|
139
|
+
} catch (error) {
|
|
140
|
+
const statusCode = toStatusCode(error);
|
|
141
|
+
const decisionContext = {
|
|
142
|
+
requestId,
|
|
143
|
+
target,
|
|
144
|
+
method,
|
|
145
|
+
url,
|
|
146
|
+
attempt,
|
|
147
|
+
maxAttempts,
|
|
148
|
+
error,
|
|
149
|
+
statusCode
|
|
150
|
+
};
|
|
151
|
+
if (error?.name === 'TimeoutError') emitDegradedEvent(transport, {
|
|
152
|
+
requestId,
|
|
153
|
+
target,
|
|
154
|
+
method,
|
|
155
|
+
url,
|
|
156
|
+
reason: 'timeout',
|
|
157
|
+
attempt,
|
|
158
|
+
maxAttempts,
|
|
159
|
+
timeoutMs,
|
|
160
|
+
statusCode,
|
|
161
|
+
error
|
|
162
|
+
});
|
|
163
|
+
const canRetry = attempt < maxAttempts && shouldRetry(transport?.retry, decisionContext, retryableStatusCodes);
|
|
164
|
+
if (!canRetry) {
|
|
165
|
+
if (retries > 0 || error?.name === 'TimeoutError') emitDegradedEvent(transport, {
|
|
166
|
+
requestId,
|
|
167
|
+
target,
|
|
168
|
+
method,
|
|
169
|
+
url,
|
|
170
|
+
reason: 'retry_exhausted',
|
|
171
|
+
attempt,
|
|
172
|
+
maxAttempts,
|
|
173
|
+
timeoutMs,
|
|
174
|
+
statusCode,
|
|
175
|
+
error
|
|
176
|
+
});
|
|
177
|
+
throw error;
|
|
178
|
+
}
|
|
179
|
+
const backoffMs = getBackoffMs(transport?.retry, attempt);
|
|
180
|
+
emitDegradedEvent(transport, {
|
|
181
|
+
requestId,
|
|
182
|
+
target,
|
|
183
|
+
method,
|
|
184
|
+
url,
|
|
185
|
+
reason: 'retry',
|
|
186
|
+
attempt,
|
|
187
|
+
maxAttempts,
|
|
188
|
+
timeoutMs,
|
|
189
|
+
backoffMs,
|
|
190
|
+
statusCode,
|
|
191
|
+
error
|
|
192
|
+
});
|
|
193
|
+
if (backoffMs > 0) await wait(backoffMs);
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
};
|
|
197
|
+
export { executeWithResilience };
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import "node:module";
|
|
2
|
+
const BFF_ENVELOPE_HEADER = 'x-modernjs-bff-envelope';
|
|
3
|
+
const BFF_OPERATION_CONTEXT_HEADER = 'x-operation-id';
|
|
4
|
+
const BFF_OPERATION_CONTEXT_DETAIL_HEADER = 'x-modernjs-bff-operation-context';
|
|
5
|
+
const BFF_DEFAULT_PROTECTED_IDENTITY_HEADERS = [
|
|
6
|
+
'x-tenant-id',
|
|
7
|
+
'x-subject-id',
|
|
8
|
+
'x-user-id',
|
|
9
|
+
BFF_OPERATION_CONTEXT_HEADER
|
|
10
|
+
];
|
|
11
|
+
export { BFF_DEFAULT_PROTECTED_IDENTITY_HEADERS, BFF_ENVELOPE_HEADER, BFF_OPERATION_CONTEXT_DETAIL_HEADER, BFF_OPERATION_CONTEXT_HEADER };
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import "node:module";
|
|
2
|
+
import { escapeHtmlAttribute } from "./html.mjs";
|
|
3
|
+
function getScriptTags(template) {
|
|
4
|
+
const scriptRegExp = /<script\b[^>]*\bsrc=(["'])(.*?)\1[^>]*><\/script>/g;
|
|
5
|
+
return Array.from(template.matchAll(scriptRegExp)).map((match)=>({
|
|
6
|
+
index: match.index ?? 0,
|
|
7
|
+
tag: match[0],
|
|
8
|
+
src: match[2]
|
|
9
|
+
}));
|
|
10
|
+
}
|
|
11
|
+
function getAssetBasename(src) {
|
|
12
|
+
const withoutQuery = src.split(/[?#]/)[0];
|
|
13
|
+
return withoutQuery.split('/').pop() || withoutQuery;
|
|
14
|
+
}
|
|
15
|
+
function isEntryScript(src, entryName, asyncEntry) {
|
|
16
|
+
const basename = getAssetBasename(src);
|
|
17
|
+
const prefix = asyncEntry ? `async-${entryName}` : entryName;
|
|
18
|
+
return basename === `${prefix}.js` || basename.startsWith(`${prefix}.`) || basename.startsWith(`${prefix}-`);
|
|
19
|
+
}
|
|
20
|
+
const dedupeByUrl = (chunks)=>{
|
|
21
|
+
const seen = new Set();
|
|
22
|
+
return chunks.filter((chunk)=>{
|
|
23
|
+
if (void 0 === chunk.url || '' === chunk.url || seen.has(chunk.url)) return false;
|
|
24
|
+
seen.add(chunk.url);
|
|
25
|
+
return true;
|
|
26
|
+
});
|
|
27
|
+
};
|
|
28
|
+
const isAsyncEntryScriptChunk = (chunk, entryName)=>{
|
|
29
|
+
if (void 0 === chunk.url || !chunk.url.endsWith('.js')) return false;
|
|
30
|
+
const asyncEntryName = `async-${entryName}`;
|
|
31
|
+
const filename = chunk.filename ?? chunk.url;
|
|
32
|
+
const basename = filename.split('/').pop() ?? filename;
|
|
33
|
+
return basename === `${asyncEntryName}.js` || basename.startsWith(`${asyncEntryName}.`) || basename.startsWith(`${asyncEntryName}-`);
|
|
34
|
+
};
|
|
35
|
+
function getMatchedRouteChunks(routeManifest, matchedRouteIds, routeAssetToChunk) {
|
|
36
|
+
const routeAssets = routeManifest?.routeAssets;
|
|
37
|
+
if (void 0 === routeAssets) return [];
|
|
38
|
+
return matchedRouteIds.flatMap((routeId)=>routeAssets[routeId]?.assets ?? []).map(routeAssetToChunk);
|
|
39
|
+
}
|
|
40
|
+
const orderHydrationScriptChunks = ({ asyncEntryChunks, collectedChunks, matchedRouteChunks, entryName })=>{
|
|
41
|
+
const asyncEntryScriptChunks = [];
|
|
42
|
+
const asyncEntryDependencyChunks = [];
|
|
43
|
+
for (const chunk of asyncEntryChunks)if (isAsyncEntryScriptChunk(chunk, entryName)) asyncEntryScriptChunks.push(chunk);
|
|
44
|
+
else asyncEntryDependencyChunks.push(chunk);
|
|
45
|
+
return dedupeByUrl([
|
|
46
|
+
...asyncEntryDependencyChunks,
|
|
47
|
+
...collectedChunks,
|
|
48
|
+
...matchedRouteChunks,
|
|
49
|
+
...asyncEntryScriptChunks
|
|
50
|
+
]);
|
|
51
|
+
};
|
|
52
|
+
function injectBeforeHydrationEntryScript(template, scripts, entryName = 'index') {
|
|
53
|
+
if ('' === scripts) return template;
|
|
54
|
+
const scriptTags = getScriptTags(template);
|
|
55
|
+
const target = scriptTags.find((match)=>isEntryScript(match.src, entryName, false)) ?? scriptTags.find((match)=>isEntryScript(match.src, entryName, true));
|
|
56
|
+
if (void 0 === target) return template;
|
|
57
|
+
return `${template.slice(0, target.index)}${scripts}${template.slice(target.index)}`;
|
|
58
|
+
}
|
|
59
|
+
function replaceChunkJsPlaceholder(template, scripts, entryName, placeholder) {
|
|
60
|
+
if (!template.includes(placeholder)) return template;
|
|
61
|
+
if ('' === scripts) return template.replace(placeholder, ()=>'');
|
|
62
|
+
const withoutPlaceholder = template.replace(placeholder, ()=>'');
|
|
63
|
+
const withEarlyScripts = injectBeforeHydrationEntryScript(withoutPlaceholder, scripts, entryName);
|
|
64
|
+
if (withEarlyScripts !== withoutPlaceholder) return withEarlyScripts;
|
|
65
|
+
return template.replace(placeholder, ()=>scripts);
|
|
66
|
+
}
|
|
67
|
+
function createRouteHydrationScriptTags(routeManifest, matchedRouteIds, entryName, options = {}) {
|
|
68
|
+
const { nonce, template } = options;
|
|
69
|
+
const routeAssets = routeManifest?.routeAssets;
|
|
70
|
+
if (void 0 === routeAssets) return '';
|
|
71
|
+
const existingScriptSrcs = void 0 === template ? new Set() : new Set(getScriptTags(template).map(({ src })=>src));
|
|
72
|
+
const jsAssets = Array.from(new Set([
|
|
73
|
+
...getMatchedRouteChunks(routeManifest, matchedRouteIds, (asset)=>asset),
|
|
74
|
+
...routeAssets[`async-${entryName}`]?.assets ?? []
|
|
75
|
+
].filter((asset)=>asset.endsWith('.js'))));
|
|
76
|
+
return jsAssets.filter((asset)=>!existingScriptSrcs.has(asset)).map((asset)=>`<script src="${escapeHtmlAttribute(asset)}"${nonce ? ` nonce="${escapeHtmlAttribute(nonce)}"` : ''}></script>`).join(' ');
|
|
77
|
+
}
|
|
78
|
+
export { createRouteHydrationScriptTags, getMatchedRouteChunks, injectBeforeHydrationEntryScript, orderHydrationScriptChunks, replaceChunkJsPlaceholder };
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
import "node:module";
|
|
2
|
+
import { getNavigationWarmupCacheKey } from "./navigationWarmup.mjs";
|
|
3
|
+
import { normalizePreloadBehavior } from "./prefetchPolicy.mjs";
|
|
4
|
+
const INTENT_DELAY = 100;
|
|
5
|
+
const VIEWPORT_ROOT_MARGIN = '200px';
|
|
6
|
+
const MAX_CONCURRENT_WARMUPS = 4;
|
|
7
|
+
const WARMUP_TTL = 30000;
|
|
8
|
+
function createRouterPrefetchPolicy() {
|
|
9
|
+
const cache = new Map();
|
|
10
|
+
const queue = [];
|
|
11
|
+
let activeWarmups = 0;
|
|
12
|
+
const canWarmup = ()=>{
|
|
13
|
+
const navigator = globalThis.navigator;
|
|
14
|
+
const connection = navigator?.connection || navigator?.mozConnection || navigator?.webkitConnection;
|
|
15
|
+
return !connection?.saveData && connection?.effectiveType !== 'slow-2g' && connection?.effectiveType !== '2g';
|
|
16
|
+
};
|
|
17
|
+
const runNext = ()=>{
|
|
18
|
+
while(activeWarmups < MAX_CONCURRENT_WARMUPS && queue.length > 0){
|
|
19
|
+
const task = queue.shift();
|
|
20
|
+
if (task.cancelled) continue;
|
|
21
|
+
activeWarmups += 1;
|
|
22
|
+
task.run().catch(()=>{
|
|
23
|
+
cache.delete(task.key);
|
|
24
|
+
}).finally(()=>{
|
|
25
|
+
activeWarmups -= 1;
|
|
26
|
+
runNext();
|
|
27
|
+
});
|
|
28
|
+
}
|
|
29
|
+
};
|
|
30
|
+
return {
|
|
31
|
+
canWarmup,
|
|
32
|
+
allowData (route) {
|
|
33
|
+
return route?.handle?.navigationWarmup?.data !== false;
|
|
34
|
+
},
|
|
35
|
+
observe ({ element, prefetch: inputPrefetch, preload: inputPreload, notify }) {
|
|
36
|
+
const prefetch = inputPrefetch ?? 'render';
|
|
37
|
+
const preload = normalizePreloadBehavior(inputPreload, prefetch);
|
|
38
|
+
let state = {
|
|
39
|
+
code: 'render' === prefetch || 'render' === preload,
|
|
40
|
+
data: 'render' === prefetch
|
|
41
|
+
};
|
|
42
|
+
let timer;
|
|
43
|
+
let observer;
|
|
44
|
+
const update = (next)=>{
|
|
45
|
+
state = next;
|
|
46
|
+
notify(state);
|
|
47
|
+
};
|
|
48
|
+
const cancelTimer = ()=>{
|
|
49
|
+
if (void 0 !== timer) {
|
|
50
|
+
clearTimeout(timer);
|
|
51
|
+
timer = void 0;
|
|
52
|
+
}
|
|
53
|
+
};
|
|
54
|
+
notify(state);
|
|
55
|
+
if (element && ('viewport' === prefetch || 'viewport' === preload) && "u" > typeof IntersectionObserver) {
|
|
56
|
+
observer = new IntersectionObserver((entries)=>{
|
|
57
|
+
if (!entries.some((entry)=>entry.isIntersecting)) return;
|
|
58
|
+
update({
|
|
59
|
+
code: true,
|
|
60
|
+
data: state.data || 'viewport' === prefetch
|
|
61
|
+
});
|
|
62
|
+
observer?.disconnect();
|
|
63
|
+
}, {
|
|
64
|
+
rootMargin: VIEWPORT_ROOT_MARGIN
|
|
65
|
+
});
|
|
66
|
+
observer.observe(element);
|
|
67
|
+
}
|
|
68
|
+
return {
|
|
69
|
+
onIntent () {
|
|
70
|
+
if ('intent' !== prefetch && 'intent' !== preload) return;
|
|
71
|
+
if (void 0 !== timer) return;
|
|
72
|
+
timer = setTimeout(()=>{
|
|
73
|
+
timer = void 0;
|
|
74
|
+
update({
|
|
75
|
+
code: true,
|
|
76
|
+
data: state.data || 'intent' === prefetch
|
|
77
|
+
});
|
|
78
|
+
}, INTENT_DELAY);
|
|
79
|
+
},
|
|
80
|
+
onCancel () {
|
|
81
|
+
if ('intent' === prefetch || 'intent' === preload) {
|
|
82
|
+
cancelTimer();
|
|
83
|
+
update({
|
|
84
|
+
code: false,
|
|
85
|
+
data: false
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
},
|
|
89
|
+
dispose () {
|
|
90
|
+
cancelTimer();
|
|
91
|
+
observer?.disconnect();
|
|
92
|
+
}
|
|
93
|
+
};
|
|
94
|
+
},
|
|
95
|
+
schedule ({ runtimeContext, chunkLoader, publicPath, key: operationKey, run }) {
|
|
96
|
+
if (!canWarmup()) return ()=>{};
|
|
97
|
+
const now = performance.now();
|
|
98
|
+
for (const [key, timestamp] of cache)if (now - timestamp > WARMUP_TTL) cache.delete(key);
|
|
99
|
+
const key = getNavigationWarmupCacheKey(runtimeContext, chunkLoader, publicPath, operationKey);
|
|
100
|
+
if (cache.has(key)) return ()=>{};
|
|
101
|
+
cache.set(key, now);
|
|
102
|
+
const task = {
|
|
103
|
+
key,
|
|
104
|
+
run,
|
|
105
|
+
cancelled: false
|
|
106
|
+
};
|
|
107
|
+
queue.push(task);
|
|
108
|
+
runNext();
|
|
109
|
+
return ()=>{
|
|
110
|
+
task.cancelled = true;
|
|
111
|
+
if (queue.includes(task)) cache.delete(key);
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
export { createRouterPrefetchPolicy };
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import "node:module";
|
|
2
|
+
import { merge } from "@modern-js/runtime-utils/merge";
|
|
3
|
+
function reportUnsupportedProviderRegistryHooks(providerPlugin, routerProviderRegistryHooks) {
|
|
4
|
+
const unsupportedHookNames = Object.keys(providerPlugin.registryHooks ?? {}).filter((hookName)=>!(hookName in routerProviderRegistryHooks));
|
|
5
|
+
if (unsupportedHookNames.length > 0) console.warn(`[@modern-js/runtime] The router provider "${providerPlugin.name}" declares registry hooks outside the router hook contract: ${unsupportedHookNames.join(', ')}. These hooks are not registered when the provider is resolved through \`runtime.router.framework\` — declare them on a separate runtime plugin instead.`);
|
|
6
|
+
return unsupportedHookNames;
|
|
7
|
+
}
|
|
8
|
+
function createRouterProviderRealm(registrations) {
|
|
9
|
+
const providers = new Map();
|
|
10
|
+
let defaultProvider;
|
|
11
|
+
for (const registration of registrations){
|
|
12
|
+
if (0 === registration.name.length) throw new Error('[@modern-js/runtime] A router provider realm cannot contain an unnamed provider.');
|
|
13
|
+
if (providers.has(registration.name)) throw new Error(`[@modern-js/runtime] Router provider "${registration.name}" is declared more than once in the same runtime realm.`);
|
|
14
|
+
if (true === registration.isDefault && void 0 !== defaultProvider && defaultProvider !== registration.name) throw new Error(`[@modern-js/runtime] Router provider realm declares both "${defaultProvider}" and "${registration.name}" as defaults.`);
|
|
15
|
+
providers.set(registration.name, registration.factory);
|
|
16
|
+
if (true === registration.isDefault) defaultProvider = registration.name;
|
|
17
|
+
}
|
|
18
|
+
const providerNames = Object.freeze([
|
|
19
|
+
...providers.keys()
|
|
20
|
+
]);
|
|
21
|
+
return Object.freeze({
|
|
22
|
+
...void 0 !== defaultProvider ? {
|
|
23
|
+
defaultProvider
|
|
24
|
+
} : {},
|
|
25
|
+
get: (name)=>providers.get(name),
|
|
26
|
+
names: ()=>providerNames
|
|
27
|
+
});
|
|
28
|
+
}
|
|
29
|
+
function resolveRouterProvider(framework, options) {
|
|
30
|
+
const name = framework || options.realm.defaultProvider;
|
|
31
|
+
const realmProviderNames = options.realm.names();
|
|
32
|
+
if (void 0 === name) throw new Error(`[@modern-js/runtime] The app-owned router provider realm does not declare a default provider. Available realm providers: ${realmProviderNames.join(', ') || '(none)'}.`);
|
|
33
|
+
const factory = options.realm.get(name);
|
|
34
|
+
if (void 0 === factory) throw new Error(`[@modern-js/runtime] Router provider "${name}" is not registered in the app-owned router provider realm. Available realm providers: ${realmProviderNames.join(', ') || '(none)'}.`);
|
|
35
|
+
return factory;
|
|
36
|
+
}
|
|
37
|
+
function createRouterPlugin({ defaultProvider, registryHooks, localProviders = [] }) {
|
|
38
|
+
const realm = createRouterProviderRealm([
|
|
39
|
+
{
|
|
40
|
+
...defaultProvider,
|
|
41
|
+
isDefault: true
|
|
42
|
+
},
|
|
43
|
+
...localProviders
|
|
44
|
+
]);
|
|
45
|
+
return (userConfig = {})=>({
|
|
46
|
+
name: '@modern-js/plugin-router',
|
|
47
|
+
registryHooks,
|
|
48
|
+
setup (api) {
|
|
49
|
+
const mergedConfig = merge(api.getRuntimeConfig().router || {}, userConfig);
|
|
50
|
+
const factory = resolveRouterProvider(mergedConfig.framework, {
|
|
51
|
+
realm
|
|
52
|
+
});
|
|
53
|
+
const provider = factory(userConfig);
|
|
54
|
+
reportUnsupportedProviderRegistryHooks(provider, registryHooks);
|
|
55
|
+
provider.setup?.(api);
|
|
56
|
+
}
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
export { createRouterPlugin, createRouterProviderRealm, reportUnsupportedProviderRegistryHooks, resolveRouterProvider };
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
import "node:module";
|
|
2
|
+
import { createRuntimeContextExtension } from "./contextExtensions.mjs";
|
|
3
|
+
const routerRuntimeStateExtension = createRuntimeContextExtension('@modern-js/runtime:router-runtime-state');
|
|
4
|
+
const routerServerSnapshotExtension = createRuntimeContextExtension('@modern-js/runtime:router-server-snapshot');
|
|
5
|
+
function getRouterRuntimeState(runtimeContext) {
|
|
6
|
+
return routerRuntimeStateExtension.get(runtimeContext);
|
|
7
|
+
}
|
|
8
|
+
function getRouterServerSnapshot(runtimeContext) {
|
|
9
|
+
return routerServerSnapshotExtension.get(runtimeContext);
|
|
10
|
+
}
|
|
11
|
+
function toHydrationScripts(state) {
|
|
12
|
+
if (state.hydrationScripts?.length) return state.hydrationScripts;
|
|
13
|
+
return state.hydrationScript ? [
|
|
14
|
+
state.hydrationScript
|
|
15
|
+
] : void 0;
|
|
16
|
+
}
|
|
17
|
+
function getMatchedRouteIdsFromMatches(matches) {
|
|
18
|
+
const routeIds = matches?.map((match)=>match.assetRouteId ?? match.routeId).filter((routeId)=>'string' == typeof routeId);
|
|
19
|
+
return routeIds?.length ? routeIds : void 0;
|
|
20
|
+
}
|
|
21
|
+
function createRouterServerSnapshot(state) {
|
|
22
|
+
const hydrationScripts = toHydrationScripts(state);
|
|
23
|
+
const matchedRouteIds = state.matchedRouteIds ?? getMatchedRouteIdsFromMatches(state.matches);
|
|
24
|
+
return {
|
|
25
|
+
...state,
|
|
26
|
+
...hydrationScripts?.length ? {
|
|
27
|
+
hydrationScript: state.hydrationScript ?? hydrationScripts[0],
|
|
28
|
+
hydrationScripts
|
|
29
|
+
} : {},
|
|
30
|
+
...matchedRouteIds ? {
|
|
31
|
+
matchedRouteIds
|
|
32
|
+
} : {}
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
function createRouterRuntimeState(state) {
|
|
36
|
+
const hasSnapshotState = Boolean(state.serverSnapshot) || Boolean(state.hydrationScript) || Boolean(state.hydrationScripts?.length) || Boolean(state.matchedRouteIds?.length) || Boolean(state.matches?.length);
|
|
37
|
+
const serverSnapshot = state.serverSnapshot ? createRouterServerSnapshot({
|
|
38
|
+
...state.serverSnapshot,
|
|
39
|
+
framework: state.serverSnapshot.framework ?? state.framework,
|
|
40
|
+
basename: state.serverSnapshot.basename ?? state.basename,
|
|
41
|
+
hydrationScript: state.serverSnapshot.hydrationScript ?? state.hydrationScript,
|
|
42
|
+
hydrationScripts: state.serverSnapshot.hydrationScripts ?? state.hydrationScripts,
|
|
43
|
+
matchedRouteIds: state.serverSnapshot.matchedRouteIds ?? state.matchedRouteIds,
|
|
44
|
+
matches: state.serverSnapshot.matches ?? state.matches
|
|
45
|
+
}) : hasSnapshotState ? createRouterServerSnapshot({
|
|
46
|
+
framework: state.framework,
|
|
47
|
+
basename: state.basename,
|
|
48
|
+
hydrationScript: state.hydrationScript,
|
|
49
|
+
hydrationScripts: state.hydrationScripts,
|
|
50
|
+
matchedRouteIds: state.matchedRouteIds,
|
|
51
|
+
matches: state.matches
|
|
52
|
+
}) : void 0;
|
|
53
|
+
const hydrationScripts = toHydrationScripts({
|
|
54
|
+
hydrationScript: state.hydrationScript ?? serverSnapshot?.hydrationScript,
|
|
55
|
+
hydrationScripts: state.hydrationScripts ?? serverSnapshot?.hydrationScripts
|
|
56
|
+
});
|
|
57
|
+
const matchedRouteIds = state.matchedRouteIds ?? serverSnapshot?.matchedRouteIds ?? getMatchedRouteIdsFromMatches(state.matches);
|
|
58
|
+
return {
|
|
59
|
+
...state,
|
|
60
|
+
...hydrationScripts?.length ? {
|
|
61
|
+
hydrationScript: state.hydrationScript ?? hydrationScripts[0],
|
|
62
|
+
hydrationScripts
|
|
63
|
+
} : {},
|
|
64
|
+
...matchedRouteIds ? {
|
|
65
|
+
matchedRouteIds
|
|
66
|
+
} : {},
|
|
67
|
+
...serverSnapshot ? {
|
|
68
|
+
serverSnapshot
|
|
69
|
+
} : {}
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
const routerRuntimeStateListeners = new WeakMap();
|
|
73
|
+
function subscribeRouterRuntimeState(runtimeContext, listener) {
|
|
74
|
+
if (!runtimeContext || 'object' != typeof runtimeContext) return ()=>void 0;
|
|
75
|
+
let listeners = routerRuntimeStateListeners.get(runtimeContext);
|
|
76
|
+
if (!listeners) {
|
|
77
|
+
listeners = new Set();
|
|
78
|
+
routerRuntimeStateListeners.set(runtimeContext, listeners);
|
|
79
|
+
}
|
|
80
|
+
listeners.add(listener);
|
|
81
|
+
return ()=>{
|
|
82
|
+
listeners?.delete(listener);
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
const pendingRouterRuntimeStateNotifications = new WeakSet();
|
|
86
|
+
function notifyRouterRuntimeState(runtimeContext) {
|
|
87
|
+
const listeners = routerRuntimeStateListeners.get(runtimeContext);
|
|
88
|
+
if (!listeners?.size) return;
|
|
89
|
+
if (pendingRouterRuntimeStateNotifications.has(runtimeContext)) return;
|
|
90
|
+
pendingRouterRuntimeStateNotifications.add(runtimeContext);
|
|
91
|
+
const deliver = ()=>{
|
|
92
|
+
pendingRouterRuntimeStateNotifications.delete(runtimeContext);
|
|
93
|
+
const current = routerRuntimeStateListeners.get(runtimeContext);
|
|
94
|
+
if (!current?.size) return;
|
|
95
|
+
for (const listener of [
|
|
96
|
+
...current
|
|
97
|
+
])try {
|
|
98
|
+
listener();
|
|
99
|
+
} catch {}
|
|
100
|
+
};
|
|
101
|
+
if ('function' == typeof queueMicrotask) queueMicrotask(deliver);
|
|
102
|
+
else setTimeout(deliver, 0);
|
|
103
|
+
}
|
|
104
|
+
function applyRouterRuntimeState(runtimeContext, state) {
|
|
105
|
+
const previous = routerRuntimeStateExtension.get(runtimeContext);
|
|
106
|
+
const normalized = createRouterRuntimeState(state);
|
|
107
|
+
routerRuntimeStateExtension.set(runtimeContext, normalized);
|
|
108
|
+
if (normalized.serverSnapshot) routerServerSnapshotExtension.set(runtimeContext, normalized.serverSnapshot);
|
|
109
|
+
if (previous?.instance !== normalized.instance || previous?.framework !== normalized.framework) notifyRouterRuntimeState(runtimeContext);
|
|
110
|
+
return runtimeContext;
|
|
111
|
+
}
|
|
112
|
+
function applyRouterServerPrepareResult(runtimeContext, result) {
|
|
113
|
+
const state = createRouterRuntimeState({
|
|
114
|
+
...result.state,
|
|
115
|
+
cleanup: result.cleanup ?? result.state.cleanup,
|
|
116
|
+
serverSnapshot: result.snapshot ?? result.state.serverSnapshot
|
|
117
|
+
});
|
|
118
|
+
applyRouterRuntimeState(runtimeContext, state);
|
|
119
|
+
return runtimeContext;
|
|
120
|
+
}
|
|
121
|
+
function getRouterHydrationScripts(runtimeContext) {
|
|
122
|
+
const serverSnapshot = getRouterServerSnapshot(runtimeContext);
|
|
123
|
+
const runtimeState = getRouterRuntimeState(runtimeContext);
|
|
124
|
+
return serverSnapshot?.hydrationScripts ?? toHydrationScripts({
|
|
125
|
+
hydrationScript: serverSnapshot?.hydrationScript
|
|
126
|
+
}) ?? runtimeState?.hydrationScripts ?? toHydrationScripts({
|
|
127
|
+
hydrationScript: runtimeState?.hydrationScript
|
|
128
|
+
}) ?? [];
|
|
129
|
+
}
|
|
130
|
+
function getRouterMatchedRouteIds(runtimeContext) {
|
|
131
|
+
const serverSnapshot = getRouterServerSnapshot(runtimeContext);
|
|
132
|
+
const runtimeState = getRouterRuntimeState(runtimeContext);
|
|
133
|
+
return serverSnapshot?.matchedRouteIds ?? getMatchedRouteIdsFromMatches(serverSnapshot?.matches) ?? runtimeState?.matchedRouteIds ?? getMatchedRouteIdsFromMatches(runtimeState?.matches);
|
|
134
|
+
}
|
|
135
|
+
async function cleanupRouterRuntimeState(runtimeContext) {
|
|
136
|
+
try {
|
|
137
|
+
await getRouterRuntimeState(runtimeContext)?.cleanup?.();
|
|
138
|
+
} catch {}
|
|
139
|
+
}
|
|
140
|
+
export { applyRouterRuntimeState, applyRouterServerPrepareResult, cleanupRouterRuntimeState, createRouterRuntimeState, createRouterServerSnapshot, getRouterHydrationScripts, getRouterMatchedRouteIds, getRouterRuntimeState, getRouterServerSnapshot, subscribeRouterRuntimeState };
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import "node:module";
|
|
2
|
+
import { createRouterPrefetchPolicy } from "./routerPrefetchPolicy.mjs";
|
|
3
|
+
import { applyRouterRuntimeState, createRouterServerSnapshot } from "./routerState.mjs";
|
|
4
|
+
function createRouterStatePlugin({ registryHooks }) {
|
|
5
|
+
return {
|
|
6
|
+
name: '@modern-js/router-runtime-policy',
|
|
7
|
+
registryHooks,
|
|
8
|
+
setup (api) {
|
|
9
|
+
api.onBeforeRender((context)=>{
|
|
10
|
+
const runtimeContext = context;
|
|
11
|
+
runtimeContext.linkPrefetchPolicy ??= createRouterPrefetchPolicy();
|
|
12
|
+
});
|
|
13
|
+
api.onAfterCreateRouter((event)=>{
|
|
14
|
+
if ('react-router' !== event.framework) return;
|
|
15
|
+
if ('ssr-prepare' === event.phase) {
|
|
16
|
+
const { routerContext } = event.runtimeContext;
|
|
17
|
+
if (!routerContext) return;
|
|
18
|
+
const serverSnapshot = createRouterServerSnapshot({
|
|
19
|
+
framework: event.framework,
|
|
20
|
+
basename: event.basename,
|
|
21
|
+
statusCode: routerContext.statusCode,
|
|
22
|
+
errors: routerContext.errors ?? void 0,
|
|
23
|
+
routerData: {
|
|
24
|
+
loaderData: routerContext.loaderData,
|
|
25
|
+
errors: routerContext.errors ?? void 0
|
|
26
|
+
},
|
|
27
|
+
matches: routerContext.matches.flatMap((match)=>'string' == typeof match.route.id ? [
|
|
28
|
+
{
|
|
29
|
+
routeId: match.route.id
|
|
30
|
+
}
|
|
31
|
+
] : [])
|
|
32
|
+
});
|
|
33
|
+
applyRouterRuntimeState(event.runtimeContext, {
|
|
34
|
+
framework: event.framework,
|
|
35
|
+
basename: event.basename,
|
|
36
|
+
instance: event.router,
|
|
37
|
+
matchedRouteIds: serverSnapshot.matchedRouteIds,
|
|
38
|
+
serverSnapshot
|
|
39
|
+
});
|
|
40
|
+
} else if ('client-create' === event.phase) applyRouterRuntimeState(event.runtimeContext, {
|
|
41
|
+
framework: event.framework,
|
|
42
|
+
basename: event.basename,
|
|
43
|
+
instance: event.router
|
|
44
|
+
});
|
|
45
|
+
});
|
|
46
|
+
}
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
export { createRouterStatePlugin };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import "node:module";
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import "node:module";
|
|
2
|
+
import { disabledRscRuntime } from "./rscDisabledRuntimeError.mjs";
|
|
3
|
+
const createFromFetch = disabledRscRuntime;
|
|
4
|
+
const createFromReadableStream = disabledRscRuntime;
|
|
5
|
+
const createServerReference = disabledRscRuntime;
|
|
6
|
+
const createTemporaryReferenceSet = disabledRscRuntime;
|
|
7
|
+
const encodeReply = disabledRscRuntime;
|
|
8
|
+
const registerServerReference = disabledRscRuntime;
|
|
9
|
+
const setFindSourceMapURLCallback = disabledRscRuntime;
|
|
10
|
+
const setServerCallback = disabledRscRuntime;
|
|
11
|
+
export { createFromFetch, createFromReadableStream, createServerReference, createTemporaryReferenceSet, encodeReply, registerServerReference, setFindSourceMapURLCallback, setServerCallback };
|