The best way to control Claude Code, Codex and more from any computer or phone

main
ts 210 lines 7.14 KB
Raw
1 import * as NodePath from "node:path";
2 /**
3 * `@alchemy.run/frontend-frameworks/vocs/node` — the Node container deploy
4 * target for Vocs.
5 *
6 * Vocs is Waku-based RSC. The target runs the vocs build in a disposable
7 * child process (cwd = project root) with waku's node adapter, then writes
8 * a Node HTTP program that serves `clientDirectory` first (extensionless
9 * HTML: `/about` → `about/index.html`) and falls through to
10 * `INTERNAL_runFetch`. Vocs' default `renderStrategy` is `"dynamic"`, so
11 * dropping server modules would deploy an empty html-shell (no pages).
12 */
13 import * as Effect from "effect/Effect";
14 import * as FileSystem from "effect/FileSystem";
15 import * as Path from "effect/Path";
16 import { runBuildChild } from "../core/BuildChild.ts";
17 import { isInsideDevChild, runDevChild } from "../core/DevChild.ts";
18 import {
19 DeployTargetError,
20 Framework,
21 makeDeployTarget,
22 type Framework as FrameworkService,
23 } from "../core/index.ts";
24 import {
25 NODE_BUNDLE_CONDITIONS,
26 NODE_SERVE_ENTRY_FILE_NAME,
27 relativeClientDirExpression,
28 writeNodeServeEntry,
29 } from "../core/NodeServe.ts";
30 import type { VocsTarget } from "./Target.ts";
31 import { make as makeVocsLayer } from "./Vocs.ts";
32
33 export interface VocsNodeTargetConfig {}
34
35 const fail = (message: string, cause?: unknown) =>
36 new DeployTargetError({ platform: "node", message, cause });
37
38 /**
39 * The in-child target: adapter + empty vite plugins, no wholesale `build`
40 * (the child runs the regular vocs pipeline). `finish` writes the Node
41 * serve entry so dynamic pages SSR instead of serving the empty html-shell.
42 */
43 const makeNodeAdapterTarget = (
44 config: VocsNodeTargetConfig = {},
45 ): VocsTarget<VocsNodeTargetConfig> =>
46 makeDeployTarget({
47 platform: "node",
48 config,
49 bundle: {
50 conditions: [...NODE_BUNDLE_CONDITIONS],
51 },
52 adapter: (context) =>
53 Effect.succeed(NodePath.join(context.wakuDirectory, "dist/adapters/node.js")),
54 vitePlugins: () => Effect.sync(() => []),
55 finish: (output) =>
56 Effect.gen(function* () {
57 const fs = yield* FileSystem.FileSystem;
58 const path = yield* Path.Path;
59 if (output.distDirectory === undefined) {
60 return yield* fail("The vocs build produced no dist directory");
61 }
62 if (output.clientDirectory === undefined) {
63 return yield* fail(
64 "The vocs build produced no client directory for the Node serve entry",
65 );
66 }
67 const serverDir = path.join(output.distDirectory, "server");
68 const serverIndex = path.join(serverDir, "index.js");
69 const hasServerIndex = yield* fs
70 .exists(serverIndex)
71 .pipe(Effect.mapError((error) => fail("Failed to probe the built server entry", error)));
72 if (!hasServerIndex) {
73 return yield* fail(`The vocs build produced no server entry at ${serverIndex}`);
74 }
75 yield* fs
76 .writeFileString(
77 path.join(serverDir, "package.json"),
78 `${JSON.stringify({ type: "module" }, null, 2)}\n`,
79 )
80 .pipe(
81 Effect.mapError((error) => fail("Failed to write dist/server/package.json", error)),
82 );
83 const servePath = path.join(serverDir, NODE_SERVE_ENTRY_FILE_NAME);
84 return yield* writeNodeServeEntry({
85 output,
86 servePath,
87 serveModuleName: path.join("server", NODE_SERVE_ENTRY_FILE_NAME).replaceAll("\\", "/"),
88 clientDirExpression: relativeClientDirExpression(servePath, output.clientDirectory),
89 handler: {
90 kind: "fetch",
91 imports: `import { INTERNAL_runFetch } from "./index.js";`,
92 expr: "(req, ...args) => INTERNAL_runFetch(process.env, req, ...args)",
93 },
94 htmlHandling: "drop-trailing-slash",
95 platform: "node",
96 });
97 }),
98 });
99
100 export interface VocsNodeBuildChildConfig {
101 readonly rootDir: string;
102 readonly config: VocsNodeTargetConfig;
103 }
104
105 export const buildInChild = (config: VocsNodeBuildChildConfig) =>
106 Effect.gen(function* () {
107 const framework = yield* Framework.pipe(
108 Effect.provide(
109 makeVocsLayer({
110 root: config.rootDir,
111 target: makeNodeAdapterTarget(config.config),
112 }),
113 ),
114 );
115 return yield* framework.build({ root: config.rootDir });
116 });
117
118 /**
119 * Create the Node {@link VocsTarget}: the wholesale `build` hook runs
120 * the vocs pipeline in a child process (cwd = project root).
121 */
122 export const makeNodeTarget = (
123 config: VocsNodeTargetConfig = {},
124 ): VocsTarget<VocsNodeTargetConfig> => ({
125 ...makeNodeAdapterTarget(config),
126 build: (context) =>
127 runBuildChild({
128 module: import.meta.url,
129 rootDir: context.root,
130 env: context.env,
131 framework: "vocs",
132 config: {
133 rootDir: context.root,
134 config,
135 } satisfies VocsNodeBuildChildConfig,
136 }).pipe(Effect.mapError((error) => fail(error.message, error.cause))),
137 });
138
139 export const target = makeNodeTarget;
140
141 export default makeNodeTarget;
142
143 export interface VocsNodeFrameworkOptions {
144 readonly root?: string | undefined;
145 readonly target?: string | undefined;
146 readonly outDir?: string | undefined;
147 }
148
149 /**
150 * Framework-module contract used by container Website composites
151 * (`module.make(...)` returns `{ build, dev }`, not a Layer).
152 */
153 export const make = (options: VocsNodeFrameworkOptions = {}) =>
154 Effect.gen(function* () {
155 const path = yield* Path.Path;
156 const resolveRoot = (override: string | undefined) =>
157 path.resolve(override ?? options.root ?? process.cwd());
158
159 const withFramework = <A, E, R>(
160 root: string,
161 use: (framework: FrameworkService["Service"]) => Effect.Effect<A, E, R>,
162 ) =>
163 Effect.gen(function* () {
164 const framework = yield* Framework.pipe(
165 Effect.provide(
166 makeVocsLayer({
167 root,
168 // Parent path: child-process target so Vocs Config.resolve()
169 // and group-icons glob src/pages with cwd = project root.
170 target: makeNodeTarget({}),
171 }),
172 ),
173 );
174 return yield* use(framework);
175 });
176
177 return {
178 build: (buildOptions?: { readonly root?: string }) => {
179 const root = resolveRoot(buildOptions?.root);
180 return withFramework(root, (framework) => framework.build({ root }));
181 },
182 dev: (devOptions?: {
183 readonly root?: string;
184 readonly port?: number;
185 readonly host?: string;
186 }) => {
187 const root = resolveRoot(devOptions?.root);
188 if (!isInsideDevChild()) {
189 return runDevChild({
190 // Vocs's Vite dev server (like its build) exhausts memory under
191 // Bun; run the dev child under Node from PATH.
192 runtime: "node",
193 framework: "vocs",
194 module: "@alchemy.run/frontend-frameworks/vocs/node",
195 callerUrl: import.meta.url,
196 rootDir: root,
197 makeOptions: { ...options, root },
198 devOptions: { ...devOptions, root },
199 });
200 }
201 return withFramework(root, (framework) =>
202 framework.dev({
203 root,
204 port: devOptions?.port,
205 host: devOptions?.host,
206 }),
207 );
208 },
209 };
210 });