@satilian/plugin-mf 0.0.0-stage → 1.0.0

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 (103) hide show
  1. package/README.md +522 -2
  2. package/dist/build/bootstrap.d.ts +9 -0
  3. package/dist/build/bootstrap.js +51 -0
  4. package/dist/build/build-expose.d.ts +11 -0
  5. package/dist/build/build-expose.js +142 -0
  6. package/dist/build/build-release.d.ts +12 -0
  7. package/dist/build/build-release.js +61 -0
  8. package/dist/build/build-types.d.ts +7 -0
  9. package/dist/build/build-types.js +88 -0
  10. package/dist/build/config.d.ts +14 -0
  11. package/dist/build/config.js +1 -0
  12. package/dist/build/format-stats.d.ts +8 -0
  13. package/dist/build/format-stats.js +35 -0
  14. package/dist/build/plugin.d.ts +3 -0
  15. package/dist/build/plugin.js +87 -0
  16. package/dist/build/resolver.d.ts +1 -0
  17. package/dist/build/resolver.js +13 -0
  18. package/dist/build/shared-dependencies.d.ts +2 -0
  19. package/dist/build/shared-dependencies.js +56 -0
  20. package/dist/build/sync-types.d.ts +7 -0
  21. package/dist/build/sync-types.js +202 -0
  22. package/dist/build/type-cache.d.ts +13 -0
  23. package/dist/build/type-cache.js +160 -0
  24. package/dist/build/types-cli.d.ts +2 -0
  25. package/dist/build/types-cli.js +99 -0
  26. package/dist/build/types-options.d.ts +11 -0
  27. package/dist/build/types-options.js +10 -0
  28. package/dist/client.d.ts +12 -0
  29. package/dist/client.js +6 -0
  30. package/dist/index.d.ts +8 -0
  31. package/dist/index.js +2 -0
  32. package/dist/protocol/asset-path.d.ts +1 -0
  33. package/dist/protocol/asset-path.js +10 -0
  34. package/dist/protocol/load-error.d.ts +29 -0
  35. package/dist/protocol/load-error.js +17 -0
  36. package/dist/protocol/module.d.ts +12 -0
  37. package/dist/protocol/module.js +1 -0
  38. package/dist/protocol/network-policy.d.ts +5 -0
  39. package/dist/protocol/network-policy.js +1 -0
  40. package/dist/protocol/observability.d.ts +26 -0
  41. package/dist/protocol/observability.js +1 -0
  42. package/dist/protocol/preload.d.ts +16 -0
  43. package/dist/protocol/preload.js +1 -0
  44. package/dist/protocol/registry.d.ts +17 -0
  45. package/dist/protocol/registry.js +75 -0
  46. package/dist/protocol/release-manifest.d.ts +17 -0
  47. package/dist/protocol/release-manifest.js +29 -0
  48. package/dist/protocol/remote-manifest.d.ts +13 -0
  49. package/dist/protocol/remote-manifest.js +27 -0
  50. package/dist/protocol/shared-dependencies.d.ts +19 -0
  51. package/dist/protocol/shared-dependencies.js +20 -0
  52. package/dist/protocol/ssr-releases.d.ts +4 -0
  53. package/dist/protocol/ssr-releases.js +22 -0
  54. package/dist/protocol/type-manifest.d.ts +9 -0
  55. package/dist/protocol/type-manifest.js +19 -0
  56. package/dist/protocol/types-lock.d.ts +11 -0
  57. package/dist/protocol/types-lock.js +33 -0
  58. package/dist/release-manifest.test.d.ts +1 -0
  59. package/dist/release-manifest.test.js +119 -0
  60. package/dist/runtime/client/runtime.d.ts +12 -0
  61. package/dist/runtime/client/runtime.js +115 -0
  62. package/dist/runtime/client/runtime.js.LICENSE.txt +1 -0
  63. package/dist/runtime/core/manifest-loader.d.ts +6 -0
  64. package/dist/runtime/core/manifest-loader.js +29 -0
  65. package/dist/runtime/core/preload.d.ts +8 -0
  66. package/dist/runtime/core/preload.js +45 -0
  67. package/dist/runtime/core/remote-source.d.ts +32 -0
  68. package/dist/runtime/core/remote-source.js +159 -0
  69. package/dist/runtime/react/remote.d.ts +8 -0
  70. package/dist/runtime/react/remote.js +42 -0
  71. package/dist/runtime/server/cache/config.d.ts +11 -0
  72. package/dist/runtime/server/cache/config.js +1 -0
  73. package/dist/runtime/server/cache/disk-cache.d.ts +10 -0
  74. package/dist/runtime/server/cache/disk-cache.js +172 -0
  75. package/dist/runtime/server/cache/entry.d.ts +13 -0
  76. package/dist/runtime/server/cache/entry.js +47 -0
  77. package/dist/runtime/server/cache/lock.d.ts +3 -0
  78. package/dist/runtime/server/cache/lock.js +115 -0
  79. package/dist/runtime/server/cache/paths.d.ts +2 -0
  80. package/dist/runtime/server/cache/paths.js +17 -0
  81. package/dist/runtime/server/cache/prune.d.ts +4 -0
  82. package/dist/runtime/server/cache/prune.js +88 -0
  83. package/dist/runtime/server/loader.d.ts +11 -0
  84. package/dist/runtime/server/loader.js +49 -0
  85. package/dist/runtime/server/runtime.d.ts +18 -0
  86. package/dist/runtime/server/runtime.js +106 -0
  87. package/dist/server.d.ts +13 -0
  88. package/dist/server.js +6 -0
  89. package/dist/shared.d.ts +2 -0
  90. package/dist/shared.js +1 -0
  91. package/dist/sharing/registry.d.ts +13 -0
  92. package/dist/sharing/registry.js +69 -0
  93. package/dist/transport/loading.d.ts +16 -0
  94. package/dist/transport/loading.js +186 -0
  95. package/dist/transport/network-policy.d.ts +4 -0
  96. package/dist/transport/network-policy.js +30 -0
  97. package/dist/transport/observability.d.ts +9 -0
  98. package/dist/transport/observability.js +111 -0
  99. package/dist/transport/registry.d.ts +14 -0
  100. package/dist/transport/registry.js +96 -0
  101. package/dist/transport/release-loader.d.ts +4 -0
  102. package/dist/transport/release-loader.js +12 -0
  103. package/package.json +74 -6
