// bankai build — the production build. Only the CLIENT is bundled: the // server side of a choo v8 app is plain ESM that Node runs as-authored, // so there is no server build to rot. Outputs: // dist/assets/* hashed client chunks + css // dist/.vite/manifest.json Vite's build manifest // dist/bankai.json bankai's route/asset metadata for serving // dist/**/index.html prerendered routes (--prerender) // dist/sw.js service worker (if /sw.js exists), // with the precached asset list defined in // *.br / *.gz precompressed siblings for every text asset import { readFile, writeFile, readdir, stat, access, mkdir } from 'node:fs/promises' import { join, dirname, resolve } from 'node:path' import { pathToFileURL } from 'node:url' import { brotliCompress, gzip, constants } from 'node:zlib' import { promisify } from 'node:util' import bankaiPlugin, { findCss, CLIENT_ID } from './plugin.js' import { resolveApp } from './app.js' import { documentHead, documentTail } from './document.js' const brotli = promisify(brotliCompress) const gzipP = promisify(gzip) export default async function buildApp ({ entry, outDir = 'dist', title = 'choo', prerender = [] }) { const { build } = await import('vite') entry = resolve(entry) outDir = resolve(outDir) const css = await findCss(entry) await build({ appType: 'custom', plugins: [bankaiPlugin(entry, { css })], logLevel: 'warn', // real-world stylesheets (tachyons et al) carry IE-era hacks like // *zoom; strip them instead of refusing to build css: { lightningcss: { errorRecovery: true } }, build: { outDir, emptyOutDir: true, manifest: true, rollupOptions: { input: { main: CLIENT_ID } } } }) // derive the route-independent asset set from Vite's manifest const manifest = JSON.parse(await readFile(join(outDir, '.vite', 'manifest.json'), 'utf8')) const entryChunk = Object.values(manifest).find((m) => m.isEntry) const modulepreload = (entryChunk.imports || []).map((key) => '/' + manifest[key].file) const assets = { scripts: ['/' + entryChunk.file], modulepreload, css: collectCss(manifest, entryChunk) } const meta = { title, entry, assets, builtAt: new Date().toISOString() } await writeFile(join(outDir, 'bankai.json'), JSON.stringify(meta, null, 2)) // static prerender: routes rendered through the same toStream path the // server uses, written as /index.html const prerendered = [] if (prerender.length) { const mod = await import(pathToFileURL(entry)) for (const route of prerender) { const app = resolveApp(mod, entry) const state = {} let body = '' const decoder = new TextDecoder() for await (const chunk of app.toStream(route, state)) { body += decoder.decode(chunk, { stream: true }) } const page = documentHead({ title: state.title || title, ...assets }) + body + documentTail(state) const rel = route === '/' ? 'index.html' : join(route.replace(/^\//, '').replace(/\/$/, ''), 'index.html') const target = join(outDir, rel) await mkdir(dirname(target), { recursive: true }) await writeFile(target, page) prerendered.push(route) } } // service worker: /sw.js, built standalone with the asset // list injected — the choo-service-worker convention, manifest edition const swSource = join(dirname(entry), 'sw.js') if (await exists(swSource)) { const precache = [ ...(prerendered.length ? prerendered : ['/']), ...assets.scripts, ...assets.modulepreload, ...assets.css ] await build({ appType: 'custom', logLevel: 'warn', define: { __BANKAI_ASSETS__: JSON.stringify(precache) }, build: { outDir, emptyOutDir: false, rollupOptions: { input: { sw: swSource }, output: { entryFileNames: 'sw.js' } } } }) } // precompress text assets so the server never compresses at request time const compressed = await precompress(outDir) return { outDir, meta, compressed, prerendered } } function collectCss (manifest, entryChunk) { const css = new Set(entryChunk.css || []) for (const key of entryChunk.imports || []) { for (const file of manifest[key].css || []) css.add(file) } return [...css].map((file) => '/' + file) } const COMPRESSIBLE = /\.(js|mjs|css|html|json|svg|txt|map)$/ async function precompress (dir) { let count = 0 for (const name of await readdir(dir)) { const path = join(dir, name) const info = await stat(path) if (info.isDirectory()) { count += await precompress(path) continue } if (!COMPRESSIBLE.test(name) || info.size < 1024) continue const data = await readFile(path) await writeFile(path + '.br', await brotli(data, { params: { [constants.BROTLI_PARAM_QUALITY]: constants.BROTLI_MAX_QUALITY } })) await writeFile(path + '.gz', await gzipP(data, { level: constants.Z_BEST_COMPRESSION })) count++ } return count } async function exists (path) { try { await access(path) return true } catch (e) { return false } }