/** * Package discovery and the build-entry shims, shared by build.ts and sizes.ts. * * Every directory under packages/ with an index.ts(x) is a component: * build.ts bundles it to dist/.js and sizes.ts measures it. A package * may also ship packages//.css → dist/.css (the raw sheet, * for zero-JS pages). * * Build entries are shims generated into .build/, never the package's own * index: Bun elides the whole module graph when the entrypoint itself lives * inside a package (the entry collapses to a re-export facade; pebble's * scripts/invokers-entry.ts documents the bug — 3665 B vs 85 B). The shim is * an external importer, and the graph bundles correctly. * * A component package must not set "sideEffects": false: the import IS the * registration. build.ts refuses to build one that does. */ import { Glob } from "bun"; import { existsSync, mkdirSync } from "node:fs"; import { resolve } from "node:path"; export const ROOT = resolve(`${import.meta.dir}/..`); const BUILD_DIR = `${ROOT}/.build`; export interface Package { /** Directory name under packages/, and the dist basename: dist/.js. */ name: string; /** Absolute path of packages//index.ts(x). */ entry: string; /** Absolute path of packages//.css, when the package ships one. */ css?: string; } export async function discoverPackages(): Promise { const packages = new Map(); for (const pattern of ["packages/*/index.ts", "packages/*/index.tsx"]) { for (const path of new Glob(pattern).scanSync(ROOT)) { const name = path.split("/")[1]; if (packages.has(name)) continue; const meta = Bun.file(`${ROOT}/packages/${name}/package.json`); if (await meta.exists()) { const json = await meta.json(); if (json.sideEffects === false) { throw new Error( `packages/${name}/package.json sets "sideEffects": false — a component's import IS its registration; the flag lets bundlers drop it. Remove it.`, ); } } const css = `${ROOT}/packages/${name}/${name}.css`; packages.set(name, { name, entry: `${ROOT}/${path}`, ...(existsSync(css) ? { css } : {}) }); } } return [...packages.values()].sort((a, b) => a.name.localeCompare(b.name)); } /** * Writes the package's build entry to .build/.entry.ts and returns its * path. The shim is outside the package on purpose (see the header comment). */ export async function writeEntryShim(pkg: Package): Promise { mkdirSync(BUILD_DIR, { recursive: true }); const path = `${BUILD_DIR}/${pkg.name}.entry.ts`; await Bun.write( path, `// Generated by scripts/packages.ts — the build entry for packages/${pkg.name}. Do not edit.\n` + `import "../packages/${pkg.name}/index";\n` + `export * from "../packages/${pkg.name}/index";\n`, ); return path; }