@@ -0,0 +1,16 @@
1
+ export type RemoteAsset = {
2
+ path: string;
3
+ bytes: number;
4
+ type: "js" | "css";
5
+ };
6
+ export type PreloadTarget = {
7
+ remote: string;
8
+ expose: string;
9
+ };
10
+ export type PreloadOptions = {
11
+ concurrency?: number;
12
+ maxRemotes?: number;
13
+ maxJSBytes?: number;
14
+ maxCSSBytes?: number;
15
+ signal?: AbortSignal;
16
+ };
@@ -0,0 +1 @@
1
+ export { };
@@ -0,0 +1,17 @@
1
+ import type { ResolvedRelease } from "./release-manifest.ts";
2
+ export declare const MF_REGISTRY_ELEMENT_ID = "mf-registry";
3
+ export type RegistrySelection = {
4
+ url: string;
5
+ enabled?: boolean;
6
+ release?: ResolvedRelease | null;
7
+ };
8
+ export type RegistryEntry = RegistrySelection & {
9
+ canary?: RegistrySelection & {
10
+ percentage: number;
11
+ };
12
+ };
13
+ export type RegistryConfig = Record<string, RegistryEntry>;
14
+ export type RegistrySnapshot = Record<string, RegistrySelection>;
15
+ export declare function parseRegistry(value: unknown): RegistryConfig;
16
+ export declare function selectRegistry(config: RegistryConfig, key: string): RegistrySnapshot;
17
+ export declare function findRegistrySelection(name: string, fallback: string | undefined, snapshot: RegistrySnapshot): RegistrySelection | undefined;
@@ -0,0 +1,75 @@
1
+ import { parseSSRReleases } from "./ssr-releases.js";
2
+ const MF_REGISTRY_ELEMENT_ID = "mf-registry";
3
+ function parseSelection(value) {
4
+ if (!value || "object" != typeof value || !("url" in value) || "string" != typeof value.url) throw new Error("[plugin-mf] Invalid registry selection");
5
+ const url = new URL(value.url);
6
+ if (![
7
+ "http:",
8
+ "https:"
9
+ ].includes(url.protocol) || url.username || url.password) throw new Error("[plugin-mf] Invalid registry URL");
10
+ if ("enabled" in value && "boolean" != typeof value.enabled) throw new Error("[plugin-mf] Invalid registry enabled flag");
11
+ const selection = {
12
+ url: url.href.replace(/\/$/, ""),
13
+ enabled: !("enabled" in value) || true === value.enabled
14
+ };
15
+ if ("release" in value && void 0 !== value.release) selection.release = parseSSRReleases({
16
+ [url.href]: value.release
17
+ })[url.href];
18
+ return selection;
19
+ }
20
+ function parseRegistry(value) {
21
+ if (!value || "object" != typeof value || Array.isArray(value)) throw new Error("[plugin-mf] Invalid registry");
22
+ return Object.fromEntries(Object.entries(value).map(([name, entry])=>{
23
+ const selection = parseSelection(entry);
24
+ if (entry && "object" == typeof entry && "canary" in entry && void 0 !== entry.canary) {
25
+ const canary = entry.canary;
26
+ if (!canary || "object" != typeof canary || !("percentage" in canary) || "number" != typeof canary.percentage || !Number.isFinite(canary.percentage) || canary.percentage < 0 || canary.percentage > 100) throw new Error(`[plugin-mf] Invalid canary percentage: ${name}`);
27
+ selection.canary = {
28
+ ...parseSelection(canary),
29
+ percentage: canary.percentage
30
+ };
31
+ }
32
+ return [
33
+ name,
34
+ selection
35
+ ];
36
+ }));
37
+ }
38
+ function selectRegistry(config, key) {
39
+ const selected = Object.fromEntries(Object.entries(config).map(([name, entry])=>{
40
+ let hash = 2166136261;
41
+ for (const char of `${name}:${key}`)hash = Math.imul(hash ^ char.charCodeAt(0), 16777619);
42
+ const choice = entry.canary && (hash >>> 0) % 10000 < 100 * entry.canary.percentage ? entry.canary : entry;
43
+ return [
44
+ name,
45
+ {
46
+ url: choice.url,
47
+ enabled: choice.enabled,
48
+ ...void 0 !== choice.release ? {
49
+ release: choice.release
50
+ } : {}
51
+ }
52
+ ];
53
+ }));
54
+ const releases = new Map();
55
+ for (const entry of Object.values(selected))if (false !== entry.enabled && void 0 !== entry.release) {
56
+ if (releases.has(entry.url) && JSON.stringify(releases.get(entry.url)) !== JSON.stringify(entry.release)) throw new Error(`[plugin-mf] Conflicting registry releases for ${entry.url}`);
57
+ releases.set(entry.url, entry.release);
58
+ }
59
+ for (const entry of Object.values(selected))if (releases.has(entry.url)) entry.release = releases.get(entry.url);
60
+ return selected;
61
+ }
62
+ function findRegistrySelection(name, fallback, snapshot) {
63
+ if (Object.hasOwn(snapshot, name)) return snapshot[name];
64
+ if (!fallback) return;
65
+ const url = fallback.replace(/\/$/, "");
66
+ const pinned = Object.values(snapshot).find((entry)=>entry.url === url && void 0 !== entry.release);
67
+ return {
68
+ url,
69
+ enabled: true,
70
+ ...pinned?.release !== void 0 ? {
71
+ release: pinned.release
72
+ } : {}
73
+ };
74
+ }
75
+ export { MF_REGISTRY_ELEMENT_ID, findRegistrySelection, parseRegistry, selectRegistry };
@@ -0,0 +1,17 @@
1
+ import { type ReleaseSharing } from "./shared-dependencies.ts";
2
+ export declare const RELEASE_MANIFEST_VERSION = 1;
3
+ /** Paths are relative to the directory containing manifest.json. */
4
+ export type ReleaseManifest = {
5
+ version: typeof RELEASE_MANIFEST_VERSION;
6
+ releaseId: string;
7
+ server?: string;
8
+ client?: string;
9
+ types: string;
10
+ shared?: ReleaseSharing;
11
+ };
12
+ export type ResolvedRelease = {
13
+ manifest: ReleaseManifest;
14
+ baseUrl: string;
15
+ };
16
+ export declare function parseReleaseManifest(value: unknown): ReleaseManifest;
17
+ export declare function parseReleaseId(value: unknown): string;
@@ -0,0 +1,29 @@
1
+ import { parseSharedRequirements } from "./shared-dependencies.js";
2
+ const RELEASE_MANIFEST_VERSION = 1;
3
+ function parseReleaseManifest(value) {
4
+ if (!value || "object" != typeof value || Array.isArray(value)) throw new Error("Invalid release manifest");
5
+ const manifest = value;
6
+ if (manifest.version !== RELEASE_MANIFEST_VERSION) throw new Error(`Unsupported release manifest version: ${String(manifest.version)}`);
7
+ parseReleaseId(manifest.releaseId);
8
+ if (void 0 !== manifest.shared) {
9
+ const shared = manifest.shared;
10
+ if (!shared || "object" != typeof shared || !("client" in shared) || !("server" in shared)) throw new Error("Invalid release shared requirements");
11
+ parseSharedRequirements(shared.client);
12
+ parseSharedRequirements(shared.server);
13
+ }
14
+ for (const key of [
15
+ "server",
16
+ "client",
17
+ "types"
18
+ ]){
19
+ const value = manifest[key];
20
+ if (("types" === key || void 0 !== value) && ("string" != typeof value || !value || value.startsWith("/") || value.includes("\\") || value.split("/").some((part)=>!part || ".." === part || "." === part) || value.includes(":") || value.includes("?") || value.includes("#"))) throw new Error(`Invalid ${key} path in release manifest`);
21
+ }
22
+ if (void 0 === manifest.server && void 0 === manifest.client) throw new Error("Release manifest does not contain server or client assets");
23
+ return manifest;
24
+ }
25
+ function parseReleaseId(value) {
26
+ if ("string" != typeof value || !/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(value)) throw new Error("Invalid releaseId in release manifest");
27
+ return value;
28
+ }
29
+ export { RELEASE_MANIFEST_VERSION, parseReleaseId, parseReleaseManifest };
@@ -0,0 +1,13 @@
1
+ import type { RemoteAsset } from "./preload.ts";
2
+ export type RemoteManifest = Record<string, string | {
3
+ js: string;
4
+ css: string[];
5
+ files?: string[];
6
+ integrity?: Record<string, string>;
7
+ assets?: RemoteAsset[];
8
+ }>;
9
+ export type RemoteInfo = {
10
+ manifest: RemoteManifest;
11
+ __baseUrl: string;
12
+ };
13
+ export declare function parseRemoteManifest(value: unknown): RemoteManifest;
@@ -0,0 +1,27 @@
1
+ import { validateAssetPath } from "./asset-path.js";
2
+ function parseRemoteManifest(value) {
3
+ const manifest = value;
4
+ if (!manifest || "object" != typeof manifest || Array.isArray(manifest)) throw new Error("Invalid remote manifest");
5
+ for (const [name, path] of Object.entries(manifest))if ("string" != typeof path || !path.length) {
6
+ if (!path || "object" != typeof path || Array.isArray(path) || "string" != typeof path.js || !path.js || !Array.isArray(path.css) || !path.css.every((asset)=>"string" == typeof asset && asset.length > 0)) throw new Error(`Invalid remote assets for "${name}"`);
7
+ if (void 0 !== path.files) {
8
+ if (!Array.isArray(path.files) || !path.files.includes(path.js)) throw new Error(`Invalid remote files for "${name}"`);
9
+ for (const file of path.files){
10
+ if ("string" != typeof file) throw new Error(`Invalid remote file for "${name}"`);
11
+ validateAssetPath(file);
12
+ }
13
+ }
14
+ if (void 0 !== path.integrity) {
15
+ if (!path.integrity || "object" != typeof path.integrity || Array.isArray(path.integrity) || !path.files || Object.keys(path.integrity).length !== path.files.length || !path.files.every((file)=>"string" == typeof path.integrity[file] && /^[a-f0-9]{64}$/.test(path.integrity[file]))) throw new Error(`Invalid server integrity for "${name}"`);
16
+ }
17
+ if (void 0 !== path.assets) {
18
+ if (!Array.isArray(path.assets)) throw new Error(`Invalid asset sizes for "${name}"`);
19
+ for (const asset of path.assets){
20
+ if (!asset || "object" != typeof asset || "string" != typeof asset.path || !Number.isSafeInteger(asset.bytes) || asset.bytes < 0 || "js" !== asset.type && "css" !== asset.type) throw new Error(`Invalid asset size for "${name}"`);
21
+ validateAssetPath(asset.path);
22
+ }
23
+ }
24
+ }
25
+ return manifest;
26
+ }
27
+ export { parseRemoteManifest };
@@ -0,0 +1,19 @@
1
+ export type SharedConfig = {
2
+ name: string;
3
+ version?: string;
4
+ requiredVersion?: string;
5
+ singleton?: boolean;
6
+ };
7
+ export type SharedDependency = string | SharedConfig;
8
+ export type SharedRequirement = {
9
+ version: string;
10
+ requiredVersion: string;
11
+ singleton: boolean;
12
+ };
13
+ export type SharedRequirements = Record<string, SharedRequirement>;
14
+ export type ReleaseSharing = {
15
+ client: SharedRequirements;
16
+ server: SharedRequirements;
17
+ };
18
+ export declare function packageName(request: string): string;
19
+ export declare function parseSharedRequirements(value: unknown): SharedRequirements;
@@ -0,0 +1,20 @@
1
+ import valid from "semver/functions/valid.js";
2
+ import ranges_valid from "semver/ranges/valid.js";
3
+ function packageName(request) {
4
+ return request.startsWith("@") ? request.split("/").slice(0, 2).join("/") : request.split("/")[0];
5
+ }
6
+ function parseSharedRequirements(value) {
7
+ if (!value || "object" != typeof value || Array.isArray(value)) throw new Error("Invalid shared requirements");
8
+ return Object.fromEntries(Object.entries(value).map(([name, entry])=>{
9
+ if (!name || !entry || "object" != typeof entry || !("version" in entry) || "string" != typeof entry.version || !valid(entry.version) || !("requiredVersion" in entry) || "string" != typeof entry.requiredVersion || !ranges_valid(entry.requiredVersion) || !("singleton" in entry) || "boolean" != typeof entry.singleton) throw new Error(`Invalid shared requirement: ${name}`);
10
+ return [
11
+ name,
12
+ {
13
+ version: entry.version,
14
+ requiredVersion: entry.requiredVersion,
15
+ singleton: entry.singleton
16
+ }
17
+ ];
18
+ }));
19
+ }
20
+ export { packageName, parseSharedRequirements };
@@ -0,0 +1,4 @@
1
+ import { type ResolvedRelease } from "./release-manifest.ts";
2
+ export declare const MF_RELEASES_ELEMENT_ID = "mf-releases";
3
+ export type SSRReleases = Record<string, ResolvedRelease | null>;
4
+ export declare function parseSSRReleases(value: unknown): SSRReleases;
@@ -0,0 +1,22 @@
1
+ import { parseReleaseManifest } from "./release-manifest.js";
2
+ const MF_RELEASES_ELEMENT_ID = "mf-releases";
3
+ function parseSSRReleases(value) {
4
+ if (!value || "object" != typeof value || Array.isArray(value)) throw new Error("[plugin-mf] Invalid SSR release map");
5
+ return Object.fromEntries(Object.entries(value).map(([url, release])=>{
6
+ if (null === release) return [
7
+ url,
8
+ null
9
+ ];
10
+ if (!release || "object" != typeof release || !("baseUrl" in release) || "string" != typeof release.baseUrl || !("manifest" in release)) throw new Error(`[plugin-mf] Invalid SSR release for "${url}"`);
11
+ const baseUrl = new URL(release.baseUrl);
12
+ if ("http:" !== baseUrl.protocol && "https:" !== baseUrl.protocol) throw new Error(`[plugin-mf] Invalid SSR release base URL for "${url}"`);
13
+ return [
14
+ url,
15
+ {
16
+ baseUrl: baseUrl.href,
17
+ manifest: parseReleaseManifest(release.manifest)
18
+ }
19
+ ];
20
+ }));
21
+ }
22
+ export { MF_RELEASES_ELEMENT_ID, parseSSRReleases };
@@ -0,0 +1,9 @@
1
+ export type RemoteTypeManifest = {
2
+ version: 1;
3
+ files: string[];
4
+ exposes: Record<string, {
5
+ path: string;
6
+ export: string;
7
+ }>;
8
+ };
9
+ export declare function parseTypeManifest(value: unknown): RemoteTypeManifest;
@@ -0,0 +1,19 @@
1
+ import { validateAssetPath } from "./asset-path.js";
2
+ function parseTypeManifest(value) {
3
+ if (!value || "object" != typeof value) throw new Error("Invalid types manifest");
4
+ const manifest = value;
5
+ if (1 !== manifest.version || !Array.isArray(manifest.files) || !manifest.exposes || "object" != typeof manifest.exposes || Array.isArray(manifest.exposes)) throw new Error("Invalid types manifest");
6
+ for (const filePath of manifest.files)validatePath(filePath);
7
+ if (new Set(manifest.files.map((file)=>file.toLowerCase())).size !== manifest.files.length) throw new Error("Duplicate declaration paths in types manifest");
8
+ for (const [name, info] of Object.entries(manifest.exposes)){
9
+ if (!name || !info || "string" != typeof info.path || "string" != typeof info.export) throw new Error("Invalid exposed type in manifest");
10
+ validatePath(info.path);
11
+ if (!manifest.files.includes(info.path)) throw new Error(`Missing declaration "${info.path}" for exposed module "${name}"`);
12
+ }
13
+ return manifest;
14
+ }
15
+ function validatePath(filePath) {
16
+ if ("string" != typeof filePath || !filePath.endsWith(".d.ts")) throw new Error(`Invalid declaration path "${filePath}"`);
17
+ validateAssetPath(filePath);
18
+ }
19
+ export { parseTypeManifest };
@@ -0,0 +1,11 @@
1
+ export type TypesLockEntry = {
2
+ provider: string;
3
+ releaseId?: string;
4
+ manifestUrl: string;
5
+ cacheKey: string;
6
+ };
7
+ export type TypesLock = {
8
+ version: 1;
9
+ remotes: Record<string, TypesLockEntry>;
10
+ };
11
+ export declare function parseTypesLock(value: unknown): TypesLock;
@@ -0,0 +1,33 @@
1
+ import { parseReleaseId } from "./release-manifest.js";
2
+ function parseTypesLock(value) {
3
+ if (!value || "object" != typeof value || !("version" in value) || 1 !== value.version || !("remotes" in value) || !value.remotes || "object" != typeof value.remotes || Array.isArray(value.remotes)) throw new Error("[plugin-mf] Invalid types lock file");
4
+ const remotes = {};
5
+ for (const [name, entry] of Object.entries(value.remotes)){
6
+ if (!entry || "object" != typeof entry || !("provider" in entry) || "string" != typeof entry.provider || !("manifestUrl" in entry) || "string" != typeof entry.manifestUrl || !("cacheKey" in entry) || "string" != typeof entry.cacheKey || !/^[a-f0-9]{64}$/.test(entry.cacheKey)) throw new Error(`[plugin-mf] Invalid types lock entry: ${name}`);
7
+ for (const url of [
8
+ entry.provider,
9
+ entry.manifestUrl
10
+ ])if (![
11
+ "http:",
12
+ "https:"
13
+ ].includes(new URL(url).protocol)) throw new Error("[plugin-mf] Invalid types lock URL");
14
+ let releaseId;
15
+ if ("releaseId" in entry && void 0 !== entry.releaseId) releaseId = parseReleaseId(entry.releaseId);
16
+ Object.defineProperty(remotes, name, {
17
+ enumerable: true,
18
+ value: {
19
+ provider: entry.provider,
20
+ manifestUrl: entry.manifestUrl,
21
+ cacheKey: entry.cacheKey,
22
+ ...releaseId ? {
23
+ releaseId
24
+ } : {}
25
+ }
26
+ });
27
+ }
28
+ return {
29
+ version: 1,
30
+ remotes
31
+ };
32
+ }
33
+ export { parseTypesLock };
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,119 @@
1
+ import strict from "node:assert/strict";
2
+ import { afterEach, test } from "node:test";
3
+ import { parseReleaseManifest } from "./protocol/release-manifest.js";
4
+ import { loadReleaseManifest } from "./transport/release-loader.js";
5
+ import { Remote } from "./runtime/react/remote.js";
6
+ const originalFetch = globalThis.fetch;
7
+ afterEach(()=>{
8
+ globalThis.fetch = originalFetch;
9
+ });
10
+ function response(body, url, status = 200) {
11
+ return {
12
+ ok: status < 400,
13
+ status,
14
+ statusText: 404 === status ? "Not Found" : "OK",
15
+ url,
16
+ json: async ()=>body
17
+ };
18
+ }
19
+ test("release manifest validates version, paths and identifier", ()=>{
20
+ const valid = {
21
+ version: 1,
22
+ releaseId: "release-123",
23
+ server: "server/manifest.json",
24
+ client: "client/manifest.json",
25
+ types: "types/manifest.json"
26
+ };
27
+ strict.deepEqual(parseReleaseManifest(valid), valid);
28
+ for (const invalid of [
29
+ {
30
+ ...valid,
31
+ version: 2
32
+ },
33
+ {
34
+ ...valid,
35
+ releaseId: "../escape"
36
+ },
37
+ {
38
+ ...valid,
39
+ client: "../escape"
40
+ },
41
+ {
42
+ ...valid,
43
+ types: "https://other.invalid/types"
44
+ },
45
+ {
46
+ ...valid,
47
+ server: void 0,
48
+ client: void 0
49
+ }
50
+ ])strict.throws(()=>parseReleaseManifest(invalid));
51
+ });
52
+ test("only 404 selects legacy layout", async ()=>{
53
+ globalThis.fetch = async (url)=>response(null, String(url), 404);
54
+ strict.equal(await loadReleaseManifest("https://example.test/mf/manifest.json"), void 0);
55
+ globalThis.fetch = async (url)=>response(null, String(url), 500);
56
+ await strict.rejects(loadReleaseManifest("https://example.test/mf/manifest.json"), /500/);
57
+ });
58
+ test("server resolves both manifests from the same release", async ()=>{
59
+ const urls = [];
60
+ globalThis.fetch = async (input)=>{
61
+ const url = String(input);
62
+ urls.push(url);
63
+ if (url.endsWith("/mf/manifest.json")) return response({
64
+ version: 1,
65
+ releaseId: "r1",
66
+ server: "releases/r1/server/manifest.json",
67
+ client: "releases/r1/client/manifest.json",
68
+ types: "releases/r1/types/manifest.json"
69
+ }, url);
70
+ if (url.endsWith("/server/manifest.json")) return response({
71
+ Card: {
72
+ js: "card.js",
73
+ css: []
74
+ }
75
+ }, url);
76
+ if (url.endsWith("/client/manifest.json")) return response({
77
+ Card: {
78
+ js: "card.js",
79
+ css: [
80
+ "card.css"
81
+ ]
82
+ }
83
+ }, url);
84
+ throw new Error(`Unexpected fetch: ${url}`);
85
+ };
86
+ const remote = new Remote("https://example.test/mf", {
87
+ load: async ()=>({
88
+ Card: ()=>null
89
+ })
90
+ }, "server");
91
+ strict.equal(typeof await remote.component("Card"), "function");
92
+ strict.equal(remote.releaseId, "r1");
93
+ strict.deepEqual(urls, [
94
+ "https://example.test/mf/manifest.json",
95
+ "https://example.test/mf/releases/r1/server/manifest.json",
96
+ "https://example.test/mf/releases/r1/client/manifest.json"
97
+ ]);
98
+ });
99
+ test("legacy remote uses scope manifests without a release", async ()=>{
100
+ const urls = [];
101
+ globalThis.fetch = async (input)=>{
102
+ const url = String(input);
103
+ urls.push(url);
104
+ return url.endsWith("/mf/manifest.json") ? response(null, url, 404) : response({
105
+ Card: "card.js"
106
+ }, url);
107
+ };
108
+ const remote = new Remote("https://example.test/mf", {
109
+ load: async ()=>({
110
+ Card: ()=>null
111
+ })
112
+ }, "client");
113
+ strict.equal(typeof await remote.component("Card"), "function");
114
+ strict.equal(remote.releaseId, void 0);
115
+ strict.deepEqual(urls, [
116
+ "https://example.test/mf/manifest.json",
117
+ "https://example.test/mf/client/manifest.json"
118
+ ]);
119
+ });
@@ -0,0 +1,12 @@
1
+ import type { ModuleLoader, RemoteModule, ModuleLoadContext } from "../../protocol/module.ts";
2
+ import { type ComponentType } from "react";
3
+ import type { PreloadOptions, PreloadTarget } from "../../protocol/preload.ts";
4
+ import { Remote } from "../react/remote.ts";
5
+ export declare class Loader implements ModuleLoader {
6
+ #private;
7
+ load(url: string, context?: ModuleLoadContext): Promise<RemoteModule>;
8
+ }
9
+ export declare function initializeMFReleases(): Promise<void>;
10
+ export declare function getRemote(name: string): Remote;
11
+ export declare function preloadRemotes(targets: PreloadTarget[], options?: PreloadOptions): Promise<void>;
12
+ export declare function createRemoteComponent<Props extends object = Record<string, unknown>>(remoteName: string, expose: string): ComponentType<Props>;
@@ -0,0 +1,115 @@
1
+ /*! LICENSE: runtime.js.LICENSE.txt */
2
+ import { createElement } from "react";
3
+ import { configureLoading, fetchResource, loadingPolicy, retryNetwork, withDeadline } from "../../transport/loading.js";
4
+ import { RemoteLoadError } from "../../protocol/load-error.js";
5
+ import { assertRemoteURL, configureNetwork } from "../../transport/network-policy.js";
6
+ import { emitLoadingEvent, observeLoading } from "../../transport/observability.js";
7
+ import { preload } from "../core/preload.js";
8
+ import { getRegistryOverrides, registerStaticRemotes } from "../../transport/registry.js";
9
+ import { MF_REGISTRY_ELEMENT_ID, findRegistrySelection, parseRegistry, selectRegistry } from "../../protocol/registry.js";
10
+ import { Remote } from "../react/remote.js";
11
+ import { MF_RELEASES_ELEMENT_ID, parseSSRReleases } from "../../protocol/ssr-releases.js";
12
+ const importModule = (url)=>import(/* webpackIgnore: true, reason: "@preserve native import" */ url);
13
+ class Loader {
14
+ #cache = new Map();
15
+ #attempts = new Map();
16
+ load(url, context) {
17
+ const provider = context?.provider ?? url;
18
+ assertRemoteURL(url, provider);
19
+ const loadContext = {
20
+ remote: provider,
21
+ releaseId: context?.releaseId,
22
+ stage: "module"
23
+ };
24
+ const cached = this.#cache.get(url);
25
+ if (cached) {
26
+ emitLoadingEvent({
27
+ ...loadContext,
28
+ type: "cache-hit",
29
+ operation: "module"
30
+ });
31
+ return cached;
32
+ }
33
+ const attempt = this.#attempts.get(url) ?? 0;
34
+ const promise = observeLoading(loadContext, "module", ()=>withDeadline(loadContext, loadingPolicy().moduleTimeoutMs, (signal)=>retryNetwork(async (retry)=>{
35
+ const target = new URL(url);
36
+ const generation = attempt + retry;
37
+ this.#attempts.set(url, generation);
38
+ if (generation) target.searchParams.set("mf_retry", String(generation));
39
+ const checked = await fetchResource(target.href, {
40
+ remote: provider,
41
+ releaseId: context?.releaseId,
42
+ stage: "module"
43
+ }, async (response)=>{
44
+ await response.arrayBuffer();
45
+ return response.url || target.href;
46
+ }, signal);
47
+ return importModule(checked);
48
+ }, signal, (error)=>error instanceof TypeError && /failed to fetch dynamically imported module|error loading dynamically imported module|failed to load module script|importing a module script failed/i.test(error.message), loadContext))).catch((error)=>{
49
+ this.#cache.delete(url);
50
+ this.#attempts.set(url, (this.#attempts.get(url) ?? attempt) + 1);
51
+ throw error;
52
+ });
53
+ this.#cache.set(url, promise);
54
+ return promise;
55
+ }
56
+ }
57
+ const remotes = new Map();
58
+ let releases;
59
+ let pinnedRegistry;
60
+ let registryInitialized = false;
61
+ function readMFReleases() {
62
+ if (releases) return releases;
63
+ const element = document.getElementById(MF_RELEASES_ELEMENT_ID);
64
+ if (element) releases = parseSSRReleases(JSON.parse(element.textContent || ""));
65
+ return releases;
66
+ }
67
+ async function initializeMFReleases() {
68
+ if ("loading" === document.readyState) await new Promise((resolve)=>document.addEventListener("DOMContentLoaded", ()=>resolve(), {
69
+ once: true
70
+ }));
71
+ readMFReleases();
72
+ readRegistry();
73
+ }
74
+ function readRegistry() {
75
+ if (pinnedRegistry) return pinnedRegistry;
76
+ const element = document.getElementById(MF_REGISTRY_ELEMENT_ID);
77
+ if (element) pinnedRegistry = selectRegistry(parseRegistry(JSON.parse(element.textContent || "")), "");
78
+ return pinnedRegistry;
79
+ }
80
+ if ("u" > typeof __MF_NETWORK__) configureNetwork(__MF_NETWORK__);
81
+ function ensureInit() {
82
+ if (registryInitialized) return;
83
+ if ("u" > typeof __MF_LOADING__) configureLoading(__MF_LOADING__);
84
+ registerStaticRemotes("u" < typeof __MF_REMOTES__ ? {} : __MF_REMOTES__ ?? {});
85
+ registryInitialized = true;
86
+ }
87
+ function getRemote(name) {
88
+ ensureInit();
89
+ const selection = findRegistrySelection(name, "u" < typeof __MF_REMOTES__ ? void 0 : __MF_REMOTES__?.[name], readRegistry() ?? getRegistryOverrides());
90
+ if (!selection || false === selection.enabled) throw new RemoteLoadError({
91
+ remote: name,
92
+ stage: "module"
93
+ }, "LOAD_FAILED", selection ? "Remote is disabled" : "Remote not found in registry");
94
+ const identity = JSON.stringify(selection);
95
+ const cached = remotes.get(name);
96
+ if (cached?.identity === identity) return cached.remote;
97
+ const remote = new Remote(selection.url, new Loader(), "client", ()=>void 0 !== selection.release ? selection.release : readMFReleases()?.[selection.url]);
98
+ remotes.set(name, {
99
+ identity,
100
+ remote
101
+ });
102
+ return remote;
103
+ }
104
+ function preloadRemotes(targets, options) {
105
+ return preload(targets.map(({ remote, expose })=>({
106
+ source: getRemote(remote),
107
+ expose
108
+ })), options);
109
+ }
110
+ function createRemoteComponent(remoteName, expose) {
111
+ return function(props) {
112
+ return createElement(getRemote(remoteName).lazyComponent(expose), props);
113
+ };
114
+ }
115
+ export { Loader, createRemoteComponent, getRemote, initializeMFReleases, preloadRemotes };
@@ -0,0 +1 @@
1
+ /* webpackIgnore: true, reason: "@preserve native import" */
@@ -0,0 +1,6 @@
1
+ import { type RemoteInfo } from "../../protocol/remote-manifest.ts";
2
+ import type { LoadContext } from "../../protocol/load-error.ts";
3
+ export declare class ManifestLoader {
4
+ #private;
5
+ load(url: string, context: LoadContext, signal?: AbortSignal): Promise<RemoteInfo>;
6
+ }
@@ -0,0 +1,29 @@
1
+ import { parseRemoteManifest } from "../../protocol/remote-manifest.js";
2
+ import { fetchResource } from "../../transport/loading.js";
3
+ import { emitLoadingEvent } from "../../transport/observability.js";
4
+ class ManifestLoader {
5
+ #cache = new Map();
6
+ async load(url, context, signal) {
7
+ const cached = this.#cache.get(url);
8
+ if (cached) {
9
+ emitLoadingEvent({
10
+ ...context,
11
+ type: "cache-hit",
12
+ operation: "fetch"
13
+ });
14
+ return cached;
15
+ }
16
+ const promise = fetchResource(url, context, async (response)=>({
17
+ manifest: parseRemoteManifest(await response.json()),
18
+ __baseUrl: new URL(".", response.url).href
19
+ }), signal);
20
+ this.#cache.set(url, promise);
21
+ try {
22
+ return await promise;
23
+ } catch (error) {
24
+ this.#cache.delete(url);
25
+ throw error;
26
+ }
27
+ }
28
+ }
29
+ export { ManifestLoader };
@@ -0,0 +1,8 @@
1
+ import type { PreloadOptions } from "../../protocol/preload.ts";
2
+ import type { RemoteSource } from "./remote-source.ts";
3
+ type Target = {
4
+ source: RemoteSource;
5
+ expose: string;
6
+ };
7
+ export declare function preload(targets: Target[], options?: PreloadOptions): Promise<void>;
8
+ export {};