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

main
ts 193 lines 7.28 KB
Raw
1 import { createHash } from "node:crypto";
2 import path from "node:path";
3 import MagicString from "magic-string";
4 import type {
5 Plugin,
6 PluginContext,
7 RenderedChunk,
8 RolldownMagicString,
9 SourceMap,
10 } from "rolldown";
11 import { createPlugin } from "../factory.ts";
12 import { sanitizePath, toPosixPath } from "../utils.ts";
13
14 export const MODULE_RULES = [
15 { type: "CompiledWasm", pattern: /\.wasm(\?module)?$/ },
16 { type: "Data", pattern: /\.bin$/ },
17 { type: "Text", pattern: /\.(txt|html|sql)$/ },
18 ] as const;
19
20 const MODULE_REFERENCE_PATTERN = `__CLOUDFLARE_MODULE__(${MODULE_RULES.map((rule) => rule.type).join("|")})__(.*?)__CLOUDFLARE_MODULE__`;
21 export const MODULE_REFERENCE_REGEX = new RegExp(MODULE_REFERENCE_PATTERN);
22 const MODULE_REFERENCE_GLOBAL_REGEX = new RegExp(MODULE_REFERENCE_PATTERN, "g");
23
24 export const additionalModulesPlugin = createPlugin("additional-modules", (options) => {
25 const additionalModulePaths = new Set<string>();
26 // The first module type ever emitted per content hash. Never cleared, so
27 // outputs rendering in parallel (Vite environments) agree on which type
28 // rolldown may name and merge; every other type gets an explicit name.
29 const emittedTypes = new Map<string, ModuleType>();
30 const userRules = options.moduleRules ?? [];
31 // Subpath imports (`#html`) resolve to a module type only once resolved,
32 // as in `@cloudflare/vite-plugin`.
33 const builtinFilter = [...MODULE_RULES.map((rule) => rule.pattern), /^#/];
34 // Built-in rules see the same imports as without user rules. User rules
35 // only claim plain imported files: entries, externals, virtual ids and
36 // query imports (`?init`, `?raw`, ...) belong to other plugins.
37 const matchType = (
38 source: string,
39 resolved: { id: string; external?: boolean | string },
40 importer: string | undefined,
41 ) => {
42 const userRule =
43 importer && !resolved.external && isPlainFile(resolved.id)
44 ? userRules.find((rule) => rule.test(sanitizePath(resolved.id)))
45 : undefined;
46 if (userRule) {
47 return userRule.type ?? uploadedType(resolved.id) ?? "Data";
48 }
49 return builtinFilter.some((pattern) => pattern.test(source))
50 ? MODULE_RULES.find((rule) => rule.pattern.test(resolved.id))?.type
51 : undefined;
52 };
53 return {
54 vite: {
55 enforce: "pre",
56 hotUpdate(options) {
57 if (additionalModulePaths.has(options.file)) {
58 void options.server.restart();
59 return [];
60 }
61 },
62 },
63 shared: {
64 resolveId: {
65 // User rules match the resolved path, so they can't narrow the filter.
66 filter: userRules.length ? { id: { exclude: /^\0/ } } : { id: builtinFilter },
67 async handler(source, importer, options) {
68 const resolved = await this.resolve(source, importer, options);
69 if (!resolved) {
70 return;
71 }
72
73 const type = matchType(source, resolved, importer);
74 if (!type) {
75 return resolved;
76 }
77
78 const filePath = sanitizePath(resolved.id);
79 additionalModulePaths.add(filePath);
80
81 return {
82 id: moduleReferenceId(type, filePath),
83 external: true,
84 };
85 },
86 },
87 renderChunk: {
88 filter: { code: { include: MODULE_REFERENCE_REGEX } },
89 handler: withMagicString(async function (code, chunk, magicString) {
90 const matches = code.matchAll(MODULE_REFERENCE_GLOBAL_REGEX);
91 for (const match of matches) {
92 const [full, type, id] = match as unknown as [string, ModuleType, string];
93 const source = await this.fs.readFile(id);
94 const name = moduleFileName(type, path.basename(id));
95 // Rolldown merges assets with identical bytes, which would give a
96 // Data import the Text module of another file. Only then is the
97 // name explicit, keyed by type and content; otherwise rolldown
98 // names the asset (`assetFileNames`, collisions).
99 const content = createHash("sha256").update(source).digest("hex");
100 const firstType = emittedTypes.get(content) ?? type;
101 emittedTypes.set(content, firstType);
102 const referenceId = this.emitFile(
103 firstType === type
104 ? { type: "asset", name, source }
105 : {
106 type: "asset",
107 fileName: uniqueFileName(name, type, content),
108 source,
109 },
110 );
111 const fileName = this.getFileName(referenceId);
112 const relativePath = toPosixPath(path.relative(path.dirname(chunk.fileName), fileName));
113 const importPath = relativePath.startsWith(".") ? relativePath : `./${relativePath}`;
114 magicString.update(match.index, match.index + full.length, importPath);
115 }
116 }),
117 },
118 },
119 };
120 });
121
122 type ModuleType = (typeof MODULE_RULES)[number]["type"];
123
124 /** The module type the uploader infers from a file name, as Wrangler does. */
125 function typeFromExtension(name: string): ModuleType | undefined {
126 return MODULE_RULES.find((rule) => rule.pattern.test(name))?.type;
127 }
128
129 /**
130 * The module type uploads give a file name: the built-in rules' types, Text
131 * for `.custom`, nothing for code and source maps, and Data otherwise.
132 */
133 function uploadedType(name: string): ModuleType | undefined {
134 if (/\.([cm]?js|py|map)$/.test(name)) return undefined;
135 if (name.endsWith(".custom")) return "Text";
136 return typeFromExtension(name) ?? "Data";
137 }
138
139 /**
140 * Uploads infer a module's type from its extension, so a file whose rule
141 * picks another type gets that type's extension.
142 */
143 function moduleFileName(type: ModuleType, name: string) {
144 if (uploadedType(name) === type) return name;
145 return `${name}${type === "Text" ? ".txt" : type === "Data" ? ".bin" : ".wasm"}`;
146 }
147
148 function uniqueFileName(name: string, type: ModuleType, content: string) {
149 const ext = path.extname(name);
150 const hash = createHash("sha256").update(type).update(content).digest("hex").slice(0, 8);
151 return `assets/${name.slice(0, name.length - ext.length)}-${hash}${ext}`;
152 }
153
154 function isPlainFile(id: string) {
155 return path.isAbsolute(id) && !/[?#]/.test(id.replace(/\?module$/, ""));
156 }
157
158 function moduleReferenceId(type: ModuleType, id: string) {
159 return `__CLOUDFLARE_MODULE__${type}__${id}__CLOUDFLARE_MODULE__` as const;
160 }
161
162 type PluginHandler<T extends keyof Plugin> = Plugin[T] extends infer T
163 ? T extends (...args: any) => any
164 ? T
165 : never
166 : never;
167
168 /**
169 * Returns a `renderChunk` handler that transforms the chunk using a magic string.
170 * Uses Rolldown's native magic string if available, or the `magic-string` library otherwise.
171 */
172 function withMagicString(
173 renderChunk: (
174 this: PluginContext,
175 code: string,
176 chunk: RenderedChunk,
177 magicString: MagicString | RolldownMagicString,
178 ) => Promise<void>,
179 ): PluginHandler<"renderChunk"> {
180 return async function (code, chunk, outputOptions, meta) {
181 const magicString = meta.magicString ?? new MagicString(code);
182 await renderChunk.call(this, code, chunk, magicString);
183 if ("isRolldownMagicString" in magicString && magicString.isRolldownMagicString) {
184 return magicString;
185 }
186 return {
187 code: magicString.toString(),
188 map: outputOptions.sourcemap
189 ? (magicString.generateMap({ hires: "boundary" }) as SourceMap)
190 : null,
191 };
192 };
193 }