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

main
ts 324 lines 12.6 KB
Raw
1 /** @effect-diagnostics anyUnknownInErrorContext:off */
2
3 /**
4 * The Lambda Function code-bundling machinery, extracted from the live
5 * provider closure so it is reusable outside `FunctionProvider` — the floci
6 * local provider's watch loop rebuilds the exact same artifact on file
7 * change (see [FlociFunctionProvider](./FlociFunctionProvider.ts)).
8 *
9 * `makeFunctionBundler` resolves the platform services once and returns the
10 * same `bundleCode(id, props)` the live provider always used, plus the
11 * split-out pieces (`resolveBundlePlan` / `finishBundle` / `prebuiltCode`)
12 * that let a watcher run `Bundle.watch` with the identical rolldown config
13 * and post-process each incremental output into a deployable archive.
14 */
15
16 import * as Bundle from "alchemy/Bundle/Bundle";
17 import {
18 hashPackageInstallIdentity,
19 installResolvedPackages,
20 matchesPackageRoot,
21 normalizeInstallTargets,
22 resolvePackageInstallIdentity,
23 } from "alchemy/Bundle/InstalledPackages";
24 import * as TempRoot from "alchemy/Bundle/TempRoot";
25 import { sha256, sha256Object } from "alchemy/Util/sha256";
26 import { zipCode, zipFiles, type ZipFile } from "alchemy/Util/zip";
27 import * as Effect from "effect/Effect";
28 import * as FileSystem from "effect/FileSystem";
29 import type * as Path from "effect/Path";
30 import type { PlatformError } from "effect/PlatformError";
31 import type { ChildProcessSpawner } from "effect/process/ChildProcessSpawner";
32 import type * as rolldown from "rolldown";
33 import { roleHostBundle } from "../AWSBindings.ts";
34 import type { FunctionArchitecture, FunctionZipProps } from "./Function.ts";
35
36 /**
37 * Evaluates a user-supplied Rolldown `external` option (string, RegExp, array,
38 * or predicate) for a single module id, preserving its original semantics.
39 */
40 export const matchesConfiguredExternal = (
41 external: rolldown.InputOptions["external"],
42 moduleId: string,
43 parentId: string | undefined,
44 isResolved: boolean,
45 ): boolean => {
46 if (external === undefined) return false;
47 if (typeof external === "function") {
48 return external(moduleId, parentId, isResolved) === true;
49 }
50 const matchers = Array.isArray(external) ? external : [external];
51 return matchers.some((matcher) =>
52 typeof matcher === "string" ? matcher === moduleId : matcher.test(moduleId),
53 );
54 };
55
56 /**
57 * The resolved rolldown configuration for a `bundle: true` Function — the
58 * exact input/output options `bundleCode` hands to `Bundle.build`, reusable
59 * verbatim with `Bundle.watch` for incremental dev rebuilds, plus the
60 * post-processing inputs `finishBundle` needs.
61 */
62 export interface FunctionBundlePlan {
63 readonly inputOptions: rolldown.InputOptions;
64 readonly outputOptions: rolldown.OutputOptions;
65 readonly extra: Bundle.BundleExtraOptions | undefined;
66 readonly cwd: string;
67 readonly requested: Record<string, string>;
68 readonly sourcemap: boolean | "inline" | "hidden";
69 readonly uploadSourceMap: boolean;
70 readonly architecture: FunctionArchitecture;
71 }
72
73 export interface FunctionBundleResult {
74 /** Identity hash driving change detection in `diff` / watch dedupe. */
75 readonly identityHash: string;
76 /** Deferred archive build (performs native-package installs). */
77 readonly buildArchive: Effect.Effect<
78 { archive: Uint8Array<ArrayBufferLike>; archiveHash: string },
79 Bundle.BundleError,
80 BundleServices
81 >;
82 }
83
84 type BundleServices = FileSystem.FileSystem | Path.Path | ChildProcessSpawner;
85
86 /**
87 * Per-host overrides for the generated archive. The Event Function defaults
88 * apply when omitted; `AWS.Lambda.WebFunction` supplies its own HTTP-server
89 * entry.
90 */
91 export interface FunctionBundleOptions {
92 /**
93 * Source of the generated entry module that imports an Effect `main`.
94 * Replaces the Event Function `bootstrap` entry. External (`isExternal`)
95 * modules are always bundled as-is.
96 */
97 readonly entry?: (importPath: string) => string;
98 }
99
100 export const makeFunctionBundler = Effect.gen(function* () {
101 const fs = yield* FileSystem.FileSystem;
102 const virtualEntryPlugin = yield* Bundle.virtualEntryPlugin;
103
104 // Recursively list every file under `root` as sorted POSIX-relative
105 // paths (prebuilt-directory packaging).
106 const walkFiles = (root: string): Effect.Effect<string[], PlatformError, never> =>
107 Effect.gen(function* () {
108 const out: string[] = [];
109 const go: (rel: string) => Effect.Effect<void, PlatformError> = Effect.fn(function* (
110 rel: string,
111 ) {
112 const absolute = rel === "" ? root : `${root}/${rel}`;
113 const entries = yield* fs.readDirectory(absolute);
114 for (const entry of entries) {
115 const childRel = rel === "" ? entry : `${rel}/${entry}`;
116 const info = yield* fs.stat(`${root}/${childRel}`);
117 if (info.type === "Directory") {
118 yield* go(childRel);
119 } else {
120 out.push(childRel);
121 }
122 }
123 });
124 yield* go("");
125 return out.sort();
126 });
127
128 // `bundle: false` — ship `main`'s directory as-is. Framework outputs
129 // like nitro's `.output/server` are complete deployment units (entry +
130 // chunks + their own `node_modules`); re-bundling them can orphan
131 // CJS `require`s of exports-mapped subpaths.
132 const prebuiltCode: (realMain: string) => Effect.Effect<FunctionBundleResult, PlatformError> =
133 Effect.fn(function* (realMain: string) {
134 const lastSlash = realMain.lastIndexOf("/");
135 const dir = realMain.slice(0, lastSlash);
136 const files = yield* walkFiles(dir);
137 const archiveFiles: ZipFile[] = [];
138 const fileHashes: Record<string, string> = {};
139 for (const rel of files) {
140 const content = yield* fs.readFile(`${dir}/${rel}`);
141 archiveFiles.push({ path: rel, content });
142 fileHashes[rel] = yield* sha256(content);
143 }
144 const identityHash = yield* sha256Object(fileHashes);
145 const buildArchive = Effect.gen(function* () {
146 const archive = yield* zipFiles(archiveFiles);
147 return { archive, archiveHash: identityHash };
148 });
149 return { identityHash, buildArchive };
150 });
151
152 const resolveBundlePlan: (
153 props: FunctionZipProps,
154 options?: FunctionBundleOptions,
155 ) => Effect.Effect<
156 FunctionBundlePlan,
157 Bundle.BundleError | PlatformError,
158 FileSystem.FileSystem | Path.Path
159 > = Effect.fn(function* (props: FunctionZipProps, options?: FunctionBundleOptions) {
160 const {
161 output: buildOutput,
162 install,
163 pure: _pure,
164 bundleAnalyzer: _bundleAnalyzer,
165 ...inputOptions
166 } = props.build ?? {};
167 const sourcemap = buildOutput?.sourcemap ?? true;
168 const uploadSourceMap = props.uploadSourceMap ?? true;
169
170 const realMain = yield* TempRoot.resolveMainPath(props.main);
171 const cwd = yield* TempRoot.findCwdForBundle(realMain);
172
173 const rolldownSourcemap = sourcemap;
174 const architecture = props.architecture ?? "x86_64";
175
176 // Explicit install roots are excluded from the bundle and installed
177 // into the deployment artifact. build.external stays a pure Rolldown
178 // escape hatch and is not installed by Alchemy.
179 const requested = yield* normalizeInstallTargets(install);
180 const installRoots = new Set(Object.keys(requested));
181 const configuredExternal = inputOptions.external;
182 const externalOption = (
183 moduleId: string,
184 parentId: string | undefined,
185 isResolved: boolean,
186 ): boolean => {
187 if (moduleId.startsWith("@aws-sdk/")) return true;
188 for (const root of installRoots) {
189 if (matchesPackageRoot(moduleId, root)) return true;
190 }
191 return matchesConfiguredExternal(configuredExternal, moduleId, parentId, isResolved);
192 };
193
194 const entryPlugin = props.isExternal
195 ? undefined
196 : virtualEntryPlugin(
197 options?.entry ??
198 ((importPath) => `
199 import { bootstrap } from "@alchemy.run/aws/Bootstrap/Lambda";
200 import entrypoint from ${JSON.stringify(importPath)};
201
202 export default await bootstrap(entrypoint);
203 `),
204 );
205
206 return {
207 inputOptions: roleHostBundle({
208 ...inputOptions,
209 input: realMain,
210 cwd,
211 external: externalOption,
212 platform: "node",
213 // The zip runtime is Node (`nodejs22.x` | `nodejs24.x`): resolve with
214 // the node conditions and let rolldown supply the import kind. A
215 // `bun` condition here would hand a Node function any package's
216 // bun-specific entry. (Container-image functions are built by the
217 // user's Dockerfile and never pass through this bundler.)
218 resolve: {
219 ...inputOptions.resolve,
220 conditionNames: [
221 ...(inputOptions.resolve?.conditionNames ?? Bundle.NODE_CONDITION_NAMES),
222 ],
223 },
224 plugins: [inputOptions.plugins, entryPlugin],
225 }),
226 outputOptions: {
227 ...buildOutput,
228 format: "esm",
229 sourcemap: rolldownSourcemap,
230 // Minified like Workers: source maps ship and `--enable-source-maps`
231 // is set (see `withNodeSourceMaps`), so stack traces still map back,
232 // and `keepNames` keeps class and function names for Effect spans.
233 minify: buildOutput?.minify ?? true,
234 keepNames: buildOutput?.keepNames ?? true,
235 entryFileNames: "index.js",
236 codeSplitting: buildOutput?.codeSplitting ?? false,
237 },
238 extra: props.build,
239 cwd,
240 requested,
241 sourcemap: rolldownSourcemap,
242 uploadSourceMap,
243 architecture,
244 } satisfies FunctionBundlePlan;
245 });
246
247 const finishBundle: (
248 plan: FunctionBundlePlan,
249 bundleOutput: Bundle.BundleOutput,
250 ) => Effect.Effect<FunctionBundleResult, Bundle.BundleError, BundleServices> = Effect.fn(
251 function* (plan: FunctionBundlePlan, bundleOutput: Bundle.BundleOutput) {
252 const mainFile = bundleOutput.files[0];
253 const code =
254 typeof mainFile.content === "string"
255 ? new TextEncoder().encode(mainFile.content)
256 : mainFile.content;
257
258 const includeSourceMaps =
259 plan.uploadSourceMap && (plan.sourcemap === true || plan.sourcemap === "hidden");
260
261 const extraFiles = bundleOutput.files
262 .slice(1)
263 .filter((f: Bundle.BundleFile) => includeSourceMaps || !f.path.endsWith(".map"))
264 .map((f: Bundle.BundleFile) => ({ path: f.path, content: f.content }));
265
266 // Resolve install versions without running npm so `diff` can compare a
267 // stable identity hash. The archive build performs the install.
268 const installIdentity = yield* resolvePackageInstallIdentity({
269 cwd: plan.cwd,
270 requested: plan.requested,
271 });
272 const resolved = installIdentity.resolved;
273 const hasInstalledPackages = Object.keys(resolved).length > 0;
274
275 // Identity hash drives change detection in `diff`. With native packages,
276 // the installed bytes are not captured by the bundle hash, so fold the
277 // resolved versions, package-manager lockfile, and architecture in
278 // instead of installing.
279 const identityHash = hasInstalledPackages
280 ? yield* hashPackageInstallIdentity({
281 bundleHash: bundleOutput.hash,
282 identity: installIdentity,
283 architecture: plan.architecture,
284 })
285 : bundleOutput.hash;
286
287 const buildArchive = Effect.gen(function* () {
288 const installedPackageFiles = hasInstalledPackages
289 ? yield* installResolvedPackages({
290 resolved,
291 overrides: installIdentity.overrides,
292 architecture: plan.architecture,
293 })
294 : [];
295 const archiveFiles = [...extraFiles, ...installedPackageFiles];
296 const archive = yield* zipCode(code, archiveFiles.length > 0 ? archiveFiles : undefined);
297 // The S3 asset key is content-addressed, so the archive hash must be a
298 // true hash of the bytes when native packages are present.
299 const archiveHash =
300 installedPackageFiles.length > 0 ? yield* sha256(archive) : bundleOutput.hash;
301 return { archive, archiveHash };
302 });
303
304 return { identityHash, buildArchive };
305 },
306 );
307
308 const bundleCode: (
309 id: string,
310 props: FunctionZipProps,
311 options?: FunctionBundleOptions,
312 ) => Effect.Effect<FunctionBundleResult, Bundle.BundleError | PlatformError, BundleServices> =
313 Effect.fn(function* (_id: string, props: FunctionZipProps, options?: FunctionBundleOptions) {
314 if (props.bundle === false) {
315 const realMain = yield* TempRoot.resolveMainPath(props.main);
316 return yield* prebuiltCode(realMain);
317 }
318 const plan = yield* resolveBundlePlan(props, options);
319 const bundleOutput = yield* Bundle.build(plan.inputOptions, plan.outputOptions, plan.extra);
320 return yield* finishBundle(plan, bundleOutput);
321 });
322
323 return { bundleCode, prebuiltCode, resolveBundlePlan, finishBundle };
324 });