@bleedingdev/modern-js-runtime 3.9.0-ultramodern.2 → 3.9.0-ultramodern.20
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/cli/code.js +3 -1
- package/dist/cjs/cli/ssr/index.js +2 -74
- package/dist/cjs/cli/ssr/loadable-bundler-plugin.js +2 -0
- package/dist/cjs/cli/template.server.js +1 -2
- package/dist/cjs/core/browser/hydrate.js +9 -10
- package/dist/cjs/core/browser/index.js +4 -5
- package/dist/cjs/core/context/index.js +12 -45
- package/dist/cjs/core/context/public.js +4 -7
- package/dist/cjs/core/context/runtime.js +10 -4
- package/dist/cjs/core/index.js +3 -3
- package/dist/cjs/core/plugin/index.js +2 -2
- package/dist/cjs/core/react/index.js +3 -3
- package/dist/cjs/core/react/wrapper.js +23 -67
- package/dist/cjs/core/server/helmet.js +5 -4
- package/dist/cjs/core/server/requestHandler.js +6 -7
- package/dist/cjs/core/server/requestResponse.js +4 -4
- package/dist/cjs/core/server/routerCleanup.js +2 -2
- package/dist/cjs/core/server/shared.js +171 -4
- package/dist/cjs/core/server/stream/afterTemplate.js +21 -16
- package/dist/cjs/core/server/stream/beforeTemplate.js +37 -28
- package/dist/cjs/core/server/stream/beforeTemplate.worker.js +30 -23
- package/dist/cjs/core/server/stream/createReadableStream.js +222 -125
- package/dist/cjs/core/server/stream/createReadableStream.worker.js +171 -90
- package/dist/cjs/core/server/stream/deferredScript.js +3 -3
- package/dist/cjs/core/server/stream/shared.js +6 -2
- package/dist/cjs/core/server/string/index.js +104 -66
- package/dist/cjs/core/server/string/loadable.js +38 -23
- package/dist/cjs/core/server/string/ssrData.js +5 -12
- package/dist/cjs/core/server/utils.js +1 -2
- package/dist/cjs/exports/head.js +7 -14
- package/dist/cjs/internal.js +2 -2
- package/dist/cjs/router/cli/code/nestedRoutes.js +1 -2
- package/dist/cjs/router/cli/code/templates.js +1 -1
- package/dist/cjs/router/cli/code/utils.js +2 -2
- package/dist/cjs/router/runtime/DeferredDataScripts.node.js +10 -9
- package/dist/cjs/router/runtime/PrefetchLink.js +69 -125
- package/dist/cjs/router/runtime/hooks.js +13 -2
- package/dist/cjs/router/runtime/internal.js +7 -45
- package/dist/cjs/router/runtime/plugin.js +19 -34
- package/dist/cjs/router/runtime/plugin.node.js +9 -37
- package/dist/cjs/router/runtime/redirect.js +1 -1
- package/dist/esm/cli/code.mjs +3 -1
- package/dist/esm/cli/ssr/index.mjs +3 -72
- package/dist/esm/cli/ssr/loadable-bundler-plugin.mjs +2 -0
- package/dist/esm/cli/template.server.mjs +1 -2
- package/dist/esm/core/browser/hydrate.mjs +10 -11
- package/dist/esm/core/browser/index.mjs +1 -2
- package/dist/esm/core/context/index.mjs +2 -5
- package/dist/esm/core/context/public.mjs +1 -5
- package/dist/esm/core/context/runtime.mjs +6 -3
- package/dist/esm/core/index.mjs +1 -1
- package/dist/esm/core/plugin/index.mjs +1 -1
- package/dist/esm/core/react/index.mjs +1 -1
- package/dist/esm/core/react/wrapper.mjs +20 -67
- package/dist/esm/core/server/helmet.mjs +5 -4
- package/dist/esm/core/server/requestHandler.mjs +1 -2
- package/dist/esm/core/server/requestResponse.mjs +3 -3
- package/dist/esm/core/server/routerCleanup.mjs +1 -1
- package/dist/esm/core/server/shared.mjs +153 -1
- package/dist/esm/core/server/stream/afterTemplate.mjs +23 -18
- package/dist/esm/core/server/stream/beforeTemplate.mjs +40 -31
- package/dist/esm/core/server/stream/beforeTemplate.worker.mjs +33 -26
- package/dist/esm/core/server/stream/createReadableStream.mjs +220 -123
- package/dist/esm/core/server/stream/createReadableStream.worker.mjs +161 -90
- package/dist/esm/core/server/stream/deferredScript.mjs +3 -3
- package/dist/esm/core/server/stream/shared.mjs +4 -3
- package/dist/esm/core/server/string/index.mjs +106 -68
- package/dist/esm/core/server/string/loadable.mjs +38 -23
- package/dist/esm/core/server/string/ssrData.mjs +5 -12
- package/dist/esm/core/server/utils.mjs +1 -2
- package/dist/esm/exports/head.mjs +7 -14
- package/dist/esm/internal.mjs +1 -1
- package/dist/esm/router/cli/code/nestedRoutes.mjs +1 -2
- package/dist/esm/router/cli/code/templates.mjs +1 -1
- package/dist/esm/router/cli/code/utils.mjs +2 -2
- package/dist/esm/router/runtime/DeferredDataScripts.node.mjs +10 -9
- package/dist/esm/router/runtime/PrefetchLink.mjs +68 -124
- package/dist/esm/router/runtime/hooks.mjs +9 -1
- package/dist/esm/router/runtime/internal.mjs +2 -33
- package/dist/esm/router/runtime/plugin.mjs +10 -25
- package/dist/esm/router/runtime/plugin.node.mjs +3 -31
- package/dist/esm/router/runtime/redirect.mjs +1 -1
- package/dist/esm-node/cli/code.mjs +3 -1
- package/dist/esm-node/cli/ssr/index.mjs +3 -72
- package/dist/esm-node/cli/ssr/loadable-bundler-plugin.mjs +2 -0
- package/dist/esm-node/cli/template.server.mjs +1 -2
- package/dist/esm-node/core/browser/hydrate.mjs +10 -11
- package/dist/esm-node/core/browser/index.mjs +1 -2
- package/dist/esm-node/core/context/index.mjs +2 -5
- package/dist/esm-node/core/context/public.mjs +1 -5
- package/dist/esm-node/core/context/runtime.mjs +6 -3
- package/dist/esm-node/core/index.mjs +1 -1
- package/dist/esm-node/core/plugin/index.mjs +1 -1
- package/dist/esm-node/core/react/index.mjs +1 -1
- package/dist/esm-node/core/react/wrapper.mjs +20 -67
- package/dist/esm-node/core/server/helmet.mjs +5 -4
- package/dist/esm-node/core/server/requestHandler.mjs +1 -2
- package/dist/esm-node/core/server/requestResponse.mjs +3 -3
- package/dist/esm-node/core/server/routerCleanup.mjs +1 -1
- package/dist/esm-node/core/server/shared.mjs +153 -1
- package/dist/esm-node/core/server/stream/afterTemplate.mjs +23 -18
- package/dist/esm-node/core/server/stream/beforeTemplate.mjs +40 -31
- package/dist/esm-node/core/server/stream/beforeTemplate.worker.mjs +33 -26
- package/dist/esm-node/core/server/stream/createReadableStream.mjs +220 -123
- package/dist/esm-node/core/server/stream/createReadableStream.worker.mjs +161 -90
- package/dist/esm-node/core/server/stream/deferredScript.mjs +3 -3
- package/dist/esm-node/core/server/stream/shared.mjs +4 -3
- package/dist/esm-node/core/server/string/index.mjs +106 -68
- package/dist/esm-node/core/server/string/loadable.mjs +38 -23
- package/dist/esm-node/core/server/string/ssrData.mjs +5 -12
- package/dist/esm-node/core/server/utils.mjs +1 -2
- package/dist/esm-node/exports/head.mjs +7 -14
- package/dist/esm-node/internal.mjs +1 -1
- package/dist/esm-node/router/cli/code/nestedRoutes.mjs +1 -2
- package/dist/esm-node/router/cli/code/templates.mjs +1 -1
- package/dist/esm-node/router/cli/code/utils.mjs +2 -2
- package/dist/esm-node/router/runtime/DeferredDataScripts.node.mjs +10 -9
- package/dist/esm-node/router/runtime/PrefetchLink.mjs +68 -124
- package/dist/esm-node/router/runtime/hooks.mjs +9 -1
- package/dist/esm-node/router/runtime/internal.mjs +2 -33
- package/dist/esm-node/router/runtime/plugin.mjs +10 -25
- package/dist/esm-node/router/runtime/plugin.node.mjs +3 -31
- package/dist/esm-node/router/runtime/redirect.mjs +1 -1
- package/dist/types/cli/ssr/index.d.ts +0 -3
- package/dist/types/core/context/index.d.ts +4 -6
- package/dist/types/core/context/public.d.ts +1 -23
- package/dist/types/core/context/runtime.d.ts +26 -2
- package/dist/types/core/index.d.ts +1 -1
- package/dist/types/core/react/wrapper.d.ts +7 -1
- package/dist/types/core/server/helmet.d.ts +4 -5
- package/dist/types/core/server/requestHandler.d.ts +3 -3
- package/dist/types/core/server/requestResponse.d.ts +1 -1
- package/dist/types/core/server/routerCleanup.d.ts +1 -1
- package/dist/types/core/server/shared.d.ts +24 -1
- package/dist/types/core/server/stream/afterTemplate.d.ts +2 -1
- package/dist/types/core/server/stream/beforeTemplate.d.ts +4 -1
- package/dist/types/core/server/stream/beforeTemplate.worker.d.ts +4 -1
- package/dist/types/core/server/stream/shared.d.ts +16 -2
- package/dist/types/core/server/string/loadable.d.ts +6 -3
- package/dist/types/core/server/string/ssrData.d.ts +2 -1
- package/dist/types/core/server/string/types.d.ts +1 -5
- package/dist/types/core/server/tracer.d.ts +1 -1
- package/dist/types/core/server/utils.d.ts +1 -1
- package/dist/types/core/types.d.ts +1 -2
- package/dist/types/exports/head.d.ts +2 -2
- package/dist/types/internal.d.ts +1 -1
- package/dist/types/router/runtime/PrefetchLink.d.ts +27 -2
- package/dist/types/router/runtime/hooks.d.ts +19 -2
- package/dist/types/router/runtime/internal.d.ts +4 -21
- package/dist/types/router/runtime/types.d.ts +2 -43
- package/package.json +18 -46
- package/rslib.config.mts +3 -0
- package/rstest.config.mts +28 -2
- package/dist/cjs/boundary-debugger/index.js +0 -317
- package/dist/cjs/core/context/extensions.js +0 -74
- package/dist/cjs/core/context/helmetContext.js +0 -54
- package/dist/cjs/core/server/federatedCss.js +0 -58
- package/dist/cjs/core/server/scriptOrder.js +0 -140
- package/dist/cjs/module-federation/consume-surface.js +0 -199
- package/dist/cjs/module-federation/distributed-ssr.js +0 -135
- package/dist/cjs/module-federation/index.js +0 -316
- package/dist/cjs/module-federation/last-known-good.js +0 -157
- package/dist/cjs/module-federation/manifest-recovery-runtime-plugin.js +0 -129
- package/dist/cjs/module-federation/surface-resolution-types.js +0 -61
- package/dist/cjs/router/runtime/lifecycle.js +0 -167
- package/dist/cjs/router/runtime/provider.js +0 -153
- package/dist/cjs/rsc/server.worker.js +0 -62
- package/dist/esm/boundary-debugger/index.mjs +0 -277
- package/dist/esm/core/context/extensions.mjs +0 -33
- package/dist/esm/core/context/helmetContext.mjs +0 -13
- package/dist/esm/core/server/federatedCss.mjs +0 -20
- package/dist/esm/core/server/scriptOrder.mjs +0 -90
- package/dist/esm/module-federation/consume-surface.mjs +0 -158
- package/dist/esm/module-federation/distributed-ssr.mjs +0 -82
- package/dist/esm/module-federation/index.mjs +0 -115
- package/dist/esm/module-federation/last-known-good.mjs +0 -113
- package/dist/esm/module-federation/manifest-recovery-runtime-plugin.mjs +0 -89
- package/dist/esm/module-federation/surface-resolution-types.mjs +0 -8
- package/dist/esm/router/runtime/lifecycle.mjs +0 -105
- package/dist/esm/router/runtime/provider.mjs +0 -100
- package/dist/esm/rsc/server.worker.mjs +0 -1
- package/dist/esm-node/boundary-debugger/index.mjs +0 -278
- package/dist/esm-node/core/context/extensions.mjs +0 -34
- package/dist/esm-node/core/context/helmetContext.mjs +0 -14
- package/dist/esm-node/core/server/federatedCss.mjs +0 -21
- package/dist/esm-node/core/server/scriptOrder.mjs +0 -91
- package/dist/esm-node/module-federation/consume-surface.mjs +0 -159
- package/dist/esm-node/module-federation/distributed-ssr.mjs +0 -83
- package/dist/esm-node/module-federation/index.mjs +0 -116
- package/dist/esm-node/module-federation/last-known-good.mjs +0 -114
- package/dist/esm-node/module-federation/manifest-recovery-runtime-plugin.mjs +0 -90
- package/dist/esm-node/module-federation/surface-resolution-types.mjs +0 -9
- package/dist/esm-node/router/runtime/lifecycle.mjs +0 -106
- package/dist/esm-node/router/runtime/provider.mjs +0 -101
- package/dist/esm-node/rsc/server.worker.mjs +0 -2
- package/dist/types/boundary-debugger/index.d.ts +0 -28
- package/dist/types/core/context/extensions.d.ts +0 -35
- package/dist/types/core/context/helmetContext.d.ts +0 -10
- package/dist/types/core/server/federatedCss.d.ts +0 -5
- package/dist/types/core/server/scriptOrder.d.ts +0 -25
- package/dist/types/module-federation/consume-surface.d.ts +0 -104
- package/dist/types/module-federation/distributed-ssr.d.ts +0 -61
- package/dist/types/module-federation/index.d.ts +0 -71
- package/dist/types/module-federation/last-known-good.d.ts +0 -52
- package/dist/types/module-federation/manifest-recovery-runtime-plugin.d.ts +0 -25
- package/dist/types/module-federation/surface-resolution-types.d.ts +0 -23
- package/dist/types/router/runtime/lifecycle.d.ts +0 -27
- package/dist/types/router/runtime/provider.d.ts +0 -78
- package/dist/types/rsc/server.worker.d.ts +0 -1
|
@@ -1,33 +0,0 @@
|
|
|
1
|
-
const EXTENSIONS_SLOT = Symbol.for('@modern-js/runtime:context-extensions');
|
|
2
|
-
function getStore(context) {
|
|
3
|
-
return context[EXTENSIONS_SLOT];
|
|
4
|
-
}
|
|
5
|
-
function ensureStore(context) {
|
|
6
|
-
const target = context;
|
|
7
|
-
const store = target[EXTENSIONS_SLOT] ?? new Map();
|
|
8
|
-
Object.defineProperty(target, EXTENSIONS_SLOT, {
|
|
9
|
-
configurable: true,
|
|
10
|
-
enumerable: true,
|
|
11
|
-
value: store
|
|
12
|
-
});
|
|
13
|
-
return store;
|
|
14
|
-
}
|
|
15
|
-
function stripRuntimeContextExtensions(context) {
|
|
16
|
-
delete context[EXTENSIONS_SLOT];
|
|
17
|
-
}
|
|
18
|
-
function createRuntimeContextExtension(id) {
|
|
19
|
-
const key = Symbol.for(`@modern-js/runtime:context-extension:${id}`);
|
|
20
|
-
return {
|
|
21
|
-
key,
|
|
22
|
-
get (context) {
|
|
23
|
-
return getStore(context)?.get(key);
|
|
24
|
-
},
|
|
25
|
-
set (context, value) {
|
|
26
|
-
ensureStore(context).set(key, value);
|
|
27
|
-
},
|
|
28
|
-
remove (context) {
|
|
29
|
-
getStore(context)?.delete(key);
|
|
30
|
-
}
|
|
31
|
-
};
|
|
32
|
-
}
|
|
33
|
-
export { createRuntimeContextExtension, stripRuntimeContextExtensions };
|
|
@@ -1,13 +0,0 @@
|
|
|
1
|
-
import { createRuntimeContextExtension } from "./extensions.mjs";
|
|
2
|
-
const helmetContextExtension = createRuntimeContextExtension('@modern-js/runtime:helmet-context');
|
|
3
|
-
function getHelmetContext(context) {
|
|
4
|
-
return helmetContextExtension.get(context);
|
|
5
|
-
}
|
|
6
|
-
function ensureHelmetContext(context) {
|
|
7
|
-
const existing = helmetContextExtension.get(context);
|
|
8
|
-
if (void 0 !== existing) return existing;
|
|
9
|
-
const created = {};
|
|
10
|
-
helmetContextExtension.set(context, created);
|
|
11
|
-
return created;
|
|
12
|
-
}
|
|
13
|
-
export { ensureHelmetContext, getHelmetContext };
|
|
@@ -1,20 +0,0 @@
|
|
|
1
|
-
import { escapeHtmlAttribute } from "@modern-js/runtime-extensions";
|
|
2
|
-
import { attributesToString, hasStylesheetLink } from "./utils.mjs";
|
|
3
|
-
const createFederatedCssLinks = (assets, options)=>{
|
|
4
|
-
if (void 0 === assets || 0 === assets.length) return '';
|
|
5
|
-
const seen = new Set(options.existingAssets || []);
|
|
6
|
-
const attributes = attributesToString(Object.fromEntries(Object.entries(options.attributes || {}).filter(([name])=>![
|
|
7
|
-
'href',
|
|
8
|
-
'rel'
|
|
9
|
-
].includes(name.toLowerCase()))));
|
|
10
|
-
const links = [];
|
|
11
|
-
for (const asset of assets){
|
|
12
|
-
const href = escapeHtmlAttribute(asset);
|
|
13
|
-
if (!('' === asset || seen.has(asset) || hasStylesheetLink(options.template, asset) || hasStylesheetLink(options.template, href))) {
|
|
14
|
-
seen.add(asset);
|
|
15
|
-
links.push(`<link${attributes} href="${href}" rel="stylesheet" />`);
|
|
16
|
-
}
|
|
17
|
-
}
|
|
18
|
-
return links.join('');
|
|
19
|
-
};
|
|
20
|
-
export { createFederatedCssLinks };
|
|
@@ -1,90 +0,0 @@
|
|
|
1
|
-
import { getRouterMatchedRouteIds } from "../../router/runtime/lifecycle.mjs";
|
|
2
|
-
import { CHUNK_JS_PLACEHOLDER } from "./constants.mjs";
|
|
3
|
-
import { attributesToString, safeReplace } from "./utils.mjs";
|
|
4
|
-
function getScriptTags(template) {
|
|
5
|
-
const scriptRegExp = /<script\b[^>]*\bsrc=(["'])(.*?)\1[^>]*><\/script>/g;
|
|
6
|
-
return Array.from(template.matchAll(scriptRegExp)).map((match)=>({
|
|
7
|
-
index: match.index ?? 0,
|
|
8
|
-
tag: match[0],
|
|
9
|
-
src: match[2]
|
|
10
|
-
}));
|
|
11
|
-
}
|
|
12
|
-
function getAssetBasename(src) {
|
|
13
|
-
const withoutQuery = src.split(/[?#]/)[0];
|
|
14
|
-
return withoutQuery.split('/').pop() || withoutQuery;
|
|
15
|
-
}
|
|
16
|
-
function isEntryScript(src, entryName, asyncEntry) {
|
|
17
|
-
const basename = getAssetBasename(src);
|
|
18
|
-
const prefix = asyncEntry ? `async-${entryName}` : entryName;
|
|
19
|
-
return basename === `${prefix}.js` || basename.startsWith(`${prefix}.`) || basename.startsWith(`${prefix}-`);
|
|
20
|
-
}
|
|
21
|
-
const dedupeByUrl = (chunks)=>{
|
|
22
|
-
const seen = new Set();
|
|
23
|
-
return chunks.filter((chunk)=>{
|
|
24
|
-
if (void 0 === chunk.url || '' === chunk.url || seen.has(chunk.url)) return false;
|
|
25
|
-
seen.add(chunk.url);
|
|
26
|
-
return true;
|
|
27
|
-
});
|
|
28
|
-
};
|
|
29
|
-
const isAsyncEntryScriptChunk = (chunk, entryName)=>{
|
|
30
|
-
if (void 0 === chunk.url || !chunk.url.endsWith('.js')) return false;
|
|
31
|
-
const asyncEntryName = `async-${entryName}`;
|
|
32
|
-
const filename = chunk.filename ?? chunk.url;
|
|
33
|
-
const basename = filename.split('/').pop() ?? filename;
|
|
34
|
-
return basename === `${asyncEntryName}.js` || basename.startsWith(`${asyncEntryName}.`) || basename.startsWith(`${asyncEntryName}-`);
|
|
35
|
-
};
|
|
36
|
-
function getRouteAssets(runtimeContext, routeManifest = runtimeContext.routeManifest) {
|
|
37
|
-
return routeManifest?.routeAssets;
|
|
38
|
-
}
|
|
39
|
-
function getMatchedRouteAssets(runtimeContext, routeManifest) {
|
|
40
|
-
const routeAssets = getRouteAssets(runtimeContext, routeManifest);
|
|
41
|
-
if (void 0 === routeAssets) return [];
|
|
42
|
-
const matchedRouteIds = getRouterMatchedRouteIds(runtimeContext) ?? [];
|
|
43
|
-
return matchedRouteIds.flatMap((routeId)=>routeAssets[routeId]?.assets ?? []);
|
|
44
|
-
}
|
|
45
|
-
function getMatchedRouteChunks(runtimeContext, routeManifest, routeAssetToChunk) {
|
|
46
|
-
if (void 0 === routeManifest) return [];
|
|
47
|
-
return getMatchedRouteAssets(runtimeContext, routeManifest).map(routeAssetToChunk);
|
|
48
|
-
}
|
|
49
|
-
const orderHydrationScriptChunks = ({ asyncEntryChunks, collectedChunks, matchedRouteChunks, entryName })=>{
|
|
50
|
-
const asyncEntryScriptChunks = [];
|
|
51
|
-
const asyncEntryDependencyChunks = [];
|
|
52
|
-
for (const chunk of asyncEntryChunks)if (isAsyncEntryScriptChunk(chunk, entryName)) asyncEntryScriptChunks.push(chunk);
|
|
53
|
-
else asyncEntryDependencyChunks.push(chunk);
|
|
54
|
-
return dedupeByUrl([
|
|
55
|
-
...asyncEntryDependencyChunks,
|
|
56
|
-
...collectedChunks,
|
|
57
|
-
...matchedRouteChunks,
|
|
58
|
-
...asyncEntryScriptChunks
|
|
59
|
-
]);
|
|
60
|
-
};
|
|
61
|
-
function injectBeforeHydrationEntryScript(template, scripts, entryName = 'index') {
|
|
62
|
-
if ('' === scripts) return template;
|
|
63
|
-
const scriptTags = getScriptTags(template);
|
|
64
|
-
const target = scriptTags.find((match)=>isEntryScript(match.src, entryName, false)) ?? scriptTags.find((match)=>isEntryScript(match.src, entryName, true));
|
|
65
|
-
if (void 0 === target) return template;
|
|
66
|
-
return `${template.slice(0, target.index)}${scripts}${template.slice(target.index)}`;
|
|
67
|
-
}
|
|
68
|
-
function replaceChunkJsPlaceholder(template, scripts, entryName, placeholder = CHUNK_JS_PLACEHOLDER) {
|
|
69
|
-
if (!template.includes(placeholder)) return template;
|
|
70
|
-
if ('' === scripts) return safeReplace(template, placeholder, '');
|
|
71
|
-
const withoutPlaceholder = safeReplace(template, placeholder, '');
|
|
72
|
-
const withEarlyScripts = injectBeforeHydrationEntryScript(withoutPlaceholder, scripts, entryName);
|
|
73
|
-
if (withEarlyScripts !== withoutPlaceholder) return withEarlyScripts;
|
|
74
|
-
return safeReplace(template, placeholder, scripts);
|
|
75
|
-
}
|
|
76
|
-
function createRouteHydrationScriptTags(runtimeContext, entryName, options = {}) {
|
|
77
|
-
const { nonce, template } = options;
|
|
78
|
-
const routeAssets = getRouteAssets(runtimeContext);
|
|
79
|
-
if (void 0 === routeAssets) return '';
|
|
80
|
-
const existingScriptSrcs = void 0 === template ? new Set() : new Set(getScriptTags(template).map(({ src })=>src));
|
|
81
|
-
const jsAssets = Array.from(new Set([
|
|
82
|
-
...getMatchedRouteAssets(runtimeContext),
|
|
83
|
-
...routeAssets[`async-${entryName}`]?.assets ?? []
|
|
84
|
-
].filter((asset)=>asset.endsWith('.js'))));
|
|
85
|
-
return jsAssets.filter((asset)=>!existingScriptSrcs.has(asset)).map((asset)=>`<script${attributesToString({
|
|
86
|
-
src: asset,
|
|
87
|
-
nonce: nonce || void 0
|
|
88
|
-
})}></script>`).join(' ');
|
|
89
|
-
}
|
|
90
|
-
export { createRouteHydrationScriptTags, getMatchedRouteChunks, injectBeforeHydrationEntryScript, orderHydrationScriptChunks, replaceChunkJsPlaceholder };
|
|
@@ -1,158 +0,0 @@
|
|
|
1
|
-
import { classifyModuleFederationFallback, createModuleFederationFallbackTelemetry, emitModuleFederationFallbackTelemetry } from "./index.mjs";
|
|
2
|
-
import { createDiscoveryError, formatSurfaceRef, parseSurfaceRef, validateSurfaceRef } from "./surface-resolution-types.mjs";
|
|
3
|
-
function classifyDiscoveryError(code) {
|
|
4
|
-
switch(code){
|
|
5
|
-
case 'major-not-published':
|
|
6
|
-
case 'stale-record':
|
|
7
|
-
return 'version-skew';
|
|
8
|
-
case 'identity-mismatch':
|
|
9
|
-
return 'contract';
|
|
10
|
-
case 'unknown-unit':
|
|
11
|
-
case 'unknown-surface':
|
|
12
|
-
case 'provider-unavailable':
|
|
13
|
-
return 'remote-unavailable';
|
|
14
|
-
default:
|
|
15
|
-
return 'remote-unavailable';
|
|
16
|
-
}
|
|
17
|
-
}
|
|
18
|
-
function toRemoteString(ref) {
|
|
19
|
-
return void 0 === validateSurfaceRef(ref) ? formatSurfaceRef(ref) : `${ref.unitId}#${ref.surfaceId}`;
|
|
20
|
-
}
|
|
21
|
-
async function reportFailure(options, ref, base) {
|
|
22
|
-
const remote = toRemoteString(ref);
|
|
23
|
-
const telemetry = createModuleFederationFallbackTelemetry({
|
|
24
|
-
appName: options.appName,
|
|
25
|
-
classification: base.classification,
|
|
26
|
-
error: base.error ?? base.discoveryError,
|
|
27
|
-
metadata: {
|
|
28
|
-
env: options.env,
|
|
29
|
-
surfaceRef: remote,
|
|
30
|
-
...base.discoveryError ? {
|
|
31
|
-
discoveryErrorCode: base.discoveryError.code
|
|
32
|
-
} : {},
|
|
33
|
-
...base.resolved ? {
|
|
34
|
-
buildMarker: base.resolved.buildMarker
|
|
35
|
-
} : {}
|
|
36
|
-
},
|
|
37
|
-
phase: base.phase,
|
|
38
|
-
remote,
|
|
39
|
-
status: 'degraded'
|
|
40
|
-
});
|
|
41
|
-
try {
|
|
42
|
-
await emitModuleFederationFallbackTelemetry({
|
|
43
|
-
appName: options.appName,
|
|
44
|
-
classification: base.classification,
|
|
45
|
-
error: base.error ?? base.discoveryError,
|
|
46
|
-
metadata: telemetry.metadata,
|
|
47
|
-
phase: base.phase,
|
|
48
|
-
remote,
|
|
49
|
-
status: 'degraded'
|
|
50
|
-
}, options.telemetry ?? {});
|
|
51
|
-
} catch {}
|
|
52
|
-
const failure = {
|
|
53
|
-
ref,
|
|
54
|
-
env: options.env,
|
|
55
|
-
phase: base.phase,
|
|
56
|
-
classification: base.classification,
|
|
57
|
-
telemetry
|
|
58
|
-
};
|
|
59
|
-
if (base.discoveryError) failure.discoveryError = base.discoveryError;
|
|
60
|
-
if (void 0 !== base.error) failure.error = base.error;
|
|
61
|
-
if (base.resolved) failure.resolved = base.resolved;
|
|
62
|
-
const critical = (options.classification ?? 'critical') === 'critical';
|
|
63
|
-
const reason = base.discoveryError ?? (void 0 !== base.error ? base.error : createDiscoveryError('identity-mismatch', remote, `resolved record for "${remote}" is incompatible`, {
|
|
64
|
-
env: options.env
|
|
65
|
-
}));
|
|
66
|
-
let degradedValue;
|
|
67
|
-
try {
|
|
68
|
-
degradedValue = await options.degraded(failure);
|
|
69
|
-
} catch (handlerError) {
|
|
70
|
-
try {
|
|
71
|
-
await emitModuleFederationFallbackTelemetry({
|
|
72
|
-
appName: options.appName,
|
|
73
|
-
classification: base.classification,
|
|
74
|
-
error: handlerError,
|
|
75
|
-
metadata: {
|
|
76
|
-
...telemetry.metadata,
|
|
77
|
-
degradedHandlerFailed: true
|
|
78
|
-
},
|
|
79
|
-
phase: base.phase,
|
|
80
|
-
remote,
|
|
81
|
-
status: 'failed'
|
|
82
|
-
}, options.telemetry ?? {});
|
|
83
|
-
} catch {}
|
|
84
|
-
if (critical) throw reason;
|
|
85
|
-
return;
|
|
86
|
-
}
|
|
87
|
-
if (critical) throw reason;
|
|
88
|
-
return degradedValue;
|
|
89
|
-
}
|
|
90
|
-
async function consumeSurface(options) {
|
|
91
|
-
let ref;
|
|
92
|
-
if ('string' == typeof options.ref) {
|
|
93
|
-
const parsed = parseSurfaceRef(options.ref);
|
|
94
|
-
if (!parsed.ok) {
|
|
95
|
-
const hashIndex = options.ref.indexOf('#');
|
|
96
|
-
const echoed = -1 === hashIndex ? {
|
|
97
|
-
unitId: options.ref,
|
|
98
|
-
surfaceId: ''
|
|
99
|
-
} : {
|
|
100
|
-
unitId: options.ref.slice(0, hashIndex),
|
|
101
|
-
surfaceId: options.ref.slice(hashIndex + 1)
|
|
102
|
-
};
|
|
103
|
-
return reportFailure(options, echoed, {
|
|
104
|
-
phase: 'discovery',
|
|
105
|
-
classification: 'remote-unavailable',
|
|
106
|
-
discoveryError: createDiscoveryError('unknown-surface', options.ref, `SurfaceRef "${options.ref}" is not a valid canonical reference (${parsed.error.code}).`, {
|
|
107
|
-
parseError: parsed.error,
|
|
108
|
-
env: options.env
|
|
109
|
-
})
|
|
110
|
-
});
|
|
111
|
-
}
|
|
112
|
-
ref = parsed.ref;
|
|
113
|
-
} else ref = options.ref;
|
|
114
|
-
let resolution;
|
|
115
|
-
try {
|
|
116
|
-
resolution = await options.provider.resolve(ref, options.env);
|
|
117
|
-
} catch (error) {
|
|
118
|
-
return reportFailure(options, ref, {
|
|
119
|
-
phase: 'discovery',
|
|
120
|
-
classification: classifyModuleFederationFallback(error),
|
|
121
|
-
error
|
|
122
|
-
});
|
|
123
|
-
}
|
|
124
|
-
if (!resolution.ok) return reportFailure(options, ref, {
|
|
125
|
-
phase: 'discovery',
|
|
126
|
-
classification: classifyDiscoveryError(resolution.error.code),
|
|
127
|
-
discoveryError: resolution.error
|
|
128
|
-
});
|
|
129
|
-
const resolved = resolution.unit;
|
|
130
|
-
if ('incompatible' === resolved.compatibility.status) return reportFailure(options, ref, {
|
|
131
|
-
phase: 'discovery',
|
|
132
|
-
classification: 'contract',
|
|
133
|
-
resolved
|
|
134
|
-
});
|
|
135
|
-
try {
|
|
136
|
-
return await options.load({
|
|
137
|
-
resolved,
|
|
138
|
-
ref,
|
|
139
|
-
env: options.env
|
|
140
|
-
});
|
|
141
|
-
} catch (error) {
|
|
142
|
-
return reportFailure(options, ref, {
|
|
143
|
-
phase: 'load',
|
|
144
|
-
classification: classifyModuleFederationFallback(error),
|
|
145
|
-
error,
|
|
146
|
-
resolved
|
|
147
|
-
});
|
|
148
|
-
}
|
|
149
|
-
}
|
|
150
|
-
function createSurfaceConsumer(base) {
|
|
151
|
-
return function(options) {
|
|
152
|
-
return consumeSurface({
|
|
153
|
-
...base,
|
|
154
|
-
...options
|
|
155
|
-
});
|
|
156
|
-
};
|
|
157
|
-
}
|
|
158
|
-
export { consumeSurface, createSurfaceConsumer };
|
|
@@ -1,82 +0,0 @@
|
|
|
1
|
-
import { jsx } from "react/jsx-runtime";
|
|
2
|
-
import { useRuntimeContext } from "../core/context/runtime.mjs";
|
|
3
|
-
const DISTRIBUTED_SSR_FRAGMENTS_LOCALS_KEY = '__modernDistributedSsrFragments';
|
|
4
|
-
const DISTRIBUTED_SSR_FRAGMENT_REQUEST_LOCALS_KEY = '__modernDistributedSsrFragmentRequest';
|
|
5
|
-
function distributedSsrFragmentKey(remote, expose) {
|
|
6
|
-
return `${remote}::${expose}`;
|
|
7
|
-
}
|
|
8
|
-
function getDistributedSsrFragmentContext(response) {
|
|
9
|
-
const locals = response?.locals;
|
|
10
|
-
if ('object' != typeof locals || null === locals) return;
|
|
11
|
-
const context = DISTRIBUTED_SSR_FRAGMENTS_LOCALS_KEY in locals ? locals[DISTRIBUTED_SSR_FRAGMENTS_LOCALS_KEY] : void 0;
|
|
12
|
-
if ('object' != typeof context || null === context) return;
|
|
13
|
-
return context;
|
|
14
|
-
}
|
|
15
|
-
function useDistributedSsrFragmentProps({ boundaryId, expose }) {
|
|
16
|
-
const runtimeContext = useRuntimeContext();
|
|
17
|
-
const locals = runtimeContext.requestContext?.response?.locals;
|
|
18
|
-
const request = 'object' == typeof locals && null !== locals && DISTRIBUTED_SSR_FRAGMENT_REQUEST_LOCALS_KEY in locals ? locals[DISTRIBUTED_SSR_FRAGMENT_REQUEST_LOCALS_KEY] : void 0;
|
|
19
|
-
if ('object' != typeof request || null === request || !('boundaryId' in request) || request.boundaryId !== boundaryId || !('expose' in request) || request.expose !== expose) throw new Error(`Distributed SSR fragment request contract mismatch for ${boundaryId} ${expose}.`);
|
|
20
|
-
const props = 'props' in request ? request.props : void 0;
|
|
21
|
-
if ('object' != typeof props || null === props || Array.isArray(props)) throw new Error(`Distributed SSR fragment request props must be an object for ${boundaryId} ${expose}.`);
|
|
22
|
-
return props;
|
|
23
|
-
}
|
|
24
|
-
function isThenable(value) {
|
|
25
|
-
return void 0 !== value && 'then' in value && 'function' == typeof value.then;
|
|
26
|
-
}
|
|
27
|
-
function DistributedSsrBoundary({ children, expose, fallback, fragmentProps, remote }) {
|
|
28
|
-
const runtimeContext = useRuntimeContext();
|
|
29
|
-
const key = distributedSsrFragmentKey(remote, expose);
|
|
30
|
-
const attributes = {
|
|
31
|
-
'data-modern-distributed-ssr-boundary': key
|
|
32
|
-
};
|
|
33
|
-
if (runtimeContext.isBrowser) return /*#__PURE__*/ jsx("div", {
|
|
34
|
-
...attributes,
|
|
35
|
-
children: children
|
|
36
|
-
});
|
|
37
|
-
const fragmentContext = getDistributedSsrFragmentContext(runtimeContext.requestContext?.response);
|
|
38
|
-
if (void 0 === fragmentContext) return /*#__PURE__*/ jsx("div", {
|
|
39
|
-
...attributes,
|
|
40
|
-
children: children
|
|
41
|
-
});
|
|
42
|
-
const resolverFragmentProps = void 0 === fragmentProps ? {} : Object.fromEntries(Object.entries(fragmentProps));
|
|
43
|
-
const fragmentOrPromise = fragmentContext.resolve?.(remote, expose, resolverFragmentProps) ?? fragmentContext.fragments?.[key];
|
|
44
|
-
if (isThenable(fragmentOrPromise)) throw fragmentOrPromise;
|
|
45
|
-
const fragment = fragmentOrPromise;
|
|
46
|
-
if (fragment?.status === 'ready') return /*#__PURE__*/ jsx("div", {
|
|
47
|
-
...attributes,
|
|
48
|
-
"data-modern-distributed-ssr-build": fragment.buildMarker,
|
|
49
|
-
"data-modern-distributed-ssr-digest": fragment.digest,
|
|
50
|
-
"data-modern-distributed-ssr-status": "ready",
|
|
51
|
-
dangerouslySetInnerHTML: {
|
|
52
|
-
__html: fragment.html
|
|
53
|
-
}
|
|
54
|
-
});
|
|
55
|
-
return /*#__PURE__*/ jsx("div", {
|
|
56
|
-
...attributes,
|
|
57
|
-
"data-modern-distributed-ssr-reason": fragment?.reason ?? 'missing',
|
|
58
|
-
"data-modern-distributed-ssr-status": "degraded",
|
|
59
|
-
children: fallback
|
|
60
|
-
});
|
|
61
|
-
}
|
|
62
|
-
function createDistributedSsrComponent({ createComponent, expose, fallback, remote }) {
|
|
63
|
-
let RemoteComponent;
|
|
64
|
-
function DeferredRemoteComponent(props) {
|
|
65
|
-
RemoteComponent ??= createComponent();
|
|
66
|
-
return /*#__PURE__*/ jsx(RemoteComponent, {
|
|
67
|
-
...props
|
|
68
|
-
});
|
|
69
|
-
}
|
|
70
|
-
return function(props) {
|
|
71
|
-
return /*#__PURE__*/ jsx(DistributedSsrBoundary, {
|
|
72
|
-
expose: expose,
|
|
73
|
-
fallback: fallback,
|
|
74
|
-
fragmentProps: props,
|
|
75
|
-
remote: remote,
|
|
76
|
-
children: /*#__PURE__*/ jsx(DeferredRemoteComponent, {
|
|
77
|
-
...props
|
|
78
|
-
})
|
|
79
|
-
});
|
|
80
|
-
};
|
|
81
|
-
}
|
|
82
|
-
export { DISTRIBUTED_SSR_FRAGMENTS_LOCALS_KEY, DISTRIBUTED_SSR_FRAGMENT_REQUEST_LOCALS_KEY, DistributedSsrBoundary, createDistributedSsrComponent, distributedSsrFragmentKey, useDistributedSsrFragmentProps };
|
|
@@ -1,115 +0,0 @@
|
|
|
1
|
-
export * from "./consume-surface.mjs";
|
|
2
|
-
export * from "./distributed-ssr.mjs";
|
|
3
|
-
export * from "./last-known-good.mjs";
|
|
4
|
-
export * from "./manifest-recovery-runtime-plugin.mjs";
|
|
5
|
-
export * from "./surface-resolution-types.mjs";
|
|
6
|
-
const MODULE_FEDERATION_FALLBACK_SIGNAL_EVENT = 'modernjs:mf-runtime-fallback';
|
|
7
|
-
const MODULE_FEDERATION_RECOVERY_SIGNAL_EVENT = 'modernjs:mf-runtime-recovery';
|
|
8
|
-
const DEFAULT_RUNTIME_FALLBACK_SIGNAL_ENDPOINT = '/_modern/contract-gates/runtime-fallback';
|
|
9
|
-
const DEFAULT_RUNTIME_FALLBACK_SIGNAL_AUTH_HEADER = 'x-modernjs-runtime-signal-token';
|
|
10
|
-
class ModuleFederationRemoteLoadTimeoutError extends Error {
|
|
11
|
-
constructor(remote, timeoutMs){
|
|
12
|
-
super(`Loading remote "${remote}" timed out after ${timeoutMs}ms`);
|
|
13
|
-
this.name = 'ModuleFederationRemoteLoadTimeoutError';
|
|
14
|
-
}
|
|
15
|
-
}
|
|
16
|
-
class ModuleFederationRemoteLoadError extends Error {
|
|
17
|
-
constructor(remote, attempts, causeError){
|
|
18
|
-
super(`Unable to load remote "${remote}" after ${attempts} attempt${attempts > 1 ? 's' : ''}: ${causeError.message}`);
|
|
19
|
-
this.name = 'ModuleFederationRemoteLoadError';
|
|
20
|
-
this.remote = remote;
|
|
21
|
-
this.attempts = attempts;
|
|
22
|
-
this.causeError = causeError;
|
|
23
|
-
}
|
|
24
|
-
}
|
|
25
|
-
class ModuleFederationRemoteComponentContractError extends Error {
|
|
26
|
-
constructor(remote, exportName){
|
|
27
|
-
super(`Remote "${remote}" export "${exportName}" is not a valid React component`);
|
|
28
|
-
this.name = 'ModuleFederationRemoteComponentContractError';
|
|
29
|
-
}
|
|
30
|
-
}
|
|
31
|
-
function toError(error) {
|
|
32
|
-
if (error instanceof Error) return error;
|
|
33
|
-
return new Error('string' == typeof error ? error : 'Unknown remote load error');
|
|
34
|
-
}
|
|
35
|
-
function classifyModuleFederationFallback(error) {
|
|
36
|
-
const normalizedError = toError(error);
|
|
37
|
-
if (normalizedError instanceof ModuleFederationRemoteLoadError) return classifyModuleFederationFallback(normalizedError.causeError);
|
|
38
|
-
if (normalizedError instanceof ModuleFederationRemoteLoadTimeoutError) return 'timeout';
|
|
39
|
-
if (normalizedError instanceof ModuleFederationRemoteComponentContractError) return 'contract';
|
|
40
|
-
const message = normalizedError.message;
|
|
41
|
-
if (/version|requiredVersion|singleton|share scope|shared module/i.test(message)) return 'version-skew';
|
|
42
|
-
if (/network|fetch|script|timeout|chunk|loading/i.test(message)) return 'network';
|
|
43
|
-
return 'remote-unavailable';
|
|
44
|
-
}
|
|
45
|
-
function createModuleFederationFallbackTelemetry(input) {
|
|
46
|
-
const error = void 0 !== input.error ? toError(input.error) : void 0;
|
|
47
|
-
const status = input.status ?? 'degraded';
|
|
48
|
-
const eventName = input.eventName ?? ('recovered' === status ? MODULE_FEDERATION_RECOVERY_SIGNAL_EVENT : MODULE_FEDERATION_FALLBACK_SIGNAL_EVENT);
|
|
49
|
-
const metadata = {
|
|
50
|
-
...input.metadata ?? {},
|
|
51
|
-
classification: input.classification,
|
|
52
|
-
remote: input.remote,
|
|
53
|
-
status
|
|
54
|
-
};
|
|
55
|
-
if (void 0 !== input.exportName) metadata.exportName = input.exportName;
|
|
56
|
-
if (void 0 !== input.runtimeDigest) metadata.runtimeDigest = input.runtimeDigest;
|
|
57
|
-
if (void 0 !== error) {
|
|
58
|
-
metadata.errorName = error.name;
|
|
59
|
-
metadata.errorMessage = error.message;
|
|
60
|
-
}
|
|
61
|
-
const payload = {
|
|
62
|
-
appName: input.appName,
|
|
63
|
-
eventName,
|
|
64
|
-
metadata,
|
|
65
|
-
phase: input.phase,
|
|
66
|
-
reason: input.classification,
|
|
67
|
-
schemaVersion: 1
|
|
68
|
-
};
|
|
69
|
-
if (void 0 !== input.entry) payload.entry = input.entry;
|
|
70
|
-
if (void 0 !== input.runtimeDigest) payload.runtimeDigest = input.runtimeDigest;
|
|
71
|
-
return payload;
|
|
72
|
-
}
|
|
73
|
-
function toModuleFederationFallbackAttributes(payload) {
|
|
74
|
-
return {
|
|
75
|
-
'data-mf-fallback-app': payload.appName,
|
|
76
|
-
'data-mf-fallback-classification': payload.reason,
|
|
77
|
-
'data-mf-fallback-phase': payload.phase,
|
|
78
|
-
'data-mf-fallback-remote': String(payload.metadata.remote),
|
|
79
|
-
'data-mf-fallback-status': String(payload.metadata.status),
|
|
80
|
-
'data-mf-telemetry-event': payload.eventName
|
|
81
|
-
};
|
|
82
|
-
}
|
|
83
|
-
async function emitModuleFederationFallbackTelemetry(input, options = {}) {
|
|
84
|
-
const payload = createModuleFederationFallbackTelemetry(input);
|
|
85
|
-
if ("u" > typeof window && 'function' == typeof window.dispatchEvent && "u" > typeof CustomEvent) window.dispatchEvent(new CustomEvent(payload.eventName, {
|
|
86
|
-
detail: payload
|
|
87
|
-
}));
|
|
88
|
-
const shouldPost = true === options.postSignal || Boolean(options.endpoint);
|
|
89
|
-
if (!shouldPost) return {
|
|
90
|
-
dispatched: true,
|
|
91
|
-
posted: false
|
|
92
|
-
};
|
|
93
|
-
const fetchImpl = options.fetchImpl ?? globalThis.fetch;
|
|
94
|
-
if ('function' != typeof fetchImpl) return {
|
|
95
|
-
dispatched: true,
|
|
96
|
-
posted: false
|
|
97
|
-
};
|
|
98
|
-
const headers = new Headers({
|
|
99
|
-
'content-type': 'application/json'
|
|
100
|
-
});
|
|
101
|
-
if (void 0 !== options.authToken && options.authToken.length > 0) headers.set(options.authHeaderName ?? DEFAULT_RUNTIME_FALLBACK_SIGNAL_AUTH_HEADER, options.authToken);
|
|
102
|
-
const response = await fetchImpl(options.endpoint ?? DEFAULT_RUNTIME_FALLBACK_SIGNAL_ENDPOINT, {
|
|
103
|
-
body: JSON.stringify(payload),
|
|
104
|
-
headers,
|
|
105
|
-
method: 'POST',
|
|
106
|
-
keepalive: true
|
|
107
|
-
});
|
|
108
|
-
return {
|
|
109
|
-
dispatched: true,
|
|
110
|
-
posted: true,
|
|
111
|
-
postStatus: response.status
|
|
112
|
-
};
|
|
113
|
-
}
|
|
114
|
-
export { DISTRIBUTED_SSR_FRAGMENT_REQUEST_LOCALS_KEY, useDistributedSsrFragmentProps } from "./distributed-ssr.mjs";
|
|
115
|
-
export { DEFAULT_RUNTIME_FALLBACK_SIGNAL_AUTH_HEADER, DEFAULT_RUNTIME_FALLBACK_SIGNAL_ENDPOINT, MODULE_FEDERATION_FALLBACK_SIGNAL_EVENT, MODULE_FEDERATION_RECOVERY_SIGNAL_EVENT, ModuleFederationRemoteComponentContractError, ModuleFederationRemoteLoadError, ModuleFederationRemoteLoadTimeoutError, classifyModuleFederationFallback, createModuleFederationFallbackTelemetry, emitModuleFederationFallbackTelemetry, toModuleFederationFallbackAttributes };
|
|
@@ -1,113 +0,0 @@
|
|
|
1
|
-
import { selectResolvedSurface } from "@modern-js/utils/universal";
|
|
2
|
-
import { createDiscoveryError, deliveryUnitResolutionKey } from "./surface-resolution-types.mjs";
|
|
3
|
-
const LAST_KNOWN_GOOD_PROVIDER_NAME = 'last-known-good';
|
|
4
|
-
function createInMemoryLkgStorage() {
|
|
5
|
-
const map = new Map();
|
|
6
|
-
return {
|
|
7
|
-
read (key) {
|
|
8
|
-
return map.get(key);
|
|
9
|
-
},
|
|
10
|
-
write (key, record) {
|
|
11
|
-
map.set(key, record);
|
|
12
|
-
}
|
|
13
|
-
};
|
|
14
|
-
}
|
|
15
|
-
function markDegraded(resolved, reason) {
|
|
16
|
-
return {
|
|
17
|
-
...resolved,
|
|
18
|
-
compatibility: {
|
|
19
|
-
...resolved.compatibility,
|
|
20
|
-
status: 'degraded',
|
|
21
|
-
reason
|
|
22
|
-
}
|
|
23
|
-
};
|
|
24
|
-
}
|
|
25
|
-
function staleRecordResult(ref, env, ageMs, maxStaleMs) {
|
|
26
|
-
return {
|
|
27
|
-
ok: false,
|
|
28
|
-
error: createDiscoveryError('stale-record', ref, `Last-known-good record for surface is stale: age ${ageMs}ms exceeds maxStaleMs ${maxStaleMs}ms`, {
|
|
29
|
-
env,
|
|
30
|
-
ageMs,
|
|
31
|
-
maxStaleMs
|
|
32
|
-
})
|
|
33
|
-
};
|
|
34
|
-
}
|
|
35
|
-
function resolutionAnswersRef(resolved, ref) {
|
|
36
|
-
const selected = selectResolvedSurface(resolved, ref);
|
|
37
|
-
return selected.ok && selected.surface.servedMajor === ref.major;
|
|
38
|
-
}
|
|
39
|
-
function createLastKnownGoodProvider(options) {
|
|
40
|
-
const storage = options.storage ?? createInMemoryLkgStorage();
|
|
41
|
-
const now = options.now ?? (()=>Math.floor(performance.timeOrigin + performance.now()));
|
|
42
|
-
const maxStaleMs = options.freshness?.maxStaleMs;
|
|
43
|
-
let nextResolutionGeneration = 0;
|
|
44
|
-
const latestCacheableGenerationByKey = new Map();
|
|
45
|
-
const writeTailByKey = new Map();
|
|
46
|
-
async function cacheCompatibleResolution(key, generation, record) {
|
|
47
|
-
latestCacheableGenerationByKey.set(key, Math.max(latestCacheableGenerationByKey.get(key) ?? 0, generation));
|
|
48
|
-
const previous = writeTailByKey.get(key) ?? Promise.resolve();
|
|
49
|
-
const write = previous.catch(()=>void 0).then(async ()=>{
|
|
50
|
-
if (latestCacheableGenerationByKey.get(key) !== generation) return;
|
|
51
|
-
await storage.write(key, record);
|
|
52
|
-
});
|
|
53
|
-
writeTailByKey.set(key, write);
|
|
54
|
-
try {
|
|
55
|
-
await write;
|
|
56
|
-
} finally{
|
|
57
|
-
if (writeTailByKey.get(key) === write) writeTailByKey.delete(key);
|
|
58
|
-
}
|
|
59
|
-
}
|
|
60
|
-
async function serveFromCache(ref, env, fallback) {
|
|
61
|
-
const key = deliveryUnitResolutionKey(ref.unitId, env);
|
|
62
|
-
const cached = await storage.read(key);
|
|
63
|
-
if (!cached) return fallback();
|
|
64
|
-
if (cached.major !== ref.major) return fallback();
|
|
65
|
-
if (!resolutionAnswersRef(cached.resolved, ref)) return fallback();
|
|
66
|
-
if ('compatible' !== cached.resolved.compatibility.status) return fallback();
|
|
67
|
-
const ageMs = now() - cached.storedAt;
|
|
68
|
-
if (void 0 !== maxStaleMs && ageMs > maxStaleMs) return staleRecordResult(ref, env, ageMs, maxStaleMs);
|
|
69
|
-
return {
|
|
70
|
-
ok: true,
|
|
71
|
-
unit: markDegraded(cached.resolved, `served last-known-good record (age ${ageMs}ms) after provider failure`)
|
|
72
|
-
};
|
|
73
|
-
}
|
|
74
|
-
return {
|
|
75
|
-
name: LAST_KNOWN_GOOD_PROVIDER_NAME,
|
|
76
|
-
async resolve (ref, env) {
|
|
77
|
-
const key = deliveryUnitResolutionKey(ref.unitId, env);
|
|
78
|
-
const generation = ++nextResolutionGeneration;
|
|
79
|
-
let resolution;
|
|
80
|
-
try {
|
|
81
|
-
resolution = await options.provider.resolve(ref, env);
|
|
82
|
-
} catch (error) {
|
|
83
|
-
return serveFromCache(ref, env, ()=>({
|
|
84
|
-
ok: false,
|
|
85
|
-
error: createDiscoveryError('provider-unavailable', ref, error instanceof Error ? error.message : 'provider threw a non-error value', {
|
|
86
|
-
env,
|
|
87
|
-
provider: options.provider.name
|
|
88
|
-
})
|
|
89
|
-
}));
|
|
90
|
-
}
|
|
91
|
-
if (!resolution.ok) {
|
|
92
|
-
const failure = resolution;
|
|
93
|
-
return serveFromCache(ref, env, ()=>failure);
|
|
94
|
-
}
|
|
95
|
-
if (!resolutionAnswersRef(resolution.unit, ref)) return serveFromCache(ref, env, ()=>({
|
|
96
|
-
ok: false,
|
|
97
|
-
error: createDiscoveryError('identity-mismatch', ref, `Provider ${options.provider.name} returned a delivery unit that does not answer the requested surface.`, {
|
|
98
|
-
env,
|
|
99
|
-
provider: options.provider.name,
|
|
100
|
-
recordUnitId: resolution.unit.unitId,
|
|
101
|
-
availableSurfaces: resolution.unit.surfaces.map((surface)=>surface.surfaceId)
|
|
102
|
-
})
|
|
103
|
-
}));
|
|
104
|
-
if ('compatible' === resolution.unit.compatibility.status) await cacheCompatibleResolution(key, generation, {
|
|
105
|
-
resolved: resolution.unit,
|
|
106
|
-
storedAt: now(),
|
|
107
|
-
major: ref.major
|
|
108
|
-
});
|
|
109
|
-
return resolution;
|
|
110
|
-
}
|
|
111
|
-
};
|
|
112
|
-
}
|
|
113
|
-
export { LAST_KNOWN_GOOD_PROVIDER_NAME, createInMemoryLkgStorage, createLastKnownGoodProvider };
|