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

main
ts 170 lines 6.73 KB
Raw
1 /**
2 * `@alchemy.run/frontend-frameworks/react-router/node` — the Node container
3 * deploy target for the React Router v7 integration.
4 *
5 * React Router builds through Vite: `reactRouter()` in the project's
6 * `vite.config.ts` builds a `client` environment into
7 * `<buildDirectory>/client` and a server environment into
8 * `<buildDirectory>/server`. Its server output is a `ServerBuild` MANIFEST
9 * with no default export, so the framework half makes the server build's
10 * rollup input a wrapper that turns the manifest into a fetch handler with
11 * `createRequestHandler` from `react-router` (see `serverEntrySource` in
12 * `ReactRouter.ts`). What this target owns is the Node packaging on top of
13 * that fetch handler:
14 *
15 * - **`serverEntryFileName`** — `index.js`, the chunk the server pass emits
16 * (React Router's `serverBuildFile`); the finishing pass wraps it.
17 * - **`finish`** — emits the Node deployment surface next to the entry: a
18 * `package.json` (`type: "module"` so Node classifies the `.js` server
19 * build as ESM) and a Node HTTP program (`serve-node.mjs`) that serves
20 * `clientDirectory` first, then falls through to that fetch handler on
21 * `PORT` (default 3000), and answers `GET /health`.
22 * - **`bundle`** — Node resolve conditions (no `workerd`, no `@aws-sdk/`).
23 *
24 * No Lambda adapter: the serve entry talks to the fetch handler directly.
25 */
26 import * as Effect from "effect/Effect";
27 import * as FileSystem from "effect/FileSystem";
28 import * as Path from "effect/Path";
29 import { runBuildChild } from "../core/BuildChild.ts";
30 import { DeployTargetError, makeDeployTarget } from "../core/index.ts";
31 import {
32 NODE_BUNDLE_CONDITIONS,
33 NODE_SERVE_ENTRY_FILE_NAME,
34 relativeClientDirExpression,
35 writeNodeServeEntry,
36 } from "../core/NodeServe.ts";
37 import {
38 DEFAULT_SERVER_BUILD_FILE,
39 make,
40 type ReactRouterTarget,
41 type ReactRouterTargetConfig,
42 } from "./ReactRouter.ts";
43
44 /** The server entry file name React Router's server pass emits. */
45 export const SERVER_ENTRY_FILE_NAME = DEFAULT_SERVER_BUILD_FILE;
46
47 /** Node-specific knobs carried on the shared {@link ReactRouterTargetConfig}. */
48 export interface ReactRouterNodeTargetConfig extends ReactRouterTargetConfig {}
49
50 /** The Node {@link ReactRouterTarget}, carrying the Node-specific config. */
51 export interface ReactRouterNodeTarget extends ReactRouterTarget {
52 readonly config: ReactRouterNodeTargetConfig;
53 }
54
55 const fail = (message: string, cause?: unknown) =>
56 new DeployTargetError({ platform: "node", message, cause });
57
58 /**
59 * Import the server build's fetch handler. The entry module default-exports
60 * `{ fetch }` (the shape the integration's virtual server entry produces). A
61 * project whose own entry default-exports the bare fetch function is
62 * accepted too.
63 */
64 const fetchHandlerImports = (serverEntryFileName: string): string =>
65 `import * as serverEntry from ${JSON.stringify(`./${serverEntryFileName}`)};
66
67 const entry = serverEntry.default ?? serverEntry;
68 const fetchHandler =
69 typeof entry === "function"
70 ? entry
71 : (request) => entry.fetch(request);`;
72
73 const makeNodeFinishTarget = (config: ReactRouterNodeTargetConfig = {}): ReactRouterNodeTarget =>
74 makeDeployTarget({
75 platform: "node",
76 config,
77 bundle: {
78 conditions: [...NODE_BUNDLE_CONDITIONS],
79 },
80 serverEntryFileName: SERVER_ENTRY_FILE_NAME,
81 finish: (output, context) =>
82 Effect.gen(function* () {
83 const fs = yield* FileSystem.FileSystem;
84 const path = yield* Path.Path;
85 if (context.entry === undefined) {
86 return yield* fail("The React Router build produced no on-disk server entry to finish");
87 }
88 if (output.clientDirectory === undefined) {
89 return yield* fail(
90 "The React Router build produced no client directory for the Node serve entry",
91 );
92 }
93 const serverDir = path.dirname(context.entry);
94 const serverEntryFileName = path.basename(context.entry);
95 yield* fs
96 .writeFileString(path.join(serverDir, "package.json"), '{"type":"module"}\n')
97 .pipe(Effect.mapError((error) => fail("Failed to write the server package.json", error)));
98 const servePath = path.join(serverDir, NODE_SERVE_ENTRY_FILE_NAME);
99 return yield* writeNodeServeEntry({
100 output,
101 servePath,
102 serveModuleName: path.join("server", NODE_SERVE_ENTRY_FILE_NAME).replaceAll("\\", "/"),
103 clientDirExpression: relativeClientDirExpression(servePath, output.clientDirectory),
104 handler: {
105 kind: "fetch",
106 imports: fetchHandlerImports(serverEntryFileName),
107 expr: "fetchHandler",
108 },
109 platform: "node",
110 });
111 }),
112 });
113
114 /**
115 * A React Router build loads and executes the project's `vite.config.*` and
116 * `react-router.config.ts` (user plugins may mutate `process.env` or
117 * `process.chdir`, and React Router's config loader spins its own vite-node
118 * server) — none of which may touch the engine process, where many deploys
119 * share one event loop. This target's wholesale `build` therefore runs the
120 * framework in a disposable child process whose working directory IS the
121 * project root (see `core/BuildChild.ts`). The shared
122 * `core/BuildChildRunner` entry imports this module in the child and calls
123 * the exported {@link buildInChild}.
124 */
125 export interface ReactRouterNodeBuildChildConfig {
126 readonly rootDir: string;
127 /** The (JSON-serializable) target config the parent was created with. */
128 readonly config: ReactRouterNodeTargetConfig;
129 }
130
131 export const buildInChild = (config: ReactRouterNodeBuildChildConfig) =>
132 Effect.gen(function* () {
133 const framework = yield* make({
134 root: config.rootDir,
135 // The finish-only target: no wholesale `build` hook, so the child
136 // runs the regular vite build + finish pipeline (no recursion).
137 target: makeNodeFinishTarget(config.config),
138 buildDirectory: config.config.buildDirectory,
139 });
140 return yield* framework.build({ root: config.rootDir });
141 });
142
143 /**
144 * Create the Node {@link ReactRouterTarget}. See the module doc for the
145 * seams.
146 */
147 export const makeNodeTarget = (
148 config: ReactRouterNodeTargetConfig = {},
149 ): ReactRouterNodeTarget => ({
150 ...makeNodeFinishTarget(config),
151 build: (context) =>
152 runBuildChild({
153 module: import.meta.url,
154 rootDir: context.root,
155 env: context.env,
156 framework: "react-router",
157 config: {
158 rootDir: context.root,
159 config,
160 } satisfies ReactRouterNodeBuildChildConfig,
161 }).pipe(Effect.mapError((error) => fail(error.message, error.cause))),
162 });
163
164 /**
165 * The deploy-target module contract (`resolveDeployTarget` accepts the
166 * default export — or the named `target` export — as a value or factory).
167 */
168 export const target = makeNodeTarget;
169
170 export default makeNodeTarget;