@bleedingdev/modern-js-federation-runtime 0.0.0 → 3.9.0-ultramodern.5

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 (33) hide show
  1. package/LICENSE +21 -0
  2. package/dist/cjs/module-federation/consume-surface.js +199 -0
  3. package/dist/cjs/module-federation/distributed-ssr.js +135 -0
  4. package/dist/cjs/module-federation/index.js +316 -0
  5. package/dist/cjs/module-federation/last-known-good.js +157 -0
  6. package/dist/cjs/module-federation/manifest-recovery-runtime-plugin.js +130 -0
  7. package/dist/cjs/module-federation/surface-resolution-types.js +61 -0
  8. package/dist/esm/module-federation/consume-surface.mjs +158 -0
  9. package/dist/esm/module-federation/distributed-ssr.mjs +82 -0
  10. package/dist/esm/module-federation/index.mjs +115 -0
  11. package/dist/esm/module-federation/last-known-good.mjs +113 -0
  12. package/dist/esm/module-federation/manifest-recovery-runtime-plugin.mjs +90 -0
  13. package/dist/esm/module-federation/surface-resolution-types.mjs +8 -0
  14. package/dist/esm-node/module-federation/consume-surface.mjs +159 -0
  15. package/dist/esm-node/module-federation/distributed-ssr.mjs +83 -0
  16. package/dist/esm-node/module-federation/index.mjs +116 -0
  17. package/dist/esm-node/module-federation/last-known-good.mjs +114 -0
  18. package/dist/esm-node/module-federation/manifest-recovery-runtime-plugin.mjs +91 -0
  19. package/dist/esm-node/module-federation/surface-resolution-types.mjs +9 -0
  20. package/dist/types/module-federation/consume-surface.d.ts +104 -0
  21. package/dist/types/module-federation/distributed-ssr.d.ts +61 -0
  22. package/dist/types/module-federation/index.d.ts +71 -0
  23. package/dist/types/module-federation/last-known-good.d.ts +52 -0
  24. package/dist/types/module-federation/manifest-recovery-runtime-plugin.d.ts +25 -0
  25. package/dist/types/module-federation/surface-resolution-types.d.ts +23 -0
  26. package/package.json +86 -4
  27. package/src/module-federation/consume-surface.ts +369 -0
  28. package/src/module-federation/distributed-ssr.tsx +240 -0
  29. package/src/module-federation/index.ts +274 -0
  30. package/src/module-federation/last-known-good.ts +292 -0
  31. package/src/module-federation/manifest-recovery-runtime-plugin.ts +215 -0
  32. package/src/module-federation/surface-resolution-types.ts +60 -0
  33. package/README.md +0 -3
