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

main
ts 131 lines 4.71 KB
Raw
1 import { fileURLToPath } from "node:url";
2 import { dotAlchemyDirectory } from "alchemy/AlchemyContext";
3 import type * as Bundle from "alchemy/Bundle/Bundle";
4 import { isPathWithin } from "alchemy/Util/isPathWithin";
5 import * as Effect from "effect/Effect";
6 import * as FileSystem from "effect/FileSystem";
7 import * as Stream from "effect/Stream";
8 import path from "pathe";
9 import type {
10 DevContext,
11 SourceContext,
12 SourceDevHandle,
13 SourceError,
14 SourceProvider,
15 SourceServices,
16 } from "../Source.ts";
17
18 /**
19 * Convert a Worker `main` entry (a plain path or a `file://` URL) to a
20 * filesystem path, without resolving it.
21 *
22 * Internal to `Workers/Sources/` — not exported from the package index.
23 */
24 export const mainToPath = (main: string) =>
25 Effect.sync(() => {
26 try {
27 return fileURLToPath(main);
28 } catch {
29 return main;
30 }
31 });
32
33 /**
34 * Resolve a Worker `main` entry (path or `file://` URL) to an absolute
35 * path without following symlinks (Alchemy v1 parity): the module walk
36 * happens in the directory the user pointed at, not the entry's
37 * canonical location.
38 *
39 * Deliberately distinct from `Bundle/TempRoot.ts`'s same-named helper,
40 * which canonicalizes through `fs.realPath` — the rolldown bundler wants
41 * the real path, the byte-for-byte readers (python, prebuilt) do not.
42 *
43 * Internal to `Workers/Sources/` — not exported from the package index.
44 */
45 export const resolveMainPath = (main: string) =>
46 mainToPath(main).pipe(Effect.map((p) => path.resolve(p)));
47
48 /**
49 * A {@link SourceProvider} that only produces a server bundle: no static
50 * assets, and `bundle` as its single hash slot. Every built-in source
51 * except vite has this shape — they differ only in how they produce the
52 * bundle and how they watch it for local dev.
53 *
54 * `build` is used for both `build()` and `hash()`; implementations that
55 * are expensive route it through `Artifacts.cached` so diff and reconcile
56 * build once per run.
57 *
58 * Internal to `Workers/Sources/` — not exported from the package index.
59 */
60 export const bundleSource = (spec: {
61 readonly build: (
62 ctx: SourceContext,
63 ) => Effect.Effect<Bundle.BundleOutput, SourceError, SourceServices>;
64 readonly watch: (
65 ctx: DevContext,
66 ) => Effect.Effect<Stream.Stream<Bundle.BundleWatchEvent, SourceError, any>, SourceError, any>;
67 }): SourceProvider => ({
68 ownsAssets: false,
69 build: (ctx) =>
70 spec.build(ctx).pipe(
71 Effect.map((bundle) => ({
72 bundle,
73 assets: undefined,
74 hash: { bundle: bundle.hash },
75 })),
76 ),
77 hash: (ctx) => spec.build(ctx).pipe(Effect.map((bundle) => ({ bundle: bundle.hash }))),
78 dev: (ctx) =>
79 spec.watch(ctx).pipe(Effect.map((bundles) => ({ mode: "bundle", bundles }) as SourceDevHandle)),
80 });
81
82 /**
83 * Watch the directory containing a Worker's entry module and re-read the
84 * bundle on change (debounced), emitting the
85 * {@link Bundle.BundleWatchEvent} protocol the rolldown watcher speaks so
86 * local dev consumes either stream interchangeably.
87 *
88 * Used by the sources that read their bundle byte-for-byte off disk
89 * (python, prebuilt) rather than bundling it — the re-read never goes
90 * through rolldown, preserving their byte-for-byte contract.
91 *
92 * Internal to `Workers/Sources/` — not exported from the package index.
93 */
94 export const watchBundleDirectory = <R>(options: {
95 readonly main: string;
96 readonly read: Effect.Effect<Bundle.BundleOutput, Bundle.BundleError, R>;
97 /** Paths for which a change should NOT trigger a re-read. */
98 readonly ignore?: (path: string) => boolean;
99 }) =>
100 Stream.unwrap(
101 Effect.gen(function* () {
102 const fs = yield* FileSystem.FileSystem;
103 const main = yield* resolveMainPath(options.main);
104 const runtimeBase = process.cwd();
105 const dotAlchemy = yield* dotAlchemyDirectory;
106 const root = path.dirname(main);
107 const read = options.read.pipe(
108 Effect.map((output): Bundle.BundleWatchEvent => ({
109 _tag: "Success",
110 output,
111 })),
112 Effect.catch((error) => Effect.succeed<Bundle.BundleWatchEvent>({ _tag: "Error", error })),
113 );
114 const rebuilds = fs.watch(root).pipe(
115 Stream.filter(
116 (event) =>
117 isPathWithin(dotAlchemy, root, runtimeBase) ||
118 !isPathWithin(dotAlchemy, path.resolve(root, event.path), runtimeBase),
119 ),
120 options.ignore ? Stream.filter((event) => !options.ignore!(event.path)) : (self) => self,
121 Stream.debounce("200 millis"),
122 Stream.flatMap(() =>
123 Stream.make({ _tag: "Start" } as Bundle.BundleWatchEvent).pipe(
124 Stream.concat(Stream.fromEffect(read)),
125 ),
126 ),
127 Stream.catchCause(() => Stream.empty),
128 );
129 return Stream.fromEffect(read).pipe(Stream.concat(rebuilds));
130 }),
131 );