every-plugin 3.0.0-rc.4 → 3.0.0-rc.6

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.
@@ -19,6 +19,9 @@ function hasFolderFormUi(cwd) {
19
19
  const uiDir = node_path.default.join(cwd, UI_DIR);
20
20
  return node_fs.default.existsSync(node_path.default.join(uiDir, "src", "routes")) && !node_fs.default.existsSync(node_path.default.join(uiDir, "package.json"));
21
21
  }
22
+ function uiDistDirFor(cwd) {
23
+ return node_path.default.join(cwd, UI_DIR, "dist");
24
+ }
22
25
  function generatedUiConfig(pluginId) {
23
26
  return `import path from "node:path";
24
27
  import { createUiRsbuildConfig } from "every-plugin/build/ui";
@@ -115,4 +118,5 @@ exports.ensureGeneratedUiRsbuildConfig = ensureGeneratedUiRsbuildConfig;
115
118
  exports.hasCoreUiWorkspace = hasCoreUiWorkspace;
116
119
  exports.hasFolderFormUi = hasFolderFormUi;
117
120
  exports.pluginLayoutKey = pluginLayoutKey;
121
+ exports.uiDistDirFor = uiDistDirFor;
118
122
  //# sourceMappingURL=generated-config.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"generated-config.cjs","names":["path","fs","findBosConfigPath"],"sources":["../../../src/build/ui/generated-config.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport path from \"node:path\";\nimport { findBosConfigPath } from \"../rspack/compose\";\n\nconst UI_DIR = \"ui\";\nconst GENERATED_CONFIG_DIR = \".every-plugin\";\nconst GENERATED_UI_CONFIG = \"ui.rsbuild.config.generated.mjs\";\n\n/**\n * Folder-form UI source: a `ui/` directory with route files but no own\n * package.json — the plugin workspace owns the build (single-workspace\n * plugin, one dev process, one deploy train). Workspace-form ui sources\n * (own package.json + scripts) are NOT managed here.\n */\nexport function hasFolderFormUi(cwd: string): boolean {\n const uiDir = path.join(cwd, UI_DIR);\n return (\n fs.existsSync(path.join(uiDir, \"src\", \"routes\")) &&\n !fs.existsSync(path.join(uiDir, \"package.json\"))\n );\n}\n\nfunction generatedUiConfig(pluginId: string): string {\n return `import path from \"node:path\";\nimport { createUiRsbuildConfig } from \"every-plugin/build/ui\";\nimport pkg from \"../package.json\";\n\nconst workspaceRoot = path.resolve(import.meta.dirname, \"..\", \"ui\");\n\nexport default createUiRsbuildConfig({\n workspaceRoot,\n pkg,\n role: \"consumer\",\n manifestName: ${JSON.stringify(pluginId)},\n devPort: Number(process.env.BOS_UI_PORT) || 0,\n webEntry: \"./ui/src/routeConfig.gen.ts\",\n webExposes: { \"./routeConfig\": \"./ui/src/routeConfig.gen.ts\" },\n nodeEntry: \"./ui/src/routeConfig.gen.ts\",\n nodeExposes: { \"./routeConfig\": \"./ui/src/routeConfig.gen.ts\" },\n routesDirectory: \"./ui/src/routes\",\n});\n`;\n}\n\n/**\n * Canonical config-layout derivation: the composition key for a plugin\n * workspace — the `<key>` of the `plugins/<key>` directory relative to the\n * nearest `bos.config.json`. The dev server and the generated ui config\n * both key off this; no consumer keeps a private copy.\n */\nexport function pluginLayoutKey(cwd: string): string | null {\n const bosConfigPath = findBosConfigPath(cwd);\n const relativeWorkspace = bosConfigPath\n ? path.relative(path.dirname(bosConfigPath), cwd)\n : undefined;\n const [workspaceGroup, layoutKey] = relativeWorkspace?.split(path.sep) ?? [];\n return workspaceGroup === \"plugins\" && layoutKey ? layoutKey : null;\n}\n\n/**\n * Synthesize the rsbuild config for a folder-form ui source (the plugin\n * build contract, not per-plugin config — mirrors the rspack generated\n * config). Returns the config file path, or null when the workspace has no\n * folder-form ui source.\n */\nexport function ensureGeneratedUiRsbuildConfig(cwd: string): string | null {\n if (!hasFolderFormUi(cwd)) return null;\n // The manifest's name derives ONLY from the plugins/<key> layout key\n // (ADR 0008 §2) — a non-derivable key fails the build loudly, never the\n // container-name fallback that mis-keyed manifests.\n const pluginId = pluginLayoutKey(cwd);\n if (!pluginId) {\n throw new Error(\n `[every-plugin] cannot derive the ui's composition key from ${cwd} — no authored config (bos.app.ts / bos.config.json) found above a plugins/<key> directory. The manifest name is the layout key; the container name is never a fallback.`,\n );\n }\n const outDir = path.join(cwd, GENERATED_CONFIG_DIR);\n fs.mkdirSync(outDir, { recursive: true });\n const outPath = path.join(outDir, GENERATED_UI_CONFIG);\n const next = generatedUiConfig(pluginId);\n if (!fs.existsSync(outPath) || fs.readFileSync(outPath, \"utf8\") !== next) {\n fs.writeFileSync(outPath, next);\n }\n return outPath;\n}\n\nconst CORE_UI_MARKERS = {\n routes: \"src/routes\",\n contract: \"src/contract.ts\",\n};\n\n/**\n * Workspace-form core ui: the workspace IS the ui (own package.json, route\n * tree) and is not plugin-shaped — the /api counterpart of the plugin\n * workspace form. The entry stub is NOT a marker: it is generated\n * (ADR 0023), so a fresh clone has no bootstrap stubs until the first\n * generation pass.\n */\nexport function hasCoreUiWorkspace(cwd: string = process.cwd()): boolean {\n return (\n fs.existsSync(path.join(cwd, CORE_UI_MARKERS.routes)) &&\n !fs.existsSync(path.join(cwd, CORE_UI_MARKERS.contract)) &&\n !fs.existsSync(path.join(cwd, \"plugin.dev.ts\"))\n );\n}\n\nfunction generatedCoreUiConfig(): string {\n return `import { defineConfig } from \"@rsbuild/core\";\nimport { readAuthoredConfigInput } from \"everything-dev/config\";\nimport { createCoreUiRsbuildConfig } from \"every-plugin/build/ui\";\n\nexport default defineConfig(async () =>\n createCoreUiRsbuildConfig(await readAuthoredConfigInput()),\n);\n`;\n}\n\n/**\n * Synthesize the rsbuild config for a workspace-form core ui with no local\n * `rsbuild.config.ts` — the /api generated-config model. A local file is an\n * override and wins untouched. Returns the workspace-relative config path,\n * or null when the workspace is not a core ui (or has a local config).\n */\nexport function ensureGeneratedCoreUiRsbuildConfig(cwd: string = process.cwd()): string | null {\n if (!hasCoreUiWorkspace(cwd)) return null;\n if (fs.existsSync(path.join(cwd, \"rsbuild.config.ts\"))) return null;\n const outDir = path.join(cwd, GENERATED_CONFIG_DIR);\n fs.mkdirSync(outDir, { recursive: true });\n const outPath = path.join(outDir, GENERATED_UI_CONFIG);\n fs.writeFileSync(outPath, generatedCoreUiConfig());\n console.log(\"[every-plugin] rsbuild.config.ts not found — using the core ui build factory.\");\n return path.join(GENERATED_CONFIG_DIR, GENERATED_UI_CONFIG);\n}\n"],"mappings":";;;;;;;;AAIA,MAAM,SAAS;AACf,MAAM,uBAAuB;AAC7B,MAAM,sBAAsB;;;;;;;AAQ5B,SAAgB,gBAAgB,KAAsB;CACpD,MAAM,QAAQA,kBAAK,KAAK,KAAK,MAAM;CACnC,OACEC,gBAAG,WAAWD,kBAAK,KAAK,OAAO,OAAO,QAAQ,CAAC,KAC/C,CAACC,gBAAG,WAAWD,kBAAK,KAAK,OAAO,cAAc,CAAC;AAEnD;AAEA,SAAS,kBAAkB,UAA0B;CACnD,OAAO;;;;;;;;;;kBAUS,KAAK,UAAU,QAAQ,EAAE;;;;;;;;;AAS3C;;;;;;;AAQA,SAAgB,gBAAgB,KAA4B;CAC1D,MAAM,gBAAgBE,kCAAkB,GAAG;CAI3C,MAAM,CAAC,gBAAgB,cAHG,gBACtBF,kBAAK,SAASA,kBAAK,QAAQ,aAAa,GAAG,GAAG,IAC9C,OACiD,EAAE,MAAMA,kBAAK,GAAG,KAAK,CAAC;CAC3E,OAAO,mBAAmB,aAAa,YAAY,YAAY;AACjE;;;;;;;AAQA,SAAgB,+BAA+B,KAA4B;CACzE,IAAI,CAAC,gBAAgB,GAAG,GAAG,OAAO;CAIlC,MAAM,WAAW,gBAAgB,GAAG;CACpC,IAAI,CAAC,UACH,MAAM,IAAI,MACR,8DAA8D,IAAI,yKACpE;CAEF,MAAM,SAASA,kBAAK,KAAK,KAAK,oBAAoB;CAClD,gBAAG,UAAU,QAAQ,EAAE,WAAW,KAAK,CAAC;CACxC,MAAM,UAAUA,kBAAK,KAAK,QAAQ,mBAAmB;CACrD,MAAM,OAAO,kBAAkB,QAAQ;CACvC,IAAI,CAACC,gBAAG,WAAW,OAAO,KAAKA,gBAAG,aAAa,SAAS,MAAM,MAAM,MAClE,gBAAG,cAAc,SAAS,IAAI;CAEhC,OAAO;AACT;AAEA,MAAM,kBAAkB;CACtB,QAAQ;CACR,UAAU;AACZ;;;;;;;;AASA,SAAgB,mBAAmB,MAAc,QAAQ,IAAI,GAAY;CACvE,OACEA,gBAAG,WAAWD,kBAAK,KAAK,KAAK,gBAAgB,MAAM,CAAC,KACpD,CAACC,gBAAG,WAAWD,kBAAK,KAAK,KAAK,gBAAgB,QAAQ,CAAC,KACvD,CAACC,gBAAG,WAAWD,kBAAK,KAAK,KAAK,eAAe,CAAC;AAElD;AAEA,SAAS,wBAAgC;CACvC,OAAO;;;;;;;;AAQT;;;;;;;AAQA,SAAgB,mCAAmC,MAAc,QAAQ,IAAI,GAAkB;CAC7F,IAAI,CAAC,mBAAmB,GAAG,GAAG,OAAO;CACrC,IAAIC,gBAAG,WAAWD,kBAAK,KAAK,KAAK,mBAAmB,CAAC,GAAG,OAAO;CAC/D,MAAM,SAASA,kBAAK,KAAK,KAAK,oBAAoB;CAClD,gBAAG,UAAU,QAAQ,EAAE,WAAW,KAAK,CAAC;CACxC,MAAM,UAAUA,kBAAK,KAAK,QAAQ,mBAAmB;CACrD,gBAAG,cAAc,SAAS,sBAAsB,CAAC;CACjD,QAAQ,IAAI,+EAA+E;CAC3F,OAAOA,kBAAK,KAAK,sBAAsB,mBAAmB;AAC5D"}
1
+ {"version":3,"file":"generated-config.cjs","names":["path","fs","findBosConfigPath"],"sources":["../../../src/build/ui/generated-config.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport path from \"node:path\";\nimport { findBosConfigPath } from \"../rspack/compose\";\n\nconst UI_DIR = \"ui\";\nconst GENERATED_CONFIG_DIR = \".every-plugin\";\nconst GENERATED_UI_CONFIG = \"ui.rsbuild.config.generated.mjs\";\n\n/**\n * Folder-form UI source: a `ui/` directory with route files but no own\n * package.json — the plugin workspace owns the build (single-workspace\n * plugin, one dev process, one deploy train). Workspace-form ui sources\n * (own package.json + scripts) are NOT managed here.\n */\nexport function hasFolderFormUi(cwd: string): boolean {\n const uiDir = path.join(cwd, UI_DIR);\n return (\n fs.existsSync(path.join(uiDir, \"src\", \"routes\")) &&\n !fs.existsSync(path.join(uiDir, \"package.json\"))\n );\n}\n\nexport function uiDistDirFor(cwd: string): string {\n return path.join(cwd, UI_DIR, \"dist\");\n}\n\nfunction generatedUiConfig(pluginId: string): string {\n return `import path from \"node:path\";\nimport { createUiRsbuildConfig } from \"every-plugin/build/ui\";\nimport pkg from \"../package.json\";\n\nconst workspaceRoot = path.resolve(import.meta.dirname, \"..\", \"ui\");\n\nexport default createUiRsbuildConfig({\n workspaceRoot,\n pkg,\n role: \"consumer\",\n manifestName: ${JSON.stringify(pluginId)},\n devPort: Number(process.env.BOS_UI_PORT) || 0,\n webEntry: \"./ui/src/routeConfig.gen.ts\",\n webExposes: { \"./routeConfig\": \"./ui/src/routeConfig.gen.ts\" },\n nodeEntry: \"./ui/src/routeConfig.gen.ts\",\n nodeExposes: { \"./routeConfig\": \"./ui/src/routeConfig.gen.ts\" },\n routesDirectory: \"./ui/src/routes\",\n});\n`;\n}\n\n/**\n * Canonical config-layout derivation: the composition key for a plugin\n * workspace — the `<key>` of the `plugins/<key>` directory relative to the\n * nearest `bos.config.json`. The dev server and the generated ui config\n * both key off this; no consumer keeps a private copy.\n */\nexport function pluginLayoutKey(cwd: string): string | null {\n const bosConfigPath = findBosConfigPath(cwd);\n const relativeWorkspace = bosConfigPath\n ? path.relative(path.dirname(bosConfigPath), cwd)\n : undefined;\n const [workspaceGroup, layoutKey] = relativeWorkspace?.split(path.sep) ?? [];\n return workspaceGroup === \"plugins\" && layoutKey ? layoutKey : null;\n}\n\n/**\n * Synthesize the rsbuild config for a folder-form ui source (the plugin\n * build contract, not per-plugin config — mirrors the rspack generated\n * config). Returns the config file path, or null when the workspace has no\n * folder-form ui source.\n */\nexport function ensureGeneratedUiRsbuildConfig(cwd: string): string | null {\n if (!hasFolderFormUi(cwd)) return null;\n // The manifest's name derives ONLY from the plugins/<key> layout key\n // (ADR 0008 §2) — a non-derivable key fails the build loudly, never the\n // container-name fallback that mis-keyed manifests.\n const pluginId = pluginLayoutKey(cwd);\n if (!pluginId) {\n throw new Error(\n `[every-plugin] cannot derive the ui's composition key from ${cwd} — no authored config (bos.app.ts / bos.config.json) found above a plugins/<key> directory. The manifest name is the layout key; the container name is never a fallback.`,\n );\n }\n const outDir = path.join(cwd, GENERATED_CONFIG_DIR);\n fs.mkdirSync(outDir, { recursive: true });\n const outPath = path.join(outDir, GENERATED_UI_CONFIG);\n const next = generatedUiConfig(pluginId);\n if (!fs.existsSync(outPath) || fs.readFileSync(outPath, \"utf8\") !== next) {\n fs.writeFileSync(outPath, next);\n }\n return outPath;\n}\n\nconst CORE_UI_MARKERS = {\n routes: \"src/routes\",\n contract: \"src/contract.ts\",\n};\n\n/**\n * Workspace-form core ui: the workspace IS the ui (own package.json, route\n * tree) and is not plugin-shaped — the /api counterpart of the plugin\n * workspace form. The entry stub is NOT a marker: it is generated\n * (ADR 0023), so a fresh clone has no bootstrap stubs until the first\n * generation pass.\n */\nexport function hasCoreUiWorkspace(cwd: string = process.cwd()): boolean {\n return (\n fs.existsSync(path.join(cwd, CORE_UI_MARKERS.routes)) &&\n !fs.existsSync(path.join(cwd, CORE_UI_MARKERS.contract)) &&\n !fs.existsSync(path.join(cwd, \"plugin.dev.ts\"))\n );\n}\n\nfunction generatedCoreUiConfig(): string {\n return `import { defineConfig } from \"@rsbuild/core\";\nimport { readAuthoredConfigInput } from \"everything-dev/config\";\nimport { createCoreUiRsbuildConfig } from \"every-plugin/build/ui\";\n\nexport default defineConfig(async () =>\n createCoreUiRsbuildConfig(await readAuthoredConfigInput()),\n);\n`;\n}\n\n/**\n * Synthesize the rsbuild config for a workspace-form core ui with no local\n * `rsbuild.config.ts` — the /api generated-config model. A local file is an\n * override and wins untouched. Returns the workspace-relative config path,\n * or null when the workspace is not a core ui (or has a local config).\n */\nexport function ensureGeneratedCoreUiRsbuildConfig(cwd: string = process.cwd()): string | null {\n if (!hasCoreUiWorkspace(cwd)) return null;\n if (fs.existsSync(path.join(cwd, \"rsbuild.config.ts\"))) return null;\n const outDir = path.join(cwd, GENERATED_CONFIG_DIR);\n fs.mkdirSync(outDir, { recursive: true });\n const outPath = path.join(outDir, GENERATED_UI_CONFIG);\n fs.writeFileSync(outPath, generatedCoreUiConfig());\n console.log(\"[every-plugin] rsbuild.config.ts not found — using the core ui build factory.\");\n return path.join(GENERATED_CONFIG_DIR, GENERATED_UI_CONFIG);\n}\n"],"mappings":";;;;;;;;AAIA,MAAM,SAAS;AACf,MAAM,uBAAuB;AAC7B,MAAM,sBAAsB;;;;;;;AAQ5B,SAAgB,gBAAgB,KAAsB;CACpD,MAAM,QAAQA,kBAAK,KAAK,KAAK,MAAM;CACnC,OACEC,gBAAG,WAAWD,kBAAK,KAAK,OAAO,OAAO,QAAQ,CAAC,KAC/C,CAACC,gBAAG,WAAWD,kBAAK,KAAK,OAAO,cAAc,CAAC;AAEnD;AAEA,SAAgB,aAAa,KAAqB;CAChD,OAAOA,kBAAK,KAAK,KAAK,QAAQ,MAAM;AACtC;AAEA,SAAS,kBAAkB,UAA0B;CACnD,OAAO;;;;;;;;;;kBAUS,KAAK,UAAU,QAAQ,EAAE;;;;;;;;;AAS3C;;;;;;;AAQA,SAAgB,gBAAgB,KAA4B;CAC1D,MAAM,gBAAgBE,kCAAkB,GAAG;CAI3C,MAAM,CAAC,gBAAgB,cAHG,gBACtBF,kBAAK,SAASA,kBAAK,QAAQ,aAAa,GAAG,GAAG,IAC9C,OACiD,EAAE,MAAMA,kBAAK,GAAG,KAAK,CAAC;CAC3E,OAAO,mBAAmB,aAAa,YAAY,YAAY;AACjE;;;;;;;AAQA,SAAgB,+BAA+B,KAA4B;CACzE,IAAI,CAAC,gBAAgB,GAAG,GAAG,OAAO;CAIlC,MAAM,WAAW,gBAAgB,GAAG;CACpC,IAAI,CAAC,UACH,MAAM,IAAI,MACR,8DAA8D,IAAI,yKACpE;CAEF,MAAM,SAASA,kBAAK,KAAK,KAAK,oBAA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mC"}
1
+ {"version":3,"file":"generated-config.d.cts","names":[],"sources":["../../../src/build/ui/generated-config.ts"],"mappings":";;;;;;;iBAcgB,gBAAgB;;;;;;;iBAuDhB,+BAA+B;;;;;;;;iBAiC/B,mBAAmB;;;;;;;iBAyBnB,mCAAmC"}
@@ -1 +1 @@
1
- {"version":3,"file":"generated-config.d.mts","names":[],"sources":["../../../src/build/ui/generated-config.ts"],"mappings":";;;;;;;iBAcgB,gBAAgB;;;;;;;iBAmDhB,+BAA+B;;;;;;;;iBAiC/B,mBAAmB;;;;;;;iBAyBnB,mCAAmC"}
1
+ {"version":3,"file":"generated-config.d.mts","names":[],"sources":["../../../src/build/ui/generated-config.ts"],"mappings":";;;;;;;iBAcgB,gBAAgB;;;;;;;iBAuDhB,+BAA+B;;;;;;;;iBAiC/B,mBAAmB;;;;;;;iBAyBnB,mCAAmC"}
@@ -16,6 +16,9 @@ function hasFolderFormUi(cwd) {
16
16
  const uiDir = path.join(cwd, UI_DIR);
17
17
  return fs.existsSync(path.join(uiDir, "src", "routes")) && !fs.existsSync(path.join(uiDir, "package.json"));
18
18
  }
