everything-dev 1.49.0 → 1.50.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (142) hide show
  1. package/dist/app.cjs +66 -86
  2. package/dist/app.cjs.map +1 -1
  3. package/dist/app.mjs +66 -87
  4. package/dist/app.mjs.map +1 -1
  5. package/dist/cli/db-doctor.cjs +6 -23
  6. package/dist/cli/db-doctor.cjs.map +1 -1
  7. package/dist/cli/db-doctor.mjs +7 -24
  8. package/dist/cli/db-doctor.mjs.map +1 -1
  9. package/dist/cli/db-repair.cjs +25 -20
  10. package/dist/cli/db-repair.cjs.map +1 -1
  11. package/dist/cli/db-repair.mjs +25 -20
  12. package/dist/cli/db-repair.mjs.map +1 -1
  13. package/dist/cli/db-studio.cjs +4 -2
  14. package/dist/cli/db-studio.cjs.map +1 -1
  15. package/dist/cli/db-studio.mjs +5 -3
  16. package/dist/cli/db-studio.mjs.map +1 -1
  17. package/dist/cli/framework-version.cjs +45 -9
  18. package/dist/cli/framework-version.cjs.map +1 -1
  19. package/dist/cli/framework-version.mjs +45 -10
  20. package/dist/cli/framework-version.mjs.map +1 -1
  21. package/dist/cli/infra.cjs +89 -3
  22. package/dist/cli/infra.cjs.map +1 -1
  23. package/dist/cli/infra.mjs +83 -4
  24. package/dist/cli/infra.mjs.map +1 -1
  25. package/dist/cli/init.cjs +39 -15
  26. package/dist/cli/init.cjs.map +1 -1
  27. package/dist/cli/init.d.cts +8 -3
  28. package/dist/cli/init.d.cts.map +1 -1
  29. package/dist/cli/init.d.mts +8 -3
  30. package/dist/cli/init.d.mts.map +1 -1
  31. package/dist/cli/init.mjs +39 -16
  32. package/dist/cli/init.mjs.map +1 -1
  33. package/dist/cli/status.cjs +6 -2
  34. package/dist/cli/status.cjs.map +1 -1
  35. package/dist/cli/status.mjs +7 -3
  36. package/dist/cli/status.mjs.map +1 -1
  37. package/dist/cli/sync.cjs +1 -3
  38. package/dist/cli/sync.cjs.map +1 -1
  39. package/dist/cli/sync.mjs +1 -3
  40. package/dist/cli/sync.mjs.map +1 -1
  41. package/dist/cli/upgrade.cjs +8 -4
  42. package/dist/cli/upgrade.cjs.map +1 -1
  43. package/dist/cli/upgrade.mjs +8 -4
  44. package/dist/cli/upgrade.mjs.map +1 -1
  45. package/dist/cli.cjs +73 -9
  46. package/dist/cli.cjs.map +1 -1
  47. package/dist/cli.mjs +74 -10
  48. package/dist/cli.mjs.map +1 -1
  49. package/dist/config.cjs +7 -3
  50. package/dist/config.cjs.map +1 -1
  51. package/dist/config.d.cts.map +1 -1
  52. package/dist/config.d.mts.map +1 -1
  53. package/dist/config.mjs +7 -3
  54. package/dist/config.mjs.map +1 -1
  55. package/dist/contract.cjs +76 -4
  56. package/dist/contract.cjs.map +1 -1
  57. package/dist/contract.d.cts +164 -19
  58. package/dist/contract.d.cts.map +1 -1
  59. package/dist/contract.d.mts +164 -19
  60. package/dist/contract.d.mts.map +1 -1
  61. package/dist/contract.meta.cjs +17 -2
  62. package/dist/contract.meta.cjs.map +1 -1
  63. package/dist/contract.meta.d.cts +23 -2
  64. package/dist/contract.meta.d.mts +23 -2
  65. package/dist/contract.meta.mjs +17 -2
  66. package/dist/contract.meta.mjs.map +1 -1
  67. package/dist/contract.mjs +72 -5
  68. package/dist/contract.mjs.map +1 -1
  69. package/dist/db.cjs +32 -24
  70. package/dist/db.cjs.map +1 -1
  71. package/dist/db.d.cts +16 -9
  72. package/dist/db.d.cts.map +1 -1
  73. package/dist/db.d.mts +16 -9
  74. package/dist/db.d.mts.map +1 -1
  75. package/dist/db.mjs +32 -23
  76. package/dist/db.mjs.map +1 -1
  77. package/dist/dev-session.cjs +28 -0
  78. package/dist/dev-session.cjs.map +1 -1
  79. package/dist/dev-session.mjs +29 -1
  80. package/dist/dev-session.mjs.map +1 -1
  81. package/dist/index.cjs +5 -0
  82. package/dist/index.d.cts +2 -2
  83. package/dist/index.d.mts +2 -2
  84. package/dist/index.mjs +2 -2
  85. package/dist/infra/planner.cjs +337 -0
  86. package/dist/infra/planner.cjs.map +1 -0
  87. package/dist/infra/planner.mjs +336 -0
  88. package/dist/infra/planner.mjs.map +1 -0
  89. package/dist/infra/preflight.cjs +131 -0
  90. package/dist/infra/preflight.cjs.map +1 -0
  91. package/dist/infra/preflight.mjs +130 -0
  92. package/dist/infra/preflight.mjs.map +1 -0
  93. package/dist/infra/types.cjs +9 -0
  94. package/dist/infra/types.cjs.map +1 -0
  95. package/dist/infra/types.mjs +8 -0
  96. package/dist/infra/types.mjs.map +1 -0
  97. package/dist/near-cli.cjs +37 -0
  98. package/dist/near-cli.cjs.map +1 -1
  99. package/dist/near-cli.mjs +36 -1
  100. package/dist/near-cli.mjs.map +1 -1
  101. package/dist/orchestrator.cjs +10 -2
  102. package/dist/orchestrator.cjs.map +1 -1
  103. package/dist/orchestrator.mjs +10 -2
  104. package/dist/orchestrator.mjs.map +1 -1
  105. package/dist/plugin.cjs +160 -43
  106. package/dist/plugin.cjs.map +1 -1
  107. package/dist/plugin.d.cts +64 -8
  108. package/dist/plugin.d.cts.map +1 -1
  109. package/dist/plugin.d.mts +64 -8
  110. package/dist/plugin.d.mts.map +1 -1
  111. package/dist/plugin.mjs +164 -47
  112. package/dist/plugin.mjs.map +1 -1
  113. package/dist/process-registry.cjs +88 -0
  114. package/dist/process-registry.cjs.map +1 -0
  115. package/dist/process-registry.mjs +83 -0
  116. package/dist/process-registry.mjs.map +1 -0
  117. package/dist/publish.cjs +4 -0
  118. package/dist/publish.cjs.map +1 -1
  119. package/dist/publish.mjs +4 -0
  120. package/dist/publish.mjs.map +1 -1
  121. package/dist/service-descriptor.cjs +4 -0
  122. package/dist/service-descriptor.cjs.map +1 -1
  123. package/dist/service-descriptor.mjs +4 -1
  124. package/dist/service-descriptor.mjs.map +1 -1
  125. package/dist/types.d.cts +2 -2
  126. package/dist/types.d.mts +2 -2
  127. package/dist/ui/index.cjs +2 -1
  128. package/dist/ui/index.d.cts +2 -2
  129. package/dist/ui/index.d.mts +2 -2
  130. package/dist/ui/index.mjs +2 -2
  131. package/dist/ui/router.cjs +40 -0
  132. package/dist/ui/router.cjs.map +1 -1
  133. package/dist/ui/router.d.cts +6 -1
  134. package/dist/ui/router.d.cts.map +1 -1
  135. package/dist/ui/router.d.mts +6 -1
  136. package/dist/ui/router.d.mts.map +1 -1
  137. package/dist/ui/router.mjs +40 -1
  138. package/dist/ui/router.mjs.map +1 -1
  139. package/package.json +4 -1
  140. package/skills/cli-reference/SKILL.md +5 -4
  141. package/skills/dev-workflow/SKILL.md +40 -11
  142. package/skills/plugin-development/SKILL.md +9 -2
package/dist/app.cjs CHANGED
@@ -1,15 +1,17 @@
1
1
  const require_runtime = require('./_virtual/_rolldown/runtime.cjs');
2
2
  const require_config = require('./config.cjs');
3
+ const require_process_registry = require('./process-registry.cjs');
3
4
  let node_fs = require("node:fs");
4
5
  let node_path = require("node:path");
6
+ let effect = require("effect");
5
7
  let node_net = require("node:net");
6
8
 
7
9
  //#region src/app.ts
8
- const DEFAULT_HOST_PORT = 3e3;
9
- const DEFAULT_API_PORT = 3001;
10
- const DEFAULT_AUTH_PORT = 3002;
11
- const DEFAULT_UI_PORT = 3003;
12
- const DEFAULT_PLUGIN_PORT_START = 3010;
10
+ const PROBE_TIMEOUT_MS = 250;
11
+ const MAX_PORT_SCAN_STEPS = 1e3;
12
+ const PARALLEL_PROBE_WINDOW = 8;
13
+ var PortAllocationError = class extends effect.Data.TaggedError("PortAllocationError") {};
14
+ var PortAllocator = class extends effect.Context.Tag("PortAllocator")() {};
13
15
  function detectLocalPackages(bosConfig, runtimeConfig) {
14
16
  const packages = [];
15
17
  const configDir = require_config.getProjectRoot();
@@ -38,97 +40,75 @@ function buildRuntimeConfig(bosConfig, options) {
38
40
  plugins: options.plugins
39
41
  });
40
42
  }
