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

main
ts 398 lines 15.6 KB
Raw
1 import * as Effect from "effect/Effect";
2 import * as FileSystem from "effect/FileSystem";
3 import * as Layer from "effect/Layer";
4 import * as Path from "effect/Path";
5 import * as Schedule from "effect/Schedule";
6 import * as FrameworkCore from "../core/index.ts";
7 import {
8 Framework,
9 FrameworkError,
10 type DeployTarget,
11 type DeployTargetInput,
12 } from "../core/index.ts";
13
14 /**
15 * The structural slice of the project's `vite` module this package drives.
16 * Typed structurally so the package carries no dependency on vite — the
17 * *project's* install is always the one loaded.
18 *
19 * `createBuilder` (not `build`) is the entry point: TanStack Start's plugin
20 * declares a `builder.buildApp` that builds the `client` and `ssr`
21 * environments (plus the server-function provider environment when RSC is
22 * enabled). Vite's legacy `build()` only builds the default environment, so
23 * it would silently produce the client bundle and nothing else.
24 */
25 export interface TanStackStartViteModule {
26 readonly version?: string;
27 readonly createBuilder: (config: Record<string, unknown>) => Promise<TanStackStartViteBuilder>;
28 readonly createServer: (config: Record<string, unknown>) => Promise<TanStackStartViteDevServer>;
29 }
30
31 /** The structural slice of a vite builder this package reads. */
32 export interface TanStackStartViteBuilder {
33 readonly buildApp: () => Promise<unknown>;
34 }
35
36 /** The structural slice of a Vite dev server this package reads. */
37 export interface TanStackStartViteDevServer {
38 readonly listen: () => Promise<unknown>;
39 readonly close: () => Promise<void>;
40 readonly resolvedUrls?: { readonly local: ReadonlyArray<string> } | null | undefined;
41 }
42
43 /**
44 * The configuration this package assembles from
45 * {@link TanStackStartOptions} and hands to a deploy-target factory. The
46 * target treats it as its `DeployTarget.config`; the framework half never
47 * inspects a resolved target's config.
48 */
49 export interface TanStackStartTargetConfig {
50 /**
51 * Build output directory relative to the project root — the parent of
52 * `client/` and `server/`. Mirrors the project config's `build.outDir`.
53 * @default "dist"
54 */
55 readonly outDir?: string | undefined;
56 }
57
58 /**
59 * A deploy target for TanStack Start: the generic `DeployTarget` seams plus
60 * the one framework-specific hook the build needs — the file name of the
61 * server entry the SSR environment emits, which the target's finishing pass
62 * wraps.
63 */
64 export interface TanStackStartTarget extends DeployTarget<TanStackStartTargetConfig> {
65 /**
66 * The server entry file name within the SSR output directory. TanStack
67 * Start's SSR environment builds a single rollup input — the resolved
68 * server entry (`src/server.ts`, else the framework's default one) — so
69 * the emitted chunk is named after it (`server.js`). Omitted targets fall
70 * back to {@link DEFAULT_SERVER_ENTRY_FILE_NAME}, and a build that emits
71 * exactly one top-level module under the server directory uses that
72 * instead when the expected name is absent.
73 */
74 readonly serverEntryFileName?: string | undefined;
75 }
76
77 /**
78 * How a deploy target is passed to this package: a `TanStackStartTarget`
79 * value, a factory `(config) => TanStackStartTarget`, or a module specifier
80 * resolved from the *project's* `node_modules`.
81 */
82 export type TanStackStartTargetInput = DeployTargetInput<
83 TanStackStartTarget,
84 TanStackStartTargetConfig
85 >;
86
87 /**
88 * The default deploy target: this package's own AWS Lambda target module,
89 * loaded from the project's dependency tree. (Cloudflare deploys TanStack
90 * Start through its native Vite integration — `Cloudflare.Website.Vite` —
91 * so no Cloudflare target exists here.)
92 */
93 export const DEFAULT_TARGET_SPECIFIER = "@alchemy.run/frontend-frameworks/tanstack-start/aws";
94
95 /** The vite plugin package a TanStack Start project must install. */
96 export const TANSTACK_START_PLUGIN_SPECIFIER = "@tanstack/start-plugin-core";
97
98 /** The default root output directory (the parent of `client/` and `server/`). */
99 export const DEFAULT_OUT_DIR = "dist";
100
101 /** The default server entry file name inside the SSR output directory. */
102 export const DEFAULT_SERVER_ENTRY_FILE_NAME = "server.js";
103
104 export interface TanStackStartOptions {
105 /**
106 * Project root (the directory containing `vite.config.*`).
107 * @default process.cwd()
108 */
109 readonly root?: string | undefined;
110 /**
111 * The deploy target the build is produced for. Accepts a target value, a
112 * `(config) => target` factory, or a module specifier string.
113 * @default "@alchemy.run/frontend-frameworks/tanstack-start/aws"
114 */
115 readonly target?: TanStackStartTargetInput | undefined;
116 /**
117 * Build output directory relative to the project root — the parent of
118 * `client/` and `server/`. Must match the project's `build.outDir` when it
119 * sets one.
120 * @default "dist"
121 */
122 readonly outDir?: string | undefined;
123 readonly dev?:
124 | {
125 /** Default dev-server port (overridden by `FrameworkDevOptions.port`). */
126 readonly port?: number | undefined;
127 }
128 | undefined;
129 }
130
131 const fail = (message: string, cause?: unknown) =>
132 new FrameworkError({ framework: "tanstack-start", message, cause });
133
134 /**
135 * The inline config the integration merges over the project's own
136 * `vite.config.*`.
137 *
138 * `resolve.noExternal: true` on the SSR environment is the load-bearing
139 * override: vite externalizes `node_modules` imports from SSR bundles by
140 * default, so a stock TanStack Start server build emits
141 * `import { RouterProvider } from "@tanstack/react-router"` and is only
142 * runnable next to an installed dependency tree. A Lambda ships the server
143 * directory alone, so the SSR bundle must be self-contained — only `node:`
144 * builtins stay external. Declared on both the legacy `ssr` key and the
145 * environment key so it holds across Vite majors.
146 */
147 export const inlineBuildConfig = (
148 root: string,
149 outDir: string | undefined,
150 ): Record<string, unknown> => ({
151 root,
152 // Warn-level: rolldown-vite's native progress reporter writes straight to
153 // the fd, corrupting hosting-process reporters that can only intercept
154 // JS-level writers.
155 logLevel: "warn",
156 ...(outDir !== undefined ? { build: { outDir } } : undefined),
157 ssr: { noExternal: true },
158 environments: { ssr: { resolve: { noExternal: true } } },
159 });
160
161 /**
162 * Build the `Framework` service implementation for a TanStack Start project.
163 *
164 * - `build` resolves the deploy target, then either delegates wholesale
165 * (`target.build`) or drives the PROJECT's own Vite install
166 * programmatically: `createBuilder({ root, ... })` followed by
167 * `buildApp()`. TanStack Start is pure Vite — `tanstackStart()` in the
168 * project's `vite.config.ts` owns routing, the client/`ssr` environments,
169 * and the server entry — so there is no adapter to select and no plugin to
170 * inject; the integration only forces the SSR bundle to be self-contained
171 * (see {@link inlineBuildConfig}). The `BuildOutput` is read from disk:
172 * `serverModules` entry-first from `<outDir>/server`, `clientDirectory` =
173 * `<outDir>/client`.
174 * - `dev` runs the project's own Vite dev server (TanStack Start's
175 * dev-server plugin serves SSR, server routes, and server functions
176 * through it with native HMR), scoped — closing the Scope closes the
177 * server.
178 *
179 * This module is target-agnostic: everything AWS-specific lives in
180 * `@alchemy.run/frontend-frameworks/tanstack-start/aws`.
181 */
182 export const make: (
183 options?: TanStackStartOptions,
184 ) => Effect.Effect<Framework["Service"], never, FileSystem.FileSystem | Path.Path> =
185 Effect.fnUntraced(function* (options?: TanStackStartOptions) {
186 const fs = yield* FileSystem.FileSystem;
187 const path = yield* Path.Path;
188 const baseRoot = options?.root ?? (yield* Effect.sync(() => process.cwd()));
189
190 const targetConfig: TanStackStartTargetConfig = { outDir: options?.outDir };
191
192 const resolveTarget = (root: string) =>
193 FrameworkCore.resolveDeployTarget<TanStackStartTarget, TanStackStartTargetConfig>(
194 root,
195 options?.target ?? DEFAULT_TARGET_SPECIFIER,
196 targetConfig,
197 ).pipe(Effect.mapError((error) => fail(error.message, error.cause)));
198
199 const loadVite = (root: string) =>
200 FrameworkCore.loadProjectModule<TanStackStartViteModule>(root, "vite").pipe(
201 Effect.mapError((error) => fail("Failed to load the project's Vite install", error.cause)),
202 );
203
204 const build: Framework["Service"]["build"] = Effect.fn(function* (buildOptions) {
205 const root = buildOptions?.root ?? baseRoot;
206 const target = yield* resolveTarget(root);
207 const targetContext = {
208 root,
209 framework: "tanstack-start",
210 env: buildOptions?.env,
211 };
212
213 // Wholesale build takeover (the AWS target uses this seam to run the
214 // build in a disposable child process — vite.config.* executes user
215 // plugins that must not touch the engine process, and TanStack
216 // Start's plugin crawls framework packages from `process.cwd()`).
217 if (target.build !== undefined) {
218 return yield* target.build(targetContext).pipe(
219 Effect.mapError((error) => fail(error.message, error.cause)),
220 Effect.provideService(FileSystem.FileSystem, fs),
221 Effect.provideService(Path.Path, path),
222 );
223 }
224
225 const vite = yield* loadVite(root);
226 yield* Effect.tryPromise({
227 try: async () => {
228 const builder = await vite.createBuilder(inlineBuildConfig(root, options?.outDir));
229 return await builder.buildApp();
230 },
231 catch: (error) => fail("Failed to build", error),
232 });
233
234 const dir = path.resolve(root, options?.outDir ?? DEFAULT_OUT_DIR);
235 const output = yield* readTanStackStartOutput({
236 dir,
237 serverDir: path.join(dir, "server"),
238 clientDir: path.join(dir, "client"),
239 serverEntryFileName: target.serverEntryFileName,
240 }).pipe(Effect.provideService(FileSystem.FileSystem, fs));
241
242 const entryName = output.serverModules?.[0]?.name;
243 return yield* FrameworkCore.applyDeployTargetFinish(target, output, {
244 ...targetContext,
245 ...(entryName !== undefined ? { entry: path.join(dir, entryName) } : undefined),
246 }).pipe(
247 Effect.mapError((error) => fail(error.message, error.cause)),
248 Effect.provideService(FileSystem.FileSystem, fs),
249 Effect.provideService(Path.Path, path),
250 );
251 });
252
253 const dev: Framework["Service"]["dev"] = Effect.fn(function* (devOptions) {
254 const root = devOptions?.root ?? baseRoot;
255 const vite = yield* loadVite(root);
256 // `port: 0` (true OS-assigned) on Vite >= 8.2.1, probed ephemeral port
257 // on older Vite — see `resolveViteDevPort`.
258 const port = yield* FrameworkCore.resolveViteDevPort(
259 vite.version,
260 devOptions?.port ?? options?.dev?.port,
261 );
262 const host = devOptions?.host;
263
264 const server = yield* Effect.acquireRelease(
265 Effect.tryPromise({
266 try: async () => {
267 const server = await vite.createServer({
268 root,
269 logLevel: "warn",
270 server: {
271 port,
272 ...(host !== undefined ? { host } : undefined),
273 },
274 });
275 await server.listen();
276 return server;
277 },
278 catch: (error) => fail("Failed to start the TanStack Start dev server", error),
279 }),
280 (server) =>
281 Effect.promise(async () => {
282 try {
283 await server.close();
284 } catch {
285 // teardown is best-effort
286 }
287 }),
288 );
289
290 const resolved = server.resolvedUrls?.local[0];
291 if (resolved === undefined) {
292 return yield* fail("Could not determine the dev server URL");
293 }
294 // Vite reports its local URL with a trailing slash; hand back an origin
295 // that concatenates correctly (`${url}/about`, not `//about`).
296 const url = resolved.endsWith("/") ? resolved.slice(0, -1) : resolved;
297
298 // Bounded readiness probe: any HTTP response counts (vite serves
299 // lazily; we only need the listener to answer).
300 yield* Effect.tryPromise({
301 try: async () => {
302 const response = await fetch(url, { redirect: "manual" });
303 await response.arrayBuffer().catch(() => {});
304 },
305 catch: (error) => fail("The dev server did not become reachable", error),
306 }).pipe(Effect.retry({ schedule: Schedule.spaced("250 millis"), times: 40 }));
307
308 return { url };
309 });
310
311 return Framework.of({ build, dev });
312 });
313
314 /** The resolved TanStack Start build output directories. */
315 export interface TanStackStartOutputDirs {
316 /** Root output directory (`<root>/dist`). */
317 readonly dir: string;
318 /** SSR bundle directory (`<root>/dist/server`). */
319 readonly serverDir: string;
320 /** Client assets directory (`<root>/dist/client`), `public/` copied in. */
321 readonly clientDir: string;
322 /**
323 * The emitted server entry file name within `serverDir`.
324 * @default "server.js"
325 */
326 readonly serverEntryFileName?: string | undefined;
327 }
328
329 /**
330 * Pick the server entry among the modules read off disk.
331 *
332 * The expected name wins. Otherwise, a build whose server directory holds
333 * exactly one top-level module (chunks live under `assets/`) is
334 * unambiguous — that module is the entry, which covers a project that names
335 * its server entry something other than `server.ts`.
336 */
337 export const selectServerEntryName = (
338 moduleNames: ReadonlyArray<string>,
339 expected: string,
340 ): string | undefined => {
341 if (moduleNames.includes(expected)) return expected;
342 const topLevel = moduleNames.filter(
343 (name) =>
344 !name.slice("server/".length).includes("/") &&
345 (name.endsWith(".js") || name.endsWith(".mjs")),
346 );
347 return topLevel.length === 1 ? topLevel[0] : undefined;
348 };
349
350 /**
351 * Map TanStack Start's on-disk `dist` onto the `BuildOutput` contract:
352 * `serverModules` entry-first from `<outDir>/server` (POSIX names,
353 * sha256-hashed), `clientDirectory` = `<outDir>/client`. The SSR bundle is
354 * built with `resolve.noExternal: true`, so it is self-contained (only
355 * `node:` builtins external) and there are no external workspace roots to
356 * watch.
357 */
358 export const readTanStackStartOutput = (
359 dirs: TanStackStartOutputDirs,
360 ): Effect.Effect<FrameworkCore.BuildOutput, FrameworkError, FileSystem.FileSystem> =>
361 Effect.gen(function* () {
362 const expected = `server/${dirs.serverEntryFileName ?? DEFAULT_SERVER_ENTRY_FILE_NAME}`;
363 const modules = yield* FrameworkCore.readServerModulesFromDisk({
364 directory: dirs.serverDir,
365 prefix: "server",
366 }).pipe(Effect.mapError((error) => fail(error.message, error.cause)));
367 if (modules.length === 0) {
368 return yield* fail(
369 `The TanStack Start build produced no server modules in ${dirs.serverDir}`,
370 );
371 }
372 const entryName = selectServerEntryName(
373 modules.map((module) => module.name),
374 expected,
375 );
376 if (entryName === undefined) {
377 return yield* fail(
378 `The TanStack Start build produced no "${expected}" entry in ${dirs.serverDir} — ` +
379 "is the SSR environment's rollup input the project's server entry?",
380 );
381 }
382 return {
383 distDirectory: dirs.dir,
384 clientDirectory: dirs.clientDir,
385 serverModules: FrameworkCore.sortServerModules(modules, entryName),
386 externalWorkspaces: new Set<string>(),
387 } satisfies FrameworkCore.BuildOutput;
388 });
389
390 /**
391 * A `Layer` providing framework-core's `Framework` service for a TanStack
392 * Start project — the fully-typed entrypoint for `e2e.config.ts` and
393 * alchemy's `AWS.Website.TanStackStart` composite.
394 */
395 export const layer = (
396 options?: TanStackStartOptions,
397 ): Layer.Layer<Framework, never, FileSystem.FileSystem | Path.Path> =>
398 Layer.effect(Framework, make(options));