/** * The two loaders that make an app's source runnable: `.tsx` → the server JSX factory, and * `.scss` → CSS plus a class-name map. Both are Bun runtime plugins, so `x dev`, `x build` and * `bun test` all load a component the same way and there is no separate "bundled" behaviour. */ import { renderThrowable } from '@ultimat3/core'; import { compileStylesheet, isGlobalStylesheet, stripCharset } from './css-modules'; import { PrerenderFailedError } from './errors'; import { comparablePath, isPathBelow, pathBelow } from './stylesheet-path'; import type { Surface } from './surfaces'; import { surfaceUnder } from './surfaces'; /** * Why a transform at all: Bun's own compile of a `.tsx` under the app's `tsconfig.json` (`jsx: * 'preserve'`, `jsxImportSource: 'solid-js'`) is wrong on every Bun. Through 1.4.2 it fell back to * the CLASSIC React factory — `React.createElement` against a global that does not exist. From * 1.4.3 it honours `jsxImportSource` and imports `jsxDEV` from `solid-js/jsx-dev-runtime`, which * solid-js maps to a module exporting no such name: a link-time `SyntaxError` (issue #883, * measured on 1.3.14 and 1.4.3). Solid ships no runtime factory because its JSX is a COMPILE-time * contract. `jsxImportSource` stays pointed at `solid-js` because that is where the JSX *type* * namespace lives (`class`, not `className`); the *runtime* factory is the framework's, every graph * that loads a `.tsx` installs this transform or the island one, and an app never configures one. */ const JSX_FACTORY = '__xh'; const JSX_FRAGMENT = '__xFragment'; const RENDER_PACKAGE = '@ultimat3/render'; /** * The specifier the prelude imports, resolved ONCE in the LOADER's frame — never the compiled * file's. It was the bare package name, resolved from the IMPORTING file, and the plugin is * process-wide the moment anything imports `@ultimat3/render/server`: so every `.tsx` compiled * somewhere the package is not installed above it — a `mkdtemp` fixture, a scaffolded app under * test, anything outside this repository — died at link time with `Cannot find module`. * * The loader's frame is also the only CORRECT one, which is what makes this a resolution and not a * workaround: the prelude names the factory whose nodes THIS package's renderer and brand checks * (`isJsxNode`, `isIslandNode`) read back, so it has to be this instance rather than whichever copy * happens to sit above the file being compiled. Measured: the resolved URL and the package name * answer the same module object in the workspace, so nothing that resolved before resolves twice. * * Why the emitted TEXT changes rather than the plugin, measured on Bun 1.4.0: a runtime * `Bun.plugin` ignores `onResolve` outright — the callback never fires, from module scope or from * a `--preload`, and a virtual namespace never resolves — and ignores `resolveDir` on an `onLoad` * result. Neither seam can carry the resolution, so the specifier must. Revisit if Bun wires * either: an `onResolve` hook would leave every compiled module byte-identical. Upstream: * https://github.com/oven-sh/bun/issues/40579. * * The fallback is the status quo, for the one frame that cannot answer: inside a * `bun build --compile` binary `import.meta.url` is `file:///$bunfs/root/` and * `import.meta.resolve` throws `Cannot find package`. There the prelude emits the bare name again * and resolves from the file — exactly what every build did before this constant existed. */ export const JSX_FACTORY_SPECIFIER = ((): string => { try { return import.meta.resolve(RENDER_PACKAGE); } catch { return RENDER_PACKAGE; } })(); /** No newline: the prelude shares line 1 with the file's own first line, so stack traces still point at it. */ const jsxPrelude = (factory: string): string => `import { h as ${JSX_FACTORY}, Fragment as ${JSX_FRAGMENT} } from ${JSON.stringify(factory)};`; const transpiler = new Bun.Transpiler({ loader: 'tsx', tsconfig: { compilerOptions: { jsx: 'react', jsxFactory: JSX_FACTORY, jsxFragmentFactory: JSX_FRAGMENT, }, } as never, }); export interface Stylesheet { /** Absolute path of the source file. */ readonly file: string; /** The surface that owns it, or `null` for a package stylesheet shared by both graphs. */ readonly surface: Surface | null; /** * A PACKAGE's sheet whose surface came from `claimStylesheets`, not from where the file sits. * It is carried by that one surface and still ordered with the library — see `stylesheetOrder`. */ readonly claimed: boolean; /** A plain (non-module) stylesheet: the tokens and the reset, which the cascade needs first. */ readonly global: boolean; /** * Registered only by an ISLAND build, never by the server's module graph — what `x build --target * docker` records in the island store. Not an ordering key: every sheet is ordered by * `stylesheetOrder`, whoever registered it. */ readonly island: boolean; readonly css: string; /** The partials this sheet's compilation read (`CompiledStylesheet.dependencies`). */ readonly dependencies: readonly string[]; } const stylesheets = new Map(); /** * Bumped whenever the registry's CONTENT changes — a sheet arriving, a sheet's rules changing, the * whole map being cleared. It exists so a caller can cache something derived from `stylesFor` (the * CLI content-addresses the surface stylesheet and serves it as a file) without re-deriving it per * request, and without a cache that goes stale the moment `x dev` rebuilds an island: island CSS * registers through this same `loadStylesheet`, on every `Bun.build`. * * A re-registration with IDENTICAL css does not bump it. `buildIslands` re-runs its plugins on * every watcher tick, so counting registrations rather than changes would mint a new stylesheet * URL on every save of an unrelated file — the immutable-cache miss this counter exists to avoid. */ let revision = 0; export function stylesheetsRevision(): number { return revision; } export function registeredStylesheets(): readonly Stylesheet[] { return [...stylesheets.values()]; } /** * The directory a sheet's surface is read below. Absent, the process's working directory — which * is the app root in the container (`WORKDIR /app`) and under every `x` command run from one. * Held as a `comparablePath`, like every claim: on Windows each arrives as `D:\app\…`. */ let stylesheetRoot: string | undefined; const rootOfSheets = (): string => stylesheetRoot ?? comparablePath(process.cwd()); /** * Directories a package claimed for ONE surface, longest first. A package's sheet has no surface * of its own and rides both graphs — right for a design system, and the reason an app's static * `site/` documents carried the admin's stylesheet for screens only `app/` serves (axiom 6). */ const claims: { readonly dir: string; readonly surface: Surface }[] = []; const claimedSurface = (path: string): Surface | undefined => { const comparable = comparablePath(path); return claims.find((claim) => isPathBelow(comparable, claim.dir))?.surface; }; const surfaceOfSheet = (path: string): Surface | null => claimedSurface(path) ?? surfaceUnder(rootOfSheets(), comparablePath(path)); /** Every registered sheet, classified again; the revision moves only when an answer does. */ const reclassify = (): void => { for (const [path, sheet] of stylesheets) { const surface = surfaceOfSheet(path); const claimed = claimedSurface(path) !== undefined; if (surface === sheet.surface && claimed === sheet.claimed) continue; stylesheets.set(path, { ...sheet, surface, claimed }); revision += 1; } }; /** * A package says its own stylesheets belong to one surface: every sheet below `dir` is carried by * documents of `surface` and by no other. Called by the package that OWNS the directory, with its * own `import.meta.dir` — a sheet loads when its module is linked, which is before the claiming * module's body runs, so a claim re-classifies what is already registered. * * A claim is a fact about a package's source, made once per process: `clearStylesheets()` leaves * it standing, because the module that made it is cached and will not make it again. */ export function claimStylesheets(dir: string, surface: Surface): void { const claimed = comparablePath(dir); if (claims.some((claim) => claim.dir === claimed && claim.surface === surface)) return; claims.push({ dir: claimed, surface }); claims.sort((a, b) => b.dir.length - a.dir.length); reclassify(); } /** * Names the app root the registry classifies against; `loadApp` calls it before importing a module. * Every sheet already registered is classified again, because a sheet can load before the root is * named — and a classification frozen then would keep the answer the wrong root gave. The revision * moves only when an answer does, so naming the same root twice mints no new stylesheet URL. * A relative root is resolved against the working directory. `undefined` returns to the working * directory. */ export function setStylesheetRoot(root: string | undefined): void { // Resolved: `loadApp('.')` is a legal call, and `.` is a prefix of no absolute path. stylesheetRoot = root === undefined ? undefined : comparablePath(root); reclassify(); } /** Test seam: the registry is process-global because the module cache it mirrors is too. */ export function clearStylesheets(): void { if (stylesheets.size > 0) revision += 1; stylesheets.clear(); } /** * The CSS a document on `surface` must carry. A `site/` page never receives `app/` CSS — that is * axiom 6 applied to bytes the browser parses, not just bytes it executes. * * `shared/` is carried by both graphs by definition — it is the one directory both surfaces import * from, and it is where an app's own global stylesheet lives. Filtering it out (which this did) * meant an app could put its tokens in the one place the convention names and have every document * silently drop them. * * THE ORDER IS A FUNCTION OF THE SHEETS, NEVER OF THEIR ARRIVAL (22.3.5). A sheet registers in Bun's * `onLoad`, which runs as the loader fetches a module's dependencies — in parallel — and an island * build's too: the arrival order differed on every boot of one image, and so did the joined bytes * and the `/styles/.css` minted from them (one adopter, 22.3.2–22.3.4: two pods, two URLs, * each the other's 404). `stylesheetOrder` is the whole rule: * * | key | first | why | * |---|---|---| * | global | the global layer | the reset styles bare elements at the lowest specificity there is, so a reset after a module rule wins ties it must lose | * | owner | a package's sheet, then `shared/`, then the surface's own | library before app: an app's rule wins a tie against the component it restyles | * | path | app-root-relative, by code unit | a total order; the same on every machine | */ export function stylesFor(surface: Surface | null): string { const carried = [...stylesheets.values()].filter( (sheet) => sheet.surface === null || sheet.surface === 'shared' || sheet.surface === surface, ); // `stripCharset` on every sheet, not only the first: a `@charset` or a BOM is legal at byte 0 of // a FILE and nowhere else, and this join is what turns seven files into one. return carried .sort(stylesheetOrder) .map((sheet) => stripCharset(sheet.css)) .join(''); } const OWNER_RANK = (sheet: Stylesheet): number => // A claimed sheet is a package's whichever surface carries it: library first. sheet.surface === null || sheet.claimed ? 0 : sheet.surface === 'shared' ? 1 : 2; /** * Relative to the app root and `/`-separated, so a container at `/app`, a laptop and a Windows * checkout at `D:\app` order one app alike — and so mint one stylesheet hash. */ const orderPath = (sheet: Stylesheet): string => pathBelow(comparablePath(sheet.file), rootOfSheets()); /** See `stylesFor`: global layer, then owner, then path. Exported for the tests that pin it. */ export function stylesheetOrder(a: Stylesheet, b: Stylesheet): number { if (a.global !== b.global) return a.global ? -1 : 1; const owner = OWNER_RANK(a) - OWNER_RANK(b); if (owner !== 0) return owner; const [x, y] = [orderPath(a), orderPath(b)]; return x < y ? -1 : x > y ? 1 : 0; } /** * `.tsx` source → JS calling the server factory. Exported so the transform is testable as a pure * function: the plugin below is the six lines of glue that hand it a file. * * `factory` is the specifier the prelude imports `h` from: the runtime loader's resolved URL by * default, and the PATH that URL names for a bundler (`tsx-build-plugin.ts` says why). */ export function transformTsx(source: string, factory: string = JSX_FACTORY_SPECIFIER): string { // No newline between: the prelude shares line 1 with the file's own first line, so every stack // trace and every reported error still points at the line the author wrote. return jsxPrelude(factory) + transpiler.transformSync(source); } /** * `.scss` source → the module body an `import styles from …` receives, registering the CSS. * * Keyed by absolute path, which is what makes the global layer emit ONCE however many app modules * import it. Sass dedupes `@use` within a single compilation, and every file here is its own * compilation — so a token file `@use`d by twenty `page.module.scss` would inline its `:root` block * twenty times. One file, imported for its side effect, is the shape that cannot do that. */ export function loadStylesheet( path: string, source: string, origin: 'module' | 'island' = 'module', ): string { const compiled = compileStylesheet(path, source); // An EMPTY compile unregisters: under `x dev` an edit that deleted every rule left the old entry // in place, serving rules the file no longer had until the process restarted. if (compiled.css.length === 0 && stylesheets.delete(path)) revision += 1; if (compiled.css.length > 0) { const held = stylesheets.get(path); // Island-only until the server graph loads it too; then it takes its place in load order. const island = origin === 'island' && (held === undefined || held.island); if (held?.css !== compiled.css || held.island !== island) revision += 1; if (held?.island === true && !island) stylesheets.delete(path); stylesheets.set(path, { file: path, surface: surfaceOfSheet(path), claimed: claimedSurface(path) !== undefined, global: isGlobalStylesheet(path), island, css: compiled.css, dependencies: compiled.dependencies, }); } return `export default ${JSON.stringify(compiled.classes)};`; } let installed = false; /** * Idempotent: importing `@ultimat3/render` from anywhere installs it once, which is the only * placement that covers `x dev`, `x build`, the production `server.ts` and `bun test` without each * of them remembering to. A plugin only affects modules loaded AFTER it, and every route module is. */ /** `/a/page.tsx?x-reload=3` → `/a/page.tsx`: the file on disk, which is what the hook reads. */ const withoutQuery = (path: string): string => path.replace(/\?[^/]*$/, ''); export function installRenderLoader(): void { if (installed) return; installed = true; Bun.plugin({ name: 'ultimate-render', setup(build): void { // The query is admitted and then stripped. `x dev` re-imports an edited route module as // `?x-reload=` — the only cache key Bun honours — and Bun hands this hook the // specifier QUERY INCLUDED. Anchored on `.tsx$` the filter let that import fall through to // Bun's own loader, which compiles JSX to `React.createElement`: every reloaded page then // died on its first render with `__xh is not defined`. build.onLoad({ filter: /\.tsx(?:\?[^/]*)?$/ }, async ({ path }) => ({ contents: transformTsx(await Bun.file(withoutQuery(path)).text()), loader: 'js', })); build.onLoad({ filter: /\.(?:s?css)$/ }, async ({ path }) => { const source = await Bun.file(path).text(); try { return { contents: loadStylesheet(path, source), loader: 'js' }; } catch (error) { if (error instanceof PrerenderFailedError) throw error; throw new PrerenderFailedError( // `renderThrowable` from core, never `.message`/`String()`: this catch is the loader's // last frame, and a value that fights being read would replace the coded failure with // a bare throw out of a Bun plugin — where no route and no file name survives. `${path} could not be loaded: ${renderThrowable(error)}`, `open ${path} and fix the stylesheet it @use-s`, ); } }); }, }); }