@@ -0,0 +1,116 @@
1
+ import "node:module";
2
+ export * from "./consume-surface.mjs";
3
+ export * from "./distributed-ssr.mjs";
4
+ export * from "./last-known-good.mjs";
5
+ export * from "./manifest-recovery-runtime-plugin.mjs";
6
+ export * from "./surface-resolution-types.mjs";
7
+ const MODULE_FEDERATION_FALLBACK_SIGNAL_EVENT = 'modernjs:mf-runtime-fallback';
8
+ const MODULE_FEDERATION_RECOVERY_SIGNAL_EVENT = 'modernjs:mf-runtime-recovery';
9
+ const DEFAULT_RUNTIME_FALLBACK_SIGNAL_ENDPOINT = '/_modern/contract-gates/runtime-fallback';
10
+ const DEFAULT_RUNTIME_FALLBACK_SIGNAL_AUTH_HEADER = 'x-modernjs-runtime-signal-token';
11
+ class ModuleFederationRemoteLoadTimeoutError extends Error {
12
+ constructor(remote, timeoutMs){
13
+ super(`Loading remote "${remote}" timed out after ${timeoutMs}ms`);
14
+ this.name = 'ModuleFederationRemoteLoadTimeoutError';
15
+ }
16
+ }
17
+ class ModuleFederationRemoteLoadError extends Error {
18
+ constructor(remote, attempts, causeError){
19
+ super(`Unable to load remote "${remote}" after ${attempts} attempt${attempts > 1 ? 's' : ''}: ${causeError.message}`);
20
+ this.name = 'ModuleFederationRemoteLoadError';
21
+ this.remote = remote;
22
+ this.attempts = attempts;
23
+ this.causeError = causeError;
24
+ }
25
+ }
26
+ class ModuleFederationRemoteComponentContractError extends Error {
27
+ constructor(remote, exportName){
28
+ super(`Remote "${remote}" export "${exportName}" is not a valid React component`);
29
+ this.name = 'ModuleFederationRemoteComponentContractError';
30
+ }
31
+ }
32
+ function toError(error) {
33
+ if (error instanceof Error) return error;
34
+ return new Error('string' == typeof error ? error : 'Unknown remote load error');
35
+ }
36
+ function classifyModuleFederationFallback(error) {
37
+ const normalizedError = toError(error);
38
+ if (normalizedError instanceof ModuleFederationRemoteLoadError) return classifyModuleFederationFallback(normalizedError.causeError);
39
+ if (normalizedError instanceof ModuleFederationRemoteLoadTimeoutError) return 'timeout';
40
+ if (normalizedError instanceof ModuleFederationRemoteComponentContractError) return 'contract';
41
+ const message = normalizedError.message;
42
+ if (/version|requiredVersion|singleton|share scope|shared module/i.test(message)) return 'version-skew';
43
+ if (/network|fetch|script|timeout|chunk|loading/i.test(message)) return 'network';
44
+ return 'remote-unavailable';
45
+ }
46
+ function createModuleFederationFallbackTelemetry(input) {
47
+ const error = void 0 !== input.error ? toError(input.error) : void 0;
48
+ const status = input.status ?? 'degraded';
49
+ const eventName = input.eventName ?? ('recovered' === status ? MODULE_FEDERATION_RECOVERY_SIGNAL_EVENT : MODULE_FEDERATION_FALLBACK_SIGNAL_EVENT);
50
+ const metadata = {
51
+ ...input.metadata ?? {},
52
+ classification: input.classification,
53
+ remote: input.remote,
54
+ status
55
+ };
56
+ if (void 0 !== input.exportName) metadata.exportName = input.exportName;
57
+ if (void 0 !== input.runtimeDigest) metadata.runtimeDigest = input.runtimeDigest;
58
+ if (void 0 !== error) {
59
+ metadata.errorName = error.name;
60
+ metadata.errorMessage = error.message;
61
+ }
62
+ const payload = {
63
+ appName: input.appName,
64
+ eventName,
65
+ metadata,
66
+ phase: input.phase,
67
+ reason: input.classification,
68
+ schemaVersion: 1
69
+ };
70
+ if (void 0 !== input.entry) payload.entry = input.entry;
71
+ if (void 0 !== input.runtimeDigest) payload.runtimeDigest = input.runtimeDigest;
72
+ return payload;
73
+ }
74
+ function toModuleFederationFallbackAttributes(payload) {
75
+ return {
76
+ 'data-mf-fallback-app': payload.appName,
77
+ 'data-mf-fallback-classification': payload.reason,
78
+ 'data-mf-fallback-phase': payload.phase,
79
+ 'data-mf-fallback-remote': String(payload.metadata.remote),
80
+ 'data-mf-fallback-status': String(payload.metadata.status),
81
+ 'data-mf-telemetry-event': payload.eventName
82
+ };
83
+ }
84
+ async function emitModuleFederationFallbackTelemetry(input, options = {}) {
85
+ const payload = createModuleFederationFallbackTelemetry(input);
86
+ if ("u" > typeof window && 'function' == typeof window.dispatchEvent && "u" > typeof CustomEvent) window.dispatchEvent(new CustomEvent(payload.eventName, {
87
+ detail: payload
88
+ }));
89
+ const shouldPost = true === options.postSignal || Boolean(options.endpoint);
90
+ if (!shouldPost) return {
91
+ dispatched: true,
92
+ posted: false
93
+ };
94
+ const fetchImpl = options.fetchImpl ?? globalThis.fetch;
95
+ if ('function' != typeof fetchImpl) return {
96
+ dispatched: true,
97
+ posted: false
98
+ };
99
+ const headers = new Headers({
100
+ 'content-type': 'application/json'
101
+ });
102
+ if (void 0 !== options.authToken && options.authToken.length > 0) headers.set(options.authHeaderName ?? DEFAULT_RUNTIME_FALLBACK_SIGNAL_AUTH_HEADER, options.authToken);
103
+ const response = await fetchImpl(options.endpoint ?? DEFAULT_RUNTIME_FALLBACK_SIGNAL_ENDPOINT, {
104
+ body: JSON.stringify(payload),
105
+ headers,
106
+ method: 'POST',
107
+ keepalive: true
108
+ });
109
+ return {
110
+ dispatched: true,
111
+ posted: true,
112
+ postStatus: response.status
113
+ };
114
+ }
115
+ export { DISTRIBUTED_SSR_FRAGMENT_REQUEST_LOCALS_KEY, useDistributedSsrFragmentProps } from "./distributed-ssr.mjs";
116
+ 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 };
@@ -0,0 +1,114 @@
1
+ import "node:module";
2
+ import { selectResolvedSurface } from "@modern-js/surface-resolution";
3
+ import { createDiscoveryError, deliveryUnitResolutionKey } from "./surface-resolution-types.mjs";
4
+ const LAST_KNOWN_GOOD_PROVIDER_NAME = 'last-known-good';
5
+ function createInMemoryLkgStorage() {
6
+ const map = new Map();
7
+ return {
8
+ read (key) {
9
+ return map.get(key);
10
+ },
11
+ write (key, record) {
12
+ map.set(key, record);
13
+ }
14
+ };
15
+ }
16
+ function markDegraded(resolved, reason) {
17
+ return {
18
+ ...resolved,
19
+ compatibility: {
20
+ ...resolved.compatibility,
21
+ status: 'degraded',
22
+ reason
23
+ }
24
+ };
25
+ }
26
+ function staleRecordResult(ref, env, ageMs, maxStaleMs) {
27
+ return {
28
+ ok: false,
29
+ error: createDiscoveryError('stale-record', ref, `Last-known-good record for surface is stale: age ${ageMs}ms exceeds maxStaleMs ${maxStaleMs}ms`, {
30
+ env,
31
+ ageMs,
32
+ maxStaleMs
33
+ })
34
+ };
35
+ }
36
+ function resolutionAnswersRef(resolved, ref) {
37
+ const selected = selectResolvedSurface(resolved, ref);
38
+ return selected.ok && selected.surface.servedMajor === ref.major;
39
+ }
40
+ function createLastKnownGoodProvider(options) {
41
+ const storage = options.storage ?? createInMemoryLkgStorage();
42
+ const now = options.now ?? (()=>Math.floor(performance.timeOrigin + performance.now()));
43
+ const maxStaleMs = options.freshness?.maxStaleMs;
44
+ let nextResolutionGeneration = 0;
45
+ const latestCacheableGenerationByKey = new Map();
46
+ const writeTailByKey = new Map();
47
+ async function cacheCompatibleResolution(key, generation, record) {
48
+ latestCacheableGenerationByKey.set(key, Math.max(latestCacheableGenerationByKey.get(key) ?? 0, generation));
49
+ const previous = writeTailByKey.get(key) ?? Promise.resolve();
50
+ const write = previous.catch(()=>void 0).then(async ()=>{
51
+ if (latestCacheableGenerationByKey.get(key) !== generation) return;
52
+ await storage.write(key, record);
53
+ });
54
+ writeTailByKey.set(key, write);
55
+ try {
56
+ await write;
57
+ } finally{
58
+ if (writeTailByKey.get(key) === write) writeTailByKey.delete(key);
59
+ }
60
+ }
61
+ async function serveFromCache(ref, env, fallback) {
62
+ const key = deliveryUnitResolutionKey(ref.unitId, env);
63
+ const cached = await storage.read(key);
64
+ if (!cached) return fallback();
65
+ if (cached.major !== ref.major) return fallback();
66
+ if (!resolutionAnswersRef(cached.resolved, ref)) return fallback();
67
+ if ('compatible' !== cached.resolved.compatibility.status) return fallback();
68
+ const ageMs = now() - cached.storedAt;
69
+ if (void 0 !== maxStaleMs && ageMs > maxStaleMs) return staleRecordResult(ref, env, ageMs, maxStaleMs);
70
+ return {
71
+ ok: true,
72
+ unit: markDegraded(cached.resolved, `served last-known-good record (age ${ageMs}ms) after provider failure`)
73
+ };
74
+ }
75
+ return {
76
+ name: LAST_KNOWN_GOOD_PROVIDER_NAME,
77
+ async resolve (ref, env) {
78
+ const key = deliveryUnitResolutionKey(ref.unitId, env);
79
+ const generation = ++nextResolutionGeneration;
80
+ let resolution;
81
+ try {
82
+ resolution = await options.provider.resolve(ref, env);
83
+ } catch (error) {
84
+ return serveFromCache(ref, env, ()=>({
85
+ ok: false,
86
+ error: createDiscoveryError('provider-unavailable', ref, error instanceof Error ? error.message : 'provider threw a non-error value', {
87
+ env,
88
+ provider: options.provider.name
89
+ })
90
+ }));
91
+ }
92
+ if (!resolution.ok) {
93
+ const failure = resolution;
94
+ return serveFromCache(ref, env, ()=>failure);
95
+ }
96
+ if (!resolutionAnswersRef(resolution.unit, ref)) return serveFromCache(ref, env, ()=>({
97
+ ok: false,
98
+ error: createDiscoveryError('identity-mismatch', ref, `Provider ${options.provider.name} returned a delivery unit that does not answer the requested surface.`, {
99
+ env,
100
+ provider: options.provider.name,
101
+ recordUnitId: resolution.unit.unitId,
102
+ availableSurfaces: resolution.unit.surfaces.map((surface)=>surface.surfaceId)
103
+ })
104
+ }));
105
+ if ('compatible' === resolution.unit.compatibility.status) await cacheCompatibleResolution(key, generation, {
106
+ resolved: resolution.unit,
107
+ storedAt: now(),
108
+ major: ref.major
109
+ });
110
+ return resolution;
111
+ }
112
+ };
113
+ }
114
+ export { LAST_KNOWN_GOOD_PROVIDER_NAME, createInMemoryLkgStorage, createLastKnownGoodProvider };
@@ -0,0 +1,91 @@
1
+ import "node:module";
2
+ const DEFAULT_ATTEMPTS = 3;
3
+ const DEFAULT_RETRY_DELAY_MS = 100;
4
+ const DEFAULT_TIMEOUT_MS = 1000;
5
+ const MAX_ATTEMPTS = 5;
6
+ const MAX_RETRY_DELAY_MS = 1000;
7
+ const MAX_TIMEOUT_MS = 5000;
8
+ const RETRYABLE_HTTP_STATUSES = new Set([
9
+ 408,
10
+ 425,
11
+ 429,
12
+ 500,
13
+ 502,
14
+ 503,
15
+ 504
16
+ ]);
17
+ const NON_RETRYABLE_ERROR_PATTERNS = [
18
+ /RUNTIME-013/i,
19
+ /invalid manifest/i,
20
+ /manifest (?:schema|contract|version|identity)/i,
21
+ /(?:incompatible|mismatch).*(?:manifest|remote)/i
22
+ ];
23
+ const clampInteger = (value, fallback, minimum, maximum)=>{
24
+ if (void 0 === value || !Number.isFinite(value)) return fallback;
25
+ return Math.min(maximum, Math.max(minimum, Math.floor(value)));
26
+ };
27
+ const getErrorMessage = (error)=>{
28
+ if (error instanceof Error) return error.message;
29
+ return 'string' == typeof error ? error : '';
30
+ };
31
+ const getErrorStatus = (error)=>{
32
+ if ('object' == typeof error && null !== error && 'status' in error && 'number' == typeof error.status) return error.status;
33
+ };
34
+ const isRetryableError = (error)=>{
35
+ if (error instanceof SyntaxError) return false;
36
+ const message = getErrorMessage(error);
37
+ if (NON_RETRYABLE_ERROR_PATTERNS.some((pattern)=>pattern.test(message))) return false;
38
+ const status = getErrorStatus(error);
39
+ if (void 0 !== status) return RETRYABLE_HTTP_STATUSES.has(status);
40
+ if (error instanceof Error && [
41
+ 'AbortError',
42
+ 'TimeoutError'
43
+ ].includes(error.name)) return true;
44
+ return error instanceof TypeError || /(?:fetch failed|network|ECONNREFUSED|ECONNRESET|ETIMEDOUT|EAI_AGAIN)/i.test(message);
45
+ };
46
+ const isHttpManifestUrl = (id)=>{
47
+ if (void 0 === id || 0 === id.length) return false;
48
+ try {
49
+ const url = new URL(id);
50
+ return ('http:' === url.protocol || 'https:' === url.protocol) && url.pathname.endsWith('.json');
51
+ } catch {
52
+ return false;
53
+ }
54
+ };
55
+ const defaultWait = (milliseconds)=>new Promise((resolve)=>{
56
+ setTimeout(resolve, milliseconds);
57
+ });
58
+ const fetchWithTimeout = (fetchImpl, url, timeoutMs)=>fetchImpl(url, {
59
+ signal: AbortSignal.timeout(timeoutMs)
60
+ });
61
+ const createModuleFederationManifestRecoveryPlugin = (options = {})=>{
62
+ const attempts = clampInteger(options.attempts, DEFAULT_ATTEMPTS, 1, MAX_ATTEMPTS);
63
+ const retryDelayMs = clampInteger(options.retryDelayMs, DEFAULT_RETRY_DELAY_MS, 0, MAX_RETRY_DELAY_MS);
64
+ const timeoutMs = clampInteger(options.timeoutMs, DEFAULT_TIMEOUT_MS, 1, MAX_TIMEOUT_MS);
65
+ const fetchImpl = options.fetchImpl ?? globalThis.fetch;
66
+ const waitImpl = options.waitImpl ?? defaultWait;
67
+ const recoverManifest = (url, attempt)=>{
68
+ const fetchManifest = ()=>Promise.resolve().then(()=>fetchWithTimeout(fetchImpl, url, timeoutMs)).then((response)=>{
69
+ if (!response.ok) {
70
+ if (!RETRYABLE_HTTP_STATUSES.has(response.status) || attempt === attempts - 1) return;
71
+ return recoverManifest(url, attempt + 1);
72
+ }
73
+ return Promise.resolve().then(()=>response.json()).then((manifest)=>manifest, ()=>void 0);
74
+ }, (error)=>{
75
+ if (!isRetryableError(error) || attempt === attempts - 1) return;
76
+ return recoverManifest(url, attempt + 1);
77
+ });
78
+ if (attempt > 0 && retryDelayMs > 0) return waitImpl(retryDelayMs).then(fetchManifest);
79
+ return fetchManifest();
80
+ };
81
+ return {
82
+ name: 'modern-js-manifest-recovery-plugin',
83
+ errorLoadRemote (args) {
84
+ if ('afterResolve' !== args.lifecycle || !isHttpManifestUrl(args.id) || !isRetryableError(args.error) || 'function' != typeof fetchImpl) return Promise.resolve(void 0);
85
+ return recoverManifest(args.id, 0);
86
+ }
87
+ };
88
+ };
89
+ const manifest_recovery_runtime_plugin = createModuleFederationManifestRecoveryPlugin;
90
+ export default manifest_recovery_runtime_plugin;
91
+ export { createModuleFederationManifestRecoveryPlugin };
@@ -0,0 +1,9 @@
1
+ import "node:module";
2
+ import { createDiscoveryError, formatSurfaceRef, parseSurfaceRef, validateSurfaceRef } from "@modern-js/surface-resolution";
3
+ function surfaceResolutionKey(ref, env) {
4
+ return `${env}::${formatSurfaceRef(ref)}`;
5
+ }
6
+ function deliveryUnitResolutionKey(unitId, env) {
7
+ return `${env}::${unitId}`;
8
+ }
9
+ export { createDiscoveryError, deliveryUnitResolutionKey, formatSurfaceRef, parseSurfaceRef, surfaceResolutionKey, validateSurfaceRef };
@@ -0,0 +1,104 @@
1
+ /**
2
+ * G22 — mandatory degraded consumption API.
3
+ *
4
+ * CONTEXT.md (Degraded State): "consuming a surface obliges the consumer to
5
+ * define a degraded state". This module turns that obligation into a
6
+ * compile-level one: {@link SurfaceConsumerOptions.degraded} is a REQUIRED
7
+ * field, so a call site that forgets its fallback does not type-check.
8
+ *
9
+ * The consumer wraps the loadRemote-ish flow (resolve a SurfaceRef through a
10
+ * provider, then load the execution artifact from the resolved record) and
11
+ * guarantees isolation: any discovery/load failure is caught, classified,
12
+ * reported through the existing MF fallback telemetry, and handed to the
13
+ * required degraded handler.
14
+ *
15
+ * Criticality (owner-default 5: unclassified consumption is `critical`). For a
16
+ * `noncritical` consumption the degraded handler's result is returned and the
17
+ * failure is swallowed, so one failing consumption can never propagate to a
18
+ * sibling (CONTEXT.md: faults isolate at the vertical boundary). For a
19
+ * `critical` consumption the degraded handler still runs — telemetry and
20
+ * fallback-UI obligations hold — but the returned promise then REJECTS with the
21
+ * typed failure so callers and rollout machinery observe it. Critical
22
+ * consumption during a rollout window should be driven by expand/contract, not
23
+ * by silent degrade.
24
+ */
25
+ import { type ModuleFederationFallbackClassification, type ModuleFederationFallbackTelemetryEmitOptions, type ModuleFederationFallbackTelemetryPayload } from './index.js';
26
+ import { type DiscoveryError, type EnvironmentId, type ParsedSurfaceRef, type ResolvedDeliveryUnit, type SurfaceResolutionProvider } from './surface-resolution-types.js';
27
+ /** Where in the consumption lifecycle a failure was raised. */
28
+ export type SurfaceConsumptionPhase = 'discovery' | 'load' | 'mount';
29
+ /**
30
+ * The typed failure surfaced to the degraded handler. Exactly one of
31
+ * `discoveryError` (resolver returned a typed {@link DiscoveryError}) or
32
+ * `error` (something threw) is populated for a given failure.
33
+ */
34
+ export type SurfaceConsumptionFailure = {
35
+ ref: ParsedSurfaceRef;
36
+ env: EnvironmentId;
37
+ phase: SurfaceConsumptionPhase;
38
+ classification: ModuleFederationFallbackClassification;
39
+ /** Present when discovery returned a typed error state. */
40
+ discoveryError?: DiscoveryError;
41
+ /** Present when a thrown error caused the failure. */
42
+ error?: unknown;
43
+ /** The resolved record, when discovery succeeded but load/mount failed. */
44
+ resolved?: ResolvedDeliveryUnit;
45
+ /** The fallback telemetry payload emitted for this failure. */
46
+ telemetry: ModuleFederationFallbackTelemetryPayload;
47
+ };
48
+ export type SurfaceLoadInput = {
49
+ resolved: ResolvedDeliveryUnit;
50
+ ref: ParsedSurfaceRef;
51
+ env: EnvironmentId;
52
+ };
53
+ export type SurfaceConsumerOptions<T> = {
54
+ /** The logical surface to consume (object or canonical string form). */
55
+ ref: ParsedSurfaceRef | string;
56
+ env: EnvironmentId;
57
+ /** The pluggable resolution seam (RESOLUTION-0001 §2.2). */
58
+ provider: SurfaceResolutionProvider;
59
+ /** Consumer app name, used for telemetry attribution. */
60
+ appName: string;
61
+ /**
62
+ * Loads the execution artifact from a resolved record — the loadRemote-ish
63
+ * flow. Receives the whole {@link ResolvedDeliveryUnit} so the adapter reads
64
+ * locations under one buildMarker (RESOLUTION-0001 §2.3).
65
+ */
66
+ load: (input: SurfaceLoadInput) => Promise<T> | T;
67
+ /**
68
+ * REQUIRED degraded handler (G22 compile-level obligation). There is no
69
+ * default and no way to opt out at the type level: omitting this field is a
70
+ * compile error. Return the value to serve while the surface is unavailable
71
+ * or incompatible.
72
+ */
73
+ degraded: (failure: SurfaceConsumptionFailure) => T | Promise<T>;
74
+ /**
75
+ * Consumption criticality (owner-default 5). Defaults to `'critical'` when
76
+ * omitted.
77
+ *
78
+ * - `'noncritical'`: the degraded handler's result is returned and the
79
+ * failure is swallowed — the promise never rejects.
80
+ * - `'critical'`: the degraded handler still runs (telemetry + fallback-UI
81
+ * obligations hold), but the returned promise then REJECTS with the typed
82
+ * failure so callers / rollout machinery observe it. Prefer expand/contract
83
+ * over silent degrade for critical surfaces during rollout windows.
84
+ */
85
+ classification?: 'critical' | 'noncritical';
86
+ /** Optional telemetry emission options (endpoint/auth/fetch overrides). */
87
+ telemetry?: ModuleFederationFallbackTelemetryEmitOptions;
88
+ };
89
+ /**
90
+ * Consume one surface with a mandatory degraded fallback. On any discovery or
91
+ * load failure the required degraded handler runs (telemetry + fallback UI).
92
+ *
93
+ * For a `noncritical` consumption (see {@link SurfaceConsumerOptions.classification})
94
+ * this resolves to the degraded value and never rejects, so a failing
95
+ * consumption is isolated from any sibling. For a `critical` consumption (the
96
+ * default) it rejects with the typed failure AFTER the degraded handler has
97
+ * run, so callers / rollout machinery observe the failure.
98
+ */
99
+ export declare function consumeSurface<T>(options: SurfaceConsumerOptions<T>): Promise<T>;
100
+ /**
101
+ * Build a reusable consumer bound to a provider/env/app, still requiring a
102
+ * degraded handler per call. Per-call options override the bound base.
103
+ */
104
+ export declare function createSurfaceConsumer(base: Pick<SurfaceConsumerOptions<unknown>, 'provider' | 'env' | 'appName' | 'telemetry'>): <T>(options: Omit<SurfaceConsumerOptions<T>, keyof typeof base> & Partial<Pick<SurfaceConsumerOptions<T>, keyof typeof base>>) => Promise<T>;
@@ -0,0 +1,61 @@
1
+ import type { ComponentType, ReactNode } from 'react';
2
+ export declare const DISTRIBUTED_SSR_FRAGMENTS_LOCALS_KEY = "__modernDistributedSsrFragments";
3
+ export declare const DISTRIBUTED_SSR_FRAGMENT_REQUEST_LOCALS_KEY = "__modernDistributedSsrFragmentRequest";
4
+ export type DistributedSsrFragment = {
5
+ boundaryId: string;
6
+ buildMarker?: string;
7
+ digest?: string;
8
+ expose: string;
9
+ html: string;
10
+ remote: string;
11
+ status: 'ready';
12
+ };
13
+ export type DistributedSsrFragmentFailure = {
14
+ boundaryId: string;
15
+ expose: string;
16
+ reason: string;
17
+ remote: string;
18
+ status: 'degraded';
19
+ };
20
+ type DistributedSsrFragmentResult = DistributedSsrFragment | DistributedSsrFragmentFailure;
21
+ export type DistributedSsrFragmentContext = {
22
+ fragments?: Record<string, DistributedSsrFragment | DistributedSsrFragmentFailure>;
23
+ required: true;
24
+ resolve?: (remote: string, expose: string, props: Record<string, unknown>) => DistributedSsrFragmentResult | PromiseLike<DistributedSsrFragmentResult>;
25
+ };
26
+ export type DistributedSsrBoundaryProps<Props extends object = Record<string, unknown>> = {
27
+ children: ReactNode;
28
+ expose: string;
29
+ fallback: ReactNode;
30
+ fragmentProps?: Props;
31
+ remote: string;
32
+ };
33
+ export type CreateDistributedSsrComponentOptions<Props extends object> = {
34
+ createComponent: () => ComponentType<Props>;
35
+ expose: string;
36
+ fallback: ReactNode;
37
+ remote: string;
38
+ };
39
+ export declare function distributedSsrFragmentKey(remote: string, expose: string): string;
40
+ export declare function useDistributedSsrFragmentProps<Props extends object>({ boundaryId, expose, }: {
41
+ boundaryId: string;
42
+ expose: string;
43
+ }): Props;
44
+ /**
45
+ * Keeps the browser on the native Module Federation component while allowing
46
+ * servers that cannot execute remote code (notably workerd) to render a
47
+ * trusted fragment produced by the remote Worker itself.
48
+ *
49
+ * Node SSR has no distributed-fragment context and therefore renders the
50
+ * child normally, preserving Module Federation's in-process SSR path.
51
+ */
52
+ export declare function DistributedSsrBoundary<Props extends object = Record<string, unknown>>({ children, expose, fallback, fragmentProps, remote, }: DistributedSsrBoundaryProps<Props>): import("react").JSX.Element;
53
+ /**
54
+ * Defers creation of the native Module Federation component until React
55
+ * actually renders that child. A workerd request with a verified distributed
56
+ * fragment never constructs the native remote, so its module cannot perform
57
+ * forbidden global-scope network I/O. Browser and Node rendering keep using
58
+ * the native Module Federation component unchanged.
59
+ */
60
+ export declare function createDistributedSsrComponent<Props extends object>({ createComponent, expose, fallback, remote, }: CreateDistributedSsrComponentOptions<Props>): (props: Props) => import("react").JSX.Element;
61
+ export {};
@@ -0,0 +1,71 @@
1
+ export * from './consume-surface.js';
2
+ export * from './distributed-ssr.js';
3
+ export { DISTRIBUTED_SSR_FRAGMENT_REQUEST_LOCALS_KEY, useDistributedSsrFragmentProps, } from './distributed-ssr.js';
4
+ export * from './last-known-good.js';
5
+ export * from './manifest-recovery-runtime-plugin.js';
6
+ export * from './surface-resolution-types.js';
7
+ export declare const MODULE_FEDERATION_FALLBACK_SIGNAL_EVENT = "modernjs:mf-runtime-fallback";
8
+ export declare const MODULE_FEDERATION_RECOVERY_SIGNAL_EVENT = "modernjs:mf-runtime-recovery";
9
+ export declare const DEFAULT_RUNTIME_FALLBACK_SIGNAL_ENDPOINT = "/_modern/contract-gates/runtime-fallback";
10
+ export declare const DEFAULT_RUNTIME_FALLBACK_SIGNAL_AUTH_HEADER = "x-modernjs-runtime-signal-token";
11
+ export type ModuleFederationFallbackClassification = 'timeout' | 'network' | 'contract' | 'version-skew' | 'remote-unavailable';
12
+ export type ModuleFederationFallbackStatus = 'degraded' | 'failed' | 'recovered';
13
+ export type ModuleFederationFallbackTelemetryInput = {
14
+ appName: string;
15
+ classification: ModuleFederationFallbackClassification;
16
+ entry?: string;
17
+ error?: unknown;
18
+ eventName?: string;
19
+ exportName?: string;
20
+ metadata?: Record<string, unknown>;
21
+ phase: 'discovery' | 'load' | 'mount' | 'hydrate' | 'recover';
22
+ remote: string;
23
+ runtimeDigest?: string;
24
+ status?: ModuleFederationFallbackStatus;
25
+ };
26
+ export type ModuleFederationFallbackTelemetryPayload = {
27
+ appName: string;
28
+ entry?: string;
29
+ eventName: string;
30
+ phase: ModuleFederationFallbackTelemetryInput['phase'];
31
+ reason: ModuleFederationFallbackClassification;
32
+ runtimeDigest?: string;
33
+ schemaVersion: 1;
34
+ metadata: {
35
+ classification: ModuleFederationFallbackClassification;
36
+ errorMessage?: string;
37
+ errorName?: string;
38
+ exportName?: string;
39
+ remote: string;
40
+ runtimeDigest?: string;
41
+ status: ModuleFederationFallbackStatus;
42
+ } & Record<string, unknown>;
43
+ };
44
+ export type ModuleFederationFallbackTelemetryEmitOptions = {
45
+ authHeaderName?: string;
46
+ authToken?: string;
47
+ endpoint?: string;
48
+ fetchImpl?: typeof fetch;
49
+ postSignal?: boolean;
50
+ };
51
+ export type ModuleFederationFallbackTelemetryEmitResult = {
52
+ dispatched: boolean;
53
+ posted: boolean;
54
+ postStatus?: number;
55
+ };
56
+ export declare class ModuleFederationRemoteLoadTimeoutError extends Error {
57
+ constructor(remote: string, timeoutMs: number);
58
+ }
59
+ export declare class ModuleFederationRemoteLoadError extends Error {
60
+ readonly remote: string;
61
+ readonly attempts: number;
62
+ readonly causeError: Error;
63
+ constructor(remote: string, attempts: number, causeError: Error);
64
+ }
65
+ export declare class ModuleFederationRemoteComponentContractError extends Error {
66
+ constructor(remote: string, exportName: string);
67
+ }
68
+ export declare function classifyModuleFederationFallback(error: unknown): ModuleFederationFallbackClassification;
69
+ export declare function createModuleFederationFallbackTelemetry(input: ModuleFederationFallbackTelemetryInput): ModuleFederationFallbackTelemetryPayload;
70
+ export declare function toModuleFederationFallbackAttributes(payload: ModuleFederationFallbackTelemetryPayload): Record<string, string>;
71
+ export declare function emitModuleFederationFallbackTelemetry(input: ModuleFederationFallbackTelemetryInput, options?: ModuleFederationFallbackTelemetryEmitOptions): Promise<ModuleFederationFallbackTelemetryEmitResult>;
@@ -0,0 +1,52 @@
1
+ import { type ResolvedDeliveryUnit, type SurfaceResolutionProvider } from './surface-resolution-types.js';
2
+ export declare const LAST_KNOWN_GOOD_PROVIDER_NAME = "last-known-good";
3
+ /** One cached complete record plus the time it was stored. */
4
+ export type LkgRecord = {
5
+ resolved: ResolvedDeliveryUnit;
6
+ storedAt: number;
7
+ /**
8
+ * External-major selector the record was resolved against. Participates in
9
+ * lookup validation — a cached record is only served for a matching major —
10
+ * but never in the storage key, which is (unitId, env) so all surfaces of a
11
+ * unit share one atomically-swapped record.
12
+ */
13
+ major?: number;
14
+ };
15
+ /**
16
+ * Pluggable storage hook. The default is an in-memory Map; callers may supply a
17
+ * durable store (KV, disk, etc). Reads/writes may be async. A store only ever
18
+ * receives whole records.
19
+ */
20
+ export type LkgStorage = {
21
+ read(key: string): (LkgRecord | undefined) | Promise<LkgRecord | undefined>;
22
+ write(key: string, record: LkgRecord): void | Promise<void>;
23
+ };
24
+ export type LkgFreshnessPolicy = {
25
+ /**
26
+ * Maximum age, in ms, a stored record may be served after a provider
27
+ * failure. When omitted, a served record never expires by age. A record
28
+ * older than this yields a typed `stale-record` discovery error.
29
+ */
30
+ maxStaleMs?: number;
31
+ };
32
+ export type LastKnownGoodOptions = {
33
+ /** The wrapped provider (env/static, Zephyr, or any other). */
34
+ provider: SurfaceResolutionProvider;
35
+ /** Pluggable storage; defaults to a process-local in-memory Map. */
36
+ storage?: LkgStorage;
37
+ freshness?: LkgFreshnessPolicy;
38
+ /** Clock injection for deterministic freshness tests. */
39
+ now?: () => number;
40
+ };
41
+ /** Default process-local in-memory storage. */
42
+ export declare function createInMemoryLkgStorage(): LkgStorage;
43
+ /**
44
+ * Wrap a provider with a last-known-good cache. On success the whole record is
45
+ * cached (atomic swap). On provider failure (typed discovery error or a thrown
46
+ * error) the last complete record is served, marked degraded — unless it has
47
+ * expired per {@link LkgFreshnessPolicy}, in which case a typed `stale-record`
48
+ * error is returned. If there is no cached record, the original failure is
49
+ * passed through (a thrown error becomes a `provider-unavailable` discovery
50
+ * error).
51
+ */
52
+ export declare function createLastKnownGoodProvider(options: LastKnownGoodOptions): SurfaceResolutionProvider;
@@ -0,0 +1,25 @@
1
+ type ErrorLoadRemoteArgs = {
2
+ id?: string;
3
+ error?: unknown;
4
+ lifecycle?: string;
5
+ };
6
+ export type ModuleFederationManifestRecoveryPluginOptions = {
7
+ attempts?: number;
8
+ retryDelayMs?: number;
9
+ timeoutMs?: number;
10
+ fetchImpl?: typeof fetch;
11
+ waitImpl?: (milliseconds: number) => Promise<void>;
12
+ };
13
+ /**
14
+ * Gives server-side manifest loading a small, bounded recovery window.
15
+ *
16
+ * Returning `undefined` deliberately hands control back to Module Federation:
17
+ * its runtime preserves the original typed RUNTIME-003 error and invalidates
18
+ * the rejected manifest promise. Parsed manifests are returned without schema
19
+ * interpretation so runtime-core remains the authority for RUNTIME-013.
20
+ */
21
+ export declare const createModuleFederationManifestRecoveryPlugin: (options?: ModuleFederationManifestRecoveryPluginOptions) => {
22
+ name: string;
23
+ errorLoadRemote(args: ErrorLoadRemoteArgs): Promise<unknown>;
24
+ };
25
+ export default createModuleFederationManifestRecoveryPlugin;