1import path from "node:path";
2import type * as rolldown from "rolldown";
3
4const PACKAGE_NAME = "@alchemy.run/cloudflare-runtime";
5
6/**
7 * Keeps the Vite build's references to sibling runtime components external.
8 * Source code uses ordinary relative TypeScript imports, while published
9 * output must cross component boundaries through the package export map so
10 * consumers receive one shared copy of the runtime types.
11 */
12export const RuntimeSubpathExportPlugin = (): rolldown.Plugin => ({
13 name: "alchemy:runtime-subpath-exports",
14 resolveId(source, importer) {
15 if (importer === undefined || !source.startsWith(".")) {
16 return;
17 }
18
19 const normalizedImporter = importer.replaceAll("\\", "/");
20 const normalizedSource = source.replaceAll("\\", "/");
21 const absoluteImporter = /^[A-Za-z]:\//.test(normalizedImporter)
22 ? `/${normalizedImporter}`
23 : normalizedImporter;
24 const resolved = path.posix.resolve(
25 path.posix.dirname(absoluteImporter),
26 normalizedSource,
27 );
28 const match = resolved.match(/\/src\/(core|rolldown)\/(.+)\.ts$/);
29 if (match === null) {
30 return;
31 }
32
33 const [, component, modulePath] = match;
34 // Wire constants are internal and safe to inline in the Vite bundle.
35 if (component === "core" && modulePath === "globals/ProxyHeaders.shared") {
36 return;
37 }
38 const subpath =
39 modulePath === "index"
40 ? component
41 : `${component}/${modulePath.replace(/\.shared$/, "").replace(/\/index$/, "")}`;
42 return { id: `${PACKAGE_NAME}/${subpath}`, external: true };
43 },
44});