19
+ function uiDistDirFor(cwd) {
20
+ return path.join(cwd, UI_DIR, "dist");
21
+ }
19
22
  function generatedUiConfig(pluginId) {
20
23
  return `import path from "node:path";
21
24
  import { createUiRsbuildConfig } from "every-plugin/build/ui";
@@ -107,5 +110,5 @@ function ensureGeneratedCoreUiRsbuildConfig(cwd = process.cwd()) {
107
110
  }
108
111
 
109
112
  //#endregion
110
- export { ensureGeneratedCoreUiRsbuildConfig, ensureGeneratedUiRsbuildConfig, hasCoreUiWorkspace, hasFolderFormUi, pluginLayoutKey };
113
+ export { ensureGeneratedCoreUiRsbuildConfig, ensureGeneratedUiRsbuildConfig, hasCoreUiWorkspace, hasFolderFormUi, pluginLayoutKey, uiDistDirFor };
111
114
  //# sourceMappingURL=generated-config.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"generated-config.mjs","names":[],"sources":["../../../src/build/ui/generated-config.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport path from \"node:path\";\nimport { findBosConfigPath } from \"../rspack/compose\";\n\nconst UI_DIR = \"ui\";\nconst GENERATED_CONFIG_DIR = \".every-plugin\";\nconst GENERATED_UI_CONFIG = \"ui.rsbuild.config.generated.mjs\";\n\n/**\n * Folder-form UI source: a `ui/` directory with route files but no own\n * package.json — the plugin workspace owns the build (single-workspace\n * plugin, one dev process, one deploy train). Workspace-form ui sources\n * (own package.json + scripts) are NOT managed here.\n */\nexport function hasFolderFormUi(cwd: string): boolean {\n const uiDir = path.join(cwd, UI_DIR);\n return (\n fs.existsSync(path.join(uiDir, \"src\", \"routes\")) &&\n !fs.existsSync(path.join(uiDir, \"package.json\"))\n );\n}\n\nfunction generatedUiConfig(pluginId: string): string {\n return `import path from \"node:path\";\nimport { createUiRsbuildConfig } from \"every-plugin/build/ui\";\nimport pkg from \"../package.json\";\n\nconst workspaceRoot = path.resolve(import.meta.dirname, \"..\", \"ui\");\n\nexport default createUiRsbuildConfig({\n workspaceRoot,\n pkg,\n role: \"consumer\",\n manifestName: ${JSON.stringify(pluginId)},\n devPort: Number(process.env.BOS_UI_PORT) || 0,\n webEntry: \"./ui/src/routeConfig.gen.ts\",\n webExposes: { \"./routeConfig\": \"./ui/src/routeConfig.gen.ts\" },\n nodeEntry: \"./ui/src/routeConfig.gen.ts\",\n nodeExposes: { \"./routeConfig\": \"./ui/src/routeConfig.gen.ts\" },\n routesDirectory: \"./ui/src/routes\",\n});\n`;\n}\n\n/**\n * Canonical config-layout derivation: the composition key for a plugin\n * workspace — the `<key>` of the `plugins/<key>` directory relative to the\n * nearest `bos.config.json`. The dev server and the generated ui config\n * both key off this; no consumer keeps a private copy.\n */\nexport function pluginLayoutKey(cwd: string): string | null {\n const bosConfigPath = findBosConfigPath(cwd);\n const relativeWorkspace = bosConfigPath\n ? path.relative(path.dirname(bosConfigPath), cwd)\n : undefined;\n const [workspaceGroup, layoutKey] = relativeWorkspace?.split(path.sep) ?? [];\n return workspaceGroup === \"plugins\" && layoutKey ? layoutKey : null;\n}\n\n/**\n * Synthesize the rsbuild config for a folder-form ui source (the plugin\n * build contract, not per-plugin config — mirrors the rspack generated\n * config). Returns the config file path, or null when the workspace has no\n * folder-form ui source.\n */\nexport function ensureGeneratedUiRsbuildConfig(cwd: string): string | null {\n if (!hasFolderFormUi(cwd)) return null;\n // The manifest's name derives ONLY from the plugins/<key> layout key\n // (ADR 0008 §2) — a non-derivable key fails the build loudly, never the\n // container-name fallback that mis-keyed manifests.\n const pluginId = pluginLayoutKey(cwd);\n if (!pluginId) {\n throw new Error(\n `[every-plugin] cannot derive the ui's composition key from ${cwd} — no authored config (bos.app.ts / bos.config.json) found above a plugins/<key> directory. The manifest name is the layout key; the container name is never a fallback.`,\n );\n }\n const outDir = path.join(cwd, GENERATED_CONFIG_DIR);\n fs.mkdirSync(outDir, { recursive: true });\n const outPath = path.join(outDir, GENERATED_UI_CONFIG);\n const next = generatedUiConfig(pluginId);\n if (!fs.existsSync(outPath) || fs.readFileSync(outPath, \"utf8\") !== next) {\n fs.writeFileSync(outPath, next);\n }\n return outPath;\n}\n\nconst CORE_UI_MARKERS = {\n routes: \"src/routes\",\n contract: \"src/contract.ts\",\n};\n\n/**\n * Workspace-form core ui: the workspace IS the ui (own package.json, route\n * tree) and is not plugin-shaped — the /api counterpart of the plugin\n * workspace form. The entry stub is NOT a marker: it is generated\n * (ADR 0023), so a fresh clone has no bootstrap stubs until the first\n * generation pass.\n */\nexport function hasCoreUiWorkspace(cwd: string = process.cwd()): boolean {\n return (\n fs.existsSync(path.join(cwd, CORE_UI_MARKERS.routes)) &&\n !fs.existsSync(path.join(cwd, CORE_UI_MARKERS.contract)) &&\n !fs.existsSync(path.join(cwd, \"plugin.dev.ts\"))\n );\n}\n\nfunction generatedCoreUiConfig(): string {\n return `import { defineConfig } from \"@rsbuild/core\";\nimport { readAuthoredConfigInput } from \"everything-dev/config\";\nimport { createCoreUiRsbuildConfig } from \"every-plugin/build/ui\";\n\nexport default defineConfig(async () =>\n createCoreUiRsbuildConfig(await readAuthoredConfigInput()),\n);\n`;\n}\n\n/**\n * Synthesize the rsbuild config for a workspace-form core ui with no local\n * `rsbuild.config.ts` — the /api generated-config model. A local file is an\n * override and wins untouched. Returns the workspace-relative config path,\n * or null when the workspace is not a core ui (or has a local config).\n */\nexport function ensureGeneratedCoreUiRsbuildConfig(cwd: string = process.cwd()): string | null {\n if (!hasCoreUiWorkspace(cwd)) return null;\n if (fs.existsSync(path.join(cwd, \"rsbuild.config.ts\"))) return null;\n const outDir = path.join(cwd, GENERATED_CONFIG_DIR);\n fs.mkdirSync(outDir, { recursive: true });\n const outPath = path.join(outDir, GENERATED_UI_CONFIG);\n fs.writeFileSync(outPath, generatedCoreUiConfig());\n console.log(\"[every-plugin] rsbuild.config.ts not found — using the core ui build factory.\");\n return path.join(GENERATED_CONFIG_DIR, GENERATED_UI_CONFIG);\n}\n"],"mappings":";;;;;AAIA,MAAM,SAAS;AACf,MAAM,uBAAuB;AAC7B,MAAM,sBAAsB;;;;;;;AAQ5B,SAAgB,gBAAgB,KAAsB;CACpD,MAAM,QAAQ,KAAK,KAAK,KAAK,MAAM;CACnC,OACE,GAAG,WAAW,KAAK,KAAK,OAAO,OAAO,QAAQ,CAAC,KAC/C,CAAC,GAAG,WAAW,KAAK,KAAK,OAAO,cAAc,CAAC;AAEnD;AAEA,SAAS,kBAAkB,UAA0B;CACnD,OAAO;;;;;;;;;;kBAUS,KAAK,UAAU,QAAQ,EAAE;;;;;;;;;AAS3C;;;;;;;AAQA,SAAgB,gBAAgB,KAA4B;CAC1D,MAAM,gBAAgB,kBAAkB,GAAG;CAI3C,MAAM,CAAC,gBAAgB,cAHG,gBACtB,KAAK,SAAS,KAAK,QAAQ,aAAa,GAAG,GAAG,IAC9C,OACiD,EAAE,MAAM,KAAK,GAAG,KAAK,CAAC;CAC3E,OAAO,mBAAmB,aAAa,YAAY,YAAY;AACjE;;;;;;;AAQA,SAAgB,+BAA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mjs","names":[],"sources":["../../../src/build/ui/generated-config.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport path from \"node:path\";\nimport { findBosConfigPath } from \"../rspack/compose\";\n\nconst UI_DIR = \"ui\";\nconst GENERATED_CONFIG_DIR = \".every-plugin\";\nconst GENERATED_UI_CONFIG = \"ui.rsbuild.config.generated.mjs\";\n\n/**\n * Folder-form UI source: a `ui/` directory with route files but no own\n * package.json — the plugin workspace owns the build (single-workspace\n * plugin, one dev process, one deploy train). Workspace-form ui sources\n * (own package.json + scripts) are NOT managed here.\n */\nexport function hasFolderFormUi(cwd: string): boolean {\n const uiDir = path.join(cwd, UI_DIR);\n return (\n fs.existsSync(path.join(uiDir, \"src\", \"routes\")) &&\n !fs.existsSync(path.join(uiDir, \"package.json\"))\n );\n}\n\nexport function uiDistDirFor(cwd: string): string {\n return path.join(cwd, UI_DIR, \"dist\");\n}\n\nfunction generatedUiConfig(pluginId: string): string {\n return `import path from \"node:path\";\nimport { createUiRsbuildConfig } from \"every-plugin/build/ui\";\nimport pkg from \"../package.json\";\n\nconst workspaceRoot = path.resolve(import.meta.dirname, \"..\", \"ui\");\n\nexport default createUiRsbuildConfig({\n workspaceRoot,\n pkg,\n role: \"consumer\",\n manifestName: ${JSON.stringify(pluginId)},\n devPort: Number(process.env.BOS_UI_PORT) || 0,\n webEntry: \"./ui/src/routeConfig.gen.ts\",\n webExposes: { \"./routeConfig\": \"./ui/src/routeConfig.gen.ts\" },\n nodeEntry: \"./ui/src/routeConfig.gen.ts\",\n nodeExposes: { \"./routeConfig\": \"./ui/src/routeConfig.gen.ts\" },\n routesDirectory: \"./ui/src/routes\",\n});\n`;\n}\n\n/**\n * Canonical config-layout derivation: the composition key for a plugin\n * workspace — the `<key>` of the `plugins/<key>` directory relative to the\n * nearest `bos.config.json`. The dev server and the generated ui config\n * both key off this; no consumer keeps a private copy.\n */\nexport function pluginLayoutKey(cwd: string): string | null {\n const bosConfigPath = findBosConfigPath(cwd);\n const relativeWorkspace = bosConfigPath\n ? path.relative(path.dirname(bosConfigPath), cwd)\n : undefined;\n const [workspaceGroup, layoutKey] = relativeWorkspace?.split(path.sep) ?? [];\n return workspaceGroup === \"plugins\" && layoutKey ? layoutKey : null;\n}\n\n/**\n * Synthesize the rsbuild config for a folder-form ui source (the plugin\n * build contract, not per-plugin config — mirrors the rspack generated\n * config). Returns the config file path, or null when the workspace has no\n * folder-form ui source.\n */\nexport function ensureGeneratedUiRsbuildConfig(cwd: string): string | null {\n if (!hasFolderFormUi(cwd)) return null;\n // The manifest's name derives ONLY from the plugins/<key> layout key\n // (ADR 0008 §2) — a non-derivable key fails the build loudly, never the\n // container-name fallback that mis-keyed manifests.\n const pluginId = pluginLayoutKey(cwd);\n if (!pluginId) {\n throw new Error(\n `[every-plugin] cannot derive the ui's composition key from ${cwd} — no authored config (bos.app.ts / bos.config.json) found above a plugins/<key> directory. The manifest name is the layout key; the container name is never a fallback.`,\n );\n }\n const outDir = path.join(cwd, GENERATED_CONFIG_DIR);\n fs.mkdirSync(outDir, { recursive: true });\n const outPath = path.join(outDir, GENERATED_UI_CONFIG);\n const next = generatedUiConfig(pluginId);\n if (!fs.existsSync(outPath) || fs.readFileSync(outPath, \"utf8\") !== next) {\n fs.writeFileSync(outPath, next);\n }\n return outPath;\n}\n\nconst CORE_UI_MARKERS = {\n routes: \"src/routes\",\n contract: \"src/contract.ts\",\n};\n\n/**\n * Workspace-form core ui: the workspace IS the ui (own package.json, route\n * tree) and is not plugin-shaped — the /api counterpart of the plugin\n * workspace form. The entry stub is NOT a marker: it is generated\n * (ADR 0023), so a fresh clone has no bootstrap stubs until the first\n * generation pass.\n */\nexport function hasCoreUiWorkspace(cwd: string = process.cwd()): boolean {\n return (\n fs.existsSync(path.join(cwd, CORE_UI_MARKERS.routes)) &&\n !fs.existsSync(path.join(cwd, CORE_UI_MARKERS.contract)) &&\n !fs.existsSync(path.join(cwd, \"plugin.dev.ts\"))\n );\n}\n\nfunction generatedCoreUiConfig(): string {\n return `import { defineConfig } from \"@rsbuild/core\";\nimport { readAuthoredConfigInput } from \"everything-dev/config\";\nimport { createCoreUiRsbuildConfig } from \"every-plugin/build/ui\";\n\nexport default defineConfig(async () =>\n createCoreUiRsbuildConfig(await readAuthoredConfigInput()),\n);\n`;\n}\n\n/**\n * Synthesize the rsbuild config for a workspace-form core ui with no local\n * `rsbuild.config.ts` — the /api generated-config model. A local file is an\n * override and wins untouched. Returns the workspace-relative config path,\n * or null when the workspace is not a core ui (or has a local config).\n */\nexport function ensureGeneratedCoreUiRsbuildConfig(cwd: string = process.cwd()): string | null {\n if (!hasCoreUiWorkspace(cwd)) return null;\n if (fs.existsSync(path.join(cwd, \"rsbuild.config.ts\"))) return null;\n const outDir = path.join(cwd, GENERATED_CONFIG_DIR);\n fs.mkdirSync(outDir, { recursive: true });\n const outPath = path.join(outDir, GENERATED_UI_CONFIG);\n fs.writeFileSync(outPath, generatedCoreUiConfig());\n console.log(\"[every-plugin] rsbuild.config.ts not found — using the core ui build factory.\");\n return path.join(GENERATED_CONFIG_DIR, GENERATED_UI_CONFIG);\n}\n"],"mappings":";;;;;AAIA,MAAM,SAAS;AACf,MAAM,uBAAuB;AAC7B,MAAM,sBAAsB;;;;;;;AAQ5B,SAAgB,gBAAgB,KAAsB;CACpD,MAAM,QAAQ,KAAK,KAAK,KAAK,MAAM;CACnC,OACE,GAAG,WAAW,KAAK,KAAK,OAAO,OAAO,QAAQ,CAAC,KAC/C,CAAC,GAAG,WAAW,KAAK,KAAK,OAAO,cAAc,CAAC;AAEnD;AAEA,SAAgB,aAAa,KAAqB;CAChD,OAAO,KAAK,KAAK,KAAK,QAAQ,MAAM;AACtC;AAEA,SAAS,kBAAkB,UAA0B;CACnD,OAAO;;;;;;;;;;kBAUS,KAAK,UAAU,QAAQ,EAAE;;;;;;;;;AAS3C;;;;;;;AAQA,SAAgB,gBAAgB,KAA4B;CAC1D,MAAM,gBAAgB,kBAAkB,GAAG;CAI3C,MAAM,CAAC,gBAAgB,cAHG,g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,KAAK,KAAK,QAAQ,mBAAmB;CACrD,GAAG,cAAc,SAAS,sBAAsB,CAAC;CACjD,QAAQ,IAAI,+EAA+E;CAC3F,OAAO,KAAK,KAAK,sBAAsB,mBAAmB;AAC5D"}
@@ -143,8 +143,8 @@ async function startPluginDevServer(options = {}) {
143
143
  "--config",
144
144
  uiConfig
145
145
  ]);
146
- const uiDistDir = node_path.default.basename(cwd) === "ui" ? node_path.default.join(cwd, "dist") : node_path.default.join(cwd, "ui", "dist");
147
- if (!node_fs.default.existsSync(node_path.default.join(uiDistDir, "remoteEntry.js"))) console.error(`❌ UI dist is missing at ${uiDistDir} — the ui static server would serve 404s for every asset (build output layout mismatch?)`);
146
+ const uiDistDir = require_generated_config.uiDistDirFor(cwd);
147
+ if (!node_fs.default.existsSync(node_path.default.join(uiDistDir, "remoteEntry.js"))) throw new Error(`❌ UI dist is missing at ${uiDistDir} after the rsbuild one-shot — build output layout mismatch?`);
148
148
  const serveUiStatic = (0, sirv.default)(uiDistDir, { dev: true });
