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

main
ts 290 lines 11.9 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 Schema from "effect/Schema";
6 import type { Plugin } from "vite";
7 import * as Core from "../core/index.ts";
8 import type { NodeServeHtmlHandling, NodeServeNotFoundHandling } from "../core/NodeServe.ts";
9 import { make as makeVite, type ViteBuildConfig } from "../vite/Vite.ts";
10
11 /** The completed-build contract exposed by @foldkit/vite-plugin >= 0.25.0. */
12 export const BuildMetadata = Schema.Struct({
13 root: Schema.String,
14 clientDirectory: Schema.String,
15 serverDirectory: Schema.String,
16 serverEntry: Schema.String,
17 manifest: Schema.Struct({
18 schemaVersion: Schema.Literals([1]),
19 client: Schema.String,
20 server: Schema.String,
21 serverEntry: Schema.String,
22 prerendered: Schema.Array(Schema.String),
23 }),
24 });
25 export type BuildMetadata = typeof BuildMetadata.Type;
26
27 export interface FoldkitTargetConfig {
28 /** Serializable overrides for the project's Vite configuration. */
29 readonly vite?: ViteBuildConfig | undefined;
30 /** AWS topology: browser-only, prerendered assets, or a server with assets. Omit for automatic detection. */
31 readonly output?: "spa" | "static" | "server" | undefined;
32 /** Override the default SPA fallback for browser-only builds. */
33 readonly notFoundHandling?: NodeServeNotFoundHandling | undefined;
34 /** Override static HTML routing. */
35 readonly htmlHandling?: NodeServeHtmlHandling | undefined;
36 }
37 export interface FoldkitTarget extends Core.DeployTarget<FoldkitTargetConfig> {}
38 export type FoldkitTargetInput = Core.DeployTargetInput<FoldkitTarget, FoldkitTargetConfig>;
39 export interface FoldkitOptions extends FoldkitTargetConfig {
40 /** Project directory. @default process.cwd() */
41 readonly root?: string | undefined;
42 /** Deployment target. @default "@alchemy.run/frontend-frameworks/foldkit/aws" */
43 readonly target?: FoldkitTargetInput | undefined;
44 /** Native Vite development server options. */
45 readonly dev?: { readonly port?: number | undefined } | undefined;
46 }
47 export const DEFAULT_TARGET_SPECIFIER = "@alchemy.run/frontend-frameworks/foldkit/aws";
48
49 interface ViteBuilder {
50 readonly config: {
51 readonly root: string;
52 readonly base: string;
53 readonly plugins: ReadonlyArray<Pick<Plugin, "name" | "api">>;
54 readonly build: { readonly outDir: string };
55 };
56 readonly environments: Record<
57 string,
58 {
59 readonly config: {
60 readonly root: string;
61 readonly base: string;
62 readonly build: { readonly outDir: string };
63 };
64 }
65 >;
66 readonly buildApp: () => Promise<unknown>;
67 readonly build: (environment: unknown) => Promise<unknown>;
68 }
69 interface ViteModule {
70 readonly createBuilder: (config: Record<string, unknown>) => Promise<ViteBuilder>;
71 }
72 const fail = (message: string, cause?: unknown) =>
73 new Core.FrameworkError({ framework: "foldkit", message, cause });
74
75 /** Capture the plugin API before building, but only read it after buildApp succeeds. */
76 export const metadataReader = (plugins: ViteBuilder["config"]["plugins"]) => {
77 const plugin = plugins.find((plugin) => plugin.name === "foldkit:build");
78 if (!plugin) return undefined;
79 if (typeof plugin.api?.getBuildMetadata !== "function") {
80 throw fail("Foldkit SSR requires @foldkit/vite-plugin >= 0.25.0 with getBuildMetadata().");
81 }
82 // oxlint-disable-next-line effecttsgo/schema-sync -- read inside Vite's build callback; a throw is caught by its tryPromise
83 return () => Schema.decodeUnknownSync(BuildMetadata)(plugin.api.getBuildMetadata());
84 };
85
86 /** Package only deployment artifacts, including independently configured client/server directories. */
87 export const readFoldkitOutput = (
88 root: string,
89 clientDirectory: string,
90 metadata?: BuildMetadata,
91 output?: FoldkitTargetConfig["output"],
92 ) =>
93 Effect.gen(function* () {
94 const fs = yield* FileSystem.FileSystem;
95 const path = yield* Path.Path;
96 if (output === "spa" && metadata) {
97 return yield* fail(
98 'Foldkit produced a server build. Set output: "server" for SSR/hybrid or output: "static" for prerendered assets.',
99 );
100 }
101 if (output === "server" && !metadata) {
102 return yield* fail(
103 'Foldkit produced no server handler. Enable ssr.build in vite.config.ts or omit output: "server".',
104 );
105 }
106 if (output === "static" && metadata && metadata.manifest.prerendered.length === 0) {
107 return yield* fail(
108 'Static Foldkit output requires prerendered pages. Configure ssr.build.prerender or use output: "server".',
109 );
110 }
111 // Packaging lives outside `.alchemy`, which Neon's packager refuses to
112 // ship from, and like it is gitignored and excluded from build memos.
113 const distDirectory = path.join(root, "node_modules", ".cache", "alchemy", "foldkit");
114 const isWithin = (parent: string, child: string) => {
115 const relative = path.relative(parent, child);
116 return (
117 relative === "" ||
118 (!relative.startsWith(`..${path.sep}`) && relative !== ".." && !path.isAbsolute(relative))
119 );
120 };
121 for (const directory of [clientDirectory, ...(metadata ? [metadata.serverDirectory] : [])]) {
122 if (isWithin(distDirectory, directory) || isWithin(directory, distDirectory)) {
123 return yield* fail(
124 "Foldkit output directories must not overlap node_modules/.cache/alchemy/foldkit, which is reserved for deployment packaging.",
125 );
126 }
127 }
128 if (
129 metadata &&
130 (!isWithin(metadata.serverDirectory, metadata.serverEntry) ||
131 metadata.serverEntry === metadata.serverDirectory)
132 ) {
133 return yield* fail("Foldkit's server entry must be inside its server output directory.");
134 }
135 yield* fs.remove(distDirectory, { recursive: true, force: true });
136 yield* fs.makeDirectory(distDirectory, { recursive: true });
137 const client = path.join(distDirectory, "client");
138 yield* fs.copy(clientDirectory, client);
139 if (!metadata || output === "static") {
140 return {
141 output: {
142 distDirectory,
143 clientDirectory: client,
144 serverModules: undefined,
145 externalWorkspaces: new Set<string>(),
146 } satisfies Core.BuildOutput,
147 entry: undefined,
148 };
149 }
150 const server = path.join(distDirectory, "server");
151 yield* fs.copy(metadata.serverDirectory, server);
152 const entryName = path
153 .relative(metadata.serverDirectory, metadata.serverEntry)
154 .replaceAll("\\", "/");
155 const modules = yield* Core.readServerModulesFromDisk({
156 directory: server,
157 prefix: "server",
158 });
159 if (!modules.some((module) => module.name === `server/${entryName}`)) {
160 return yield* fail("Foldkit's generated server entry is missing from the build output.");
161 }
162 return {
163 output: {
164 distDirectory,
165 clientDirectory: client,
166 serverModules: Core.sortServerModules(modules, `server/${entryName}`),
167 externalWorkspaces: new Set<string>(),
168 } satisfies Core.BuildOutput,
169 entry: path.join(server, entryName),
170 };
171 }).pipe(
172 Effect.mapError((cause) =>
173 cause instanceof Core.FrameworkError
174 ? cause
175 : fail("Failed to collect Foldkit build output", cause),
176 ),
177 );
178
179 /** Build with the project's plugin and host its native development server. */
180 export const make: (
181 options?: FoldkitOptions,
182 ) => Effect.Effect<Core.Framework["Service"], never, FileSystem.FileSystem | Path.Path> =
183 Effect.fnUntraced(function* (options: FoldkitOptions = {}) {
184 const fs = yield* FileSystem.FileSystem;
185 const path = yield* Path.Path;
186 const baseRoot = options.root ?? process.cwd();
187 const config: FoldkitTargetConfig = {
188 vite: options.vite,
189 output: options.output,
190 notFoundHandling: options.notFoundHandling,
191 htmlHandling: options.htmlHandling,
192 };
193 const native = yield* makeVite({
194 root: baseRoot,
195 vite: options.vite,
196 dev: options.dev,
197 });
198 const provide = <A, E>(effect: Effect.Effect<A, E, FileSystem.FileSystem | Path.Path>) =>
199 effect.pipe(
200 Effect.provideService(FileSystem.FileSystem, fs),
201 Effect.provideService(Path.Path, path),
202 );
203 const build: Core.Framework["Service"]["build"] = Effect.fn(function* (buildOptions) {
204 const root = path.resolve(buildOptions?.root ?? baseRoot);
205 const target = yield* Core.resolveDeployTarget<FoldkitTarget, FoldkitTargetConfig>(
206 root,
207 options.target ?? DEFAULT_TARGET_SPECIFIER,
208 config,
209 ).pipe(Effect.mapError((error) => fail(error.message, error.cause)));
210 const context = { root, framework: "foldkit", env: buildOptions?.env };
211 if (target.build)
212 return yield* provide(target.build(context)).pipe(
213 Effect.mapError((error) => fail(error.message, error.cause)),
214 );
215 const vite = yield* Core.loadProjectModule<ViteModule>(root, "vite").pipe(
216 Effect.mapError((error) => fail(error.message, error.cause)),
217 );
218 const built = yield* Effect.tryPromise({
219 try: async () => {
220 const outDir = options.vite?.outDir;
221 const outputPlugin: Plugin = {
222 name: "alchemy:foldkit-output",
223 enforce: "post",
224 config: (config) =>
225 config.environments?.ssr?.build?.ssr
226 ? {
227 // Like TanStack Start, deploy a self-contained Node bundle.
228 ssr: { noExternal: true },
229 environments: {
230 ...(outDir !== undefined
231 ? {
232 client: {
233 build: { outDir: path.join(outDir, "client") },
234 },
235 }
236 : {}),
237 ssr: {
238 resolve: { noExternal: true },
239 ...(outDir !== undefined
240 ? { build: { outDir: path.join(outDir, "server") } }
241 : {}),
242 },
243 },
244 }
245 : undefined,
246 };
247 const builder = await vite.createBuilder({
248 root,
249 logLevel: "warn",
250 ...(options.vite?.configFile !== undefined
251 ? { configFile: path.resolve(root, options.vite.configFile) }
252 : {}),
253 ...(options.vite?.base !== undefined ? { base: options.vite.base } : {}),
254 ...(outDir !== undefined ? { build: { outDir } } : {}),
255 plugins: [outputPlugin],
256 });
257 const read = metadataReader(builder.config.plugins);
258 // Without Foldkit's SSR build plugin the app is client-only; the
259 // default `buildApp` would also build the `ssr` environment, whose
260 // only input is `index.html`.
261 if (read) await builder.buildApp();
262 else await builder.build(builder.environments.client);
263 const metadata = read?.();
264 const client = builder.environments.client?.config ?? builder.config;
265 return {
266 metadata,
267 assetBasePath: decodeURIComponent(new URL(client.base, "http://localhost").pathname),
268 client: metadata?.clientDirectory ?? path.resolve(client.root, client.build.outDir),
269 };
270 },
271 catch: (cause) => fail("Failed to build Foldkit", cause),
272 });
273 const collected = yield* provide(
274 readFoldkitOutput(root, built.client, built.metadata, options.output),
275 );
276 return yield* provide(
277 Core.applyDeployTargetFinish(target, collected.output, {
278 ...context,
279 entry: collected.entry,
280 assetBasePath: built.assetBasePath,
281 }),
282 ).pipe(Effect.mapError((error) => fail(error.message, error.cause)));
283 });
284 return Core.Framework.of({ build, dev: native.dev });
285 });
286
287 export const layer = (
288 options?: FoldkitOptions,
289 ): Layer.Layer<Core.Framework, never, FileSystem.FileSystem | Path.Path> =>
290 Layer.effect(Core.Framework, make(options));