everything-dev 0.3.3 → 1.3.3

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 (313) hide show
  1. package/README.md +64 -0
  2. package/cli.js +10 -0
  3. package/dist/_virtual/_rolldown/runtime.cjs +29 -0
  4. package/dist/api-contract.cjs +172 -0
  5. package/dist/api-contract.cjs.map +1 -0
  6. package/dist/api-contract.mjs +171 -0
  7. package/dist/api-contract.mjs.map +1 -0
  8. package/dist/api.cjs +124 -0
  9. package/dist/api.cjs.map +1 -0
  10. package/dist/api.d.cts +36 -0
  11. package/dist/api.d.cts.map +1 -0
  12. package/dist/api.d.mts +36 -0
  13. package/dist/api.d.mts.map +1 -0
  14. package/dist/api.mjs +119 -0
  15. package/dist/api.mjs.map +1 -0
  16. package/dist/app.cjs +156 -0
  17. package/dist/app.cjs.map +1 -0
  18. package/dist/app.mjs +153 -0
  19. package/dist/app.mjs.map +1 -0
  20. package/dist/cli/catalog.cjs +30 -0
  21. package/dist/cli/catalog.cjs.map +1 -0
  22. package/dist/cli/catalog.mjs +29 -0
  23. package/dist/cli/catalog.mjs.map +1 -0
  24. package/dist/cli/help.cjs +16 -0
  25. package/dist/cli/help.cjs.map +1 -0
  26. package/dist/cli/help.mjs +16 -0
  27. package/dist/cli/help.mjs.map +1 -0
  28. package/dist/cli/init.cjs +287 -0
  29. package/dist/cli/init.cjs.map +1 -0
  30. package/dist/cli/init.d.cts +36 -0
  31. package/dist/cli/init.d.cts.map +1 -0
  32. package/dist/cli/init.d.mts +36 -0
  33. package/dist/cli/init.d.mts.map +1 -0
  34. package/dist/cli/init.mjs +279 -0
  35. package/dist/cli/init.mjs.map +1 -0
  36. package/dist/cli/parse.cjs +96 -0
  37. package/dist/cli/parse.cjs.map +1 -0
  38. package/dist/cli/parse.mjs +95 -0
  39. package/dist/cli/parse.mjs.map +1 -0
  40. package/dist/cli/prompts.cjs +42 -0
  41. package/dist/cli/prompts.cjs.map +1 -0
  42. package/dist/cli/prompts.mjs +41 -0
  43. package/dist/cli/prompts.mjs.map +1 -0
  44. package/dist/cli.cjs +167 -0
  45. package/dist/cli.cjs.map +1 -0
  46. package/dist/cli.d.cts +1 -0
  47. package/dist/cli.d.mts +1 -0
  48. package/dist/cli.mjs +166 -0
  49. package/dist/cli.mjs.map +1 -0
  50. package/dist/components/dev-view.cjs +307 -0
  51. package/dist/components/dev-view.cjs.map +1 -0
  52. package/dist/components/dev-view.mjs +306 -0
  53. package/dist/components/dev-view.mjs.map +1 -0
  54. package/dist/components/streaming-view.cjs +146 -0
  55. package/dist/components/streaming-view.cjs.map +1 -0
  56. package/dist/components/streaming-view.mjs +144 -0
  57. package/dist/components/streaming-view.mjs.map +1 -0
  58. package/dist/config.cjs +280 -0
  59. package/dist/config.cjs.map +1 -0
  60. package/dist/config.d.cts +35 -0
  61. package/dist/config.d.cts.map +1 -0
  62. package/dist/config.d.mts +35 -0
  63. package/dist/config.d.mts.map +1 -0
  64. package/dist/config.mjs +266 -0
  65. package/dist/config.mjs.map +1 -0
  66. package/dist/contract.cjs +209 -0
  67. package/dist/contract.cjs.map +1 -0
  68. package/dist/contract.d.cts +490 -0
  69. package/dist/contract.d.cts.map +1 -0
  70. package/dist/contract.d.mts +490 -0
  71. package/dist/contract.d.mts.map +1 -0
  72. package/dist/contract.meta.cjs +104 -0
  73. package/dist/contract.meta.cjs.map +1 -0
  74. package/dist/contract.meta.d.cts +141 -0
  75. package/dist/contract.meta.d.cts.map +1 -0
  76. package/dist/contract.meta.d.mts +141 -0
  77. package/dist/contract.meta.d.mts.map +1 -0
  78. package/dist/contract.meta.mjs +102 -0
  79. package/dist/contract.meta.mjs.map +1 -0
  80. package/dist/contract.mjs +186 -0
  81. package/dist/contract.mjs.map +1 -0
  82. package/dist/dev-logs.cjs +53 -0
  83. package/dist/dev-logs.cjs.map +1 -0
  84. package/dist/dev-logs.mjs +51 -0
  85. package/dist/dev-logs.mjs.map +1 -0
  86. package/dist/dev-session.cjs +195 -0
  87. package/dist/dev-session.cjs.map +1 -0
  88. package/dist/dev-session.mjs +194 -0
  89. package/dist/dev-session.mjs.map +1 -0
  90. package/dist/fastkv.cjs +89 -0
  91. package/dist/fastkv.cjs.map +1 -0
  92. package/dist/fastkv.d.cts +11 -0
  93. package/dist/fastkv.d.cts.map +1 -0
  94. package/dist/fastkv.d.mts +11 -0
  95. package/dist/fastkv.d.mts.map +1 -0
  96. package/dist/fastkv.mjs +82 -0
  97. package/dist/fastkv.mjs.map +1 -0
  98. package/dist/federation.server.cjs +27 -0
  99. package/dist/federation.server.cjs.map +1 -0
  100. package/dist/federation.server.mjs +27 -0
  101. package/dist/federation.server.mjs.map +1 -0
  102. package/dist/host.cjs +367 -0
  103. package/dist/host.cjs.map +1 -0
  104. package/dist/host.d.cts +22 -0
  105. package/dist/host.d.cts.map +1 -0
  106. package/dist/host.d.mts +22 -0
  107. package/dist/host.d.mts.map +1 -0
  108. package/dist/host.mjs +364 -0
  109. package/dist/host.mjs.map +1 -0
  110. package/dist/index.cjs +122 -0
  111. package/dist/index.d.cts +7 -0
  112. package/dist/index.d.mts +7 -0
  113. package/dist/index.mjs +9 -0
  114. package/dist/integrity.cjs +39 -0
  115. package/dist/integrity.cjs.map +1 -0
  116. package/dist/integrity.d.cts +7 -0
  117. package/dist/integrity.d.cts.map +1 -0
  118. package/dist/integrity.d.mts +7 -0
  119. package/dist/integrity.d.mts.map +1 -0
  120. package/dist/integrity.mjs +35 -0
  121. package/dist/integrity.mjs.map +1 -0
  122. package/dist/internal/manifest-normalizer.cjs +140 -0
  123. package/dist/internal/manifest-normalizer.cjs.map +1 -0
  124. package/dist/internal/manifest-normalizer.mjs +138 -0
  125. package/dist/internal/manifest-normalizer.mjs.map +1 -0
  126. package/dist/mf.cjs +77 -0
  127. package/dist/mf.cjs.map +1 -0
  128. package/dist/mf.d.cts +19 -0
  129. package/dist/mf.d.cts.map +1 -0
  130. package/dist/mf.d.mts +19 -0
  131. package/dist/mf.d.mts.map +1 -0
  132. package/dist/mf.mjs +71 -0
  133. package/dist/mf.mjs.map +1 -0
  134. package/dist/near-cli.cjs +196 -0
  135. package/dist/near-cli.cjs.map +1 -0
  136. package/dist/near-cli.mjs +193 -0
  137. package/dist/near-cli.mjs.map +1 -0
  138. package/dist/network.cjs +9 -0
  139. package/dist/network.cjs.map +1 -0
  140. package/dist/network.mjs +8 -0
  141. package/dist/network.mjs.map +1 -0
  142. package/dist/orchestrator.cjs +441 -0
  143. package/dist/orchestrator.cjs.map +1 -0
  144. package/dist/orchestrator.d.cts +40 -0
  145. package/dist/orchestrator.d.cts.map +1 -0
  146. package/dist/orchestrator.d.mts +40 -0
  147. package/dist/orchestrator.d.mts.map +1 -0
  148. package/dist/orchestrator.mjs +436 -0
  149. package/dist/orchestrator.mjs.map +1 -0
  150. package/dist/plugin.cjs +830 -0
  151. package/dist/plugin.cjs.map +1 -0
  152. package/dist/plugin.d.cts +347 -0
  153. package/dist/plugin.d.cts.map +1 -0
  154. package/dist/plugin.d.mts +348 -0
  155. package/dist/plugin.d.mts.map +1 -0
  156. package/dist/plugin.mjs +827 -0
  157. package/dist/plugin.mjs.map +1 -0
  158. package/dist/process-registry.cjs +120 -0
  159. package/dist/process-registry.cjs.map +1 -0
  160. package/dist/process-registry.d.cts +25 -0
  161. package/dist/process-registry.d.cts.map +1 -0
  162. package/dist/process-registry.d.mts +25 -0
  163. package/dist/process-registry.d.mts.map +1 -0
  164. package/dist/process-registry.mjs +119 -0
  165. package/dist/process-registry.mjs.map +1 -0
  166. package/dist/sdk.cjs +61 -0
  167. package/dist/sdk.d.cts +5 -0
  168. package/dist/sdk.d.mts +5 -0
  169. package/dist/sdk.mjs +6 -0
  170. package/dist/shared.cjs +143 -0
  171. package/dist/shared.cjs.map +1 -0
  172. package/dist/shared.d.cts +33 -0
  173. package/dist/shared.d.cts.map +1 -0
  174. package/dist/shared.d.mts +33 -0
  175. package/dist/shared.d.mts.map +1 -0
  176. package/dist/shared.mjs +140 -0
  177. package/dist/shared.mjs.map +1 -0
  178. package/dist/types.cjs +160 -0
  179. package/dist/types.cjs.map +1 -0
  180. package/dist/types.d.cts +269 -0
  181. package/dist/types.d.cts.map +1 -0
  182. package/dist/types.d.mts +269 -0
  183. package/dist/types.d.mts.map +1 -0
  184. package/dist/types.mjs +144 -0
  185. package/dist/types.mjs.map +1 -0
  186. package/dist/ui/head.cjs +67 -0
  187. package/dist/ui/head.cjs.map +1 -0
  188. package/dist/ui/head.d.cts +19 -0
  189. package/dist/ui/head.d.cts.map +1 -0
  190. package/dist/ui/head.d.mts +19 -0
  191. package/dist/ui/head.d.mts.map +1 -0
  192. package/dist/ui/head.mjs +61 -0
  193. package/dist/ui/head.mjs.map +1 -0
  194. package/dist/ui/index.cjs +32 -0
  195. package/dist/ui/index.d.cts +7 -0
  196. package/dist/ui/index.d.mts +7 -0
  197. package/dist/ui/index.mjs +6 -0
  198. package/dist/ui/metadata.cjs +106 -0
  199. package/dist/ui/metadata.cjs.map +1 -0
  200. package/dist/ui/metadata.d.cts +35 -0
  201. package/dist/ui/metadata.d.cts.map +1 -0
  202. package/dist/ui/metadata.d.mts +35 -0
  203. package/dist/ui/metadata.d.mts.map +1 -0
  204. package/dist/ui/metadata.mjs +100 -0
  205. package/dist/ui/metadata.mjs.map +1 -0
  206. package/dist/ui/router.cjs +56 -0
  207. package/dist/ui/router.cjs.map +1 -0
  208. package/dist/ui/router.d.cts +11 -0
  209. package/dist/ui/router.d.cts.map +1 -0
  210. package/dist/ui/router.d.mts +11 -0
  211. package/dist/ui/router.d.mts.map +1 -0
  212. package/dist/ui/router.mjs +51 -0
  213. package/dist/ui/router.mjs.map +1 -0
  214. package/dist/ui/runtime.cjs +65 -0
  215. package/dist/ui/runtime.cjs.map +1 -0
  216. package/dist/ui/runtime.d.cts +29 -0
  217. package/dist/ui/runtime.d.cts.map +1 -0
  218. package/dist/ui/runtime.d.mts +29 -0
  219. package/dist/ui/runtime.d.mts.map +1 -0
  220. package/dist/ui/runtime.mjs +53 -0
  221. package/dist/ui/runtime.mjs.map +1 -0
  222. package/dist/ui/types.cjs +0 -0
  223. package/dist/ui/types.d.cts +52 -0
  224. package/dist/ui/types.d.cts.map +1 -0
  225. package/dist/ui/types.d.mts +52 -0
  226. package/dist/ui/types.d.mts.map +1 -0
  227. package/dist/ui/types.mjs +1 -0
  228. package/dist/utils/banner.cjs +24 -0
  229. package/dist/utils/banner.cjs.map +1 -0
  230. package/dist/utils/banner.mjs +23 -0
  231. package/dist/utils/banner.mjs.map +1 -0
  232. package/dist/utils/linkify.cjs +15 -0
  233. package/dist/utils/linkify.cjs.map +1 -0
  234. package/dist/utils/linkify.mjs +14 -0
  235. package/dist/utils/linkify.mjs.map +1 -0
  236. package/dist/utils/run.cjs +40 -0
  237. package/dist/utils/run.cjs.map +1 -0
  238. package/dist/utils/run.mjs +39 -0
  239. package/dist/utils/run.mjs.map +1 -0
  240. package/dist/utils/theme.cjs +44 -0
  241. package/dist/utils/theme.cjs.map +1 -0
  242. package/dist/utils/theme.mjs +37 -0
  243. package/dist/utils/theme.mjs.map +1 -0
  244. package/package.json +269 -80
  245. package/src/api-contract.ts +309 -0
  246. package/src/api.ts +181 -0
  247. package/src/app.ts +346 -0
  248. package/src/cli/catalog.ts +49 -0
  249. package/src/cli/help.ts +13 -0
  250. package/src/cli/init.ts +386 -0
  251. package/src/cli/parse.ts +130 -0
  252. package/src/cli/prompts.ts +64 -0
  253. package/src/cli.ts +203 -1507
  254. package/src/components/dev-view.tsx +307 -255
  255. package/src/components/streaming-view.ts +164 -128
  256. package/src/config.ts +462 -532
  257. package/src/contract.meta.ts +96 -0
  258. package/src/contract.ts +164 -561
  259. package/src/dev-logs.ts +85 -0
  260. package/src/dev-session.ts +318 -0
  261. package/src/fastkv.ts +153 -0
  262. package/src/federation.server.ts +43 -0
  263. package/src/host.ts +526 -0
  264. package/src/index.ts +6 -3
  265. package/src/integrity.ts +54 -0
  266. package/src/internal/manifest-normalizer.ts +251 -0
  267. package/src/mf.ts +105 -0
  268. package/src/near-cli.ts +284 -0
  269. package/src/network.ts +3 -0
  270. package/src/orchestrator.ts +648 -0
  271. package/src/plugin.ts +1130 -2311
  272. package/src/process-registry.ts +154 -0
  273. package/src/scripts/sync-api-contract.ts +24 -0
  274. package/src/sdk.ts +14 -0
  275. package/src/shared.ts +206 -0
  276. package/src/types.ts +152 -206
  277. package/src/ui/head.ts +34 -27
  278. package/src/ui/index.ts +3 -3
  279. package/src/ui/metadata.ts +95 -0
  280. package/src/ui/router.ts +22 -6
  281. package/src/ui/runtime.ts +55 -6
  282. package/src/ui/types.ts +24 -11
  283. package/src/utils/banner.ts +10 -6
  284. package/src/utils/run.ts +26 -27
  285. package/src/utils/theme.ts +3 -66
  286. package/src/components/monitor-view.tsx +0 -475
  287. package/src/components/status-view.tsx +0 -173
  288. package/src/lib/env.ts +0 -109
  289. package/src/lib/near-cli.ts +0 -289
  290. package/src/lib/nova.ts +0 -266
  291. package/src/lib/orchestrator.ts +0 -276
  292. package/src/lib/process-registry.ts +0 -166
  293. package/src/lib/process.ts +0 -550
  294. package/src/lib/resource-monitor/assertions.ts +0 -234
  295. package/src/lib/resource-monitor/command.ts +0 -283
  296. package/src/lib/resource-monitor/diff.ts +0 -157
  297. package/src/lib/resource-monitor/errors.ts +0 -127
  298. package/src/lib/resource-monitor/index.ts +0 -305
  299. package/src/lib/resource-monitor/platform/darwin.ts +0 -306
  300. package/src/lib/resource-monitor/platform/index.ts +0 -35
  301. package/src/lib/resource-monitor/platform/linux.ts +0 -332
  302. package/src/lib/resource-monitor/platform/windows.ts +0 -298
  303. package/src/lib/resource-monitor/snapshot.ts +0 -217
  304. package/src/lib/resource-monitor/types.ts +0 -74
  305. package/src/lib/session-recorder/errors.ts +0 -102
  306. package/src/lib/session-recorder/flows/login.ts +0 -210
  307. package/src/lib/session-recorder/index.ts +0 -361
  308. package/src/lib/session-recorder/playwright.ts +0 -257
  309. package/src/lib/session-recorder/report.ts +0 -353
  310. package/src/lib/session-recorder/server.ts +0 -268
  311. package/src/lib/session-recorder/types.ts +0 -115
  312. package/src/lib/sync.ts +0 -1
  313. package/src/ui/files.ts +0 -134