149
149
  uiStaticServer = node_http.default.createServer((req, res) => {
150
150
  applyCorsHeaders(res);
@@ -1 +1 @@
1
- {"version":3,"file":"serve.cjs","names":["DEV_ENTRY_FILENAME","Effect","loadRemoteWithRetry","getPluginInfo","loadDevConfig","path","pluginLayoutKey","spawn","ensureGeneratedRspackConfig","ensureGeneratedUiRsbuildConfig","fs","http","startDirectModuleHost","PLUGIN_ERROR_STATUS_MAP","killChildEscalating"],"sources":["../../src/dev/serve.ts"],"sourcesContent":["import { spawn } from \"node:child_process\";\nimport fs from \"node:fs\";\nimport http from \"node:http\";\nimport path from \"node:path\";\nimport { Effect } from \"effect\";\nimport sirv from \"sirv\";\nimport { DEV_ENTRY_FILENAME } from \"../build/artifact-names\";\nimport { ensureGeneratedRspackConfig } from \"../build/rspack/generated-config\";\nimport { getPluginInfo, loadDevConfig } from \"../build/rspack/utils\";\nimport { ensureGeneratedUiRsbuildConfig, pluginLayoutKey } from \"../build/ui/generated-config\";\nimport { PLUGIN_ERROR_STATUS_MAP } from \"../errors\";\nimport { loadRemoteWithRetry } from \"../remote-entry\";\nimport { startDirectModuleHost } from \"./host\";\nimport { killChildEscalating, watchParentDeath } from \"./watch-kill\";\n\nconst corsHeaders = {\n \"Access-Control-Allow-Origin\": \"*\",\n \"Access-Control-Allow-Methods\": \"GET, POST, PUT, DELETE, PATCH, OPTIONS\",\n \"Access-Control-Allow-Headers\": \"X-Requested-With, content-type, Authorization\",\n};\n\nconst applyCorsHeaders = (res: http.ServerResponse) => {\n Object.entries(corsHeaders).forEach(([key, value]) => {\n res.setHeader(key, value);\n });\n};\n\nconst normalizePrefix = (prefix?: string): string => {\n if (!prefix) return \"\";\n const cleaned = prefix.replace(/^\\/+|\\/+$/g, \"\");\n return cleaned ? `/${cleaned}` : \"\";\n};\n\nconst readRuntimeConfigFromEnv = (): any => {\n const raw = process.env.BOS_RUNTIME_CONFIG;\n if (!raw) return null;\n try {\n return JSON.parse(raw);\n } catch {\n return null;\n }\n};\n\nconst collectSiblingRemotes = (runtimeConfig: any, pluginId: string) => {\n const siblings: Record<string, { remote: string }> = {};\n\n const isApi = pluginId === \"api\" || runtimeConfig?.api?.name === pluginId;\n\n const ownKey = runtimeConfig?.plugins?.[pluginId] ? pluginId : null;\n let dependsOn: string[] = [];\n if (ownKey) {\n dependsOn = runtimeConfig.plugins[ownKey].dependsOn ?? [];\n } else if (isApi) {\n dependsOn = runtimeConfig?.api?.dependsOn ?? [];\n }\n\n for (const depId of dependsOn) {\n const dep = runtimeConfig?.plugins?.[depId];\n if (!dep || dep.source !== \"local\" || !dep.url) continue;\n if (depId === pluginId) continue;\n const base = dep.url.replace(/\\/$/, \"\");\n siblings[depId] = { remote: `${base}/${DEV_ENTRY_FILENAME}` };\n }\n\n return { siblings, dependsOn };\n};\n\nconst loadPluginWithRetry = (\n runtime: any,\n pluginId: string,\n remoteUrl: string,\n options: Record<string, unknown> = { variables: {}, secrets: {} },\n pluginsMap?: Record<string, unknown>,\n timeoutMs = 90000,\n): Promise<any> =>\n Effect.runPromise(\n loadRemoteWithRetry({\n label: pluginId,\n remoteUrl,\n load: () => runtime.usePlugin(pluginId, options, pluginsMap),\n timeoutMs,\n }),\n );\n\nconst sendText = (res: http.ServerResponse, status: number, text: string) => {\n res.statusCode = status;\n res.setHeader(\"content-type\", \"text/plain; charset=utf-8\");\n res.end(text);\n};\n\nexport interface PluginDevServeOptions {\n cwd?: string;\n port?: number;\n watch?: boolean;\n}\n\nexport interface PluginDevServerHandle {\n port: number;\n close: () => Promise<void>;\n}\n\n/**\n * The dev server's plugin id — the workspace's npm package name, the same\n * value the host passes as `runtimeId`. Both initialize sites must agree:\n * `registerRemote` derives the MF remote name from it, and the plugin's\n * database layer derives its migration slug from it, so a pre-normalized\n * remote name here would migrate into a different schema than the host\n * expects. plugin.dev.ts no longer carries a pluginId field.\n */\nexport const resolveDevPluginId = (cwd: string): string => getPluginInfo(cwd).name;\n\nexport async function startPluginDevServer(\n options: PluginDevServeOptions = {},\n): Promise<PluginDevServerHandle> {\n process.env.BOS_DEV_SERVER = \"1\";\n const cwd = options.cwd ?? process.cwd();\n const pluginInfo = getPluginInfo(cwd);\n const devConfig = loadDevConfig(path.join(cwd, \"plugin.dev.ts\"));\n const pluginId = resolveDevPluginId(cwd);\n const compositionKey = pluginLayoutKey(cwd) ?? pluginId;\n const port = options.port ?? (Number(process.env.PORT) || devConfig?.port || 3999);\n const rpcPrefix = normalizePrefix(devConfig?.prefix);\n\n const distDir = path.join(cwd, \"dist\");\n const serveStatic = sirv(distDir, { dev: true });\n\n // No-watch mode (BOS_NO_WATCH=1): build once, serve the built output.\n // Regression/CI stacks need no hot reload — watchers are the stack's\n // heaviest processes and stall runs freeze under their accumulated\n // footprint. One-shot builds exit; steady state is small static servers.\n const noWatch = options.watch === false || process.env.BOS_NO_WATCH === \"1\";\n\n const runOnce = (cmd: string, args: string[]) =>\n new Promise<void>((resolve, reject) => {\n const child = spawn(cmd, args, { cwd, stdio: \"inherit\", env: process.env });\n child.on(\"error\", reject);\n child.on(\"exit\", (code) => {\n if (code === 0) resolve();\n else reject(new Error(`❌ ${cmd} ${args.join(\" \")} exited with ${code}`));\n });\n });\n\n let watcher: ReturnType<typeof spawn> | null = null;\n if (noWatch) {\n const generatedConfig = ensureGeneratedRspackConfig(cwd);\n await runOnce(\"rspack\", generatedConfig ? [\"build\", \"--config\", generatedConfig] : [\"build\"]);\n } else if (options.watch !== false) {\n const generatedConfig = ensureGeneratedRspackConfig(cwd);\n watcher = spawn(\n \"rspack\",\n generatedConfig ? [\"build\", \"--watch\", \"--config\", generatedConfig] : [\"build\", \"--watch\"],\n {\n cwd,\n stdio: \"inherit\",\n env: process.env,\n },\n );\n watcher.on(\"error\", (error) => {\n console.error(`❌ Failed to spawn rspack build --watch: ${error.message}`);\n });\n }\n\n let uiWatcher: ReturnType<typeof spawn> | null = null;\n let uiStaticServer: http.Server | null = null;\n const uiPort = process.env.BOS_UI_PORT;\n const uiConfig = ensureGeneratedUiRsbuildConfig(cwd);\n if (uiConfig && noWatch && uiPort) {\n // Folder-form ui: one-shot build, then serve the ui source root's dist\n // (the factory's absolute distPath target) statically on the ui port.\n await runOnce(\"rsbuild\", [\"build\", \"--config\", uiConfig]);\n const uiDistDir =\n path.basename(cwd) === \"ui\" ? path.join(cwd, \"dist\") : path.join(cwd, \"ui\", \"dist\");\n if (!fs.existsSync(path.join(uiDistDir, DEV_ENTRY_FILENAME))) {\n console.error(\n `❌ UI dist is missing at ${uiDistDir} — the ui static server would serve 404s for every asset (build output layout mismatch?)`,\n );\n }\n const serveUiStatic = sirv(uiDistDir, { dev: true });\n uiStaticServer = http.createServer((req, res) => {\n applyCorsHeaders(res);\n serveUiStatic(req, res, () => {\n sendText(res, 404, \"Not Found\");\n });\n });\n await new Promise<void>((resolve, reject) => {\n uiStaticServer!.once(\"error\", reject);\n uiStaticServer!.listen(Number(uiPort), () => resolve());\n });\n console.log(`├─ 🎨 UI: http://localhost:${uiPort} (built, no watch)`);\n } else if (uiConfig) {\n uiWatcher = spawn(\"rsbuild\", [\"dev\", \"--config\", uiConfig], {\n cwd,\n stdio: \"inherit\",\n env: uiPort ? { ...process.env, PORT: uiPort } : process.env,\n });\n uiWatcher.on(\"error\", (error) => {\n console.error(`❌ Failed to spawn rsbuild ui dev: ${error.message}`);\n });\n console.log(`├─ 🎨 UI: ${uiPort ? `http://localhost:${uiPort}` : \"(rsbuild auto port)\"}`);\n }\n\n const handlers: { rpc: any; api: any } = { rpc: null, api: null };\n const effectContextHolder: { context: unknown } = { context: null };\n let runtime: { shutdown: () => Promise<void> } | null = null;\n const host = await startDirectModuleHost({\n name: pluginInfo.normalizedName,\n version: pluginInfo.version,\n handlers,\n effectContext: () => effectContextHolder.context,\n port,\n staticHandler: serveStatic,\n });\n\n console.log(`🚀 ${pluginInfo.name} dev server listening on port ${host.port}`);\n console.log(`├─ 📡 RPC: http://localhost:${host.port}/api/rpc${rpcPrefix}`);\n console.log(`├─ 📖 Docs: http://localhost:${host.port}/api`);\n console.log(`└─ 💚 Health: http://localhost:${host.port}/`);\n\n const load = async () => {\n try {\n // Import framework internals directly. A package self-import can resolve\n // the published entry while this source-first dev server is running,\n // which leaves the runtime exports unavailable on Windows.\n const { createPluginRuntime } = await import(\"../runtime\");\n const { RPCHandler } = await import(\"@orpc/server/fetch\");\n const { OpenAPIHandler } = await import(\"@orpc/openapi/fetch\");\n const { OpenAPIGenerator } = await import(\"@orpc/openapi\");\n const { OpenAPIReferenceHandlerPlugin } = await import(\"@orpc/openapi/plugins\");\n const { ZodToJsonSchemaConverter } = await import(\"@orpc/zod\");\n const { onError } = await import(\"@orpc/server\");\n const { formatORPCError } = await import(\"../errors\");\n\n const runtimeConfig = readRuntimeConfigFromEnv();\n const { siblings, dependsOn } = collectSiblingRemotes(runtimeConfig, compositionKey);\n\n if (dependsOn.length > 0) {\n console.log(`🔗 Loading sibling plugin(s): ${dependsOn.join(\", \")}`);\n }\n\n const registry: Record<string, { remote: string }> = {\n [pluginId]: {\n remote: `http://localhost:${host.port}/${DEV_ENTRY_FILENAME}`,\n },\n ...siblings,\n };\n\n const mfRuntime = createPluginRuntime({ registry });\n runtime = mfRuntime;\n\n const pluginsMap: Record<string, unknown> = {};\n const siblingEffectContexts: unknown[] = [];\n for (const depId of Object.keys(siblings)) {\n const dep = await loadPluginWithRetry(mfRuntime, depId, siblings[depId]!.remote);\n pluginsMap[depId] = { client: dep.createClient, router: dep.router };\n if (dep.initialized?.effectContext) {\n siblingEffectContexts.push(dep.initialized.effectContext);\n }\n console.log(`✅ Loaded dependency plugin: ${depId}`);\n }\n\n const loaded: any = await loadPluginWithRetry(\n mfRuntime,\n pluginId,\n registry[pluginId]!.remote,\n (devConfig?.config ?? { variables: {}, secrets: {} }) as Record<string, unknown>,\n Object.keys(pluginsMap).length > 0 ? pluginsMap : undefined,\n );\n\n const { Context } = await import(\"effect\");\n effectContextHolder.context = [loaded.initialized?.effectContext, ...siblingEffectContexts]\n .filter(Boolean)\n .reduce((acc: any, ctx: any) => Context.merge(acc, ctx), Context.empty());\n\n handlers.rpc = new RPCHandler(loaded.router, {\n errorStatusMap: PLUGIN_ERROR_STATUS_MAP,\n interceptors: [\n onError((error: any) => {\n const formatted = formatORPCError(error);\n if (formatted) console.error(formatted);\n }),\n ],\n });\n\n const generator = new OpenAPIGenerator({ converters: [new ZodToJsonSchemaConverter()] });\n\n handlers.api = new OpenAPIHandler(loaded.router, {\n errorStatusMap: PLUGIN_ERROR_STATUS_MAP,\n plugins: [\n new OpenAPIReferenceHandlerPlugin({\n spec: () => generator.generate(loaded.router, { version: \"3.1.1\" }),\n }),\n ],\n interceptors: [\n onError((error: any) => {\n const formatted = formatORPCError(error);\n if (formatted) console.error(formatted);\n }),\n ],\n });\n\n console.log(`✅ Plugin ready: ${pluginId}`);\n } catch (error) {\n console.error(`❌ Failed to load plugin ${pluginId}:`, error);\n console.error(\" Server stays up; fix the build and retry via rebuild.\");\n }\n };\n\n void load();\n\n const close = async () => {\n handlers.rpc = null;\n handlers.api = null;\n effectContextHolder.context = null;\n for (const child of [watcher, uiWatcher]) {\n if (child) {\n await killChildEscalating(child);\n }\n }\n if (uiStaticServer) {\n await new Promise<void>((resolve) => uiStaticServer.close(() => resolve()));\n }\n await host.close();\n if (runtime) await runtime.shutdown().catch(() => {});\n };\n\n process.once(\"SIGINT\", async () => {\n const timeout = setTimeout(() => process.exit(0), 3000);\n await close();\n clearTimeout(timeout);\n process.exit(0);\n });\n process.once(\"SIGTERM\", async () => {\n const timeout = setTimeout(() => process.exit(0), 3000);\n await close();\n clearTimeout(timeout);\n process.exit(0);\n });\n\n watchParentDeath(async () => {\n const timeout = setTimeout(() => process.exit(0), 3000);\n await close();\n clearTimeout(timeout);\n process.exit(0);\n });\n\n return { port, close };\n}\n\nconst invokedAsCli = import.meta.main || (process.argv[1] ?? \"\").includes(\"every-plugin-serve\");\n\nif (invokedAsCli) {\n startPluginDevServer().catch((error) => {\n console.error(\"❌ Plugin dev server fatal error:\", error);\n process.exit(1);\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAeA,MAAM,cAAc;CAClB,+BAA+B;CAC/B,gCAAgC;CAChC,gCAAgC;AAClC;AAEA,MAAM,oBAAoB,QAA6B;CACrD,OAAO,QAAQ,WAAW,CAAC,CAAC,SAAS,CAAC,KAAK,WAAW;EACpD,IAAI,UAAU,KAAK,KAAK;CAC1B,CAAC;AACH;AAEA,MAAM,mBAAmB,WAA4B;CACnD,IAAI,CAAC,QAAQ,OAAO;CACpB,MAAM,UAAU,OAAO,QAAQ,cAAc,EAAE;CAC/C,OAAO,UAAU,IAAI,YAAY;AACnC;AAEA,MAAM,iCAAsC;CAC1C,MAAM,MAAM,QAAQ,IAAI;CACxB,IAAI,CAAC,KAAK,OAAO;CACjB,IAAI;EACF,OAAO,KAAK,MAAM,GAAG;CACvB,QAAQ;EACN,OAAO;CACT;AACF;AAEA,MAAM,yBAAyB,eAAoB,aAAqB;CACtE,MAAM,WAA+C,CAAC;CAEtD,M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AS,MAAM,QAAQ,SAAS,CAAC,CAAC,YAAY,CAAC,CAAC;CACtD;CAEA,QAAQ,KAAK,UAAU,YAAY;EACjC,MAAM,UAAU,iBAAiB,QAAQ,KAAK,CAAC,GAAG,GAAI;EACtD,MAAM,MAAM;EACZ,aAAa,OAAO;EACpB,QAAQ,KAAK,CAAC;CAChB,CAAC;CACD,QAAQ,KAAK,WAAW,YAAY;EAClC,MAAM,UAAU,iBAAiB,QAAQ,KAAK,CAAC,GAAG,GAAI;EACtD,MAAM,MAAM;EACZ,aAAa,OAAO;EACpB,QAAQ,KAAK,CAAC;CAChB,CAAC;CAED,oCAAiB,YAAY;EAC3B,MAAM,UAAU,iBAAiB,QAAQ,KAAK,CAAC,GAAG,GAAI;EACtD,MAAM,MAAM;EACZ,aAAa,OAAO;EACpB,QAAQ,KAAK,CAAC;CAChB,CAAC;CAED,OAAO;EAAE;EAAM;CAAM;AACvB;AAIA,OAFiC,SAAS,QAAQ,KAAK,MAAM,GAAE,CAAE,SAAS,oBAAoB,GAG5F,qBAAqB,CAAC,CAAC,OAAO,UAAU;CACtC,QAAQ,MAAM,oCAAoC,KAAK;CACvD,QAAQ,KAAK,CAAC;AAChB,CAAC"}
1
+ {"version":3,"file":"serve.cjs","names":["DEV_ENTRY_FILENAME","Effect","loadRemoteWithRetry","getPluginInfo","loadDevConfig","path","pluginLayoutKey","spawn","ensureGeneratedRspackConfig","ensureGeneratedUiRsbuildConfig","uiDistDirFor","fs","http","startDirectModuleHost","PLUGIN_ERROR_STATUS_MAP","killChildEscalating"],"sources":["../../src/dev/serve.ts"],"sourcesContent":["import { spawn } from \"node:child_process\";\nimport fs from \"node:fs\";\nimport http from \"node:http\";\nimport path from \"node:path\";\nimport { Effect } from \"effect\";\nimport sirv from \"sirv\";\nimport { DEV_ENTRY_FILENAME } from \"../build/artifact-names\";\nimport { ensureGeneratedRspackConfig } from \"../build/rspack/generated-config\";\nimport { getPluginInfo, loadDevConfig } from \"../build/rspack/utils\";\nimport {\n ensureGeneratedUiRsbuildConfig,\n pluginLayoutKey,\n uiDistDirFor,\n} from \"../build/ui/generated-config\";\nimport { PLUGIN_ERROR_STATUS_MAP } from \"../errors\";\nimport { loadRemoteWithRetry } from \"../remote-entry\";\nimport { startDirectModuleHost } from \"./host\";\nimport { killChildEscalating, watchParentDeath } from \"./watch-kill\";\n\nconst corsHeaders = {\n \"Access-Control-Allow-Origin\": \"*\",\n \"Access-Control-Allow-Methods\": \"GET, POST, PUT, DELETE, PATCH, OPTIONS\",\n \"Access-Control-Allow-Headers\": \"X-Requested-With, content-type, Authorization\",\n};\n\nconst applyCorsHeaders = (res: http.ServerResponse) => {\n Object.entries(corsHeaders).forEach(([key, value]) => {\n res.setHeader(key, value);\n });\n};\n\nconst normalizePrefix = (prefix?: string): string => {\n if (!prefix) return \"\";\n const cleaned = prefix.replace(/^\\/+|\\/+$/g, \"\");\n return cleaned ? `/${cleaned}` : \"\";\n};\n\nconst readRuntimeConfigFromEnv = (): any => {\n const raw = process.env.BOS_RUNTIME_CONFIG;\n if (!raw) return null;\n try {\n return JSON.parse(raw);\n } catch {\n return null;\n }\n};\n\nconst collectSiblingRemotes = (runtimeConfig: any, pluginId: string) => {\n const siblings: Record<string, { remote: string }> = {};\n\n const isApi = pluginId === \"api\" || runtimeConfig?.api?.name === pluginId;\n\n const ownKey = runtimeConfig?.plugins?.[pluginId] ? pluginId : null;\n let dependsOn: string[] = [];\n if (ownKey) {\n dependsOn = runtimeConfig.plugins[ownKey].dependsOn ?? [];\n } else if (isApi) {\n dependsOn = runtimeConfig?.api?.dependsOn ?? [];\n }\n\n for (const depId of dependsOn) {\n const dep = runtimeConfig?.plugins?.[depId];\n if (!dep || dep.source !== \"local\" || !dep.url) continue;\n if (depId === pluginId) continue;\n const base = dep.url.replace(/\\/$/, \"\");\n siblings[depId] = { remote: `${base}/${DEV_ENTRY_FILENAME}` };\n }\n\n return { siblings, dependsOn };\n};\n\nconst loadPluginWithRetry = (\n runtime: any,\n pluginId: string,\n remoteUrl: string,\n options: Record<string, unknown> = { variables: {}, secrets: {} },\n pluginsMap?: Record<string, unknown>,\n timeoutMs = 90000,\n): Promise<any> =>\n Effect.runPromise(\n loadRemoteWithRetry({\n label: pluginId,\n remoteUrl,\n load: () => runtime.usePlugin(pluginId, options, pluginsMap),\n timeoutMs,\n }),\n );\n\nconst sendText = (res: http.ServerResponse, status: number, text: string) => {\n res.statusCode = status;\n res.setHeader(\"content-type\", \"text/plain; charset=utf-8\");\n res.end(text);\n};\n\nexport interface PluginDevServeOptions {\n cwd?: string;\n port?: number;\n watch?: boolean;\n}\n\nexport interface PluginDevServerHandle {\n port: number;\n close: () => Promise<void>;\n}\n\n/**\n * The dev server's plugin id — the workspace's npm package name, the same\n * value the host passes as `runtimeId`. Both initialize sites must agree:\n * `registerRemote` derives the MF remote name from it, and the plugin's\n * database layer derives its migration slug from it, so a pre-normalized\n * remote name here would migrate into a different schema than the host\n * expects. plugin.dev.ts no longer carries a pluginId field.\n */\nexport const resolveDevPluginId = (cwd: string): string => getPluginInfo(cwd).name;\n\nexport async function startPluginDevServer(\n options: PluginDevServeOptions = {},\n): Promise<PluginDevServerHandle> {\n process.env.BOS_DEV_SERVER = \"1\";\n const cwd = options.cwd ?? process.cwd();\n const pluginInfo = getPluginInfo(cwd);\n const devConfig = loadDevConfig(path.join(cwd, \"plugin.dev.ts\"));\n const pluginId = resolveDevPluginId(cwd);\n const compositionKey = pluginLayoutKey(cwd) ?? pluginId;\n const port = options.port ?? (Number(process.env.PORT) || devConfig?.port || 3999);\n const rpcPrefix = normalizePrefix(devConfig?.prefix);\n\n const distDir = path.join(cwd, \"dist\");\n const serveStatic = sirv(distDir, { dev: true });\n\n // No-watch mode (BOS_NO_WATCH=1): build once, serve the built output.\n // Regression/CI stacks need no hot reload — watchers are the stack's\n // heaviest processes and stall runs freeze under their accumulated\n // footprint. One-shot builds exit; steady state is small static servers.\n const noWatch = options.watch === false || process.env.BOS_NO_WATCH === \"1\";\n\n const runOnce = (cmd: string, args: string[]) =>\n new Promise<void>((resolve, reject) => {\n const child = spawn(cmd, args, { cwd, stdio: \"inherit\", env: process.env });\n child.on(\"error\", reject);\n child.on(\"exit\", (code) => {\n if (code === 0) resolve();\n else reject(new Error(`❌ ${cmd} ${args.join(\" \")} exited with ${code}`));\n });\n });\n\n let watcher: ReturnType<typeof spawn> | null = null;\n if (noWatch) {\n const generatedConfig = ensureGeneratedRspackConfig(cwd);\n await runOnce(\"rspack\", generatedConfig ? [\"build\", \"--config\", generatedConfig] : [\"build\"]);\n } else if (options.watch !== false) {\n const generatedConfig = ensureGeneratedRspackConfig(cwd);\n watcher = spawn(\n \"rspack\",\n generatedConfig ? [\"build\", \"--watch\", \"--config\", generatedConfig] : [\"build\", \"--watch\"],\n {\n cwd,\n stdio: \"inherit\",\n env: process.env,\n },\n );\n watcher.on(\"error\", (error) => {\n console.error(`❌ Failed to spawn rspack build --watch: ${error.message}`);\n });\n }\n\n let uiWatcher: ReturnType<typeof spawn> | null = null;\n let uiStaticServer: http.Server | null = null;\n const uiPort = process.env.BOS_UI_PORT;\n const uiConfig = ensureGeneratedUiRsbuildConfig(cwd);\n if (uiConfig && noWatch && uiPort) {\n // Folder-form ui: one-shot build, then serve the ui source root's dist\n // (the factory's absolute distPath target) statically on the ui port.\n await runOnce(\"rsbuild\", [\"build\", \"--config\", uiConfig]);\n const uiDistDir = uiDistDirFor(cwd);\n if (!fs.existsSync(path.join(uiDistDir, DEV_ENTRY_FILENAME))) {\n throw new Error(\n `❌ UI dist is missing at ${uiDistDir} after the rsbuild one-shot — build output layout mismatch?`,\n );\n }\n const serveUiStatic = sirv(uiDistDir, { dev: true });\n uiStaticServer = http.createServer((req, res) => {\n applyCorsHeaders(res);\n serveUiStatic(req, res, () => {\n sendText(res, 404, \"Not Found\");\n });\n });\n await new Promise<void>((resolve, reject) => {\n uiStaticServer!.once(\"error\", reject);\n uiStaticServer!.listen(Number(uiPort), () => resolve());\n });\n console.log(`├─ 🎨 UI: http://localhost:${uiPort} (built, no watch)`);\n } else if (uiConfig) {\n uiWatcher = spawn(\"rsbuild\", [\"dev\", \"--config\", uiConfig], {\n cwd,\n stdio: \"inherit\",\n env: uiPort ? { ...process.env, PORT: uiPort } : process.env,\n });\n uiWatcher.on(\"error\", (error) => {\n console.error(`❌ Failed to spawn rsbuild ui dev: ${error.message}`);\n });\n console.log(`├─ 🎨 UI: ${uiPort ? `http://localhost:${uiPort}` : \"(rsbuild auto port)\"}`);\n }\n\n const handlers: { rpc: any; api: any } = { rpc: null, api: null };\n const effectContextHolder: { context: unknown } = { context: null };\n let runtime: { shutdown: () => Promise<void> } | null = null;\n const host = await startDirectModuleHost({\n name: pluginInfo.normalizedName,\n version: pluginInfo.version,\n handlers,\n effectContext: () => effectContextHolder.context,\n port,\n staticHandler: serveStatic,\n });\n\n console.log(`🚀 ${pluginInfo.name} dev server listening on port ${host.port}`);\n console.log(`├─ 📡 RPC: http://localhost:${host.port}/api/rpc${rpcPrefix}`);\n console.log(`├─ 📖 Docs: http://localhost:${host.port}/api`);\n console.log(`└─ 💚 Health: http://localhost:${host.port}/`);\n\n const load = async () => {\n try {\n // Import framework internals directly. A package self-import can resolve\n // the published entry while this source-first dev server is running,\n // which leaves the runtime exports unavailable on Windows.\n const { createPluginRuntime } = await import(\"../runtime\");\n const { RPCHandler } = await import(\"@orpc/server/fetch\");\n const { OpenAPIHandler } = await import(\"@orpc/openapi/fetch\");\n const { OpenAPIGenerator } = await import(\"@orpc/openapi\");\n const { OpenAPIReferenceHandlerPlugin } = await import(\"@orpc/openapi/plugins\");\n const { ZodToJsonSchemaConverter } = await import(\"@orpc/zod\");\n const { onError } = await import(\"@orpc/server\");\n const { formatORPCError } = await import(\"../errors\");\n\n const runtimeConfig = readRuntimeConfigFromEnv();\n const { siblings, dependsOn } = collectSiblingRemotes(runtimeConfig, compositionKey);\n\n if (dependsOn.length > 0) {\n console.log(`🔗 Loading sibling plugin(s): ${dependsOn.join(\", \")}`);\n }\n\n const registry: Record<string, { remote: string }> = {\n [pluginId]: {\n remote: `http://localhost:${host.port}/${DEV_ENTRY_FILENAME}`,\n },\n ...siblings,\n };\n\n const mfRuntime = createPluginRuntime({ registry });\n runtime = mfRuntime;\n\n const pluginsMap: Record<string, unknown> = {};\n const siblingEffectContexts: unknown[] = [];\n for (const depId of Object.keys(siblings)) {\n const dep = await loadPluginWithRetry(mfRuntime, depId, siblings[depId]!.remote);\n pluginsMap[depId] = { client: dep.createClient, router: dep.router };\n if (dep.initialized?.effectContext) {\n siblingEffectContexts.push(dep.initialized.effectContext);\n }\n console.log(`✅ Loaded dependency plugin: ${depId}`);\n }\n\n const loaded: any = await loadPluginWithRetry(\n mfRuntime,\n pluginId,\n registry[pluginId]!.remote,\n (devConfig?.config ?? { variables: {}, secrets: {} }) as Record<string, unknown>,\n Object.keys(pluginsMap).length > 0 ? pluginsMap : undefined,\n );\n\n const { Context } = await import(\"effect\");\n effectContextHolder.context = [loaded.initialized?.effectContext, ...siblingEffectContexts]\n .filter(Boolean)\n .reduce((acc: any, ctx: any) => Context.merge(acc, ctx), Context.empty());\n\n handlers.rpc = new RPCHandler(loaded.router, {\n errorStatusMap: PLUGIN_ERROR_STATUS_MAP,\n interceptors: [\n onError((error: any) => {\n const formatted = formatORPCError(error);\n if (formatted) console.error(formatted);\n }),\n ],\n });\n\n const generator = new OpenAPIGenerator({ converters: [new ZodToJsonSchemaConverter()] });\n\n handlers.api = new OpenAPIHandler(loaded.router, {\n errorStatusMap: PLUGIN_ERROR_STATUS_MAP,\n plugins: [\n new OpenAPIReferenceHandlerPlugin({\n spec: () => generator.generate(loaded.router, { version: \"3.1.1\" }),\n }),\n ],\n interceptors: [\n onError((error: any) => {\n const formatted = formatORPCError(error);\n if (formatted) console.error(formatted);\n }),\n ],\n });\n\n console.log(`✅ Plugin ready: ${pluginId}`);\n } catch (error) {\n console.error(`❌ Failed to load plugin ${pluginId}:`, error);\n console.error(\" Server stays up; fix the build and retry via rebuild.\");\n }\n };\n\n void load();\n\n const close = async () => {\n handlers.rpc = null;\n handlers.api = null;\n effectContextHolder.context = null;\n for (const child of [watcher, uiWatcher]) {\n if (child) {\n await killChildEscalating(child);\n }\n }\n if (uiStaticServer) {\n await new Promise<void>((resolve) => uiStaticServer.close(() => resolve()));\n }\n await host.close();\n if (runtime) await runtime.shutdown().catch(() => {});\n };\n\n process.once(\"SIGINT\", async () => {\n const timeout = setTimeout(() => process.exit(0), 3000);\n await close();\n clearTimeout(timeout);\n process.exit(0);\n });\n process.once(\"SIGTERM\", async () => {\n const timeout = setTimeout(() => process.exit(0), 3000);\n await close();\n clearTimeout(timeout);\n process.exit(0);\n });\n\n watchParentDeath(async () => {\n const timeout = setTimeout(() => process.exit(0), 3000);\n await close();\n clearTimeout(timeout);\n process.exit(0);\n });\n\n return { port, close };\n}\n\nconst invokedAsCli = import.meta.main || (process.argv[1] ?? \"\").includes(\"every-plugin-serve\");\n\nif (invokedAsCli) {\n startPluginDevServer().catch((error) => {\n console.error(\"❌ Plugin dev server fatal error:\", error);\n process.exit(1);\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAmBA,MAAM,cAAc;CAClB,+BAA+B;CAC/B,gCAAgC;CAChC,gCAAgC;AAClC;AAEA,MAAM,oBAAoB,QAA6B;CACrD,OAAO,QAAQ,WAAW,CAAC,CAAC,SAAS,CAAC,KAAK,WAAW;EACpD,IAAI,UAAU,KAAK,KAAK;CAC1B,CAAC;AACH;AAEA,MAAM,mBAAmB,WAA4B;CACnD,IAAI,CAAC,QAAQ,OAAO;CACpB,MAAM,UAAU,OAAO,QAAQ,cAAc,EAAE;CAC/C,OAAO,UAAU,IAAI,YAAY;AACnC;AAEA,MAAM,iCAAsC;CAC1C,MAAM,MAAM,QAAQ,IAAI;CACxB,IAAI,CAAC,KAAK,OAAO;CACjB,IAAI;EACF,OAAO,KAAK,MAAM,GAAG;CACvB,QAAQ;EACN,OAAO;CACT;AACF;AAEA,MAAM,yBAAyB,eAAoB,aAAqB;CACtE,MA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tD;CAEA,QAAQ,KAAK,UAAU,YAAY;EACjC,MAAM,UAAU,iBAAiB,QAAQ,KAAK,CAAC,GAAG,GAAI;EACtD,MAAM,MAAM;EACZ,aAAa,OAAO;EACpB,QAAQ,KAAK,CAAC;CAChB,CAAC;CACD,QAAQ,KAAK,WAAW,YAAY;EAClC,MAAM,UAAU,iBAAiB,QAAQ,KAAK,CAAC,GAAG,GAAI;EACtD,MAAM,MAAM;EACZ,aAAa,OAAO;EACpB,QAAQ,KAAK,CAAC;CAChB,CAAC;CAED,oCAAiB,YAAY;EAC3B,MAAM,UAAU,iBAAiB,QAAQ,KAAK,CAAC,GAAG,GAAI;EACtD,MAAM,MAAM;EACZ,aAAa,OAAO;EACpB,QAAQ,KAAK,CAAC;CAChB,CAAC;CAED,OAAO;EAAE;EAAM;CAAM;AACvB;AAIA,OAFiC,SAAS,QAAQ,KAAK,MAAM,GAAE,CAAE,SAAS,oBAAoB,GAG5F,qBAAqB,CAAC,CAAC,OAAO,UAAU;CACtC,QAAQ,MAAM,oCAAoC,KAAK;CACvD,QAAQ,KAAK,CAAC;AAChB,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"serve.d.cts","names":[],"sources":["../../src/dev/serve.ts"],"mappings":";UA0FiB;EACf;EACA;EACA;;UAGe;EACf;EACA,aAAa;;;;;;;;;;cAWF,qBAAkB;iBAET,qBACpB,UAAS,wBACR,QAAQ"}
1
+ {"version":3,"file":"serve.d.cts","names":[],"sources":["../../src/dev/serve.ts"],"mappings":";UA8FiB;EACf;EACA;EACA;;UAGe;EACf;EACA,aAAa;;;;;;;;;;cAWF,qBAAkB;iBAET,qBACpB,UAAS,wBACR,QAAQ"}
@@ -1 +1 @@
1
- {"version":3,"file":"serve.d.mts","names":[],"sources":["../../src/dev/serve.ts"],"mappings":";UA0FiB;EACf;EACA;EACA;;UAGe;EACf;EACA,aAAa;;;;;;;;;;cAWF,qBAAkB;iBAET,qBACpB,UAAS,wBACR,QAAQ"}
1
+ {"version":3,"file":"serve.d.mts","names":[],"sources":["../../src/dev/serve.ts"],"mappings":";UA8FiB;EACf;EACA;EACA;;UAGe;EACf;EACA,aAAa;;;;;;;;;;cAWF,qBAAkB;iBAET,qBACpB,UAAS,wBACR,QAAQ"}
@@ -3,7 +3,7 @@ import { PLUGIN_ERROR_STATUS_MAP } from "../errors.mjs";
3
3
  import { DEV_ENTRY_FILENAME } from "../build/artifact-names.mjs";
4
4
  import { loadRemoteWithRetry } from "../remote-entry.mjs";
5
5
  import { getPluginInfo, loadDevConfig } from "../build/rspack/utils.mjs";
6
- import { ensureGeneratedUiRsbuildConfig, pluginLayoutKey } from "../build/ui/generated-config.mjs";
6
+ import { ensureGeneratedUiRsbuildConfig, pluginLayoutKey, uiDistDirFor } from "../build/ui/generated-config.mjs";
7
7
  import { startDirectModuleHost } from "./host.mjs";
8
8
  import { ensureGeneratedRspackConfig } from "../build/rspack/generated-config.mjs";
9
9
  import { killChildEscalating, watchParentDeath } from "./watch-kill.mjs";
@@ -138,8 +138,8 @@ async function startPluginDevServer(options = {}) {
138
138
  "--config",
139
139
  uiConfig
140
140
  ]);
141
- const uiDistDir = path.basename(cwd) === "ui" ? path.join(cwd, "dist") : path.join(cwd, "ui", "dist");
142
- if (!fs.existsSync(path.join(uiDistDir, "remoteEntry.js"))) console.error(`❌ UI dist is missing at ${uiDistDir} — the ui static server would serve 404s for every asset (build output layout mismatch?)`);
141
+ const uiDistDir = uiDistDirFor(cwd);
142
+ if (!fs.existsSync(path.join(uiDistDir, "remoteEntry.js"))) throw new Error(`❌ UI dist is missing at ${uiDistDir} after the rsbuild one-shot — build output layout mismatch?`);
143
143
  const serveUiStatic = sirv(uiDistDir, { dev: true });
144
144
  uiStaticServer = http.createServer((req, res) => {
145
145
  applyCorsHeaders(res);
@@ -1 +1 @@
1
- {"version":3,"file":"serve.mjs","names":[],"sources":["../../src/dev/serve.ts"],"sourcesContent":["import { spawn } from \"node:child_process\";\nimport fs from \"node:fs\";\nimport http from \"node:http\";\nimport path from \"node:path\";\nimport { Effect } from \"effect\";\nimport sirv from \"sirv\";\nimport { DEV_ENTRY_FILENAME } from \"../build/artifact-names\";\nimport { ensureGeneratedRspackConfig } from \"../build/rspack/generated-config\";\nimport { getPluginInfo, loadDevConfig } from \"../build/rspack/utils\";\nimport { ensureGeneratedUiRsbuildConfig, pluginLayoutKey } from \"../build/ui/generated-config\";\nimport { PLUGIN_ERROR_STATUS_MAP } from \"../errors\";\nimport { loadRemoteWithRetry } from \"../remote-entry\";\nimport { startDirectModuleHost } from \"./host\";\nimport { killChildEscalating, watchParentDeath } from \"./watch-kill\";\n\nconst corsHeaders = {\n \"Access-Control-Allow-Origin\": \"*\",\n \"Access-Control-Allow-Methods\": \"GET, POST, PUT, DELETE, PATCH, OPTIONS\",\n \"Access-Control-Allow-Headers\": \"X-Requested-With, content-type, Authorization\",\n};\n\nconst applyCorsHeaders = (res: http.ServerResponse) => {\n Object.entries(corsHeaders).forEach(([key, value]) => {\n res.setHeader(key, value);\n });\n};\n\nconst normalizePrefix = (prefix?: string): string => {\n if (!prefix) return \"\";\n const cleaned = prefix.replace(/^\\/+|\\/+$/g, \"\");\n return cleaned ? `/${cleaned}` : \"\";\n};\n\nconst readRuntimeConfigFromEnv = (): any => {\n const raw = process.env.BOS_RUNTIME_CONFIG;\n if (!raw) return null;\n try {\n return JSON.parse(raw);\n } catch {\n return null;\n }\n};\n\nconst collectSiblingRemotes = (runtimeConfig: any, pluginId: string) => {\n const siblings: Record<string, { remote: string }> = {};\n\n const isApi = pluginId === \"api\" || runtimeConfig?.api?.name === pluginId;\n\n const ownKey = runtimeConfig?.plugins?.[pluginId] ? pluginId : null;\n let dependsOn: string[] = [];\n if (ownKey) {\n dependsOn = runtimeConfig.plugins[ownKey].dependsOn ?? [];\n } else if (isApi) {\n dependsOn = runtimeConfig?.api?.dependsOn ?? [];\n }\n\n for (const depId of dependsOn) {\n const dep = runtimeConfig?.plugins?.[depId];\n if (!dep || dep.source !== \"local\" || !dep.url) continue;\n if (depId === pluginId) continue;\n const base = dep.url.replace(/\\/$/, \"\");\n siblings[depId] = { remote: `${base}/${DEV_ENTRY_FILENAME}` };\n }\n\n return { siblings, dependsOn };\n};\n\nconst loadPluginWithRetry = (\n runtime: any,\n pluginId: string,\n remoteUrl: string,\n options: Record<string, unknown> = { variables: {}, secrets: {} },\n pluginsMap?: Record<string, unknown>,\n timeoutMs = 90000,\n): Promise<any> =>\n Effect.runPromise(\n loadRemoteWithRetry({\n label: pluginId,\n remoteUrl,\n load: () => runtime.usePlugin(pluginId, options, pluginsMap),\n timeoutMs,\n }),\n );\n\nconst sendText = (res: http.ServerResponse, status: number, text: string) => {\n res.statusCode = status;\n res.setHeader(\"content-type\", \"text/plain; charset=utf-8\");\n res.end(text);\n};\n\nexport interface PluginDevServeOptions {\n cwd?: string;\n port?: number;\n watch?: boolean;\n}\n\nexport interface PluginDevServerHandle {\n port: number;\n close: () => Promise<void>;\n}\n\n/**\n * The dev server's plugin id — the workspace's npm package name, the same\n * value the host passes as `runtimeId`. Both initialize sites must agree:\n * `registerRemote` derives the MF remote name from it, and the plugin's\n * database layer derives its migration slug from it, so a pre-normalized\n * remote name here would migrate into a different schema than the host\n * expects. plugin.dev.ts no longer carries a pluginId field.\n */\nexport const resolveDevPluginId = (cwd: string): string => getPluginInfo(cwd).name;\n\nexport async function startPluginDevServer(\n options: PluginDevServeOptions = {},\n): Promise<PluginDevServerHandle> {\n process.env.BOS_DEV_SERVER = \"1\";\n const cwd = options.cwd ?? process.cwd();\n const pluginInfo = getPluginInfo(cwd);\n const devConfig = loadDevConfig(path.join(cwd, \"plugin.dev.ts\"));\n const pluginId = resolveDevPluginId(cwd);\n const compositionKey = pluginLayoutKey(cwd) ?? pluginId;\n const port = options.port ?? (Number(process.env.PORT) || devConfig?.port || 3999);\n const rpcPrefix = normalizePrefix(devConfig?.prefix);\n\n const distDir = path.join(cwd, \"dist\");\n const serveStatic = sirv(distDir, { dev: true });\n\n // No-watch mode (BOS_NO_WATCH=1): build once, serve the built output.\n // Regression/CI stacks need no hot reload — watchers are the stack's\n // heaviest processes and stall runs freeze under their accumulated\n // footprint. One-shot builds exit; steady state is small static servers.\n const noWatch = options.watch === false || process.env.BOS_NO_WATCH === \"1\";\n\n const runOnce = (cmd: string, args: string[]) =>\n new Promise<void>((resolve, reject) => {\n const child = spawn(cmd, args, { cwd, stdio: \"inherit\", env: process.env });\n child.on(\"error\", reject);\n child.on(\"exit\", (code) => {\n if (code === 0) resolve();\n else reject(new Error(`❌ ${cmd} ${args.join(\" \")} exited with ${code}`));\n });\n });\n\n let watcher: ReturnType<typeof spawn> | null = null;\n if (noWatch) {\n const generatedConfig = ensureGeneratedRspackConfig(cwd);\n await runOnce(\"rspack\", generatedConfig ? [\"build\", \"--config\", generatedConfig] : [\"build\"]);\n } else if (options.watch !== false) {\n const generatedConfig = ensureGeneratedRspackConfig(cwd);\n watcher = spawn(\n \"rspack\",\n generatedConfig ? [\"build\", \"--watch\", \"--config\", generatedConfig] : [\"build\", \"--watch\"],\n {\n cwd,\n stdio: \"inherit\",\n env: process.env,\n },\n );\n watcher.on(\"error\", (error) => {\n console.error(`❌ Failed to spawn rspack build --watch: ${error.message}`);\n });\n }\n\n let uiWatcher: ReturnType<typeof spawn> | null = null;\n let uiStaticServer: http.Server | null = null;\n const uiPort = process.env.BOS_UI_PORT;\n const uiConfig = ensureGeneratedUiRsbuildConfig(cwd);\n if (uiConfig && noWatch && uiPort) {\n // Folder-form ui: one-shot build, then serve the ui source root's dist\n // (the factory's absolute distPath target) statically on the ui port.\n await runOnce(\"rsbuild\", [\"build\", \"--config\", uiConfig]);\n const uiDistDir =\n path.basename(cwd) === \"ui\" ? path.join(cwd, \"dist\") : path.join(cwd, \"ui\", \"dist\");\n if (!fs.existsSync(path.join(uiDistDir, DEV_ENTRY_FILENAME))) {\n console.error(\n `❌ UI dist is missing at ${uiDistDir} — the ui static server would serve 404s for every asset (build output layout mismatch?)`,\n );\n }\n const serveUiStatic = sirv(uiDistDir, { dev: true });\n uiStaticServer = http.createServer((req, res) => {\n applyCorsHeaders(res);\n serveUiStatic(req, res, () => {\n sendText(res, 404, \"Not Found\");\n });\n });\n await new Promise<void>((resolve, reject) => {\n uiStaticServer!.once(\"error\", reject);\n uiStaticServer!.listen(Number(uiPort), () => resolve());\n });\n console.log(`├─ 🎨 UI: http://localhost:${uiPort} (built, no watch)`);\n } else if (uiConfig) {\n uiWatcher = spawn(\"rsbuild\", [\"dev\", \"--config\", uiConfig], {\n cwd,\n stdio: \"inherit\",\n env: uiPort ? { ...process.env, PORT: uiPort } : process.env,\n });\n uiWatcher.on(\"error\", (error) => {\n console.error(`❌ Failed to spawn rsbuild ui dev: ${error.message}`);\n });\n console.log(`├─ 🎨 UI: ${uiPort ? `http://localhost:${uiPort}` : \"(rsbuild auto port)\"}`);\n }\n\n const handlers: { rpc: any; api: any } = { rpc: null, api: null };\n const effectContextHolder: { context: unknown } = { context: null };\n let runtime: { shutdown: () => Promise<void> } | null = null;\n const host = await startDirectModuleHost({\n name: pluginInfo.normalizedName,\n version: pluginInfo.version,\n handlers,\n effectContext: () => effectContextHolder.context,\n port,\n staticHandler: serveStatic,\n });\n\n console.log(`🚀 ${pluginInfo.name} dev server listening on port ${host.port}`);\n console.log(`├─ 📡 RPC: http://localhost:${host.port}/api/rpc${rpcPrefix}`);\n console.log(`├─ 📖 Docs: http://localhost:${host.port}/api`);\n console.log(`└─ 💚 Health: http://localhost:${host.port}/`);\n\n const load = async () => {\n try {\n // Import framework internals directly. A package self-import can resolve\n // the published entry while this source-first dev server is running,\n // which leaves the runtime exports unavailable on Windows.\n const { createPluginRuntime } = await import(\"../runtime\");\n const { RPCHandler } = await import(\"@orpc/server/fetch\");\n const { OpenAPIHandler } = await import(\"@orpc/openapi/fetch\");\n const { OpenAPIGenerator } = await import(\"@orpc/openapi\");\n const { OpenAPIReferenceHandlerPlugin } = await import(\"@orpc/openapi/plugins\");\n const { ZodToJsonSchemaConverter } = await import(\"@orpc/zod\");\n const { onError } = await import(\"@orpc/server\");\n const { formatORPCError } = await import(\"../errors\");\n\n const runtimeConfig = readRuntimeConfigFromEnv();\n const { siblings, dependsOn } = collectSiblingRemotes(runtimeConfig, compositionKey);\n\n if (dependsOn.length > 0) {\n console.log(`🔗 Loading sibling plugin(s): ${dependsOn.join(\", \")}`);\n }\n\n const registry: Record<string, { remote: string }> = {\n [pluginId]: {\n remote: `http://localhost:${host.port}/${DEV_ENTRY_FILENAME}`,\n },\n ...siblings,\n };\n\n const mfRuntime = createPluginRuntime({ registry });\n runtime = mfRuntime;\n\n const pluginsMap: Record<string, unknown> = {};\n const siblingEffectContexts: unknown[] = [];\n for (const depId of Object.keys(siblings)) {\n const dep = await loadPluginWithRetry(mfRuntime, depId, siblings[depId]!.remote);\n pluginsMap[depId] = { client: dep.createClient, router: dep.router };\n if (dep.initialized?.effectContext) {\n siblingEffectContexts.push(dep.initialized.effectContext);\n }\n console.log(`✅ Loaded dependency plugin: ${depId}`);\n }\n\n const loaded: any = await loadPluginWithRetry(\n mfRuntime,\n pluginId,\n registry[pluginId]!.remote,\n (devConfig?.config ?? { variables: {}, secrets: {} }) as Record<string, unknown>,\n Object.keys(pluginsMap).length > 0 ? pluginsMap : undefined,\n );\n\n const { Context } = await import(\"effect\");\n effectContextHolder.context = [loaded.initialized?.effectContext, ...siblingEffectContexts]\n .filter(Boolean)\n .reduce((acc: any, ctx: any) => Context.merge(acc, ctx), Context.empty());\n\n handlers.rpc = new RPCHandler(loaded.router, {\n errorStatusMap: PLUGIN_ERROR_STATUS_MAP,\n interceptors: [\n onError((error: any) => {\n const formatted = formatORPCError(error);\n if (formatted) console.error(formatted);\n }),\n ],\n });\n\n const generator = new OpenAPIGenerator({ converters: [new ZodToJsonSchemaConverter()] });\n\n handlers.api = new OpenAPIHandler(loaded.router, {\n errorStatusMap: PLUGIN_ERROR_STATUS_MAP,\n plugins: [\n new OpenAPIReferenceHandlerPlugin({\n spec: () => generator.generate(loaded.router, { version: \"3.1.1\" }),\n }),\n ],\n interceptors: [\n onError((error: any) => {\n const formatted = formatORPCError(error);\n if (formatted) console.error(formatted);\n }),\n ],\n });\n\n console.log(`✅ Plugin ready: ${pluginId}`);\n } catch (error) {\n console.error(`❌ Failed to load plugin ${pluginId}:`, error);\n console.error(\" Server stays up; fix the build and retry via rebuild.\");\n }\n };\n\n void load();\n\n const close = async () => {\n handlers.rpc = null;\n handlers.api = null;\n effectContextHolder.context = null;\n for (const child of [watcher, uiWatcher]) {\n if (child) {\n await killChildEscalating(child);\n }\n }\n if (uiStaticServer) {\n await new Promise<void>((resolve) => uiStaticServer.close(() => resolve()));\n }\n await host.close();\n if (runtime) await runtime.shutdown().catch(() => {});\n };\n\n process.once(\"SIGINT\", async () => {\n const timeout = setTimeout(() => process.exit(0), 3000);\n await close();\n clearTimeout(timeout);\n process.exit(0);\n });\n process.once(\"SIGTERM\", async () => {\n const timeout = setTimeout(() => process.exit(0), 3000);\n await close();\n clearTimeout(timeout);\n process.exit(0);\n });\n\n watchParentDeath(async () => {\n const timeout = setTimeout(() => process.exit(0), 3000);\n await close();\n clearTimeout(timeout);\n process.exit(0);\n });\n\n return { port, close };\n}\n\nconst invokedAsCli = import.meta.main || (process.argv[1] ?? \"\").includes(\"every-plugin-serve\");\n\nif (invokedAsCli) {\n startPluginDevServer().catch((error) => {\n console.error(\"❌ Plugin dev server fatal error:\", error);\n process.exit(1);\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAeA,MAAM,cAAc;CAClB,+BAA+B;CAC/B,gCAAgC;CAChC,gCAAgC;AAClC;AAEA,MAAM,oBAAoB,QAA6B;CACrD,OAAO,QAAQ,WAAW,CAAC,CAAC,SAAS,CAAC,KAAK,WAAW;EACpD,IAAI,UAAU,KAAK,KAAK;CAC1B,CAAC;AACH;AAEA,MAAM,mBAAmB,WAA4B;CACnD,IAAI,CAAC,QAAQ,OAAO;CACpB,MAAM,UAAU,OAAO,QAAQ,cAAc,EAAE;CAC/C,OAAO,UAAU,IAAI,YAA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U;EAC9B,KAAK,MAAM,SAAS,CAAC,SAAS,SAAS,GACrC,IAAI,OACF,MAAM,oBAAoB,KAAK;EAGnC,IAAI,gBACF,MAAM,IAAI,SAAe,YAAY,eAAe,YAAY,QAAQ,CAAC,CAAC;EAE5E,MAAM,KAAK,MAAM;EACjB,IAAI,SAAS,MAAM,QAAQ,SAAS,CAAC,CAAC,YAAY,CAAC,CAAC;CACtD;CAEA,QAAQ,KAAK,UAAU,YAAY;EACjC,MAAM,UAAU,iBAAiB,QAAQ,KAAK,CAAC,GAAG,GAAI;EACtD,MAAM,MAAM;EACZ,aAAa,OAAO;EACpB,QAAQ,KAAK,CAAC;CAChB,CAAC;CACD,QAAQ,KAAK,WAAW,YAAY;EAClC,MAAM,UAAU,iBAAiB,QAAQ,KAAK,CAAC,GAAG,GAAI;EACtD,MAAM,MAAM;EACZ,aAAa,OAAO;EACpB,QAAQ,KAAK,CAAC;CAChB,CAAC;CAED,iBAAiB,YAAY;EAC3B,MAAM,UAAU,iBAAiB,QAAQ,KAAK,CAAC,GAAG,GAAI;EACtD,MAAM,MAAM;EACZ,aAAa,OAAO;EACpB,QAAQ,KAAK,CAAC;CAChB,CAAC;CAED,OAAO;EAAE;EAAM;CAAM;AACvB;AAIA,IAFqB,YAAY,SAAS,QAAQ,KAAK,MAAM,GAAE,CAAE,SAAS,oBAAoB,GAG5F,qBAAqB,CAAC,CAAC,OAAO,UAAU;CACtC,QAAQ,MAAM,oCAAoC,KAAK;CACvD,QAAQ,KAAK,CAAC;AAChB,CAAC"}
1
+ {"version":3,"file":"serve.mjs","names":[],"sources":["../../src/dev/serve.ts"],"sourcesContent":["import { spawn } from \"node:child_process\";\nimport fs from \"node:fs\";\nimport http from \"node:http\";\nimport path from \"node:path\";\nimport { Effect } from \"effect\";\nimport sirv from \"sirv\";\nimport { DEV_ENTRY_FILENAME } from \"../build/artifact-names\";\nimport { ensureGeneratedRspackConfig } from \"../build/rspack/generated-config\";\nimport { getPluginInfo, loadDevConfig } from \"../build/rspack/utils\";\nimport {\n ensureGeneratedUiRsbuildConfig,\n pluginLayoutKey,\n uiDistDirFor,\n} from \"../build/ui/generated-config\";\nimport { PLUGIN_ERROR_STATUS_MAP } from \"../errors\";\nimport { loadRemoteWithRetry } from \"../remote-entry\";\nimport { startDirectModuleHost } from \"./host\";\nimport { killChildEscalating, watchParentDeath } from \"./watch-kill\";\n\nconst corsHeaders = {\n \"Access-Control-Allow-Origin\": \"*\",\n \"Access-Control-Allow-Methods\": \"GET, POST, PUT, DELETE, PATCH, OPTIONS\",\n \"Access-Control-Allow-Headers\": \"X-Requested-With, content-type, Authorization\",\n};\n\nconst applyCorsHeaders = (res: http.ServerResponse) => {\n Object.entries(corsHeaders).forEach(([key, value]) => {\n res.setHeader(key, value);\n });\n};\n\nconst normalizePrefix = (prefix?: string): string => {\n if (!prefix) return \"\";\n const cleaned = prefix.replace(/^\\/+|\\/+$/g, \"\");\n return cleaned ? `/${cleaned}` : \"\";\n};\n\nconst readRuntimeConfigFromEnv = (): any => {\n const raw = process.env.BOS_RUNTIME_CONFIG;\n if (!raw) return null;\n try {\n return JSON.parse(raw);\n } catch {\n return null;\n }\n};\n\nconst collectSiblingRemotes = (runtimeConfig: any, pluginId: string) => {\n const siblings: Record<string, { remote: string }> = {};\n\n const isApi = pluginId === \"api\" || runtimeConfig?.api?.name === pluginId;\n\n const ownKey = runtimeConfig?.plugins?.[pluginId] ? pluginId : null;\n let dependsOn: string[] = [];\n if (ownKey) {\n dependsOn = runtimeConfig.plugins[ownKey].dependsOn ?? [];\n } else if (isApi) {\n dependsOn = runtimeConfig?.api?.dependsOn ?? [];\n }\n\n for (const depId of dependsOn) {\n const dep = runtimeConfig?.plugins?.[depId];\n if (!dep || dep.source !== \"local\" || !dep.url) continue;\n if (depId === pluginId) continue;\n const base = dep.url.replace(/\\/$/, \"\");\n siblings[depId] = { remote: `${base}/${DEV_ENTRY_FILENAME}` };\n }\n\n return { siblings, dependsOn };\n};\n\nconst loadPluginWithRetry = (\n runtime: any,\n pluginId: string,\n remoteUrl: string,\n options: Record<string, unknown> = { variables: {}, secrets: {} },\n pluginsMap?: Record<string, unknown>,\n timeoutMs = 90000,\n): Promise<any> =>\n Effect.runPromise(\n loadRemoteWithRetry({\n label: pluginId,\n remoteUrl,\n load: () => runtime.usePlugin(pluginId, options, pluginsMap),\n timeoutMs,\n }),\n );\n\nconst sendText = (res: http.ServerResponse, status: number, text: string) => {\n res.statusCode = status;\n res.setHeader(\"content-type\", \"text/plain; charset=utf-8\");\n res.end(text);\n};\n\nexport interface PluginDevServeOptions {\n cwd?: string;\n port?: number;\n watch?: boolean;\n}\n\nexport interface PluginDevServerHandle {\n port: number;\n close: () => Promise<void>;\n}\n\n/**\n * The dev server's plugin id — the workspace's npm package name, the same\n * value the host passes as `runtimeId`. Both initialize sites must agree:\n * `registerRemote` derives the MF remote name from it, and the plugin's\n * database layer derives its migration slug from it, so a pre-normalized\n * remote name here would migrate into a different schema than the host\n * expects. plugin.dev.ts no longer carries a pluginId field.\n */\nexport const resolveDevPluginId = (cwd: string): string => getPluginInfo(cwd).name;\n\nexport async function startPluginDevServer(\n options: PluginDevServeOptions = {},\n): Promise<PluginDevServerHandle> {\n process.env.BOS_DEV_SERVER = \"1\";\n const cwd = options.cwd ?? process.cwd();\n const pluginInfo = getPluginInfo(cwd);\n const devConfig = loadDevConfig(path.join(cwd, \"plugin.dev.ts\"));\n const pluginId = resolveDevPluginId(cwd);\n const compositionKey = pluginLayoutKey(cwd) ?? pluginId;\n const port = options.port ?? (Number(process.env.PORT) || devConfig?.port || 3999);\n const rpcPrefix = normalizePrefix(devConfig?.prefix);\n\n const distDir = path.join(cwd, \"dist\");\n const serveStatic = sirv(distDir, { dev: true });\n\n // No-watch mode (BOS_NO_WATCH=1): build once, serve the built output.\n // Regression/CI stacks need no hot reload — watchers are the stack's\n // heaviest processes and stall runs freeze under their accumulated\n // footprint. One-shot builds exit; steady state is small static servers.\n const noWatch = options.watch === false || process.env.BOS_NO_WATCH === \"1\";\n\n const runOnce = (cmd: string, args: string[]) =>\n new Promise<void>((resolve, reject) => {\n const child = spawn(cmd, args, { cwd, stdio: \"inherit\", env: process.env });\n child.on(\"error\", reject);\n child.on(\"exit\", (code) => {\n if (code === 0) resolve();\n else reject(new Error(`❌ ${cmd} ${args.join(\" \")} exited with ${code}`));\n });\n });\n\n let watcher: ReturnType<typeof spawn> | null = null;\n if (noWatch) {\n const generatedConfig = ensureGeneratedRspackConfig(cwd);\n await runOnce(\"rspack\", generatedConfig ? [\"build\", \"--config\", generatedConfig] : [\"build\"]);\n } else if (options.watch !== false) {\n const generatedConfig = ensureGeneratedRspackConfig(cwd);\n watcher = spawn(\n \"rspack\",\n generatedConfig ? [\"build\", \"--watch\", \"--config\", generatedConfig] : [\"build\", \"--watch\"],\n {\n cwd,\n stdio: \"inherit\",\n env: process.env,\n },\n );\n watcher.on(\"error\", (error) => {\n console.error(`❌ Failed to spawn rspack build --watch: ${error.message}`);\n });\n }\n\n let uiWatcher: ReturnType<typeof spawn> | null = null;\n let uiStaticServer: http.Server | null = null;\n const uiPort = process.env.BOS_UI_PORT;\n const uiConfig = ensureGeneratedUiRsbuildConfig(cwd);\n if (uiConfig && noWatch && uiPort) {\n // Folder-form ui: one-shot build, then serve the ui source root's dist\n // (the factory's absolute distPath target) statically on the ui port.\n await runOnce(\"rsbuild\", [\"build\", \"--config\", uiConfig]);\n const uiDistDir = uiDistDirFor(cwd);\n if (!fs.existsSync(path.join(uiDistDir, DEV_ENTRY_FILENAME))) {\n throw new Error(\n `❌ UI dist is missing at ${uiDistDir} after the rsbuild one-shot — build output layout mismatch?`,\n );\n }\n const serveUiStatic = sirv(uiDistDir, { dev: true });\n uiStaticServer = http.createServer((req, res) => {\n applyCorsHeaders(res);\n serveUiStatic(req, res, () => {\n sendText(res, 404, \"Not Found\");\n });\n });\n await new Promise<void>((resolve, reject) => {\n uiStaticServer!.once(\"error\", reject);\n uiStaticServer!.listen(Number(uiPort), () => resolve());\n });\n console.log(`├─ 🎨 UI: http://localhost:${uiPort} (built, no watch)`);\n } else if (uiConfig) {\n uiWatcher = spawn(\"rsbuild\", [\"dev\", \"--config\", uiConfig], {\n cwd,\n stdio: \"inherit\",\n env: uiPort ? { ...process.env, PORT: uiPort } : process.env,\n });\n uiWatcher.on(\"error\", (error) => {\n console.error(`❌ Failed to spawn rsbuild ui dev: ${error.message}`);\n });\n console.log(`├─ 🎨 UI: ${uiPort ? `http://localhost:${uiPort}` : \"(rsbuild auto port)\"}`);\n }\n\n const handlers: { rpc: any; api: any } = { rpc: null, api: null };\n const effectContextHolder: { context: unknown } = { context: null };\n let runtime: { shutdown: () => Promise<void> } | null = null;\n const host = await startDirectModuleHost({\n name: pluginInfo.normalizedName,\n version: pluginInfo.version,\n handlers,\n effectContext: () => effectContextHolder.context,\n port,\n staticHandler: serveStatic,\n });\n\n console.log(`🚀 ${pluginInfo.name} dev server listening on port ${host.port}`);\n console.log(`├─ 📡 RPC: http://localhost:${host.port}/api/rpc${rpcPrefix}`);\n console.log(`├─ 📖 Docs: http://localhost:${host.port}/api`);\n console.log(`└─ 💚 Health: http://localhost:${host.port}/`);\n\n const load = async () => {\n try {\n // Import framework internals directly. A package self-import can resolve\n // the published entry while this source-first dev server is running,\n // which leaves the runtime exports unavailable on Windows.\n const { createPluginRuntime } = await import(\"../runtime\");\n const { RPCHandler } = await import(\"@orpc/server/fetch\");\n const { OpenAPIHandler } = await import(\"@orpc/openapi/fetch\");\n const { OpenAPIGenerator } = await import(\"@orpc/openapi\");\n const { OpenAPIReferenceHandlerPlugin } = await import(\"@orpc/openapi/plugins\");\n const { ZodToJsonSchemaConverter } = await import(\"@orpc/zod\");\n const { onError } = await import(\"@orpc/server\");\n const { formatORPCError } = await import(\"../errors\");\n\n const runtimeConfig = readRuntimeConfigFromEnv();\n const { siblings, dependsOn } = collectSiblingRemotes(runtimeConfig, compositionKey);\n\n if (dependsOn.length > 0) {\n console.log(`🔗 Loading sibling plugin(s): ${dependsOn.join(\", \")}`);\n }\n\n const registry: Record<string, { remote: string }> = {\n [pluginId]: {\n remote: `http://localhost:${host.port}/${DEV_ENTRY_FILENAME}`,\n },\n ...siblings,\n };\n\n const mfRuntime = createPluginRuntime({ registry });\n runtime = mfRuntime;\n\n const pluginsMap: Record<string, unknown> = {};\n const siblingEffectContexts: unknown[] = [];\n for (const depId of Object.keys(siblings)) {\n const dep = await loadPluginWithRetry(mfRuntime, depId, siblings[depId]!.remote);\n pluginsMap[depId] = { client: dep.createClient, router: dep.router };\n if (dep.initialized?.effectContext) {\n siblingEffectContexts.push(dep.initialized.effectContext);\n }\n console.log(`✅ Loaded dependency plugin: ${depId}`);\n }\n\n const loaded: any = await loadPluginWithRetry(\n mfRuntime,\n pluginId,\n registry[pluginId]!.remote,\n (devConfig?.config ?? { variables: {}, secrets: {} }) as Record<string, unknown>,\n Object.keys(pluginsMap).length > 0 ? pluginsMap : undefined,\n );\n\n const { Context } = await import(\"effect\");\n effectContextHolder.context = [loaded.initialized?.effectContext, ...siblingEffectContexts]\n .filter(Boolean)\n .reduce((acc: any, ctx: any) => Context.merge(acc, ctx), Context.empty());\n\n handlers.rpc = new RPCHandler(loaded.router, {\n errorStatusMap: PLUGIN_ERROR_STATUS_MAP,\n interceptors: [\n onError((error: any) => {\n const formatted = formatORPCError(error);\n if (formatted) console.error(formatted);\n }),\n ],\n });\n\n const generator = new OpenAPIGenerator({ converters: [new ZodToJsonSchemaConverter()] });\n\n handlers.api = new OpenAPIHandler(loaded.router, {\n errorStatusMap: PLUGIN_ERROR_STATUS_MAP,\n plugins: [\n new OpenAPIReferenceHandlerPlugin({\n spec: () => generator.generate(loaded.router, { version: \"3.1.1\" }),\n }),\n ],\n interceptors: [\n onError((error: any) => {\n const formatted = formatORPCError(error);\n if (formatted) console.error(formatted);\n }),\n ],\n });\n\n console.log(`✅ Plugin ready: ${pluginId}`);\n } catch (error) {\n console.error(`❌ Failed to load plugin ${pluginId}:`, error);\n console.error(\" Server stays up; fix the build and retry via rebuild.\");\n }\n };\n\n void load();\n\n const close = async () => {\n handlers.rpc = null;\n handlers.api = null;\n effectContextHolder.context = null;\n for (const child of [watcher, uiWatcher]) {\n if (child) {\n await killChildEscalating(child);\n }\n }\n if (uiStaticServer) {\n await new Promise<void>((resolve) => uiStaticServer.close(() => resolve()));\n }\n await host.close();\n if (runtime) await runtime.shutdown().catch(() => {});\n };\n\n process.once(\"SIGINT\", async () => {\n const timeout = setTimeout(() => process.exit(0), 3000);\n await close();\n clearTimeout(timeout);\n process.exit(0);\n });\n process.once(\"SIGTERM\", async () => {\n const timeout = setTimeout(() => process.exit(0), 3000);\n await close();\n clearTimeout(timeout);\n process.exit(0);\n });\n\n watchParentDeath(async () => {\n const timeout = setTimeout(() => process.exit(0), 3000);\n await close();\n clearTimeout(timeout);\n process.exit(0);\n });\n\n return { port, close };\n}\n\nconst invokedAsCli = import.meta.main || (process.argv[1] ?? \"\").includes(\"every-plugin-serve\");\n\nif (invokedAsCli) {\n startPluginDevServer().catch((error) => {\n console.error(\"❌ Plugin dev server fatal error:\", error);\n process.exit(1);\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAmBA,MAAM,cAAc;CAClB,+BAA+B;CAC/B,gCAAgC;CAChC,gCAAgC;AAClC;AAEA,MAAM,oBAAoB,QAA6B;CACrD,OAAO,QAAQ,WAAW,CAAC,CAAC,SAAS,CAAC,KAAK,WAAW;EACpD,IAAI,UAAU,KAAK,KAAK;CAC1B,CAAC;AACH;AAEA,MAAM,mBAAmB,WAA4B;CACnD,IAAI,CAAC,QAAQ,OAAO;CACpB,MAAM,UAAU,OAAO,QAAQ,cAAc,EAAE;CAC/C,OAAO,UAAU,IAAI,YAAY;AACnC;AAEA,MAAM,iCAAsC;CAC1C,MAAM,MAAM,QAAQ,IAAI;CACxB,IAAI,CAAC,KAAK,OAAO;CACjB,IAAI;EACF,OAAO,KAAK,MAAM,GAAG;CACvB,QAAQ;EACN,OAAO;CACT;AACF;AAEA,MAAM,yBAAyB,eAAoB,a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,KAAK,UAAU,YAAY;EACjC,MAAM,UAAU,iBAAiB,QAAQ,KAAK,CAAC,GAAG,GAAI;EACtD,MAAM,MAAM;EACZ,aAAa,OAAO;EACpB,QAAQ,KAAK,CAAC;CAChB,CAAC;CACD,QAAQ,KAAK,WAAW,YAAY;EAClC,MAAM,UAAU,iBAAiB,QAAQ,KAAK,CAAC,GAAG,GAAI;EACtD,MAAM,MAAM;EACZ,aAAa,OAAO;EACpB,QAAQ,KAAK,CAAC;CAChB,CAAC;CAED,iBAAiB,YAAY;EAC3B,MAAM,UAAU,iBAAiB,QAAQ,KAAK,CAAC,GAAG,GAAI;EACtD,MAAM,MAAM;EACZ,aAAa,OAAO;EACpB,QAAQ,KAAK,CAAC;CAChB,CAAC;CAED,OAAO;EAAE;EAAM;CAAM;AACvB;AAIA,IAFqB,YAAY,SAAS,QAAQ,KAAK,MAAM,GAAE,CAAE,SAAS,oBAAoB,GAG5F,qBAAqB,CAAC,CAAC,OAAO,UAAU;CACtC,QAAQ,MAAM,oCAAoC,KAAK;CACvD,QAAQ,KAAK,CAAC;AAChB,CAAC"}
@@ -98,6 +98,5 @@ const loadRemoteWithRetry = (options) => {
98
98
  exports.isRemoteEntryBody = isRemoteEntryBody;
99
99
  exports.loadRemoteWithRetry = loadRemoteWithRetry;
100
100
  exports.purgeRemoteEntryCache = purgeRemoteEntryCache;
101
- exports.sleep = sleep;
102
101
  exports.waitForRemoteEntryReady = waitForRemoteEntryReady;
103
102
  //# sourceMappingURL=remote-entry.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"remote-entry.cjs","names":["Schedule","Duration","Effect","classifyPluginFailure","deepestErrorStack","toPluginRuntimeError"],"sources":["../src/remote-entry.ts"],"sourcesContent":["/**\n * Remote-entry loading resilience — the ONE contract every MF consumer in\n * the dev stack shares (plugin dev serves, the host's plugin loader).\n *\n * Two failure classes it exists for:\n * 1. Cold compile: remoteEntry.js 404s until the remote's first build —\n * the 404 body gets eval'd as JS (\"Unexpected identifier 'Found'\").\n * 2. Watch-rebuild poisoning: a failed entry load is memoized forever in\n * `globalThis.__GLOBAL_LOADING_REMOTE_ENTRY__` (runtime-core never evicts\n * rejections), so retries without a purge await the same failure.\n */\nimport { Duration, Effect, Schedule } from \"effect\";\nimport type { PluginRuntimeError } from \"./runtime/errors\";\nimport {\n classifyPluginFailure,\n deepestErrorStack,\n type PluginFailureClassification,\n toPluginRuntimeError,\n} from \"./runtime/errors\";\n\nconst POLL_INTERVAL_MS = 300;\nconst DEFAULT_TIMEOUT_MS = 120_000;\nconst RETRY_BASE_DELAY_MS = 500;\nconst RETRY_MAX_DELAY_MS = 5_000;\n\nexport const sleep = (ms: number): Promise<void> =>\n new Promise((resolve) => setTimeout(resolve, ms));\n\n/**\n * Deletes the failed remote's keys from the process-global entry-load cache.\n * Deleting a RESOLVED entry would force a wasteful re-eval, so only call\n * this from failure paths.\n */\nexport const purgeRemoteEntryCache = (remoteUrl: string): void => {\n const globalLoading = (globalThis as Record<string, unknown>).__GLOBAL_LOADING_REMOTE_ENTRY__ as\n | Record<string, unknown>\n | undefined;\n if (!globalLoading) return;\n for (const key of Object.keys(globalLoading)) {\n if (key.endsWith(`:${remoteUrl}`)) delete globalLoading[key];\n }\n};\n\nexport const isRemoteEntryBody = (body: string): boolean =>\n !/not found|<(!doctype|html)/i.test(body.slice(0, 64));\n\nexport const waitForRemoteEntryReady = async (\n label: string,\n url: string,\n timeoutMs = DEFAULT_TIMEOUT_MS,\n): Promise<void> => {\n const deadline = Date.now() + timeoutMs;\n let announced = false;\n while (Date.now() < deadline) {\n const res = await fetch(url).catch(() => null);\n if (res?.ok && isRemoteEntryBody(await res.text().catch(() => \"\"))) return;\n if (!announced) {\n announced = true;\n console.log(`⏳ waiting for ${label} to compile (remote entry not ready)…`);\n }\n await sleep(POLL_INTERVAL_MS);\n }\n throw new Error(`${label} remote entry never became ready at ${url}`);\n};\n\nexport interface PluginLoadAttemptInfo {\n attempt: number;\n classification: PluginFailureClassification;\n}\n\nexport interface PluginLoadRetryOptions<T> {\n /** short plugin key for log prefixes (host entry key or plugin id) */\n label: string;\n remoteUrl: string;\n load: () => Promise<T>;\n /** wall-clock budget for the retry loop */\n timeoutMs?: number;\n /**\n * Budget for the readiness poll (cold-compile wait) — defaults to the\n * retry budget, preserving the historical behavior. Pass `0` to skip the\n * poll (useful when the caller stubs `load` and does not need network).\n */\n readinessTimeoutMs?: number;\n /**\n * Observes every failed attempt (including non-retryable ones that end the\n * loop). Defaults to classification-deduped console.error under the\n * `[Plugins]` prefix.\n */\n onAttempt?: ((error: unknown, info: PluginLoadAttemptInfo) => void) | undefined;\n}\n\n/**\n * The one plugin-load retry policy: poll the remote entry until it is actually\n * served, then load with capped exponential backoff — purging the poisoned\n * global entry cache between attempts so each retry genuinely re-fetches.\n *\n * Recovery policy is `classifyPluginFailure().retryable`: transient network\n * conditions retry until the wall-clock budget runs out; permanent failures\n * (MF identity skew, schema validation, dead remotes, TLS verification) fail\n * fast on the first attempt instead of burning the budget silently.\n *\n * Fails with the ORIGINAL error from `load` — the host builds\n * `PluginBootstrapError.cause` from it and classification walks it.\n */\nexport const loadRemoteWithRetry = <T>(\n options: PluginLoadRetryOptions<T>,\n): Effect.Effect<T, PluginRuntimeError> => {\n const {\n label,\n remoteUrl,\n load,\n timeoutMs = DEFAULT_TIMEOUT_MS,\n readinessTimeoutMs,\n onAttempt,\n } = options;\n const readinessTimeout = readinessTimeoutMs ?? timeoutMs;\n\n const schedule = Schedule.exponential(Duration.millis(RETRY_BASE_DELAY_MS)).pipe(\n Schedule.modifyDelay(({ output }) =>\n Effect.succeed(\n Duration.toMillis(output) > RETRY_MAX_DELAY_MS\n ? Duration.millis(RETRY_MAX_DELAY_MS)\n : output,\n ),\n ),\n Schedule.upTo({ duration: Duration.millis(timeoutMs) }),\n );\n\n let attempt = 0;\n let lastSignature: string | undefined;\n const reportFailure = (error: unknown): void => {\n attempt += 1;\n purgeRemoteEntryCache(remoteUrl);\n const classification = classifyPluginFailure(error);\n if (onAttempt) {\n onAttempt(error, { attempt, classification });\n return;\n }\n const signature = `${classification.kind}::${classification.message}`;\n if (signature === lastSignature) return;\n lastSignature = signature;\n // The message alone is rarely enough, and the wrapper's own stack points\n // at the wrapping frames — log the DEEPEST cause's stack (the original\n // throw site inside the evaluated remote entry).\n const stack = deepestErrorStack(error);\n console.error(\n `[Plugins][${label}] ❌ ${classification.kind} failure (attempt ${attempt}): ${classification.message}` +\n (classification.suggestion ? `\\n[Plugins][${label}] → ${classification.suggestion}` : \"\") +\n (stack ? `\\n[Plugins][${label}] ${stack}` : \"\"),\n );\n };\n\n const loadWithRetry = Effect.tryPromise({\n try: load,\n catch: (error) => toPluginRuntimeError(error, label, undefined, \"remote-entry-load\"),\n }).pipe(\n Effect.tapError((error) => Effect.sync(() => reportFailure(error))),\n Effect.retry({ schedule, while: (error) => classifyPluginFailure(error).retryable }),\n );\n\n // readinessTimeoutMs: 0 skips the cold-compile poll (tests stub `load` and\n // must not race a 1ms wall-clock window against the event loop).\n if (readinessTimeout === 0) {\n return loadWithRetry;\n }\n\n return Effect.tryPromise({\n try: () => waitForRemoteEntryReady(label, remoteUrl, readinessTimeout),\n catch: (error) => toPluginRuntimeError(error, label, undefined, \"remote-entry-readiness\"),\n }).pipe(Effect.flatMap(() => loadWithRetry));\n};\n"],"mappings":";;;;;;;;;;;;;;;;AAoBA,MAAM,mBAAmB;AACzB,MAAM,qBAAqB;AAC3B,MAAM,sBAAsB;AAC5B,MAAM,qBAAqB;AAE3B,MAAa,SAAS,OACpB,IAAI,SAAS,YAAY,WAAW,SAAS,EAAE,CAAC;;;;;;AAOlD,MAAa,yBAAyB,cAA4B;CAChE,MAAM,gBAAiB,WAAuC;CAG9D,IAAI,CAAC,eAAe;CACpB,KAAK,MAAM,OAAO,OAAO,KAAK,aAAa,GACzC,IAAI,IAAI,SAAS,IAAI,WAAW,GAAG,OAAO,cAAc;AAE5D;AAEA,MAAa,qBAAqB,SAChC,CAAC,8BAA8B,KAAK,KAAK,MAA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KAAK,oBAAoB,QAAQ,KAAK,eAAe,aAC1F,eAAe,aAAa,eAAe,MAAM,MAAM,eAAe,eAAe,OACrF,QAAQ,eAAe,MAAM,IAAI,UAAU,GAChD;CACF;CAEA,MAAM,gBAAgBF,cAAO,WAAW;EACtC,KAAK;EACL,QAAQ,UAAUG,oCAAqB,OAAO,OAAO,QAAW,mBAAmB;CACrF,CAAC,CAAC,CAAC,KACDH,cAAO,UAAU,UAAUA,cAAO,WAAW,cAAc,KAAK,CAAC,CAAC,GAClEA,cAAO,MAAM;EAAE;EAAU,QAAQ,UAAUC,qCAAsB,KAAK,CAAC,CAAC;CAAU,CAAC,CACrF;CAIA,IAAI,qBAAqB,GACvB,OAAO;CAGT,OAAOD,cAAO,WAAW;EACvB,WAAW,wBAAwB,OAAO,WAAW,gBAAgB;EACrE,QAAQ,UAAUG,oCAAqB,OAAO,OAAO,QAAW,wBAAwB;CAC1F,CAAC,CAAC,CAAC,KAAKH,cAAO,cAAc,aAAa,CAAC;AAC7C"}
1
+ {"version":3,"file":"remote-entry.cjs","names":["Schedule","Duration","Effect","classifyPluginFailure","deepestErrorStack","toPluginRuntimeError"],"sources":["../src/remote-entry.ts"],"sourcesContent":["/**\n * Remote-entry loading resilience — the ONE contract every MF consumer in\n * the dev stack shares (plugin dev serves, the host's plugin loader).\n *\n * Two failure classes it exists for:\n * 1. Cold compile: remoteEntry.js 404s until the remote's first build —\n * the 404 body gets eval'd as JS (\"Unexpected identifier 'Found'\").\n * 2. Watch-rebuild poisoning: a failed entry load is memoized forever in\n * `globalThis.__GLOBAL_LOADING_REMOTE_ENTRY__` (runtime-core never evicts\n * rejections), so retries without a purge await the same failure.\n */\nimport { Duration, Effect, Schedule } from \"effect\";\nimport type { PluginRuntimeError } from \"./runtime/errors\";\nimport {\n classifyPluginFailure,\n deepestErrorStack,\n type PluginFailureClassification,\n toPluginRuntimeError,\n} from \"./runtime/errors\";\n\nconst POLL_INTERVAL_MS = 300;\nconst DEFAULT_TIMEOUT_MS = 120_000;\nconst RETRY_BASE_DELAY_MS = 500;\nconst RETRY_MAX_DELAY_MS = 5_000;\n\nconst sleep = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms));\n\n/**\n * Deletes the failed remote's keys from the process-global entry-load cache.\n * Deleting a RESOLVED entry would force a wasteful re-eval, so only call\n * this from failure paths.\n */\nexport const purgeRemoteEntryCache = (remoteUrl: string): void => {\n const globalLoading = (globalThis as Record<string, unknown>).__GLOBAL_LOADING_REMOTE_ENTRY__ as\n | Record<string, unknown>\n | undefined;\n if (!globalLoading) return;\n for (const key of Object.keys(globalLoading)) {\n if (key.endsWith(`:${remoteUrl}`)) delete globalLoading[key];\n }\n};\n\nexport const isRemoteEntryBody = (body: string): boolean =>\n !/not found|<(!doctype|html)/i.test(body.slice(0, 64));\n\nexport const waitForRemoteEntryReady = async (\n label: string,\n url: string,\n timeoutMs = DEFAULT_TIMEOUT_MS,\n): Promise<void> => {\n const deadline = Date.now() + timeoutMs;\n let announced = false;\n while (Date.now() < deadline) {\n const res = await fetch(url).catch(() => null);\n if (res?.ok && isRemoteEntryBody(await res.text().catch(() => \"\"))) return;\n if (!announced) {\n announced = true;\n console.log(`⏳ waiting for ${label} to compile (remote entry not ready)…`);\n }\n await sleep(POLL_INTERVAL_MS);\n }\n throw new Error(`${label} remote entry never became ready at ${url}`);\n};\n\nexport interface PluginLoadAttemptInfo {\n attempt: number;\n classification: PluginFailureClassification;\n}\n\nexport interface PluginLoadRetryOptions<T> {\n /** short plugin key for log prefixes (host entry key or plugin id) */\n label: string;\n remoteUrl: string;\n load: () => Promise<T>;\n /** wall-clock budget for the retry loop */\n timeoutMs?: number;\n /**\n * Budget for the readiness poll (cold-compile wait) — defaults to the\n * retry budget, preserving the historical behavior. Pass `0` to skip the\n * poll (useful when the caller stubs `load` and does not need network).\n */\n readinessTimeoutMs?: number;\n /**\n * Observes every failed attempt (including non-retryable ones that end the\n * loop). Defaults to classification-deduped console.error under the\n * `[Plugins]` prefix.\n */\n onAttempt?: ((error: unknown, info: PluginLoadAttemptInfo) => void) | undefined;\n}\n\n/**\n * The one plugin-load retry policy: poll the remote entry until it is actually\n * served, then load with capped exponential backoff — purging the poisoned\n * global entry cache between attempts so each retry genuinely re-fetches.\n *\n * Recovery policy is `classifyPluginFailure().retryable`: transient network\n * conditions retry until the wall-clock budget runs out; permanent failures\n * (MF identity skew, schema validation, dead remotes, TLS verification) fail\n * fast on the first attempt instead of burning the budget silently.\n *\n * Fails with the ORIGINAL error from `load` — the host builds\n * `PluginBootstrapError.cause` from it and classification walks it.\n */\nexport const loadRemoteWithRetry = <T>(\n options: PluginLoadRetryOptions<T>,\n): Effect.Effect<T, PluginRuntimeError> => {\n const {\n label,\n remoteUrl,\n load,\n timeoutMs = DEFAULT_TIMEOUT_MS,\n readinessTimeoutMs,\n onAttempt,\n } = options;\n const readinessTimeout = readinessTimeoutMs ?? timeoutMs;\n\n const schedule = Schedule.exponential(Duration.millis(RETRY_BASE_DELAY_MS)).pipe(\n Schedule.modifyDelay(({ output }) =>\n Effect.succeed(\n Duration.toMillis(output) > RETRY_MAX_DELAY_MS\n ? Duration.millis(RETRY_MAX_DELAY_MS)\n : output,\n ),\n ),\n Schedule.upTo({ duration: Duration.millis(timeoutMs) }),\n );\n\n let attempt = 0;\n let lastSignature: string | undefined;\n const reportFailure = (error: unknown): void => {\n attempt += 1;\n purgeRemoteEntryCache(remoteUrl);\n const classification = classifyPluginFailure(error);\n if (onAttempt) {\n onAttempt(error, { attempt, classification });\n return;\n }\n const signature = `${classification.kind}::${classification.message}`;\n if (signature === lastSignature) return;\n lastSignature = signature;\n // The message alone is rarely enough, and the wrapper's own stack points\n // at the wrapping frames — log the DEEPEST cause's stack (the original\n // throw site inside the evaluated remote entry).\n const stack = deepestErrorStack(error);\n console.error(\n `[Plugins][${label}] ❌ ${classification.kind} failure (attempt ${attempt}): ${classification.message}` +\n (classification.suggestion ? `\\n[Plugins][${label}] → ${classification.suggestion}` : \"\") +\n (stack ? `\\n[Plugins][${label}] ${stack}` : \"\"),\n );\n };\n\n const loadWithRetry = Effect.tryPromise({\n try: load,\n catch: (error) => toPluginRuntimeError(error, label, undefined, \"remote-entry-load\"),\n }).pipe(\n Effect.tapError((error) => Effect.sync(() => reportFailure(error))),\n Effect.retry({ schedule, while: (error) => classifyPluginFailure(error).retryable }),\n );\n\n // readinessTimeoutMs: 0 skips the cold-compile poll (tests stub `load` and\n // must not race a 1ms wall-clock window against the event loop).\n if (readinessTimeout === 0) {\n return loadWithRetry;\n }\n\n return Effect.tryPromise({\n try: () => waitForRemoteEntryReady(label, remoteUrl, readinessTimeout),\n catch: (error) => toPluginRuntimeError(error, label, undefined, \"remote-entry-readiness\"),\n }).pipe(Effect.flatMap(() => loadWithRetry));\n};\n"],"mappings":";;;;;;;;;;;;;;;;AAoBA,MAAM,mBAAmB;AACzB,MAAM,qBAAqB;AAC3B,MAAM,sBAAsB;AAC5B,MAAM,qBAAqB;AAE3B,MAAM,SAAS,OAA8B,IAAI,SAAS,YAAY,WAAW,SAAS,EAAE,CAAC;;;;;;AAO7F,MAAa,yBAAyB,cAA4B;CAChE,MAAM,gBAAiB,WAAuC;CAG9D,IAAI,CAAC,eAAe;CACpB,KAAK,MAAM,OAAO,OAAO,KAAK,aAAa,GACzC,IAAI,IAAI,SAAS,IAAI,WAAW,GAAG,OAAO,cAAc;AAE5D;AAEA,MAAa,qBAAqB,SAChC,CAAC,8BAA8B,KAAK,KAAK,MAAM,GAAG,EAAE,CAAC;AAEvD,MAAa,0BAA0B,OACrC,OACA,KACA,YAAY,uBACM;CAClB,MAAM,WAAW,KAAK,IAAI,IAAI;CAC9B,IAAI,YAAY;CAChB,OAAO,KAAK,IAAI,IAAI,UAAU;EAC5B,MAAM,MAAM,MAAM,MAAM,GAAG,CAAC,CAAC,YAAY,IAAI;EAC7C,IAAI,KAAK,MAAM,kBAAkB,MAAM,IAAI,KAAK,CAAC,CAAC,YAAY,EAAE,CAAC,GAAG;EACpE,IAAI,CAAC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O,MAAM;EAAE;EAAU,QAAQ,UAAUC,qCAAsB,KAAK,CAAC,CAAC;CAAU,CAAC,CACrF;CAIA,IAAI,qBAAqB,GACvB,OAAO;CAGT,OAAOD,cAAO,WAAW;EACvB,WAAW,wBAAwB,OAAO,WAAW,gBAAgB;EACrE,QAAQ,UAAUG,oCAAqB,OAAO,OAAO,QAAW,wBAAwB;CAC1F,CAAC,CAAC,CAAC,KAAKH,cAAO,cAAc,aAAa,CAAC;AAC7C"}
@@ -1,7 +1,6 @@
1
1
  import { PluginFailureClassification, PluginRuntimeError } from "./runtime/errors.cjs";
2
2
  import { Effect } from "effect";
3
3
  //#region src/remote-entry.d.ts
4
- declare const sleep: (ms: number) => Promise<void>;
5
4
  /**
6
5
  * Deletes the failed remote's keys from the process-global entry-load cache.
7
6
  * Deleting a RESOLVED entry would force a wasteful re-eval, so only call
@@ -49,5 +48,5 @@ interface PluginLoadRetryOptions<T> {
49
48
  */
50
49
  declare const loadRemoteWithRetry: <T>(options: PluginLoadRetryOptions<T>) => Effect.Effect<T, PluginRuntimeError>;
51
50
  //#endregion
52
- export { PluginLoadAttemptInfo, PluginLoadRetryOptions, isRemoteEntryBody, loadRemoteWithRetry, purgeRemoteEntryCache, sleep, waitForRemoteEntryReady };
51
+ export { PluginLoadAttemptInfo, PluginLoadRetryOptions, isRemoteEntryBody, loadRemoteWithRetry, purgeRemoteEntryCache, waitForRemoteEntryReady };
53
52
  //# sourceMappingURL=remote-entry.d.cts.map
@@ -1 +1 @@
1
- {"version":3,"file":"remote-entry.d.cts","names":[],"sources":["../src/remote-entry.ts"],"mappings":";;;cAyBa,QAAK,eAAiB;;;;;;cAQtB,wBAAqB;cAUrB,oBAAiB;cAGjB,0BAAuB,eACrB,aACF,uBAEV;UAec;EACf;EACA,gBAAgB;;UAGD,uBAAuB;;EAEtC;EACA;EACA,YAAY,QAAQ;;EAEpB;;;;;;EAMA;;;;;;EAMA,cAAc,gBAAgB,MAAM;;;;;;;;;;;;;;;cAgBzB,sBAAuB,GAAC,SAC1B,uBAAuB,OAC/B,OAAO,OAAO,GAAG"}
1
+ {"version":3,"file":"remote-entry.d.cts","names":[],"sources":["../src/remote-entry.ts"],"mappings":";;;;;;;;cAgCa,wBAAqB;cAUrB,oBAAiB;cAGjB,0BAAuB,eACrB,aACF,uBAEV;UAec;EACf;EACA,gBAAgB;;UAGD,uBAAuB;;EAEtC;EACA;EACA,YAAY,QAAQ;;EAEpB;;;;;;EAMA;;;;;;EAMA,cAAc,gBAAgB,MAAM;;;;;;;;;;;;;;;cAgBzB,sBAAuB,GAAC,SAC1B,uBAAuB,OAC/B,OAAO,OAAO,GAAG"}
@@ -1,7 +1,6 @@
1
1
  import { PluginFailureClassification, PluginRuntimeError } from "./runtime/errors.mjs";
2
2
  import { Effect } from "effect";
3
3
  //#region src/remote-entry.d.ts
4
- declare const sleep: (ms: number) => Promise<void>;
5
4
  /**
6
5
  * Deletes the failed remote's keys from the process-global entry-load cache.
7
6
  * Deleting a RESOLVED entry would force a wasteful re-eval, so only call
@@ -49,5 +48,5 @@ interface PluginLoadRetryOptions<T> {
49
48
  */
50
49
  declare const loadRemoteWithRetry: <T>(options: PluginLoadRetryOptions<T>) => Effect.Effect<T, PluginRuntimeError>;
51
50
  //#endregion
52
- export { PluginLoadAttemptInfo, PluginLoadRetryOptions, isRemoteEntryBody, loadRemoteWithRetry, purgeRemoteEntryCache, sleep, waitForRemoteEntryReady };
51
+ export { PluginLoadAttemptInfo, PluginLoadRetryOptions, isRemoteEntryBody, loadRemoteWithRetry, purgeRemoteEntryCache, waitForRemoteEntryReady };
53
52
  //# sourceMappingURL=remote-entry.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"remote-entry.d.mts","names":[],"sources":["../src/remote-entry.ts"],"mappings":";;;cAyBa,QAAK,eAAiB;;;;;;cAQtB,wBAAqB;cAUrB,oBAAiB;cAGjB,0BAAuB,eACrB,aACF,uBAEV;UAec;EACf;EACA,gBAAgB;;UAGD,uBAAuB;;EAEtC;EACA;EACA,YAAY,QAAQ;;EAEpB;;;;;;EAMA;;;;;;EAMA,cAAc,gBAAgB,MAAM;;;;;;;;;;;;;;;cAgBzB,sBAAuB,GAAC,SAC1B,uBAAuB,OAC/B,OAAO,OAAO,GAAG"}
1
+ {"version":3,"file":"remote-entry.d.mts","names":[],"sources":["../src/remote-entry.ts"],"mappings":";;;;;;;;cAgCa,wBAAqB;cAUrB,oBAAiB;cAGjB,0BAAuB,eACrB,aACF,uBAEV;UAec;EACf;EACA,gBAAgB;;UAGD,uBAAuB;;EAEtC;EACA;EACA,YAAY,QAAQ;;EAEpB;;;;;;EAMA;;;;;;EAMA,cAAc,gBAAgB,MAAM;;;;;;;;;;;;;;;cAgBzB,sBAAuB,GAAC,SAC1B,uBAAuB,OAC/B,OAAO,OAAO,GAAG"}
@@ -94,5 +94,5 @@ const loadRemoteWithRetry = (options) => {
94
94
  };
95
95
 
96
96
  //#endregion
97
- export { isRemoteEntryBody, loadRemoteWithRetry, purgeRemoteEntryCache, sleep, waitForRemoteEntryReady };
97
+ export { isRemoteEntryBody, loadRemoteWithRetry, purgeRemoteEntryCache, waitForRemoteEntryReady };
98
98
  //# sourceMappingURL=remote-entry.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"remote-entry.mjs","names":[],"sources":["../src/remote-entry.ts"],"sourcesContent":["/**\n * Remote-entry loading resilience — the ONE contract every MF consumer in\n * the dev stack shares (plugin dev serves, the host's plugin loader).\n *\n * Two failure classes it exists for:\n * 1. Cold compile: remoteEntry.js 404s until the remote's first build —\n * the 404 body gets eval'd as JS (\"Unexpected identifier 'Found'\").\n * 2. Watch-rebuild poisoning: a failed entry load is memoized forever in\n * `globalThis.__GLOBAL_LOADING_REMOTE_ENTRY__` (runtime-core never evicts\n * rejections), so retries without a purge await the same failure.\n */\nimport { Duration, Effect, Schedule } from \"effect\";\nimport type { PluginRuntimeError } from \"./runtime/errors\";\nimport {\n classifyPluginFailure,\n deepestErrorStack,\n type PluginFailureClassification,\n toPluginRuntimeError,\n} from \"./runtime/errors\";\n\nconst POLL_INTERVAL_MS = 300;\nconst DEFAULT_TIMEOUT_MS = 120_000;\nconst RETRY_BASE_DELAY_MS = 500;\nconst RETRY_MAX_DELAY_MS = 5_000;\n\nexport const sleep = (ms: number): Promise<void> =>\n new Promise((resolve) => setTimeout(resolve, ms));\n\n/**\n * Deletes the failed remote's keys from the process-global entry-load cache.\n * Deleting a RESOLVED entry would force a wasteful re-eval, so only call\n * this from failure paths.\n */\nexport const purgeRemoteEntryCache = (remoteUrl: string): void => {\n const globalLoading = (globalThis as Record<string, unknown>).__GLOBAL_LOADING_REMOTE_ENTRY__ as\n | Record<string, unknown>\n | undefined;\n if (!globalLoading) return;\n for (const key of Object.keys(globalLoading)) {\n if (key.endsWith(`:${remoteUrl}`)) delete globalLoading[key];\n }\n};\n\nexport const isRemoteEntryBody = (body: string): boolean =>\n !/not found|<(!doctype|html)/i.test(body.slice(0, 64));\n\nexport const waitForRemoteEntryReady = async (\n label: string,\n url: string,\n timeoutMs = DEFAULT_TIMEOUT_MS,\n): Promise<void> => {\n const deadline = Date.now() + timeoutMs;\n let announced = false;\n while (Date.now() < deadline) {\n const res = await fetch(url).catch(() => null);\n if (res?.ok && isRemoteEntryBody(await res.text().catch(() => \"\"))) return;\n if (!announced) {\n announced = true;\n console.log(`⏳ waiting for ${label} to compile (remote entry not ready)…`);\n }\n await sleep(POLL_INTERVAL_MS);\n }\n throw new Error(`${label} remote entry never became ready at ${url}`);\n};\n\nexport interface PluginLoadAttemptInfo {\n attempt: number;\n classification: PluginFailureClassification;\n}\n\nexport interface PluginLoadRetryOptions<T> {\n /** short plugin key for log prefixes (host entry key or plugin id) */\n label: string;\n remoteUrl: string;\n load: () => Promise<T>;\n /** wall-clock budget for the retry loop */\n timeoutMs?: number;\n /**\n * Budget for the readiness poll (cold-compile wait) — defaults to the\n * retry budget, preserving the historical behavior. Pass `0` to skip the\n * poll (useful when the caller stubs `load` and does not need network).\n */\n readinessTimeoutMs?: number;\n /**\n * Observes every failed attempt (including non-retryable ones that end the\n * loop). Defaults to classification-deduped console.error under the\n * `[Plugins]` prefix.\n */\n onAttempt?: ((error: unknown, info: PluginLoadAttemptInfo) => void) | undefined;\n}\n\n/**\n * The one plugin-load retry policy: poll the remote entry until it is actually\n * served, then load with capped exponential backoff — purging the poisoned\n * global entry cache between attempts so each retry genuinely re-fetches.\n *\n * Recovery policy is `classifyPluginFailure().retryable`: transient network\n * conditions retry until the wall-clock budget runs out; permanent failures\n * (MF identity skew, schema validation, dead remotes, TLS verification) fail\n * fast on the first attempt instead of burning the budget silently.\n *\n * Fails with the ORIGINAL error from `load` — the host builds\n * `PluginBootstrapError.cause` from it and classification walks it.\n */\nexport const loadRemoteWithRetry = <T>(\n options: PluginLoadRetryOptions<T>,\n): Effect.Effect<T, PluginRuntimeError> => {\n const {\n label,\n remoteUrl,\n load,\n timeoutMs = DEFAULT_TIMEOUT_MS,\n readinessTimeoutMs,\n onAttempt,\n } = options;\n const readinessTimeout = readinessTimeoutMs ?? timeoutMs;\n\n const schedule = Schedule.exponential(Duration.millis(RETRY_BASE_DELAY_MS)).pipe(\n Schedule.modifyDelay(({ output }) =>\n Effect.succeed(\n Duration.toMillis(output) > RETRY_MAX_DELAY_MS\n ? Duration.millis(RETRY_MAX_DELAY_MS)\n : output,\n ),\n ),\n Schedule.upTo({ duration: Duration.millis(timeoutMs) }),\n );\n\n let attempt = 0;\n let lastSignature: string | undefined;\n const reportFailure = (error: unknown): void => {\n attempt += 1;\n purgeRemoteEntryCache(remoteUrl);\n const classification = classifyPluginFailure(error);\n if (onAttempt) {\n onAttempt(error, { attempt, classification });\n return;\n }\n const signature = `${classification.kind}::${classification.message}`;\n if (signature === lastSignature) return;\n lastSignature = signature;\n // The message alone is rarely enough, and the wrapper's own stack points\n // at the wrapping frames — log the DEEPEST cause's stack (the original\n // throw site inside the evaluated remote entry).\n const stack = deepestErrorStack(error);\n console.error(\n `[Plugins][${label}] ❌ ${classification.kind} failure (attempt ${attempt}): ${classification.message}` +\n (classification.suggestion ? `\\n[Plugins][${label}] → ${classification.suggestion}` : \"\") +\n (stack ? `\\n[Plugins][${label}] ${stack}` : \"\"),\n );\n };\n\n const loadWithRetry = Effect.tryPromise({\n try: load,\n catch: (error) => toPluginRuntimeError(error, label, undefined, \"remote-entry-load\"),\n }).pipe(\n Effect.tapError((error) => Effect.sync(() => reportFailure(error))),\n Effect.retry({ schedule, while: (error) => classifyPluginFailure(error).retryable }),\n );\n\n // readinessTimeoutMs: 0 skips the cold-compile poll (tests stub `load` and\n // must not race a 1ms wall-clock window against the event loop).\n if (readinessTimeout === 0) {\n return loadWithRetry;\n }\n\n return Effect.tryPromise({\n try: () => waitForRemoteEntryReady(label, remoteUrl, readinessTimeout),\n catch: (error) => toPluginRuntimeError(error, label, undefined, \"remote-entry-readiness\"),\n }).pipe(Effect.flatMap(() => loadWithRetry));\n};\n"],"mappings":";;;;;;;;;;;;;;;AAoBA,MAAM,mBAAmB;AACzB,MAAM,qBAAqB;AAC3B,MAAM,sBAAsB;AAC5B,MAAM,qBAAqB;AAE3B,MAAa,SAAS,OACpB,IAAI,SAAS,YAAY,WAAW,SAAS,EAAE,CAAC;;;;;;AAOlD,MAAa,yBAAyB,cAA4B;CAChE,MAAM,gBAAiB,WAAuC;CAG9D,IAAI,CAAC,eAAe;CACpB,KAAK,MAAM,OAAO,OAAO,KAAK,aAAa,GACzC,IAAI,IAAI,SAAS,IAAI,WAAW,GAAG,OAAO,cAAc;AAE5D;AAEA,MAAa,qBAAqB,SAChC,CAAC,8BAA8B,KAAK,KAAK,MAAM,GAAG,EAAE,CAAC;AAEvD,MAAa,0BAA0B,OACrC,OACA,KACA,YAAY,uBACM;CAClB,MAAM,WAAW,KAAK,IAAI,IAAI;CAC9B,IAAI,YAAY;CAChB,OAAO,KAAK,IAAI,IAAI,UAAU;EAC5B,MAAM,MAAM,MAAM,MAAM,GAAG,CAAC,CAAC,YAAY,IAAI;EAC7C,IAAI,KAAK,M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,UAAU,UAAU,OAAO,WAAW,cAAc,KAAK,CAAC,CAAC,GAClE,OAAO,MAAM;EAAE;EAAU,QAAQ,UAAU,sBAAsB,KAAK,CAAC,CAAC;CAAU,CAAC,CACrF;CAIA,IAAI,qBAAqB,GACvB,OAAO;CAGT,OAAO,OAAO,WAAW;EACvB,WAAW,wBAAwB,OAAO,WAAW,gBAAgB;EACrE,QAAQ,UAAU,qBAAqB,OAAO,OAAO,QAAW,wBAAwB;CAC1F,CAAC,CAAC,CAAC,KAAK,OAAO,cAAc,aAAa,CAAC;AAC7C"}
1
+ {"version":3,"file":"remote-entry.mjs","names":[],"sources":["../src/remote-entry.ts"],"sourcesContent":["/**\n * Remote-entry loading resilience — the ONE contract every MF consumer in\n * the dev stack shares (plugin dev serves, the host's plugin loader).\n *\n * Two failure classes it exists for:\n * 1. Cold compile: remoteEntry.js 404s until the remote's first build —\n * the 404 body gets eval'd as JS (\"Unexpected identifier 'Found'\").\n * 2. Watch-rebuild poisoning: a failed entry load is memoized forever in\n * `globalThis.__GLOBAL_LOADING_REMOTE_ENTRY__` (runtime-core never evicts\n * rejections), so retries without a purge await the same failure.\n */\nimport { Duration, Effect, Schedule } from \"effect\";\nimport type { PluginRuntimeError } from \"./runtime/errors\";\nimport {\n classifyPluginFailure,\n deepestErrorStack,\n type PluginFailureClassification,\n toPluginRuntimeError,\n} from \"./runtime/errors\";\n\nconst POLL_INTERVAL_MS = 300;\nconst DEFAULT_TIMEOUT_MS = 120_000;\nconst RETRY_BASE_DELAY_MS = 500;\nconst RETRY_MAX_DELAY_MS = 5_000;\n\nconst sleep = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms));\n\n/**\n * Deletes the failed remote's keys from the process-global entry-load cache.\n * Deleting a RESOLVED entry would force a wasteful re-eval, so only call\n * this from failure paths.\n */\nexport const purgeRemoteEntryCache = (remoteUrl: string): void => {\n const globalLoading = (globalThis as Record<string, unknown>).__GLOBAL_LOADING_REMOTE_ENTRY__ as\n | Record<string, unknown>\n | undefined;\n if (!globalLoading) return;\n for (const key of Object.keys(globalLoading)) {\n if (key.endsWith(`:${remoteUrl}`)) delete globalLoading[key];\n }\n};\n\nexport const isRemoteEntryBody = (body: string): boolean =>\n !/not found|<(!doctype|html)/i.test(body.slice(0, 64));\n\nexport const waitForRemoteEntryReady = async (\n label: string,\n url: string,\n timeoutMs = DEFAULT_TIMEOUT_MS,\n): Promise<void> => {\n const deadline = Date.now() + timeoutMs;\n let announced = false;\n while (Date.now() < deadline) {\n const res = await fetch(url).catch(() => null);\n if (res?.ok && isRemoteEntryBody(await res.text().catch(() => \"\"))) return;\n if (!announced) {\n announced = true;\n console.log(`⏳ waiting for ${label} to compile (remote entry not ready)…`);\n }\n await sleep(POLL_INTERVAL_MS);\n }\n throw new Error(`${label} remote entry never became ready at ${url}`);\n};\n\nexport interface PluginLoadAttemptInfo {\n attempt: number;\n classification: PluginFailureClassification;\n}\n\nexport interface PluginLoadRetryOptions<T> {\n /** short plugin key for log prefixes (host entry key or plugin id) */\n label: string;\n remoteUrl: string;\n load: () => Promise<T>;\n /** wall-clock budget for the retry loop */\n timeoutMs?: number;\n /**\n * Budget for the readiness poll (cold-compile wait) — defaults to the\n * retry budget, preserving the historical behavior. Pass `0` to skip the\n * poll (useful when the caller stubs `load` and does not need network).\n */\n readinessTimeoutMs?: number;\n /**\n * Observes every failed attempt (including non-retryable ones that end the\n * loop). Defaults to classification-deduped console.error under the\n * `[Plugins]` prefix.\n */\n onAttempt?: ((error: unknown, info: PluginLoadAttemptInfo) => void) | undefined;\n}\n\n/**\n * The one plugin-load retry policy: poll the remote entry until it is actually\n * served, then load with capped exponential backoff — purging the poisoned\n * global entry cache between attempts so each retry genuinely re-fetches.\n *\n * Recovery policy is `classifyPluginFailure().retryable`: transient network\n * conditions retry until the wall-clock budget runs out; permanent failures\n * (MF identity skew, schema validation, dead remotes, TLS verification) fail\n * fast on the first attempt instead of burning the budget silently.\n *\n * Fails with the ORIGINAL error from `load` — the host builds\n * `PluginBootstrapError.cause` from it and classification walks it.\n */\nexport const loadRemoteWithRetry = <T>(\n options: PluginLoadRetryOptions<T>,\n): Effect.Effect<T, PluginRuntimeError> => {\n const {\n label,\n remoteUrl,\n load,\n timeoutMs = DEFAULT_TIMEOUT_MS,\n readinessTimeoutMs,\n onAttempt,\n } = options;\n const readinessTimeout = readinessTimeoutMs ?? timeoutMs;\n\n const schedule = Schedule.exponential(Duration.millis(RETRY_BASE_DELAY_MS)).pipe(\n Schedule.modifyDelay(({ output }) =>\n Effect.succeed(\n Duration.toMillis(output) > RETRY_MAX_DELAY_MS\n ? Duration.millis(RETRY_MAX_DELAY_MS)\n : output,\n ),\n ),\n Schedule.upTo({ duration: Duration.millis(timeoutMs) }),\n );\n\n let attempt = 0;\n let lastSignature: string | undefined;\n const reportFailure = (error: unknown): void => {\n attempt += 1;\n purgeRemoteEntryCache(remoteUrl);\n const classification = classifyPluginFailure(error);\n if (onAttempt) {\n onAttempt(error, { attempt, classification });\n return;\n }\n const signature = `${classification.kind}::${classification.message}`;\n if (signature === lastSignature) return;\n lastSignature = signature;\n // The message alone is rarely enough, and the wrapper's own stack points\n // at the wrapping frames — log the DEEPEST cause's stack (the original\n // throw site inside the evaluated remote entry).\n const stack = deepestErrorStack(error);\n console.error(\n `[Plugins][${label}] ❌ ${classification.kind} failure (attempt ${attempt}): ${classification.message}` +\n (classification.suggestion ? `\\n[Plugins][${label}] → ${classification.suggestion}` : \"\") +\n (stack ? `\\n[Plugins][${label}] ${stack}` : \"\"),\n );\n };\n\n const loadWithRetry = Effect.tryPromise({\n try: load,\n catch: (error) => toPluginRuntimeError(error, label, undefined, \"remote-entry-load\"),\n }).pipe(\n Effect.tapError((error) => Effect.sync(() => reportFailure(error))),\n Effect.retry({ schedule, while: (error) => classifyPluginFailure(error).retryable }),\n );\n\n // readinessTimeoutMs: 0 skips the cold-compile poll (tests stub `load` and\n // must not race a 1ms wall-clock window against the event loop).\n if (readinessTimeout === 0) {\n return loadWithRetry;\n }\n\n return Effect.tryPromise({\n try: () => waitForRemoteEntryReady(label, remoteUrl, readinessTimeout),\n catch: (error) => toPluginRuntimeError(error, label, undefined, \"remote-entry-readiness\"),\n }).pipe(Effect.flatMap(() => loadWithRetry));\n};\n"],"mappings":";;;;;;;;;;;;;;;AAoBA,MAAM,mBAAmB;AACzB,MAAM,qBAAqB;AAC3B,MAAM,sBAAsB;AAC5B,MAAM,qBAAqB;AAE3B,MAAM,SAAS,OAA8B,IAAI,SAAS,YAAY,WAAW,SAAS,EAAE,CAAC;;;;;;AAO7F,MAAa,yBAAyB,cAA4B;CAChE,MAAM,gBAAiB,WAAuC;CAG9D,IAAI,CAAC,eAAe;CACpB,KAAK,MAAM,OAAO,OAAO,KAAK,aAAa,GACzC,IAAI,IAAI,SAAS,IAAI,WAAW,GAAG,OAAO,cAAc;AAE5D;AAEA,MAAa,qBAAqB,SAChC,CAAC,8BAA8B,KAAK,KAAK,MAAM,GAAG,EAAE,CAAC;AAEvD,MAAa,0BAA0B,OACrC,OACA,KACA,YAAY,uBACM;CAClB,MAAM,WAAW,KAAK,IAAI,IAAI;CAC9B,IAAI,YAAY;CAChB,OAAO,KAAK,IAAI,IAAI,UAAU;EAC5B,MAAM,MAAM,MAAM,MAAM,GAAG,CAAC,CAAC,YAAY,IAAI;EAC7C,IAAI,KAAK,MAAM,kBAAkB,MAAM,IAAI,KAAK,CAAC,CAAC,YAAY,EAAE,CAAC,GAAG;EACpE,IAAI,CAAC,WAAW;GACd,YAAY;GACZ,QAAQ,IAAI,iBAAiB,MAAM,sCAAsC;EAC3E;EACA,MAAM,MAAM,gBAAgB;CAC9B;CACA,MAAM,IAAI,MAAM,GAAG,MAAM,sCAAsC,KAAK;AACtE;;;;;;;;;;;;;;AAyCA,MAAa,uBACX,YACyC;CACzC,MAAM,EACJ,OACA,WACA,MACA,YAAY,oBACZ,oBACA,cACE;CACJ,MAAM,mBAAmB,sBAAsB;CAE/C,MAAM,WAAW,SAAS,YAAY,SAAS,OAAO,m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3
  let node_fs = require("node:fs");
4
4
 
5
5
  //#region src/runtime/mf-config.ts
6
- const PLUGIN_VERSION = "3.0.0-rc.4";
6
+ const PLUGIN_VERSION = "3.0.0-rc.6";
7
7
  const MF_CORE_SHARED_DEPS = require_shared_deps_spec.buildMfCoreSharedDependencies({ ownVersion: PLUGIN_VERSION });
8
8
 
9
9
  //#endregion
@@ -2,7 +2,7 @@ import { buildMfCoreSharedDependencies } from "../shared-deps-spec.mjs";
2
2
  import { readFileSync } from "node:fs";
3
3
 
4
4
  //#region src/runtime/mf-config.ts
5
- const PLUGIN_VERSION = "3.0.0-rc.4";
5
+ const PLUGIN_VERSION = "3.0.0-rc.6";
6
6
  const MF_CORE_SHARED_DEPS = buildMfCoreSharedDependencies({ ownVersion: PLUGIN_VERSION });
7
7
 
8
8
  //#endregion
@@ -36,7 +36,19 @@ const WorkspaceVersionManifestSchema = zod.z.object({
36
36
  * it and skip re-uploading unchanged files; readers that predate the field
37
37
  * ignore it (zod strips unknown keys). Participates in the version hash.
38
38
  */
39
- files: zod.z.record(zod.z.string(), SRI).optional()
39
+ files: zod.z.record(zod.z.string(), SRI).optional(),
40
+ /**
41
+ * Source archive of the workspace subtree (object path → served-object SRI)
42
+ * published beside the dists when the runtime opts in via
43
+ * `publish.sourcePublish` — lets `bos import` dereference a published
44
+ * config slot to the exact source bytes that build came from, with no
45
+ * GitHub dependency. Readers that predate the field ignore it (zod strips
46
+ * unknown keys). Participates in the version hash.
47
+ */
48
+ source: zod.z.object({
49
+ file: zod.z.string().min(1),
50
+ integrity: SRI
51
+ }).optional()
40
52
  });
41
53
  /**
42
54
  * Compose the manifest with its `version` derived from the canonical content
@@ -1 +1 @@
1
- {"version":3,"file":"version-manifest.cjs","names":["z","createHash"],"sources":["../src/version-manifest.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\nimport { z } from \"zod\";\n\n/**\n * WorkspaceVersionManifest — the immutable per-deploy document at\n * `bundles/<account>/<gateway>/<workspace>/versions/<version>.json`\n * (ADR 0020, as amended; atomic-deploys MAP decision 1). The published\n * config's slot pins this document via its `pin` (`manifest` + the\n * manifest's own SRI); every artifact coordinate lives here, so the config\n * stops growing with artifact kinds and old versions stay fully servable.\n */\n\nconst SRI = z.string().regex(/^sha384-[A-Za-z0-9+/=]+$/);\n\nexport const WorkspaceVersionManifestSchema = z.object({\n version: z.string().regex(/^[0-9a-f]{16}$/),\n builtAt: z.string().optional(),\n gitSha: z.string().optional(),\n entry: z.string().min(1),\n entryIntegrity: SRI,\n ssr: z\n .object({\n entry: z.string().min(1),\n integrity: SRI,\n })\n .optional(),\n browserManifest: z\n .object({\n file: z.string().min(1),\n integrity: SRI,\n })\n .optional(),\n /** extra assets (css, icons) — logical name → served-object SRI */\n assets: z.record(z.string(), SRI).optional(),\n /** shared-dependency versions this build was built against */\n shared: z.record(z.string(), z.string()).optional(),\n /**\n * Full per-file digest map of the dist (object path → served-object SRI).\n * Written by `every-plugin`-based deploys so the next deploy can diff against\n * it and skip re-uploading unchanged files; readers that predate the field\n * ignore it (zod strips unknown keys). Participates in the version hash.\n */\n files: z.record(z.string(), SRI).optional(),\n});\nexport type WorkspaceVersionManifest = z.infer<typeof WorkspaceVersionManifestSchema>;\n\nexport interface VersionManifestInput {\n /** Omit: a per-build timestamp makes the same version id map to different\n * manifest bytes per machine, breaking the pin's SRI against the image's\n * staged copy and the CDN's immutability for republished versions. */\n builtAt?: string;\n gitSha?: string;\n entry: string;\n entryIntegrity: string;\n ssr?: { entry: string; integrity: string };\n browserManifest?: { file: string; integrity: string };\n assets?: Record<string, string>;\n shared?: Record<string, string>;\n files?: Record<string, string>;\n}\n\n/**\n * Compose the manifest with its `version` derived from the canonical content\n * of the artifact coordinates alone (key-sorted, `builtAt` excluded) —\n * identical bytes → identical version id regardless of when they were built,\n * so republishing unchanged content is a pointer no-op. Any changed\n * coordinate → a new version (and a new file).\n */\nexport function composeVersionManifest(input: VersionManifestInput): WorkspaceVersionManifest {\n const { builtAt: _builtAt, ...hashedInputs } = input;\n const version = createHash(\"sha256\")\n .update(stableStringify(hashedInputs))\n .digest(\"hex\")\n .slice(0, 16);\n return WorkspaceVersionManifestSchema.parse({ ...input, version });\n}\n\nfunction stableStringify(value: unknown): string {\n if (Array.isArray(value)) return `[${value.map(stableStringify).join(\",\")}]`;\n if (value && typeof value === \"object\") {\n return `{${Object.entries(value)\n .filter(([, v]) => v !== undefined)\n .map(([k, v]) => `${JSON.stringify(k)}:${stableStringify(v)}`)\n .sort()\n .join(\",\")}}`;\n }\n return JSON.stringify(value) ?? \"null\";\n}\n"],"mappings":";;;;;;;;;;;;;AAYA,MAAM,MAAMA,MAAE,OAAO,CAAC,CAAC,MAAM,0BAA0B;AAEvD,MAAa,iCAAiCA,MAAE,OAAO;CACrD,SAASA,MAAE,OAAO,CAAC,CAAC,MAAM,gBAAgB;CAC1C,SAASA,MAAE,OAAO,CAAC,CAAC,SAAS;CAC7B,QAAQA,MAAE,OAAO,CAAC,CAAC,SAAS;CAC5B,OAAOA,MAAE,OAAO,CAAC,CAAC,IAAI,CAAC;CACvB,gBAAgB;CAChB,KAAKA,MACF,OAAO;EACN,OAAOA,MAAE,OAAO,CAAC,CAAC,IAAI,CAAC;EACvB,WAAW;CACb,CAAC,CAAC,CACD,SAAS;CACZ,iBAAiBA,MACd,OAAO;EACN,MAAMA,MAAE,OAAO,CAAC,CAAC,IAAI,CAAC;EACtB,WAAW;CACb,CAAC,CAAC,CACD,SAAS;;CAEZ,QAAQA,MAAE,OAAOA,MAAE,OAAO,GAAG,GAAG,CAAC,CAAC,SAAS;;CAE3C,QAAQA,MAAE,OAAOA,MAAE,OAAO,GAAGA,MAAE,OAAO,CAAC,CAAC,CAAC,SAAS;;;;;;;CAOlD,OAAOA,MAAE,OAAOA,MAAE,OAAO,GAAG,GAAG,CAAC,CAAC,SAAS;AAC5C,CAAC;;;;;;;;AAyBD,SAAgB,uBAAuB,OAAuD;CAC5F,MAAM,EAAE,SAAS,UAAU,GAAG,iBAAiB;CAC/C,MAAM,cAAUC,wBAAW,QAAQ,CAAC,CACjC,OAAO,gBAAgB,YAAY,CAAC,CAAC,CACrC,OAAO,KAAK,CAAC,CACb,MAAM,GAAG,EAAE;CACd,OAAO,+BAA+B,MAAM;EAAE,GAAG;EAAO;CAAQ,CAAC;AACnE;AAEA,SAAS,gBAAgB,OAAwB;CAC/C,IAAI,MAAM,QAAQ,KAAK,GAAG,OAAO,IAAI,MAAM,IAAI,eAAe,CAAC,CAAC,KAAK,GAAG,EAAE;CAC1E,IAAI,SAAS,OAAO,UAAU,UAC5B,OAAO,IAAI,OAAO,QAAQ,KAAK,CAAC,CAC7B,QAAQ,GAAG,OAAO,MAAM,MAAS,CAAC,CAClC,KAAK,CAAC,GAAG,OAAO,GAAG,KAAK,UAAU,CAAC,EAAE,GAAG,gBAAgB,CAAC,GAAG,CAAC,CAC7D,KAAK,CAAC,CACN,KAAK,GAAG,EAAE;CAEf,OAAO,KAAK,UAAU,KAAK,KAAK;AAClC"}
1
+ {"version":3,"file":"version-manifest.cjs","names":["z","createHash"],"sources":["../src/version-manifest.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\nimport { z } from \"zod\";\n\n/**\n * WorkspaceVersionManifest — the immutable per-deploy document at\n * `bundles/<account>/<gateway>/<workspace>/versions/<version>.json`\n * (ADR 0020, as amended; atomic-deploys MAP decision 1). The published\n * config's slot pins this document via its `pin` (`manifest` + the\n * manifest's own SRI); every artifact coordinate lives here, so the config\n * stops growing with artifact kinds and old versions stay fully servable.\n */\n\nconst SRI = z.string().regex(/^sha384-[A-Za-z0-9+/=]+$/);\n\nexport const WorkspaceVersionManifestSchema = z.object({\n version: z.string().regex(/^[0-9a-f]{16}$/),\n builtAt: z.string().optional(),\n gitSha: z.string().optional(),\n entry: z.string().min(1),\n entryIntegrity: SRI,\n ssr: z\n .object({\n entry: z.string().min(1),\n integrity: SRI,\n })\n .optional(),\n browserManifest: z\n .object({\n file: z.string().min(1),\n integrity: SRI,\n })\n .optional(),\n /** extra assets (css, icons) — logical name → served-object SRI */\n assets: z.record(z.string(), SRI).optional(),\n /** shared-dependency versions this build was built against */\n shared: z.record(z.string(), z.string()).optional(),\n /**\n * Full per-file digest map of the dist (object path → served-object SRI).\n * Written by `every-plugin`-based deploys so the next deploy can diff against\n * it and skip re-uploading unchanged files; readers that predate the field\n * ignore it (zod strips unknown keys). Participates in the version hash.\n */\n files: z.record(z.string(), SRI).optional(),\n /**\n * Source archive of the workspace subtree (object path → served-object SRI)\n * published beside the dists when the runtime opts in via\n * `publish.sourcePublish` — lets `bos import` dereference a published\n * config slot to the exact source bytes that build came from, with no\n * GitHub dependency. Readers that predate the field ignore it (zod strips\n * unknown keys). Participates in the version hash.\n */\n source: z\n .object({\n file: z.string().min(1),\n integrity: SRI,\n })\n .optional(),\n});\nexport type WorkspaceVersionManifest = z.infer<typeof WorkspaceVersionManifestSchema>;\n\n/** A published-artifact coordinate: object path within the bundle namespace + its served SRI. */\nexport type SourceRef = NonNullable<WorkspaceVersionManifest[\"source\"]>;\n\nexport interface VersionManifestInput {\n /** Omit: a per-build timestamp makes the same version id map to different\n * manifest bytes per machine, breaking the pin's SRI against the image's\n * staged copy and the CDN's immutability for republished versions. */\n builtAt?: string;\n gitSha?: string;\n entry: string;\n entryIntegrity: string;\n ssr?: { entry: string; integrity: string };\n browserManifest?: { file: string; integrity: string };\n assets?: Record<string, string>;\n shared?: Record<string, string>;\n files?: Record<string, string>;\n source?: { file: string; integrity: string };\n}\n\n/**\n * Compose the manifest with its `version` derived from the canonical content\n * of the artifact coordinates alone (key-sorted, `builtAt` excluded) —\n * identical bytes → identical version id regardless of when they were built,\n * so republishing unchanged content is a pointer no-op. Any changed\n * coordinate → a new version (and a new file).\n */\nexport function composeVersionManifest(input: VersionManifestInput): WorkspaceVersionManifest {\n const { builtAt: _builtAt, ...hashedInputs } = input;\n const version = createHash(\"sha256\")\n .update(stableStringify(hashedInputs))\n .digest(\"hex\")\n .slice(0, 16);\n return WorkspaceVersionManifestSchema.parse({ ...input, version });\n}\n\nfunction stableStringify(value: unknown): string {\n if (Array.isArray(value)) return `[${value.map(stableStringify).join(\",\")}]`;\n if (value && typeof value === \"object\") {\n return `{${Object.entries(value)\n .filter(([, v]) => v !== undefined)\n .map(([k, v]) => `${JSON.stringify(k)}:${stableStringify(v)}`)\n .sort()\n .join(\",\")}}`;\n }\n return JSON.stringify(value) ?? \"null\";\n}\n"],"mappings":";;;;;;;;;;;;;AAYA,MAAM,MAAMA,MAAE,OAAO,CAAC,CAAC,MAAM,0BAA0B;AAEvD,MAAa,iCAAiCA,MAAE,OAAO;CACrD,SAASA,MAAE,OAAO,CAAC,CAAC,MAAM,gBAAgB;CAC1C,SAASA,MAAE,OAAO,CAAC,CAAC,SAAS;CAC7B,QAAQA,MAAE,OAAO,CAAC,CAAC,SAAS;CAC5B,OAAOA,MAAE,OAAO,CAAC,CAAC,IAAI,CAAC;CACvB,gBAAgB;CAChB,KAAKA,MACF,OAAO;EACN,OAAOA,MAAE,OAAO,CAAC,CAAC,IAAI,CAAC;EACvB,WAAW;CACb,CAAC,CAAC,CACD,SAAS;CACZ,iBAAiBA,MACd,OAAO;EACN,MAAMA,MAAE,OAAO,CAAC,CAAC,IAAI,CAAC;EACtB,WAAW;CACb,CAAC,CAAC,CACD,SAAS;;CAEZ,QAAQA,MAAE,OAAOA,MAAE,OAAO,GAAG,GAAG,CAAC,CAAC,SAAS;;CAE3C,QAAQA,MAAE,OAAOA,MAAE,OAAO,GAAGA,MAAE,OAAO,CAAC,CAAC,CAAC,SAAS;;;;;;;CAOlD,OAAOA,MAAE,OAAOA,MAAE,OAAO,GAAG,GAAG,CAAC,CAAC,SAAS;;;;;;;;;CAS1C,QAAQA,MACL,OAAO;EACN,MAAMA,MAAE,OAAO,CAAC,CAAC,IAAI,CAAC;EACtB,WAAW;CACb,CAAC,CAAC,CACD,SAAS;AACd,CAAC;;;;;;;;AA6BD,SAAgB,uBAAuB,OAAuD;CAC5F,MAAM,EAAE,SAAS,UAAU,GAAG,iBAAiB;CAC/C,MAAM,cAAUC,wBAAW,QAAQ,CAAC,CACjC,OAAO,gBAAgB,YAAY,CAAC,CAAC,CACrC,OAAO,KAAK,CAAC,CACb,MAAM,GAAG,EAAE;CACd,OAAO,+BAA+B,MAAM;EAAE,GAAG;EAAO;CAAQ,CAAC;AACnE;AAEA,SAAS,gBAAgB,OAAwB;CAC/C,IAAI,MAAM,QAAQ,KAAK,GAAG,OAAO,IAAI,MAAM,IAAI,eAAe,CAAC,CAAC,KAAK,GAAG,EAAE;CAC1E,IAAI,SAAS,OAAO,UAAU,UAC5B,OAAO,IAAI,OAAO,QAAQ,KAAK,CAAC,CAC7B,QAAQ,GAAG,OAAO,MAAM,MAAS,CAAC,CAClC,KAAK,CAAC,GAAG,OAAO,GAAG,KAAK,UAAU,CAAC,EAAE,GAAG,gBAAgB,CAAC,GAAG,CAAC,CAC7D,KAAK,CAAC,CACN,KAAK,GAAG,EAAE;CAEf,OAAO,KAAK,UAAU,KAAK,KAAK;AAClC"}
@@ -17,8 +17,14 @@ declare const WorkspaceVersionManifestSchema: z.ZodObject<{
17
17
  assets: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
18
18
  shared: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
19
19
  files: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
20
+ source: z.ZodOptional<z.ZodObject<{
21
+ file: z.ZodString;
22
+ integrity: z.ZodString;
23
+ }, z.core.$strip>>;
20
24
  }, z.core.$strip>;
21
25
  type WorkspaceVersionManifest = z.infer<typeof WorkspaceVersionManifestSchema>;
26
+ /** A published-artifact coordinate: object path within the bundle namespace + its served SRI. */
27
+ type SourceRef = NonNullable<WorkspaceVersionManifest["source"]>;
22
28
  interface VersionManifestInput {
23
29
  /** Omit: a per-build timestamp makes the same version id map to different
24
30
  * manifest bytes per machine, breaking the pin's SRI against the image's
@@ -38,6 +44,10 @@ interface VersionManifestInput {
38
44
  assets?: Record<string, string>;
39
45
  shared?: Record<string, string>;
40
46
  files?: Record<string, string>;
47
+ source?: {
48
+ file: string;
49
+ integrity: string;
50
+ };
41
51
  }
42
52
  /**
43
53
  * Compose the manifest with its `version` derived from the canonical content
@@ -48,5 +58,5 @@ interface VersionManifestInput {
48
58
  */
49
59
  declare function composeVersionManifest(input: VersionManifestInput): WorkspaceVersionManifest;
50
60
  //#endregion
51
- export { VersionManifestInput, WorkspaceVersionManifest, WorkspaceVersionManifestSchema, composeVersionManifest };
61
+ export { SourceRef, VersionManifestInput, WorkspaceVersionManifest, WorkspaceVersionManifestSchema, composeVersionManifest };
52
62
  //# sourceMappingURL=version-manifest.d.cts.map
@@ -1 +1 @@
1
- {"version":3,"file":"version-manifest.d.cts","names":[],"sources":["../src/version-manifest.ts"],"mappings":";;cAca,gCAA8B,EAAA;;;;;;;;;;;;;;;;;GA6BzC,EAAA,KAAA;KACU,2BAA2B,EAAE,aAAa;UAErC;;;;EAIf;EACA;EACA;EACA;EACA;IAAQ;IAAe;;EACvB;IAAoB;IAAc;;EAClC,SAAS;EACT,SAAS;EACT,QAAQ;;;;;;;;;iBAUM,uBAAuB,OAAO,uBAAuB"}
1
+ {"version":3,"file":"version-manifest.d.cts","names":[],"sources":["../src/version-manifest.ts"],"mappings":";;cAca,gCAA8B,EAAA;;;;;;;;;;;;;;;;;;;;;GA2CzC,EAAA,KAAA;KACU,2BAA2B,EAAE,aAAa;;KAG1C,YAAY,YAAY;UAEnB;;;;EAIf;EACA;EACA;EACA;EACA;IAAQ;IAAe;;EACvB;IAAoB;IAAc;;EAClC,SAAS;EACT,SAAS;EACT,QAAQ;EACR;IAAW;IAAc;;;;;;;;;;iBAUX,uBAAuB,OAAO,uBAAuB"}
@@ -17,8 +17,14 @@ declare const WorkspaceVersionManifestSchema: z.ZodObject<{
17
17
  assets: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
18
18
  shared: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
19
19
  files: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
20
+ source: z.ZodOptional<z.ZodObject<{
21
+ file: z.ZodString;
22
+ integrity: z.ZodString;
23
+ }, z.core.$strip>>;
20
24
  }, z.core.$strip>;
21
25
  type WorkspaceVersionManifest = z.infer<typeof WorkspaceVersionManifestSchema>;
26
+ /** A published-artifact coordinate: object path within the bundle namespace + its served SRI. */
27
+ type SourceRef = NonNullable<WorkspaceVersionManifest["source"]>;
22
28
  interface VersionManifestInput {
23
29
  /** Omit: a per-build timestamp makes the same version id map to different
24
30
  * manifest bytes per machine, breaking the pin's SRI against the image's
@@ -38,6 +44,10 @@ interface VersionManifestInput {
38
44
  assets?: Record<string, string>;
39
45
  shared?: Record<string, string>;
40
46
  files?: Record<string, string>;
47
+ source?: {
48
+ file: string;
49
+ integrity: string;
50
+ };
41
51
  }
42
52
  /**
43
53
  * Compose the manifest with its `version` derived from the canonical content
@@ -48,5 +58,5 @@ interface VersionManifestInput {
48
58
  */
49
59
  declare function composeVersionManifest(input: VersionManifestInput): WorkspaceVersionManifest;
50
60
  //#endregion
51
- export { VersionManifestInput, WorkspaceVersionManifest, WorkspaceVersionManifestSchema, composeVersionManifest };
61
+ export { SourceRef, VersionManifestInput, WorkspaceVersionManifest, WorkspaceVersionManifestSchema, composeVersionManifest };
52
62
  //# sourceMappingURL=version-manifest.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"version-manifest.d.mts","names":[],"sources":["../src/version-manifest.ts"],"mappings":";;cAca,gCAA8B,EAAA;;;;;;;;;;;;;;;;;GA6BzC,EAAA,KAAA;KACU,2BAA2B,EAAE,aAAa;UAErC;;;;EAIf;EACA;EACA;EACA;EACA;IAAQ;IAAe;;EACvB;IAAoB;IAAc;;EAClC,SAAS;EACT,SAAS;EACT,QAAQ;;;;;;;;;iBAUM,uBAAuB,OAAO,uBAAuB"}
1
+ {"version":3,"file":"version-manifest.d.mts","names":[],"sources":["../src/version-manifest.ts"],"mappings":";;cAca,gCAA8B,EAAA;;;;;;;;;;;;;;;;;;;;;GA2CzC,EAAA,KAAA;KACU,2BAA2B,EAAE,aAAa;;KAG1C,YAAY,YAAY;UAEnB;;;;EAIf;EACA;EACA;EACA;EACA;IAAQ;IAAe;;EACvB;IAAoB;IAAc;;EAClC,SAAS;EACT,SAAS;EACT,QAAQ;EACR;IAAW;IAAc;;;;;;;;;;iBAUX,uBAAuB,OAAO,uBAAuB"}
@@ -35,7 +35,19 @@ const WorkspaceVersionManifestSchema = z.object({
35
35
  * it and skip re-uploading unchanged files; readers that predate the field
36
36
  * ignore it (zod strips unknown keys). Participates in the version hash.
37
37
  */
38
- files: z.record(z.string(), SRI).optional()
38
+ files: z.record(z.string(), SRI).optional(),
39
+ /**
40
+ * Source archive of the workspace subtree (object path → served-object SRI)
41
+ * published beside the dists when the runtime opts in via
42
+ * `publish.sourcePublish` — lets `bos import` dereference a published
43
+ * config slot to the exact source bytes that build came from, with no
44
+ * GitHub dependency. Readers that predate the field ignore it (zod strips
45
+ * unknown keys). Participates in the version hash.
46
+ */
47
+ source: z.object({
48
+ file: z.string().min(1),
49
+ integrity: SRI
50
+ }).optional()
39
51
  });
40
52
  /**
41
53
  * Compose the manifest with its `version` derived from the canonical content
@@ -1 +1 @@
1
- {"version":3,"file":"version-manifest.mjs","names":[],"sources":["../src/version-manifest.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\nimport { z } from \"zod\";\n\n/**\n * WorkspaceVersionManifest — the immutable per-deploy document at\n * `bundles/<account>/<gateway>/<workspace>/versions/<version>.json`\n * (ADR 0020, as amended; atomic-deploys MAP decision 1). The published\n * config's slot pins this document via its `pin` (`manifest` + the\n * manifest's own SRI); every artifact coordinate lives here, so the config\n * stops growing with artifact kinds and old versions stay fully servable.\n */\n\nconst SRI = z.string().regex(/^sha384-[A-Za-z0-9+/=]+$/);\n\nexport const WorkspaceVersionManifestSchema = z.object({\n version: z.string().regex(/^[0-9a-f]{16}$/),\n builtAt: z.string().optional(),\n gitSha: z.string().optional(),\n entry: z.string().min(1),\n entryIntegrity: SRI,\n ssr: z\n .object({\n entry: z.string().min(1),\n integrity: SRI,\n })\n .optional(),\n browserManifest: z\n .object({\n file: z.string().min(1),\n integrity: SRI,\n })\n .optional(),\n /** extra assets (css, icons) — logical name → served-object SRI */\n assets: z.record(z.string(), SRI).optional(),\n /** shared-dependency versions this build was built against */\n shared: z.record(z.string(), z.string()).optional(),\n /**\n * Full per-file digest map of the dist (object path → served-object SRI).\n * Written by `every-plugin`-based deploys so the next deploy can diff against\n * it and skip re-uploading unchanged files; readers that predate the field\n * ignore it (zod strips unknown keys). Participates in the version hash.\n */\n files: z.record(z.string(), SRI).optional(),\n});\nexport type WorkspaceVersionManifest = z.infer<typeof WorkspaceVersionManifestSchema>;\n\nexport interface VersionManifestInput {\n /** Omit: a per-build timestamp makes the same version id map to different\n * manifest bytes per machine, breaking the pin's SRI against the image's\n * staged copy and the CDN's immutability for republished versions. */\n builtAt?: string;\n gitSha?: string;\n entry: string;\n entryIntegrity: string;\n ssr?: { entry: string; integrity: string };\n browserManifest?: { file: string; integrity: string };\n assets?: Record<string, string>;\n shared?: Record<string, string>;\n files?: Record<string, string>;\n}\n\n/**\n * Compose the manifest with its `version` derived from the canonical content\n * of the artifact coordinates alone (key-sorted, `builtAt` excluded) —\n * identical bytes → identical version id regardless of when they were built,\n * so republishing unchanged content is a pointer no-op. Any changed\n * coordinate → a new version (and a new file).\n */\nexport function composeVersionManifest(input: VersionManifestInput): WorkspaceVersionManifest {\n const { builtAt: _builtAt, ...hashedInputs } = input;\n const version = createHash(\"sha256\")\n .update(stableStringify(hashedInputs))\n .digest(\"hex\")\n .slice(0, 16);\n return WorkspaceVersionManifestSchema.parse({ ...input, version });\n}\n\nfunction stableStringify(value: unknown): string {\n if (Array.isArray(value)) return `[${value.map(stableStringify).join(\",\")}]`;\n if (value && typeof value === \"object\") {\n return `{${Object.entries(value)\n .filter(([, v]) => v !== undefined)\n .map(([k, v]) => `${JSON.stringify(k)}:${stableStringify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EAAE;CAC1E,IAAI,SAAS,OAAO,UAAU,UAC5B,OAAO,IAAI,OAAO,QAAQ,KAAK,CAAC,CAC7B,QAAQ,GAAG,OAAO,MAAM,MAAS,CAAC,CAClC,KAAK,CAAC,GAAG,OAAO,GAAG,KAAK,UAAU,CAAC,EAAE,GAAG,gBAAgB,CAAC,GAAG,CAAC,CAC7D,KAAK,CAAC,CACN,KAAK,GAAG,EAAE;CAEf,OAAO,KAAK,UAAU,KAAK,KAAK;AAClC"}
1
+ {"version":3,"file":"version-manifest.mjs","names":[],"sources":["../src/version-manifest.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\nimport { z } from \"zod\";\n\n/**\n * WorkspaceVersionManifest — the immutable per-deploy document at\n * `bundles/<account>/<gateway>/<workspace>/versions/<version>.json`\n * (ADR 0020, as amended; atomic-deploys MAP decision 1). The published\n * config's slot pins this document via its `pin` (`manifest` + the\n * manifest's own SRI); every artifact coordinate lives here, so the config\n * stops growing with artifact kinds and old versions stay fully servable.\n */\n\nconst SRI = z.string().regex(/^sha384-[A-Za-z0-9+/=]+$/);\n\nexport const WorkspaceVersionManifestSchema = z.object({\n version: z.string().regex(/^[0-9a-f]{16}$/),\n builtAt: z.string().optional(),\n gitSha: z.string().optional(),\n entry: z.string().min(1),\n entryIntegrity: SRI,\n ssr: z\n .object({\n entry: z.string().min(1),\n integrity: SRI,\n })\n .optional(),\n browserManifest: z\n .object({\n file: z.string().min(1),\n integrity: SRI,\n })\n .optional(),\n /** extra assets (css, icons) — logical name → served-object SRI */\n assets: z.record(z.string(), SRI).optional(),\n /** shared-dependency versions this build was built against */\n shared: z.record(z.string(), z.string()).optional(),\n /**\n * Full per-file digest map of the dist (object path → served-object SRI).\n * Written by `every-plugin`-based deploys so the next deploy can diff against\n * it and skip re-uploading unchanged files; readers that predate the field\n * ignore it (zod strips unknown keys). Participates in the version hash.\n */\n files: z.record(z.string(), SRI).optional(),\n /**\n * Source archive of the workspace subtree (object path → served-object SRI)\n * published beside the dists when the runtime opts in via\n * `publish.sourcePublish` — lets `bos import` dereference a published\n * config slot to the exact source bytes that build came from, with no\n * GitHub dependency. Readers that predate the field ignore it (zod strips\n * unknown keys). Participates in the version hash.\n */\n source: z\n .object({\n file: z.string().min(1),\n integrity: SRI,\n })\n .optional(),\n});\nexport type WorkspaceVersionManifest = z.infer<typeof WorkspaceVersionManifestSchema>;\n\n/** A published-artifact coordinate: object path within the bundle namespace + its served SRI. */\nexport type SourceRef = NonNullable<WorkspaceVersionManifest[\"source\"]>;\n\nexport interface VersionManifestInput {\n /** Omit: a per-build timestamp makes the same version id map to different\n * manifest bytes per machine, breaking the pin's SRI against the image's\n * staged copy and the CDN's immutability for republished versions. */\n builtAt?: string;\n gitSha?: string;\n entry: string;\n entryIntegrity: string;\n ssr?: { entry: string; integrity: string };\n browserManifest?: { file: string; integrity: string };\n assets?: Record<string, string>;\n shared?: Record<string, string>;\n files?: Record<string, string>;\n source?: { file: string; integrity: string };\n}\n\n/**\n * Compose the manifest with its `version` derived from the canonical content\n * of the artifact coordinates alone (key-sorted, `builtAt` excluded) —\n * identical bytes → identical version id regardless of when they were built,\n * so republishing unchanged content is a pointer no-op. Any changed\n * coordinate → a new version (and a new file).\n */\nexport function composeVersionManifest(input: VersionManifestInput): WorkspaceVersionManifest {\n const { builtAt: _builtAt, ...hashedInputs } = input;\n const version = createHash(\"sha256\")\n .update(stableStringify(hashedInputs))\n .digest(\"hex\")\n .slice(0, 16);\n return WorkspaceVersionManifestSchema.parse({ ...input, version });\n}\n\nfunction stableStringify(value: unknown): string {\n if (Array.isArray(value)) return `[${value.map(stableStringify).join(\",\")}]`;\n if (value && typeof value === \"object\") {\n return `{${Object.entries(value)\n .filter(([, v]) => v !== undefined)\n .map(([k, v]) => `${JSON.stringify(k)}:${stableStringify(v)}`)\n .sort()\n .join(\",\")}}`;\n }\n return JSON.stringify(value) ?? \"null\";\n}\n"],"mappings":";;;;;;;;;;;;AAYA,MAAM,MAAM,EAAE,OAAO,CAAC,CAA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C1E,IAAI,SAAS,OAAO,UAAU,UAC5B,OAAO,IAAI,OAAO,QAAQ,KAAK,CAAC,CAC7B,QAAQ,GAAG,OAAO,MAAM,MAAS,CAAC,CAClC,KAAK,CAAC,GAAG,OAAO,GAAG,KAAK,UAAU,CAAC,EAAE,GAAG,gBAAgB,CAAC,GAAG,CAAC,CAC7D,KAAK,CAAC,CACN,KAAK,GAAG,EAAE;CAEf,OAAO,KAAK,UAAU,KAAK,KAAK;AAClC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "every-plugin",
3
- "version": "3.0.0-rc.4",
3
+ "version": "3.0.0-rc.6",
4
4
  "type": "module",
5
5
  "publishConfig": {
6
6
  "access": "public"
@@ -20,6 +20,10 @@ export function hasFolderFormUi(cwd: string): boolean {
20
20
  );
21
21
  }
22
22
 
23
+ export function uiDistDirFor(cwd: string): string {
24
+ return path.join(cwd, UI_DIR, "dist");
25
+ }
26
+
23
27
  function generatedUiConfig(pluginId: string): string {
24
28
  return `import path from "node:path";
25
29
  import { createUiRsbuildConfig } from "every-plugin/build/ui";
package/src/dev/serve.ts CHANGED
@@ -7,7 +7,11 @@ import sirv from "sirv";
7
7
  import { DEV_ENTRY_FILENAME } from "../build/artifact-names";
8
8
  import { ensureGeneratedRspackConfig } from "../build/rspack/generated-config";
9
9
  import { getPluginInfo, loadDevConfig } from "../build/rspack/utils";
10
- import { ensureGeneratedUiRsbuildConfig, pluginLayoutKey } from "../build/ui/generated-config";
10
+ import {
11
+ ensureGeneratedUiRsbuildConfig,
12
+ pluginLayoutKey,
13
+ uiDistDirFor,
14
+ } from "../build/ui/generated-config";
11
15
  import { PLUGIN_ERROR_STATUS_MAP } from "../errors";
12
16
  import { loadRemoteWithRetry } from "../remote-entry";
13
17
  import { startDirectModuleHost } from "./host";
@@ -168,11 +172,10 @@ export async function startPluginDevServer(
168
172
  // Folder-form ui: one-shot build, then serve the ui source root's dist
169
173
  // (the factory's absolute distPath target) statically on the ui port.
170
174
  await runOnce("rsbuild", ["build", "--config", uiConfig]);
171
- const uiDistDir =
172
- path.basename(cwd) === "ui" ? path.join(cwd, "dist") : path.join(cwd, "ui", "dist");
175
+ const uiDistDir = uiDistDirFor(cwd);
173
176
  if (!fs.existsSync(path.join(uiDistDir, DEV_ENTRY_FILENAME))) {
174
- console.error(
175
- `❌ UI dist is missing at ${uiDistDir} — the ui static server would serve 404s for every asset (build output layout mismatch?)`,
177
+ throw new Error(
178
+ `❌ UI dist is missing at ${uiDistDir} after the rsbuild one-shot — build output layout mismatch?`,
176
179
  );
177
180
  }
178
181
  const serveUiStatic = sirv(uiDistDir, { dev: true });
@@ -23,8 +23,7 @@ const DEFAULT_TIMEOUT_MS = 120_000;
23
23
  const RETRY_BASE_DELAY_MS = 500;
24
24
  const RETRY_MAX_DELAY_MS = 5_000;
25
25
 
26
- export const sleep = (ms: number): Promise<void> =>
27
- new Promise((resolve) => setTimeout(resolve, ms));
26
+ const sleep = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms));
28
27
 
29
28
  /**
30
29
  * Deletes the failed remote's keys from the process-global entry-load cache.
@@ -41,9 +41,26 @@ export const WorkspaceVersionManifestSchema = z.object({
41
41
  * ignore it (zod strips unknown keys). Participates in the version hash.
42
42
  */
43
43
  files: z.record(z.string(), SRI).optional(),
44
+ /**
45
+ * Source archive of the workspace subtree (object path → served-object SRI)
46
+ * published beside the dists when the runtime opts in via
47
+ * `publish.sourcePublish` — lets `bos import` dereference a published
48
+ * config slot to the exact source bytes that build came from, with no
49
+ * GitHub dependency. Readers that predate the field ignore it (zod strips
50
+ * unknown keys). Participates in the version hash.
51
+ */
52
+ source: z
53
+ .object({
54
+ file: z.string().min(1),
55
+ integrity: SRI,
56
+ })
57
+ .optional(),
44
58
  });
45
59
  export type WorkspaceVersionManifest = z.infer<typeof WorkspaceVersionManifestSchema>;
46
60
 
61
+ /** A published-artifact coordinate: object path within the bundle namespace + its served SRI. */
62
+ export type SourceRef = NonNullable<WorkspaceVersionManifest["source"]>;
63
+
47
64
  export interface VersionManifestInput {
48
65
  /** Omit: a per-build timestamp makes the same version id map to different
49
66
  * manifest bytes per machine, breaking the pin's SRI against the image's
@@ -57,6 +74,7 @@ export interface VersionManifestInput {
57
74
  assets?: Record<string, string>;
58
75
  shared?: Record<string, string>;
59
76
  files?: Record<string, string>;
77
+ source?: { file: string; integrity: string };
60
78
  }
61
79
 
62
80
  /**