@brust/core 2.0.0-alpha.2 → 2.0.0-alpha.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/README.md +66 -6
  2. package/native/index.d.ts +91 -4
  3. package/native/index.js +60 -54
  4. package/package.json +25 -9
  5. package/src/actions/client.ts +22 -5
  6. package/src/actions/load.ts +2 -1
  7. package/src/actions/prefix.ts +24 -2
  8. package/src/actions-bridge.ts +29 -11
  9. package/src/browser.ts +3 -1
  10. package/src/build/actions-only.ts +86 -0
  11. package/src/build/build-eval.ts +332 -0
  12. package/src/build/build-icons.ts +69 -0
  13. package/src/build/bundle.ts +462 -52
  14. package/src/build/cf-assets.ts +83 -0
  15. package/src/build/cf-core.ts +90 -0
  16. package/src/build/cf-entry.ts +76 -0
  17. package/src/build/cf-wrangler.ts +169 -0
  18. package/src/build/cloudflare.ts +320 -0
  19. package/src/build/compile.ts +116 -6
  20. package/src/build/config.ts +294 -11
  21. package/src/build/css.ts +331 -0
  22. package/src/build/esm-resolve.ts +170 -0
  23. package/src/build/features.ts +114 -0
  24. package/src/build/index.ts +264 -20
  25. package/src/build/manifest.ts +85 -7
  26. package/src/build/pkg-src.ts +514 -0
  27. package/src/build/recognised.ts +19 -0
  28. package/src/build/scan.ts +71 -20
  29. package/src/build/server-only.ts +39 -0
  30. package/src/build/ssg-render.ts +65 -0
  31. package/src/build/ssg.ts +146 -0
  32. package/src/build/static-worker.ts +91 -0
  33. package/src/build/static.ts +258 -0
  34. package/src/build/tailwind.ts +117 -0
  35. package/src/build/tsconfig-paths.ts +67 -0
  36. package/src/build-time.ts +10 -0
  37. package/src/cache-adapter/bridge.ts +91 -0
  38. package/src/cache-adapter/conformance.ts +226 -0
  39. package/src/cache-adapter/index.ts +10 -0
  40. package/src/cache-adapter/load.ts +144 -0
  41. package/src/cache-adapter/memory.ts +229 -0
  42. package/src/cache-adapter/runtime.ts +124 -0
  43. package/src/cache-adapter/types.ts +96 -0
  44. package/src/cache-adapter/workers.ts +118 -0
  45. package/src/cache.ts +4 -1
  46. package/src/cf.ts +19 -0
  47. package/src/cli.ts +71 -2
  48. package/src/config.ts +127 -25
  49. package/src/css-modules.d.ts +8 -0
  50. package/src/dev/bun.ts +371 -0
  51. package/src/dev/client.ts +92 -0
  52. package/src/dev/devtools-data.ts +23 -0
  53. package/src/dev/devtools.ts +356 -0
  54. package/src/dev/diag.ts +30 -0
  55. package/src/dev/proxy.ts +236 -0
  56. package/src/dev/tui.ts +144 -0
  57. package/src/dev/watch.ts +130 -0
  58. package/src/dev.ts +97 -0
  59. package/src/handlers.ts +282 -0
  60. package/src/index.ts +3 -1
  61. package/src/native.ts +38 -1
  62. package/src/routes.ts +20 -1
  63. package/src/run.ts +59 -12
  64. package/src/server-handlers.ts +32 -0
  65. package/src/shadcn/init.ts +513 -0
  66. package/src/shadcn/jsonc.ts +129 -0
  67. package/src/shadcn/registry.ts +149 -0
  68. package/src/worker.ts +127 -245
@@ -4,16 +4,25 @@
4
4
  // edited by hand. An out dir that could hold the app's own sources, or a non-empty one that is not
5
5
  // a previous brust dist (no `manifest.json` / `.brust` marker; `--force` overrides), is refused
6
6
  // before anything is written or removed.
