every-plugin 3.0.0-rc.0 → 3.0.0-rc.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/client.cjs +69 -0
- package/dist/client.cjs.map +1 -0
- package/dist/client.d.cts +15 -0
- package/dist/client.d.cts.map +1 -0
- package/dist/client.d.mts +15 -0
- package/dist/client.d.mts.map +1 -0
- package/dist/client.mjs +68 -0
- package/dist/client.mjs.map +1 -0
- package/dist/dev/host.cjs +149 -0
- package/dist/dev/host.cjs.map +1 -0
- package/dist/dev/host.d.cts +32 -0
- package/dist/dev/host.d.cts.map +1 -0
- package/dist/dev/host.d.mts +32 -0
- package/dist/dev/host.d.mts.map +1 -0
- package/dist/dev/host.mjs +148 -0
- package/dist/dev/host.mjs.map +1 -0
- package/dist/dev/serve.cjs +14 -109
- package/dist/dev/serve.cjs.map +1 -1
- package/dist/dev/serve.d.cts.map +1 -1
- package/dist/dev/serve.d.mts.map +1 -1
- package/dist/dev/serve.mjs +14 -109
- package/dist/dev/serve.mjs.map +1 -1
- package/dist/errors.cjs +1 -0
- package/dist/errors.cjs.map +1 -1
- package/dist/errors.d.cts +2 -2
- package/dist/errors.d.mts +2 -2
- package/dist/errors.mjs +2 -2
- package/dist/errors.mjs.map +1 -1
- package/dist/index.cjs +3 -0
- package/dist/index.d.cts +5 -4
- package/dist/index.d.mts +5 -4
- package/dist/index.mjs +3 -2
- package/dist/plugin.cjs +1 -0
- package/dist/plugin.cjs.map +1 -1
- package/dist/plugin.d.cts +17 -3
- package/dist/plugin.d.cts.map +1 -1
- package/dist/plugin.d.mts +16 -2
- package/dist/plugin.d.mts.map +1 -1
- package/dist/plugin.mjs +1 -0
- package/dist/plugin.mjs.map +1 -1
- package/dist/runtime/errors.cjs +20 -0
- package/dist/runtime/errors.cjs.map +1 -1
- package/dist/runtime/errors.d.cts +23 -1
- package/dist/runtime/errors.d.cts.map +1 -1
- package/dist/runtime/errors.d.mts +23 -1
- package/dist/runtime/errors.d.mts.map +1 -1
- package/dist/runtime/errors.mjs +20 -1
- package/dist/runtime/errors.mjs.map +1 -1
- package/dist/runtime/mf-config.cjs +1 -1
- package/dist/runtime/mf-config.mjs +1 -1
- package/dist/runtime/services/module-federation.service.cjs +1 -7
- package/dist/runtime/services/module-federation.service.cjs.map +1 -1
- package/dist/runtime/services/module-federation.service.mjs +1 -7
- package/dist/runtime/services/module-federation.service.mjs.map +1 -1
- package/dist/runtime/services/plugin-loader.service.cjs +26 -1
- package/dist/runtime/services/plugin-loader.service.cjs.map +1 -1
- package/dist/runtime/services/plugin-loader.service.d.cts +2 -2
- package/dist/runtime/services/plugin-loader.service.mjs +26 -1
- package/dist/runtime/services/plugin-loader.service.mjs.map +1 -1
- package/dist/runtime/services/shared-identity.cjs +1 -1
- package/dist/runtime/services/shared-identity.cjs.map +1 -1
- package/dist/runtime/services/shared-identity.mjs +1 -1
- package/dist/runtime/services/shared-identity.mjs.map +1 -1
- package/dist/types.d.cts +26 -2
- package/dist/types.d.cts.map +1 -1
- package/dist/types.d.mts +25 -1
- package/dist/types.d.mts.map +1 -1
- package/dist/version-manifest.cjs +1 -1
- package/dist/version-manifest.cjs.map +1 -1
- package/dist/version-manifest.mjs +1 -1
- package/dist/version-manifest.mjs.map +1 -1
- package/package.json +19 -2
- package/src/client.ts +111 -0
- package/src/dev/host.ts +235 -0
- package/src/dev/serve.ts +14 -135
- package/src/errors.ts +2 -1
- package/src/index.ts +9 -0
- package/src/plugin.ts +20 -1
- package/src/runtime/errors.ts +44 -0
- package/src/runtime/services/module-federation.service.ts +4 -7
- package/src/runtime/services/plugin-loader.service.ts +32 -0
- package/src/runtime/services/shared-identity.ts +1 -1
- package/src/types.ts +39 -2
- package/src/version-manifest.ts +1 -1
package/dist/dev/serve.cjs
CHANGED
|
@@ -5,6 +5,7 @@ const require_build_artifact_names = require('../build/artifact-names.cjs');
|
|
|
5
5
|
const require_remote_entry = require('../remote-entry.cjs');
|
|
6
6
|
const require_utils = require('../build/rspack/utils.cjs');
|
|
7
7
|
const require_generated_config = require('../build/ui/generated-config.cjs');
|
|
8
|
+
const require_dev_host = require('./host.cjs');
|
|
8
9
|
const require_generated_config$1 = require('../build/rspack/generated-config.cjs');
|
|
9
10
|
const require_watch_kill = require('./watch-kill.cjs');
|
|
10
11
|
let effect = require("effect");
|
|
@@ -70,11 +71,6 @@ const loadPluginWithRetry = (runtime, pluginId, remoteUrl, options = {
|
|
|
70
71
|
load: () => runtime.usePlugin(pluginId, options, pluginsMap),
|
|
71
72
|
timeoutMs
|
|
72
73
|
}));
|
|
73
|
-
const sendJson = (res, status, body) => {
|
|
74
|
-
res.statusCode = status;
|
|
75
|
-
res.setHeader("content-type", "application/json; charset=utf-8");
|
|
76
|
-
res.end(JSON.stringify(body));
|
|
77
|
-
};
|
|
78
74
|
const sendText = (res, status, text) => {
|
|
79
75
|
res.statusCode = status;
|
|
80
76
|
res.setHeader("content-type", "text/plain; charset=utf-8");
|
|
@@ -98,7 +94,6 @@ async function startPluginDevServer(options = {}) {
|
|
|
98
94
|
const compositionKey = require_generated_config.pluginLayoutKey(cwd) ?? pluginId;
|
|
99
95
|
const port = options.port ?? (Number(process.env.PORT) || devConfig?.port || 3999);
|
|
100
96
|
const rpcPrefix = normalizePrefix(devConfig?.prefix);
|
|
101
|
-
const rpcBase = `/api/rpc${rpcPrefix}`;
|
|
102
97
|
const distDir = node_path.default.join(cwd, "dist");
|
|
103
98
|
const serveStatic = (0, sirv.default)(distDir, { dev: true });
|
|
104
99
|
const noWatch = options.watch === false || process.env.BOS_NO_WATCH === "1";
|
|
@@ -186,108 +181,18 @@ async function startPluginDevServer(options = {}) {
|
|
|
186
181
|
};
|
|
187
182
|
const effectContextHolder = { context: null };
|
|
188
183
|
let runtime = null;
|
|
189
|
-
const
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
getRawBody: async () => {
|
|
197
|
-
if (cachedRawBody !== null) return cachedRawBody;
|
|
198
|
-
if (!rawClone) {
|
|
199
|
-
cachedRawBody = "";
|
|
200
|
-
return cachedRawBody;
|
|
201
|
-
}
|
|
202
|
-
cachedRawBody = await rawClone.text();
|
|
203
|
-
return cachedRawBody;
|
|
204
|
-
}
|
|
205
|
-
};
|
|
206
|
-
};
|
|
207
|
-
const toWebRequest = (req) => {
|
|
208
|
-
const url = `http://localhost:${port}${req.url}`;
|
|
209
|
-
return new Request(url, {
|
|
210
|
-
method: req.method,
|
|
211
|
-
headers: req.headers,
|
|
212
|
-
body: req.method !== "GET" && req.method !== "HEAD" ? req : void 0,
|
|
213
|
-
duplex: req.method !== "GET" && req.method !== "HEAD" ? "half" : void 0
|
|
214
|
-
});
|
|
215
|
-
};
|
|
216
|
-
const handleOrpc = async (req, res, handler, prefix, errorLabel) => {
|
|
217
|
-
try {
|
|
218
|
-
const webRequest = toWebRequest(req);
|
|
219
|
-
const result = await handler.handle(webRequest, {
|
|
220
|
-
prefix,
|
|
221
|
-
context: buildDevContext(req, webRequest)
|
|
222
|
-
});
|
|
223
|
-
if (result.response) {
|
|
224
|
-
res.statusCode = result.response.status;
|
|
225
|
-
result.response.headers.forEach((value, key) => {
|
|
226
|
-
res.setHeader(key, value);
|
|
227
|
-
});
|
|
228
|
-
const text = await result.response.text();
|
|
229
|
-
if (!res.getHeader("content-length")) res.setHeader("content-length", Buffer.byteLength(text).toString());
|
|
230
|
-
res.end(text);
|
|
231
|
-
} else sendText(res, 404, "Not Found");
|
|
232
|
-
} catch (error) {
|
|
233
|
-
console.error(`${errorLabel} error:`, error);
|
|
234
|
-
sendJson(res, 500, { error: error.message });
|
|
235
|
-
}
|
|
236
|
-
};
|
|
237
|
-
const server = node_http.default.createServer((req, res) => {
|
|
238
|
-
applyCorsHeaders(res);
|
|
239
|
-
const pathname = pathnameOf(req);
|
|
240
|
-
if (req.method === "OPTIONS") {
|
|
241
|
-
res.statusCode = 200;
|
|
242
|
-
res.end();
|
|
243
|
-
return;
|
|
244
|
-
}
|
|
245
|
-
if (pathname === "/" && (req.method === "GET" || req.method === "HEAD")) {
|
|
246
|
-
sendJson(res, 200, {
|
|
247
|
-
ok: true,
|
|
248
|
-
plugin: pluginInfo.normalizedName,
|
|
249
|
-
version: pluginInfo.version,
|
|
250
|
-
status: handlers.rpc ? "ready" : "loading",
|
|
251
|
-
endpoints: {
|
|
252
|
-
health: "/",
|
|
253
|
-
docs: "/api",
|
|
254
|
-
rpc: rpcBase
|
|
255
|
-
}
|
|
256
|
-
});
|
|
257
|
-
return;
|
|
258
|
-
}
|
|
259
|
-
if (pathname === "/health" && (req.method === "GET" || req.method === "HEAD")) {
|
|
260
|
-
sendText(res, 200, "OK");
|
|
261
|
-
return;
|
|
262
|
-
}
|
|
263
|
-
if (pathname.startsWith(`${rpcBase}/`)) {
|
|
264
|
-
if (!handlers.rpc) {
|
|
265
|
-
sendJson(res, 503, { error: "Plugin still loading..." });
|
|
266
|
-
return;
|
|
267
|
-
}
|
|
268
|
-
handleOrpc(req, res, handlers.rpc, rpcBase, "RPC").catch(() => {});
|
|
269
|
-
return;
|
|
270
|
-
}
|
|
271
|
-
if (pathname === "/api" || pathname.startsWith("/api/")) {
|
|
272
|
-
if (!handlers.api) {
|
|
273
|
-
sendJson(res, 503, { error: "Plugin still loading..." });
|
|
274
|
-
return;
|
|
275
|
-
}
|
|
276
|
-
handleOrpc(req, res, handlers.api, "/api", "OpenAPI").catch(() => {});
|
|
277
|
-
return;
|
|
278
|
-
}
|
|
279
|
-
serveStatic(req, res, () => {
|
|
280
|
-
sendText(res, 404, "Not Found");
|
|
281
|
-
});
|
|
282
|
-
});
|
|
283
|
-
await new Promise((resolve, reject) => {
|
|
284
|
-
server.once("error", reject);
|
|
285
|
-
server.listen(port, () => resolve());
|
|
184
|
+
const host = await require_dev_host.startDirectModuleHost({
|
|
185
|
+
name: pluginInfo.normalizedName,
|
|
186
|
+
version: pluginInfo.version,
|
|
187
|
+
handlers,
|
|
188
|
+
effectContext: () => effectContextHolder.context,
|
|
189
|
+
port,
|
|
190
|
+
staticHandler: serveStatic
|
|
286
191
|
});
|
|
287
|
-
console.log(`🚀 ${pluginInfo.name} dev server listening on port ${port}`);
|
|
288
|
-
console.log(`├─ 📡 RPC: http://localhost:${port}/api/rpc${rpcPrefix}`);
|
|
289
|
-
console.log(`├─ 📖 Docs: http://localhost:${port}/api`);
|
|
290
|
-
console.log(`└─ 💚 Health: http://localhost:${port}/`);
|
|
192
|
+
console.log(`🚀 ${pluginInfo.name} dev server listening on port ${host.port}`);
|
|
193
|
+
console.log(`├─ 📡 RPC: http://localhost:${host.port}/api/rpc${rpcPrefix}`);
|
|
194
|
+
console.log(`├─ 📖 Docs: http://localhost:${host.port}/api`);
|
|
195
|
+
console.log(`└─ 💚 Health: http://localhost:${host.port}/`);
|
|
291
196
|
const load = async () => {
|
|
292
197
|
try {
|
|
293
198
|
const { createPluginRuntime } = await Promise.resolve().then(() => require("../runtime/index.cjs"));
|
|
@@ -302,7 +207,7 @@ async function startPluginDevServer(options = {}) {
|
|
|
302
207
|
const { siblings, dependsOn } = collectSiblingRemotes(runtimeConfig, compositionKey);
|
|
303
208
|
if (dependsOn.length > 0) console.log(`🔗 Loading sibling plugin(s): ${dependsOn.join(", ")}`);
|
|
304
209
|
const registry = {
|
|
305
|
-
[pluginId]: { remote: `http://localhost:${port}/${require_build_artifact_names.DEV_ENTRY_FILENAME}` },
|
|
210
|
+
[pluginId]: { remote: `http://localhost:${host.port}/${require_build_artifact_names.DEV_ENTRY_FILENAME}` },
|
|
306
211
|
...siblings
|
|
307
212
|
};
|
|
308
213
|
const mfRuntime = createPluginRuntime({ registry });
|
|
@@ -353,8 +258,8 @@ async function startPluginDevServer(options = {}) {
|
|
|
353
258
|
effectContextHolder.context = null;
|
|
354
259
|
for (const child of [watcher, uiWatcher]) if (child) await require_watch_kill.killChildEscalating(child);
|
|
355
260
|
if (uiStaticServer) await new Promise((resolve) => uiStaticServer.close(() => resolve()));
|
|
261
|
+
await host.close();
|
|
356
262
|
if (runtime) await runtime.shutdown().catch(() => {});
|
|
357
|
-
await new Promise((resolve) => server.close(() => resolve()));
|
|
358
263
|
};
|
|
359
264
|
process.once("SIGINT", async () => {
|
|
360
265
|
const timeout = setTimeout(() => process.exit(0), 3e3);
|
package/dist/dev/serve.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"serve.cjs","names":["DEV_ENTRY_FILENAME","Effect","loadRemoteWithRetry","getPluginInfo","loadDevConfig","path","pluginLayoutKey","spawn","ensureGeneratedRspackConfig","ensureGeneratedUiRsbuildConfig","fs","http","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 { 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 sendJson = (res: http.ServerResponse, status: number, body: unknown) => {\n res.statusCode = status;\n res.setHeader(\"content-type\", \"application/json; charset=utf-8\");\n res.end(JSON.stringify(body));\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 const rpcBase = `/api/rpc${rpcPrefix}`;\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\n const pathnameOf = (req: http.IncomingMessage): string =>\n ((req.url ?? \"/\").split(\"?\")[0] ?? \"/\").replace(/\\/+$/, \"\") || \"/\";\n\n const buildDevContext = (_req: http.IncomingMessage, webRequest: Request) => {\n const rawClone =\n webRequest.method === \"GET\" || webRequest.method === \"HEAD\" ? null : webRequest.clone();\n let cachedRawBody: string | null = null;\n return {\n reqHeaders: webRequest.headers,\n \"effect/context\": effectContextHolder.context,\n getRawBody: async (): Promise<string> => {\n if (cachedRawBody !== null) return cachedRawBody;\n if (!rawClone) {\n cachedRawBody = \"\";\n return cachedRawBody;\n }\n cachedRawBody = await rawClone.text();\n return cachedRawBody;\n },\n };\n };\n\n const toWebRequest = (req: http.IncomingMessage): Request => {\n const url = `http://localhost:${port}${req.url}`;\n return new Request(url, {\n method: req.method,\n headers: req.headers,\n body: req.method !== \"GET\" && req.method !== \"HEAD\" ? req : undefined,\n duplex: req.method !== \"GET\" && req.method !== \"HEAD\" ? \"half\" : undefined,\n } as RequestInit);\n };\n\n const handleOrpc = async (\n req: http.IncomingMessage,\n res: http.ServerResponse,\n handler: any,\n prefix: string,\n errorLabel: string,\n ) => {\n try {\n const webRequest = toWebRequest(req);\n const result = await handler.handle(webRequest, {\n prefix,\n context: buildDevContext(req, webRequest),\n });\n\n if (result.response) {\n res.statusCode = result.response.status;\n result.response.headers.forEach((value: string, key: string) => {\n res.setHeader(key, value);\n });\n const text = await result.response.text();\n if (!res.getHeader(\"content-length\")) {\n res.setHeader(\"content-length\", Buffer.byteLength(text).toString());\n }\n res.end(text);\n } else {\n sendText(res, 404, \"Not Found\");\n }\n } catch (error) {\n console.error(`${errorLabel} error:`, error);\n sendJson(res, 500, { error: (error as Error).message });\n }\n };\n\n const server = http.createServer((req, res) => {\n applyCorsHeaders(res);\n const pathname = pathnameOf(req);\n\n if (req.method === \"OPTIONS\") {\n res.statusCode = 200;\n res.end();\n return;\n }\n\n if (pathname === \"/\" && (req.method === \"GET\" || req.method === \"HEAD\")) {\n sendJson(res, 200, {\n ok: true,\n plugin: pluginInfo.normalizedName,\n version: pluginInfo.version,\n status: handlers.rpc ? \"ready\" : \"loading\",\n endpoints: {\n health: \"/\",\n docs: \"/api\",\n rpc: rpcBase,\n },\n });\n return;\n }\n\n if (pathname === \"/health\" && (req.method === \"GET\" || req.method === \"HEAD\")) {\n sendText(res, 200, \"OK\");\n return;\n }\n\n if (pathname.startsWith(`${rpcBase}/`)) {\n if (!handlers.rpc) {\n sendJson(res, 503, { error: \"Plugin still loading...\" });\n return;\n }\n handleOrpc(req, res, handlers.rpc, rpcBase, \"RPC\").catch(() => {});\n return;\n }\n\n if (pathname === \"/api\" || pathname.startsWith(\"/api/\")) {\n if (!handlers.api) {\n sendJson(res, 503, { error: \"Plugin still loading...\" });\n return;\n }\n handleOrpc(req, res, handlers.api, \"/api\", \"OpenAPI\").catch(() => {});\n return;\n }\n\n serveStatic(req, res, () => {\n sendText(res, 404, \"Not Found\");\n });\n });\n\n await new Promise<void>((resolve, reject) => {\n server.once(\"error\", reject);\n server.listen(port, () => resolve());\n });\n\n console.log(`🚀 ${pluginInfo.name} dev server listening on port ${port}`);\n console.log(`├─ 📡 RPC: http://localhost:${port}/api/rpc${rpcPrefix}`);\n console.log(`├─ 📖 Docs: http://localhost:${port}/api`);\n console.log(`└─ 💚 Health: http://localhost:${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:${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 if (runtime) await runtime.shutdown().catch(() => {});\n await new Promise<void>((resolve) => server.close(() => resolve()));\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":";;;;;;;;;;;;;;;;;;;;;AAcA,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,MAA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EA,AAAK,KAAK;CAEV,MAAM,QAAQ,YAAY;EACxB,SAAS,MAAM;EACf,SAAS,MAAM;EACf,oBAAoB,UAAU;EAC9B,KAAK,MAAM,SAAS,CAAC,SAAS,SAAS,GACrC,IAAI,OACF,MAAMC,uCAAoB,KAAK;EAGnC,IAAI,gBACF,MAAM,IAAI,SAAe,YAAY,eAAe,YAAY,QAAQ,CAAC,CAAC;EAE5E,IAAI,SAAS,MAAM,QAAQ,SAAS,CAAC,CAAC,YAAY,CAAC,CAAC;EACpD,MAAM,IAAI,SAAe,YAAY,OAAO,YAAY,QAAQ,CAAC,CAAC;CACpE;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","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;C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/serve.ts"],"mappings":";
|
|
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"}
|
package/dist/dev/serve.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"serve.d.mts","names":[],"sources":["../../src/dev/serve.ts"],"mappings":";
|
|
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"}
|
package/dist/dev/serve.mjs
CHANGED
|
@@ -4,6 +4,7 @@ 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
6
|
import { ensureGeneratedUiRsbuildConfig, pluginLayoutKey } from "../build/ui/generated-config.mjs";
|
|
7
|
+
import { startDirectModuleHost } from "./host.mjs";
|
|
7
8
|
import { ensureGeneratedRspackConfig } from "../build/rspack/generated-config.mjs";
|
|
8
9
|
import { killChildEscalating, watchParentDeath } from "./watch-kill.mjs";
|
|
9
10
|
import { Effect } from "effect";
|
|
@@ -65,11 +66,6 @@ const loadPluginWithRetry = (runtime, pluginId, remoteUrl, options = {
|
|
|
65
66
|
load: () => runtime.usePlugin(pluginId, options, pluginsMap),
|
|
66
67
|
timeoutMs
|
|
67
68
|
}));
|
|
68
|
-
const sendJson = (res, status, body) => {
|
|
69
|
-
res.statusCode = status;
|
|
70
|
-
res.setHeader("content-type", "application/json; charset=utf-8");
|
|
71
|
-
res.end(JSON.stringify(body));
|
|
72
|
-
};
|
|
73
69
|
const sendText = (res, status, text) => {
|
|
74
70
|
res.statusCode = status;
|
|
75
71
|
res.setHeader("content-type", "text/plain; charset=utf-8");
|
|
@@ -93,7 +89,6 @@ async function startPluginDevServer(options = {}) {
|
|
|
93
89
|
const compositionKey = pluginLayoutKey(cwd) ?? pluginId;
|
|
94
90
|
const port = options.port ?? (Number(process.env.PORT) || devConfig?.port || 3999);
|
|
95
91
|
const rpcPrefix = normalizePrefix(devConfig?.prefix);
|
|
96
|
-
const rpcBase = `/api/rpc${rpcPrefix}`;
|
|
97
92
|
const distDir = path.join(cwd, "dist");
|
|
98
93
|
const serveStatic = sirv(distDir, { dev: true });
|
|
99
94
|
const noWatch = options.watch === false || process.env.BOS_NO_WATCH === "1";
|
|
@@ -181,108 +176,18 @@ async function startPluginDevServer(options = {}) {
|
|
|
181
176
|
};
|
|
182
177
|
const effectContextHolder = { context: null };
|
|
183
178
|
let runtime = null;
|
|
184
|
-
const
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
getRawBody: async () => {
|
|
192
|
-
if (cachedRawBody !== null) return cachedRawBody;
|
|
193
|
-
if (!rawClone) {
|
|
194
|
-
cachedRawBody = "";
|
|
195
|
-
return cachedRawBody;
|
|
196
|
-
}
|
|
197
|
-
cachedRawBody = await rawClone.text();
|
|
198
|
-
return cachedRawBody;
|
|
199
|
-
}
|
|
200
|
-
};
|
|
201
|
-
};
|
|
202
|
-
const toWebRequest = (req) => {
|
|
203
|
-
const url = `http://localhost:${port}${req.url}`;
|
|
204
|
-
return new Request(url, {
|
|
205
|
-
method: req.method,
|
|
206
|
-
headers: req.headers,
|
|
207
|
-
body: req.method !== "GET" && req.method !== "HEAD" ? req : void 0,
|
|
208
|
-
duplex: req.method !== "GET" && req.method !== "HEAD" ? "half" : void 0
|
|
209
|
-
});
|
|
210
|
-
};
|
|
211
|
-
const handleOrpc = async (req, res, handler, prefix, errorLabel) => {
|
|
212
|
-
try {
|
|
213
|
-
const webRequest = toWebRequest(req);
|
|
214
|
-
const result = await handler.handle(webRequest, {
|
|
215
|
-
prefix,
|
|
216
|
-
context: buildDevContext(req, webRequest)
|
|
217
|
-
});
|
|
218
|
-
if (result.response) {
|
|
219
|
-
res.statusCode = result.response.status;
|
|
220
|
-
result.response.headers.forEach((value, key) => {
|
|
221
|
-
res.setHeader(key, value);
|
|
222
|
-
});
|
|
223
|
-
const text = await result.response.text();
|
|
224
|
-
if (!res.getHeader("content-length")) res.setHeader("content-length", Buffer.byteLength(text).toString());
|
|
225
|
-
res.end(text);
|
|
226
|
-
} else sendText(res, 404, "Not Found");
|
|
227
|
-
} catch (error) {
|
|
228
|
-
console.error(`${errorLabel} error:`, error);
|
|
229
|
-
sendJson(res, 500, { error: error.message });
|
|
230
|
-
}
|
|
231
|
-
};
|
|
232
|
-
const server = http.createServer((req, res) => {
|
|
233
|
-
applyCorsHeaders(res);
|
|
234
|
-
const pathname = pathnameOf(req);
|
|
235
|
-
if (req.method === "OPTIONS") {
|
|
236
|
-
res.statusCode = 200;
|
|
237
|
-
res.end();
|
|
238
|
-
return;
|
|
239
|
-
}
|
|
240
|
-
if (pathname === "/" && (req.method === "GET" || req.method === "HEAD")) {
|
|
241
|
-
sendJson(res, 200, {
|
|
242
|
-
ok: true,
|
|
243
|
-
plugin: pluginInfo.normalizedName,
|
|
244
|
-
version: pluginInfo.version,
|
|
245
|
-
status: handlers.rpc ? "ready" : "loading",
|
|
246
|
-
endpoints: {
|
|
247
|
-
health: "/",
|
|
248
|
-
docs: "/api",
|
|
249
|
-
rpc: rpcBase
|
|
250
|
-
}
|
|
251
|
-
});
|
|
252
|
-
return;
|
|
253
|
-
}
|
|
254
|
-
if (pathname === "/health" && (req.method === "GET" || req.method === "HEAD")) {
|
|
255
|
-
sendText(res, 200, "OK");
|
|
256
|
-
return;
|
|
257
|
-
}
|
|
258
|
-
if (pathname.startsWith(`${rpcBase}/`)) {
|
|
259
|
-
if (!handlers.rpc) {
|
|
260
|
-
sendJson(res, 503, { error: "Plugin still loading..." });
|
|
261
|
-
return;
|
|
262
|
-
}
|
|
263
|
-
handleOrpc(req, res, handlers.rpc, rpcBase, "RPC").catch(() => {});
|
|
264
|
-
return;
|
|
265
|
-
}
|
|
266
|
-
if (pathname === "/api" || pathname.startsWith("/api/")) {
|
|
267
|
-
if (!handlers.api) {
|
|
268
|
-
sendJson(res, 503, { error: "Plugin still loading..." });
|
|
269
|
-
return;
|
|
270
|
-
}
|
|
271
|
-
handleOrpc(req, res, handlers.api, "/api", "OpenAPI").catch(() => {});
|
|
272
|
-
return;
|
|
273
|
-
}
|
|
274
|
-
serveStatic(req, res, () => {
|
|
275
|
-
sendText(res, 404, "Not Found");
|
|
276
|
-
});
|
|
277
|
-
});
|
|
278
|
-
await new Promise((resolve, reject) => {
|
|
279
|
-
server.once("error", reject);
|
|
280
|
-
server.listen(port, () => resolve());
|
|
179
|
+
const host = await startDirectModuleHost({
|
|
180
|
+
name: pluginInfo.normalizedName,
|
|
181
|
+
version: pluginInfo.version,
|
|
182
|
+
handlers,
|
|
183
|
+
effectContext: () => effectContextHolder.context,
|
|
184
|
+
port,
|
|
185
|
+
staticHandler: serveStatic
|
|
281
186
|
});
|
|
282
|
-
console.log(`🚀 ${pluginInfo.name} dev server listening on port ${port}`);
|
|
283
|
-
console.log(`├─ 📡 RPC: http://localhost:${port}/api/rpc${rpcPrefix}`);
|
|
284
|
-
console.log(`├─ 📖 Docs: http://localhost:${port}/api`);
|
|
285
|
-
console.log(`└─ 💚 Health: http://localhost:${port}/`);
|
|
187
|
+
console.log(`🚀 ${pluginInfo.name} dev server listening on port ${host.port}`);
|
|
188
|
+
console.log(`├─ 📡 RPC: http://localhost:${host.port}/api/rpc${rpcPrefix}`);
|
|
189
|
+
console.log(`├─ 📖 Docs: http://localhost:${host.port}/api`);
|
|
190
|
+
console.log(`└─ 💚 Health: http://localhost:${host.port}/`);
|
|
286
191
|
const load = async () => {
|
|
287
192
|
try {
|
|
288
193
|
const { createPluginRuntime } = await import("../runtime/index.mjs");
|
|
@@ -297,7 +202,7 @@ async function startPluginDevServer(options = {}) {
|
|
|
297
202
|
const { siblings, dependsOn } = collectSiblingRemotes(runtimeConfig, compositionKey);
|
|
298
203
|
if (dependsOn.length > 0) console.log(`🔗 Loading sibling plugin(s): ${dependsOn.join(", ")}`);
|
|
299
204
|
const registry = {
|
|
300
|
-
[pluginId]: { remote: `http://localhost:${port}/${DEV_ENTRY_FILENAME}` },
|
|
205
|
+
[pluginId]: { remote: `http://localhost:${host.port}/${DEV_ENTRY_FILENAME}` },
|
|
301
206
|
...siblings
|
|
302
207
|
};
|
|
303
208
|
const mfRuntime = createPluginRuntime({ registry });
|
|
@@ -348,8 +253,8 @@ async function startPluginDevServer(options = {}) {
|
|
|
348
253
|
effectContextHolder.context = null;
|
|
349
254
|
for (const child of [watcher, uiWatcher]) if (child) await killChildEscalating(child);
|
|
350
255
|
if (uiStaticServer) await new Promise((resolve) => uiStaticServer.close(() => resolve()));
|
|
256
|
+
await host.close();
|
|
351
257
|
if (runtime) await runtime.shutdown().catch(() => {});
|
|
352
|
-
await new Promise((resolve) => server.close(() => resolve()));
|
|
353
258
|
};
|
|
354
259
|
process.once("SIGINT", async () => {
|
|
355
260
|
const timeout = setTimeout(() => process.exit(0), 3e3);
|
package/dist/dev/serve.mjs.map
CHANGED
|
@@ -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 { 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 sendJson = (res: http.ServerResponse, status: number, body: unknown) => {\n res.statusCode = status;\n res.setHeader(\"content-type\", \"application/json; charset=utf-8\");\n res.end(JSON.stringify(body));\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 const rpcBase = `/api/rpc${rpcPrefix}`;\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\n const pathnameOf = (req: http.IncomingMessage): string =>\n ((req.url ?? \"/\").split(\"?\")[0] ?? \"/\").replace(/\\/+$/, \"\") || \"/\";\n\n const buildDevContext = (_req: http.IncomingMessage, webRequest: Request) => {\n const rawClone =\n webRequest.method === \"GET\" || webRequest.method === \"HEAD\" ? null : webRequest.clone();\n let cachedRawBody: string | null = null;\n return {\n reqHeaders: webRequest.headers,\n \"effect/context\": effectContextHolder.context,\n getRawBody: async (): Promise<string> => {\n if (cachedRawBody !== null) return cachedRawBody;\n if (!rawClone) {\n cachedRawBody = \"\";\n return cachedRawBody;\n }\n cachedRawBody = await rawClone.text();\n return cachedRawBody;\n },\n };\n };\n\n const toWebRequest = (req: http.IncomingMessage): Request => {\n const url = `http://localhost:${port}${req.url}`;\n return new Request(url, {\n method: req.method,\n headers: req.headers,\n body: req.method !== \"GET\" && req.method !== \"HEAD\" ? req : undefined,\n duplex: req.method !== \"GET\" && req.method !== \"HEAD\" ? \"half\" : undefined,\n } as RequestInit);\n };\n\n const handleOrpc = async (\n req: http.IncomingMessage,\n res: http.ServerResponse,\n handler: any,\n prefix: string,\n errorLabel: string,\n ) => {\n try {\n const webRequest = toWebRequest(req);\n const result = await handler.handle(webRequest, {\n prefix,\n context: buildDevContext(req, webRequest),\n });\n\n if (result.response) {\n res.statusCode = result.response.status;\n result.response.headers.forEach((value: string, key: string) => {\n res.setHeader(key, value);\n });\n const text = await result.response.text();\n if (!res.getHeader(\"content-length\")) {\n res.setHeader(\"content-length\", Buffer.byteLength(text).toString());\n }\n res.end(text);\n } else {\n sendText(res, 404, \"Not Found\");\n }\n } catch (error) {\n console.error(`${errorLabel} error:`, error);\n sendJson(res, 500, { error: (error as Error).message });\n }\n };\n\n const server = http.createServer((req, res) => {\n applyCorsHeaders(res);\n const pathname = pathnameOf(req);\n\n if (req.method === \"OPTIONS\") {\n res.statusCode = 200;\n res.end();\n return;\n }\n\n if (pathname === \"/\" && (req.method === \"GET\" || req.method === \"HEAD\")) {\n sendJson(res, 200, {\n ok: true,\n plugin: pluginInfo.normalizedName,\n version: pluginInfo.version,\n status: handlers.rpc ? \"ready\" : \"loading\",\n endpoints: {\n health: \"/\",\n docs: \"/api\",\n rpc: rpcBase,\n },\n });\n return;\n }\n\n if (pathname === \"/health\" && (req.method === \"GET\" || req.method === \"HEAD\")) {\n sendText(res, 200, \"OK\");\n return;\n }\n\n if (pathname.startsWith(`${rpcBase}/`)) {\n if (!handlers.rpc) {\n sendJson(res, 503, { error: \"Plugin still loading...\" });\n return;\n }\n handleOrpc(req, res, handlers.rpc, rpcBase, \"RPC\").catch(() => {});\n return;\n }\n\n if (pathname === \"/api\" || pathname.startsWith(\"/api/\")) {\n if (!handlers.api) {\n sendJson(res, 503, { error: \"Plugin still loading...\" });\n return;\n }\n handleOrpc(req, res, handlers.api, \"/api\", \"OpenAPI\").catch(() => {});\n return;\n }\n\n serveStatic(req, res, () => {\n sendText(res, 404, \"Not Found\");\n });\n });\n\n await new Promise<void>((resolve, reject) => {\n server.once(\"error\", reject);\n server.listen(port, () => resolve());\n });\n\n console.log(`🚀 ${pluginInfo.name} dev server listening on port ${port}`);\n console.log(`├─ 📡 RPC: http://localhost:${port}/api/rpc${rpcPrefix}`);\n console.log(`├─ 📖 Docs: http://localhost:${port}/api`);\n console.log(`└─ 💚 Health: http://localhost:${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:${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 if (runtime) await runtime.shutdown().catch(() => {});\n await new Promise<void>((resolve) => server.close(() => resolve()));\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().cat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M;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 { 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(\"❌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oBAAoB,GAG5F,qBAAqB,CAAC,CAAC,OAAO,UAAU;CACtC,QAAQ,MAAM,oCAAoC,KAAK;CACvD,QAAQ,KAAK,CAAC;AAChB,CAAC"}
|
package/dist/errors.cjs
CHANGED
|
@@ -137,6 +137,7 @@ exports.TIMEOUT = TIMEOUT;
|
|
|
137
137
|
exports.UNAUTHORIZED = UNAUTHORIZED;
|
|
138
138
|
exports.ValidationError = require_errors.ValidationError;
|
|
139
139
|
exports.classifyPluginFailure = require_errors.classifyPluginFailure;
|
|
140
|
+
exports.defaultMissingSecretWarnings = require_errors.defaultMissingSecretWarnings;
|
|
140
141
|
exports.extractFromFiberFailure = require_errors.extractFromFiberFailure;
|
|
141
142
|
exports.formatORPCError = require_errors.formatORPCError;
|
|
142
143
|
exports.toPluginRuntimeError = require_errors.toPluginRuntimeError;
|
package/dist/errors.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"errors.cjs","names":["z","COMMON_ERROR_STATUS_MAP"],"sources":["../src/errors.ts"],"sourcesContent":["import { COMMON_ERROR_STATUS_MAP } from \"@orpc/server\";\nimport { z } from \"zod\";\n\n/**\n * Common error schemas for plugin contracts.\n * Import individually or use the grouped PluginErrors export.\n *\n * @example\n * ```typescript\n * import { NOT_FOUND, FORBIDDEN, UNAUTHORIZED } from \"every-plugin/errors\";\n *\n * export const contract = oc.router({\n * getData: oc.route(...)\n * .errors({ NOT_FOUND, FORBIDDEN, UNAUTHORIZED })\n * });\n * ```\n */\n\nexport const UNAUTHORIZED = {\n status: 401,\n data: z.object({\n apiKeyProvided: z.boolean(),\n provider: z.string().optional(),\n authType: z.enum([\"apiKey\", \"oauth\", \"token\"]).optional(),\n }),\n} as const;\n\nexport const RATE_LIMITED = {\n status: 429,\n data: z.object({\n retryAfter: z.number().int().min(1),\n remainingRequests: z.number().int().min(0).optional(),\n resetTime: z.string().datetime().optional(),\n limitType: z.enum([\"requests\", \"tokens\", \"bandwidth\"]).optional(),\n }),\n} as const;\n\nexport const SERVICE_UNAVAILABLE = {\n status: 503,\n data: z.object({\n retryAfter: z.number().int().optional(),\n maintenanceWindow: z.boolean().default(false),\n estimatedUptime: z.string().datetime().optional(),\n }),\n} as const;\n\nexport const BAD_REQUEST = {\n status: 400,\n data: z.object({\n invalidFields: z.array(z.string()).optional(),\n validationErrors: z\n .array(\n z.object({\n field: z.string(),\n message: z.string(),\n code: z.string().optional(),\n }),\n )\n .optional(),\n }),\n} as const;\n\nexport const NOT_FOUND = {\n status: 404,\n data: z.object({\n resource: z.string().optional(),\n resourceId: z.string().optional(),\n }),\n} as const;\n\nexport const FORBIDDEN = {\n status: 403,\n data: z.object({\n requiredPermissions: z.array(z.string()).optional(),\n action: z.string().optional(),\n }),\n} as const;\n\nexport const TIMEOUT = {\n status: 504,\n data: z.object({\n timeoutMs: z.number().int().min(0).optional(),\n operation: z.string().optional(),\n retryable: z.boolean().default(true),\n }),\n} as const;\n\nexport const CONNECTION_ERROR = {\n status: 502,\n data: z.object({\n errorCode: z.string().optional(),\n host: z.string().optional(),\n port: z.number().int().optional(),\n suggestion: z.string().optional(),\n }),\n} as const;\n\n/**\n * Grouped export for all plugin errors.\n * Use individual imports for cleaner code.\n */\nexport const PluginErrors = {\n UNAUTHORIZED,\n RATE_LIMITED,\n SERVICE_UNAVAILABLE,\n BAD_REQUEST,\n NOT_FOUND,\n FORBIDDEN,\n TIMEOUT,\n CONNECTION_ERROR,\n} as const;\n\n/**\n * Error-code -> HTTP-status map for handlers.\n *\n * oRPC v2 resolves statuses at the handler boundary via `errorStatusMap`\n * (default `COMMON_ERROR_STATUS_MAP`, where TIMEOUT is 408). Providing a\n * map REPLACES the default entirely, so the standard codes must be spread\n * back in. These custom entries preserve the v1 wire behavior:\n * TIMEOUT -> 504, CONNECTION_ERROR -> 502.\n */\nexport const PLUGIN_ERROR_STATUS_MAP: Record<string, number> = {\n ...COMMON_ERROR_STATUS_MAP,\n TIMEOUT: 504,\n CONNECTION_ERROR: 502,\n} as const;\n\nexport type { PluginLoadFailureInfo } from \"./runtime/errors\";\nexport {\n classifyPluginFailure,\n extractFromFiberFailure,\n formatORPCError,\n ModuleFederationError,\n PluginRuntimeError,\n toPluginRuntimeError,\n ValidationError,\n wrapORPCError,\n} from \"./runtime/errors\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAkBA,MAAa,eAAe;CAC1B,QAAQ;CACR,MAAMA,MAAE,OAAO;EACb,gBAAgBA,MAAE,QAAQ;EAC1B,UAAUA,MAAE,OAAO,CAAC,CAAC,SAAS;EAC9B,UAAUA,MAAE,KAAK;GAAC;GAAU;GAAS;EAAO,CAAC,CAAC,CAAC,SAAS;CAC1D,CAAC;AACH;AAEA,MAAa,eAAe;CAC1B,QAAQ;CACR,MAAMA,MAAE,OAAO;EACb,YAAYA,MAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC;EAClC,mBAAmBA,MAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS;EACpD,WAAWA,MAAE,OAAO,CAAC,CAAC,SAAS,CAAC,CAAC,SAAS;EAC1C,WAAWA,MAAE,KAAK;GAAC;GAAY;GAAU;EAAW,CAAC,CAAC,CAAC,SAAS;CAClE,CAAC;AACH;AAEA,MAAa,sBAAsB;CACjC,QAAQ;CACR,MAAMA,MAAE,OAAO;EACb,YAAYA,MAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,SAAS;EACtC,mBAAmBA,MAAE,QAAQ,CAAC,CAAC,QAAQ,KAAK;EAC5C,iBAAiBA,MAAE,OAAO,CAAC,CAAC,SAAS,CAAC,CAAC,SAAS;CAClD,CAAC;AACH;AAEA,MAAa,cAAc;CACzB,QAAQ;CACR,MAAMA,MAAE,OAAO;EACb,eAAeA,MAAE,MAAMA,MAAE,OAAO,CAAC,CAAC,CAAC,SAAS;EAC5C,kBAAkBA,MACf,MACCA,MAAE,OAAO;GACP,OAAOA,MAAE,OAAO;GAChB,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MAP } from \"@orpc/server\";\nimport { z } from \"zod\";\n\n/**\n * Common error schemas for plugin contracts.\n * Import individually or use the grouped PluginErrors export.\n *\n * @example\n * ```typescript\n * import { NOT_FOUND, FORBIDDEN, UNAUTHORIZED } from \"every-plugin/errors\";\n *\n * export const contract = oc.router({\n * getData: oc.route(...)\n * .errors({ NOT_FOUND, FORBIDDEN, UNAUTHORIZED })\n * });\n * ```\n */\n\nexport const UNAUTHORIZED = {\n status: 401,\n data: z.object({\n apiKeyProvided: z.boolean(),\n provider: z.string().optional(),\n authType: z.enum([\"apiKey\", \"oauth\", \"token\"]).optional(),\n }),\n} as const;\n\nexport const RATE_LIMITED = {\n status: 429,\n data: z.object({\n retryAfter: z.number().int().min(1),\n remainingRequests: z.number().int().min(0).optional(),\n resetTime: z.string().datetime().optional(),\n limitType: z.enum([\"requests\", \"tokens\", \"bandwidth\"]).optional(),\n }),\n} as const;\n\nexport const SERVICE_UNAVAILABLE = {\n status: 503,\n data: z.object({\n retryAfter: z.number().int().optional(),\n maintenanceWindow: z.boolean().default(false),\n estimatedUptime: z.string().datetime().optional(),\n }),\n} as const;\n\nexport const BAD_REQUEST = {\n status: 400,\n data: z.object({\n invalidFields: z.array(z.string()).optional(),\n validationErrors: z\n .array(\n z.object({\n field: z.string(),\n message: z.string(),\n code: z.string().optional(),\n }),\n )\n .optional(),\n }),\n} as const;\n\nexport const NOT_FOUND = {\n status: 404,\n data: z.object({\n resource: z.string().optional(),\n resourceId: z.string().optional(),\n }),\n} as const;\n\nexport const FORBIDDEN = {\n status: 403,\n data: z.object({\n requiredPermissions: z.array(z.string()).optional(),\n action: z.string().optional(),\n }),\n} as const;\n\nexport const TIMEOUT = {\n status: 504,\n data: z.object({\n timeoutMs: z.number().int().min(0).optional(),\n operation: z.string().optional(),\n retryable: z.boolean().default(true),\n }),\n} as const;\n\nexport const CONNECTION_ERROR = {\n status: 502,\n data: z.object({\n errorCode: z.string().optional(),\n host: z.string().optional(),\n port: z.number().int().optional(),\n suggestion: z.string().optional(),\n }),\n} as const;\n\n/**\n * Grouped export for all plugin errors.\n * Use individual imports for cleaner code.\n */\nexport const PluginErrors = {\n UNAUTHORIZED,\n RATE_LIMITED,\n SERVICE_UNAVAILABLE,\n BAD_REQUEST,\n NOT_FOUND,\n FORBIDDEN,\n TIMEOUT,\n CONNECTION_ERROR,\n} as const;\n\n/**\n * Error-code -> HTTP-status map for handlers.\n *\n * oRPC v2 resolves statuses at the handler boundary via `errorStatusMap`\n * (default `COMMON_ERROR_STATUS_MAP`, where TIMEOUT is 408). Providing a\n * map REPLACES the default entirely, so the standard codes must be spread\n * back in. These custom entries preserve the v1 wire behavior:\n * TIMEOUT -> 504, CONNECTION_ERROR -> 502.\n */\nexport const PLUGIN_ERROR_STATUS_MAP: Record<string, number> = {\n ...COMMON_ERROR_STATUS_MAP,\n TIMEOUT: 504,\n CONNECTION_ERROR: 502,\n} as const;\n\nexport type { PluginLoadFailureInfo, PluginWarningInfo } from \"./runtime/errors\";\nexport {\n classifyPluginFailure,\n defaultMissingSecretWarnings,\n extractFromFiberFailure,\n formatORPCError,\n ModuleFederationError,\n PluginRuntimeError,\n toPluginRuntimeError,\n ValidationError,\n wrapORPCError,\n} from \"./runtime/errors\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAkBA,MAAa,eAAe;CAC1B,QAAQ;CACR,MAAMA,MAAE,OAAO;EACb,gBAAgBA,MAAE,QAAQ;EAC1B,UAAUA,MAAE,OAAO,CAAC,CAAC,SAAS;EAC9B,UAAUA,MAAE,KAAK;GAAC;GAAU;GAAS;EAAO,CAAC,CAAC,CAAC,SAAS;CAC1D,CAAC;AACH;AAEA,MAAa,eAAe;CAC1B,QAAQ;CACR,MAAMA,MAAE,OAAO;EACb,YAAYA,MAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC;EAClC,mBAAmBA,MAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS;EACp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WAAWA,MAAE,QAAQ,CAAC,CAAC,QAAQ,IAAI;CACrC,CAAC;AACH;AAEA,MAAa,mBAAmB;CAC9B,QAAQ;CACR,MAAMA,MAAE,OAAO;EACb,WAAWA,MAAE,OAAO,CAAC,CAAC,SAAS;EAC/B,MAAMA,MAAE,OAAO,CAAC,CAAC,SAAS;EAC1B,MAAMA,MAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,SAAS;EAChC,YAAYA,MAAE,OAAO,CAAC,CAAC,SAAS;CAClC,CAAC;AACH;;;;;AAMA,MAAa,eAAe;CAC1B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;;;;;;;;;AAWA,MAAa,0BAAkD;CAC7D,GAAGC;CACH,SAAS;CACT,kBAAkB;AACpB"}
|
package/dist/errors.d.cts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { ModuleFederationError, PluginLoadFailureInfo, PluginRuntimeError, ValidationError, classifyPluginFailure, extractFromFiberFailure, formatORPCError, toPluginRuntimeError, wrapORPCError } from "./runtime/errors.cjs";
|
|
1
|
+
import { ModuleFederationError, PluginLoadFailureInfo, PluginRuntimeError, PluginWarningInfo, ValidationError, classifyPluginFailure, defaultMissingSecretWarnings, extractFromFiberFailure, formatORPCError, toPluginRuntimeError, wrapORPCError } from "./runtime/errors.cjs";
|
|
2
2
|
import { z } from "zod";
|
|
3
3
|
//#region src/errors.d.ts
|
|
4
4
|
/**
|
|
@@ -182,5 +182,5 @@ declare const PluginErrors: {
|
|
|
182
182
|
*/
|
|
183
183
|
declare const PLUGIN_ERROR_STATUS_MAP: Record<string, number>;
|
|
184
184
|
//#endregion
|
|
185
|
-
export { BAD_REQUEST, CONNECTION_ERROR, FORBIDDEN, ModuleFederationError, NOT_FOUND, PLUGIN_ERROR_STATUS_MAP, PluginErrors, type PluginLoadFailureInfo, PluginRuntimeError, RATE_LIMITED, SERVICE_UNAVAILABLE, TIMEOUT, UNAUTHORIZED, ValidationError, classifyPluginFailure, extractFromFiberFailure, formatORPCError, toPluginRuntimeError, wrapORPCError };
|
|
185
|
+
export { BAD_REQUEST, CONNECTION_ERROR, FORBIDDEN, ModuleFederationError, NOT_FOUND, PLUGIN_ERROR_STATUS_MAP, PluginErrors, type PluginLoadFailureInfo, PluginRuntimeError, type PluginWarningInfo, RATE_LIMITED, SERVICE_UNAVAILABLE, TIMEOUT, UNAUTHORIZED, ValidationError, classifyPluginFailure, defaultMissingSecretWarnings, extractFromFiberFailure, formatORPCError, toPluginRuntimeError, wrapORPCError };
|
|
186
186
|
//# sourceMappingURL=errors.d.cts.map
|