feat(bankai): bankai v10 — the isomorphic compiler & server on Vite 8

One command, zero config, and only the client ever bundles: v8 server
code is plain ESM that Node runs as-authored, so there is no server
build to rot (the lesson of v9).

- start: Vite middleware mode + HMR with per-request streaming SSR via
  ssrLoadModule; a virtual client entry generates the browser glue so
  the user writes exactly one isomorphic module (plan decision D5).
- build: client bundle via Vite 8/Rolldown, manifest-derived route
  assets in dist/bankai.json, service worker built with the precache
  list injected (choo-service-worker convention, manifest edition),
  brotli+gzip precompression of every text asset.
- serve: immutable caching + precompressed negotiation for hashed
  assets, 103 Early Hints (res.writeEarlyHints) with the route's assets
  before every page, streaming SSR, and a window.initialState tail with
  script-breakout-safe serialization and choo internals filtered out.
- inspect: raw/gzip/brotli size report.

Integration tests drive the real counter example through build and
serve, asserting the 103 interim response at the HTTP level.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014NgfSjHE11oFpoSnLVKLXd
This commit is contained in:
Bendik Aagaard Lynghaug
2026-09-08 19:32:37 +02:00
co-authored by Claude Fable 5
parent d755af5ca0
commit 7e08b585ac
13 changed files with 716 additions and 1 deletions
+23
View File
@@ -0,0 +1,23 @@
// The isomorphic entry contract (plan decision D5): the entry module's
// default export is either a choo app instance (typically
// `export default app.mount('body')` — mount() on the server records the
// selector and returns the app) or a factory returning one (preferred:
// fresh state per request). One module, three consumers: browser mount,
// server render, build metadata.
export function resolveApp (mod, entry) {
const value = mod && mod.default
if (!value) {
throw new Error(`bankai: ${entry} has no default export — export your choo app (or a function returning one)`)
}
// a factory is a plain function; an app instance has .mount
const app = typeof value === 'function' && !value.mount ? value() : value
if (typeof app.toStream !== 'function') {
throw new Error(`bankai: the default export of ${entry} is not a choo v8 app (missing toStream)`)
}
return app
}
export function selectorOf (app) {
return app.selector || 'body'
}
+114
View File
@@ -0,0 +1,114 @@
// 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/sw.js service worker (if <entry dir>/sw.js exists),
// with the precached asset list defined in
// *.br / *.gz precompressed siblings for every text asset
import { readFile, writeFile, readdir, stat, access } from 'node:fs/promises'
import { join, dirname, resolve } from 'node:path'
import { brotliCompress, gzip, constants } from 'node:zlib'
import { promisify } from 'node:util'
import bankaiPlugin, { CLIENT_ID } from './plugin.js'
const brotli = promisify(brotliCompress)
const gzipP = promisify(gzip)
export default async function buildApp ({ entry, outDir = 'dist', title = 'choo' }) {
const { build } = await import('vite')
entry = resolve(entry)
outDir = resolve(outDir)
await build({
appType: 'custom',
plugins: [bankaiPlugin(entry)],
logLevel: 'warn',
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))
// service worker: <entry dir>/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 = ['/', ...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 }
}
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
}
}
+59
View File
@@ -0,0 +1,59 @@
// bankai start — the dev server: Vite middleware mode for the module
// graph and HMR, per-request streaming SSR of the same entry through
// vite.ssrLoadModule so server code shares Vite's transforms and cache.
import { createServer } from 'node:http'
import bankaiPlugin, { CLIENT_URL } from './plugin.js'
import { resolveApp } from './app.js'
import { documentHead, documentTail } from './document.js'
export default async function dev ({ entry, port = 8080, title = 'choo' }) {
const { createServer: createViteServer } = await import('vite')
const vite = await createViteServer({
appType: 'custom',
server: { middlewareMode: true },
plugins: [bankaiPlugin(entry)],
logLevel: 'warn'
})
const server = createServer((req, res) => {
vite.middlewares(req, res, async () => {
// not an asset Vite knows: this is a page navigation — SSR it
try {
const mod = await vite.ssrLoadModule(entry)
const app = resolveApp(mod, entry)
const state = {}
res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' })
res.write(documentHead({
title,
scripts: ['/@vite/client', CLIENT_URL]
}))
for await (const chunk of app.toStream(req.url, state)) {
res.write(chunk)
}
res.end(documentTail(state))
} catch (err) {
vite.ssrFixStacktrace(err)
console.error(err)
if (!res.headersSent) res.writeHead(500, { 'content-type': 'text/plain' })
res.end('bankai dev error:\n\n' + (err.stack || err.message))
}
})
})
await new Promise((resolve) => server.listen(port, resolve))
return {
server,
vite,
port: server.address().port,
origin: `http://localhost:${server.address().port}`,
close: async () => {
await vite.close()
await new Promise((resolve) => server.close(resolve))
}
}
}
+55
View File
@@ -0,0 +1,55 @@
// The HTML document around the app's streamed body. bankai owns the
// <head> (charset, viewport, title, asset links) and the tail
// (window.initialState + </html>); the app's view owns <body>.
// Page scripts live in <head> (type=module defers itself); the one
// exception is the initialState script, which must be inline and is
// emitted after the body — inline scripts execute during parse, module
// scripts only after it, so the order still holds.
export function documentHead ({ title, css = [], modulepreload = [], scripts = [] }) {
let head = '<!doctype html>\n<html lang="en">\n<head>\n<meta charset="utf-8">\n<meta name="viewport" content="width=device-width, initial-scale=1">\n'
if (title) head += `<title>${escapeHtml(title)}</title>\n`
for (const href of css) {
head += `<link rel="stylesheet" href="${escapeHtml(href)}">\n`
}
for (const href of modulepreload) {
head += `<link rel="modulepreload" href="${escapeHtml(href)}">\n`
}
for (const src of scripts) {
head += `<script type="module" src="${escapeHtml(src)}"></script>\n`
}
head += '</head>\n'
return head
}
export function documentTail (state) {
return `\n<script>window.initialState=${serializeState(state)}</script>\n</html>\n`
}
// choo internals that every boot recomputes \u2014 no point shipping them
const RECOMPUTED = new Set(['events', 'cache', 'prefetch'])
// JSON that is safe to embed in an inline <script>: no '</script>' or
// '<!--' breakouts, no raw line separators
export function serializeState (state) {
return JSON.stringify(state, function (key, value) {
if (this === state && RECOMPUTED.has(key)) return undefined
return value
})
.replace(/</g, '\\u003c')
.replace(/\u2028/g, '\\u2028')
.replace(/\u2029/g, '\\u2029')
}
// Early Hints / Link header values for a route's assets
export function assetLinks ({ css = [], modulepreload = [], scripts = [] }) {
const links = []
for (const href of scripts) links.push(`<${href}>; rel=modulepreload`)
for (const href of modulepreload) links.push(`<${href}>; rel=modulepreload`)
for (const href of css) links.push(`<${href}>; rel=preload; as=style`)
return links
}
function escapeHtml (str) {
return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;')
}
+56
View File
@@ -0,0 +1,56 @@
// bankai inspect — what did the build produce, and how big is it on the
// wire? Reads the manifest + dist and prints raw/gzip/brotli sizes.
import { readFile, readdir, stat } from 'node:fs/promises'
import { join, resolve, relative } from 'node:path'
export default async function inspect ({ outDir = 'dist' }) {
outDir = resolve(outDir)
const meta = JSON.parse(await readFile(join(outDir, 'bankai.json'), 'utf8'))
const rows = []
await walk(outDir, rows, outDir)
rows.sort((a, b) => b.raw - a.raw)
console.log(`\nbankai build — ${meta.title} (${meta.builtAt})\n`)
console.log(' ' + 'file'.padEnd(44) + 'raw'.padStart(10) + 'gzip'.padStart(10) + 'brotli'.padStart(10))
let totals = { raw: 0, gz: 0, br: 0 }
for (const row of rows) {
totals.raw += row.raw
totals.gz += row.gz || 0
totals.br += row.br || 0
console.log(' ' + row.file.padEnd(44) + kb(row.raw) + kb(row.gz) + kb(row.br))
}
console.log(' ' + 'total'.padEnd(44) + kb(totals.raw) + kb(totals.gz) + kb(totals.br) + '\n')
return rows
}
async function walk (dir, rows, root) {
for (const name of await readdir(dir)) {
if (name === '.vite') continue
const path = join(dir, name)
const info = await stat(path)
if (info.isDirectory()) {
await walk(path, rows, root)
continue
}
if (name.endsWith('.br') || name.endsWith('.gz')) continue
const row = { file: relative(root, path), raw: info.size, gz: null, br: null }
row.gz = await sizeOf(path + '.gz')
row.br = await sizeOf(path + '.br')
rows.push(row)
}
}
async function sizeOf (path) {
try {
return (await stat(path)).size
} catch (e) {
return null
}
}
function kb (bytes) {
if (bytes === null) return '—'.padStart(10)
return (bytes < 1024 ? bytes + ' B' : (bytes / 1024).toFixed(1) + ' kB').padStart(10)
}
+28
View File
@@ -0,0 +1,28 @@
// Vite plugin: a virtual client entry that mounts the user's app. The
// user writes one isomorphic module; bankai generates the two lines of
// browser glue instead of asking for a second file.
export const CLIENT_ID = 'bankai:client'
const RESOLVED_CLIENT_ID = '\0' + CLIENT_ID
// the URL a browser uses to import the virtual module through Vite's dev
// middleware ('\0' encodes as '__x00__')
export const CLIENT_URL = '/@id/__x00__' + CLIENT_ID
export default function bankaiPlugin (entry) {
return {
name: 'bankai',
resolveId (id) {
if (id === CLIENT_ID) return RESOLVED_CLIENT_ID
},
load (id) {
if (id === RESOLVED_CLIENT_ID) {
return [
`import create from ${JSON.stringify(entry)}`,
'const app = typeof create === "function" && !create.mount ? create() : create',
'app.mount(app.selector || "body")'
].join('\n')
}
}
}
}
+116
View File
@@ -0,0 +1,116 @@
// bankai serve — the production server. Static assets from dist
// (precompressed variants negotiated, hashed assets cached forever);
// everything else is a page: 103 Early Hints from the build manifest,
// then streaming SSR of the entry module — imported natively, because
// the server side never needed a build.
import { createServer } from 'node:http'
import { createReadStream } from 'node:fs'
import { readFile, stat } from 'node:fs/promises'
import { join, normalize, extname, resolve } from 'node:path'
import { pathToFileURL } from 'node:url'
import { resolveApp } from './app.js'
import { documentHead, documentTail, assetLinks } from './document.js'
const MIME = {
'.html': 'text/html; charset=utf-8',
'.js': 'text/javascript; charset=utf-8',
'.mjs': 'text/javascript; charset=utf-8',
'.css': 'text/css; charset=utf-8',
'.json': 'application/json; charset=utf-8',
'.svg': 'image/svg+xml',
'.map': 'application/json',
'.txt': 'text/plain; charset=utf-8',
'.woff2': 'font/woff2',
'.png': 'image/png',
'.webp': 'image/webp',
'.ico': 'image/x-icon'
}
export default async function serve ({ outDir = 'dist', port = 8080 }) {
outDir = resolve(outDir)
const meta = JSON.parse(await readFile(join(outDir, 'bankai.json'), 'utf8'))
const mod = await import(pathToFileURL(meta.entry))
const links = assetLinks(meta.assets)
const server = createServer(async (req, res) => {
const url = new URL(req.url, 'http://localhost')
const pathname = decodeURIComponent(url.pathname)
// static asset?
const file = normalize(join(outDir, pathname))
if (file.startsWith(outDir) && extname(pathname)) {
if (await isFile(file)) return sendFile(req, res, file, pathname)
if (MIME[extname(pathname)]) {
// a missing asset is a miss, not a page
res.writeHead(404, { 'content-type': 'text/plain' })
return res.end('not found: ' + pathname)
}
}
// page: hints first, then stream
try {
const app = resolveApp(mod, meta.entry)
const state = {}
if (links.length && res.writeEarlyHints) {
res.writeEarlyHints({ link: links })
}
res.writeHead(200, {
'content-type': 'text/html; charset=utf-8',
link: links.join(', ')
})
res.write(documentHead({ title: meta.title, ...meta.assets }))
for await (const chunk of app.toStream(req.url, state)) {
res.write(chunk)
}
res.end(documentTail(state))
} catch (err) {
console.error(err)
if (!res.headersSent) res.writeHead(500, { 'content-type': 'text/plain' })
res.end('bankai: render error')
}
})
await new Promise((resolveListen) => server.listen(port, resolveListen))
return {
server,
port: server.address().port,
origin: `http://localhost:${server.address().port}`,
close: () => new Promise((resolveClose) => server.close(resolveClose))
}
}
async function isFile (path) {
try {
return (await stat(path)).isFile()
} catch (e) {
return false
}
}
async function sendFile (req, res, file, pathname) {
const headers = {
'content-type': MIME[extname(file)] || 'application/octet-stream',
// hashed build assets are immutable; everything else revalidates
'cache-control': pathname.startsWith('/assets/')
? 'public, max-age=31536000, immutable'
: 'no-cache',
vary: 'accept-encoding'
}
// negotiate precompressed siblings written at build time
const accepted = String(req.headers['accept-encoding'] || '')
for (const [encoding, ext] of [['br', '.br'], ['gzip', '.gz']]) {
if (accepted.includes(encoding) && await isFile(file + ext)) {
headers['content-encoding'] = encoding
res.writeHead(200, headers)
createReadStream(file + ext).pipe(res)
return
}
}
res.writeHead(200, headers)
createReadStream(file).pipe(res)
}