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

main
ts 615 lines 27.9 KB
Raw
1 import { createHash } from "node:crypto";
2 import { createRequire } from "node:module";
3 import { gunzipSync } from "node:zlib";
4 import { isResolved } from "alchemy/Diff";
5 import { createPhysicalName } from "alchemy/PhysicalName";
6 import * as Provider from "alchemy/Provider";
7 import { Resource } from "alchemy/Resource";
8 import { initialCwd } from "alchemy/Util/Node";
9 import { sha256 } from "alchemy/Util/sha256";
10 import { zipFiles, type ZipFile } from "alchemy/Util/zip";
11 import { loadFrontendCore } from "alchemy/Website/FrontendCore";
12 import { packSiteExtraFiles } from "alchemy/Website/packExtraFiles";
13 import * as Data from "effect/Data";
14 import * as Effect from "effect/Effect";
15 import * as FileSystem from "effect/FileSystem";
16 import * as FetchHttpClient from "effect/http/FetchHttpClient";
17 import * as HttpClient from "effect/http/HttpClient";
18 import * as Path from "effect/Path";
19 import type { PlatformError } from "effect/PlatformError";
20 import * as Stream from "effect/Stream";
21 import { validateFunctionZip } from "../FunctionArtifact.ts";
22 import { nativeArtifactError, neonRuntimeTarget as runtimeTarget } from "../NativeArtifact.ts";
23 import { packageWebsiteInChild } from "./Package.ts";
24 import { traceWebsiteFiles } from "./Trace.ts";
25
26 /** Build output staged after Website.Server finishes. */
27 export interface WebsiteArtifactProps {
28 /** Application directory relative to the initial working directory. */
29 root: string;
30 /** Dedicated output directory, or the application root for Next.js. */
31 distDir: string;
32 /** Fetch entrypoint relative to the initial working directory. */
33 serverEntry?: string;
34 /** Static-file handler configuration, instead of a framework entrypoint. */
35 static?: {
36 /** Unmatched-path behavior. @default "none" */
37 notFoundHandling?: "none" | "spa" | "404-page";
38 /** Extensionless HTML behavior. @default "none" */
39 htmlHandling?: "none" | "drop-trailing-slash";
40 /** HTML file returned for misses, relative to output. @default "404.html" */
41 errorPage?: string;
42 };
43 /** Next.js includes .next, public assets, and configuration. */
44 layout?: "output" | "next";
45 /** Build dependency fingerprint; traced dependencies are also hashed. */
46 buildHash?: string;
47 }
48
49 /** Filesystem-only staging lifecycle; never owns cloud resources. */
50 export interface WebsiteArtifact extends Resource<
51 "Neon.WebsiteArtifact",
52 WebsiteArtifactProps,
53 {
54 /** Private directory owned by this artifact resource. */
55 directory: string;
56 /** Validated, deterministic Function ZIP. */
57 artifactPath: string;
58 /** SHA-256 of the complete ZIP, including traced dependencies. */
59 hash: string;
60 }
61 > {}
62
63 export const WebsiteArtifact = Resource<WebsiteArtifact>("Neon.WebsiteArtifact");
64
65 /** Packaging failed before any Function deployment. */
66 export class WebsiteArtifactError extends Data.TaggedError("WebsiteArtifactError")<{
67 /** Sanitized explanation of the unsupported or unsafe artifact. */
68 message: string;
69 }> {}
70
71 const MAX_ENTRIES = 50_000;
72 const MAX_BYTES = 250 * 1024 * 1024;
73 const excluded = (file: string) =>
74 file
75 .split(/[\\/]/)
76 .some(
77 (part) =>
78 /^(?:\.git|\.alchemy|\.env.*|\.npmrc|\.yarnrc.*|\.netrc|\.pypirc|\.aws|\.ssh|credentials(?:\.json)?|service-account.*\.json|id_rsa|id_ed25519)$/.test(
79 part,
80 ) || /\.(?:pem|key|p12|pfx)$/.test(part),
81 );
82 const sourceOnly = (file: string) => /(?:\.map|\.d\.[cm]?ts)$/.test(file);
83 const native = (file: string) => /\.(?:node|dylib|dll|so(?:\.\d+)*)$/.test(file);
84 const javascript = (file: string) => /\.[cm]?[jt]sx?$/.test(file);
85 const nextExcluded = (relative: string) =>
86 /^\.next\/(?:cache|standalone|types|diagnostics|dev)(?:\/|$)/.test(relative) ||
87 /^\.next\/trace(?:-|$)/.test(relative);
88 const fail = (message: string) => Effect.fail(new WebsiteArtifactError({ message }));
89
90 const exactVersion = /^\d+\.\d+\.\d+(?:-[\w.-]+)?$/;
91 interface PackageManifest {
92 name?: string;
93 version?: string;
94 os?: string[];
95 cpu?: string[];
96 libc?: string[];
97 optionalDependencies?: Record<string, string>;
98 }
99 const compatible = (manifest: PackageManifest) =>
100 Object.entries(runtimeTarget).every(([key, value]) => {
101 const field = manifest[key as keyof typeof runtimeTarget];
102 return (
103 field === undefined ||
104 (Array.isArray(field) &&
105 field.every((item) => typeof item === "string") &&
106 !field.includes(`!${value}`) &&
107 (field.every((item) => item.startsWith("!")) || field.includes(value)))
108 );
109 });
110
111 const validateBinary = (file: string, content: Uint8Array) => {
112 const message = nativeArtifactError(file, content);
113 if (message) throw new WebsiteArtifactError({ message });
114 };
115
116 /** Fetch only an exact platform package; never re-resolve the application's dependency graph. */
117 const platformPackage = Effect.fn(
118 function* (name: string, version: string) {
119 if (!/^@img\/sharp-(?:libvips-)?linux-arm64$/.test(name) || !exactVersion.test(version))
120 return yield* fail("Sharp must declare exact Linux ARM64 platform package versions.");
121 const client = (yield* HttpClient.HttpClient).pipe(HttpClient.filterStatusOk);
122 const metadataResponse = yield* client.get(
123 `https://registry.npmjs.org/${encodeURIComponent(name)}/${version}`,
124 );
125 const metadata = (yield* metadataResponse.json) as PackageManifest & {
126 dist?: { integrity?: string; tarball?: string };
127 };
128 if (
129 metadata.name !== name ||
130 metadata.version !== version ||
131 !compatible(metadata) ||
132 !metadata.dist?.integrity?.match(/^sha512-[A-Za-z0-9+/]+={0,2}$/)
133 )
134 return yield* fail(`Invalid registry identity or integrity for ${name}@${version}.`);
135 const url = yield* Effect.try({
136 try: () => new URL(metadata.dist!.tarball!),
137 catch: () =>
138 new WebsiteArtifactError({
139 message: "Invalid platform package tarball URL.",
140 }),
141 });
142 if (
143 url.origin !== "https://registry.npmjs.org" ||
144 url.username ||
145 url.password ||
146 url.search ||
147 url.hash ||
148 url.pathname !== `/${name}/-/${name.split("/")[1]}-${version}.tgz`
149 )
150 return yield* fail("Platform packages must use the canonical npm registry tarball.");
151 const response = yield* client.get(url.href);
152 let compressedBytes = 0;
153 const chunks = yield* response.stream.pipe(
154 Stream.mapEffect((chunk) => {
155 compressedBytes += chunk.length;
156 return compressedBytes > MAX_BYTES
157 ? fail("Platform tarball exceeds its byte limit.")
158 : Effect.succeed(chunk);
159 }),
160 Stream.runCollect,
161 Effect.map((chunks) => [...chunks]),
162 );
163 const files = yield* Effect.try({
164 try: () => {
165 const compressed = Buffer.concat(chunks);
166 const integrity = `sha512-${createHash("sha512").update(compressed).digest("base64")}`;
167 if (integrity !== metadata.dist!.integrity) throw new Error("Registry integrity mismatch");
168 const tar = gunzipSync(compressed, { maxOutputLength: MAX_BYTES });
169 const files = new Map<string, Uint8Array>();
170 const text = (start: number, size: number) =>
171 new TextDecoder().decode(tar.subarray(start, start + size)).replace(/\0.*$/s, "");
172 let entries = 0;
173 for (let offset = 0; offset < tar.length;) {
174 if (++entries > MAX_ENTRIES) throw new Error("Too many tar entries");
175 if (tar.subarray(offset, offset + 512).every((byte) => byte === 0)) break;
176 if (offset + 512 > tar.length) throw new Error("Truncated tar header");
177 const header = tar.subarray(offset, offset + 512);
178 const checksum = Number.parseInt(text(offset + 148, 8).trim(), 8);
179 const actual = header.reduce(
180 (sum, byte, index) => sum + (index >= 148 && index < 156 ? 32 : byte),
181 0,
182 );
183 if (checksum !== actual) throw new Error("Invalid tar checksum");
184 const prefix = text(offset + 345, 155);
185 const entry = `${prefix ? `${prefix}/` : ""}${text(offset, 100)}`;
186 const sizeText = text(offset + 124, 12).trim();
187 if (!/^[0-7]+$/.test(sizeText)) throw new Error("Invalid tar size");
188 const size = Number.parseInt(sizeText, 8);
189 const type = header[156];
190 if (
191 !entry.startsWith("package/") ||
192 entry.includes("\\") ||
193 entry
194 .replace(/\/$/, "")
195 .split("/")
196 .some((part) => !part || part === ".." || part === ".") ||
197 excluded(entry)
198 )
199 throw new Error("Unsafe tar path");
200 if (![0, 48, 53].includes(type!)) throw new Error("Non-regular tar entry");
201 if (!Number.isSafeInteger(size) || size < 0 || offset + 512 + size > tar.length)
202 throw new Error("Truncated tar entry");
203 if (type !== 53) {
204 const file = entry.slice(8);
205 if (!file || files.has(file) || files.size >= MAX_ENTRIES)
206 throw new Error("Invalid tar entries");
207 const content = tar.subarray(offset + 512, offset + 512 + size);
208 validateBinary(file, content);
209 files.set(file, content);
210 }
211 offset += 512 + Math.ceil(size / 512) * 512;
212 }
213 const manifest = JSON.parse(
214 Buffer.from(files.get("package.json")!).toString("utf8"),
215 ) as PackageManifest;
216 if (manifest.name !== name || manifest.version !== version || !compatible(manifest))
217 throw new Error("Package identity or platform mismatch");
218 if (![...files.keys()].some(native))
219 throw new Error("Platform package contains no native library");
220 return files;
221 },
222 catch: () =>
223 new WebsiteArtifactError({
224 message: `Failed integrity, archive, or Linux ARM64 validation for ${name}@${version}.`,
225 }),
226 });
227 return files;
228 },
229 Effect.provide(FetchHttpClient.layer),
230 Effect.provideService(FetchHttpClient.RequestInit, { redirect: "error" }),
231 Effect.timeout("45 seconds"),
232 );
233
234 /**
235 * Preserve the traced module layout, materializing only selected symlink targets.
236 * Node 24 resolution hooks restore canonical package identity without ZIP links.
237 * The caller must archive the temporary directory before its Scope closes.
238 */
239 export const stageWebsiteArtifact = Effect.fn(function* (props: WebsiteArtifactProps) {
240 const fs = yield* FileSystem.FileSystem;
241 const path = yield* Path.Path;
242 const root = yield* fs.realPath(path.resolve(initialCwd, props.root));
243 const dist = yield* fs.realPath(path.resolve(initialCwd, props.distDir));
244 const entry =
245 props.serverEntry === undefined
246 ? undefined
247 : yield* fs.realPath(path.resolve(initialCwd, props.serverEntry));
248 const within = (directory: string, file: string) => {
249 const relative = path.relative(directory, file);
250 return relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative);
251 };
252 if (!entry && !props.static)
253 return yield* fail("A Fetch entrypoint or static options are required.");
254 if (props.layout !== "next" && root === dist)
255 return yield* fail("Output must be a dedicated directory, not the application root.");
256 if (!within(root, dist))
257 return yield* fail("Website output must be inside the application root.");
258 if (entry && !within(props.layout === "next" ? root : dist, entry))
259 return yield* fail("Fetch entrypoint escapes the build output.");
260 if (
261 props.static?.errorPage &&
262 (path.isAbsolute(props.static.errorPage) ||
263 !within(dist, path.resolve(dist, props.static.errorPage)))
264 )
265 return yield* fail("Error page escapes the build output.");
266 const standaloneConfig =
267 props.layout === "next" &&
268 entry !== undefined &&
269 (yield* fs.readFileString(entry)).includes("__NEXT_PRIVATE_STANDALONE_CONFIG");
270 const files = new Set<string>(entry ? [entry] : []);
271 const seeds = new Set<string>(entry ? [entry] : []);
272 const manifests: string[] = [];
273 let visited = 0;
274 const collect: (
275 source: string,
276 boundary?: string,
277 ancestors?: ReadonlySet<string>,
278 runtimePackage?: boolean,
279 ) => Effect.Effect<void, WebsiteArtifactError | PlatformError> = Effect.fn(function* (
280 source,
281 boundary,
282 ancestors = new Set(),
283 runtimePackage = false,
284 ) {
285 if (++visited > MAX_ENTRIES)
286 return yield* fail("Website exceeds the 50,000-entry safety limit.");
287 const relative = path.relative(root, source).replaceAll("\\", "/");
288 if (
289 excluded(source) ||
290 sourceOnly(source) ||
291 (props.layout === "next" && nextExcluded(relative))
292 )
293 return;
294 const real = yield* fs.realPath(source);
295 if (excluded(real)) return yield* fail("An output symlink targets a sensitive file.");
296 if (!within(boundary ?? real, real))
297 return yield* fail("An output symlink escapes its selected directory.");
298 const stat = yield* fs.stat(real);
299 if (stat.type === "Directory") {
300 if (ancestors.has(real)) return yield* fail("Cyclic output symlink.");
301 const next = new Set([...ancestors, real]);
302 for (const name of (yield* fs.readDirectory(source)).sort()) {
303 if (name !== "node_modules")
304 yield* collect(path.join(source, name), boundary ?? real, next, runtimePackage);
305 }
306 } else if (stat.type === "File") {
307 files.add(source);
308 if (!runtimePackage && !props.static && javascript(source)) seeds.add(source);
309 if (props.layout === "next" && source.endsWith(".nft.json")) manifests.push(source);
310 } else return yield* fail("Website output contains a non-regular file.");
311 });
312 const extras = yield* packSiteExtraFiles(
313 props.layout === "next" ? root : dist,
314 props.layout === "next" ? "next" : "client",
315 );
316 if (props.layout === "next" && !(yield* fs.exists(path.join(root, ".next", "BUILD_ID"))))
317 return yield* fail("Next.js output is missing .next/BUILD_ID.");
318 for (const extra of extras ?? []) {
319 if (standaloneConfig && path.basename(extra.source).startsWith("next.config.")) continue;
320 yield* collect(extra.source);
321 }
322 let nextPackageRoot: string | undefined;
323 if (props.layout === "next") {
324 for (const name of ["next.config.mts", "next.config.cts"]) {
325 const config = path.join(root, name);
326 if (!standaloneConfig && (yield* fs.exists(config))) yield* collect(config);
327 }
328 const nextPackage = yield* Effect.try(() =>
329 createRequire(path.join(root, "package.json")).resolve("next/package.json"),
330 );
331 nextPackageRoot = path.dirname(nextPackage);
332 // Next's runtime alias tables are not statically evaluable by NFT.
333 yield* collect(nextPackageRoot, undefined, undefined, true);
334 }
335 for (const manifest of manifests) {
336 const text = yield* fs.readFileString(manifest);
337 const parsed = yield* Effect.try(() => JSON.parse(text) as { files?: unknown });
338 if (
339 !Array.isArray(parsed.files) ||
340 !parsed.files.every((file): file is string => typeof file === "string")
341 )
342 return yield* fail("Invalid Next.js dependency manifest.");
343 for (const file of parsed.files) {
344 const source = path.resolve(path.dirname(manifest), file);
345 if (excluded(source)) return yield* fail("A Next.js trace selects a sensitive file.");
346 if (sourceOnly(source)) continue;
347 files.add(source);
348 }
349 }
350 let workspace = root;
351 for (let candidate = root; ; candidate = path.dirname(candidate)) {
352 if (yield* fs.exists(path.join(candidate, "pnpm-workspace.yaml"))) {
353 workspace = candidate;
354 break;
355 }
356 if (candidate === path.dirname(candidate)) break;
357 }
358 const traceBase = path.parse(root).root;
359 const tracedFiles =
360 seeds.size === 0
361 ? []
362 : yield* traceWebsiteFiles({
363 seeds: [...seeds],
364 base: traceBase,
365 root,
366 next: props.layout === "next",
367 }).pipe(
368 Effect.timeout("60 seconds"),
369 Effect.mapError(
370 () =>
371 new WebsiteArtifactError({
372 message:
373 "Runtime tracing failed. Node 24 and @vercel/nft are required in the deployment workspace.",
374 }),
375 ),
376 );
377 for (const file of tracedFiles) if (!sourceOnly(file)) files.add(path.resolve(traceBase, file));
378 if (files.size > MAX_ENTRIES)
379 return yield* fail("Dependency trace exceeds the 50,000-entry limit.");
380 const selected = new Set<string>();
381 const links = new Map<string, string>();
382 const generated = new Map<string, Uint8Array>();
383 const replaced = new Set<string>();
384 const packageRoot = (file: string) => {
385 const parts = file.split(path.sep);
386 const index = parts.lastIndexOf("node_modules");
387 if (index < 0 || !parts[index + 1]) return undefined;
388 return parts.slice(0, index + (parts[index + 1]!.startsWith("@") ? 3 : 2)).join(path.sep);
389 };
390 const sharpRoots = new Set<string>();
391 for (const file of files) {
392 const real = yield* fs.realPath(file);
393 const pkg = packageRoot(real);
394 // Metadata-only trace entries do not load Sharp's native runtime.
395 if (pkg && path.basename(pkg) === "sharp" && javascript(real)) sharpRoots.add(pkg);
396 }
397 for (const sharpRoot of sharpRoots) {
398 if (!within(workspace, sharpRoot))
399 return yield* fail("Sharp escapes the application workspace.");
400 const installed = yield* fs.readFileString(path.join(sharpRoot, "package.json"));
401 const sharp = yield* Effect.try(() => JSON.parse(installed) as PackageManifest);
402 const packages = ["@img/sharp-linux-arm64", "@img/sharp-libvips-linux-arm64"];
403 for (const name of packages) {
404 const version = sharp.optionalDependencies?.[name];
405 if (!version || !exactVersion.test(version))
406 return yield* fail(
407 "This Sharp version does not declare exact Linux ARM64 prebuilt packages.",
408 );
409 const targetFiles = yield* platformPackage(name, version);
410 for (const [file, content] of targetFiles)
411 generated.set(path.join(path.dirname(sharpRoot), name, file), content);
412 }
413 // Only discard platform variants after their exact target replacements validated.
414 for (const name of Object.keys(sharp.optionalDependencies ?? {})) {
415 if (!name.startsWith("@img/sharp-")) continue;
416 const alias = path.join(path.dirname(sharpRoot), name);
417 replaced.add(alias);
418 if (yield* fs.exists(alias)) replaced.add(yield* fs.realPath(alias));
419 }
420 }
421 const isReplaced = (file: string) => [...replaced].some((pkg) => within(pkg, file));
422 for (const file of files) {
423 const real = yield* fs.realPath(file);
424 if (!within(workspace, file) || !within(workspace, real))
425 return yield* fail("A traced dependency escapes the application workspace.");
426 if (excluded(file) || excluded(real)) {
427 const sensitive = path
428 .relative(workspace, excluded(file) ? file : real)
429 .replaceAll("\\", "/")
430 .replace(/[^a-zA-Z0-9_./@+-]/g, "_");
431 return yield* fail(`A traced dependency selects a sensitive file: ${sensitive}`);
432 }
433 if (isReplaced(file) || isReplaced(real)) continue;
434 const stat = yield* fs.stat(real);
435 if (stat.type === "File") selected.add(real);
436 else if (stat.type !== "Directory" || file === real)
437 return yield* fail("A traced dependency is not a regular file.");
438 if (file !== real) links.set(file, real);
439 }
440 if (nextPackageRoot) links.set(path.join(root, "node_modules/next"), nextPackageRoot);
441 let base = root;
442 for (const file of [...selected, ...generated.keys(), ...links.keys(), ...links.values()])
443 while (!within(base, file)) base = path.dirname(base);
444 const directory = yield* fs.makeTempDirectoryScoped({
445 prefix: "alchemy-neon-website-",
446 });
447 const relative = (file: string) =>
448 path.join("files", path.relative(base, file)).replaceAll("\\", "/");
449 const staged = (file: string) => path.join(directory, relative(file));
450 let bytes = 0;
451 let entries = 0;
452 const copy = Effect.fn(function* (source: string, dest: string) {
453 if (yield* fs.exists(dest)) return;
454 const info = yield* fs.stat(source);
455 bytes += Number(info.size);
456 if (++entries > MAX_ENTRIES || bytes > MAX_BYTES)
457 return yield* fail("Materialized artifact exceeds its entry or expanded byte limit.");
458 const content = yield* fs.readFile(source);
459 yield* Effect.try({
460 try: () => validateBinary(path.relative(workspace, source), content),
461 catch: (error) =>
462 error instanceof WebsiteArtifactError
463 ? error
464 : new WebsiteArtifactError({ message: "Native validation failed." }),
465 });
466 if (native(source)) {
467 const pkg = packageRoot(source);
468 if (pkg && (yield* fs.exists(path.join(pkg, "package.json")))) {
469 const text = yield* fs.readFileString(path.join(pkg, "package.json"));
470 const manifest = yield* Effect.try(() => JSON.parse(text) as PackageManifest);
471 if (!compatible(manifest)) return yield* fail("Native package excludes Linux ARM64 glibc.");
472 }
473 }
474 yield* fs.makeDirectory(path.dirname(dest), { recursive: true });
475 yield* fs.writeFile(dest, content);
476 yield* fs.chmod(dest, info.mode & 0o777);
477 });
478 for (const [file, content] of generated) {
479 bytes += content.length;
480 if (++entries > MAX_ENTRIES || bytes > MAX_BYTES)
481 return yield* fail("Materialized artifact exceeds its entry or expanded byte limit.");
482 yield* fs.makeDirectory(path.dirname(staged(file)), { recursive: true });
483 yield* fs.writeFile(staged(file), content);
484 }
485 const sorted = [...selected].sort();
486 for (const file of sorted) yield* copy(file, staged(file));
487 // Workspace packages and npm aliases cannot self-resolve from a canonical node_modules name.
488 for (const [alias, target] of links) {
489 const parts = alias.split(path.sep);
490 const index = parts.lastIndexOf("node_modules");
491 const name = parts.slice(index + 1).join(path.sep);
492 if (index < 0 || target.endsWith(`${path.sep}node_modules${path.sep}${name}`)) continue;
493 if (selected.has(target)) yield* copy(target, staged(alias));
494 else
495 for (const file of sorted)
496 if (within(target, file))
497 yield* copy(file, path.join(staged(alias), path.relative(target, file)));
498 }
499 if (props.static) {
500 const { makeNeonServeEntrySource } = yield* loadFrontendCore;
501 let source = makeNeonServeEntrySource({
502 ...props.static,
503 clientDirExpression: `fileURLToPath(new URL(${JSON.stringify(`./${relative(dist)}/`)}, import.meta.url))`,
504 });
505 if (props.static.errorPage)
506 source = source.replace(
507 'lookup("/404.html")',
508 `lookup(${JSON.stringify(`/${props.static.errorPage}`)})`,
509 );
510 yield* fs.writeFileString(path.join(directory, "index.mjs"), source);
511 } else {
512 if (!entry) return yield* fail("Missing Fetch entrypoint.");
513 const aliases = [...links]
514 .map(([alias, target]) => [relative(alias), relative(target)])
515 .sort(([a], [b]) => b!.length - a!.length);
516 yield* fs.makeDirectory(staged(root), { recursive: true });
517 yield* fs.writeFileString(
518 path.join(directory, "index.mjs"),
519 [
520 'import { registerHooks, createRequire } from "node:module";',
521 'import { fileURLToPath } from "node:url";',
522 `const aliases = ${JSON.stringify(aliases)}.map(([from, to]) => [new URL(from, import.meta.url).href, new URL(to, import.meta.url).href]);`,
523 'const canonical = url => { for (const [from, to] of aliases) if (url === from || url.startsWith(from + "/")) return to + url.slice(from.length); return url; };',
524 "registerHooks({ resolve(specifier, context, next) {",
525 ' if (context.parentURL && !specifier.startsWith("node:") && !specifier.startsWith("#")) {',
526 ' if (specifier.startsWith(".") || specifier.startsWith("/") || specifier.startsWith("file:")) {',
527 " const url = new URL(specifier, context.parentURL).href; const mapped = canonical(url); if (mapped !== url) return next(mapped, context);",
528 ' } else if (!specifier.includes(":")) {',
529 ' const name = specifier.split("/").slice(0, specifier.startsWith("@") ? 2 : 1).join("/");',
530 ' if (aliases.some(([, target]) => target.endsWith("/node_modules/" + name) && context.parentURL.startsWith(target + "/"))) return next(specifier, context);',
531 ' for (let dir = new URL(".", context.parentURL); ; dir = new URL("..", dir)) {',
532 ' const candidate = new URL("node_modules/" + name, dir).href;',
533 " const target = aliases.find(([from]) => from === candidate)?.[1];",
534 ' if (target?.endsWith("/node_modules/" + name)) { if (context.parentURL.startsWith(target + "/")) return next(specifier, context); const parentURL = target + "/__alchemy_resolve__.mjs"; return context.conditions.includes("require") ? next(createRequire(parentURL).resolve(specifier), context) : next(specifier, { ...context, parentURL }); }',
535 ' if (new URL("..", dir).href === dir.href) break;',
536 " }",
537 " }",
538 " }",
539 " const result = next(specifier, context); return { ...result, url: canonical(result.url) };",
540 "} });",
541 `process.chdir(fileURLToPath(new URL(${JSON.stringify(`./${relative(root)}/`)}, import.meta.url)));`,
542 `const entry = await import(new URL(${JSON.stringify(`./${relative(entry)}`)}, import.meta.url).href);`,
543 "export default entry.default;",
544 "",
545 ].join("\n"),
546 );
547 }
548 return { directory };
549 });
550
551 /** Package a staging tree deterministically after all dependency changes. */
552 export const packageWebsiteArtifact = Effect.fn(function* (props: WebsiteArtifactProps) {
553 const fs = yield* FileSystem.FileSystem;
554 const path = yield* Path.Path;
555 const { directory } = yield* stageWebsiteArtifact(props);
556 const files: ZipFile[] = [];
557 const walk: (relative: string) => Effect.Effect<void, PlatformError> = Effect.fn(
558 function* (relative) {
559 for (const name of (yield* fs.readDirectory(path.join(directory, relative))).sort()) {
560 const file = path.join(relative, name);
561 const absolute = path.join(directory, file);
562 const stat = yield* fs.stat(absolute);
563 if (stat.type === "Directory") yield* walk(file);
564 else
565 files.push({
566 path: file.replaceAll("\\", "/"),
567 content: yield* fs.readFile(absolute),
568 mode: 0o100000 | (stat.mode & 0o777),
569 });
570 }
571 },
572 );
573 yield* walk("");
574 const archive = yield* zipFiles(files);
575 yield* validateFunctionZip(archive);
576 return { archive, hash: yield* sha256(archive) };
577 });
578
579 export const WebsiteArtifactProvider = () =>
580 Provider.effect(
581 WebsiteArtifact,
582 Effect.gen(function* () {
583 const fs = yield* FileSystem.FileSystem;
584 const path = yield* Path.Path;
585 return {
586 list: () => Effect.succeed([]),
587 diff: Effect.fn(function* ({ news, output }) {
588 if (!isResolved(news) || !output) return { action: "update" as const };
589 if (!(yield* fs.exists(output.artifactPath))) return { action: "update" as const };
590 if ((yield* sha256(yield* fs.readFile(output.artifactPath))) !== output.hash)
591 return { action: "update" as const };
592 // Dependencies outside the framework root can change without its build hash.
593 const { hash } = yield* packageWebsiteInChild(news).pipe(Effect.scoped);
594 return {
595 action: hash === output.hash ? ("noop" as const) : ("update" as const),
596 };
597 }),
598 reconcile: Effect.fn(function* ({ id, news }) {
599 const name = yield* createPhysicalName({ id, maxLength: 80 });
600 const directory = path.join(initialCwd, ".alchemy", "neon-websites", name);
601 const { archive, hash } = yield* packageWebsiteInChild(news).pipe(Effect.scoped);
602 yield* fs.makeDirectory(directory, { recursive: true });
603 const artifactPath = path.join(directory, `${hash}.zip`);
604 yield* fs.writeFile(artifactPath, archive);
605 for (const old of yield* fs.readDirectory(directory))
606 if (/^[a-f0-9]{64}\.zip$/.test(old) && old !== `${hash}.zip`)
607 yield* fs.remove(path.join(directory, old), { force: true });
608 return { directory, artifactPath, hash };
609 }),
610 delete: Effect.fn(function* ({ output }) {
611 yield* fs.remove(output.directory, { recursive: true, force: true });
612 }),
613 };
614 }),
615 );