@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 06:00 UTC

main
ts 559 lines 20.7 KB
Raw
1 import * as NodeNet from "node:net";
2 import * as Data from "effect/Data";
3 import * as Effect from "effect/Effect";
4 import * as Equal from "effect/Equal";
5 import * as FileSystem from "effect/FileSystem";
6 import * as Path from "effect/Path";
7 import { hashDirectory, type MemoOptions } from "../Command/Memo.ts";
8 import { havePropsChanged, isResolved } from "../Diff.ts";
9 import * as LocalProvider from "../Local/LocalProvider.ts";
10 import * as ProviderLayer from "../Local/ProviderLayer.ts";
11 import * as Provider from "../Provider.ts";
12 import { Resource } from "../Resource.ts";
13 import { initialCwd, moduleExtension } from "../Util/Node.ts";
14 import { sha256Object } from "../Util/sha256.ts";
15
16 /**
17 * The structural slice of a framework-integration module
18 * (`@alchemy.run/frontend-frameworks/nuxt`, `@alchemy.run/frontend-frameworks/astro`, ...) this resource
19 * drives. Typed structurally so alchemy carries no dependency on
20 * `@distilled.cloud/framework-core` — the *project's* install is always the
21 * one loaded. Requirement channels are erased (the module is loaded
22 * dynamically, so its effects are typed post-hoc): `build` is
23 * requirement-free and `dev` runs in the caller's ambient Scope.
24 */
25 interface FrameworkModule {
26 readonly make: (options: Record<string, unknown>) => Effect.Effect<
27 {
28 readonly build: (options?: {
29 readonly root?: string;
30 readonly env?: Record<string, string>;
31 }) => Effect.Effect<FrameworkBuildOutputSlice, unknown>;
32 readonly dev: (options?: {
33 readonly root?: string;
34 readonly port?: number;
35 readonly host?: string;
36 }) => Effect.Effect<{ readonly url: string }, unknown>;
37 },
38 unknown,
39 FileSystem.FileSystem | Path.Path
40 >;
41 }
42
43 /** The structural slice of framework-core's `BuildOutput` this resource reads. */
44 interface FrameworkBuildOutputSlice {
45 readonly distDirectory?: string | undefined;
46 readonly clientDirectory: string | undefined;
47 readonly serverModules: Array<{ readonly name: string }> | undefined;
48 }
49
50 export class FrameworkServerError extends Data.TaggedError("FrameworkServerError")<{
51 readonly framework: string;
52 readonly message: string;
53 readonly cause?: unknown;
54 }> {}
55
56 /** Drops `undefined`-valued entries from {@link ServerProps.env}. */
57 const definedEnv = (
58 env: Record<string, string | undefined> | undefined,
59 ): Record<string, string> | undefined =>
60 env === undefined
61 ? undefined
62 : Object.fromEntries(
63 Object.entries(env).filter((entry): entry is [string, string] => entry[1] !== undefined),
64 );
65
66 /**
67 * Options for the local dev server that runs a framework site under
68 * `alchemy dev`.
69 *
70 * Use `{ mode: "external" }` to skip starting a dev server entirely —
71 * useful when an external dev server (e.g. one you run yourself in
72 * another terminal) is serving the site instead.
73 */
74 export type ServerDevProps =
75 | {
76 /**
77 * Run the framework's own dev server locally (the default).
78 * @default "server"
79 */
80 mode?: "server";
81 /**
82 * Host the dev server binds to. Defaults to the framework's own
83 * choice (localhost).
84 */
85 host?: string;
86 /**
87 * Preferred port for the dev server. Defaults to an ephemeral port.
88 * If the port is unavailable, the next free port is used unless
89 * {@link strictPort} is `true`.
90 */
91 port?: number;
92 /**
93 * When `true`, fail instead of falling back to another port if
94 * {@link port} is already in use.
95 * @default false
96 */
97 strictPort?: boolean;
98 }
99 | {
100 /**
101 * Don't start a dev server; an external dev server is running instead.
102 */
103 mode: "external";
104 /**
105 * URL the external dev server is reachable at, if applicable.
106 * This will be returned as the `url` attribute of the Server resource.
107 */
108 url?: string;
109 };
110
111 export interface ServerProps {
112 /**
113 * Module specifier of the framework-integration package that implements
114 * the build and dev server (e.g. `"@alchemy.run/frontend-frameworks/nuxt"`). Must be
115 * installed in your project — it is loaded dynamically at deploy time and
116 * drives your project's own framework toolchain.
117 */
118 framework: string;
119 /**
120 * Project root directory (the directory containing the framework config),
121 * relative to the process working directory.
122 * @default "."
123 */
124 root?: string;
125 /**
126 * The deploy target the build is produced for: a module specifier
127 * resolved from your project's `node_modules`
128 * (e.g. `"@alchemy.run/frontend-frameworks/nuxt/aws"`).
129 */
130 target: string;
131 /**
132 * Framework-integration options forwarded to the module's `make()`
133 * (e.g. `{ nuxt: { ... } }` config overrides). Must be JSON-serializable —
134 * the value participates in the memo hash and is persisted in state.
135 */
136 options?: Record<string, unknown>;
137 /**
138 * Options for the local dev server that runs this site under
139 * `alchemy dev`. See {@link ServerDevProps}.
140 */
141 dev?: ServerDevProps;
142 /**
143 * Environment variables for the framework server. On deploy the
144 * composite sets these on the Lambda; during `alchemy dev` they are
145 * applied to the dev server's process environment (the dev sidecar and
146 * any child it spawns) so server code reads the same values in both
147 * modes. Changing a value restarts the dev server.
148 *
149 * Entries whose value is `undefined` are dropped — this lets website
150 * composites forward optional values (e.g. an `Output` service URL that
151 * resolves to `undefined`) without filtering first.
152 */
153 env?: Record<string, string | undefined>;
154 /**
155 * Controls which files are hashed to decide whether the build should
156 * re-run. By default every non-gitignored file in the root is hashed,
157 * plus the nearest lockfile. Set `false` to rebuild on every deploy.
158 * @default true
159 */
160 memo?: MemoOptions | boolean;
161 }
162
163 export interface Server extends Resource<
164 "Website.Server",
165 ServerProps,
166 {
167 /**
168 * Root output directory of the build (e.g. `.output`), relative to the
169 * process's initial working directory. `undefined` in dev mode (no
170 * production build runs).
171 */
172 distDir: string | undefined;
173 /**
174 * Static-assets directory of the build (prerendered pages included),
175 * relative to the initial working directory. `undefined` when the build
176 * produced no client assets, and in dev mode.
177 */
178 clientDir: string | undefined;
179 /**
180 * The server entry module on disk (e.g. `.output/server/index.mjs`),
181 * relative to the initial working directory. `undefined` for
182 * assets-only builds, and in dev mode.
183 */
184 serverEntry: string | undefined;
185 /**
186 * The framework dev server's local URL (e.g. `http://localhost:3000`)
187 * during `alchemy dev`. `undefined` on deploys.
188 */
189 url: string | undefined;
190 hash: {
191 /**
192 * Hash of the input files (plus framework/target/options) that
193 * produced this build. `undefined` in dev mode.
194 */
195 input: string | undefined;
196 /**
197 * Hash of the build output files. `undefined` in dev mode.
198 */
199 output: string | undefined;
200 };
201 }
202 > {}
203
204 /**
205 * The framework toolchain half of a website: on `alchemy deploy` it
206 * runs the framework's production build with a platform deploy target and
207 * tracks the on-disk output in state; on `alchemy dev` it runs the
208 * framework's OWN dev server (native HMR via the framework's kit) in the
209 * dev sidecar and exposes its local URL. Shared by AWS, Fly, Hetzner, and
210 * Railway website composites.
211 *
212 * The framework package and the target module are loaded from *your*
213 * project's `node_modules`, so your project's framework version drives the
214 * build. Build inputs are content-hashed so an unchanged project skips the
215 * rebuild entirely.
216 *
217 * ### Building Frameworks
218 * **Example:** Nuxt For AWS Lambda
219 * ```typescript
220 * const server = yield* Server("Server", {
221 * framework: "@alchemy.run/frontend-frameworks/nuxt",
222 * target: "@alchemy.run/frontend-frameworks/nuxt/aws",
223 * root: "./app",
224 * });
225 * // deploy: server.serverEntry -> .output/server/index.mjs (Lambda handler)
226 * // server.clientDir -> .output/public (static assets for the CDN)
227 * // dev: server.url -> http://localhost:<port> (framework HMR server)
228 * ```
229 *
230 * @resource
231 */
232 export const Server = Resource<Server>("Website.Server", {
233 aliases: ["AWS.Website.Server", "AWS.Website.FrameworkBuild"],
234 });
235
236 const importFrameworkModule = (specifier: string) =>
237 Effect.tryPromise({
238 try: () => import(specifier) as Promise<Partial<FrameworkModule>>,
239 catch: (cause) =>
240 new FrameworkServerError({
241 framework: specifier,
242 message:
243 `Failed to import the framework integration "${specifier}". ` +
244 "It must be installed in your project (it is loaded dynamically at deploy time).",
245 cause,
246 }),
247 }).pipe(
248 Effect.flatMap((module_) =>
249 typeof module_.make === "function"
250 ? Effect.succeed(module_ as FrameworkModule)
251 : Effect.fail(
252 new FrameworkServerError({
253 framework: specifier,
254 message: `"${specifier}" does not export the framework-integration contract (a "make" function)`,
255 }),
256 ),
257 ),
258 );
259
260 const makeFramework = (props: ServerProps, root: string) =>
261 importFrameworkModule(props.framework).pipe(
262 Effect.flatMap((module_) =>
263 Effect.mapError(
264 module_.make({
265 ...props.options,
266 root,
267 target: props.target,
268 }),
269 (cause) =>
270 new FrameworkServerError({
271 framework: props.framework,
272 message: "Failed to initialize the framework integration",
273 cause,
274 }),
275 ),
276 ),
277 );
278
279 export const ServerProvider = () =>
280 ProviderLayer.dual(Server, {
281 live: ServerProviderLive,
282 local: ServerProviderLocal,
283 });
284
285 export const ServerProviderLive = () =>
286 Provider.effect(
287 Server,
288 Effect.gen(function* () {
289 const path = yield* Path.Path;
290 const fs = yield* FileSystem.FileSystem;
291
292 const runBuild = Effect.fn(function* (props: ServerProps) {
293 const root = path.resolve(initialCwd, props.root ?? ".");
294 const service = yield* makeFramework(props, root);
295 return yield* Effect.mapError(
296 service.build({ root, env: definedEnv(props.env) }),
297 (cause) =>
298 new FrameworkServerError({
299 framework: props.framework,
300 message: `The ${props.framework} build failed`,
301 cause,
302 }),
303 );
304 });
305
306 const hashInput = (props: ServerProps, root: string) =>
307 hashDirectory({
308 cwd: root,
309 memo:
310 props.memo === true || props.memo === undefined || props.memo === false
311 ? {}
312 : props.memo,
313 }).pipe(
314 Effect.flatMap((files) =>
315 sha256Object({
316 files,
317 framework: props.framework,
318 target: props.target,
319 options: props.options,
320 }),
321 ),
322 );
323
324 const hashOutput = (props: ServerProps, distDir: string) =>
325 hashDirectory({
326 cwd: distDir,
327 memo: {
328 // Next.js serves from its project root, not a dedicated output directory.
329 exclude:
330 path.resolve(distDir) === path.resolve(initialCwd, props.root ?? ".")
331 ? ["**/node_modules/**", "**/.git/**", "**/.alchemy/**", ".next/cache/**"]
332 : [],
333 lockfile: false,
334 },
335 });
336
337 const makeOutput = Effect.fn(function* (
338 props: ServerProps,
339 built: FrameworkBuildOutputSlice,
340 ) {
341 const root = path.resolve(initialCwd, props.root ?? ".");
342 const distDir = built.distDirectory ?? path.join(root, "dist");
343 if (!(yield* fs.exists(distDir))) {
344 return yield* new FrameworkServerError({
345 framework: props.framework,
346 message: `The build produced no output directory at ${distDir}`,
347 });
348 }
349 const entryName = built.serverModules?.[0]?.name;
350 return {
351 distDir: path.relative(initialCwd, distDir),
352 clientDir:
353 built.clientDirectory !== undefined
354 ? path.relative(initialCwd, built.clientDirectory)
355 : undefined,
356 serverEntry:
357 entryName !== undefined
358 ? path.relative(initialCwd, path.join(distDir, entryName))
359 : undefined,
360 url: undefined,
361 hash:
362 props.memo === false
363 ? { input: undefined, output: undefined }
364 : yield* Effect.all(
365 {
366 input: hashInput(props, root),
367 output: hashOutput(props, distDir),
368 },
369 { concurrency: "unbounded" },
370 ),
371 };
372 });
373
374 return {
375 list: () => Effect.succeed([]),
376 diff: Effect.fn(function* ({ olds, news, output }) {
377 if (!output || !isResolved(news)) return undefined;
378 if (news.memo === false || !output.hash.input || !output.hash.output)
379 return { action: "update" };
380 if (havePropsChanged(olds, news)) return { action: "update" };
381 const root = path.resolve(initialCwd, news.root ?? ".");
382 // Cheap check: same inputs + output still on disk with the same
383 // content hash -> noop without re-running the build.
384 const input = yield* hashInput(news, root);
385 if (input !== output.hash.input) return { action: "update" };
386 if (output.distDir === undefined) return { action: "update" };
387 const distDir = path.resolve(initialCwd, output.distDir);
388 if (!(yield* fs.exists(distDir))) return { action: "update" };
389 const outHash = yield* hashOutput(news, distDir);
390 return {
391 action: Equal.equals(outHash, output.hash.output) ? "noop" : "update",
392 };
393 }),
394 reconcile: Effect.fn(function* ({ news }) {
395 const built = yield* runBuild(news);
396 return yield* makeOutput(news, built);
397 }),
398 delete: Effect.fn(function* ({ olds, output }) {
399 if (output.distDir === undefined) return;
400 const root = path.resolve(initialCwd, olds.root ?? ".");
401 const distDir = path.resolve(initialCwd, output.distDir);
402 if (!(yield* fs.exists(root)) || !(yield* fs.exists(distDir))) return;
403 // Some frameworks (Next.js) serve from the project root itself.
404 // Only dedicated output directories inside that root are disposable.
405 // Canonical paths also protect roots reached through a symlink.
406 const relative = path.relative(yield* fs.realPath(root), yield* fs.realPath(distDir));
407 if (
408 relative === "" ||
409 relative === ".." ||
410 relative.startsWith(`..${path.sep}`) ||
411 path.isAbsolute(relative)
412 )
413 return;
414 yield* fs.remove(distDir, { recursive: true });
415 }),
416 };
417 }),
418 );
419
420 /**
421 * Try to bind `port` on `host`; resolves `true` when the port is free.
422 * The listener is closed immediately — the port is only observed
423 * available, not reserved, so the caller should bind promptly and the
424 * framework still handles the (tiny) race window itself.
425 */
426 const isPortFree = (port: number, host: string) =>
427 Effect.callback<boolean>((resume) => {
428 const server = NodeNet.createServer();
429 server.unref();
430 server.once("error", () => resume(Effect.succeed(false)));
431 server.listen(port, host, () => {
432 server.close(() => resume(Effect.succeed(true)));
433 });
434 });
435
436 /**
437 * Resolve the dev server's port from the `dev` props: probe the preferred
438 * port and either fail (`strictPort`) or walk forward to the next free
439 * port when it is taken.
440 */
441 const resolveDevPort = Effect.fn(function* (options: {
442 readonly framework: string;
443 readonly port: number;
444 readonly host: string;
445 readonly strictPort: boolean;
446 }) {
447 const { framework, port, host, strictPort } = options;
448 if (yield* isPortFree(port, host)) return port;
449 if (strictPort) {
450 return yield* new FrameworkServerError({
451 framework,
452 message: `Port ${port} is already in use and \`dev.strictPort\` is set`,
453 });
454 }
455 for (let candidate = port + 1; candidate <= port + 100; candidate++) {
456 if (yield* isPortFree(candidate, host)) return candidate;
457 }
458 return yield* new FrameworkServerError({
459 framework,
460 message: `No free port found between ${port} and ${port + 100}`,
461 });
462 });
463
464 /**
465 * A framework dev server may advertise its *bind* address — nuxt echoes the
466 * host it was told to listen on, so a Router-attached site (which binds
467 * `0.0.0.0` to be reachable from the emulator container) reports
468 * `http://0.0.0.0:{port}/`. The unspecified address is not a connectable
469 * host: normalize it to `localhost` for the `url` attribute (browser links,
470 * Router dev routing, the emulated CloudFront edge dialing the origin). The
471 * server itself still listens on every interface.
472 */
473 const normalizeAdvertisedUrl = (url: string) =>
474 url.replace(/^(https?:\/\/)(?:0\.0\.0\.0|\[::\]|\[0+(?::0+){7}\])(?=[:/]|$)/, "$1localhost");
475
476 /**
477 * The `alchemy dev` variant: runs the framework's own dev server (native
478 * HMR through the framework's kit — nuxt, astro, ...) inside the dev
479 * sidecar, so it survives user-code hot reloads. Restarts when the
480 * framework/target/root/options config changes.
481 */
482 export const ServerProviderLocal = () =>
483 LocalProvider.make(
484 Server,
485 import.meta.resolve(`./ServerLocal${moduleExtension(import.meta.url)}`, import.meta.url),
486 Effect.gen(function* () {
487 const path = yield* Path.Path;
488 const fs = yield* FileSystem.FileSystem;
489 return {
490 start: Effect.fn(function* ({ news: props }) {
491 // External mode: an external dev server (run out-of-band by the
492 // user) serves the site — don't import the framework or spawn
493 // anything, just surface the external URL as the attribute.
494 if (props.dev?.mode === "external") {
495 return {
496 distDir: undefined,
497 clientDir: undefined,
498 serverEntry: undefined,
499 url: props.dev.url,
500 hash: { input: undefined, output: undefined },
501 };
502 }
503 const dev = props.dev;
504 const root = path.resolve(initialCwd, props.root ?? ".");
505 // Dev/live env parity: the composite sets these on the Lambda on
506 // deploy; in dev the framework server runs inside the sidecar
507 // (or as its child — `next dev`), so the sidecar's process env
508 // is what SSR code reads. `env` is part of the restart surface,
509 // so a changed value restarts the dev server with the new
510 // environment. Values are not unset on stop: sibling dev servers
511 // share the process, so clearing could clobber their keys.
512 if (props.env !== undefined) {
513 yield* Effect.sync(() => {
514 for (const [key, value] of Object.entries(props.env!)) {
515 if (value === undefined) continue;
516 process.env[key] = String(value);
517 }
518 });
519 }
520 const service = yield* makeFramework(props, root).pipe(
521 Effect.provideService(FileSystem.FileSystem, fs),
522 Effect.provideService(Path.Path, path),
523 );
524 // Resolve the port BEFORE handing off to the framework: probe
525 // the preferred port, fail on `strictPort`, otherwise walk
526 // forward to the next free port. Without a preferred port the
527 // framework picks its own (ephemeral) port.
528 const port =
529 dev?.port !== undefined
530 ? yield* resolveDevPort({
531 framework: props.framework,
532 port: dev.port,
533 host: dev.host ?? "127.0.0.1",
534 strictPort: dev.strictPort ?? false,
535 })
536 : undefined;
537 // `dev` is scoped: the server lives in the instance scope the
538 // LocalProvider helper provides and is torn down on
539 // restart/delete. It resolves at readiness with the local URL.
540 const { url } = yield* Effect.mapError(
541 service.dev({ root, port, host: dev?.host }),
542 (cause) =>
543 new FrameworkServerError({
544 framework: props.framework,
545 message: `The ${props.framework} dev server failed to start`,
546 cause,
547 }),
548 );
549 return {
550 distDir: undefined,
551 clientDir: undefined,
552 serverEntry: undefined,
553 url: normalizeAdvertisedUrl(url),
554 hash: { input: undefined, output: undefined },
555 };
556 }),
557 } satisfies LocalProvider.LocalProviderSpec<Server>;
558 }),
559 );