7
- import { cpSync, existsSync, mkdirSync, readdirSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs'
7
+ import { cpSync, existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs'
8
8
  import { homedir } from 'node:os'
9
9
  import { basename, dirname, isAbsolute, join, parse, relative, resolve } from 'node:path'
10
- import { BrustRouteError, validateRoutes } from '../routes'
11
- import { type BrowserCtx, buildActions, buildClientChunks, buildJobs, buildReactChunks, buildRuntime, storeModules } from './bundle'
12
- import { compileApp } from './compile'
13
- import { type ActionsBuildConfig, loadBuildConfig } from './config'
10
+ import { BrustRouteError, type FlatRoute, validateRoutes } from '../routes'
11
+ import { type BrowserCtx, setDevBuild, buildActions, buildCacheAdapter, buildClientChunks, buildJobs, buildReactChunks, buildRuntime, nestedOf, storeModules } from './bundle'
12
+ import { runActionsOnly } from './actions-only'
13
+ import { type CfPrepared, buildCloudflare, prepareCloudflare } from './cloudflare'
14
+ import { renderIcons } from './build-icons'
15
+ import { evaluateBuildSlots } from './build-eval'
16
+ import { preparePackageSources } from './pkg-src'
17
+ import { type Compiled, compileApp, scanAppWrites } from './compile'
18
+ import { buildCss, CssGraph, directCss, resolveGlobals, routeCssSources } from './css'
19
+ import { type ActionsBuildConfig, type CacheBuildConfig, loadBuildConfig } from './config'
14
20
  import { BuildError } from './errors'
15
- import { writeManifest } from './manifest'
21
+ import { importsStore } from './features'
22
+ import { type CacheRecord, type ManifestJson, needsWorkers, reachedJobs, tierOf, writeManifest } from './manifest'
16
23
  import { scanRoutes } from './scan'
24
+ import { type ExprReads, prepareStatic, writeStatic } from './static'
25
+ import { writeStaticWorker } from './static-worker'
17
26
 
18
27
  export { BuildError } from './errors'
19
28
 
@@ -79,17 +88,40 @@ export async function runBuild(opts: {
79
88
  outDir: string
80
89
  /** Replace a non-empty out dir even without a previous build's marker. */
81
90
  force?: boolean
91
+ /** `cloudflare` also writes `<out>/cf/` (M4-CF); `static` also writes `<out>/static/` (gaps round
92
+ * L9); default `bun` = the unchanged build. */
93
+ target?: 'bun' | 'cloudflare' | 'static'
94
+ /** `--strict` (static): a loader that reads the request fails the build. */
95
+ strict?: boolean
96
+ /** The cache key grammar's read-set (static; tests swap it). Default: the addon. */
97
+ exprReads?: ExprReads
98
+ /** `--wasm-from-source` (cloudflare only). */
99
+ wasmFromSource?: boolean
100
+ /** `--actions-only` (L16 R16.3): no pages, only the `[actions]` app; with `bun` (default) or `cloudflare`. */
101
+ actionsOnly?: boolean
102
+ /** `brust build --dev` (L14, used by `brust dev`): also writes `dev.json` and builds the client runtime with `__BRUST_DEV__`. */
103
+ dev?: boolean
82
104
  log: (s: string) => void
83
105
  }): Promise<void> {
106
+ setDevBuild(opts.dev === true)
84
107
  const appRoot = resolve(opts.appRoot)
85
108
  const entry = resolve(appRoot, opts.entry)
86
109
  const dist = resolve(appRoot, opts.outDir)
87
110
  assertSafeOutDir(dist, appRoot, [entry, join(appRoot, 'public')])
88
111
  assertReplaceable(dist, opts.force)
89
- const { serverOnly, actions } = await loadBuildConfig(appRoot)
112
+ const built = await loadBuildConfig(appRoot, { actionsOnly: opts.actionsOnly === true })
113
+ if (opts.actionsOnly)
114
+ return runActionsOnly({ appRoot, dist, config: built, target: opts.target, wasmFromSource: opts.wasmFromSource === true, statOk, assertSafeOutDir, log: opts.log })
115
+ const { serverOnly, cloudflare, cache, cssGlobal, sourceRoots } = built
116
+ // L16 R16.4b: `[actions]` with a `base_url` and no actions file (the default name, not one written in the toml)
117
+ // is a page-only build: the app is deployed elsewhere, so nothing is bundled or mounted here.
118
+ const remote =
119
+ built.actions !== null && built.actions.baseUrl !== undefined && !built.actions.entryExplicit && !statOk(resolve(appRoot, built.actions.entry)) ? built.actions : null
120
+ const actions = remote ? null : built.actions
121
+ if (actions?.prefix === '/') throw new BuildError('config', 'actions.prefix "/" is only for an actions-only build (brust build --actions-only) or a page-only build that points at one')
90
122
 
91
123
  // Everything that can fail on the app's own input runs before a byte is written.
92
- const { routes, componentFile } = await scanRoutes(entry)
124
+ const { routes, componentFile, componentIssue, appModules, appGraph } = await scanRoutes(entry, appRoot, sourceRoots)
93
125
  let leaves: ReturnType<typeof validateRoutes>
94
126
  try {
95
127
  leaves = validateRoutes(routes)
@@ -114,7 +146,26 @@ export async function runBuild(opts: {
114
146
  }
115
147
  }
116
148
  }
117
- assertSafeOutDir(dist, appRoot, [...componentFile.values(), ...(actionsEntry ? [actionsEntry] : [])])
149
+ let cacheModule: string | null = null
150
+ if (cache?.module !== undefined) {
151
+ cacheModule = resolve(appRoot, cache.module)
152
+ const rel = relative(appRoot, cacheModule)
153
+ if (isAbsolute(cache.module) || rel === '..' || rel.startsWith('../') || isAbsolute(rel) || !statOk(cacheModule)) {
154
+ throw new BuildError('cache', `cache.module ${cache.module} is not a file inside the app`)
155
+ }
156
+ }
157
+ assertSafeOutDir(dist, appRoot, [...componentFile.values(), ...(actionsEntry ? [actionsEntry] : []), ...(cacheModule ? [cacheModule] : [])])
158
+
159
+ // R9.3/R9.4: every reason to refuse a static build, before any write.
160
+ const ssgPlan =
161
+ opts.target === 'static'
162
+ ? await prepareStatic(leaves, actions !== null, opts.exprReads ?? (await import('../native')).cacheExprReads, opts.log, cache)
163
+ : null
164
+
165
+ // Config, @brust/core-cf resolution and the user's wrangler file fail here, before any write.
166
+ // L12: a static build with `[actions]` also builds the Cloudflare worker (its Pages `_worker.js`).
167
+ const hybrid = ssgPlan !== null && actions !== null
168
+ const cf = opts.target === 'cloudflare' || hybrid ? await prepareCloudflare(appRoot, cloudflare, { fromSource: opts.wasmFromSource === true, env: process.env }) : null
118
169
 
119
170
  // Sibling of `dist` (same filesystem: the final rename is atomic), fixed name (no random bytes in
120
171
  // anything the bundler sees).
@@ -122,7 +173,13 @@ export async function runBuild(opts: {
122
173
  rmSync(tmp, { recursive: true, force: true })
123
174
  mkdirSync(tmp, { recursive: true })
124
175
  try {
125
- await buildInto(tmp, { appRoot, entry, dist, leaves, componentFile, serverOnly, actions, actionsEntry, log: opts.log })
176
+ await buildInto(tmp, { dev: opts.dev === true, appRoot, entry, dist, leaves, componentFile, componentIssue, appModules, appGraph, serverOnly, actions, actionsEntry, cache, cacheModule, cf, hybrid, cssGlobal, sourceRoots, actionsRemote: remote?.prefix ?? null, log: opts.log })
177
+ if (ssgPlan) {
178
+ // Rendered from the finished temp dist, so a failed render leaves the previous dist untouched.
179
+ const version: string = (await Bun.file(join(import.meta.dir, '../../package.json')).json()).version
180
+ await writeStatic(tmp, { entry, appRoot, plan: ssgPlan, version, strict: opts.strict === true, log: opts.log, shownDir: join(dist, 'static') })
181
+ if (hybrid && cf && actions) writeStaticWorker(tmp, actions, cf, opts.log)
182
+ }
126
183
  rmSync(join(tmp, '.stage'), { recursive: true, force: true })
127
184
  if (existsSync(dist)) {
128
185
  const old = join(dirname(dist), `.${basename(dist)}.brust-old`)
@@ -140,48 +197,172 @@ export async function runBuild(opts: {
140
197
  async function buildInto(
141
198
  out: string,
142
199
  o: {
200
+ /** Write `dev.json` (L14). */
201
+ dev: boolean
143
202
  appRoot: string
144
203
  entry: string
145
204
  /** The final dist dir (`index.js` points at the entry relative to it). */
146
205
  dist: string
147
206
  leaves: ReturnType<typeof validateRoutes>
148
207
  componentFile: Map<Function, string>
208
+ componentIssue: Map<Function, string>
209
+ /** F230: every app module of the route entry's static import graph (absolute paths). */
210
+ appModules: string[]
211
+ /** F230: each app module's in-root static imports (absolute paths). */
212
+ appGraph: Map<string, string[]>
149
213
  serverOnly: string[]
150
214
  actions: ActionsBuildConfig | null
151
215
  /** Absolute path of the actions entry (null when `[actions]` is off). */
152
216
  actionsEntry: string | null
217
+ cache: CacheBuildConfig | null
218
+ /** Absolute path of a custom cache adapter module. */
219
+ cacheModule: string | null
220
+ cf: CfPrepared | null
221
+ /** `[css] global` as written (app-root relative). */
222
+ cssGlobal: string[]
223
+ /** `[build] source_roots` (F256): normalised, app-root-relative directories outside the app a relative import may reach. */
224
+ sourceRoots: string[]
225
+ /** L16 R16.4b: the prefix of an actions app deployed elsewhere (a page-only build); absent = a local app or none. */
226
+ actionsRemote: string | null
227
+ /** `--target static` with `[actions]`: the worker is built without the cache (static pages are never cached). */
228
+ hybrid: boolean
153
229
  log: (s: string) => void
154
230
  },
155
231
  ): Promise<void> {
156
232
  const { appRoot, entry, leaves } = o
157
- const ctx: BrowserCtx = { sourceOf: new Map(), appRoot, serverOnly: o.serverOnly, serverFiles: o.actionsEntry ? [realpathSync(o.actionsEntry)] : [] }
233
+ // L19: every stylesheet first, so each JS build below reads one set of CSS Module class maps.
234
+ const graph = new CssGraph()
235
+ const chainFiles = (l: FlatRoute) => l.chain.flatMap((n) => (n.Component && o.componentFile.has(n.Component) ? [o.componentFile.get(n.Component)!] : []))
236
+ const routeCss = routeCssSources(leaves, chainFiles, resolveGlobals(appRoot, o.cssGlobal), graph)
237
+ const serverCss = [o.actionsEntry, o.cacheModule].flatMap((f) => (f ? graph.of(f) : []))
238
+ mkdirSync(join(out, 'client'), { recursive: true })
239
+ // Review N3: `brust dev` builds with BRUST_BUILD_MODE=development (as the JS bundles): readable, unminified CSS.
240
+ const css = await buildCss(out, [...new Set([...[...routeCss.values()].flat(), ...serverCss])], process.env.BRUST_BUILD_MODE !== 'development', { appRoot, log: o.log })
241
+ for (const c of directCss(entry))
242
+ o.log(`[brust] warning css ${relative(appRoot, entry)} imports ${c}: the route entry belongs to no route, so it is linked nowhere; import it from a layout, or list it in [css] global`)
243
+ const ctx: BrowserCtx = { sourceOf: new Map(), appRoot, serverOnly: o.serverOnly, serverFiles: o.actionsEntry ? [realpathSync(o.actionsEntry)] : [], cssMaps: css.maps }
158
244
  // The runtime first: its hashed URL is the `runtimeImport` every client chunk is compiled with.
159
245
  const runtime = await buildRuntime(out, ctx)
160
- const { compiled, routeComponent } = compileApp({
246
+ const runtimeUrls = { core: `/_brust/${runtime.core}`, store: `/_brust/${runtime.store}` }
247
+ // F230: one scan per build for load-time writes into another app module's exports; every compile reads it.
248
+ const loadWrites = scanAppWrites(appRoot, o.appModules, o.log, o.sourceRoots)
249
+ // Where a React island renders, the load-time writers run first: every one in the SSR jobs bundle (server code the
250
+ // worker runs anyway); in an island's browser chunk only a writer of a module that island's code imports (Mellow F1:
251
+ // a writer is often a server-side setup module), with a warning.
252
+ const scanned = JSON.parse(loadWrites) as { writers: [string, string[]][] }
253
+ const real = (f: string) => {
254
+ try {
255
+ return realpathSync(f)
256
+ } catch {
257
+ return f
258
+ }
259
+ }
260
+ const writes = scanned.writers.map(([w, mods]) => ({ file: real(resolve(appRoot, w)), mods: new Set(mods.map((m) => real(resolve(appRoot, m)))) }))
261
+ const writers = [...new Set(writes.map((w) => w.file))]
262
+ const appGraph = new Map([...o.appGraph].map(([f, deps]) => [real(f), deps.map(real)]))
263
+ const writersFor = (c: Compiled, files: string[]): string[] => {
264
+ if (writes.length === 0) return []
265
+ const reached = new Set<string>()
266
+ const stack = files.map(real)
267
+ while (stack.length > 0) {
268
+ const f = stack.pop()!
269
+ if (reached.has(f)) continue
270
+ reached.add(f)
271
+ stack.push(...(appGraph.get(f) ?? []))
272
+ }
273
+ const out = writes.filter((w) => [...w.mods].some((m) => reached.has(m)))
274
+ for (const w of out)
275
+ o.log(`[brust] warning load-writer-in-client ${relative(appRoot, w.file)} is imported into the browser chunk of the React island ${c.id}: it changes ${[...w.mods].filter((m) => reached.has(m)).map((m) => relative(appRoot, m)).join(', ')} when it loads, and the island reads that module (F230). Its code ships to the browser: keep secrets and server-only code out of it, or write the value in the module that declares it`)
276
+ return [...new Set(out.map((w) => w.file))]
277
+ }
278
+ const compileOpts = {
161
279
  appRoot,
162
280
  leaves,
163
281
  componentFile: o.componentFile,
164
- runtimeImport: `/_brust/${runtime}`,
282
+ componentIssue: o.componentIssue,
283
+ loadWrites,
284
+ runtimeImport: runtimeUrls.core,
165
285
  serverOnly: o.serverOnly,
166
- log: o.log,
167
- })
286
+ sourceRoots: o.sourceRoots,
287
+ cssMaps: css.maps,
288
+ }
289
+ const firstLog: string[] = []
290
+ let { compiled, routeComponent } = compileApp({ ...compileOpts, log: (l) => firstLog.push(l) })
291
+ // F153c: the packages the app imports components from are compiled from their source when they publish it (and
292
+ // it matches what they publish); the app is compiled again with those sources. A refused package stays the island.
293
+ // F197: and the packages a helper is imported from, when the compiler asked to prove one plain.
294
+ const external = [...new Set([...compiled.values()].flatMap((c) => [...(c.ir.external ? [c.ir.external.source] : []), ...((c.ir.package_requests ?? []) as string[])]))]
295
+ const packages = preparePackageSources(appRoot, external)
296
+ if (Object.keys(packages.scopes).length > 0 || Object.keys(packages.recognised).length > 0) {
297
+ firstLog.length = 0
298
+ ;({ compiled, routeComponent } = compileApp({ ...compileOpts, packages, log: (l) => firstLog.push(l) }))
299
+ }
300
+ // L23: lucide icons the compiler could inline are rendered here (react-dom/server); L2: slots that read
301
+ // nothing request- or time-dependent are computed once, here. The app is compiled again with both (an icon with
302
+ // no markup stays the L22 island; a slot with a value is a literal: no job, no worker). The first compile's
303
+ // warnings describe icons that are inline now, so when icons were rendered only the last compile's are shown.
304
+ const hasIcons = [...compiled.values()].some((c) => (c.ir.icon_requests ?? []).length > 0)
305
+ const iconSvgs = hasIcons ? await renderIcons(compiled, appRoot, o.log) : undefined
306
+ const slotValues = await evaluateBuildSlots(out, compiled, ctx.sourceOf, appRoot, o.log)
307
+ const hasSlots = Object.keys(slotValues).length > 0
308
+ if (hasIcons || hasSlots) {
309
+ if (!hasIcons) firstLog.forEach((l) => o.log(l))
310
+ ;({ compiled, routeComponent } = compileApp({ ...compileOpts, packages, iconSvgs, iconsFinal: hasIcons, slotValues, log: hasIcons ? o.log : () => {} }))
311
+ } else firstLog.forEach((l) => o.log(l))
312
+
313
+ // F158 (R34.69/70): the compiler makes a caller of a route component fall back to React, so none is a revive host;
314
+ // if one is, the compiler missed it, and the build stops rather than let request data near the revive.
315
+ const routeRoots: ReadonlySet<string> = new Set(routeComponent.values())
316
+ for (const id of routeRoots) {
317
+ if (nestedOf(compiled, id) !== undefined) throw new BuildError('revive-host-route-root', `${id} is a page or layout and also receives lowered JSX children from a caller; this is a compiler bug (F158), please report it`)
318
+ }
168
319
 
169
320
  mkdirSync(join(out, 'jinja'), { recursive: true })
170
321
  for (const c of compiled.values()) writeFileSync(join(out, 'jinja', `${c.id}.jinja`), c.jinja)
171
322
 
172
- const runtimeUrl = `/_brust/${runtime}`
173
- const chunks = new Map([...(await buildClientChunks(out, compiled, ctx, runtimeUrl)), ...(await buildReactChunks(out, compiled, ctx, runtimeUrl))])
174
- const manifest = writeManifest({ leaves, routeComponent, compiled, runtime, chunks })
175
- await buildJobs(out, compiled, ctx.sourceOf, appRoot, storeModules(manifest))
323
+ const chunks = new Map([...(await buildClientChunks(out, compiled, ctx, runtimeUrls)), ...(await buildReactChunks(out, compiled, ctx, runtimeUrls, routeRoots, writersFor))])
324
+ const manifest = writeManifest({ leaves, routeComponent, compiled, runtime: { core: runtime.core, features: { ...runtime.features, store: runtime.store } }, chunks })
325
+ // L33: a component whose chunk imports the store module (directly or through a shared chunk) has the page preload it.
326
+ const readClient = (rel: string) => (existsSync(join(out, rel)) ? readFileSync(join(out, rel), 'utf8') : undefined)
327
+ for (const rec of Object.values(manifest.components)) if (rec.client && importsStore(readClient, rec.client, runtime.store)) rec.features.push('store')
328
+ for (const r of manifest.routes) {
329
+ const files = [...new Set((routeCss.get(r.id) ?? []).flatMap((s) => (css.file.has(s) ? [css.file.get(s)!] : [])))]
330
+ if (files.length > 0) r.css = files
331
+ }
332
+ await buildJobs(out, compiled, ctx.sourceOf, appRoot, storeModules(manifest), css.maps, routeRoots, reachedJobs(manifest), writers)
176
333
  manifest.actions =
177
334
  o.actions && o.actionsEntry
178
- ? { entry: await buildActions(out, o.actionsEntry), prefix: o.actions.prefix, maxBodyBytes: o.actions.maxBodyBytes, maxResponseBytes: o.actions.maxResponseBytes, crossSite: o.actions.crossSite }
335
+ ? { entry: await buildActions(out, o.actionsEntry, css.maps), prefix: o.actions.prefix, maxBodyBytes: o.actions.maxBodyBytes, maxResponseBytes: o.actions.maxResponseBytes, crossSite: o.actions.crossSite }
179
336
  : null
337
+ if (o.actionsRemote !== null) manifest.actions_remote = { prefix: o.actionsRemote }
338
+ if (o.cache) manifest.cache = await cacheRecord(out, manifest, o.cache, o.cacheModule, css.maps)
339
+ manifest.needs_workers = needsWorkers(manifest)
180
340
  writeFileSync(join(out, 'manifest.json'), `${JSON.stringify(manifest, null, 2)}\n`)
341
+ if (o.dev) writeFileSync(join(out, 'dev.json'), `${JSON.stringify(devJson(appRoot, compiled), null, 2)}\n`)
181
342
  writeFileSync(join(out, MARKER), 'generated by `brust build`: this directory is replaced on every build\n')
182
343
 
183
344
  const pub = join(appRoot, 'public')
184
345
  if (existsSync(pub)) cpSync(pub, join(out, 'public'), { recursive: true })
346
+ if (o.cf) {
347
+ const warnings = await buildCloudflare(
348
+ out,
349
+ {
350
+ appRoot,
351
+ entry,
352
+ dist: o.dist,
353
+ compiled,
354
+ manifest: o.hybrid ? { ...manifest, cache: undefined } : manifest,
355
+ sourceOf: ctx.sourceOf,
356
+ actionsEntry: o.actionsEntry,
357
+ cacheModule: o.hybrid ? null : o.cacheModule,
358
+ cacheGetTimeoutMs: o.hybrid ? undefined : o.cache?.getTimeoutMs,
359
+ cssMaps: css.maps,
360
+ log: o.log,
361
+ },
362
+ o.cf,
363
+ )
364
+ for (const w of warnings) o.log(w)
365
+ }
185
366
  const entryRel = relative(o.dist, entry)
186
367
  writeFileSync(
187
368
  join(out, 'index.js'),
@@ -197,3 +378,66 @@ async function buildInto(
197
378
  ].join('\n'),
198
379
  )
199
380
  }
381
+
382
+ /** `dev.json` (L14, R14.2): component id → source file, tier, the react reason, diagnostics. Only `brust build --dev` writes it. */
383
+ export function devJson(appRoot: string, compiled: Map<string, Compiled>): { version: 1; components: Record<string, DevComponent> } {
384
+ const components: Record<string, DevComponent> = {}
385
+ for (const c of compiled.values()) {
386
+ const tier = tierOf(c.ir)
387
+ const t = c.ir.tier
388
+ components[c.id] = {
389
+ file: relative(appRoot, c.file),
390
+ tier,
391
+ ...(tier === 'react' && t && typeof t === 'object' && 'React' in t ? { reason: String((t as { React: { reason: string } }).React.reason) } : {}),
392
+ diagnostics: (c.diagnostics ?? []).map((d) => ({ class: d.class, rule: d.rule, line: d.line, col: d.col, message: d.message, remediation: d.remediation })),
393
+ }
394
+ }
395
+ return { version: 1, components }
396
+ }
397
+
398
+ export interface DevComponent {
399
+ file: string
400
+ tier: 'static' | 'native' | 'react'
401
+ /** Why the compiler chose the react tier (the IR's `React.reason`). */
402
+ reason?: string
403
+ diagnostics: { class: string; rule: string; line: number; col: number; message: string; remediation: string }[]
404
+ }
405
+
406
+ /** `manifest.cache` (R7, R8): the custom module bundled for the worker, the native defaults, and the
407
+ * build id every L2 key carries. */
408
+ async function cacheRecord(out: string, manifest: ManifestJson, c: CacheBuildConfig, moduleAbs: string | null, cssMaps: Map<string, Record<string, string>>): Promise<CacheRecord> {
409
+ const module = moduleAbs ? await buildCacheAdapter(out, moduleAbs, cssMaps) : undefined
410
+ return {
411
+ adapter: c.adapter,
412
+ ...(module ? { module } : {}),
413
+ ...(c.broadcast ? { broadcast: c.broadcast, broadcastOptions: c.broadcastOptions ?? {} } : {}),
414
+ options: c.options,
415
+ namespace: c.namespace,
416
+ getTimeoutMs: c.getTimeoutMs ?? 50,
417
+ maxBodyBytes: c.maxBodyBytes,
418
+ epochIntervalMs: c.epochIntervalMs,
419
+ buildId: computeBuildId(out, manifest),
420
+ }
421
+ }
422
+
423
+ /** R7: the first 16 hex chars of sha256 over the manifest (without `cache`), every `jinja/*.jinja`
424
+ * (by name), `jobs.js` and `actions.js` when present: a rebuild of the same app keeps it, any change
425
+ * to what renders a page moves it (a deploy never serves an older build's L2 bodies). */
426
+ export function computeBuildId(out: string, manifest: ManifestJson): string {
427
+ const h = new Bun.CryptoHasher('sha256')
428
+ const { cache: _, ...rest } = manifest
429
+ h.update(JSON.stringify(rest))
430
+ const jinja = join(out, 'jinja')
431
+ for (const f of (existsSync(jinja) ? readdirSync(jinja) : []).filter((f) => f.endsWith('.jinja')).sort()) {
432
+ h.update(`\0${f}\0`)
433
+ h.update(readFileSync(join(jinja, f)))
434
+ }
435
+ for (const f of ['jobs.js', 'actions.js']) {
436
+ const p = join(out, f)
437
+ if (existsSync(p)) {
438
+ h.update(`\0${f}\0`)
439
+ h.update(readFileSync(p))
440
+ }
441
+ }
442
+ return h.digest('hex').slice(0, 16)
443
+ }
@@ -6,6 +6,7 @@
6
6
  import type { FlatRoute } from '../routes'
7
7
  import type { Compiled, ComponentIR } from './compile'
8
8
  import { BuildError } from './errors'
9
+ import { featuresOf } from './features'
9
10
 
10
11
  export interface JobCache {
11
12
  key: string | null
@@ -29,6 +30,12 @@ export interface ChildRecord {
29
30
  id: string
30
31
  instances: string
31
32
  props: Record<string, string>
33
+ /** F105: constant props; part of the child's job keys. */
34
+ literals?: Record<string, unknown>
35
+ /** F105: jinja over `__props` (and `__row`/`__idx` per row) the server evaluates. */
36
+ exprs?: Record<string, string>
37
+ /** F142 R34.43: the list of a `per-row-literal` instance (a constant the compiler read). */
38
+ rows?: unknown[]
32
39
  }
33
40
 
34
41
  export interface ComponentRecord {
@@ -40,6 +47,8 @@ export interface ComponentRecord {
40
47
  needs_worker: boolean
41
48
  use_id_slots: number
42
49
  stores: string[]
50
+ /** L33: the client runtime feature modules (`assets.features` keys) this component's output needs, in load order. */
51
+ features: string[]
43
52
  }
44
53
 
45
54
  export interface RouteRecord {
@@ -49,6 +58,8 @@ export interface RouteRecord {
49
58
  loaders: string[]
50
59
  cache: { ttl_seconds: number; prefix: string | null; bypass: true | string | null; tags: string[] } | null
51
60
  catch_all: boolean
61
+ /** L19 (R19.3): `client/<file>.css` in cascade order; absent when the route has none. */
62
+ css?: string[]
52
63
  }
53
64
 
54
65
  /** `manifest.actions` (A3): `entry` is relative to dist; `maxBodyBytes`/`maxResponseBytes` are camelCase by contract. */
@@ -60,13 +71,66 @@ export interface ActionsRecord {
60
71
  crossSite: 'reject' | 'allow'
61
72
  }
62
73
 
74
+ /** The manifest format the Rust loader accepts (`MANIFEST_VERSION` in brust-core `manifest.rs`): the one place TS names it. */
75
+ export const MANIFEST_VERSION = 3 as const
76
+
63
77
  export interface ManifestJson {
64
- version: 1
78
+ version: typeof MANIFEST_VERSION
65
79
  routes: RouteRecord[]
66
80
  components: Record<string, ComponentRecord>
67
- assets: { runtime: string }
81
+ /** `runtime` is the core; `features` maps each feature module name to its file (L33). */
82
+ assets: { runtime: string; features: Record<string, string> }
68
83
  jobs_module: string
69
84
  actions: ActionsRecord | null
85
+ /** L16 R16.3: an actions-only build (no routes, no templates); everything but the prefix is a 404 problem+json. */
86
+ actions_only?: true
87
+ /** L16 R16.4b: a page-only build: no local actions app, `base_url` points at the deployment that has it. */
88
+ actions_remote?: { prefix: string }
89
+ /** `[cache]` (cache adapters); absent without one (the manifest is then byte-identical). */
90
+ cache?: CacheRecord
91
+ /** F165 (R40.1): `brust start` spawns its worker pool (`needsWorkers`). Read by `run.ts` only; an
92
+ * absent value (an older or actions-only manifest) means the pool is needed. */
93
+ needs_workers?: boolean
94
+ }
95
+
96
+ /** F165 (R40.1): whether any request can call a worker. Workers answer four kinds of call
97
+ * (worker.ts): `loader`, `jobs` (precompute and SSR), `fetch` (the local actions app) and `cache`
98
+ * (the adapter). Only the jobs a request can plan count (`reachedJobs`, F183). */
99
+ export function needsWorkers(m: Pick<ManifestJson, 'routes' | 'components' | 'actions' | 'cache'>): boolean {
100
+ const planned = [...reachedJobs(m).planned].some((id) => (m.components[id]?.jobs.length ?? 0) > 0)
101
+ return planned || m.routes.some((r) => r.loaders.length > 0) || m.actions !== null || m.cache !== undefined
102
+ }
103
+
104
+ /** F183: the jobs a request can call, as brust-core plans them (`collect_jobs`, pipeline.rs): every job of each
105
+ * route chain component and of each of its direct `children[]` records (`planned`; nothing deeper has a job,
106
+ * `linkNativeChunks`), and the `ssr` of each component one of those jobs targets (`ssr`; the worker runs the
107
+ * target's, handlers.ts). `jobs.js` leaves out every other entry: no request reaches it. */
108
+ export function reachedJobs(m: Pick<ManifestJson, 'routes' | 'components'>): { planned: Set<string>; ssr: Set<string> } {
109
+ const planned = new Set<string>()
110
+ for (const r of m.routes)
111
+ for (const id of r.chain) {
112
+ planned.add(id)
113
+ for (const ch of m.components[id]?.children ?? []) planned.add(ch.id)
114
+ }
115
+ const ssr = new Set<string>()
116
+ for (const id of planned) for (const j of m.components[id]?.jobs ?? []) if (j.kind === 'ssr' && j.target !== undefined) ssr.add(j.target)
117
+ return { planned, ssr }
118
+ }
119
+
120
+ /** `manifest.cache` / `CONFIG.cache`: the adapter the runtime loads (`cache-adapter/load.ts`). */
121
+ export interface CacheRecord {
122
+ adapter: string
123
+ /** `custom`: the bundled module, relative to dist. */
124
+ module?: string
125
+ broadcast?: string
126
+ options: Record<string, unknown>
127
+ broadcastOptions?: Record<string, unknown>
128
+ namespace: string
129
+ getTimeoutMs: number
130
+ maxBodyBytes: number
131
+ epochIntervalMs: number
132
+ /** 16 hex chars of sha256 over the build output (R7): every L2 key carries it. */
133
+ buildId: string
70
134
  }
71
135
 
72
136
  // biome-ignore lint/suspicious/noExplicitAny: IR JSON (externally tagged enums)
@@ -208,15 +272,23 @@ export function childRecords(c: Compiled, clientOnly: string[] = []): ChildRecor
208
272
  if (inst.loops.length > 1)
209
273
  throw new BuildError('nested-instance', `${ir.id}: child ${inst.child_id} sits in nested lists (M3)`)
210
274
  const list = inst.loops[0]
211
- if (list === null)
275
+ const literal = list === null && Array.isArray(inst.rows_literal)
276
+ if (list === null && !literal)
212
277
  throw new BuildError('instance-list-path', `${ir.id}: child ${inst.child_id} sits in a list that is not a props path`)
213
278
  const props: Record<string, string> = {}
214
279
  for (const [name, path] of Object.entries(inst.props)) {
215
280
  if (path === null)
216
- throw new BuildError('instance-prop-path', `${ir.id}: child ${inst.child_id} prop ${name} is not a props path`)
281
+ throw new BuildError(
282
+ 'instance-prop-path',
283
+ `${ir.id}: child ${inst.child_id} prop ${name} is not a props path, a JSON literal or a template expression over props; compute it in a loader, or wrap the child's derived value in cache()`,
284
+ )
217
285
  props[name] = path
218
286
  }
219
- return { id: inst.child_id, instances: list === undefined ? 'static' : `per-row:${list}`, props }
287
+ const rec: ChildRecord = { id: inst.child_id, instances: literal ? 'per-row-literal' : list === undefined ? 'static' : `per-row:${list}`, props }
288
+ if (inst.literals && Object.keys(inst.literals).length > 0) rec.literals = { ...inst.literals }
289
+ if (inst.exprs && Object.keys(inst.exprs).length > 0) rec.exprs = { ...inst.exprs }
290
+ if (literal) rec.rows = inst.rows_literal
291
+ return rec
220
292
  })
221
293
  for (const id of clientOnly) out.push({ id, instances: 'static', props: {} })
222
294
  return out
@@ -243,7 +315,8 @@ export function writeManifest(opts: {
243
315
  leaves: FlatRoute[]
244
316
  routeComponent: Map<string, string>
245
317
  compiled: Map<string, Compiled>
246
- runtime: string
318
+ /** The runtime files `buildRuntime` wrote: the core and the feature modules. */
319
+ runtime: { core: string; features: Record<string, string> }
247
320
  /** component id → `client/<file>` (client chunk or react island chunk). */
248
321
  chunks: Map<string, string>
249
322
  actions?: ActionsRecord | null
@@ -262,7 +335,10 @@ export function writeManifest(opts: {
262
335
  needs_worker: jobs.length > 0,
263
336
  use_id_slots: c.ir.use_id_slots ?? 0,
264
337
  stores: storesOf(compiled, c.id),
338
+ features: featuresOf(c.id, c.jinja, tierOf(c.ir) === 'react'),
265
339
  }
340
+ for (const f of components[c.id]!.features)
341
+ if (!(f in opts.runtime.features)) throw new BuildError('runtime-feature-missing', `${c.id}: needs the client runtime feature ${f}, which the build did not ship`)
266
342
  }
267
343
  const routes: RouteRecord[] = opts.leaves.map((l) => {
268
344
  // A node without a Component (a pure path/loader group) renders nothing: not a chain entry.
@@ -284,7 +360,7 @@ export function writeManifest(opts: {
284
360
  }
285
361
  })
286
362
  linkNativeChunks(routes, compiled, components)
287
- return { version: 1, routes, components, assets: { runtime: opts.runtime }, jobs_module: 'jobs.js', actions: opts.actions ?? null }
363
+ return { version: MANIFEST_VERSION, routes, components, assets: { runtime: opts.runtime.core, features: opts.runtime.features }, jobs_module: 'jobs.js', actions: opts.actions ?? null }
288
364
  }
289
365
 
290
366
  /** S6 amendment (F66): the server's asset injection walks only each chain component's direct
@@ -297,6 +373,8 @@ function linkNativeChunks(routes: RouteRecord[], compiled: Map<string, Compiled>
297
373
  const chainIds = new Set(routes.flatMap((r) => r.chain))
298
374
  for (const root of chainIds) {
299
375
  const rec = components[root]!
376
+ // A React root renders its whole subtree itself: whatever native chunks its IR lists are not served.
377
+ if (rec.tier === 'react') continue
300
378
  const linked = new Set(rec.children.map((ch) => ch.id))
301
379
  const seen = new Set([root])
302
380
  const walk = (id: string) => {