package/src/plugin.ts CHANGED
@@ -1,2357 +1,1176 @@
1
- import { createPlugin } from "every-plugin";
2
- import { Effect } from "every-plugin/effect";
3
- import { z } from "every-plugin/zod";
4
- import { calculateRequiredDeposit, Graph } from "near-social-js";
5
-
6
- import { runMonitorCli } from "./components/monitor-view";
1
+ import { readFileSync, writeFileSync } from "node:fs";
2
+ import { basename, join, resolve } from "node:path";
3
+ import { Effect } from "effect";
4
+ import { syncApiContractBridge } from "./api-contract";
5
+ import { buildRuntimeConfig, detectLocalPackages, prepareDevelopmentRuntimeConfig } from "./app";
6
+ import {
7
+ copyFilteredFiles,
8
+ personalizeConfig,
9
+ readTemplatekeep,
10
+ resolveSourceDir,
11
+ runBunInstall,
12
+ } from "./cli/init";
13
+ import { promptInitOptions } from "./cli/prompts";
7
14
  import {
8
- type AppConfig,
9
- type BosConfig as BosConfigType,
10
- DEFAULT_DEV_CONFIG,
11
- getProjectRoot,
12
- loadConfig,
13
- parsePort,
14
- type RemoteConfig,
15
- resolvePackages,
16
- type SourceMode,
15
+ buildRuntimePluginsForConfig,
16
+ getHostDevelopmentPort,
17
+ getProjectRoot,
18
+ loadConfig,
19
+ parsePort,
20
+ resolveDevelopmentHostUrl,
21
+ resolveLocalDevelopmentPath,
17
22
  } from "./config";
18
23
  import {
19
- type BuildOptions,
20
- bosContract,
21
- type PublishOptions,
24
+ type BosConfigResult,
25
+ type BuildOptions,
26
+ bosContract,
27
+ type DevOptions,
28
+ type InitOptions,
29
+ type KeyPublishOptions,
30
+ type PluginAddOptions,
31
+ type PluginListResult,
32
+ type PluginPublishOptions,
33
+ type PluginRemoveOptions,
34
+ type PublishOptions,
35
+ type StartOptions,
22
36
  } from "./contract";
37
+ import { type AppConfig, type AppOrchestrator, startApp } from "./dev-session";
23
38
  import {
24
- getBuildEnv,
25
- hasZephyrConfig,
26
- loadBosEnv,
27
- ZEPHYR_DOCS_URL,
28
- } from "./lib/env";
29
- import {
30
- createSubaccount,
31
- ensureNearCli,
32
- executeTransaction,
33
- } from "./lib/near-cli";
34
- import {
35
- createNovaClient,
36
- getNovaConfig,
37
- getSecretsGroupId,
38
- parseEnvFile,
39
- registerSecretsGroup,
40
- removeNovaCredentials,
41
- retrieveSecrets,
42
- saveNovaCredentials,
43
- uploadSecrets,
44
- verifyNovaCredentials,
45
- } from "./lib/nova";
46
- import { type AppOrchestrator, startApp } from "./lib/orchestrator";
47
- import { createProcessRegistry } from "./lib/process-registry";
48
- import {
49
- createSnapshotWithPlatform,
50
- formatSnapshotSummary,
51
- runWithInfo,
52
- } from "./lib/resource-monitor";
53
- import {
54
- formatReportSummary,
55
- navigateTo,
56
- runLoginFlow,
57
- runNavigationFlow,
58
- SessionRecorder,
59
- } from "./lib/session-recorder";
60
- import { syncFiles } from "./lib/sync";
39
+ buildRegistryConfigUrlForNetwork,
40
+ fetchBosConfigFromFastKv,
41
+ getRegistryNamespaceForAccount,
42
+ getRegistryNamespaceForNetwork,
43
+ } from "./fastkv";
44
+ import { addFunctionCallAccessKey, ensureNearCli, executeTransaction } from "./near-cli";
45
+ import { getNetworkIdForAccount } from "./network";
46
+ import { createPlugin, z } from "./sdk";
47
+ import { syncAndGenerateSharedUi } from "./shared";
48
+ import type { BosConfig, RuntimeConfig, SourceMode } from "./types";
61
49
  import { run } from "./utils/run";
62
- import { colors, icons } from "./utils/theme";
63
50
 