41
- function probeTcpOpen(port, timeoutMs = 250) {
42
- return new Promise((resolve) => {
43
- const socket = (0, node_net.createConnection)({
44
- host: "127.0.0.1",
45
- port
43
+ function probePortBindable(port) {
44
+ return effect.Effect.async((resume) => {
45
+ const server = (0, node_net.createServer)();
46
+ server.once("listening", () => {
47
+ server.close(() => {
48
+ resume(effect.Effect.succeed(true));
49
+ });
46
50
  });
47
- const timer = setTimeout(() => {
48
- socket.destroy();
49
- resolve(false);
50
- }, timeoutMs);
51
- socket.once("connect", () => {
52
- clearTimeout(timer);
53
- socket.destroy();
54
- resolve(true);
55
- });
56
- socket.once("error", () => {
57
- clearTimeout(timer);
58
- resolve(false);
51
+ server.once("error", () => {
52
+ server.removeAllListeners();
53
+ resume(effect.Effect.succeed(false));
59
54
  });
55
+ server.listen(port, "127.0.0.1");
56
+ const timer = setTimeout(() => {
57
+ server.removeAllListeners();
58
+ try {
59
+ server.close();
60
+ } catch {}
61
+ resume(effect.Effect.succeed(false));
62
+ }, PROBE_TIMEOUT_MS);
63
+ server.once("listening", () => clearTimeout(timer));
64
+ server.once("error", () => clearTimeout(timer));
60
65
  });
61
66
  }
62
- async function pickAvailablePort(preferred, usedPorts) {
63
- let port = preferred;
64
- while (usedPorts.has(port) || await probeTcpOpen(port)) port += 1;
65
- usedPorts.add(port);
66
- return port;
67
- }
68
- function withLocalRuntimeUrl(entry, port) {
69
- const url = `http://localhost:${port}`;
70
- return {
71
- ...entry,
72
- url,
73
- entry: `${url}/mf-manifest.json`,
74
- port
75
- };
76
- }
77
- async function prepareDevelopmentRuntimeConfig(runtimeConfig, options) {
78
- const usedPorts = /* @__PURE__ */ new Set();
79
- const hostPort = await pickAvailablePort(options?.hostPort ?? DEFAULT_HOST_PORT, usedPorts);
80
- const next = {
81
- ...runtimeConfig,
82
- host: {
83
- ...runtimeConfig.host,
84
- url: `http://localhost:${hostPort}`,
85
- port: hostPort
86
- },
87
- ui: { ...runtimeConfig.ui },
88
- api: { ...runtimeConfig.api },
89
- auth: runtimeConfig.auth ? { ...runtimeConfig.auth } : void 0,
90
- plugins: runtimeConfig.plugins ? { ...runtimeConfig.plugins } : void 0
91
- };
92
- if (next.api.source === "local" && next.api.localPath) {
93
- const apiPort = await pickAvailablePort(next.api.port ?? DEFAULT_API_PORT, usedPorts);
94
- next.api = withLocalRuntimeUrl(next.api, apiPort);
95
- }
96
- if (next.auth?.source === "local" && next.auth.localPath) {
97
- const authPort = await pickAvailablePort(next.auth.port ?? DEFAULT_AUTH_PORT, usedPorts);
98
- next.auth = withLocalRuntimeUrl(next.auth, authPort);
99
- }
100
- if (next.ui.source === "local" && next.ui.localPath) {
101
- const uiPort = await pickAvailablePort(next.ui.port ?? DEFAULT_UI_PORT, usedPorts);
102
- next.ui = withLocalRuntimeUrl(next.ui, uiPort);
103
- if (options?.ssr) {
104
- const ssrPort = await pickAvailablePort(uiPort + 1, usedPorts);
105
- next.ui.ssrUrl = `http://localhost:${ssrPort}`;
106
- } else next.ui.ssrUrl = void 0;
107
- }
108
- if (next.plugins) {
109
- const entries = Object.entries(next.plugins).sort(([a], [b]) => a.localeCompare(b));
110
- let pluginBasePort = DEFAULT_PLUGIN_PORT_START;
111
- for (const [pluginId, plugin] of entries) {
112
- if (plugin.source === "local" && plugin.localPath) {
113
- const pluginPort = await pickAvailablePort(plugin.port ?? pluginBasePort, usedPorts);
114
- next.plugins[pluginId] = withLocalRuntimeUrl(plugin, pluginPort);
115
- pluginBasePort = pluginPort + 1;
67
+ function pickAvailablePort(preferred, usedPorts, budget) {
68
+ return effect.Effect.gen(function* () {
69
+ const within = (candidate) => !budget || candidate >= budget.min && candidate <= budget.max;
70
+ let port = preferred;
71
+ if (!within(port)) port = budget ? budget.min : port;
72
+ const ceiling = budget ? budget.max + 1 : Number.MAX_SAFE_INTEGER;
73
+ let steps = 0;
74
+ const fail = () => effect.Effect.fail(new PortAllocationError({
75
+ preferred,
76
+ budget,
77
+ cause: budget ? `No free port in budget [${budget.min}, ${budget.max}] starting from ${preferred}` : `No free port found starting from ${preferred} within ${MAX_PORT_SCAN_STEPS} steps`
78
+ }));
79
+ while (true) {
80
+ if (port >= ceiling || steps > MAX_PORT_SCAN_STEPS) yield* fail();
81
+ const candidates = [];
82
+ for (let i = 0; i < PARALLEL_PROBE_WINDOW && port + i < ceiling; i++) {
83
+ const candidate = port + i;
84
+ if (!usedPorts.has(candidate)) candidates.push(candidate);
85
+ }
86
+ if (candidates.length === 0) {
87
+ port += PARALLEL_PROBE_WINDOW;
88
+ steps += PARALLEL_PROBE_WINDOW;
89
+ continue;
116
90
  }
117
- if (plugin.ui?.source === "local" && plugin.ui.localPath) {
118
- const uiPort = await pickAvailablePort(plugin.ui.port ?? pluginBasePort, usedPorts);
119
- next.plugins[pluginId] = {
120
- ...next.plugins[pluginId],
121
- ui: withLocalRuntimeUrl(plugin.ui, uiPort)
122
- };
123
- pluginBasePort = uiPort + 1;
91
+ const firstFree = (yield* effect.Effect.forEach(candidates, (c) => probePortBindable(c).pipe(effect.Effect.map((free) => ({
92
+ port: c,
93
+ free
94
+ }))), { concurrency: "unbounded" })).find((r) => r.free);
95
+ if (firstFree) {
96
+ usedPorts.add(firstFree.port);
97
+ return firstFree.port;
124
98
  }
99
+ port += PARALLEL_PROBE_WINDOW;
100
+ steps += PARALLEL_PROBE_WINDOW;
125
101
  }
126
- }
127
- return next;
102
+ });
128
103
  }
104
+ const PortAllocatorLive = effect.Layer.sync(PortAllocator, () => {
105
+ const usedPorts = require_process_registry.claimedPorts();
106
+ return { pickAvailable: (preferred, budget) => pickAvailablePort(preferred, usedPorts, budget) };
107
+ });
129
108
 
130
109
  //#endregion
110
+ exports.PortAllocator = PortAllocator;
111
+ exports.PortAllocatorLive = PortAllocatorLive;
131
112
  exports.buildRuntimeConfig = buildRuntimeConfig;
132
113
  exports.detectLocalPackages = detectLocalPackages;
133
- exports.prepareDevelopmentRuntimeConfig = prepareDevelopmentRuntimeConfig;
134
114
  //# sourceMappingURL=app.cjs.map
package/dist/app.cjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"app.cjs","names":["getProjectRoot","resolveLocalDevelopmentPath","configBuildRuntimeConfig"],"sources":["../src/app.ts"],"sourcesContent":["import { existsSync } from \"node:fs\";\nimport { createConnection } from \"node:net\";\nimport { join } from \"node:path\";\nimport {\n buildRuntimeConfig as configBuildRuntimeConfig,\n getProjectRoot,\n resolveLocalDevelopmentPath,\n} from \"./config\";\nimport type { AppOrchestrator } from \"./service-descriptor\";\nimport type { BosConfig, RuntimeConfig, RuntimePluginConfig } from \"./types\";\n\nexport type { AppOrchestrator };\n\nconst DEFAULT_HOST_PORT = 3000;\nconst DEFAULT_API_PORT = 3001;\nconst DEFAULT_AUTH_PORT = 3002;\nconst DEFAULT_UI_PORT = 3003;\nconst DEFAULT_PLUGIN_PORT_START = 3010;\n\nexport function detectLocalPackages(\n bosConfig?: BosConfig,\n runtimeConfig?: RuntimeConfig,\n): string[] {\n const packages: string[] = [];\n const configDir = getProjectRoot();\n\n const uiLocalPath =\n runtimeConfig?.ui.localPath ??\n resolveLocalDevelopmentPath(bosConfig?.app.ui.development, configDir);\n if (uiLocalPath && existsSync(join(uiLocalPath, \"package.json\"))) {\n packages.push(\"ui\");\n }\n\n const apiLocalPath =\n runtimeConfig?.api.localPath ??\n resolveLocalDevelopmentPath(bosConfig?.app.api.development, configDir);\n if (apiLocalPath && existsSync(join(apiLocalPath, \"package.json\"))) {\n packages.push(\"api\");\n }\n\n const hostLocalPath =\n runtimeConfig?.host?.localPath ??\n resolveLocalDevelopmentPath(bosConfig?.app.host.development, configDir);\n if (hostLocalPath && existsSync(join(hostLocalPath, \"package.json\"))) {\n packages.push(\"host\");\n } else if (existsSync(join(configDir, \"host\", \"package.json\"))) {\n packages.push(\"host\");\n }\n\n for (const [pluginId, pluginConfig] of Object.entries(runtimeConfig?.plugins ?? {})) {\n if (pluginConfig.localPath && existsSync(join(pluginConfig.localPath, \"package.json\"))) {\n packages.push(`plugin:${pluginId}`);\n }\n if (pluginConfig.ui?.localPath && existsSync(join(pluginConfig.ui.localPath, \"package.json\"))) {\n packages.push(`plugin-ui:${pluginId}`);\n }\n }\n\n const authLocalPath =\n runtimeConfig?.auth?.localPath ??\n resolveLocalDevelopmentPath(bosConfig?.app.auth?.development, configDir);\n if (authLocalPath && existsSync(join(authLocalPath, \"package.json\"))) {\n packages.push(\"auth\");\n }\n\n return packages;\n}\n\nexport function buildRuntimeConfig(\n bosConfig: BosConfig,\n options: {\n hostSource?: \"local\" | \"remote\";\n uiSource?: \"local\" | \"remote\";\n apiSource?: \"local\" | \"remote\";\n authSource?: \"local\" | \"remote\";\n proxy?: string;\n env?: \"development\" | \"production\";\n plugins?: Record<string, RuntimePluginConfig>;\n },\n): RuntimeConfig {\n return configBuildRuntimeConfig(bosConfig, getProjectRoot(), options.env ?? \"development\", {\n hostSource: options.hostSource,\n uiSource: options.uiSource,\n apiSource: options.apiSource,\n authSource: options.authSource,\n proxy: options.proxy,\n plugins: options.plugins,\n });\n}\n\nfunction probeTcpOpen(port: number, timeoutMs = 250): Promise<boolean> {\n return new Promise((resolve) => {\n const socket = createConnection({ host: \"127.0.0.1\", port });\n const timer = setTimeout(() => {\n socket.destroy();\n resolve(false);\n }, timeoutMs);\n\n socket.once(\"connect\", () => {\n clearTimeout(timer);\n socket.destroy();\n resolve(true);\n });\n\n socket.once(\"error\", () => {\n clearTimeout(timer);\n resolve(false);\n });\n });\n}\n\nasync function pickAvailablePort(preferred: number, usedPorts: Set<number>): Promise<number> {\n let port = preferred;\n while (usedPorts.has(port) || (await probeTcpOpen(port))) {\n port += 1;\n }\n usedPorts.add(port);\n return port;\n}\n\nfunction withLocalRuntimeUrl<\n T extends { url: string; entry: string; port?: number; localPath?: string },\n>(entry: T, port: number): T {\n const url = `http://localhost:${port}`;\n return {\n ...entry,\n url,\n entry: `${url}/mf-manifest.json`,\n port,\n };\n}\n\nexport async function prepareDevelopmentRuntimeConfig(\n runtimeConfig: RuntimeConfig,\n options?: { hostPort?: number; ssr?: boolean },\n): Promise<RuntimeConfig> {\n const usedPorts = new Set<number>();\n const hostPort = await pickAvailablePort(options?.hostPort ?? DEFAULT_HOST_PORT, usedPorts);\n\n const next: RuntimeConfig = {\n ...runtimeConfig,\n host: { ...runtimeConfig.host, url: `http://localhost:${hostPort}`, port: hostPort },\n ui: { ...runtimeConfig.ui },\n api: { ...runtimeConfig.api },\n auth: runtimeConfig.auth ? { ...runtimeConfig.auth } : undefined,\n plugins: runtimeConfig.plugins ? { ...runtimeConfig.plugins } : undefined,\n };\n\n if (next.api.source === \"local\" && next.api.localPath) {\n const apiPort = await pickAvailablePort(next.api.port ?? DEFAULT_API_PORT, usedPorts);\n next.api = withLocalRuntimeUrl(next.api, apiPort);\n }\n\n if (next.auth?.source === \"local\" && next.auth.localPath) {\n const authPort = await pickAvailablePort(next.auth.port ?? DEFAULT_AUTH_PORT, usedPorts);\n next.auth = withLocalRuntimeUrl(next.auth, authPort);\n }\n\n if (next.ui.source === \"local\" && next.ui.localPath) {\n const uiPort = await pickAvailablePort(next.ui.port ?? DEFAULT_UI_PORT, usedPorts);\n next.ui = withLocalRuntimeUrl(next.ui, uiPort);\n if (options?.ssr) {\n const ssrPort = await pickAvailablePort(uiPort + 1, usedPorts);\n next.ui.ssrUrl = `http://localhost:${ssrPort}`;\n } else {\n next.ui.ssrUrl = undefined;\n }\n }\n\n if (next.plugins) {\n const entries = Object.entries(next.plugins).sort(([a], [b]) => a.localeCompare(b));\n let pluginBasePort = DEFAULT_PLUGIN_PORT_START;\n\n for (const [pluginId, plugin] of entries) {\n if (plugin.source === \"local\" && plugin.localPath) {\n const pluginPort = await pickAvailablePort(plugin.port ?? pluginBasePort, usedPorts);\n next.plugins[pluginId] = withLocalRuntimeUrl(plugin, pluginPort);\n pluginBasePort = pluginPort + 1;\n }\n\n if (plugin.ui?.source === \"local\" && plugin.ui.localPath) {\n const uiPort = await pickAvailablePort(plugin.ui.port ?? pluginBasePort, usedPorts);\n next.plugins[pluginId] = {\n ...next.plugins[pluginId]!,\n ui: withLocalRuntimeUrl(plugin.ui, uiPort),\n };\n pluginBasePort = uiPort + 1;\n }\n }\n }\n\n return next;\n}\n"],"mappings":";;;;;;;AAaA,MAAM,oBAAoB;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,oBAAoB,KAAK,KAAK,QAAQ;;AAGnD,KAAI,KAAK,MAAM,WAAW,WAAW,KAAK,KAAK,WAAW;EACxD,MAAM,WAAW,MAAM,kBAAkB,KAAK,KAAK,QAAQ,mBAAmB,UAAU;AACxF,OAAK,OAAO,oBAAoB,KAAK,MAAM,SAAS;;AAGtD,KAAI,KAAK,GAAG,WAAW,WAAW,KAAK,GAAG,WAAW;EACnD,MAAM,SAAS,MAAM,kBAAkB,KAAK,GAAG,QAAQ,iBAAiB,UAAU;AAClF,OAAK,KAAK,oBAAoB,KAAK,IAAI,OAAO;AAC9C,MAAI,SAAS,KAAK;GAChB,MAAM,UAAU,MAAM,kBAAkB,SAAS,GAAG,UAAU;AAC9D,QAAK,GAAG,SAAS,oBAAoB;QAErC,MAAK,GAAG,SAAS;;AAIrB,KAAI,KAAK,SAAS;EAChB,MAAM,UAAU,OAAO,QAAQ,KAAK,QAAQ,CAAC,MAAM,CAAC,IAAI,CAAC,OAAO,EAAE,cAAc,EAAE,CAAC;EACnF,IAAI,iBAAiB;AAErB,OAAK,MAAM,CAAC,UAAU,WAAW,SAAS;AACxC,OAAI,OAAO,WAAW,WAAW,OAAO,WAAW;IACjD,MAAM,aAAa,MAAM,kBAAkB,OAAO,QAAQ,gBAAgB,UAAU;AACpF,SAAK,QAAQ,YAAY,oBAAoB,QAAQ,WAAW;AAChE,qBAAiB,aAAa;;AAGhC,OAAI,OAAO,IAAI,WAAW,WAAW,OAAO,GAAG,WAAW;IACxD,MAAM,SAAS,MAAM,kBAAkB,OAAO,GAAG,QAAQ,gBAAgB,UAAU;AACnF,SAAK,QAAQ,YAAY;KACvB,GAAG,KAAK,QAAQ;KAChB,IAAI,oBAAoB,OAAO,IAAI,OAAO;KAC3C;AACD,qBAAiB,SAAS;;;;AAKhC,QAAO"}
1
+ {"version":3,"file":"app.cjs","names":["Data","Context","getProjectRoot","resolveLocalDevelopmentPath","configBuildRuntimeConfig","Effect","Layer","claimedPorts"],"sources":["../src/app.ts"],"sourcesContent":["import { existsSync } from \"node:fs\";\nimport { createServer } from \"node:net\";\nimport { join } from \"node:path\";\nimport { Context, Data, Effect, Layer } from \"effect\";\nimport type { DevPortState } from \"./cli/infra\";\nimport {\n buildRuntimeConfig as configBuildRuntimeConfig,\n getProjectRoot,\n resolveLocalDevelopmentPath,\n} from \"./config\";\nimport { claimedPorts } from \"./process-registry\";\nimport type { AppOrchestrator } from \"./service-descriptor\";\nimport type { BosConfig, RuntimeConfig, RuntimePluginConfig } from \"./types\";\n\nexport type { AppOrchestrator };\n\nconst DEFAULT_HOST_PORT = 3000;\nconst DEFAULT_API_PORT = 3001;\nconst DEFAULT_AUTH_PORT = 3002;\nconst DEFAULT_UI_PORT = 3003;\nconst DEFAULT_PLUGIN_PORT_START = 3010;\n\nconst PROBE_TIMEOUT_MS = 250;\nconst MAX_PORT_SCAN_STEPS = 1000;\nconst PARALLEL_PROBE_WINDOW = 8;\n\nexport type PortBudget = { min: number; max: number };\n\nexport class PortAllocationError extends Data.TaggedError(\"PortAllocationError\")<{\n preferred: number;\n budget?: PortBudget;\n cause?: unknown;\n}> {}\n\nexport class PortAllocator extends Context.Tag(\"PortAllocator\")<\n PortAllocator,\n {\n pickAvailable: (\n preferred: number,\n budget?: PortBudget,\n ) => Effect.Effect<number, PortAllocationError>;\n }\n>() {}\n\nexport function detectLocalPackages(\n bosConfig?: BosConfig,\n runtimeConfig?: RuntimeConfig,\n): string[] {\n const packages: string[] = [];\n const configDir = getProjectRoot();\n\n const uiLocalPath =\n runtimeConfig?.ui.localPath ??\n resolveLocalDevelopmentPath(bosConfig?.app.ui.development, configDir);\n if (uiLocalPath && existsSync(join(uiLocalPath, \"package.json\"))) {\n packages.push(\"ui\");\n }\n\n const apiLocalPath =\n runtimeConfig?.api.localPath ??\n resolveLocalDevelopmentPath(bosConfig?.app.api.development, configDir);\n if (apiLocalPath && existsSync(join(apiLocalPath, \"package.json\"))) {\n packages.push(\"api\");\n }\n\n const hostLocalPath =\n runtimeConfig?.host?.localPath ??\n resolveLocalDevelopmentPath(bosConfig?.app.host.development, configDir);\n if (hostLocalPath && existsSync(join(hostLocalPath, \"package.json\"))) {\n packages.push(\"host\");\n } else if (existsSync(join(configDir, \"host\", \"package.json\"))) {\n packages.push(\"host\");\n }\n\n for (const [pluginId, pluginConfig] of Object.entries(runtimeConfig?.plugins ?? {})) {\n if (pluginConfig.localPath && existsSync(join(pluginConfig.localPath, \"package.json\"))) {\n packages.push(`plugin:${pluginId}`);\n }\n if (pluginConfig.ui?.localPath && existsSync(join(pluginConfig.ui.localPath, \"package.json\"))) {\n packages.push(`plugin-ui:${pluginId}`);\n }\n }\n\n const authLocalPath =\n runtimeConfig?.auth?.localPath ??\n resolveLocalDevelopmentPath(bosConfig?.app.auth?.development, configDir);\n if (authLocalPath && existsSync(join(authLocalPath, \"package.json\"))) {\n packages.push(\"auth\");\n }\n\n return packages;\n}\n\nexport function buildRuntimeConfig(\n bosConfig: BosConfig,\n options: {\n hostSource?: \"local\" | \"remote\";\n uiSource?: \"local\" | \"remote\";\n apiSource?: \"local\" | \"remote\";\n authSource?: \"local\" | \"remote\";\n proxy?: string;\n env?: \"development\" | \"production\";\n plugins?: Record<string, RuntimePluginConfig>;\n },\n): RuntimeConfig {\n return configBuildRuntimeConfig(bosConfig, getProjectRoot(), options.env ?? \"development\", {\n hostSource: options.hostSource,\n uiSource: options.uiSource,\n apiSource: options.apiSource,\n authSource: options.authSource,\n proxy: options.proxy,\n plugins: options.plugins,\n });\n}\n\nfunction probePortBindable(port: number): Effect.Effect<boolean> {\n return Effect.async<boolean>((resume) => {\n const server = createServer();\n\n server.once(\"listening\", () => {\n server.close(() => {\n resume(Effect.succeed(true));\n });\n });\n\n server.once(\"error\", () => {\n server.removeAllListeners();\n // EADDRINUSE, EACCES, or any other bind error → not available\n resume(Effect.succeed(false));\n });\n\n server.listen(port, \"127.0.0.1\");\n\n const timer = setTimeout(() => {\n server.removeAllListeners();\n try {\n server.close();\n } catch {\n // ignore\n }\n resume(Effect.succeed(false));\n }, PROBE_TIMEOUT_MS);\n\n server.once(\"listening\", () => clearTimeout(timer));\n server.once(\"error\", () => clearTimeout(timer));\n });\n}\n\nfunction pickAvailablePort(\n preferred: number,\n usedPorts: Set<number>,\n budget?: PortBudget,\n): Effect.Effect<number, PortAllocationError> {\n return Effect.gen(function* () {\n const within = (candidate: number): boolean =>\n !budget || (candidate >= budget.min && candidate <= budget.max);\n\n let port = preferred;\n if (!within(port)) {\n port = budget ? budget.min : port;\n }\n\n const ceiling = budget ? budget.max + 1 : Number.MAX_SAFE_INTEGER;\n let steps = 0;\n\n const fail = () =>\n Effect.fail(\n new PortAllocationError({\n preferred,\n budget,\n cause: budget\n ? `No free port in budget [${budget.min}, ${budget.max}] starting from ${preferred}`\n : `No free port found starting from ${preferred} within ${MAX_PORT_SCAN_STEPS} steps`,\n }),\n );\n\n while (true) {\n if (port >= ceiling || steps > MAX_PORT_SCAN_STEPS) {\n yield* fail();\n }\n\n const candidates: number[] = [];\n for (let i = 0; i < PARALLEL_PROBE_WINDOW && port + i < ceiling; i++) {\n const candidate = port + i;\n if (!usedPorts.has(candidate)) {\n candidates.push(candidate);\n }\n }\n\n if (candidates.length === 0) {\n port += PARALLEL_PROBE_WINDOW;\n steps += PARALLEL_PROBE_WINDOW;\n continue;\n }\n\n const results = yield* Effect.forEach(\n candidates,\n (c) => probePortBindable(c).pipe(Effect.map((free) => ({ port: c, free }))),\n { concurrency: \"unbounded\" },\n );\n\n const firstFree = results.find((r) => r.free);\n if (firstFree) {\n usedPorts.add(firstFree.port);\n return firstFree.port;\n }\n\n port += PARALLEL_PROBE_WINDOW;\n steps += PARALLEL_PROBE_WINDOW;\n }\n });\n}\n\nexport const PortAllocatorLive: Layer.Layer<PortAllocator> = Layer.sync(PortAllocator, () => {\n const usedPorts = claimedPorts();\n return {\n pickAvailable: (preferred, budget) => pickAvailablePort(preferred, usedPorts, budget),\n };\n});\n\nfunction withLocalRuntimeUrl<\n T extends { url: string; entry: string; port?: number; localPath?: string },\n>(entry: T, port: number): T {\n const url = `http://localhost:${port}`;\n return {\n ...entry,\n url,\n entry: `${url}/mf-manifest.json`,\n port,\n };\n}\n\nexport interface DevPortOptions {\n hostPort?: number;\n apiPort?: number;\n uiPort?: number;\n authPort?: number;\n pluginPortStart?: number;\n ssr?: boolean;\n portBudget?: PortBudget;\n}\n\nexport interface PreparedDevRuntime {\n runtimeConfig: RuntimeConfig;\n devPorts: DevPortState;\n}\n\nexport function prepareDevelopmentRuntimeConfig(\n runtimeConfig: RuntimeConfig,\n options?: DevPortOptions,\n): Effect.Effect<PreparedDevRuntime, PortAllocationError, PortAllocator> {\n return Effect.gen(function* () {\n const allocator = yield* PortAllocator;\n const budget = options?.portBudget;\n\n const pickedHostPort = yield* allocator.pickAvailable(\n options?.hostPort ?? DEFAULT_HOST_PORT,\n budget,\n );\n\n const hostIsLocal = runtimeConfig.host.source === \"local\";\n const next: RuntimeConfig = {\n ...runtimeConfig,\n host: hostIsLocal\n ? {\n ...runtimeConfig.host,\n url: `http://localhost:${pickedHostPort}`,\n port: pickedHostPort,\n }\n : { ...runtimeConfig.host },\n ui: { ...runtimeConfig.ui },\n api: { ...runtimeConfig.api },\n auth: runtimeConfig.auth ? { ...runtimeConfig.auth } : undefined,\n plugins: runtimeConfig.plugins ? { ...runtimeConfig.plugins } : undefined,\n };\n\n const devPorts: DevPortState = {\n host: hostIsLocal ? pickedHostPort : undefined,\n api: undefined,\n ui: undefined,\n auth: undefined,\n pluginPortStart: undefined,\n };\n\n if (next.api.source === \"local\" && next.api.localPath) {\n const apiPort = yield* allocator.pickAvailable(\n options?.apiPort ?? next.api.port ?? DEFAULT_API_PORT,\n budget,\n );\n next.api = withLocalRuntimeUrl(next.api, apiPort);\n devPorts.api = apiPort;\n }\n\n if (next.auth?.source === \"local\" && next.auth.localPath) {\n const authPort = yield* allocator.pickAvailable(\n options?.authPort ?? next.auth.port ?? DEFAULT_AUTH_PORT,\n budget,\n );\n next.auth = withLocalRuntimeUrl(next.auth, authPort);\n devPorts.auth = authPort;\n }\n\n if (next.ui.source === \"local\" && next.ui.localPath) {\n const uiPort = yield* allocator.pickAvailable(\n options?.uiPort ?? next.ui.port ?? DEFAULT_UI_PORT,\n budget,\n );\n next.ui = withLocalRuntimeUrl(next.ui, uiPort);\n devPorts.ui = uiPort;\n if (options?.ssr) {\n const ssrPort = yield* allocator.pickAvailable(uiPort + 1, budget);\n next.ui.ssrUrl = `http://localhost:${ssrPort}`;\n } else {\n next.ui.ssrUrl = undefined;\n }\n }\n\n if (next.plugins) {\n const entries = Object.entries(next.plugins).sort(([a], [b]) => a.localeCompare(b));\n let pluginBasePort = options?.pluginPortStart ?? DEFAULT_PLUGIN_PORT_START;\n let firstLocalPluginPort: number | undefined;\n\n for (const [pluginId, plugin] of entries) {\n if (plugin.source === \"local\" && plugin.localPath) {\n const pluginPort = yield* allocator.pickAvailable(plugin.port ?? pluginBasePort, budget);\n next.plugins[pluginId] = withLocalRuntimeUrl(plugin, pluginPort);\n if (firstLocalPluginPort === undefined) firstLocalPluginPort = pluginPort;\n pluginBasePort = pluginPort + 1;\n }\n\n if (plugin.ui?.source === \"local\" && plugin.ui.localPath) {\n const pluginUiPort = yield* allocator.pickAvailable(\n plugin.ui.port ?? pluginBasePort,\n budget,\n );\n next.plugins[pluginId] = {\n ...next.plugins[pluginId]!,\n ui: withLocalRuntimeUrl(plugin.ui, pluginUiPort),\n };\n if (firstLocalPluginPort === undefined) firstLocalPluginPort = pluginUiPort;\n pluginBasePort = pluginUiPort + 1;\n }\n }\n\n devPorts.pluginPortStart = firstLocalPluginPort;\n }\n\n return { runtimeConfig: next, devPorts };\n });\n}\n"],"mappings":";;;;;;;;;AAsBA,MAAM,mBAAmB;AACzB,MAAM,sBAAsB;AAC5B,MAAM,wBAAwB;AAI9B,IAAa,sBAAb,cAAyCA,YAAK,YAAY,sBAAsB,CAI7E;AAEH,IAAa,gBAAb,cAAmCC,eAAQ,IAAI,gBAAgB,EAQ5D,CAAC;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AC3B,YAAQ;AACR,aAAS;AACT;;GASF,MAAM,aAAY,OANKA,cAAO,QAC5B,aACC,MAAM,kBAAkB,EAAE,CAAC,KAAKA,cAAO,KAAK,UAAU;IAAE,MAAM;IAAG;IAAM,EAAE,CAAC,EAC3E,EAAE,aAAa,aAAa,CAC7B,EAEyB,MAAM,MAAM,EAAE,KAAK;AAC7C,OAAI,WAAW;AACb,cAAU,IAAI,UAAU,KAAK;AAC7B,WAAO,UAAU;;AAGnB,WAAQ;AACR,YAAS;;GAEX;;AAGJ,MAAa,oBAAgDC,aAAM,KAAK,qBAAqB;CAC3F,MAAM,YAAYC,uCAAc;AAChC,QAAO,EACL,gBAAgB,WAAW,WAAW,kBAAkB,WAAW,WAAW,OAAO,EACtF;EACD"}
package/dist/app.mjs CHANGED
@@ -1,14 +1,16 @@
1
1
  import { buildRuntimeConfig as buildRuntimeConfig$1, getProjectRoot, resolveLocalDevelopmentPath } from "./config.mjs";
2
+ import { claimedPorts } from "./process-registry.mjs";
2
3
  import { existsSync } from "node:fs";
3
4
  import { join } from "node:path";
4
- import { createConnection } from "node:net";
5
+ import { Context, Data, Effect, Layer } from "effect";
6
+ import { createServer } from "node:net";
5
7
 
6
8
  //#region src/app.ts
7
- const DEFAULT_HOST_PORT = 3e3;
8
- const DEFAULT_API_PORT = 3001;
9
- const DEFAULT_AUTH_PORT = 3002;
10
- const DEFAULT_UI_PORT = 3003;
11
- const DEFAULT_PLUGIN_PORT_START = 3010;
9
+ const PROBE_TIMEOUT_MS = 250;
10
+ const MAX_PORT_SCAN_STEPS = 1e3;
11
+ const PARALLEL_PROBE_WINDOW = 8;
12
+ var PortAllocationError = class extends Data.TaggedError("PortAllocationError") {};
13
+ var PortAllocator = class extends Context.Tag("PortAllocator")() {};
12
14
  function detectLocalPackages(bosConfig, runtimeConfig) {
13
15
  const packages = [];
14
16
  const configDir = getProjectRoot();
@@ -37,95 +39,72 @@ function buildRuntimeConfig(bosConfig, options) {
37
39
  plugins: options.plugins
38
40
  });
39
41
  }
40
- function probeTcpOpen(port, timeoutMs = 250) {
41
- return new Promise((resolve) => {
42
- const socket = createConnection({
43
- host: "127.0.0.1",
44
- port
42
+ function probePortBindable(port) {
43
+ return Effect.async((resume) => {
44
+ const server = createServer();
45
+ server.once("listening", () => {
46
+ server.close(() => {
47
+ resume(Effect.succeed(true));
48
+ });
45
49
  });
46
- const timer = setTimeout(() => {
47
- socket.destroy();
48
- resolve(false);
49
- }, timeoutMs);
50
- socket.once("connect", () => {
51
- clearTimeout(timer);
52
- socket.destroy();
53
- resolve(true);
54
- });
55
- socket.once("error", () => {
56
- clearTimeout(timer);
57
- resolve(false);
50
+ server.once("error", () => {
51
+ server.removeAllListeners();
52
+ resume(Effect.succeed(false));
58
53
  });
54
+ server.listen(port, "127.0.0.1");
55
+ const timer = setTimeout(() => {
56
+ server.removeAllListeners();
57
+ try {
58
+ server.close();
59
+ } catch {}
60
+ resume(Effect.succeed(false));
61
+ }, PROBE_TIMEOUT_MS);
62
+ server.once("listening", () => clearTimeout(timer));
63
+ server.once("error", () => clearTimeout(timer));
59
64
  });
60
65
  }
61
- async function pickAvailablePort(preferred, usedPorts) {
62
- let port = preferred;
63
- while (usedPorts.has(port) || await probeTcpOpen(port)) port += 1;
64
- usedPorts.add(port);
65
- return port;
66
- }
67
- function withLocalRuntimeUrl(entry, port) {
68
- const url = `http://localhost:${port}`;
69
- return {
70
- ...entry,
71
- url,
72
- entry: `${url}/mf-manifest.json`,
73
- port
74
- };
75
- }
76
- async function prepareDevelopmentRuntimeConfig(runtimeConfig, options) {
77
- const usedPorts = /* @__PURE__ */ new Set();
78
- const hostPort = await pickAvailablePort(options?.hostPort ?? DEFAULT_HOST_PORT, usedPorts);
79
- const next = {
80
- ...runtimeConfig,
81
- host: {
82
- ...runtimeConfig.host,
83
- url: `http://localhost:${hostPort}`,
84
- port: hostPort
85
- },
86
- ui: { ...runtimeConfig.ui },
87
- api: { ...runtimeConfig.api },
88
- auth: runtimeConfig.auth ? { ...runtimeConfig.auth } : void 0,
89
- plugins: runtimeConfig.plugins ? { ...runtimeConfig.plugins } : void 0
90
- };
91
- if (next.api.source === "local" && next.api.localPath) {
92
- const apiPort = await pickAvailablePort(next.api.port ?? DEFAULT_API_PORT, usedPorts);
93
- next.api = withLocalRuntimeUrl(next.api, apiPort);
94
- }
95
- if (next.auth?.source === "local" && next.auth.localPath) {
96
- const authPort = await pickAvailablePort(next.auth.port ?? DEFAULT_AUTH_PORT, usedPorts);
97
- next.auth = withLocalRuntimeUrl(next.auth, authPort);
98
- }
99
- if (next.ui.source === "local" && next.ui.localPath) {
100
- const uiPort = await pickAvailablePort(next.ui.port ?? DEFAULT_UI_PORT, usedPorts);
101
- next.ui = withLocalRuntimeUrl(next.ui, uiPort);
102
- if (options?.ssr) {
103
- const ssrPort = await pickAvailablePort(uiPort + 1, usedPorts);
104
- next.ui.ssrUrl = `http://localhost:${ssrPort}`;
105
- } else next.ui.ssrUrl = void 0;
106
- }
107
- if (next.plugins) {
108
- const entries = Object.entries(next.plugins).sort(([a], [b]) => a.localeCompare(b));
109
- let pluginBasePort = DEFAULT_PLUGIN_PORT_START;
110
- for (const [pluginId, plugin] of entries) {
111
- if (plugin.source === "local" && plugin.localPath) {
112
- const pluginPort = await pickAvailablePort(plugin.port ?? pluginBasePort, usedPorts);
113
- next.plugins[pluginId] = withLocalRuntimeUrl(plugin, pluginPort);
114
- pluginBasePort = pluginPort + 1;
66
+ function pickAvailablePort(preferred, usedPorts, budget) {
67
+ return Effect.gen(function* () {
68
+ const within = (candidate) => !budget || candidate >= budget.min && candidate <= budget.max;
69
+ let port = preferred;
70
+ if (!within(port)) port = budget ? budget.min : port;
71
+ const ceiling = budget ? budget.max + 1 : Number.MAX_SAFE_INTEGER;
72
+ let steps = 0;
73
+ const fail = () => Effect.fail(new PortAllocationError({
74
+ preferred,
75
+ budget,
76
+ cause: budget ? `No free port in budget [${budget.min}, ${budget.max}] starting from ${preferred}` : `No free port found starting from ${preferred} within ${MAX_PORT_SCAN_STEPS} steps`
77
+ }));
78
+ while (true) {
79
+ if (port >= ceiling || steps > MAX_PORT_SCAN_STEPS) yield* fail();
80
+ const candidates = [];
81
+ for (let i = 0; i < PARALLEL_PROBE_WINDOW && port + i < ceiling; i++) {
82
+ const candidate = port + i;
83
+ if (!usedPorts.has(candidate)) candidates.push(candidate);
84
+ }
85
+ if (candidates.length === 0) {
86
+ port += PARALLEL_PROBE_WINDOW;
87
+ steps += PARALLEL_PROBE_WINDOW;
88
+ continue;
115
89
  }
116
- if (plugin.ui?.source === "local" && plugin.ui.localPath) {
117
- const uiPort = await pickAvailablePort(plugin.ui.port ?? pluginBasePort, usedPorts);
118
- next.plugins[pluginId] = {
119
- ...next.plugins[pluginId],
120
- ui: withLocalRuntimeUrl(plugin.ui, uiPort)
121
- };
122
- pluginBasePort = uiPort + 1;
90
+ const firstFree = (yield* Effect.forEach(candidates, (c) => probePortBindable(c).pipe(Effect.map((free) => ({
91
+ port: c,
92
+ free
93
+ }))), { concurrency: "unbounded" })).find((r) => r.free);
94
+ if (firstFree) {
95
+ usedPorts.add(firstFree.port);
96
+ return firstFree.port;
123
97
  }
98
+ port += PARALLEL_PROBE_WINDOW;
99
+ steps += PARALLEL_PROBE_WINDOW;
124
100
  }
125
- }
126
- return next;
101
+ });
127
102
  }
103
+ const PortAllocatorLive = Layer.sync(PortAllocator, () => {
104
+ const usedPorts = claimedPorts();
105
+ return { pickAvailable: (preferred, budget) => pickAvailablePort(preferred, usedPorts, budget) };
106
+ });
128
107
 
129
108
  //#endregion
130
- export { buildRuntimeConfig, detectLocalPackages, prepareDevelopmentRuntimeConfig };
109
+ export { PortAllocator, PortAllocatorLive, buildRuntimeConfig, detectLocalPackages };
131
110
  //# sourceMappingURL=app.mjs.map
package/dist/app.mjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"app.mjs","names":["configBuildRuntimeConfig"],"sources":["../src/app.ts"],"sourcesContent":["import { existsSync } from \"node:fs\";\nimport { createConnection } from \"node:net\";\nimport { join } from \"node:path\";\nimport {\n buildRuntimeConfig as configBuildRuntimeConfig,\n getProjectRoot,\n resolveLocalDevelopmentPath,\n} from \"./config\";\nimport type { AppOrchestrator } from \"./service-descriptor\";\nimport type { BosConfig, RuntimeConfig, RuntimePluginConfig } from \"./types\";\n\nexport type { AppOrchestrator };\n\nconst DEFAULT_HOST_PORT = 3000;\nconst DEFAULT_API_PORT = 3001;\nconst DEFAULT_AUTH_PORT = 3002;\nconst DEFAULT_UI_PORT = 3003;\nconst DEFAULT_PLUGIN_PORT_START = 3010;\n\nexport function detectLocalPackages(\n bosConfig?: BosConfig,\n runtimeConfig?: RuntimeConfig,\n): string[] {\n const packages: string[] = [];\n const configDir = getProjectRoot();\n\n const uiLocalPath =\n runtimeConfig?.ui.localPath ??\n resolveLocalDevelopmentPath(bosConfig?.app.ui.development, configDir);\n if (uiLocalPath && existsSync(join(uiLocalPath, \"package.json\"))) {\n packages.push(\"ui\");\n }\n\n const apiLocalPath =\n runtimeConfig?.api.localPath ??\n resolveLocalDevelopmentPath(bosConfig?.app.api.development, configDir);\n if (apiLocalPath && existsSync(join(apiLocalPath, \"package.json\"))) {\n packages.push(\"api\");\n }\n\n const hostLocalPath =\n runtimeConfig?.host?.localPath ??\n resolveLocalDevelopmentPath(bosConfig?.app.host.development, configDir);\n if (hostLocalPath && existsSync(join(hostLocalPath, \"package.json\"))) {\n packages.push(\"host\");\n } else if (existsSync(join(configDir, \"host\", \"package.json\"))) {\n packages.push(\"host\");\n }\n\n for (const [pluginId, pluginConfig] of Object.entries(runtimeConfig?.plugins ?? {})) {\n if (pluginConfig.localPath && existsSync(join(pluginConfig.localPath, \"package.json\"))) {\n packages.push(`plugin:${pluginId}`);\n }\n if (pluginConfig.ui?.localPath && existsSync(join(pluginConfig.ui.localPath, \"package.json\"))) {\n packages.push(`plugin-ui:${pluginId}`);\n }\n }\n\n const authLocalPath =\n runtimeConfig?.auth?.localPath ??\n resolveLocalDevelopmentPath(bosConfig?.app.auth?.development, configDir);\n if (authLocalPath && existsSync(join(authLocalPath, \"package.json\"))) {\n packages.push(\"auth\");\n }\n\n return packages;\n}\n\nexport function buildRuntimeConfig(\n bosConfig: BosConfig,\n options: {\n hostSource?: \"local\" | \"remote\";\n uiSource?: \"local\" | \"remote\";\n apiSource?: \"local\" | \"remote\";\n authSource?: \"local\" | \"remote\";\n proxy?: string;\n env?: \"development\" | \"production\";\n plugins?: Record<string, RuntimePluginConfig>;\n },\n): RuntimeConfig {\n return configBuildRuntimeConfig(bosConfig, getProjectRoot(), options.env ?? \"development\", {\n hostSource: options.hostSource,\n uiSource: options.uiSource,\n apiSource: options.apiSource,\n authSource: options.authSource,\n proxy: options.proxy,\n plugins: options.plugins,\n });\n}\n\nfunction probeTcpOpen(port: number, timeoutMs = 250): Promise<boolean> {\n return new Promise((resolve) => {\n const socket = createConnection({ host: \"127.0.0.1\", port });\n const timer = setTimeout(() => {\n socket.destroy();\n resolve(false);\n }, timeoutMs);\n\n socket.once(\"connect\", () => {\n clearTimeout(timer);\n socket.destroy();\n resolve(true);\n });\n\n socket.once(\"error\", () => {\n clearTimeout(timer);\n resolve(false);\n });\n });\n}\n\nasync function pickAvailablePort(preferred: number, usedPorts: Set<number>): Promise<number> {\n let port = preferred;\n while (usedPorts.has(port) || (await probeTcpOpen(port))) {\n port += 1;\n }\n usedPorts.add(port);\n return port;\n}\n\nfunction withLocalRuntimeUrl<\n T extends { url: string; entry: string; port?: number; localPath?: string },\n>(entry: T, port: number): T {\n const url = `http://localhost:${port}`;\n return {\n ...entry,\n url,\n entry: `${url}/mf-manifest.json`,\n port,\n };\n}\n\nexport async function prepareDevelopmentRuntimeConfig(\n runtimeConfig: RuntimeConfig,\n options?: { hostPort?: number; ssr?: boolean },\n): Promise<RuntimeConfig> {\n const usedPorts = new Set<number>();\n const hostPort = await pickAvailablePort(options?.hostPort ?? DEFAULT_HOST_PORT, usedPorts);\n\n const next: RuntimeConfig = {\n ...runtimeConfig,\n host: { ...runtimeConfig.host, url: `http://localhost:${hostPort}`, port: hostPort },\n ui: { ...runtimeConfig.ui },\n api: { ...runtimeConfig.api },\n auth: runtimeConfig.auth ? { ...runtimeConfig.auth } : undefined,\n plugins: runtimeConfig.plugins ? { ...runtimeConfig.plugins } : undefined,\n };\n\n if (next.api.source === \"local\" && next.api.localPath) {\n const apiPort = await pickAvailablePort(next.api.port ?? DEFAULT_API_PORT, usedPorts);\n next.api = withLocalRuntimeUrl(next.api, apiPort);\n }\n\n if (next.auth?.source === \"local\" && next.auth.localPath) {\n const authPort = await pickAvailablePort(next.auth.port ?? DEFAULT_AUTH_PORT, usedPorts);\n next.auth = withLocalRuntimeUrl(next.auth, authPort);\n }\n\n if (next.ui.source === \"local\" && next.ui.localPath) {\n const uiPort = await pickAvailablePort(next.ui.port ?? DEFAULT_UI_PORT, usedPorts);\n next.ui = withLocalRuntimeUrl(next.ui, uiPort);\n if (options?.ssr) {\n const ssrPort = await pickAvailablePort(uiPort + 1, usedPorts);\n next.ui.ssrUrl = `http://localhost:${ssrPort}`;\n } else {\n next.ui.ssrUrl = undefined;\n }\n }\n\n if (next.plugins) {\n const entries = Object.entries(next.plugins).sort(([a], [b]) => a.localeCompare(b));\n let pluginBasePort = DEFAULT_PLUGIN_PORT_START;\n\n for (const [pluginId, plugin] of entries) {\n if (plugin.source === \"local\" && plugin.localPath) {\n const pluginPort = await pickAvailablePort(plugin.port ?? pluginBasePort, usedPorts);\n next.plugins[pluginId] = withLocalRuntimeUrl(plugin, pluginPort);\n pluginBasePort = pluginPort + 1;\n }\n\n if (plugin.ui?.source === \"local\" && plugin.ui.localPath) {\n const uiPort = await pickAvailablePort(plugin.ui.port ?? pluginBasePort, usedPorts);\n next.plugins[pluginId] = {\n ...next.plugins[pluginId]!,\n ui: withLocalRuntimeUrl(plugin.ui, uiPort),\n };\n pluginBasePort = uiPort + 1;\n }\n }\n }\n\n return next;\n}\n"],"mappings":";;;;;;AAaA,MAAM,oBAAoB;AAC1B,MAAM,mBAAmB;AAC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sourcesContent":["import { existsSync } from \"node:fs\";\nimport { createServer } from \"node:net\";\nimport { join } from \"node:path\";\nimport { Context, Data, Effect, Layer } from \"effect\";\nimport type { DevPortState } from \"./cli/infra\";\nimport {\n buildRuntimeConfig as configBuildRuntimeConfig,\n getProjectRoot,\n resolveLocalDevelopmentPath,\n} from \"./config\";\nimport { claimedPorts } from \"./process-registry\";\nimport type { AppOrchestrator } from \"./service-descriptor\";\nimport type { BosConfig, RuntimeConfig, RuntimePluginConfig } from \"./types\";\n\nexport type { AppOrchestrator };\n\nconst DEFAULT_HOST_PORT = 3000;\nconst DEFAULT_API_PORT = 3001;\nconst DEFAULT_AUTH_PORT = 3002;\nconst DEFAULT_UI_PORT = 3003;\nconst DEFAULT_PLUGIN_PORT_START = 3010;\n\nconst PROBE_TIMEOUT_MS = 250;\nconst MAX_PORT_SCAN_STEPS = 1000;\nconst PARALLEL_PROBE_WINDOW = 8;\n\nexport type PortBudget = { min: number; max: number };\n\nexport class PortAllocationError extends Data.TaggedError(\"PortAllocationError\")<{\n preferred: number;\n budget?: PortBudget;\n cause?: unknown;\n}> {}\n\nexport class PortAllocator extends Context.Tag(\"PortAllocator\")<\n PortAllocator,\n {\n pickAvailable: (\n preferred: number,\n budget?: PortBudget,\n ) => Effect.Effect<number, PortAllocationError>;\n }\n>() {}\n\nexport function detectLocalPackages(\n bosConfig?: BosConfig,\n runtimeConfig?: RuntimeConfig,\n): string[] {\n const packages: string[] = [];\n const configDir = getProjectRoot();\n\n const uiLocalPath =\n runtimeConfig?.ui.localPath ??\n resolveLocalDevelopmentPath(bosConfig?.app.ui.development, configDir);\n if (uiLocalPath && existsSync(join(uiLocalPath, \"package.json\"))) {\n packages.push(\"ui\");\n }\n\n const apiLocalPath =\n runtimeConfig?.api.localPath ??\n resolveLocalDevelopmentPath(bosConfig?.app.api.development, configDir);\n if (apiLocalPath && existsSync(join(apiLocalPath, \"package.json\"))) {\n packages.push(\"api\");\n }\n\n const hostLocalPath =\n runtimeConfig?.host?.localPath ??\n resolveLocalDevelopmentPath(bosConfig?.app.host.development, configDir);\n if (hostLocalPath && existsSync(join(hostLocalPath, \"package.json\"))) {\n packages.push(\"host\");\n } else if (existsSync(join(configDir, \"host\", \"package.json\"))) {\n packages.push(\"host\");\n }\n\n for (const [pluginId, pluginConfig] of Object.entries(runtimeConfig?.plugins ?? {})) {\n if (pluginConfig.localPath && existsSync(join(pluginConfig.localPath, \"package.json\"))) {\n packages.push(`plugin:${pluginId}`);\n }\n if (pluginConfig.ui?.localPath && existsSync(join(pluginConfig.ui.localPath, \"package.json\"))) {\n packages.push(`plugin-ui:${pluginId}`);\n }\n }\n\n const authLocalPath =\n runtimeConfig?.auth?.localPath ??\n resolveLocalDevelopmentPath(bosConfig?.app.auth?.development, configDir);\n if (authLocalPath && existsSync(join(authLocalPath, \"package.json\"))) {\n packages.push(\"auth\");\n }\n\n return packages;\n}\n\nexport function buildRuntimeConfig(\n bosConfig: BosConfig,\n options: {\n hostSource?: \"local\" | \"remote\";\n uiSource?: \"local\" | \"remote\";\n apiSource?: \"local\" | \"remote\";\n authSource?: \"local\" | \"remote\";\n proxy?: string;\n env?: \"development\" | \"production\";\n plugins?: Record<string, RuntimePluginConfig>;\n },\n): RuntimeConfig {\n return configBuildRuntimeConfig(bosConfig, getProjectRoot(), options.env ?? \"development\", {\n hostSource: options.hostSource,\n uiSource: options.uiSource,\n apiSource: options.apiSource,\n authSource: options.authSource,\n proxy: options.proxy,\n plugins: options.plugins,\n });\n}\n\nfunction probePortBindable(port: number): Effect.Effect<boolean> {\n return Effect.async<boolean>((resume) => {\n const server = createServer();\n\n server.once(\"listening\", () => {\n server.close(() => {\n resume(Effect.succeed(true));\n });\n });\n\n server.once(\"error\", () => {\n server.removeAllListeners();\n // EADDRINUSE, EACCES, or any other bind error → not available\n resume(Effect.succeed(false));\n });\n\n server.listen(port, \"127.0.0.1\");\n\n const timer = setTimeout(() => {\n server.removeAllListeners();\n try {\n server.close();\n } catch {\n // ignore\n }\n resume(Effect.succeed(false));\n }, PROBE_TIMEOUT_MS);\n\n server.once(\"listening\", () => clearTimeout(timer));\n server.once(\"error\", () => clearTimeout(timer));\n });\n}\n\nfunction pickAvailablePort(\n preferred: number,\n usedPorts: Set<number>,\n budget?: PortBudget,\n): Effect.Effect<number, PortAllocationError> {\n return Effect.gen(function* () {\n const within = (candidate: number): boolean =>\n !budget || (candidate >= budget.min && candidate <= budget.max);\n\n let port = preferred;\n if (!within(port)) {\n port = budget ? budget.min : port;\n }\n\n const ceiling = budget ? budget.max + 1 : Number.MAX_SAFE_INTEGER;\n let steps = 0;\n\n const fail = () =>\n Effect.fail(\n new PortAllocationError({\n preferred,\n budget,\n cause: budget\n ? `No free port in budget [${budget.min}, ${budget.max}] starting from ${preferred}`\n : `No free port found starting from ${preferred} within ${MAX_PORT_SCAN_STEPS} steps`,\n }),\n );\n\n while (true) {\n if (port >= ceiling || steps > MAX_PORT_SCAN_STEPS) {\n yield* fail();\n }\n\n const candidates: number[] = [];\n for (let i = 0; i < PARALLEL_PROBE_WINDOW && port + i < ceiling; i++) {\n const candidate = port + i;\n if (!usedPorts.has(candidate)) {\n candidates.push(candidate);\n }\n }\n\n if (candidates.length === 0) {\n port += PARALLEL_PROBE_WINDOW;\n steps += PARALLEL_PROBE_WINDOW;\n continue;\n }\n\n const results = yield* Effect.forEach(\n candidates,\n (c) => probePortBindable(c).pipe(Effect.map((free) => ({ port: c, free }))),\n { concurrency: \"unbounded\" },\n );\n\n const firstFree = results.find((r) => r.free);\n if (firstFree) {\n usedPorts.add(firstFree.port);\n return firstFree.port;\n }\n\n port += PARALLEL_PROBE_WINDOW;\n steps += PARALLEL_PROBE_WINDOW;\n }\n });\n}\n\nexport const PortAllocatorLive: Layer.Layer<PortAllocator> = Layer.sync(PortAllocator, () => {\n const usedPorts = claimedPorts();\n return {\n pickAvailable: (preferred, budget) => pickAvailablePort(preferred, usedPorts, budget),\n };\n});\n\nfunction withLocalRuntimeUrl<\n T extends { url: string; entry: string; port?: number; localPath?: string },\n>(entry: T, port: number): T {\n const url = `http://localhost:${port}`;\n return {\n ...entry,\n url,\n entry: `${url}/mf-manifest.json`,\n port,\n };\n}\n\nexport interface DevPortOptions {\n hostPort?: number;\n apiPort?: number;\n uiPort?: number;\n authPort?: number;\n pluginPortStart?: number;\n ssr?: boolean;\n portBudget?: PortBudget;\n}\n\nexport interface PreparedDevRuntime {\n runtimeConfig: RuntimeConfig;\n devPorts: DevPortState;\n}\n\nexport function prepareDevelopmentRuntimeConfig(\n runtimeConfig: RuntimeConfig,\n options?: DevPortOptions,\n): Effect.Effect<PreparedDevRuntime, PortAllocationError, PortAllocator> {\n return Effect.gen(function* () {\n const allocator = yield* PortAllocator;\n const budget = options?.portBudget;\n\n const pickedHostPort = yield* allocator.pickAvailable(\n options?.hostPort ?? DEFAULT_HOST_PORT,\n budget,\n );\n\n const hostIsLocal = runtimeConfig.host.source === \"local\";\n const next: RuntimeConfig = {\n ...runtimeConfig,\n host: hostIsLocal\n ? {\n ...runtimeConfig.host,\n url: `http://localhost:${pickedHostPort}`,\n port: pickedHostPort,\n }\n : { ...runtimeConfig.host },\n ui: { ...runtimeConfig.ui },\n api: { ...runtimeConfig.api },\n auth: runtimeConfig.auth ? { ...runtimeConfig.auth } : undefined,\n plugins: runtimeConfig.plugins ? { ...runtimeConfig.plugins } : undefined,\n };\n\n const devPorts: DevPortState = {\n host: hostIsLocal ? pickedHostPort : undefined,\n api: undefined,\n ui: undefined,\n auth: undefined,\n pluginPortStart: undefined,\n };\n\n if (next.api.source === \"local\" && next.api.localPath) {\n const apiPort = yield* allocator.pickAvailable(\n options?.apiPort ?? next.api.port ?? DEFAULT_API_PORT,\n budget,\n );\n next.api = withLocalRuntimeUrl(next.api, apiPort);\n devPorts.api = apiPort;\n }\n\n if (next.auth?.source === \"local\" && next.auth.localPath) {\n const authPort = yield* allocator.pickAvailable(\n options?.authPort ?? next.auth.port ?? DEFAULT_AUTH_PORT,\n budget,\n );\n next.auth = withLocalRuntimeUrl(next.auth, authPort);\n devPorts.auth = authPort;\n }\n\n if (next.ui.source === \"local\" && next.ui.localPath) {\n const uiPort = yield* allocator.pickAvailable(\n options?.uiPort ?? next.ui.port ?? DEFAULT_UI_PORT,\n budget,\n );\n next.ui = withLocalRuntimeUrl(next.ui, uiPort);\n devPorts.ui = uiPort;\n if (options?.ssr) {\n const ssrPort = yield* allocator.pickAvailable(uiPort + 1, budget);\n next.ui.ssrUrl = `http://localhost:${ssrPort}`;\n } else {\n next.ui.ssrUrl = undefined;\n }\n }\n\n if (next.plugins) {\n const entries = Object.entries(next.plugins).sort(([a], [b]) => a.localeCompare(b));\n let pluginBasePort = options?.pluginPortStart ?? DEFAULT_PLUGIN_PORT_START;\n let firstLocalPluginPort: number | undefined;\n\n for (const [pluginId, plugin] of entries) {\n if (plugin.source === \"local\" && plugin.localPath) {\n const pluginPort = yield* allocator.pickAvailable(plugin.port ?? pluginBasePort, budget);\n next.plugins[pluginId] = withLocalRuntimeUrl(plugin, pluginPort);\n if (firstLocalPluginPort === undefined) firstLocalPluginPort = pluginPort;\n pluginBasePort = pluginPort + 1;\n }\n\n if (plugin.ui?.source === \"local\" && plugin.ui.localPath) {\n const pluginUiPort = yield* allocator.pickAvailable(\n plugin.ui.port ?? pluginBasePort,\n budget,\n );\n next.plugins[pluginId] = {\n ...next.plugins[pluginId]!,\n ui: withLocalRuntimeUrl(plugin.ui, pluginUiPort),\n };\n if (firstLocalPluginPort === undefined) firstLocalPluginPort = pluginUiPort;\n pluginBasePort = pluginUiPort + 1;\n }\n }\n\n devPorts.pluginPortStart = firstLocalPluginPort;\n }\n\n return { runtimeConfig: next, devPorts };\n });\n}\n"],"mappings":";;;;;;;;AAsBA,MAAM,mBAAmB;AACzB,MAAM,sBAAsB;AAC5B,MAAM,wBAAwB;AAI9B,IAAa,sBAAb,cAAyC,KAAK,YAAY,sBAAsB,CAI7E;AAEH,IAAa,gBAAb,cAAmC,QAAQ,IAAI,gBAAgB,EAQ5D,CAAC;AAEJ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AU,CAC3B,YAAW,KAAK,UAAU;;AAI9B,OAAI,WAAW,WAAW,GAAG;AAC3B,YAAQ;AACR,aAAS;AACT;;GASF,MAAM,aAAY,OANK,OAAO,QAC5B,aACC,MAAM,kBAAkB,EAAE,CAAC,KAAK,OAAO,KAAK,UAAU;IAAE,MAAM;IAAG;IAAM,EAAE,CAAC,EAC3E,EAAE,aAAa,aAAa,CAC7B,EAEyB,MAAM,MAAM,EAAE,KAAK;AAC7C,OAAI,WAAW;AACb,cAAU,IAAI,UAAU,KAAK;AAC7B,WAAO,UAAU;;AAGnB,WAAQ;AACR,YAAS;;GAEX;;AAGJ,MAAa,oBAAgD,MAAM,KAAK,qBAAqB;CAC3F,MAAM,YAAY,cAAc;AAChC,QAAO,EACL,gBAAgB,WAAW,WAAW,kBAAkB,WAAW,WAAW,OAAO,EACtF;EACD"}
@@ -31,8 +31,9 @@ function readLocalMigrations(workspaceDir) {
31
31
  async function diagnosePlugin(info) {
32
32
  const { Pool } = await Promise.resolve().then(() => require("../node_modules/pg/esm/index.cjs"));
33
33
  const slug = require_db.pluginMigrationSlug(info.key);
34
- const journalTable = `__drizzle_migrations_${slug}`;
35
- const journalSchema = "drizzle";
34
+ const storage = require_db.getMigrationStorage(slug);
35
+ const journalTable = storage.table;
36
+ const journalSchema = storage.schema;
36
37
  const journalRef = `"${journalSchema}"."${journalTable}"`;
37
38
  const localMigrations = info.workspaceDir ? readLocalMigrations(info.workspaceDir) : [];
38
39
  const expectedTables = require_db.extractExpectedTables(localMigrations);
@@ -63,10 +64,10 @@ async function diagnosePlugin(info) {
63
64
  const existing = new Set(tableResult.rows.map((r) => r.table_name));
64
65
  missingTables = expectedTables.filter((t) => !existing.has(t));
65
66
  }
66
- const legacyCount = await countLegacyHashes(pool, localHashes);
67
67
  let diagnosis;
68
68
  if (localMigrations.length === 0) diagnosis = "no-local-migrations";
69
- else if (appliedHashCount === 0 && localHashes.length > 0) diagnosis = legacyCount > 0 ? "legacy-importable" : "unapplied";
69
+ else if (appliedHashCount === 0 && missingTables.length === 0 && localHashes.length > 0) diagnosis = "untracked-existing-schema";
70
+ else if (appliedHashCount === 0 && localHashes.length > 0) diagnosis = "unapplied";
70
71
  else if (missingTables.length === 0) diagnosis = "healthy";
71
72
  else if (missingTables.length === expectedTables.length) diagnosis = "drift-safe-repair";
72
73
  else diagnosis = "drift-manual";
@@ -84,8 +85,7 @@ async function diagnosePlugin(info) {
84
85
  expectedTables,
85
86
  missingTables,
86
87
  migrationHashes,
87
- diagnosis,
88
- legacyCount
88
+ diagnosis
89
89
  };
90
90
  } catch (error) {
91
91
  return {
@@ -102,29 +102,12 @@ async function diagnosePlugin(info) {
102
102
  missingTables: [],
103
103
  migrationHashes: [],
104
104
  diagnosis: "error",
105
- legacyCount: 0,
106
105
  error: error instanceof Error ? error.message : String(error)
107
106
  };
108
107
  } finally {
109
108
  await pool.end().catch(() => {});
110
109
  }
111
110
  }
112
- async function countLegacyHashes(pool, localHashes) {
113
- if (localHashes.length === 0) return 0;
114
- const candidates = [{
115
- schema: "drizzle",
116
- table: "__drizzle_migrations"
117
- }, {
118
- schema: "public",
119
- table: "drizzle_migrations"
120
- }];
121
- let total = 0;
122
- for (const c of candidates) try {
123
- const result = await pool.query(`SELECT count(*)::int AS cnt FROM "${c.schema}"."${c.table}" WHERE hash = ANY($1)`, [localHashes]);
124
- total += result.rows[0]?.cnt ?? 0;
125
- } catch {}
126
- return total;
127
- }
128
111
 
129
112
  //#endregion
130
113
  exports.diagnosePlugin = diagnosePlugin;
@@ -1 +1 @@
1
- {"version":3,"file":"db-doctor.cjs","names":["pluginMigrationSlug","extractExpectedTables"],"sources":["../../src/cli/db-doctor.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { join, resolve } from \"node:path\";\nimport { extractExpectedTables, pluginMigrationSlug } from \"../db\";\nimport type { PluginDbInfo } from \"./db-studio\";\n\nexport interface DoctorReport {\n plugin: string;\n slug: string;\n journalTable: string;\n journalSchema: string;\n dbSecret: string;\n dbUrl: string;\n workspaceDir: string | undefined;\n localMigrationCount: number;\n appliedHashCount: number;\n expectedTables: string[];\n missingTables: string[];\n migrationHashes: string[];\n diagnosis: string;\n legacyCount: number;\n error?: string;\n}\n\nfunction hashFile(raw: string): string {\n return createHash(\"sha256\").update(raw).digest(\"hex\");\n}\n\ninterface LocalMigration {\n tag: string;\n hash: string;\n sql: string[];\n}\n\nfunction readLocalMigrations(workspaceDir: string): LocalMigration[] {\n const migrationsDir = resolve(workspaceDir, \"src/db/migrations\");\n const metaDir = join(migrationsDir, \"meta\");\n const journalPath = join(metaDir, \"_journal.json\");\n if (!existsSync(journalPath)) return [];\n\n const journal = JSON.parse(readFileSync(journalPath, \"utf8\")) as {\n entries: { idx: number; tag: string }[];\n };\n\n return journal.entries.map((entry) => {\n const sqlPath = join(migrationsDir, `${entry.tag}.sql`);\n if (!existsSync(sqlPath)) {\n return { tag: entry.tag, hash: \"\", sql: [] };\n }\n const raw = readFileSync(sqlPath, \"utf8\");\n const sql = raw.split(\"--> statement-breakpoint\").map((s) => s.trim());\n return { tag: entry.tag, hash: hashFile(raw), sql };\n });\n}\n\nexport async function diagnosePlugin(info: PluginDbInfo): Promise<DoctorReport> {\n const { Pool } = await import(\"pg\");\n\n const slug = pluginMigrationSlug(info.key);\n const journalTable = `__drizzle_migrations_${slug}`;\n const journalSchema = \"drizzle\";\n const journalRef = `\"${journalSchema}\".\"${journalTable}\"`;\n\n const localMigrations = info.workspaceDir ? readLocalMigrations(info.workspaceDir) : [];\n\n const expectedTables = extractExpectedTables(localMigrations);\n const localHashes = localMigrations.map((m) => m.hash).filter(Boolean);\n const migrationHashes = localHashes;\n\n const pool = new Pool({\n connectionString: info.databaseUrl,\n ssl:\n info.databaseUrl.includes(\"localhost\") || info.databaseUrl.includes(\"127.0.0.1\")\n ? false\n : { rejectUnauthorized: false },\n max: 1,\n connectionTimeoutMillis: 10_000,\n });\n\n try {\n const journalExists = await pool.query(`\n SELECT EXISTS (\n SELECT 1 FROM information_schema.tables\n WHERE table_schema = '${journalSchema}' AND table_name = '${journalTable}'\n ) AS exists\n `);\n\n let appliedHashCount = 0;\n if (journalExists.rows[0]?.exists) {\n const result = await pool.query(`SELECT hash FROM ${journalRef}`);\n appliedHashCount = result.rows.length;\n }\n\n let missingTables: string[] = [];\n if (expectedTables.length > 0) {\n const tableResult = await pool.query(\n `\n SELECT table_name FROM information_schema.tables\n WHERE table_schema = 'public'\n AND table_name = ANY($1)\n `,\n [expectedTables],\n );\n const existing = new Set(tableResult.rows.map((r: any) => r.table_name));\n missingTables = expectedTables.filter((t) => !existing.has(t));\n }\n\n const legacyCount = await countLegacyHashes(pool, localHashes);\n\n let diagnosis: string;\n if (localMigrations.length === 0) {\n diagnosis = \"no-local-migrations\";\n } else if (appliedHashCount === 0 && localHashes.length > 0) {\n diagnosis = legacyCount > 0 ? \"legacy-importable\" : \"unapplied\";\n } else if (missingTables.length === 0) {\n diagnosis = \"healthy\";\n } else if (missingTables.length === expectedTables.length) {\n diagnosis = \"drift-safe-repair\";\n } else {\n diagnosis = \"drift-manual\";\n }\n\n const masked = info.databaseUrl.replace(/\\/\\/[^:]+:[^@]+@/, \"//***:***@\");\n\n return {\n plugin: info.key,\n slug,\n journalTable,\n journalSchema,\n dbSecret: info.databaseSecret,\n dbUrl: masked,\n workspaceDir: info.workspaceDir,\n localMigrationCount: localMigrations.length,\n appliedHashCount,\n expectedTables,\n missingTables,\n migrationHashes,\n diagnosis,\n legacyCount,\n };\n } catch (error) {\n return {\n plugin: info.key,\n slug,\n journalTable,\n journalSchema,\n dbSecret: info.databaseSecret,\n dbUrl: info.databaseUrl.replace(/\\/\\/[^:]+:[^@]+@/, \"//***:***@\"),\n workspaceDir: info.workspaceDir,\n localMigrationCount: localMigrations.length,\n appliedHashCount: 0,\n expectedTables,\n missingTables: [],\n migrationHashes: [],\n diagnosis: \"error\",\n legacyCount: 0,\n error: error instanceof Error ? error.message : String(error),\n };\n } finally {\n await pool.end().catch(() => {});\n }\n}\n\nasync function countLegacyHashes(pool: any, localHashes: string[]): Promise<number> {\n if (localHashes.length === 0) return 0;\n const candidates = [\n { schema: \"drizzle\", table: \"__drizzle_migrations\" },\n { schema: \"public\", table: \"drizzle_migrations\" },\n ];\n let total = 0;\n for (const c of candidates) {\n try {\n const result = await pool.query(\n `SELECT count(*)::int AS cnt FROM \"${c.schema}\".\"${c.table}\" WHERE hash = ANY($1)`,\n [localHashes],\n );\n total += result.rows[0]?.cnt ?? 0;\n } catch {\n // table might not exist\n }\n }\n return total;\n}\n"],"mappings":";;;;;;;AAwBA,SAAS,SAAS,KAAqB;AACrC,oCAAkB,SAAS,CAAC,OAAO,IAAI,CAAC,OAAO,MAAM;;AASvD,SAAS,oBAAoB,cAAwC;CACnE,MAAM,uCAAwB,cAAc,oBAAoB;CAEhE,MAAM,sDADe,eAAe,OACJ,EAAE,gBAAgB;AAClD,KAAI,yBAAY,YAAY,CAAE,QAAO,EAAE;AAMvC,QAJgB,KAAK,gCAAmB,aAAa,OAAO,CAI9C,CAAC,QAAQ,KAAK,UAAU;EACpC,MAAM,8BAAe,eAAe,GAAG,MAAM,IAAI,MAAM;AACvD,MAAI,yBAAY,QAAQ,CACtB,QAAO;GAAE,KAAK,MAAM;GAAK,MAAM;GAAI,KAAK,EAAE;GAAE;EAE9C,MAAM,gCAAmB,SAAS,OAAO;EACzC,MAAM,MAAM,IAAI,MAAM,2BAA2B,CAAC,KAAK,MAAM,EAAE,MAAM,CAAC;AACtE,SAAO;GAAE,KAAK,MAAM;GAAK,MAAM,SAAS,IAAI;GAAE;GAAK;GACnD;;AAGJ,eAAsB,eAAe,MAA2C;CAC9E,MAAM,EAAE,SAAS,2CAAM;CAEvB,MAAM,OAAOA,+BAAoB,KAAK,IAAI;CAC1C,MAAM,eAAe,wBAAwB;CAC7C,MAAM,gBAAgB;CACtB,MAAM,aAAa,IAAI,cAAc,KAAK,aAAa;CAEvD,MAAM,kBAAkB,KAAK,eAAe,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A;GACA;GACA;GACD;UACM,OAAO;AACd,SAAO;GACL,QAAQ,KAAK;GACb;GACA;GACA;GACA,UAAU,KAAK;GACf,OAAO,KAAK,YAAY,QAAQ,oBAAoB,aAAa;GACjE,cAAc,KAAK;GACnB,qBAAqB,gBAAgB;GACrC,kBAAkB;GAClB;GACA,eAAe,EAAE;GACjB,iBAAiB,EAAE;GACnB,WAAW;GACX,aAAa;GACb,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM;GAC9D;WACO;AACR,QAAM,KAAK,KAAK,CAAC,YAAY,GAAG;;;AAIpC,eAAe,kBAAkB,MAAW,aAAwC;AAClF,KAAI,YAAY,WAAW,EAAG,QAAO;CACrC,MAAM,aAAa,CACjB;EAAE,QAAQ;EAAW,OAAO;EAAwB,EACpD;EAAE,QAAQ;EAAU,OAAO;EAAsB,CAClD;CACD,IAAI,QAAQ;AACZ,MAAK,MAAM,KAAK,WACd,KAAI;EACF,MAAM,SAAS,MAAM,KAAK,MACxB,qCAAqC,EAAE,OAAO,KAAK,EAAE,MAAM,yBAC3D,CAAC,YAAY,CACd;AACD,WAAS,OAAO,KAAK,IAAI,OAAO;SAC1B;AAIV,QAAO"}
1
+ {"version":3,"file":"db-doctor.cjs","names":["pluginMigrationSlug","getMigrationStorage","extractExpectedTables"],"sources":["../../src/cli/db-doctor.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { join, resolve } from \"node:path\";\nimport { extractExpectedTables, getMigrationStorage, pluginMigrationSlug } from \"../db\";\nimport type { PluginDbInfo } from \"./db-studio\";\n\nexport interface DoctorReport {\n plugin: string;\n slug: string;\n journalTable: string;\n journalSchema: string;\n dbSecret: string;\n dbUrl: string;\n workspaceDir: string | undefined;\n localMigrationCount: number;\n appliedHashCount: number;\n expectedTables: string[];\n missingTables: string[];\n migrationHashes: string[];\n diagnosis: string;\n error?: string;\n}\n\nfunction hashFile(raw: string): string {\n return createHash(\"sha256\").update(raw).digest(\"hex\");\n}\n\ninterface LocalMigration {\n tag: string;\n hash: string;\n sql: string[];\n}\n\nfunction readLocalMigrations(workspaceDir: string): LocalMigration[] {\n const migrationsDir = resolve(workspaceDir, \"src/db/migrations\");\n const metaDir = join(migrationsDir, \"meta\");\n const journalPath = join(metaDir, \"_journal.json\");\n if (!existsSync(journalPath)) return [];\n\n const journal = JSON.parse(readFileSync(journalPath, \"utf8\")) as {\n entries: { idx: number; tag: string }[];\n };\n\n return journal.entries.map((entry) => {\n const sqlPath = join(migrationsDir, `${entry.tag}.sql`);\n if (!existsSync(sqlPath)) {\n return { tag: entry.tag, hash: \"\", sql: [] };\n }\n const raw = readFileSync(sqlPath, \"utf8\");\n const sql = raw.split(\"--> statement-breakpoint\").map((s) => s.trim());\n return { tag: entry.tag, hash: hashFile(raw), sql };\n });\n}\n\nexport async function diagnosePlugin(info: PluginDbInfo): Promise<DoctorReport> {\n const { Pool } = await import(\"pg\");\n\n const slug = pluginMigrationSlug(info.key);\n const storage = getMigrationStorage(slug);\n const journalTable = storage.table;\n const journalSchema = storage.schema;\n const journalRef = `\"${journalSchema}\".\"${journalTable}\"`;\n\n const localMigrations = info.workspaceDir ? readLocalMigrations(info.workspaceDir) : [];\n\n const expectedTables = extractExpectedTables(localMigrations);\n const localHashes = localMigrations.map((m) => m.hash).filter(Boolean);\n const migrationHashes = localHashes;\n\n const pool = new Pool({\n connectionString: info.databaseUrl,\n ssl:\n info.databaseUrl.includes(\"localhost\") || info.databaseUrl.includes(\"127.0.0.1\")\n ? false\n : { rejectUnauthorized: false },\n max: 1,\n connectionTimeoutMillis: 10_000,\n });\n\n try {\n const journalExists = await pool.query(`\n SELECT EXISTS (\n SELECT 1 FROM information_schema.tables\n WHERE table_schema = '${journalSchema}' AND table_name = '${journalTable}'\n ) AS exists\n `);\n\n let appliedHashCount = 0;\n if (journalExists.rows[0]?.exists) {\n const result = await pool.query(`SELECT hash FROM ${journalRef}`);\n appliedHashCount = result.rows.length;\n }\n\n let missingTables: string[] = [];\n if (expectedTables.length > 0) {\n const tableResult = await pool.query(\n `\n SELECT table_name FROM information_schema.tables\n WHERE table_schema = 'public'\n AND table_name = ANY($1)\n `,\n [expectedTables],\n );\n const existing = new Set(tableResult.rows.map((r: any) => r.table_name));\n missingTables = expectedTables.filter((t) => !existing.has(t));\n }\n\n let diagnosis: string;\n if (localMigrations.length === 0) {\n diagnosis = \"no-local-migrations\";\n } else if (appliedHashCount === 0 && missingTables.length === 0 && localHashes.length > 0) {\n // Journal is empty but all expected public tables exist.\n diagnosis = \"untracked-existing-schema\";\n } else if (appliedHashCount === 0 && localHashes.length > 0) {\n diagnosis = \"unapplied\";\n } else if (missingTables.length === 0) {\n diagnosis = \"healthy\";\n } else if (missingTables.length === expectedTables.length) {\n diagnosis = \"drift-safe-repair\";\n } else {\n diagnosis = \"drift-manual\";\n }\n\n const masked = info.databaseUrl.replace(/\\/\\/[^:]+:[^@]+@/, \"//***:***@\");\n\n return {\n plugin: info.key,\n slug,\n journalTable,\n journalSchema,\n dbSecret: info.databaseSecret,\n dbUrl: masked,\n workspaceDir: info.workspaceDir,\n localMigrationCount: localMigrations.length,\n appliedHashCount,\n expectedTables,\n missingTables,\n migrationHashes,\n diagnosis,\n };\n } catch (error) {\n return {\n plugin: info.key,\n slug,\n journalTable,\n journalSchema,\n dbSecret: info.databaseSecret,\n dbUrl: info.databaseUrl.replace(/\\/\\/[^:]+:[^@]+@/, \"//***:***@\"),\n workspaceDir: info.workspaceDir,\n localMigrationCount: localMigrations.length,\n appliedHashCount: 0,\n expectedTables,\n missingTables: [],\n migrationHashes: [],\n diagnosis: \"error\",\n error: error instanceof Error ? error.message : String(error),\n };\n } finally {\n await pool.end().catch(() => {});\n }\n}\n"],"mappings":";;;;;;;AAuBA,SAAS,SAAS,KAAqB;AACrC,oCAAkB,SAAS,CAAC,OAAO,IAAI,CAAC,OAAO,MAAM;;AASvD,SAAS,oBAAoB,cAAwC;CACnE,MAAM,uCAAwB,cAAc,oBA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