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

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