// A page's browser client from its `client/.tsx` entry (the console's, the platform's), runtime-neutral (the // serve seam's helpers, docs/contributing/architecture.md#the-serve-seam): serve an adjacent `.bundle.js` // under either runtime, written at pack time by scripts/publish/build.mjs into dist/client/. Without one, Bun // builds the source at serve time and Node refuses it. Kept once per process; a failed attempt is retried on // the next call. Nothing here runs at module scope. import { existsSync, readFileSync } from 'node:fs'; /** A file URL's path on this machine, without `node:url` (the modules that call it ride into browser * bundles): percent-escapes decoded, and without the slash `URL.pathname` puts before a Windows drive * (`/C:/…`), which no file API opens. `new URL('../client/x.css', import.meta.url).pathname` is this. */ export function filePathOf(url: URL): string { const path = decodeURIComponent(url.pathname); return /^\/[A-Za-z]:\//.test(path) ? path.slice(1) : path; } const bundles = new Map>(); type BunBuild = { build: (o: { entrypoints: string[]; target: 'browser'; minify: boolean }) => Promise<{ success: boolean; logs: Array<{ message: string }>; outputs: Array<{ text: () => Promise }> }> }; /** A browser has no `process`. A client that imports shared helpers from its pack's server-side module can pull Node * code into its bundle (util.deprecate, crypto shims) that reads it; without a shim the page throws before it renders * (Bun adds none to a browser build). A minimal one, the page's own, before the bundle. */ const PROCESS_SHIM = 'globalThis.process=globalThis.process||{env:{NODE_ENV:"production"},browser:true,argv:[],versions:{},platform:"browser",emit:function(){return false},on:function(){},nextTick:function(f){var a=[].slice.call(arguments,1);queueMicrotask(function(){f.apply(null,a)})}};\n'; export function bundleClient(entry: string): Promise { let pending = bundles.get(entry); if (!pending) { pending = Promise.resolve().then(async () => { const prebuilt = entry.replace(/\.tsx?$/, '.bundle.js'); if (existsSync(prebuilt)) return PROCESS_SHIM + readFileSync(prebuilt, 'utf8'); const bun = (globalThis as { Bun?: Partial }).Bun; if (!bun || typeof bun.build !== 'function') throw new Error(`client bundle missing at ${prebuilt} — the package's \`build\` writes it (scripts/publish/build.mjs); Node serves the prebuilt client`); const result = await (bun as BunBuild).build({ entrypoints: [entry], target: 'browser', minify: true }); if (!result.success) throw new Error(result.logs.map((l) => l.message).join('\n') || `client build failed: ${entry}`); return PROCESS_SHIM + await result.outputs[0]!.text(); }) .catch((error) => { bundles.delete(entry); throw error; }); bundles.set(entry, pending); } return pending; }