64
- interface BosDeps {
65
- bosConfig: BosConfigType | null;
66
- configDir: string;
67
- nearPrivateKey?: string;
68
- }
69
-
70
- const DEFAULT_GATEWAY = "everything.dev";
71
-
72
- function getGatewayDomain(config: BosConfigType | null): string {
73
- if (!config) return DEFAULT_GATEWAY;
74
- const gateway = config.gateway as string | { production: string } | undefined;
75
- if (typeof gateway === "string") {
76
- return gateway.replace(/^https?:\/\//, "");
77
- }
78
- if (gateway && typeof gateway === "object" && "production" in gateway) {
79
- return gateway.production.replace(/^https?:\/\//, "");
80
- }
81
- return DEFAULT_GATEWAY;
82
- }
51
+ const DEFAULT_DEV_CONFIG: AppConfig = {
52
+ host: "local",
53
+ ui: "local",
54
+ api: "local",
55
+ ssr: false,
56
+ };
83
57
 
84
- function getAccountForNetwork(
85
- config: BosConfigType,
86
- network: "mainnet" | "testnet",
87
- ): string {
88
- if (network === "testnet") {
89
- if (!config.testnet) {
90
- throw new Error(
91
- "bos.config.json must have a 'testnet' field to use testnet network",
92
- );
93
- }
94
- return config.testnet;
95
- }
96
- return config.account;
97
- }
58
+ const buildCommands: Record<string, { cmd: string; args: string[] }> = {
59
+ host: { cmd: "bun", args: ["run", "build"] },
60
+ ui: { cmd: "bun", args: ["run", "build"] },
61
+ api: { cmd: "bun", args: ["run", "build"] },
62
+ };
98
63
 
99
- function getSocialContract(network: "mainnet" | "testnet"): string {
100
- return network === "testnet" ? "v1.social08.testnet" : "social.near";
101
- }
64
+ const PUBLISH_FUNCTION_NAMES = ["__fastdata_kv"];
102
65
 
103
- function getSocialExplorerUrl(
104
- network: "mainnet" | "testnet",
105
- path: string,
106
- ): string {
107
- const baseUrl =
108
- network === "testnet" ? "https://test.near.social" : "https://near.social";
109
- return `${baseUrl}/${path}`;
110
- }
66
+ type BosDeps = {
67
+ bosConfig: BosConfig | null;
68
+ runtimeConfig: RuntimeConfig | null;
69
+ configDir: string;
70
+ };
111
71
 
112
- function buildSocialSetArgs(
113
- account: string,
114
- gatewayDomain: string,
115
- config: BosConfigType,
116
- ): object {
117
- return {
118
- data: {
119
- [account]: {
120
- bos: {
121
- gateways: {
122
- [gatewayDomain]: {
123
- "bos.config.json": JSON.stringify(config),
124
- },
125
- },
126
- },
127
- },
128
- },
129
- };
130
- }
72
+ type PluginAttachmentConfig = NonNullable<BosConfig["plugins"]>[string];
131
73
 
132
- function parseSourceMode(
133
- value: string | undefined,
134
- defaultValue: SourceMode,
135
- ): SourceMode {
136
- if (value === "local" || value === "remote") return value;
137
- return defaultValue;
74
+ function parseSourceMode(value: string | undefined, defaultValue: SourceMode): SourceMode {
75
+ if (value === "local" || value === "remote") return value;
76
+ return defaultValue;
138
77
  }
139
78
 
140
79
  function buildAppConfig(options: {
141
- host?: string;
142
- ui?: string;
143
- api?: string;
144
- proxy?: boolean;
80
+ host?: string;
81
+ ui?: string;
82
+ api?: string;
83
+ proxy?: boolean;
84
+ ssr?: boolean;
145
85
  }): AppConfig {
146
- return {
147
- host: parseSourceMode(options.host, DEFAULT_DEV_CONFIG.host),
148
- ui: parseSourceMode(options.ui, DEFAULT_DEV_CONFIG.ui),
149
- api: parseSourceMode(options.api, DEFAULT_DEV_CONFIG.api),
150
- proxy: options.proxy,
151
- };
86
+ return {
87
+ host: parseSourceMode(options.host, DEFAULT_DEV_CONFIG.host),
88
+ ui: parseSourceMode(options.ui, DEFAULT_DEV_CONFIG.ui),
89
+ api: parseSourceMode(options.api, DEFAULT_DEV_CONFIG.api),
90
+ proxy: options.proxy,
91
+ ssr: options.ssr ?? DEFAULT_DEV_CONFIG.ssr,
92
+ };
152
93
  }
153
94
 
154
95
  function buildDescription(config: AppConfig): string {
155
- const parts: string[] = [];
96
+ if (config.host === "local" && config.ui === "local" && config.api === "local" && !config.proxy) {
97
+ return "Full Local Development";
98
+ }
99
+
100
+ const parts: string[] = [];
101
+ parts.push(config.host === "remote" ? "Remote Host" : "Local Host");
102
+ if (config.ui === "remote") parts.push("Remote UI");
103
+ if (config.proxy) parts.push("Proxy API → Production");
104
+ else if (config.api === "remote") parts.push("Remote API");
105
+ return parts.join(" + ");
106
+ }
156
107
 
157
- if (
158
- config.host === "local" &&
159
- config.ui === "local" &&
160
- config.api === "local" &&
161
- !config.proxy
162
- ) {
163
- return "Full Local Development";
164
- }
108
+ function buildConfigResult(bosConfig: BosConfig | null): BosConfigResult {
109
+ const packages = bosConfig ? Object.keys(bosConfig.app) : [];
110
+ const remotes = packages.filter((name) => name !== "host");
165
111
 
166
- if (config.host === "remote") parts.push("Remote Host");
167
- else parts.push("Local Host");
112
+ return {
113
+ config: bosConfig,
114
+ packages,
115
+ remotes,
116
+ };
117
+ }
168
118
 
169
- if (config.ui === "remote") parts.push("Remote UI");
170
- if (config.proxy) parts.push("Proxy API → Production");
171
- else if (config.api === "remote") parts.push("Remote API");
119
+ type WorkspaceTarget = {
120
+ key: string;
121
+ kind: "app" | "plugin";
122
+ path: string;
123
+ };
172
124
 
173
- return parts.join(" + ");
125
+ function resolveWorkspaceTarget(
126
+ key: string,
127
+ bosConfig: BosConfig | null,
128
+ runtimeConfig: RuntimeConfig | null,
129
+ configDir: string,
130
+ ): WorkspaceTarget | null {
131
+ if (bosConfig?.app && key in bosConfig.app) {
132
+ return {
133
+ key,
134
+ kind: "app",
135
+ path: `${configDir}/${key}`,
136
+ };
137
+ }
138
+
139
+ const runtimePlugin = runtimeConfig?.plugins?.[key];
140
+ const pluginPath =
141
+ runtimePlugin?.localPath ??
142
+ resolveLocalDevelopmentPath(bosConfig?.plugins?.[key]?.development, configDir);
143
+ if (pluginPath) {
144
+ return {
145
+ key,
146
+ kind: "plugin",
147
+ path: pluginPath,
148
+ };
149
+ }
150
+
151
+ return null;
174
152
  }
175
153
 
176
- function determineProcesses(config: AppConfig): string[] {
177
- const processes: string[] = [];
154
+ function determineProcesses(
155
+ config: AppConfig,
156
+ localPackages: string[],
157
+ runtimeConfig?: RuntimeConfig | null,
158
+ ): string[] {
159
+ const processes: string[] = [];
160
+ if (config.ssr && config.ui === "local") processes.push("ui-ssr");
161
+ if (config.ui === "local") processes.push("ui");
162
+ if (config.api === "local" && !config.proxy) processes.push("api");
163
+ for (const pkg of localPackages) {
164
+ if (pkg.startsWith("plugin:")) {
165
+ const pluginId = pkg.slice("plugin:".length);
166
+ if (runtimeConfig?.plugins?.[pluginId]?.source === "local") {
167
+ processes.push(pkg);
168
+ }
169
+ }
170
+ }
171
+ processes.push("host");
172
+ return processes;
173
+ }
178
174
 
179
- if (config.ui === "local") {
180
- processes.push("ui-ssr");
181
- processes.push("ui");
182
- }
175
+ function isValidProxyUrl(url: string): boolean {
176
+ try {
177
+ const parsed = new URL(url);
178
+ return parsed.protocol === "http:" || parsed.protocol === "https:";
179
+ } catch {
180
+ return false;
181
+ }
182
+ }
183
183
 
184
- if (config.api === "local" && !config.proxy) {
185
- processes.push("api");
186
- }
184
+ function resolveProxyUrl(bosConfig: BosConfig | null): string | null {
185
+ if (!bosConfig) return null;
186
+ const apiConfig = bosConfig.app.api;
187
+ if (!apiConfig) return null;
188
+ if (apiConfig.proxy && isValidProxyUrl(apiConfig.proxy)) return apiConfig.proxy;
189
+ if (apiConfig.production && isValidProxyUrl(apiConfig.production)) return apiConfig.production;
190
+ return null;
191
+ }
187
192
 
188
- processes.push("host");
193
+ function sanitizePluginKey(value: string): string {
194
+ return value
195
+ .replace(/[^A-Za-z0-9/_-]/g, "-")
196
+ .replace(/\/+/g, "/")
197
+ .split("/")
198
+ .filter(Boolean)
199
+ .map((segment) => segment.replace(/[^A-Za-z0-9_-]/g, "-"))
200
+ .join("/")
201
+ .replace(/^\/+|\/+$/g, "");
202
+ }
189
203
 
190
- return processes;
204
+ function defaultPluginKey(source: string): string {
205
+ const normalized = source.replace(/^local:/, "").replace(/\/$/, "");
206
+ if (source.startsWith("local:")) {
207
+ return sanitizePluginKey(basename(normalized)) || "plugin";
208
+ }
209
+
210
+ try {
211
+ const url = new URL(source);
212
+ return sanitizePluginKey(basename(url.pathname) || url.hostname) || "plugin";
213
+ } catch {
214
+ return sanitizePluginKey(source) || "plugin";
215
+ }
191
216
  }
192
217
 
193
- function isValidProxyUrl(url: string): boolean {
194
- try {
195
- const parsed = new URL(url);
196
- return parsed.protocol === "http:" || parsed.protocol === "https:";
197
- } catch {
198
- return false;
199
- }
218
+ function pluginLocalPath(configDir: string, attachment: PluginAttachmentConfig): string | null {
219
+ const source = attachment.development ?? attachment.production;
220
+ if (!source?.startsWith("local:")) {
221
+ return null;
222
+ }
223
+
224
+ return join(configDir, source.slice("local:".length));
200
225
  }
201
226
 
202
- function resolveProxyUrl(bosConfig: BosConfigType | null): string | null {
203
- if (!bosConfig) return null;
227
+ async function saveBosConfig(configDir: string, config: BosConfig): Promise<void> {
228
+ const filePath = join(configDir, "bos.config.json");
229
+ const next = `${JSON.stringify(config, null, 2)}\n`;
230
+ try {
231
+ if (readFileSync(filePath, "utf8") === next) return;
232
+ } catch {
233
+ // file does not exist yet
234
+ }
204
235
 
205
- const apiConfig = bosConfig.app.api as RemoteConfig | undefined;
206
- if (!apiConfig) return null;
236
+ writeFileSync(filePath, next);
237
+ }
207
238
 
208
- if (apiConfig.proxy && isValidProxyUrl(apiConfig.proxy)) {
209
- return apiConfig.proxy;
210
- }
239
+ function listPluginAttachments(config: BosConfig | null) {
240
+ return (Object.entries(config?.plugins ?? {}) as Array<[string, PluginAttachmentConfig]>)
241
+ .map(([key, attachment]) => ({
242
+ key,
243
+ development: attachment.development,
244
+ production: attachment.production,
245
+ localPath: attachment.development?.startsWith("local:")
246
+ ? attachment.development.slice("local:".length)
247
+ : undefined,
248
+ source: attachment.development?.startsWith("local:")
249
+ ? ("local" as const)
250
+ : ("remote" as const),
251
+ }))
252
+ .sort((a, b) => a.key.localeCompare(b.key));
253
+ }
211
254
 
212
- if (apiConfig.production && isValidProxyUrl(apiConfig.production)) {
213
- return apiConfig.production;
214
- }
255
+ async function refreshApiContractBridge(configDir: string): Promise<void> {
256
+ const refreshed = await loadConfig({ cwd: configDir, env: "development" });
257
+ if (!refreshed) return;
215
258
 
216
- return null;
259
+ await syncApiContractBridge({
260
+ configDir,
261
+ runtimeConfig: refreshed.runtime,
262
+ apiBaseUrl: refreshed.runtime.api.url,
263
+ });
264
+ }
265
+
266
+ function extractPublishedUrl(output: string): string | null {
267
+ const match = output.match(/https?:\/\/[^\s"'<>]+/g);
268
+ if (!match || match.length === 0) return null;
269
+ return match[match.length - 1] ?? null;
217
270
  }
218
271
 
219
272
  async function buildEnvVars(
220
- config: AppConfig,
221
- bosConfig?: BosConfigType | null,
273
+ config: AppConfig,
274
+ bosConfig?: BosConfig | null,
222
275
  ): Promise<Record<string, string>> {
223
- const env: Record<string, string> = {};
224
-
225
- env.HOST_SOURCE = config.host;
226
- env.UI_SOURCE = config.ui;
227
- env.API_SOURCE = config.api;
228
-
229
- if (config.host === "remote") {
230
- const remoteUrl = bosConfig?.app.host.production;
231
- if (remoteUrl) {
232
- env.HOST_REMOTE_URL = remoteUrl;
233
- }
234
- }
235
-
236
- if (config.proxy && bosConfig) {
237
- const proxyUrl = resolveProxyUrl(bosConfig);
238
- if (proxyUrl) {
239
- env.API_PROXY = proxyUrl;
240
- }
241
- }
242
-
243
- return env;
276
+ const env: Record<string, string> = {
277
+ HOST_SOURCE: config.host,
278
+ UI_SOURCE: config.ui,
279
+ API_SOURCE: config.api,
280
+ };
281
+
282
+ if (config.host === "remote") {
283
+ const remoteUrl = bosConfig?.app.host.production;
284
+ if (remoteUrl) env.HOST_REMOTE_URL = remoteUrl;
285
+ }
286
+
287
+ if (config.ui === "remote") {
288
+ const remoteUrl = bosConfig?.app.ui.production;
289
+ if (remoteUrl) env.UI_REMOTE_URL = remoteUrl;
290
+ }
291
+
292
+ if (config.api === "remote") {
293
+ const remoteUrl = bosConfig?.app.api.production;
294
+ if (remoteUrl) env.API_REMOTE_URL = remoteUrl;
295
+ }
296
+
297
+ if (config.proxy && bosConfig) {
298
+ const proxyUrl = resolveProxyUrl(bosConfig);
299
+ if (proxyUrl) env.API_PROXY = proxyUrl;
300
+ }
301
+
302
+ return env;
244
303
  }
245
304
 
246
- const buildCommands: Record<string, { cmd: string; args: string[] }> = {
247
- host: { cmd: "rsbuild", args: ["build"] },
248
- ui: { cmd: "build", args: [] },
249
- api: { cmd: "rspack", args: ["build"] },
250
- };
305
+ async function buildEveryPluginQuietly(cwd: string) {
306
+ const packageDir = `${cwd}/packages/every-plugin`;
307
+ const packageExists = await Bun.file(`${packageDir}/package.json`).exists();
308
+ if (!packageExists) {
309
+ return;
310
+ }
311
+
312
+ const distPath = `${cwd}/packages/every-plugin/dist/build/rspack/plugin.mjs`;
313
+ const distExists = await Bun.file(distPath).exists();
314
+
315
+ if (distExists) {
316
+ return;
317
+ }
318
+
319
+ const result = (await run("bun", ["run", "--cwd", "packages/every-plugin", "build"], {
320
+ cwd,
321
+ capture: true,
322
+ })) as { stdout: string; stderr: string; exitCode: number };
323
+
324
+ if (result.exitCode === 0) {
325
+ console.log("[build:ssr] build succeeded");
326
+ return;
327
+ }
328
+
329
+ if (result.stdout.trim()) {
330
+ process.stdout.write(result.stdout);
331
+ }
332
+
333
+ if (result.stderr.trim()) {
334
+ process.stderr.write(result.stderr);
335
+ }
336
+
337
+ throw new Error(
338
+ `bun run --cwd packages/every-plugin build failed with exit code ${result.exitCode}`,
339
+ );
340
+ }
341
+
342
+ async function buildEverythingDevQuietly(cwd: string) {
343
+ const packageDir = `${cwd}/packages/everything-dev`;
344
+ const packageExists = await Bun.file(`${packageDir}/package.json`).exists();
345
+ if (!packageExists) {
346
+ return;
347
+ }
348
+
349
+ const distPath = `${cwd}/packages/everything-dev/dist/index.mjs`;
350
+ const distExists = await Bun.file(distPath).exists();
351
+
352
+ if (distExists) {
353
+ return;
354
+ }
355
+
356
+ const result = (await run("bun", ["run", "--cwd", "packages/everything-dev", "build"], {
357
+ cwd,
358
+ capture: true,
359
+ })) as { stdout: string; stderr: string; exitCode: number };
360
+
361
+ if (result.exitCode === 0) {
362
+ console.log("[everything-dev] build succeeded");
363
+ return;
364
+ }
365
+
366
+ if (result.stdout.trim()) {
367
+ process.stdout.write(result.stdout);
368
+ }
369
+
370
+ if (result.stderr.trim()) {
371
+ process.stderr.write(result.stderr);
372
+ }
373
+
374
+ throw new Error(
375
+ `bun run --cwd packages/everything-dev build failed with exit code ${result.exitCode}`,
376
+ );
377
+ }
378
+
379
+ async function fetchPublishedConfig(
380
+ accountId: string,
381
+ gatewayId: string,
382
+ ): Promise<BosConfig | null> {
383
+ try {
384
+ return await fetchBosConfigFromFastKv<BosConfig>(`bos://${accountId}/${gatewayId}`);
385
+ } catch {
386
+ return null;
387
+ }
388
+ }
389
+
390
+ function selectWorkspaceTargets(packages: string, bosConfig: BosConfig | null): string[] {
391
+ const allPackages = [
392
+ ...Object.keys(bosConfig?.app ?? {}),
393
+ ...Object.keys(bosConfig?.plugins ?? {}),
394
+ ];
395
+ if (packages === "all") {
396
+ return allPackages;
397
+ }
398
+
399
+ return packages
400
+ .split(",")
401
+ .map((pkg) => pkg.trim())
402
+ .filter((pkg) => allPackages.includes(pkg));
403
+ }
404
+
405
+ async function buildWorkspaceTargets(opts: {
406
+ configDir: string;
407
+ bosConfig: BosConfig | null;
408
+ runtimeConfig: RuntimeConfig | null;
409
+ targets: string[];
410
+ deploy: boolean;
411
+ }): Promise<{ built: string[]; skipped: string[] }> {
412
+ const existing: WorkspaceTarget[] = [];
413
+ const skipped: string[] = [];
414
+
415
+ for (const target of opts.targets) {
416
+ const resolved = resolveWorkspaceTarget(
417
+ target,
418
+ opts.bosConfig,
419
+ opts.runtimeConfig,
420
+ opts.configDir,
421
+ );
422
+ if (!resolved) {
423
+ skipped.push(target);
424
+ continue;
425
+ }
426
+
427
+ const exists = await Bun.file(`${resolved.path}/package.json`).exists();
428
+ if (exists) existing.push(resolved);
429
+ else skipped.push(target);
430
+ }
431
+
432
+ if (existing.length === 0) {
433
+ return { built: [], skipped };
434
+ }
435
+
436
+ const sharedSync = await syncAndGenerateSharedUi({
437
+ configDir: opts.configDir,
438
+ hostMode: "local",
439
+ bosConfig: opts.bosConfig ?? undefined,
440
+ });
441
+ if (sharedSync.catalogChanged) {
442
+ await run("bun", ["install"], { cwd: opts.configDir });
443
+ }
444
+
445
+ if (existing.some((entry) => entry.key === "api")) {
446
+ await buildEveryPluginQuietly(opts.configDir);
447
+ }
448
+
449
+ await buildEverythingDevQuietly(opts.configDir);
450
+
451
+ const env: Record<string, string> = {
452
+ ...process.env,
453
+ NODE_ENV: opts.deploy ? "production" : "development",
454
+ };
455
+ if (opts.deploy) {
456
+ env.DEPLOY = "true";
457
+ } else {
458
+ delete env.DEPLOY;
459
+ }
460
+
461
+ const orderedExisting = opts.deploy
462
+ ? [
463
+ ...existing.filter((entry) => entry.kind === "app" && entry.key !== "host"),
464
+ ...existing.filter((entry) => entry.kind === "plugin"),
465
+ ...existing.filter((entry) => entry.kind === "app" && entry.key === "host"),
466
+ ]
467
+ : existing;
468
+ const built: string[] = [];
469
+
470
+ for (const resolved of orderedExisting) {
471
+ const pkgJson = JSON.parse(await Bun.file(`${resolved.path}/package.json`).text()) as {
472
+ scripts?: Record<string, string>;
473
+ };
474
+ const shouldDeployScript = opts.deploy && pkgJson.scripts?.deploy;
475
+ const buildConfig = shouldDeployScript
476
+ ? { cmd: "bun", args: ["run", "deploy"] }
477
+ : (buildCommands[resolved.key] ?? { cmd: "bun", args: ["run", "build"] });
478
+
479
+ await run(buildConfig.cmd, buildConfig.args, {
480
+ cwd: resolved.path,
481
+ env,
482
+ });
483
+ built.push(resolved.key);
484
+ }
485
+
486
+ return { built, skipped };
487
+ }
251
488
 
252
489
  export default createPlugin({
253
- variables: z.object({
254
- configPath: z.string().optional(),
255
- }),
256
-
257
- secrets: z.object({
258
- nearPrivateKey: z.string().optional(),
259
- }),
260
-
261
- contract: bosContract,
262
-
263
- initialize: (config) =>
264
- Effect.promise(async () => {
265
- const configResult = await loadConfig({
266
- path: config.variables.configPath,
267
- });
268
- const configDir = getProjectRoot();
269
-
270
- return {
271
- bosConfig: configResult?.config ?? null,
272
- configDir,
273
- nearPrivateKey: config.secrets.nearPrivateKey,
274
- } as BosDeps;
275
- }),
276
-
277
- shutdown: () => Effect.void,
278
-
279
- createRouter: (deps: BosDeps, builder) => ({
280
- dev: builder.dev.handler(async ({ input }) => {
281
- const { resolved, autoRemote } = await resolvePackages(
282
- ["host", "ui", "api"],
283
- {
284
- host: input.host as SourceMode,
285
- ui: input.ui as SourceMode,
286
- api: input.api as SourceMode,
287
- },
288
- );
289
-
290
- // Extract modes from resolved packages
291
- const modes = {
292
- host: resolved.host.mode,
293
- ui: resolved.ui.mode,
294
- api: resolved.api.mode,
295
- };
296
-
297
- if (autoRemote.length > 0) {
298
- console.log();
299
- console.log(
300
- colors.cyan(` ${icons.config} Auto-detecting packages...`),
301
- );
302
- for (const pkg of autoRemote) {
303
- console.log(
304
- colors.dim(` ${pkg} not found locally → using remote`),
305
- );
306
- }
307
- console.log();
308
- }
309
-
310
- const appConfig = buildAppConfig({
311
- host: modes.host,
312
- ui: modes.ui,
313
- api: modes.api,
314
- proxy: input.proxy,
315
- });
316
-
317
- if (appConfig.host === "remote") {
318
- const remoteUrl = deps.bosConfig?.app.host.production;
319
- if (!remoteUrl) {
320
- return {
321
- status: "error" as const,
322
- description: "No remote URL configured for host",
323
- processes: [],
324
- autoRemote,
325
- };
326
- }
327
- }
328
-
329
- let proxyUrl: string | undefined;
330
- if (appConfig.proxy) {
331
- proxyUrl = resolveProxyUrl(deps.bosConfig) ?? undefined;
332
- if (!proxyUrl) {
333
- console.log();
334
- console.log(
335
- colors.error(
336
- ` ${icons.err} Proxy mode requested but no valid proxy URL found`,
337
- ),
338
- );
339
- console.log(
340
- colors.dim(
341
- ` Configure 'api.proxy' or 'api.production' in bos.config.json`,
342
- ),
343
- );
344
- console.log();
345
- return {
346
- status: "error" as const,
347
- description: "No valid proxy URL configured in bos.config.json",
348
- processes: [],
349
- autoRemote,
350
- };
351
- }
352
- }
353
-
354
- const processes = determineProcesses(appConfig);
355
- const env = await buildEnvVars(appConfig, deps.bosConfig);
356
- const description = buildDescription(appConfig);
357
-
358
- const orchestrator: AppOrchestrator = {
359
- packages: processes,
360
- env,
361
- description,
362
- appConfig,
363
- bosConfig: deps.bosConfig ?? undefined,
364
- port: input.port,
365
- interactive: input.interactive,
366
- };
367
-
368
- startApp(orchestrator);
369
-
370
- return {
371
- status: "started" as const,
372
- description,
373
- processes,
374
- };
375
- }),
376
-
377
- start: builder.start.handler(async ({ input }) => {
378
- let remoteConfig: BosConfigType | null = null;
379
-
380
- if (input.account && input.domain) {
381
- const graph = new Graph();
382
- const configPath = `${input.account}/bos/gateways/${input.domain}/bos.config.json`;
383
-
384
- try {
385
- const data = await graph.get({ keys: [configPath] });
386
- if (data) {
387
- const parts = configPath.split("/");
388
- let current: unknown = data;
389
- for (const part of parts) {
390
- if (current && typeof current === "object" && part in current) {
391
- current = (current as Record<string, unknown>)[part];
392
- } else {
393
- current = null;
394
- break;
395
- }
396
- }
397
- if (typeof current === "string") {
398
- remoteConfig = JSON.parse(current) as BosConfigType;
399
- // Config is used directly, no need to write to disk or set global state
400
- }
401
- }
402
- } catch (error) {
403
- console.error(`Failed to fetch config from social.near:`, error);
404
- return {
405
- status: "error" as const,
406
- url: "",
407
- };
408
- }
409
-
410
- if (!remoteConfig) {
411
- console.error(`No config found at ${configPath}`);
412
- return {
413
- status: "error" as const,
414
- url: "",
415
- };
416
- }
417
- }
418
-
419
- const config = remoteConfig || deps.bosConfig;
420
-
421
- if (!config) {
422
- console.error(
423
- "No configuration available. Provide --account and --domain, or run from a BOS project directory.",
424
- );
425
- return {
426
- status: "error" as const,
427
- url: "",
428
- };
429
- }
430
-
431
- const port = input.port ?? 3000;
432
-
433
- const env: Record<string, string> = {
434
- NODE_ENV: "production",
435
- HOST_SOURCE: "remote",
436
- UI_SOURCE: "remote",
437
- API_SOURCE: "remote",
438
- BOS_ACCOUNT: config.account,
439
- HOST_REMOTE_URL: config.app.host.production,
440
- UI_REMOTE_URL: config.app.ui.production,
441
- API_REMOTE_URL: config.app.api.production,
442
- };
443
-
444
- if (process.env.HOST_URL) {
445
- env.HOST_URL = process.env.HOST_URL;
446
- }
447
-
448
- const uiConfig = config.app.ui as { ssr?: string };
449
- if (uiConfig.ssr) {
450
- env.UI_SSR_URL = uiConfig.ssr;
451
- }
452
-
453
- const orchestrator: AppOrchestrator = {
454
- packages: ["host"],
455
- env,
456
- description: `Production Mode (${config.account})`,
457
- appConfig: {
458
- host: "remote",
459
- ui: "remote",
460
- api: "remote",
461
- },
462
- bosConfig: config,
463
- port,
464
- interactive: input.interactive,
465
- noLogs: true,
466
- };
467
-
468
- startApp(orchestrator);
469
-
470
- return {
471
- status: "running" as const,
472
- url: `http://localhost:${port}`,
473
- };
474
- }),
475
-
476
- serve: builder.serve.handler(async ({ input }) => {
477
- const port = input.port;
478
-
479
- return {
480
- status: "serving" as const,
481
- url: `http://localhost:${port}`,
482
- endpoints: {
483
- rpc: `http://localhost:${port}/api/rpc`,
484
- docs: `http://localhost:${port}/api`,
485
- },
486
- };
487
- }),
488
-
489
- build: builder.build.handler(async ({ input }: { input: BuildOptions }) => {
490
- const allPackages = deps.bosConfig ? Object.keys(deps.bosConfig.app) : [];
491
- const { configDir } = deps;
492
-
493
- const targets =
494
- input.packages === "all"
495
- ? allPackages
496
- : input.packages
497
- .split(",")
498
- .map((p) => p.trim())
499
- .filter((p) => allPackages.includes(p));
500
-
501
- if (targets.length === 0) {
502
- console.log(colors.dim(` No valid packages to build`));
503
- return {
504
- status: "error" as const,
505
- built: [],
506
- skipped: [],
507
- };
508
- }
509
-
510
- // Check which packages exist locally
511
- const existing: string[] = [];
512
- const missing: string[] = [];
513
- for (const pkg of targets) {
514
- const pkgPath = `${configDir}/${pkg}/package.json`;
515
- const exists = await Bun.file(pkgPath).exists();
516
- if (exists) {
517
- existing.push(pkg);
518
- } else {
519
- missing.push(pkg);
520
- }
521
- }
522
-
523
- if (missing.length > 0) {
524
- console.log();
525
- console.log(
526
- colors.cyan(` ${icons.config} Auto-detecting packages...`),
527
- );
528
- for (const pkg of missing) {
529
- console.log(colors.dim(` ${pkg} not found locally → skipping`));
530
- }
531
- console.log();
532
- }
533
-
534
- if (existing.length === 0) {
535
- console.log(colors.dim(` No packages found locally to build`));
536
- return {
537
- status: "error" as const,
538
- built: [],
539
- skipped: missing,
540
- };
541
- }
542
-
543
- const built: string[] = [];
544
-
545
- const buildEffect = Effect.gen(function* () {
546
- const bosEnv = yield* loadBosEnv;
547
- const env = getBuildEnv(bosEnv);
548
-
549
- if (!input.deploy) {
550
- env.NODE_ENV = "development";
551
- } else {
552
- env.NODE_ENV = "production";
553
- env.DEPLOY = "true";
554
- if (!hasZephyrConfig(bosEnv)) {
555
- console.log(
556
- colors.dim(
557
- ` ${icons.config} Zephyr tokens not configured - you may be prompted to login`,
558
- ),
559
- );
560
- console.log(colors.dim(` Setup: ${ZEPHYR_DOCS_URL}`));
561
- console.log();
562
- }
563
- }
564
-
565
- for (const target of existing) {
566
- const buildConfig = buildCommands[target];
567
- if (!buildConfig) continue;
568
-
569
- yield* Effect.tryPromise({
570
- try: () =>
571
- run("bun", ["run", buildConfig.cmd, ...buildConfig.args], {
572
- cwd: `${configDir}/${target}`,
573
- env,
574
- }),
575
- catch: (e) => new Error(`Build failed for ${target}: ${e}`),
576
- });
577
- built.push(target);
578
- }
579
- });
580
-
581
- await Effect.runPromise(buildEffect);
582
-
583
- return {
584
- status: "success" as const,
585
- built,
586
- skipped: missing,
587
- deployed: input.deploy,
588
- };
589
- }),
590
-
591
- publish: builder.publish.handler(
592
- async ({ input }: { input: PublishOptions }) => {
593
- const { bosConfig, nearPrivateKey } = deps;
594
-
595
- if (!bosConfig) {
596
- return {
597
- status: "error" as const,
598
- txHash: "",
599
- registryUrl: "",
600
- error:
601
- "No bos.config.json found. Run from a BOS project directory.",
602
- };
603
- }
604
-
605
- const network = input.network;
606
-
607
- try {
608
- const account = getAccountForNetwork(bosConfig, network);
609
- const gatewayDomain = getGatewayDomain(bosConfig);
610
- const socialContract = getSocialContract(network);
611
- const socialPath = `${account}/bos/gateways/${gatewayDomain}/bos.config.json`;
612
-
613
- const publishEffect = Effect.gen(function* () {
614
- yield* ensureNearCli;
615
-
616
- const bosEnv = yield* loadBosEnv;
617
- const privateKey = nearPrivateKey || bosEnv.NEAR_PRIVATE_KEY;
618
-
619
- const socialArgs = buildSocialSetArgs(
620
- account,
621
- gatewayDomain,
622
- bosConfig,
623
- ) as {
624
- data: Record<string, Record<string, unknown>>;
625
- };
626
- const argsBase64 = Buffer.from(JSON.stringify(socialArgs)).toString(
627
- "base64",
628
- );
629
-
630
- const graph = new Graph({
631
- network,
632
- contractId: socialContract,
633
- });
634
- const storageBalance = yield* Effect.tryPromise({
635
- try: () => graph.storageBalanceOf(account),
636
- catch: () => new Error("Failed to fetch storage balance"),
637
- });
638
-
639
- const requiredDeposit = calculateRequiredDeposit({
640
- data: socialArgs.data,
641
- storageBalance: storageBalance
642
- ? {
643
- available: BigInt(storageBalance.available),
644
- total: BigInt(storageBalance.total),
645
- }
646
- : null,
647
- });
648
- const depositAmount = requiredDeposit.toFixed();
649
-
650
- if (input.dryRun) {
651
- return {
652
- status: "dry-run" as const,
653
- txHash: "",
654
- registryUrl: getSocialExplorerUrl(network, socialPath),
655
- };
656
- }
657
-
658
- const result = yield* executeTransaction({
659
- account,
660
- contract: socialContract,
661
- method: "set",
662
- argsBase64,
663
- network,
664
- privateKey,
665
- gas: "300Tgas",
666
- deposit:
667
- depositAmount === "0"
668
- ? "1yoctoNEAR"
669
- : `${depositAmount}yoctoNEAR`,
670
- });
671
-
672
- return {
673
- status: "published" as const,
674
- txHash: result.txHash || "unknown",
675
- registryUrl: getSocialExplorerUrl(network, socialPath),
676
- };
677
- });
678
-
679
- return await Effect.runPromise(publishEffect);
680
- } catch (error) {
681
- return {
682
- status: "error" as const,
683
- txHash: "",
684
- registryUrl: "",
685
- error: error instanceof Error ? error.message : "Unknown error",
686
- };
687
- }
688
- },
689
- ),
690
-
691
- create: builder.create.handler(async ({ input }) => {
692
- const { join } = await import("path");
693
- const { mkdir, stat, rm, writeFile } = await import("fs/promises");
694
- const { Graph } = await import("near-social-js");
695
-
696
- // Parse GitHub template format: owner/repo/subdir or owner/repo
697
- function parseTemplate(template: string): {
698
- owner: string;
699
- repo: string;
700
- subdir: string;
701
- } {
702
- const parts = template.split("/");
703
- if (parts.length < 2) {
704
- throw new Error(
705
- `Invalid template format: ${template}. Expected: owner/repo or owner/repo/subdir`,
706
- );
707
- }
708
- const owner = parts[0];
709
- const repo = parts[1];
710
- const subdir = parts.slice(2).join("/");
711
- return { owner, repo, subdir };
712
- }
713
-
714
- // Fetch parent BOS config from Near Social
715
- async function fetchParentConfig(templateUrl: string) {
716
- const match = templateUrl.match(/^bos:\/\/([^/]+)\/(.+)$/);
717
- if (!match) throw new Error("Invalid template URL format");
718
- const [, account, gateway] = match;
719
-
720
- const graph = new Graph();
721
- const configPath = `${account}/bos/gateways/${gateway}/bos.config.json`;
722
- const data = await graph.get({ keys: [configPath] });
723
-
724
- if (!data) return null;
725
-
726
- const parts = configPath.split("/");
727
- let current: unknown = data;
728
- for (const part of parts) {
729
- if (current && typeof current === "object" && part in current) {
730
- current = (current as Record<string, unknown>)[part];
731
- } else {
732
- return null;
733
- }
734
- }
735
-
736
- return typeof current === "string" ? JSON.parse(current) : null;
737
- }
738
-
739
- // Generate .env.example with secrets from parent config
740
- async function generateEnvExample(parentConfig: any): Promise<string> {
741
- const lines: string[] = [
742
- "# Environment Variables",
743
- "# Copy this file to .env and fill in your values",
744
- "",
745
- ];
746
-
747
- // Add host secrets
748
- if (parentConfig?.app?.host?.secrets?.length > 0) {
749
- lines.push("# Host Secrets (from template)");
750
- for (const secret of parentConfig.app.host.secrets) {
751
- lines.push(`${secret}=`);
752
- }
753
- lines.push("");
754
- }
755
-
756
- // Add API secrets
757
- if (parentConfig?.app?.api?.secrets?.length > 0) {
758
- lines.push("# API Secrets (from template)");
759
- for (const secret of parentConfig.app.api.secrets) {
760
- lines.push(`${secret}=`);
761
- }
762
- lines.push("");
763
- }
764
-
765
- lines.push("# Zephyr Cloud (for deployment)");
766
- lines.push("ZE_SERVER_TOKEN=");
767
- lines.push("ZE_USER_EMAIL=");
768
- lines.push("");
769
- lines.push("# NEAR (optional - for automated publishing)");
770
- lines.push("# NEAR_PRIVATE_KEY=ed25519:...");
771
-
772
- return lines.join("\n");
773
- }
774
-
775
- // Clone template using degit
776
- async function cloneTemplate(
777
- gitTemplate: string,
778
- destDir: string,
779
- packages: string[],
780
- ): Promise<void> {
781
- const { owner, repo, subdir } = parseTemplate(gitTemplate);
782
- const baseTemplate = subdir
783
- ? `${owner}/${repo}/${subdir}`
784
- : `${owner}/${repo}`;
785
-
786
- // Import degit
787
- const { default: degit } = await import("degit");
788
-
789
- // Clone packages
790
- for (const pkg of packages) {
791
- const pkgTemplate = `${baseTemplate}/${pkg}`;
792
- const pkgDest = join(destDir, pkg);
793
-
794
- const emitter = degit(pkgTemplate, {
795
- cache: false,
796
- force: true,
797
- verbose: false,
798
- });
799
-
800
- await emitter.clone(pkgDest);
801
- }
802
-
803
- // Clone root files (using demo directory or root)
804
- const rootTemplate = baseTemplate;
805
- const rootEmitter = degit(rootTemplate, {
806
- cache: false,
807
- force: true,
808
- verbose: false,
809
- });
810
-
811
- await rootEmitter.clone(destDir);
812
- }
813
-
814
- // Verify template exists on GitHub
815
- async function verifyTemplate(gitTemplate: string): Promise<boolean> {
816
- try {
817
- const { owner, repo } = parseTemplate(gitTemplate);
818
- const { execa } = await import("execa");
819
- await execa(
820
- "git",
821
- ["ls-remote", `https://github.com/${owner}/${repo}.git`, "HEAD"],
822
- {
823
- timeout: 10000,
824
- },
825
- );
826
- return true;
827
- } catch {
828
- return false;
829
- }
830
- }
831
-
832
- // Default template URL
833
- const DEFAULT_TEMPLATE = "bos://every.near/everything.dev";
834
- const templateUrl = input.template || DEFAULT_TEMPLATE;
835
-
836
- // Get project name
837
- let projectName = input.name || "";
838
-
839
- // Interactive prompts if needed
840
- const hasAllRequiredArgs = input.account && projectName;
841
- const usePrompts = !hasAllRequiredArgs;
842
-
843
- let account = input.account || "";
844
- let testnet = input.testnet || "";
845
- let includeHost = input.includeHost || false;
846
- let includeGateway = input.includeGateway || false;
847
-
848
- if (usePrompts) {
849
- // Import prompts dynamically
850
- const { input: inquirerInput, confirm } = await import(
851
- "@inquirer/prompts"
852
- );
853
-
854
- if (!projectName) {
855
- projectName = await inquirerInput({
856
- message: "Project name:",
857
- validate: (val) => val.length > 0 || "Project name is required",
858
- });
859
- }
860
-
861
- if (!account) {
862
- account = await inquirerInput({
863
- message: "NEAR account (e.g., myname.near):",
864
- default: `${projectName}.near`,
865
- validate: (val) =>
866
- val.includes(".near") || "Must be a valid NEAR account",
867
- });
868
- }
869
-
870
- const testnetInput = await inquirerInput({
871
- message: "Testnet account (optional, press Enter to skip):",
872
- default: "",
873
- });
874
- testnet = testnetInput || "";
875
-
876
- includeHost = await confirm({
877
- message:
878
- "Include host package locally? (No = use remote from everything.dev)",
879
- default: false,
880
- });
881
-
882
- includeGateway = await confirm({
883
- message:
884
- "Include gateway package locally? (No = use remote from everything.dev)",
885
- default: false,
886
- });
887
- }
888
-
889
- const destDir = join(process.cwd(), projectName);
890
-
891
- try {
892
- // Check if directory already exists
893
- try {
894
- await stat(destDir);
895
- return {
896
- status: "error" as const,
897
- path: projectName,
898
- error: `Directory ${projectName} already exists`,
899
- };
900
- } catch {
901
- // Directory doesn't exist, continue
902
- }
903
-
904
- // Fetch parent BOS config to get templates
905
- const parentConfig = await fetchParentConfig(templateUrl);
906
- if (!parentConfig) {
907
- return {
908
- status: "error" as const,
909
- path: projectName,
910
- error: `Failed to fetch parent config from ${templateUrl}`,
911
- };
912
- }
913
-
914
- // Get GitHub template from parent config
915
- const gitTemplate =
916
- parentConfig.template || "near-everything/every-plugin/demo";
917
-
918
- // Verify template exists
919
- const templateExists = await verifyTemplate(gitTemplate);
920
- if (!templateExists) {
921
- return {
922
- status: "error" as const,
923
- path: projectName,
924
- error: `Template not found: ${gitTemplate}`,
925
- };
926
- }
927
-
928
- // Determine which packages to clone
929
- const packagesToClone = ["api", "ui"];
930
- if (includeHost) packagesToClone.push("host");
931
- if (includeGateway) packagesToClone.push("gateway");
932
-
933
- // Clone template using sparse checkout
934
- await cloneTemplate(gitTemplate, destDir, packagesToClone);
935
-
936
- // Remove excluded files/directories
937
- const excludedPaths = [
938
- "database.db",
939
- ".bos",
940
- ".turbo",
941
- ".env",
942
- ".env.bos",
943
- ".env.bos.example",
944
- ];
945
-
946
- // Add host/gateway to exclusions if not requested
947
- if (!includeHost) excludedPaths.push("host");
948
- if (!includeGateway) excludedPaths.push("gateway");
949
-
950
- for (const excluded of excludedPaths) {
951
- try {
952
- await rm(join(destDir, excluded), { recursive: true, force: true });
953
- } catch {
954
- // Ignore errors
955
- }
956
- }
957
-
958
- // Generate bos.config.json
959
- const bosConfig: Record<string, unknown> = {
960
- extends: templateUrl,
961
- account: account,
962
- app: {
963
- ui: {
964
- name: "ui",
965
- development: "http://localhost:3002",
966
- },
967
- api: {
968
- name: "api",
969
- development: "http://localhost:3014",
970
- variables: {},
971
- secrets: [],
972
- },
973
- },
974
- };
975
-
976
- // Only add testnet if provided
977
- if (testnet) {
978
- bosConfig.testnet = testnet;
979
- }
980
-
981
- await writeFile(
982
- join(destDir, "bos.config.json"),
983
- JSON.stringify(bosConfig, null, 2),
984
- );
985
-
986
- // Generate .env.example with secrets from parent config
987
- const envExample = await generateEnvExample(parentConfig);
988
- await writeFile(join(destDir, ".env.example"), envExample);
989
-
990
- // Modify package.json to update workspaces
991
- try {
992
- const pkgJsonPath = join(destDir, "package.json");
993
- const pkgJsonContent = await Bun.file(pkgJsonPath).text();
994
- const pkgJson = JSON.parse(pkgJsonContent);
995
-
996
- // Update workspaces to only include cloned packages
997
- pkgJson.workspaces.packages = packagesToClone;
998
-
999
- // Remove host/gateway scripts if not included
1000
- if (!includeHost) {
1001
- delete pkgJson.scripts["dev:host"];
1002
- delete pkgJson.scripts["build:host"];
1003
- }
1004
- if (!includeGateway) {
1005
- delete pkgJson.scripts["docker:build"];
1006
- delete pkgJson.scripts["docker:run"];
1007
- delete pkgJson.scripts["docker:stop"];
1008
- }
1009
-
1010
- await writeFile(pkgJsonPath, JSON.stringify(pkgJson, null, 2));
1011
- } catch {
1012
- // Package.json might not exist, skip
1013
- }
1014
-
1015
- // Run sync to update dependencies
1016
- try {
1017
- const { syncFiles } = await import("./lib/sync");
1018
- const catalog = parentConfig.shared?.ui || {};
1019
- await syncFiles({
1020
- configDir: destDir,
1021
- packages: packagesToClone,
1022
- bosConfig: parentConfig,
1023
- catalog,
1024
- });
1025
- } catch {
1026
- // Sync might fail, continue anyway
1027
- }
1028
-
1029
- return {
1030
- status: "created" as const,
1031
- path: projectName,
1032
- };
1033
- } catch (error) {
1034
- // Cleanup on error
1035
- try {
1036
- await rm(destDir, { recursive: true, force: true });
1037
- } catch {
1038
- // Ignore cleanup errors
1039
- }
1040
-
1041
- return {
1042
- status: "error" as const,
1043
- path: projectName,
1044
- error: error instanceof Error ? error.message : "Unknown error",
1045
- };
1046
- }
1047
- }),
1048
-
1049
- info: builder.info.handler(async () => {
1050
- const config = deps.bosConfig;
1051
- const packages = config ? Object.keys(config.app) : [];
1052
- const remotes = packages.filter((k) => k !== "host");
1053
-
1054
- return {
1055
- config: config as any,
1056
- packages,
1057
- remotes,
1058
- };
1059
- }),
1060
-
1061
- status: builder.status.handler(async ({ input }) => {
1062
- const config = deps.bosConfig;
1063
-
1064
- if (!config) {
1065
- return { endpoints: [] };
1066
- }
1067
-
1068
- const host = config.app.host;
1069
- const remotes = Object.keys(config.app).filter((k) => k !== "host");
1070
- const env = input.env;
1071
-
1072
- interface Endpoint {
1073
- name: string;
1074
- url: string;
1075
- type: "host" | "remote" | "ssr";
1076
- healthy: boolean;
1077
- latency?: number;
1078
- }
1079
-
1080
- const endpoints: Endpoint[] = [];
1081
-
1082
- const checkHealth = async (
1083
- url: string,
1084
- ): Promise<{ healthy: boolean; latency?: number }> => {
1085
- const start = Date.now();
1086
- try {
1087
- const response = await fetch(url, { method: "HEAD" });
1088
- return {
1089
- healthy: response.ok,
1090
- latency: Date.now() - start,
1091
- };
1092
- } catch {
1093
- return { healthy: false };
1094
- }
1095
- };
1096
-
1097
- const hostHealth = await checkHealth(host[env]);
1098
- endpoints.push({
1099
- name: "host",
1100
- url: host[env],
1101
- type: "host",
1102
- ...hostHealth,
1103
- });
1104
-
1105
- for (const name of remotes) {
1106
- const remote = config.app[name];
1107
- if (!remote || !("name" in remote)) continue;
1108
-
1109
- const remoteHealth = await checkHealth(remote[env]);
1110
- endpoints.push({
1111
- name,
1112
- url: remote[env],
1113
- type: "remote",
1114
- ...remoteHealth,
1115
- });
1116
-
1117
- if ((remote as any).ssr && env === "production") {
1118
- const ssrHealth = await checkHealth((remote as any).ssr);
1119
- endpoints.push({
1120
- name: `${name}/ssr`,
1121
- url: (remote as any).ssr,
1122
- type: "ssr",
1123
- ...ssrHealth,
1124
- });
1125
- }
1126
- }
1127
-
1128
- return { endpoints };
1129
- }),
1130
-
1131
- clean: builder.clean.handler(async () => {
1132
- const { configDir } = deps;
1133
- const packages = deps.bosConfig ? Object.keys(deps.bosConfig.app) : [];
1134
- const removed: string[] = [];
1135
-
1136
- for (const pkg of packages) {
1137
- const distPath = `${configDir}/${pkg}/dist`;
1138
- try {
1139
- await Bun.spawn(["rm", "-rf", distPath]).exited;
1140
- removed.push(`${pkg}/dist`);
1141
- } catch {}
1142
-
1143
- const nodeModulesPath = `${configDir}/${pkg}/node_modules`;
1144
- try {
1145
- await Bun.spawn(["rm", "-rf", nodeModulesPath]).exited;
1146
- removed.push(`${pkg}/node_modules`);
1147
- } catch {}
1148
- }
1149
-
1150
- return {
1151
- status: "cleaned" as const,
1152
- removed,
1153
- };
1154
- }),
1155
-
1156
- register: builder.register.handler(async ({ input }) => {
1157
- const { bosConfig } = deps;
1158
-
1159
- if (!bosConfig) {
1160
- return {
1161
- status: "error" as const,
1162
- account: input.name,
1163
- error: "No bos.config.json found. Run from a BOS project directory.",
1164
- };
1165
- }
1166
-
1167
- const network = input.network;
1168
-
1169
- try {
1170
- const parentAccount = getAccountForNetwork(bosConfig, network);
1171
- const fullAccount = `${input.name}.${parentAccount}`;
1172
-
1173
- const registerEffect = Effect.gen(function* () {
1174
- yield* ensureNearCli;
1175
-
1176
- const bosEnv = yield* loadBosEnv;
1177
- const gatewayPrivateKey = bosEnv.GATEWAY_PRIVATE_KEY;
1178
-
1179
- yield* createSubaccount({
1180
- newAccount: fullAccount,
1181
- parentAccount,
1182
- initialBalance: "0.1NEAR",
1183
- network,
1184
- privateKey: gatewayPrivateKey,
1185
- });
1186
-
1187
- const novaConfig = yield* getNovaConfig;
1188
- const nova = createNovaClient(novaConfig);
1189
-
1190
- const gatewayNovaAccount = bosConfig.gateway?.nova?.account;
1191
- if (!gatewayNovaAccount) {
1192
- return yield* Effect.fail(
1193
- new Error(
1194
- "gateway.nova.account is required for secrets registration",
1195
- ),
1196
- );
1197
- }
1198
-
1199
- yield* registerSecretsGroup(nova, fullAccount, gatewayNovaAccount);
1200
-
1201
- return {
1202
- status: "registered" as const,
1203
- account: fullAccount,
1204
- novaGroup: getSecretsGroupId(fullAccount),
1205
- };
1206
- });
1207
-
1208
- return await Effect.runPromise(registerEffect);
1209
- } catch (error) {
1210
- const parentAccount =
1211
- network === "testnet" ? bosConfig.testnet : bosConfig.account;
1212
- return {
1213
- status: "error" as const,
1214
- account: `${input.name}.${parentAccount || bosConfig.account}`,
1215
- error: error instanceof Error ? error.message : "Unknown error",
1216
- };
1217
- }
1218
- }),
1219
-
1220
- secretsSync: builder.secretsSync.handler(async ({ input }) => {
1221
- const { bosConfig } = deps;
1222
-
1223
- if (!bosConfig) {
1224
- return {
1225
- status: "error" as const,
1226
- count: 0,
1227
- error: "No bos.config.json found. Run from a BOS project directory.",
1228
- };
1229
- }
1230
-
1231
- const syncEffect = Effect.gen(function* () {
1232
- const novaConfig = yield* getNovaConfig;
1233
- const nova = createNovaClient(novaConfig);
1234
- const groupId = getSecretsGroupId(bosConfig.account);
1235
-
1236
- const envContent = yield* Effect.tryPromise({
1237
- try: () => Bun.file(input.envPath).text(),
1238
- catch: (e) => new Error(`Failed to read env file: ${e}`),
1239
- });
1240
-
1241
- const secrets = parseEnvFile(envContent);
1242
- const result = yield* uploadSecrets(nova, groupId, secrets);
1243
-
1244
- return {
1245
- status: "synced" as const,
1246
- count: Object.keys(secrets).length,
1247
- cid: result.cid,
1248
- };
1249
- });
1250
-
1251
- try {
1252
- return await Effect.runPromise(syncEffect);
1253
- } catch (error) {
1254
- return {
1255
- status: "error" as const,
1256
- count: 0,
1257
- error: error instanceof Error ? error.message : "Unknown error",
1258
- };
1259
- }
1260
- }),
1261
-
1262
- secretsSet: builder.secretsSet.handler(async ({ input }) => {
1263
- const { bosConfig } = deps;
1264
-
1265
- if (!bosConfig) {
1266
- return {
1267
- status: "error" as const,
1268
- error: "No bos.config.json found. Run from a BOS project directory.",
1269
- };
1270
- }
1271
-
1272
- const setEffect = Effect.gen(function* () {
1273
- const novaConfig = yield* getNovaConfig;
1274
- const nova = createNovaClient(novaConfig);
1275
- const groupId = getSecretsGroupId(bosConfig.account);
1276
-
1277
- const result = yield* uploadSecrets(nova, groupId, {
1278
- [input.key]: input.value,
1279
- });
1280
-
1281
- return {
1282
- status: "set" as const,
1283
- cid: result.cid,
1284
- };
1285
- });
1286
-
1287
- try {
1288
- return await Effect.runPromise(setEffect);
1289
- } catch (error) {
1290
- return {
1291
- status: "error" as const,
1292
- error: error instanceof Error ? error.message : "Unknown error",
1293
- };
1294
- }
1295
- }),
1296
-
1297
- secretsList: builder.secretsList.handler(async () => {
1298
- const { bosConfig } = deps;
1299
-
1300
- if (!bosConfig) {
1301
- return {
1302
- status: "error" as const,
1303
- keys: [],
1304
- error: "No bos.config.json found. Run from a BOS project directory.",
1305
- };
1306
- }
1307
-
1308
- const listEffect = Effect.gen(function* () {
1309
- const novaConfig = yield* getNovaConfig;
1310
- const nova = createNovaClient(novaConfig);
1311
- const groupId = getSecretsGroupId(bosConfig.account);
1312
-
1313
- const bosEnv = yield* loadBosEnv;
1314
- const cid = bosEnv.NOVA_SECRETS_CID;
1315
-
1316
- if (!cid) {
1317
- return {
1318
- status: "listed" as const,
1319
- keys: [] as string[],
1320
- };
1321
- }
1322
-
1323
- const secretsData = yield* retrieveSecrets(nova, groupId, cid);
1324
-
1325
- return {
1326
- status: "listed" as const,
1327
- keys: Object.keys(secretsData.secrets),
1328
- };
1329
- });
1330
-
1331
- try {
1332
- return await Effect.runPromise(listEffect);
1333
- } catch (error) {
1334
- return {
1335
- status: "error" as const,
1336
- keys: [],
1337
- error: error instanceof Error ? error.message : "Unknown error",
1338
- };
1339
- }
1340
- }),
1341
-
1342
- secretsDelete: builder.secretsDelete.handler(async ({ input }) => {
1343
- const { bosConfig } = deps;
1344
-
1345
- if (!bosConfig) {
1346
- return {
1347
- status: "error" as const,
1348
- error: "No bos.config.json found. Run from a BOS project directory.",
1349
- };
1350
- }
1351
-
1352
- const deleteEffect = Effect.gen(function* () {
1353
- const novaConfig = yield* getNovaConfig;
1354
- const nova = createNovaClient(novaConfig);
1355
- const groupId = getSecretsGroupId(bosConfig.account);
1356
-
1357
- const bosEnv = yield* loadBosEnv;
1358
- const cid = bosEnv.NOVA_SECRETS_CID;
1359
-
1360
- if (!cid) {
1361
- return yield* Effect.fail(
1362
- new Error("No secrets found to delete from"),
1363
- );
1364
- }
1365
-
1366
- const secretsData = yield* retrieveSecrets(nova, groupId, cid);
1367
- const { [input.key]: _, ...remainingSecrets } = secretsData.secrets;
1368
-
1369
- const result = yield* uploadSecrets(nova, groupId, remainingSecrets);
1370
-
1371
- return {
1372
- status: "deleted" as const,
1373
- cid: result.cid,
1374
- };
1375
- });
1376
-
1377
- try {
1378
- return await Effect.runPromise(deleteEffect);
1379
- } catch (error) {
1380
- return {
1381
- status: "error" as const,
1382
- error: error instanceof Error ? error.message : "Unknown error",
1383
- };
1384
- }
1385
- }),
1386
-
1387
- login: builder.login.handler(async ({ input }) => {
1388
- const loginEffect = Effect.gen(function* () {
1389
- const { token, accountId } = input;
1390
-
1391
- if (!token || !accountId) {
1392
- return yield* Effect.fail(
1393
- new Error("Both token and accountId are required"),
1394
- );
1395
- }
1396
-
1397
- yield* verifyNovaCredentials(accountId, token);
1398
- yield* saveNovaCredentials(accountId, token);
1399
-
1400
- return {
1401
- status: "logged-in" as const,
1402
- accountId,
1403
- };
1404
- });
1405
-
1406
- try {
1407
- return await Effect.runPromise(loginEffect);
1408
- } catch (error) {
1409
- let message = "Unknown error";
1410
- if (error instanceof Error) {
1411
- message = error.message;
1412
- } else if (typeof error === "object" && error !== null) {
1413
- if ("message" in error) {
1414
- message = String(error.message);
1415
- } else if ("_tag" in error && "error" in error) {
1416
- const inner = (error as { error: unknown }).error;
1417
- message = inner instanceof Error ? inner.message : String(inner);
1418
- } else {
1419
- message = JSON.stringify(error);
1420
- }
1421
- } else {
1422
- message = String(error);
1423
- }
1424
- console.error("Login error details:", error);
1425
- return {
1426
- status: "error" as const,
1427
- error: message,
1428
- };
1429
- }
1430
- }),
1431
-
1432
- logout: builder.logout.handler(async () => {
1433
- const logoutEffect = Effect.gen(function* () {
1434
- yield* removeNovaCredentials;
1435
-
1436
- return {
1437
- status: "logged-out" as const,
1438
- };
1439
- });
1440
-
1441
- try {
1442
- return await Effect.runPromise(logoutEffect);
1443
- } catch (error) {
1444
- return {
1445
- status: "error" as const,
1446
- error: error instanceof Error ? error.message : "Unknown error",
1447
- };
1448
- }
1449
- }),
1450
-
1451
- gatewayDev: builder.gatewayDev.handler(async () => {
1452
- const { configDir } = deps;
1453
- const gatewayDir = `${configDir}/gateway`;
1454
-
1455
- const devEffect = Effect.gen(function* () {
1456
- const { execa } = yield* Effect.tryPromise({
1457
- try: () => import("execa"),
1458
- catch: (e) => new Error(`Failed to import execa: ${e}`),
1459
- });
1460
-
1461
- const subprocess = execa("npx", ["wrangler", "dev"], {
1462
- cwd: gatewayDir,
1463
- stdio: "inherit",
1464
- });
1465
-
1466
- subprocess.catch(() => {});
1467
-
1468
- return {
1469
- status: "started" as const,
1470
- url: "http://localhost:8787",
1471
- };
1472
- });
1473
-
1474
- try {
1475
- return await Effect.runPromise(devEffect);
1476
- } catch (error) {
1477
- return {
1478
- status: "error" as const,
1479
- url: "",
1480
- error: error instanceof Error ? error.message : "Unknown error",
1481
- };
1482
- }
1483
- }),
1484
-
1485
- gatewayDeploy: builder.gatewayDeploy.handler(async ({ input }) => {
1486
- const { configDir, bosConfig } = deps;
1487
-
1488
- if (!bosConfig) {
1489
- return {
1490
- status: "error" as const,
1491
- url: "",
1492
- error: "No bos.config.json found. Run from a BOS project directory.",
1493
- };
1494
- }
1495
-
1496
- const gatewayDir = `${configDir}/gateway`;
1497
-
1498
- const deployEffect = Effect.gen(function* () {
1499
- const { execa } = yield* Effect.tryPromise({
1500
- try: () => import("execa"),
1501
- catch: (e) => new Error(`Failed to import execa: ${e}`),
1502
- });
1503
-
1504
- const args = ["wrangler", "deploy"];
1505
- if (input.env) {
1506
- args.push("--env", input.env);
1507
- }
1508
-
1509
- yield* Effect.tryPromise({
1510
- try: () =>
1511
- execa("npx", args, {
1512
- cwd: gatewayDir,
1513
- stdio: "inherit",
1514
- }),
1515
- catch: (e) => new Error(`Deploy failed: ${e}`),
1516
- });
1517
-
1518
- const gatewayDomain = getGatewayDomain(bosConfig);
1519
- const domain =
1520
- input.env === "staging" ? `staging.${gatewayDomain}` : gatewayDomain;
1521
-
1522
- return {
1523
- status: "deployed" as const,
1524
- url: `https://${domain}`,
1525
- };
1526
- });
1527
-
1528
- try {
1529
- return await Effect.runPromise(deployEffect);
1530
- } catch (error) {
1531
- return {
1532
- status: "error" as const,
1533
- url: "",
1534
- error: error instanceof Error ? error.message : "Unknown error",
1535
- };
1536
- }
1537
- }),
1538
-
1539
- gatewaySync: builder.gatewaySync.handler(async () => {
1540
- const { configDir, bosConfig } = deps;
1541
-
1542
- if (!bosConfig) {
1543
- return {
1544
- status: "error" as const,
1545
- error: "No bos.config.json found. Run from a BOS project directory.",
1546
- };
1547
- }
1548
-
1549
- const wranglerPath = `${configDir}/gateway/wrangler.toml`;
1550
-
1551
- try {
1552
- const gatewayDomain = getGatewayDomain(bosConfig);
1553
- const gatewayAccount = bosConfig.gateway?.account || bosConfig.account;
1554
-
1555
- const wranglerContent = await Bun.file(wranglerPath).text();
1556
-
1557
- let updatedContent = wranglerContent.replace(
1558
- /GATEWAY_DOMAIN\s*=\s*"[^"]*"/g,
1559
- `GATEWAY_DOMAIN = "${gatewayDomain}"`,
1560
- );
1561
- updatedContent = updatedContent.replace(
1562
- /GATEWAY_ACCOUNT\s*=\s*"[^"]*"/g,
1563
- `GATEWAY_ACCOUNT = "${gatewayAccount}"`,
1564
- );
1565
-
1566
- await Bun.write(wranglerPath, updatedContent);
1567
-
1568
- return {
1569
- status: "synced" as const,
1570
- gatewayDomain,
1571
- gatewayAccount,
1572
- };
1573
- } catch (error) {
1574
- return {
1575
- status: "error" as const,
1576
- error: error instanceof Error ? error.message : "Unknown error",
1577
- };
1578
- }
1579
- }),
1580
-
1581
- depsUpdate: builder.depsUpdate.handler(async ({ input }) => {
1582
- const { configDir, bosConfig } = deps;
1583
-
1584
- if (!bosConfig) {
1585
- return {
1586
- status: "error" as const,
1587
- updated: [],
1588
- error: "No bos.config.json found. Run from a BOS project directory.",
1589
- };
1590
- }
1591
-
1592
- const category = input.category;
1593
- const sharedDeps = bosConfig.shared?.[category];
1594
-
1595
- if (!sharedDeps || Object.keys(sharedDeps).length === 0) {
1596
- return {
1597
- status: "error" as const,
1598
- updated: [],
1599
- error: `No shared.${category} dependencies found in bos.config.json`,
1600
- };
1601
- }
1602
-
1603
- const { mkdtemp, rm } = await import("fs/promises");
1604
- const { tmpdir } = await import("os");
1605
- const { join } = await import("path");
1606
- const { execa } = await import("execa");
1607
-
1608
- const tempDir = await mkdtemp(join(tmpdir(), "bos-deps-"));
1609
-
1610
- try {
1611
- const tempDeps: Record<string, string> = {};
1612
- for (const [name, config] of Object.entries(sharedDeps)) {
1613
- const version =
1614
- (config as { requiredVersion?: string }).requiredVersion || "*";
1615
- tempDeps[name] = version.replace(/^[\^~]/, "");
1616
- }
1617
-
1618
- const tempPkg = {
1619
- name: "bos-deps-update",
1620
- private: true,
1621
- dependencies: tempDeps,
1622
- };
1623
-
1624
- await Bun.write(
1625
- join(tempDir, "package.json"),
1626
- JSON.stringify(tempPkg, null, 2),
1627
- );
1628
-
1629
- await execa("bun", ["install"], {
1630
- cwd: tempDir,
1631
- stdio: "inherit",
1632
- });
1633
-
1634
- await execa("bun", ["update", "-i"], {
1635
- cwd: tempDir,
1636
- stdio: "inherit",
1637
- });
1638
-
1639
- const updatedPkg = (await Bun.file(
1640
- join(tempDir, "package.json"),
1641
- ).json()) as {
1642
- dependencies: Record<string, string>;
1643
- };
1644
-
1645
- const updated: { name: string; from: string; to: string }[] = [];
1646
- const updatedConfig = { ...bosConfig };
1647
-
1648
- if (!updatedConfig.shared) {
1649
- updatedConfig.shared = {};
1650
- }
1651
- if (!updatedConfig.shared[category]) {
1652
- updatedConfig.shared[category] = {};
1653
- }
1654
-
1655
- for (const [name, newVersion] of Object.entries(
1656
- updatedPkg.dependencies,
1657
- )) {
1658
- const oldVersion =
1659
- (sharedDeps[name] as { requiredVersion?: string })
1660
- ?.requiredVersion || "";
1661
- if (newVersion !== oldVersion) {
1662
- updated.push({ name, from: oldVersion, to: newVersion });
1663
- updatedConfig.shared[category][name] = {
1664
- ...(sharedDeps[name] as object),
1665
- requiredVersion: newVersion,
1666
- };
1667
- }
1668
- }
1669
-
1670
- if (updated.length > 0) {
1671
- const bosConfigPath = `${configDir}/bos.config.json`;
1672
- await Bun.write(
1673
- bosConfigPath,
1674
- JSON.stringify(updatedConfig, null, 2),
1675
- );
1676
-
1677
- const rootPkgPath = `${configDir}/package.json`;
1678
- const rootPkg = (await Bun.file(rootPkgPath).json()) as {
1679
- workspaces?: { catalog?: Record<string, string> };
1680
- };
1681
-
1682
- if (rootPkg.workspaces?.catalog) {
1683
- for (const { name, to } of updated) {
1684
- rootPkg.workspaces.catalog[name] = to;
1685
- }
1686
- await Bun.write(rootPkgPath, JSON.stringify(rootPkg, null, 2));
1687
- }
1688
-
1689
- await execa("bun", ["install"], {
1690
- cwd: configDir,
1691
- stdio: "inherit",
1692
- });
1693
-
1694
- return {
1695
- status: "updated" as const,
1696
- updated,
1697
- syncStatus: "synced" as const,
1698
- };
1699
- }
1700
-
1701
- return {
1702
- status: "cancelled" as const,
1703
- updated: [],
1704
- };
1705
- } catch (error) {
1706
- return {
1707
- status: "error" as const,
1708
- updated: [],
1709
- error: error instanceof Error ? error.message : "Unknown error",
1710
- };
1711
- } finally {
1712
- await rm(tempDir, { recursive: true, force: true });
1713
- }
1714
- }),
1715
-
1716
- filesSync: builder.filesSync.handler(async ({ input }) => {
1717
- const { configDir, bosConfig } = deps;
1718
-
1719
- if (!bosConfig) {
1720
- return {
1721
- status: "error" as const,
1722
- synced: [],
1723
- error: "No bos.config.json found. Run from a BOS project directory.",
1724
- };
1725
- }
1726
-
1727
- const rootPkgPath = `${configDir}/package.json`;
1728
- const rootPkg = (await Bun.file(rootPkgPath).json()) as {
1729
- workspaces?: { catalog?: Record<string, string> };
1730
- };
1731
- const catalog = rootPkg.workspaces?.catalog ?? {};
1732
-
1733
- const packages = input.packages || Object.keys(bosConfig.app);
1734
-
1735
- const synced = await syncFiles({
1736
- configDir,
1737
- packages,
1738
- bosConfig,
1739
- catalog,
1740
- force: input.force,
1741
- });
1742
-
1743
- return {
1744
- status: "synced" as const,
1745
- synced,
1746
- };
1747
- }),
1748
-
1749
- update: builder.update.handler(async ({ input }) => {
1750
- const { configDir, bosConfig } = deps;
1751
-
1752
- const DEFAULT_ACCOUNT = "every.near";
1753
-
1754
- const account = input.account || bosConfig?.account || DEFAULT_ACCOUNT;
1755
- const gateway = input.gateway || getGatewayDomain(bosConfig);
1756
- const socialUrl = `https://near.social/mob.near/widget/State.Inspector?key=${account}/bos/gateways/${gateway}`;
1757
-
1758
- if (!bosConfig) {
1759
- return {
1760
- status: "error" as const,
1761
- account,
1762
- gateway,
1763
- socialUrl,
1764
- hostUrl: "",
1765
- catalogUpdated: false,
1766
- packagesUpdated: [],
1767
- error: "No bos.config.json found. Run from a BOS project directory.",
1768
- };
1769
- }
1770
-
1771
- try {
1772
- const graph = new Graph();
1773
- const configPath = `${account}/bos/gateways/${gateway}/bos.config.json`;
1774
-
1775
- let remoteConfig: BosConfigType | null = null;
1776
-
1777
- const data = await graph.get({ keys: [configPath] });
1778
- if (data) {
1779
- const parts = configPath.split("/");
1780
- let current: unknown = data;
1781
- for (const part of parts) {
1782
- if (current && typeof current === "object" && part in current) {
1783
- current = (current as Record<string, unknown>)[part];
1784
- } else {
1785
- current = null;
1786
- break;
1787
- }
1788
- }
1789
- if (typeof current === "string") {
1790
- remoteConfig = JSON.parse(current) as BosConfigType;
1791
- }
1792
- }
1793
-
1794
- if (!remoteConfig) {
1795
- return {
1796
- status: "error" as const,
1797
- account,
1798
- gateway,
1799
- hostUrl: "",
1800
- catalogUpdated: false,
1801
- packagesUpdated: [],
1802
- error: `No config found at ${configPath} on Near Social. Run 'bos publish' first.`,
1803
- };
1804
- }
1805
-
1806
- const hostUrl = remoteConfig.app?.host?.production;
1807
- if (!hostUrl) {
1808
- return {
1809
- status: "error" as const,
1810
- account,
1811
- gateway,
1812
- hostUrl: "",
1813
- catalogUpdated: false,
1814
- packagesUpdated: [],
1815
- error: `Published config is missing 'app.host.production'. Republish with updated bos.config.json.`,
1816
- };
1817
- }
1818
-
1819
- const mergeAppConfig = (
1820
- localApp: Record<string, unknown>,
1821
- remoteApp: Record<string, unknown>,
1822
- ): Record<string, unknown> => {
1823
- const merged: Record<string, unknown> = {};
1824
-
1825
- for (const key of Object.keys(remoteApp)) {
1826
- const local = localApp[key] as Record<string, unknown> | undefined;
1827
- const remote = remoteApp[key] as Record<string, unknown>;
1828
-
1829
- if (!local) {
1830
- merged[key] = remote;
1831
- continue;
1832
- }
1833
-
1834
- merged[key] = {
1835
- ...remote,
1836
- development: local.development,
1837
- secrets: [
1838
- ...new Set([
1839
- ...((remote.secrets as string[]) || []),
1840
- ...((local.secrets as string[]) || []),
1841
- ]),
1842
- ],
1843
- variables: {
1844
- ...((remote.variables as Record<string, unknown>) || {}),
1845
- ...((local.variables as Record<string, unknown>) || {}),
1846
- },
1847
- };
1848
- }
1849
-
1850
- return merged;
1851
- };
1852
-
1853
- const updatedBosConfig: BosConfigType = {
1854
- account: bosConfig.account,
1855
- testnet: bosConfig.testnet,
1856
- template: remoteConfig.template,
1857
- shared: remoteConfig.shared,
1858
- gateway: remoteConfig.gateway,
1859
- app: mergeAppConfig(
1860
- bosConfig.app as Record<string, unknown>,
1861
- remoteConfig.app as Record<string, unknown>,
1862
- ) as BosConfigType["app"],
1863
- };
1864
-
1865
- const bosConfigPath = `${configDir}/bos.config.json`;
1866
- await Bun.write(
1867
- bosConfigPath,
1868
- JSON.stringify(updatedBosConfig, null, 2),
1869
- );
1870
- // Config is written to disk, subsequent code uses updatedBosConfig directly
1871
- // Cache will be refreshed on next loadConfig() call
1872
-
1873
- const sharedUiDeps: Record<string, string> = {};
1874
- const sharedUi = updatedBosConfig.shared?.ui as
1875
- | Record<string, { requiredVersion?: string }>
1876
- | undefined;
1877
- if (sharedUi) {
1878
- for (const [name, config] of Object.entries(sharedUi)) {
1879
- if (config.requiredVersion) {
1880
- sharedUiDeps[name] = config.requiredVersion;
1881
- }
1882
- }
1883
- }
1884
-
1885
- const rootPkgPath = `${configDir}/package.json`;
1886
- const rootPkg = (await Bun.file(rootPkgPath).json()) as {
1887
- workspaces: { packages: string[]; catalog: Record<string, string> };
1888
- [key: string]: unknown;
1889
- };
1890
-
1891
- rootPkg.workspaces.catalog = {
1892
- ...rootPkg.workspaces.catalog,
1893
- ...sharedUiDeps,
1894
- };
1895
- await Bun.write(rootPkgPath, JSON.stringify(rootPkg, null, 2));
1896
-
1897
- const packages = ["host", "ui", "api"];
1898
- const packagesUpdated: string[] = [];
1899
-
1900
- for (const pkg of packages) {
1901
- const pkgDir = `${configDir}/${pkg}`;
1902
- const pkgDirExists = await Bun.file(
1903
- `${pkgDir}/package.json`,
1904
- ).exists();
1905
- if (!pkgDirExists) continue;
1906
-
1907
- const pkgPath = `${pkgDir}/package.json`;
1908
- const pkgFile = Bun.file(pkgPath);
1909
-
1910
- const pkgJson = (await pkgFile.json()) as {
1911
- dependencies?: Record<string, string>;
1912
- devDependencies?: Record<string, string>;
1913
- peerDependencies?: Record<string, string>;
1914
- };
1915
-
1916
- let updated = false;
1917
-
1918
- for (const depType of [
1919
- "dependencies",
1920
- "devDependencies",
1921
- "peerDependencies",
1922
- ] as const) {
1923
- const deps = pkgJson[depType];
1924
- if (!deps) continue;
1925
-
1926
- for (const [name, version] of Object.entries(deps)) {
1927
- if (
1928
- name in rootPkg.workspaces.catalog &&
1929
- version !== "catalog:"
1930
- ) {
1931
- deps[name] = "catalog:";
1932
- updated = true;
1933
- }
1934
- }
1935
- }
1936
-
1937
- if (updated || input.force) {
1938
- await Bun.write(pkgPath, JSON.stringify(pkgJson, null, 2));
1939
- packagesUpdated.push(pkg);
1940
- }
1941
- }
1942
-
1943
- const results = await syncFiles({
1944
- configDir,
1945
- packages: Object.keys(updatedBosConfig.app),
1946
- bosConfig: updatedBosConfig,
1947
- catalog: rootPkg.workspaces?.catalog ?? {},
1948
- force: input.force,
1949
- });
1950
-
1951
- const filesSynced =
1952
- results.length > 0
1953
- ? results.map((r) => ({ package: r.package, files: r.files }))
1954
- : undefined;
1955
-
1956
- return {
1957
- status: "updated" as const,
1958
- account,
1959
- gateway,
1960
- socialUrl,
1961
- hostUrl,
1962
- catalogUpdated: true,
1963
- packagesUpdated,
1964
- filesSynced,
1965
- };
1966
- } catch (error) {
1967
- return {
1968
- status: "error" as const,
1969
- account,
1970
- gateway,
1971
- hostUrl: "",
1972
- catalogUpdated: false,
1973
- packagesUpdated: [],
1974
- error: error instanceof Error ? error.message : "Unknown error",
1975
- };
1976
- }
1977
- }),
1978
-
1979
- kill: builder.kill.handler(async ({ input }) => {
1980
- const killEffect = Effect.gen(function* () {
1981
- const registry = yield* createProcessRegistry();
1982
- const result = yield* registry.killAll(input.force);
1983
- return {
1984
- status: "killed" as const,
1985
- killed: result.killed,
1986
- failed: result.failed,
1987
- };
1988
- });
1989
-
1990
- try {
1991
- return await Effect.runPromise(killEffect);
1992
- } catch (error) {
1993
- return {
1994
- status: "error" as const,
1995
- killed: [],
1996
- failed: [],
1997
- error: error instanceof Error ? error.message : "Unknown error",
1998
- };
1999
- }
2000
- }),
2001
-
2002
- ps: builder.ps.handler(async () => {
2003
- const psEffect = Effect.gen(function* () {
2004
- const registry = yield* createProcessRegistry();
2005
- const processes = yield* registry.getAll();
2006
- return {
2007
- status: "listed" as const,
2008
- processes,
2009
- };
2010
- });
2011
-
2012
- try {
2013
- return await Effect.runPromise(psEffect);
2014
- } catch (error) {
2015
- return {
2016
- status: "error" as const,
2017
- processes: [],
2018
- error: error instanceof Error ? error.message : "Unknown error",
2019
- };
2020
- }
2021
- }),
2022
-
2023
- dockerBuild: builder.dockerBuild.handler(async ({ input }) => {
2024
- const { configDir, bosConfig } = deps;
2025
-
2026
- const dockerEffect = Effect.gen(function* () {
2027
- const { execa } = yield* Effect.tryPromise({
2028
- try: () => import("execa"),
2029
- catch: (e) => new Error(`Failed to import execa: ${e}`),
2030
- });
2031
-
2032
- const dockerfile =
2033
- input.target === "development" ? "Dockerfile.dev" : "Dockerfile";
2034
- const imageName = bosConfig?.account?.replace(/\./g, "-") || "bos-app";
2035
- const tag =
2036
- input.tag || (input.target === "development" ? "dev" : "latest");
2037
- const fullTag = `${imageName}:${tag}`;
2038
-
2039
- const args = ["build", "-f", dockerfile, "-t", fullTag];
2040
- if (input.noCache) {
2041
- args.push("--no-cache");
2042
- }
2043
- args.push(".");
2044
-
2045
- yield* Effect.tryPromise({
2046
- try: () =>
2047
- execa("docker", args, {
2048
- cwd: configDir,
2049
- stdio: "inherit",
2050
- }),
2051
- catch: (e) => new Error(`Docker build failed: ${e}`),
2052
- });
2053
-
2054
- return {
2055
- status: "built" as const,
2056
- image: imageName,
2057
- tag: fullTag,
2058
- };
2059
- });
2060
-
2061
- try {
2062
- return await Effect.runPromise(dockerEffect);
2063
- } catch (error) {
2064
- return {
2065
- status: "error" as const,
2066
- image: "",
2067
- tag: "",
2068
- error: error instanceof Error ? error.message : "Unknown error",
2069
- };
2070
- }
2071
- }),
2072
-
2073
- dockerRun: builder.dockerRun.handler(async ({ input }) => {
2074
- const { bosConfig } = deps;
2075
-
2076
- const dockerEffect = Effect.gen(function* () {
2077
- const { execa } = yield* Effect.tryPromise({
2078
- try: () => import("execa"),
2079
- catch: (e) => new Error(`Failed to import execa: ${e}`),
2080
- });
2081
-
2082
- const imageName = bosConfig?.account?.replace(/\./g, "-") || "bos-app";
2083
- const tag = input.target === "development" ? "dev" : "latest";
2084
- const fullTag = `${imageName}:${tag}`;
2085
- const port =
2086
- input.port || (input.target === "development" ? 4000 : 3000);
2087
-
2088
- const args = ["run"];
2089
-
2090
- if (input.detach) {
2091
- args.push("-d");
2092
- }
2093
-
2094
- args.push("-p", `${port}:${port}`);
2095
- args.push("-e", `PORT=${port}`);
2096
-
2097
- if (input.target === "development") {
2098
- args.push("-e", `MODE=${input.mode}`);
2099
- }
2100
-
2101
- if (input.env) {
2102
- for (const [key, value] of Object.entries(input.env)) {
2103
- args.push("-e", `${key}=${value}`);
2104
- }
2105
- }
2106
-
2107
- if (bosConfig) {
2108
- args.push("-e", `BOS_ACCOUNT=${bosConfig.account}`);
2109
- const gateway = bosConfig.gateway as
2110
- | { production?: string }
2111
- | string
2112
- | undefined;
2113
- if (gateway) {
2114
- const domain =
2115
- typeof gateway === "string"
2116
- ? gateway
2117
- : gateway.production?.replace(/^https?:\/\//, "") || "";
2118
- if (domain) {
2119
- args.push("-e", `GATEWAY_DOMAIN=${domain}`);
2120
- }
2121
- }
2122
- }
2123
-
2124
- args.push(fullTag);
2125
-
2126
- const result = yield* Effect.tryPromise({
2127
- try: () =>
2128
- execa("docker", args, {
2129
- stdio: input.detach ? "pipe" : "inherit",
2130
- }),
2131
- catch: (e) => new Error(`Docker run failed: ${e}`),
2132
- });
2133
-
2134
- const containerId =
2135
- input.detach && result.stdout
2136
- ? result.stdout.trim().slice(0, 12)
2137
- : "attached";
2138
-
2139
- return {
2140
- status: "running" as const,
2141
- containerId,
2142
- url: `http://localhost:${port}`,
2143
- };
2144
- });
2145
-
2146
- try {
2147
- return await Effect.runPromise(dockerEffect);
2148
- } catch (error) {
2149
- return {
2150
- status: "error" as const,
2151
- containerId: "",
2152
- url: "",
2153
- error: error instanceof Error ? error.message : "Unknown error",
2154
- };
2155
- }
2156
- }),
2157
-
2158
- dockerStop: builder.dockerStop.handler(async ({ input }) => {
2159
- const { bosConfig } = deps;
2160
-
2161
- const dockerEffect = Effect.gen(function* () {
2162
- const { execa } = yield* Effect.tryPromise({
2163
- try: () => import("execa"),
2164
- catch: (e) => new Error(`Failed to import execa: ${e}`),
2165
- });
2166
-
2167
- const stopped: string[] = [];
2168
-
2169
- if (input.containerId) {
2170
- yield* Effect.tryPromise({
2171
- try: () => execa("docker", ["stop", input.containerId!]),
2172
- catch: (e) => new Error(`Failed to stop container: ${e}`),
2173
- });
2174
- stopped.push(input.containerId!);
2175
- } else if (input.all) {
2176
- const imageName =
2177
- bosConfig?.account?.replace(/\./g, "-") || "bos-app";
2178
-
2179
- const psResult = yield* Effect.tryPromise({
2180
- try: () =>
2181
- execa("docker", [
2182
- "ps",
2183
- "-q",
2184
- "--filter",
2185
- `ancestor=${imageName}`,
2186
- ]),
2187
- catch: () => new Error("Failed to list containers"),
2188
- });
2189
-
2190
- const containerIds = psResult.stdout
2191
- .trim()
2192
- .split("\n")
2193
- .filter(Boolean);
2194
-
2195
- for (const id of containerIds) {
2196
- yield* Effect.tryPromise({
2197
- try: () => execa("docker", ["stop", id]),
2198
- catch: () => new Error(`Failed to stop container ${id}`),
2199
- }).pipe(Effect.catchAll(() => Effect.void));
2200
- stopped.push(id);
2201
- }
2202
- }
2203
-
2204
- return {
2205
- status: "stopped" as const,
2206
- stopped,
2207
- };
2208
- });
2209
-
2210
- try {
2211
- return await Effect.runPromise(dockerEffect);
2212
- } catch (error) {
2213
- return {
2214
- status: "error" as const,
2215
- stopped: [],
2216
- error: error instanceof Error ? error.message : "Unknown error",
2217
- };
2218
- }
2219
- }),
2220
-
2221
- monitor: builder.monitor.handler(async ({ input }) => {
2222
- try {
2223
- if (input.json) {
2224
- const snapshot = await runWithInfo(
2225
- createSnapshotWithPlatform(
2226
- input.ports ? { ports: input.ports } : undefined,
2227
- ),
2228
- );
2229
- return {
2230
- status: "snapshot" as const,
2231
- snapshot: snapshot as any,
2232
- };
2233
- }
2234
-
2235
- if (input.watch) {
2236
- runMonitorCli({ ports: input.ports, json: false });
2237
- return {
2238
- status: "watching" as const,
2239
- };
2240
- }
2241
-
2242
- const snapshot = await runWithInfo(
2243
- createSnapshotWithPlatform(
2244
- input.ports ? { ports: input.ports } : undefined,
2245
- ),
2246
- );
2247
- console.log(formatSnapshotSummary(snapshot));
2248
-
2249
- return {
2250
- status: "snapshot" as const,
2251
- snapshot: snapshot as any,
2252
- };
2253
- } catch (error) {
2254
- return {
2255
- status: "error" as const,
2256
- error: error instanceof Error ? error.message : "Unknown error",
2257
- };
2258
- }
2259
- }),
2260
-
2261
- session: builder.session.handler(async ({ input }) => {
2262
- const sessionEffect = Effect.gen(function* () {
2263
- const recorder = yield* SessionRecorder.create({
2264
- ports: [3000],
2265
- snapshotIntervalMs: input.snapshotInterval,
2266
- headless: input.headless,
2267
- baseUrl: "http://localhost:3000",
2268
- timeout: input.timeout,
2269
- });
2270
-
2271
- try {
2272
- yield* recorder.startServers("start");
2273
-
2274
- yield* recorder.startRecording();
2275
-
2276
- const browser = yield* recorder.launchBrowser();
2277
-
2278
- if (input.flow === "login") {
2279
- yield* runLoginFlow(
2280
- browser,
2281
- {
2282
- recordEvent: (type, label, metadata) =>
2283
- recorder.recordEvent(type, label, metadata).pipe(
2284
- Effect.asVoid,
2285
- Effect.catchAll(() => Effect.void),
2286
- ),
2287
- },
2288
- {
2289
- baseUrl: "http://localhost:3000",
2290
- headless: input.headless,
2291
- stubWallet: input.headless,
2292
- timeout: 30000,
2293
- },
2294
- );
2295
- } else if (input.flow === "navigation" && input.routes) {
2296
- yield* runNavigationFlow(
2297
- browser,
2298
- {
2299
- recordEvent: (type, label, metadata) =>
2300
- recorder.recordEvent(type, label, metadata).pipe(
2301
- Effect.asVoid,
2302
- Effect.catchAll(() => Effect.void),
2303
- ),
2304
- },
2305
- input.routes,
2306
- "http://localhost:3000",
2307
- );
2308
- } else {
2309
- yield* navigateTo(browser.page, "http://localhost:3000");
2310
- yield* Effect.sleep("5 seconds");
2311
- }
2312
-
2313
- yield* recorder.cleanup();
2314
-
2315
- const report = yield* recorder.stopRecording();
2316
-
2317
- yield* recorder.exportReport(input.output, input.format);
2318
-
2319
- console.log(formatReportSummary(report));
2320
-
2321
- return {
2322
- status: report.summary.hasLeaks
2323
- ? ("leaks_detected" as const)
2324
- : ("completed" as const),
2325
- sessionId: recorder.getSessionId(),
2326
- reportPath: input.output,
2327
- summary: {
2328
- totalMemoryDeltaMb: report.summary.totalMemoryDeltaMb,
2329
- peakMemoryMb: report.summary.peakMemoryMb,
2330
- averageMemoryMb: report.summary.averageMemoryMb,
2331
- processesSpawned: report.summary.processesSpawned,
2332
- processesKilled: report.summary.processesKilled,
2333
- orphanedProcesses: report.summary.orphanedProcesses,
2334
- portsUsed: report.summary.portsUsed,
2335
- portsLeaked: report.summary.portsLeaked,
2336
- hasLeaks: report.summary.hasLeaks,
2337
- eventCount: report.summary.eventCount,
2338
- duration: report.summary.duration,
2339
- },
2340
- };
2341
- } catch (error) {
2342
- yield* recorder.cleanup();
2343
- throw error;
2344
- }
2345
- });
2346
-
2347
- try {
2348
- return await Effect.runPromise(sessionEffect);
2349
- } catch (error) {
2350
- return {
2351
- status: "error" as const,
2352
- error: error instanceof Error ? error.message : "Unknown error",
2353
- };
2354
- }
2355
- }),
2356
- }),
490
+ variables: z.object({
491
+ configPath: z.string().optional(),
492
+ }),
493
+ secrets: z.object({}),
494
+ contract: bosContract,
495
+ initialize: (config: any) =>
496
+ Effect.promise(async () => {
497
+ const configResult = await loadConfig({ path: config.variables.configPath });
498
+ return {
499
+ bosConfig: configResult?.config ?? null,
500
+ runtimeConfig: configResult?.runtime ?? null,
501
+ configDir: getProjectRoot(),
502
+ } satisfies BosDeps;
503
+ }),
504
+ shutdown: () => Effect.void,
505
+ createRouter: (deps: BosDeps, builder: any) => ({
506
+ config: builder.config.handler(async () => buildConfigResult(deps.bosConfig)),
507
+
508
+ pluginAdd: builder.pluginAdd.handler(async ({ input }: { input: PluginAddOptions }) => {
509
+ if (!deps.bosConfig) {
510
+ return {
511
+ status: "error" as const,
512
+ key: "",
513
+ error: "No bos.config.json found",
514
+ };
515
+ }
516
+
517
+ const key = sanitizePluginKey(input.as ?? defaultPluginKey(input.source));
518
+ const existing = deps.bosConfig.plugins?.[key];
519
+ const nextPlugins = { ...(deps.bosConfig.plugins ?? {}) };
520
+
521
+ nextPlugins[key] = input.source.startsWith("local:")
522
+ ? {
523
+ ...(existing ?? {}),
524
+ development: input.source,
525
+ production: input.production ?? existing?.production,
526
+ }
527
+ : {
528
+ ...(existing ?? {}),
529
+ production: input.production ?? input.source,
530
+ };
531
+
532
+ deps.bosConfig = {
533
+ ...deps.bosConfig,
534
+ plugins: nextPlugins,
535
+ };
536
+
537
+ await saveBosConfig(deps.configDir, deps.bosConfig);
538
+ await refreshApiContractBridge(deps.configDir);
539
+
540
+ return {
541
+ status: "added" as const,
542
+ key,
543
+ development: deps.bosConfig.plugins?.[key]?.development,
544
+ production: deps.bosConfig.plugins?.[key]?.production,
545
+ };
546
+ }),
547
+
548
+ pluginRemove: builder.pluginRemove.handler(
549
+ async ({ input }: { input: PluginRemoveOptions }) => {
550
+ if (!deps.bosConfig) {
551
+ return {
552
+ status: "error" as const,
553
+ key: input.key,
554
+ error: "No bos.config.json found",
555
+ };
556
+ }
557
+
558
+ if (!deps.bosConfig.plugins?.[input.key]) {
559
+ return {
560
+ status: "error" as const,
561
+ key: input.key,
562
+ error: `Plugin '${input.key}' is not configured`,
563
+ };
564
+ }
565
+
566
+ const nextPlugins = { ...(deps.bosConfig.plugins ?? {}) };
567
+ delete nextPlugins[input.key];
568
+ deps.bosConfig = {
569
+ ...deps.bosConfig,
570
+ plugins: Object.keys(nextPlugins).length > 0 ? nextPlugins : undefined,
571
+ };
572
+
573
+ await saveBosConfig(deps.configDir, deps.bosConfig);
574
+ await refreshApiContractBridge(deps.configDir);
575
+
576
+ return {
577
+ status: "removed" as const,
578
+ key: input.key,
579
+ };
580
+ },
581
+ ),
582
+
583
+ pluginList: builder.pluginList.handler(async () => {
584
+ const plugins: PluginListResult["plugins"] = listPluginAttachments(deps.bosConfig);
585
+ return {
586
+ status: "listed" as const,
587
+ plugins,
588
+ };
589
+ }),
590
+
591
+ pluginPublish: builder.pluginPublish.handler(
592
+ async ({ input }: { input: PluginPublishOptions }) => {
593
+ if (!deps.bosConfig) {
594
+ return {
595
+ status: "error" as const,
596
+ key: input.key,
597
+ error: "No bos.config.json found",
598
+ };
599
+ }
600
+
601
+ const attachment = deps.bosConfig.plugins?.[input.key];
602
+ if (!attachment) {
603
+ return {
604
+ status: "error" as const,
605
+ key: input.key,
606
+ error: `Plugin '${input.key}' is not configured`,
607
+ };
608
+ }
609
+
610
+ const localPath = pluginLocalPath(deps.configDir, attachment);
611
+ if (!localPath) {
612
+ return {
613
+ status: "error" as const,
614
+ key: input.key,
615
+ error: `Plugin '${input.key}' does not have a local development path`,
616
+ };
617
+ }
618
+
619
+ const pkgPath = join(localPath, "package.json");
620
+ if (!(await Bun.file(pkgPath).exists())) {
621
+ return {
622
+ status: "error" as const,
623
+ key: input.key,
624
+ error: `Missing package.json at ${localPath}`,
625
+ };
626
+ }
627
+
628
+ const pkgJson = (await Bun.file(pkgPath).json()) as { scripts?: Record<string, string> };
629
+ const script = pkgJson.scripts?.deploy ? "deploy" : "build";
630
+
631
+ const { stdout, stderr, exitCode } = (await run("bun", ["run", script], {
632
+ cwd: localPath,
633
+ capture: true,
634
+ })) as { stdout: string; stderr: string; exitCode: number };
635
+
636
+ if (exitCode !== 0) {
637
+ if (stdout.trim()) process.stdout.write(stdout);
638
+ if (stderr.trim()) process.stderr.write(stderr);
639
+ return {
640
+ status: "error" as const,
641
+ key: input.key,
642
+ error: `Publish failed with exit code ${exitCode}`,
643
+ };
644
+ }
645
+
646
+ if (stdout.trim()) process.stdout.write(stdout);
647
+ if (stderr.trim()) process.stderr.write(stderr);
648
+
649
+ const publishedUrl = extractPublishedUrl(`${stdout}\n${stderr}`);
650
+ if (publishedUrl) {
651
+ deps.bosConfig = {
652
+ ...deps.bosConfig,
653
+ plugins: {
654
+ ...(deps.bosConfig.plugins ?? {}),
655
+ [input.key]: {
656
+ ...(deps.bosConfig.plugins?.[input.key] ?? {}),
657
+ production: publishedUrl,
658
+ },
659
+ },
660
+ };
661
+ await saveBosConfig(deps.configDir, deps.bosConfig);
662
+ await refreshApiContractBridge(deps.configDir);
663
+ }
664
+
665
+ return {
666
+ status: "published" as const,
667
+ key: input.key,
668
+ path: localPath,
669
+ script,
670
+ production: publishedUrl ?? attachment.production,
671
+ };
672
+ },
673
+ ),
674
+
675
+ dev: builder.dev.handler(async ({ input }: { input: DevOptions }) => {
676
+ const localPackages = detectLocalPackages(
677
+ deps.bosConfig ?? undefined,
678
+ deps.runtimeConfig ?? undefined,
679
+ );
680
+
681
+ const appConfig = buildAppConfig({
682
+ host: localPackages.includes("host") ? (input.host as string) : "remote",
683
+ ui: localPackages.includes("ui") ? (input.ui as string) : "remote",
684
+ api: localPackages.includes("api") ? (input.api as string) : "remote",
685
+ proxy: input.proxy,
686
+ ssr: input.ssr,
687
+ });
688
+
689
+ const sharedSync = await syncAndGenerateSharedUi({
690
+ configDir: deps.configDir,
691
+ hostMode: appConfig.host,
692
+ bosConfig: deps.bosConfig ?? undefined,
693
+ });
694
+ if (sharedSync.catalogChanged) {
695
+ await run("bun", ["install"], { cwd: deps.configDir });
696
+ }
697
+ if (
698
+ (appConfig.api === "local" && !appConfig.proxy) ||
699
+ localPackages.some((pkg) => pkg.startsWith("plugin:"))
700
+ ) {
701
+ await buildEveryPluginQuietly(deps.configDir);
702
+ }
703
+
704
+ await buildEverythingDevQuietly(deps.configDir);
705
+
706
+ const refreshed = await loadConfig({ cwd: deps.configDir });
707
+ deps.bosConfig = refreshed?.config ?? deps.bosConfig;
708
+ deps.runtimeConfig = refreshed?.runtime ?? deps.runtimeConfig;
709
+
710
+ if (!deps.bosConfig) {
711
+ return {
712
+ status: "error" as const,
713
+ description: "No bos.config.json found",
714
+ processes: [],
715
+ };
716
+ }
717
+
718
+ if (appConfig.proxy && !resolveProxyUrl(deps.bosConfig)) {
719
+ return {
720
+ status: "error" as const,
721
+ description: "No valid proxy URL configured in bos.config.json",
722
+ processes: [],
723
+ };
724
+ }
725
+
726
+ const refreshedLocalPackages = detectLocalPackages(
727
+ deps.bosConfig ?? undefined,
728
+ deps.runtimeConfig ?? undefined,
729
+ );
730
+ const processes = determineProcesses(appConfig, refreshedLocalPackages, deps.runtimeConfig);
731
+ const env = await buildEnvVars(appConfig, deps.bosConfig);
732
+ const hostPort = input.port ?? getHostDevelopmentPort(deps.bosConfig.app.host.development);
733
+ const developmentRuntime = buildRuntimeConfig(deps.bosConfig, {
734
+ uiSource: appConfig.ui,
735
+ apiSource: appConfig.api,
736
+ hostUrl: `http://localhost:${hostPort}`,
737
+ proxy: env.API_PROXY,
738
+ env: "development",
739
+ plugins: deps.runtimeConfig?.plugins,
740
+ });
741
+ const runtimeConfig = await prepareDevelopmentRuntimeConfig(developmentRuntime, {
742
+ hostPort,
743
+ ssr: appConfig.ssr,
744
+ });
745
+
746
+ await syncApiContractBridge({
747
+ configDir: deps.configDir,
748
+ runtimeConfig: runtimeConfig,
749
+ apiBaseUrl: runtimeConfig.api.url,
750
+ });
751
+
752
+ const orchestrator: AppOrchestrator = {
753
+ packages: processes,
754
+ env,
755
+ description: buildDescription(appConfig),
756
+ appConfig,
757
+ bosConfig: deps.bosConfig,
758
+ runtimeConfig,
759
+ port: parsePort(runtimeConfig.hostUrl),
760
+ interactive: input.interactive,
761
+ };
762
+
763
+ startApp(orchestrator);
764
+
765
+ return {
766
+ status: "started" as const,
767
+ description: orchestrator.description,
768
+ processes,
769
+ };
770
+ }),
771
+
772
+ start: builder.start.handler(async ({ input }: { input: StartOptions }) => {
773
+ let remoteConfig: BosConfig | null = null;
774
+
775
+ if (input.account && input.domain) {
776
+ remoteConfig = await fetchPublishedConfig(input.account, input.domain);
777
+ if (!remoteConfig) {
778
+ return {
779
+ status: "error" as const,
780
+ url: "",
781
+ };
782
+ }
783
+ }
784
+
785
+ const config = remoteConfig || deps.bosConfig;
786
+ if (!config) {
787
+ return {
788
+ status: "error" as const,
789
+ url: "",
790
+ };
791
+ }
792
+
793
+ const port = input.port ?? getHostDevelopmentPort(config.app.host.development);
794
+ const appConfig: AppConfig = { host: "remote", ui: "remote", api: "remote" };
795
+ const env = await buildEnvVars(appConfig, config);
796
+ const isStaging = input.env === "staging";
797
+ const runtimePlugins = remoteConfig
798
+ ? await buildRuntimePluginsForConfig(config, deps.configDir, "production")
799
+ : deps.runtimeConfig?.plugins;
800
+ const runtimeConfig = buildRuntimeConfig(config, {
801
+ uiSource: "remote",
802
+ apiSource: "remote",
803
+ hostUrl: `http://localhost:${port}`,
804
+ env: "production",
805
+ plugins: runtimePlugins,
806
+ });
807
+
808
+ await syncApiContractBridge({
809
+ configDir: deps.configDir,
810
+ runtimeConfig: runtimeConfig,
811
+ apiBaseUrl: runtimeConfig.api.url,
812
+ });
813
+
814
+ const stagingEnvVars: Record<string, string> = isStaging
815
+ ? { GATEWAY_DOMAIN: config.staging?.domain ?? config.domain ?? "" }
816
+ : {};
817
+
818
+ const orchestrator: AppOrchestrator = {
819
+ packages: ["host"],
820
+ env: {
821
+ NODE_ENV: "production",
822
+ ...env,
823
+ ...stagingEnvVars,
824
+ },
825
+ description: `${isStaging ? "Staging" : "Production"} Mode (${config.account})`,
826
+ appConfig,
827
+ bosConfig: config,
828
+ runtimeConfig,
829
+ port,
830
+ interactive: input.interactive,
831
+ noLogs: true,
832
+ };
833
+
834
+ startApp(orchestrator);
835
+ return {
836
+ status: "running" as const,
837
+ url: `http://localhost:${port}`,
838
+ };
839
+ }),
840
+
841
+ build: builder.build.handler(async ({ input }: { input: BuildOptions }) => {
842
+ if (!deps.bosConfig) {
843
+ return {
844
+ status: "error" as const,
845
+ built: [],
846
+ skipped: [],
847
+ };
848
+ }
849
+
850
+ const targets = selectWorkspaceTargets(input.packages, deps.bosConfig);
851
+ if (targets.length === 0) {
852
+ return {
853
+ status: "error" as const,
854
+ built: [],
855
+ skipped: [],
856
+ };
857
+ }
858
+
859
+ const runtimeConfig = buildRuntimeConfig(deps.bosConfig, {
860
+ uiSource: deps.bosConfig.app.ui?.development ? "local" : "remote",
861
+ apiSource: deps.bosConfig.app.api?.development ? "local" : "remote",
862
+ hostUrl: resolveDevelopmentHostUrl(deps.bosConfig.app.host.development),
863
+ env: "development",
864
+ plugins: deps.runtimeConfig?.plugins,
865
+ });
866
+
867
+ await syncApiContractBridge({
868
+ configDir: deps.configDir,
869
+ runtimeConfig,
870
+ apiBaseUrl: runtimeConfig.api.url,
871
+ });
872
+
873
+ const { built, skipped } = await buildWorkspaceTargets({
874
+ configDir: deps.configDir,
875
+ bosConfig: deps.bosConfig,
876
+ runtimeConfig: runtimeConfig,
877
+ targets,
878
+ deploy: input.deploy,
879
+ });
880
+
881
+ if (built.length === 0) {
882
+ return {
883
+ status: "error" as const,
884
+ built: [],
885
+ skipped,
886
+ };
887
+ }
888
+
889
+ return {
890
+ status: "success" as const,
891
+ built,
892
+ skipped,
893
+ deployed: input.deploy,
894
+ };
895
+ }),
896
+
897
+ publish: builder.publish.handler(async ({ input }: { input: PublishOptions }) => {
898
+ if (!deps.bosConfig) {
899
+ return {
900
+ status: "error" as const,
901
+ registryUrl: "",
902
+ error: "No bos.config.json found",
903
+ };
904
+ }
905
+
906
+ const account = deps.bosConfig.account;
907
+ const gateway = deps.bosConfig.domain;
908
+ if (!gateway) {
909
+ return {
910
+ status: "error" as const,
911
+ registryUrl: "",
912
+ error: "bos.config.json must define domain to publish",
913
+ };
914
+ }
915
+
916
+ const network = input.network ?? getNetworkIdForAccount(account);
917
+ const bosUrl = `bos://${account}/${gateway}`;
918
+ const registryUrl = buildRegistryConfigUrlForNetwork(network, account, gateway);
919
+ const targets = selectWorkspaceTargets(input.packages, deps.bosConfig);
920
+
921
+ let publishConfig = deps.bosConfig;
922
+ let built: string[] | undefined;
923
+ let skipped: string[] | undefined;
924
+
925
+ if (input.dryRun) {
926
+ return {
927
+ status: "dry-run" as const,
928
+ registryUrl,
929
+ built,
930
+ skipped,
931
+ };
932
+ }
933
+
934
+ if (input.deploy) {
935
+ const result = await buildWorkspaceTargets({
936
+ configDir: deps.configDir,
937
+ bosConfig: deps.bosConfig,
938
+ runtimeConfig: deps.runtimeConfig,
939
+ targets,
940
+ deploy: true,
941
+ });
942
+ built = result.built;
943
+ skipped = result.skipped;
944
+
945
+ const refreshed = await loadConfig({ cwd: deps.configDir });
946
+ if (refreshed?.config) {
947
+ deps.bosConfig = refreshed.config;
948
+ deps.runtimeConfig = refreshed.runtime;
949
+ publishConfig = refreshed.config;
950
+ }
951
+ }
952
+
953
+ const payload = JSON.stringify({
954
+ [`apps/${account}/${gateway}/bos.config.json`]: JSON.stringify(publishConfig),
955
+ });
956
+ const argsBase64 = Buffer.from(payload).toString("base64");
957
+ const privateKey =
958
+ input.privateKey || process.env.NEAR_PRIVATE_KEY || process.env.BOS_NEAR_PRIVATE_KEY;
959
+
960
+ try {
961
+ await Effect.runPromise(ensureNearCli);
962
+ let txHash: string | undefined;
963
+
964
+ try {
965
+ const tx = await Effect.runPromise(
966
+ executeTransaction({
967
+ account,
968
+ contract: getRegistryNamespaceForNetwork(network),
969
+ method: "__fastdata_kv",
970
+ argsBase64,
971
+ network,
972
+ privateKey,
973
+ gas: "300Tgas",
974
+ deposit: "0NEAR",
975
+ }),
976
+ );
977
+ txHash = tx.txHash;
978
+ } catch (error) {
979
+ txHash = extractTransactionHash(error);
980
+
981
+ if (!txHash) {
982
+ throw error;
983
+ }
984
+
985
+ const verifiedConfig = await fetchBosConfigFromFastKv<BosConfig>(bosUrl);
986
+ if (JSON.stringify(verifiedConfig) !== JSON.stringify(publishConfig)) {
987
+ throw error;
988
+ }
989
+ }
990
+
991
+ return {
992
+ status: "published" as const,
993
+ registryUrl,
994
+ txHash,
995
+ built,
996
+ skipped,
997
+ };
998
+ } catch (error) {
999
+ return {
1000
+ status: "error" as const,
1001
+ registryUrl,
1002
+ error: error instanceof Error ? error.message : "Unknown error",
1003
+ built,
1004
+ skipped,
1005
+ };
1006
+ }
1007
+ }),
1008
+
1009
+ keyPublish: builder.keyPublish.handler(async ({ input }: { input: KeyPublishOptions }) => {
1010
+ if (!deps.bosConfig) {
1011
+ return {
1012
+ status: "error" as const,
1013
+ account: "",
1014
+ network: "mainnet" as const,
1015
+ contract: "",
1016
+ allowance: input.allowance,
1017
+ functionNames: PUBLISH_FUNCTION_NAMES,
1018
+ error: "No bos.config.json found",
1019
+ };
1020
+ }
1021
+
1022
+ const account = deps.bosConfig.account;
1023
+ const network = getNetworkIdForAccount(account);
1024
+ const contract = getRegistryNamespaceForAccount(account);
1025
+ try {
1026
+ await Effect.runPromise(ensureNearCli);
1027
+ const keyPair = await addFunctionCallAccessKey({
1028
+ account,
1029
+ contract,
1030
+ allowance: input.allowance,
1031
+ functionNames: PUBLISH_FUNCTION_NAMES,
1032
+ network,
1033
+ });
1034
+
1035
+ return {
1036
+ status: "published" as const,
1037
+ account,
1038
+ network,
1039
+ contract,
1040
+ allowance: input.allowance,
1041
+ functionNames: PUBLISH_FUNCTION_NAMES,
1042
+ publicKey: keyPair.publicKey,
1043
+ privateKey: keyPair.privateKey,
1044
+ };
1045
+ } catch (error) {
1046
+ return {
1047
+ status: "error" as const,
1048
+ account,
1049
+ network,
1050
+ contract,
1051
+ allowance: input.allowance,
1052
+ functionNames: PUBLISH_FUNCTION_NAMES,
1053
+ error: error instanceof Error ? error.message : "Unknown error",
1054
+ };
1055
+ }
1056
+ }),
1057
+
1058
+ init: builder.init.handler(async ({ input }: { input: InitOptions }) => {
1059
+ try {
1060
+ let account = input.account;
1061
+ let gateway = input.gateway;
1062
+ let destination = input.destination;
1063
+ let name = input.name;
1064
+ let domain = input.domain;
1065
+ let withHost = input.withHost;
1066
+
1067
+ if (!account || !gateway) {
1068
+ if (input.noInteractive) {
1069
+ return {
1070
+ status: "error" as const,
1071
+ destination: "",
1072
+ parentAccount: account ?? "",
1073
+ parentGateway: gateway ?? "",
1074
+ name: input.name,
1075
+ domain: input.domain,
1076
+ extends: account && gateway ? `bos://${account}/${gateway}` : "",
1077
+ filesCopied: 0,
1078
+ error:
1079
+ "account and gateway are required (use --no-interactive to skip prompts and provide them as positional args)",
1080
+ };
1081
+ }
1082
+
1083
+ const prompted = await promptInitOptions({
1084
+ account,
1085
+ gateway,
1086
+ destination,
1087
+ name,
1088
+ domain,
1089
+ withHost,
1090
+ });
1091
+ account = prompted.account;
1092
+ gateway = prompted.gateway;
1093
+ destination = prompted.destination;
1094
+ name = prompted.name;
1095
+ domain = prompted.domain;
1096
+ withHost = prompted.withHost;
1097
+ }
1098
+
1099
+ destination = destination || gateway;
1100
+
1101
+ const { sourceDir, cleanup } = await resolveSourceDir({
1102
+ account,
1103
+ gateway,
1104
+ source: input.source,
1105
+ });
1106
+
1107
+ try {
1108
+ const patterns = await readTemplatekeep(sourceDir);
1109
+ if (patterns.length === 0) {
1110
+ return {
1111
+ status: "error" as const,
1112
+ destination,
1113
+ parentAccount: account,
1114
+ parentGateway: gateway,
1115
+ name,
1116
+ domain,
1117
+ extends: `bos://${account}/${gateway}`,
1118
+ filesCopied: 0,
1119
+ error: "No .templatekeep found in template source",
1120
+ };
1121
+ }
1122
+
1123
+ const filesCopied = await copyFilteredFiles(sourceDir, destination, patterns, {
1124
+ withHost,
1125
+ });
1126
+
1127
+ await personalizeConfig(destination, {
1128
+ parentAccount: account,
1129
+ parentGateway: gateway,
1130
+ name: name || account,
1131
+ domain: domain || gateway,
1132
+ workspaceOpts: { sourceDir },
1133
+ });
1134
+
1135
+ if (!input.noInstall) {
1136
+ await runBunInstall(destination);
1137
+ }
1138
+
1139
+ return {
1140
+ status: "initialized" as const,
1141
+ destination: resolve(destination),
1142
+ parentAccount: account,
1143
+ parentGateway: gateway,
1144
+ name,
1145
+ domain,
1146
+ extends: `bos://${account}/${gateway}`,
1147
+ filesCopied,
1148
+ };
1149
+ } finally {
1150
+ await cleanup();
1151
+ }
1152
+ } catch (error) {
1153
+ return {
1154
+ status: "error" as const,
1155
+ destination: input.destination ?? input.gateway ?? "",
1156
+ parentAccount: input.account ?? "",
1157
+ parentGateway: input.gateway ?? "",
1158
+ name: input.name,
1159
+ domain: input.domain,
1160
+ extends: input.account && input.gateway ? `bos://${input.account}/${input.gateway}` : "",
1161
+ filesCopied: 0,
1162
+ error: error instanceof Error ? error.message : "Unknown error",
1163
+ };
1164
+ }
1165
+ }),
1166
+ }),
2357
1167
  });
1168
+
1169
+ function extractTransactionHash(error: unknown) {
1170
+ const message = error instanceof Error ? error.message : String(error);
1171
+ const match =
1172
+ message.match(/Transaction ID:\s*([A-Za-z0-9]+)/i) ||
1173
+ message.match(/([A-HJ-NP-Za-km-z1-9]{43,44})/);
1174
+
1175
+ return match?.[1];
1176
+ }