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

main
ts 434 lines 16.6 KB
Raw
1 import type * as NodeChildProcessModule from "node:child_process";
2 import { randomBytes } from "node:crypto";
3 import { createRequire } from "node:module";
4 import type * as NodeNet from "node:net";
5 import * as Effect from "effect/Effect";
6 import * as FileSystem from "effect/FileSystem";
7 import * as Path from "effect/Path";
8 import type * as Scope from "effect/Scope";
9 import type { Plugin, PluginOption } from "vite";
10 import { makeChildOutput } from "../core/ChildOutput.ts";
11 import { findEphemeralPort } from "../core/DevPort.ts";
12 /**
13 * Shared programmatic Vinext builds and native development CLI helpers.
14 * Production builds run in the target's isolated Node child so Alchemy can
15 * inject deployment adapters without modifying application configuration.
16 */
17 import * as FrameworkCore from "../core/index.ts";
18 import { toOutputFile, type BuildOutput } from "../core/index.ts";
19 import { loadProjectModule, resolveProjectPackageDirectory } from "../core/Loader.ts";
20 import { loadVinextBuildConfig, type VinextRouteRootConfig } from "./BuildConfig.ts";
21 import { makeVinextCachePlugin, type VinextCacheKind } from "./cache/plugin.ts";
22 import { loadVinextModule } from "./Modules.ts";
23 import { runVinextPrerenderIfConfigured } from "./Prerender.ts";
24
25 export const failFramework = (message: string) => (cause: unknown) =>
26 new FrameworkCore.FrameworkError({ framework: "vinext", message, cause });
27
28 /** App Router RSC entry vinext writes under `dist/server`. */
29 export const VINEXT_RSC_ENTRY = "server/index.js";
30
31 /** Pages Router server entry vinext writes under `dist/server`. */
32 export const VINEXT_PAGES_ENTRY = "server/entry.js";
33
34 export const resolveVinextCli = (root: string) =>
35 resolveProjectPackageDirectory(root, "vinext").pipe(
36 Effect.map((directory) => `${directory}/dist/cli.js`),
37 Effect.mapError(
38 failFramework(
39 `Failed to resolve "vinext" from ${root}. It must be installed in your project.`,
40 ),
41 ),
42 );
43
44 export const runVinextBuild = (options: {
45 readonly root: string;
46 readonly cache: VinextCacheKind;
47 }) =>
48 Effect.gen(function* () {
49 const { root } = options;
50 const fs = yield* FileSystem.FileSystem;
51 const path = yield* Path.Path;
52 yield* Effect.sync(() => {
53 process.env.NODE_ENV = "production";
54 });
55 const vite = yield* loadProjectModule<typeof import("vite")>(root, "vite");
56 const { default: vinext } = yield* loadVinextModule<{
57 default: (
58 options?: VinextRouteRootConfig & {
59 nextConfig?: unknown;
60 cache?: unknown;
61 disableAppRouter?: boolean;
62 precompress?: boolean;
63 __skipBuildLifecycle?: boolean;
64 __pagesClientAssetsModule?: string | null;
65 },
66 ) => PluginOption;
67 }>(root, "index.js");
68 const cache = yield* makeVinextCachePlugin(root, options.cache);
69 const { loadDotenv } = yield* loadVinextModule<{
70 loadDotenv: (options: { root: string; mode: string }) => void;
71 }>(root, "config/dotenv.js");
72 yield* Effect.sync(() => loadDotenv({ root, mode: "production" }));
73 const loaded = yield* Effect.tryPromise(() =>
74 vite.loadConfigFromFile({ command: "build", mode: "production" }, undefined, root),
75 );
76 const plugins = loaded?.config.plugins ?? [vinext()];
77 const config = yield* loadVinextBuildConfig(root, plugins);
78 const { runWithPreviewBuildCredentials } = yield* loadVinextModule<{
79 runWithPreviewBuildCredentials: <T>(callback: () => T) => T;
80 }>(root, "build/preview-credentials.js");
81 const { PAGES_CLIENT_ASSETS_MODULE } = yield* loadVinextModule<{
82 PAGES_CLIENT_ASSETS_MODULE: string;
83 }>(root, "build/pages-client-assets-module.js");
84 const hasDirectory = (name: string) =>
85 Effect.gen(function* () {
86 return (
87 (yield* fs.exists(path.join(root, name))) ||
88 (yield* fs.exists(path.join(root, "src", name)))
89 );
90 });
91 const hybrid = (yield* hasDirectory("app")) && (yield* hasDirectory("pages"));
92 if (loaded?.config.build?.emptyOutDir !== false) {
93 yield* fs.remove(path.join(root, "dist"), {
94 recursive: true,
95 force: true,
96 });
97 }
98 yield* Effect.acquireUseRelease(
99 Effect.sync(() => {
100 const shared = {
101 __VINEXT_SHARED_BUILD_ID: config.nextConfig.buildId,
102 __VINEXT_SHARED_RSC_COMPATIBILITY_ID: config.rscCompatibilityId,
103 __VINEXT_SHARED_RSC_BUILD_IDENTITY: randomBytes(16).toString("hex"),
104 __VINEXT_SHARED_REVALIDATE_SECRET: randomBytes(32).toString("hex"),
105 __VINEXT_SHARED_PRERENDER_SECRET: randomBytes(32).toString("hex"),
106 };
107 const previous = Object.fromEntries(
108 Object.keys(shared).map((key) => [key, process.env[key]]),
109 );
110 Object.assign(process.env, shared);
111 return previous;
112 }),
113 () =>
114 Effect.gen(function* () {
115 yield* Effect.tryPromise(() =>
116 runWithPreviewBuildCredentials(async () => {
117 const buildConfig = await vite.loadConfigFromFile(
118 { command: "build", mode: "production" },
119 undefined,
120 root,
121 );
122 const builder = await vite.createBuilder({
123 ...buildConfig?.config,
124 root,
125 configFile: false,
126 plugins: [buildConfig?.config.plugins ?? [vinext()], cache],
127 logLevel: "warn",
128 });
129 await builder.buildApp();
130 if (!hybrid) return;
131 // The native App Router builder leaves the hybrid Pages server to its caller.
132 const flattened: Plugin[] = [];
133 const flatten = async (value: PluginOption): Promise<void> => {
134 const plugin = await value;
135 if (Array.isArray(plugin)) {
136 for (const child of plugin) await flatten(child);
137 } else if (plugin) flattened.push(plugin);
138 };
139 const pagesConfig = await vite.loadConfigFromFile(
140 { command: "build", mode: "production", isSsrBuild: true },
141 undefined,
142 root,
143 );
144 await flatten(pagesConfig?.config.plugins ?? []);
145 // The App Router build writes the Pages client-asset manifest next to its RSC entry.
146 const pagesClientAssetsPath = path.join(
147 root,
148 "dist/server",
149 PAGES_CLIENT_ASSETS_MODULE,
150 );
151 const pagesClientAssetsModule = await fs.readFileString(pagesClientAssetsPath).pipe(
152 Effect.orElseSucceed(() => null),
153 Effect.runPromise,
154 );
155 // Mirrors vinext's own hybrid Pages build (build/lifecycle.js): keep the
156 // user's config and transforms, drop App Router internals.
157 const transforms = flattened
158 .filter(
159 (plugin) =>
160 !plugin.name.startsWith("vinext:") &&
161 !plugin.name.startsWith("vite:react") &&
162 plugin.name !== "rsc" &&
163 !plugin.name.startsWith("rsc:") &&
164 plugin.name !== "vite-rsc-load-module-dev-proxy" &&
165 !plugin.name.startsWith("vite-plugin-cloudflare"),
166 )
167 .map((plugin) => ({ ...plugin, buildApp: undefined }));
168 const {
169 plugins: _plugins,
170 environments,
171 build: userBuild,
172 resolve: userResolve,
173 ...userConfig
174 } = pagesConfig?.config ?? {};
175 const { build: ssrBuild, ...pagesEnvironment } = environments?.ssr ?? {};
176 const mergedBuild = vite.mergeConfig(userBuild ?? {}, ssrBuild ?? {});
177 const userOutput = mergedBuild.rolldownOptions?.output;
178 await vite.build({
179 ...userConfig,
180 root,
181 mode: "production",
182 configFile: false,
183 plugins: [
184 transforms,
185 // vinext() does not expose its options; its config plugin carries these.
186 vinext({
187 ...config.routeRootConfig,
188 nextConfig: config.nextConfigInput,
189 cache: config.cacheConfig ?? undefined,
190 disableAppRouter: true,
191 precompress: false,
192 __skipBuildLifecycle: true,
193 __pagesClientAssetsModule: pagesClientAssetsModule,
194 }),
195 cache,
196 ],
197 environments: { ssr: { ...pagesEnvironment, consumer: "server" } },
198 resolve: {
199 ...userResolve,
200 dedupe: [
201 ...(userResolve?.dedupe ?? []),
202 "react",
203 "react-dom",
204 "react/jsx-runtime",
205 "react/jsx-dev-runtime",
206 ],
207 },
208 build: {
209 ...mergedBuild,
210 outDir: "dist/server",
211 emptyOutDir: false,
212 manifest: false,
213 ssr: "virtual:vinext-server-entry",
214 rolldownOptions: {
215 ...mergedBuild.rolldownOptions,
216 output: Array.isArray(userOutput)
217 ? userOutput.map((output) => ({ ...output, entryFileNames: "entry.js" }))
218 : { ...userOutput, entryFileNames: "entry.js" },
219 },
220 },
221 });
222 }),
223 );
224 yield* runVinextPrerenderIfConfigured(root, options.cache, config);
225 }),
226 (previous) =>
227 Effect.sync(() => {
228 for (const [key, value] of Object.entries(previous)) {
229 if (value === undefined) delete process.env[key];
230 else process.env[key] = value;
231 }
232 }),
233 );
234 }).pipe(Effect.mapError(failFramework("Failed to build vinext")));
235
236 export const collectVinextDist = (root: string) =>
237 Effect.gen(function* () {
238 const fs = yield* FileSystem.FileSystem;
239 const path = yield* Path.Path;
240 const distDir = path.join(root, "dist");
241 const serverDir = path.join(distDir, "server");
242 const clientDir = path.join(distDir, "client");
243 const rscEntry = path.join(distDir, VINEXT_RSC_ENTRY);
244 const pagesEntry = path.join(distDir, VINEXT_PAGES_ENTRY);
245 const hasDist = yield* fs.exists(distDir).pipe(Effect.orElseSucceed(() => false));
246 if (!hasDist) {
247 return yield* failFramework(`The vinext build produced no ${distDir}`)(undefined);
248 }
249 const hasRsc = yield* fs.exists(rscEntry).pipe(Effect.orElseSucceed(() => false));
250 const hasPages = yield* fs.exists(pagesEntry).pipe(Effect.orElseSucceed(() => false));
251 if (!hasRsc && !hasPages) {
252 return yield* failFramework(
253 `The vinext build produced no server entry at ${rscEntry} or ${pagesEntry}`,
254 )(undefined);
255 }
256 const hasClient = yield* fs.exists(clientDir).pipe(Effect.orElseSucceed(() => false));
257 yield* fs
258 .writeFileString(
259 path.join(serverDir, "package.json"),
260 `${JSON.stringify({ type: "module" }, null, 2)}\n`,
261 )
262 .pipe(Effect.mapError(failFramework("Failed to write dist/server/package.json")));
263 return {
264 distDirectory: distDir,
265 clientDirectory: hasClient ? clientDir : undefined,
266 serverDir,
267 hasRsc,
268 hasPages,
269 };
270 });
271
272 export const pinServeModule = (
273 output: Omit<BuildOutput, "serverModules" | "externalWorkspaces"> & {
274 readonly serverDir: string;
275 },
276 serveModuleName: string,
277 serveSource: string,
278 ) =>
279 Effect.gen(function* () {
280 const fs = yield* FileSystem.FileSystem;
281 const path = yield* Path.Path;
282 const servePath = path.join(output.serverDir, path.basename(serveModuleName));
283 yield* fs
284 .writeFileString(servePath, serveSource)
285 .pipe(Effect.mapError(failFramework(`Failed to write the serve entry at ${servePath}`)));
286 const serveModule = yield* toOutputFile(serveModuleName, serveSource);
287 return {
288 distDirectory: output.distDirectory,
289 clientDirectory: output.clientDirectory,
290 serverModules: [serveModule],
291 externalWorkspaces: new Set<string>(),
292 } satisfies BuildOutput;
293 });
294
295 export interface VinextDevChild {
296 readonly exited: () => boolean;
297 readonly output: () => string;
298 }
299
300 export const spawnVinextDev = (options: {
301 readonly root: string;
302 readonly cli: string;
303 readonly port: number;
304 readonly host?: string | undefined;
305 }): Effect.Effect<VinextDevChild, FrameworkCore.FrameworkError, Scope.Scope> =>
306 Effect.acquireRelease(
307 Effect.flatMap(makeChildOutput, (childOutput) =>
308 Effect.try({
309 try: () => {
310 const cp = createRequire(import.meta.url)(
311 "child_process",
312 ) as typeof NodeChildProcessModule;
313 const child = cp.spawn(
314 "node",
315 [
316 options.cli,
317 "dev",
318 "--port",
319 String(options.port),
320 "--strictPort",
321 ...(options.host !== undefined ? ["--host", options.host] : []),
322 ],
323 {
324 cwd: options.root,
325 stdio: ["ignore", "pipe", "pipe"],
326 detached: false,
327 },
328 );
329 let exited = false;
330 let output = "";
331 const capture = (chunk: unknown) => {
332 output += String(chunk);
333 if (output.length > 65536) output = output.slice(-32768);
334 };
335 child.stdout?.on("data", (chunk: unknown) => {
336 capture(chunk);
337 childOutput.stdout.push(String(chunk));
338 });
339 child.stderr?.on("data", (chunk: unknown) => {
340 capture(chunk);
341 childOutput.stderr.push(String(chunk));
342 });
343 // Output without a trailing newline is still a line once the
344 // streams close.
345 child.once("close", () => {
346 childOutput.stdout.flush();
347 childOutput.stderr.flush();
348 });
349 child.once("exit", () => {
350 exited = true;
351 });
352 return {
353 child,
354 handle: {
355 exited: () => exited,
356 output: () => output,
357 } satisfies VinextDevChild,
358 };
359 },
360 catch: failFramework("Failed to spawn the vinext dev CLI (is `node` on PATH?)"),
361 }),
362 ),
363 ({ child }) =>
364 Effect.callback<void>((resume) => {
365 if (child.exitCode !== null) {
366 resume(Effect.void);
367 return;
368 }
369 const killTimer = setTimeout(() => child.kill("SIGKILL"), 3000);
370 child.once("exit", () => {
371 clearTimeout(killTimer);
372 resume(Effect.void);
373 });
374 child.kill("SIGTERM");
375 }),
376 ).pipe(Effect.map(({ handle }) => handle));
377
378 /**
379 * Poll until the allocated port accepts a TCP connection. vinext/Vite can
380 * bind before the first App Router compile finishes, so an HTTP GET with
381 * a short abort restarts that compile and never converges.
382 */
383 export const awaitVinextDevReady = (options: {
384 readonly url: string;
385 readonly child: VinextDevChild;
386 }): Effect.Effect<void, FrameworkCore.FrameworkError> =>
387 Effect.gen(function* () {
388 const parsed = yield* Effect.try({
389 try: () => new URL(options.url),
390 catch: failFramework(`Invalid vinext dev URL: ${options.url}`),
391 });
392 const port = Number(parsed.port);
393 const hostname = parsed.hostname;
394 for (let attempt = 0; attempt < 240; attempt++) {
395 if (options.child.exited()) {
396 return yield* failFramework(
397 `The vinext dev CLI exited before becoming ready:\n${options.child.output().slice(-4000)}`,
398 )(undefined);
399 }
400 const ready = yield* Effect.callback<boolean>((resume) => {
401 const net = createRequire(import.meta.url)("net") as typeof NodeNet;
402 let settled = false;
403 const finish = (value: boolean) => {
404 if (settled) return;
405 settled = true;
406 resume(Effect.succeed(value));
407 };
408 const socket = net.connect({ host: hostname, port }, () => {
409 socket.destroy();
410 finish(true);
411 });
412 socket.setTimeout(2000, () => {
413 socket.destroy();
414 finish(false);
415 });
416 socket.once("error", () => {
417 socket.destroy();
418 finish(false);
419 });
420 return Effect.sync(() => {
421 settled = true;
422 socket.destroy();
423 });
424 });
425 if (ready) return;
426 yield* Effect.sleep(500);
427 }
428 return yield* failFramework(`Timed out waiting for the vinext dev server at ${options.url}`)(
429 undefined,
430 );
431 });
432
433 export const pickEphemeralPort: Effect.Effect<number, FrameworkCore.FrameworkError> =
434 findEphemeralPort();