/** * Post-pass over Bun's output. * * Bun's `minify` does whitespace, identifiers and syntax, but cannot mangle * property names. Terser can, which is worth ~6% gzipped, but only internal * names may be renamed: anything read off a user-supplied object (`props`, * `styles`, `shadow`, `scoped`, `reflect`, `type`, `equals`, …) must survive. * * So the mangle list is closed and explicit: * - `_$`-prefixed names, our own internals (Lit's convention), * - alien-signals' reactive-graph fields, which never appear in user data. * * One class is barred from the `_$` convention: properties of `Symbol.for` * singleton records (pebble's invokers/fetch registries; a component's * once-only install record, if it keeps one). Those records are created by * whichever bundle loads first and read by every other copy of the module, so * their names cross build boundaries; mangling is per-build, and two bundles * built separately from source could mangle them differently and silently * fail to share the singleton. They stay unprefixed. */ import { minify } from "terser"; /** alien-signals graph internals (see node_modules/alien-signals/esm/index.mjs). */ const ALIEN_INTERNALS = [ "depsTail", "nextSub", "nextDep", "prevDep", "subsTail", "pendingValue", "currentValue", "getter", "flags", "deps", "subs", "dep", "sub", "prevSub", "cleanup", "version", ]; export const MANGLE_PROPERTIES = new RegExp(`^(_\\$|${ALIEN_INTERNALS.join("$|")}$)`); export async function shrink(code: string): Promise { const result = await minify(code, { module: true, compress: { passes: 3 }, format: { comments: false }, // `builtins: true` lets the whitelist reach names that are also JS builtins // (`flags` appears 35× in our bundle but is skipped otherwise, because of // RegExp.prototype.flags). Safe only because the regex is a closed list. mangle: { properties: { regex: MANGLE_PROPERTIES, builtins: true } }, }); if (!result.code) throw new Error("terser produced no output"); return result.code; } /** `shrink` that also re-chains an existing source map onto the output. */ export async function shrinkWithMap( code: string, previousMap?: string, filename?: string, ): Promise<{ code: string; map?: string }> { const result = await minify(code, { module: true, compress: { passes: 3 }, format: { comments: false }, mangle: { properties: { regex: MANGLE_PROPERTIES, builtins: true } }, sourceMap: previousMap ? { content: previousMap, url: filename } : undefined, }); if (!result.code) throw new Error("terser produced no output"); return { code: result.code, map: typeof result.map === "string" ? result.map : undefined }; }