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

main
ts 350 lines 13.5 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 /** The structural slice of the project's `vite` module this package drives. */
15 export interface ViteModule {
16 readonly version?: string;
17 readonly build: (config: Record<string, unknown>) => Promise<unknown>;
18 readonly createServer: (config: Record<string, unknown>) => Promise<ViteDevServer>;
19 /**
20 * `vite.resolveConfig` — used to read the project's resolved `build.outDir`
21 * (and root) without duplicating vite's config-file discovery. Optional in
22 * the slice: ancient vite versions without it fall back to `dist`.
23 */
24 readonly resolveConfig?: (
25 config: Record<string, unknown>,
26 command: "build" | "serve",
27 ) => Promise<ResolvedViteConfigSlice>;
28 }
29
30 /** The structural slice of a resolved vite config this package reads. */
31 export interface ResolvedViteConfigSlice {
32 readonly root: string;
33 readonly build: { readonly outDir: string };
34 }
35
36 /** The structural slice of a Vite dev server this package reads. */
37 export interface ViteDevServer {
38 readonly listen: () => Promise<unknown>;
39 readonly close: () => Promise<void>;
40 /**
41 * Native Node HTTP server. `null` in middleware mode; optional so older
42 * vite slices without the field still typecheck.
43 */
44 readonly httpServer?: { readonly closeAllConnections?: () => void } | null | undefined;
45 readonly resolvedUrls?: { readonly local: ReadonlyArray<string> } | null | undefined;
46 }
47
48 /**
49 * Serializable build knobs merged OVER the project's own `vite.config.*`
50 * (which loads natively, plugins included).
51 */
52 export interface ViteBuildConfig {
53 /**
54 * Build output directory, relative to the project root. Overrides the
55 * project config's `build.outDir`.
56 * @default the project config's `build.outDir` (vite's default: "dist")
57 */
58 readonly outDir?: string | undefined;
59 /** Public base path the site deploys under (vite's `base`). */
60 readonly base?: string | undefined;
61 /**
62 * Alternate config file to load instead of the auto-discovered
63 * `vite.config.*`, resolved relative to the project root.
64 */
65 readonly configFile?: string | undefined;
66 }
67
68 /**
69 * The configuration this package assembles from {@link ViteOptions} and
70 * hands to a deploy-target factory (the target's `config`). Framework-core
71 * never inspects it.
72 */
73 export interface ViteTargetConfig {
74 readonly vite?: ViteBuildConfig | undefined;
75 /**
76 * Assets-only Node serve entry (`vite/node` finish). `"spa"` serves
77 * `index.html` for unmatched GET paths.
78 * @default "spa" on the Node target
79 */
80 readonly notFoundHandling?: "none" | "spa" | "404-page" | undefined;
81 /**
82 * Serve `about/index.html` at `/about`.
83 * @default "none"
84 */
85 readonly htmlHandling?: "none" | "drop-trailing-slash" | undefined;
86 }
87
88 /**
89 * A deploy target for plain Vite: just the generic `DeployTarget` seams.
90 * A client-only Vite build has no server output, so targets have nothing
91 * framework-specific to hook — the AWS target only uses the wholesale
92 * `build` seam to move the build into a child process.
93 */
94 export interface ViteTarget extends DeployTarget<ViteTargetConfig> {}
95
96 /** How a deploy target is passed to this package (value, factory, or specifier). */
97 export type ViteTargetInput = DeployTargetInput<ViteTarget, ViteTargetConfig>;
98
99 /**
100 * The default deploy target: this package's AWS static-site target module,
101 * loaded from the project's dependency tree. (Cloudflare deploys plain Vite
102 * projects through its native Vite plugin — `Cloudflare.Website.Vite` —
103 * so no Cloudflare target exists here.)
104 */
105 export const DEFAULT_TARGET_SPECIFIER = "@alchemy.run/frontend-frameworks/vite/aws";
106
107 export interface ViteOptions {
108 /**
109 * Project root (the directory containing `vite.config.*` / `index.html`).
110 * @default process.cwd()
111 */
112 readonly root?: string | undefined;
113 /**
114 * The deploy target the build is produced for. Accepts a target value, a
115 * `(config) => target` factory, or a module specifier string.
116 * @default "@alchemy.run/frontend-frameworks/vite/aws"
117 */
118 readonly target?: ViteTargetInput | undefined;
119 /** Serializable overrides merged over the project's `vite.config.*`. */
120 readonly vite?: ViteBuildConfig | undefined;
121 /**
122 * Forwarded to the Node target's static serve entry. Ignored by AWS
123 * (S3) / Cloudflare (Workers assets).
124 */
125 readonly notFoundHandling?: "none" | "spa" | "404-page" | undefined;
126 readonly htmlHandling?: "none" | "drop-trailing-slash" | undefined;
127 readonly dev?:
128 | {
129 /** Default dev-server port (overridden by `FrameworkDevOptions.port`). */
130 readonly port?: number | undefined;
131 }
132 | undefined;
133 }
134
135 const fail = (message: string, cause?: unknown) =>
136 new FrameworkError({ framework: "vite", message, cause });
137
138 /**
139 * Build the `Framework` service implementation for a plain Vite project —
140 * a client-only site (React/Vue/Solid SPA, an `index.html` multi-page app,
141 * a Foldkit app, ...) whose entire deployable output is static assets.
142 *
143 * - `build` resolves the deploy target, then drives the PROJECT's own Vite
144 * install programmatically: one `vite build` with the project's
145 * `vite.config.*` (plugins included) producing the assets directory. The
146 * `BuildOutput` is assets-only: `clientDirectory` = the resolved
147 * `build.outDir`, `serverModules: undefined`.
148 * - `dev` runs the project's own Vite dev server programmatically (native
149 * HMR), scoped — closing the Scope closes the server.
150 *
151 * Frameworks that wrap Vite with a server half (Octane, SvelteKit, Astro,
152 * ...) have their own integrations; Octane's fails actionably when pointed
153 * at a fullstack config, and this one deliberately never looks for server
154 * output.
155 */
156 export const make: (
157 options?: ViteOptions,
158 ) => Effect.Effect<Framework["Service"], never, FileSystem.FileSystem | Path.Path> =
159 Effect.fnUntraced(function* (options?: ViteOptions) {
160 const fs = yield* FileSystem.FileSystem;
161 const path = yield* Path.Path;
162 const baseRoot = options?.root ?? (yield* Effect.sync(() => process.cwd()));
163
164 const targetConfig: ViteTargetConfig = {
165 vite: options?.vite,
166 notFoundHandling: options?.notFoundHandling,
167 htmlHandling: options?.htmlHandling,
168 };
169
170 const resolveTarget = (root: string) =>
171 FrameworkCore.resolveDeployTarget<ViteTarget, ViteTargetConfig>(
172 root,
173 options?.target ?? DEFAULT_TARGET_SPECIFIER,
174 targetConfig,
175 ).pipe(Effect.mapError((error) => fail(error.message, error.cause)));
176
177 const loadVite = (root: string) =>
178 FrameworkCore.loadProjectModule<ViteModule>(root, "vite").pipe(
179 Effect.mapError((error) => fail("Failed to load the project's Vite install", error.cause)),
180 );
181
182 /**
183 * The inline config merged over the project's `vite.config.*` on both
184 * `build` and `resolveConfig`, so the resolved `outDir` and the actual
185 * build always agree.
186 */
187 const inlineConfig = (root: string): Record<string, unknown> => ({
188 root,
189 logLevel: "warn",
190 // Resolve against the project root, not the cwd vite would use, so
191 // "relative to rootDir" semantics hold regardless of where the engine
192 // (or the build child) happens to run.
193 ...(options?.vite?.configFile !== undefined
194 ? { configFile: path.resolve(root, options.vite.configFile) }
195 : undefined),
196 ...(options?.vite?.base !== undefined ? { base: options.vite.base } : undefined),
197 ...(options?.vite?.outDir !== undefined
198 ? { build: { outDir: options.vite.outDir } }
199 : undefined),
200 });
201
202 /** Resolve the absolute assets output directory for a build at `root`. */
203 const resolveOutDir = (vite: ViteModule, root: string) =>
204 Effect.gen(function* () {
205 if (options?.vite?.outDir !== undefined) {
206 return path.resolve(root, options.vite.outDir);
207 }
208 if (vite.resolveConfig === undefined) {
209 return path.resolve(root, "dist");
210 }
211 const resolved = yield* Effect.tryPromise({
212 try: async () =>
213 await vite.resolveConfig!({ ...inlineConfig(root), logLevel: "error" }, "build"),
214 catch: (error) => fail("Failed to resolve the project's vite config", error),
215 });
216 return path.resolve(resolved.root ?? root, resolved.build.outDir);
217 });
218
219 const build: Framework["Service"]["build"] = Effect.fn(function* (buildOptions) {
220 const root = buildOptions?.root ?? baseRoot;
221 const target = yield* resolveTarget(root);
222 const targetContext = { root, framework: "vite", env: buildOptions?.env };
223
224 // Wholesale build takeover (the AWS target uses this seam to run the
225 // build in a disposable child process — vite.config.* executes user
226 // plugins that must not touch the engine process).
227 if (target.build !== undefined) {
228 return yield* target.build(targetContext).pipe(
229 Effect.mapError((error) => fail(error.message, error.cause)),
230 Effect.provideService(FileSystem.FileSystem, fs),
231 Effect.provideService(Path.Path, path),
232 );
233 }
234
235 const vite = yield* loadVite(root);
236 yield* Effect.tryPromise({
237 try: async () => await vite.build(inlineConfig(root)),
238 catch: (error) => fail("Failed to build", error),
239 });
240
241 const outDir = yield* resolveOutDir(vite, root);
242 const output = yield* readViteOutput({ outDir }).pipe(
243 Effect.provideService(FileSystem.FileSystem, fs),
244 );
245
246 return yield* FrameworkCore.applyDeployTargetFinish(target, output, targetContext).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 ...(options?.vite?.configFile !== undefined
270 ? { configFile: path.resolve(root, options.vite.configFile) }
271 : undefined),
272 ...(options?.vite?.base !== undefined ? { base: options.vite.base } : undefined),
273 server: {
274 port,
275 ...(host !== undefined ? { host } : undefined),
276 },
277 });
278 await server.listen();
279 return server;
280 },
281 catch: (error) => fail("Failed to start the Vite dev server", error),
282 }),
283 (server) =>
284 Effect.promise(async () => {
285 try {
286 server.httpServer?.closeAllConnections?.();
287 await server.close();
288 } catch {
289 // teardown is best-effort
290 }
291 }).pipe(
292 Effect.timeout("3 seconds"),
293 Effect.orElseSucceed(() => undefined),
294 ),
295 );
296
297 const url = server.resolvedUrls?.local[0];
298 if (url === undefined) {
299 return yield* fail("Could not determine the dev server URL");
300 }
301
302 // Bounded readiness probe: any HTTP response counts (vite serves
303 // lazily; we only need the listener to answer).
304 yield* Effect.tryPromise({
305 try: async () => {
306 const response = await fetch(url, { redirect: "manual" });
307 await response.arrayBuffer().catch(() => {});
308 },
309 catch: (error) => fail("The dev server did not become reachable", error),
310 }).pipe(Effect.retry({ schedule: Schedule.spaced("250 millis"), times: 40 }));
311
312 return { url };
313 });
314
315 return Framework.of({ build, dev });
316 });
317
318 /**
319 * Map a plain Vite build's on-disk output onto the `BuildOutput` contract:
320 * assets-only — the whole `outDir` is the client directory, there are no
321 * server modules, and no external workspace roots (vite bundles workspace
322 * imports into the client assets).
323 */
324 export const readViteOutput = (options: {
325 /** Absolute assets output directory (the resolved `build.outDir`). */
326 readonly outDir: string;
327 }): Effect.Effect<FrameworkCore.BuildOutput, FrameworkError, FileSystem.FileSystem> =>
328 Effect.gen(function* () {
329 const fs = yield* FileSystem.FileSystem;
330 const exists = yield* Effect.orElseSucceed(fs.exists(options.outDir), () => false);
331 if (!exists) {
332 return yield* fail(`The Vite build produced no output directory at ${options.outDir}`);
333 }
334 return {
335 distDirectory: options.outDir,
336 clientDirectory: options.outDir,
337 serverModules: undefined,
338 externalWorkspaces: new Set<string>(),
339 } satisfies FrameworkCore.BuildOutput;
340 });
341
342 /**
343 * A `Layer` providing framework-core's `Framework` service for a plain Vite
344 * project — the fully-typed entrypoint for `e2e.config.ts` and alchemy's
345 * `AWS.Website.Vite` composite.
346 */
347 export const layer = (
348 options?: ViteOptions,
349 ): Layer.Layer<Framework, never, FileSystem.FileSystem | Path.Path> =>
350 Layer.effect(Framework, make(options));