@brust/core 2.0.0-alpha.3 → 2.0.0-alpha.4

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 (47) hide show
  1. package/README.md +64 -6
  2. package/native/index.d.ts +37 -2
  3. package/native/index.js +56 -54
  4. package/package.json +11 -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 +2 -2
  9. package/src/browser.ts +3 -1
  10. package/src/build/actions-only.ts +86 -0
  11. package/src/build/build-eval.ts +199 -0
  12. package/src/build/build-icons.ts +69 -0
  13. package/src/build/bundle.ts +39 -13
  14. package/src/build/cf-assets.ts +4 -2
  15. package/src/build/cf-entry.ts +7 -3
  16. package/src/build/cf-wrangler.ts +3 -1
  17. package/src/build/cloudflare.ts +14 -9
  18. package/src/build/compile.ts +41 -4
  19. package/src/build/config.ts +46 -10
  20. package/src/build/css.ts +286 -0
  21. package/src/build/index.ts +135 -20
  22. package/src/build/manifest.ts +23 -4
  23. package/src/build/scan.ts +59 -20
  24. package/src/build/ssg-render.ts +65 -0
  25. package/src/build/ssg.ts +146 -0
  26. package/src/build/static-worker.ts +91 -0
  27. package/src/build/static.ts +258 -0
  28. package/src/build-time.ts +10 -0
  29. package/src/cf.ts +2 -1
  30. package/src/cli.ts +19 -4
  31. package/src/config.ts +111 -25
  32. package/src/css-modules.d.ts +8 -0
  33. package/src/dev/bun.ts +365 -0
  34. package/src/dev/client.ts +92 -0
  35. package/src/dev/devtools-data.ts +23 -0
  36. package/src/dev/devtools.ts +356 -0
  37. package/src/dev/diag.ts +30 -0
  38. package/src/dev/proxy.ts +236 -0
  39. package/src/dev/tui.ts +144 -0
  40. package/src/dev/watch.ts +81 -0
  41. package/src/dev.ts +11 -28
  42. package/src/handlers.ts +41 -2
  43. package/src/index.ts +3 -1
  44. package/src/native.ts +18 -0
  45. package/src/routes.ts +20 -1
  46. package/src/run.ts +40 -8
  47. package/src/worker.ts +88 -20
@@ -0,0 +1,91 @@
1
+ // `brust build --target static` with `[actions]` (gaps round L12, R12.1): the static tree plus a
2
+ // Cloudflare Pages advanced-mode Worker that serves ONLY the action prefix.
3
+ // static/_worker.js/index.js a WorkerEntrypoint: the action prefix -> the Cloudflare core, everything else -> env.ASSETS
4
+ // static/_worker.js/core/ the `--target cloudflare` worker tree (glue + wasm + brust-app.js), verbatim
5
+ // static/_routes.json include: the prefix only, so pages and assets never invoke the Worker
6
+ // wrangler.jsonc the Pages project file (name, compatibility date); sits next to `static/`
7
+ import { cpSync, existsSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
8
+ import { join } from 'node:path'
9
+ import { type CfPrepared, cacheNeeds } from './cloudflare'
10
+ import { workerNameOf } from './cf-wrangler'
11
+ import { BuildError } from './errors'
12
+ import { CF_MIN_COMPAT_DATE } from './config'
13
+ import type { CacheRecord } from './manifest'
14
+
15
+ /** `.assetsignore`: the Worker source and the routes file are deploy inputs, never public assets. */
16
+ export const ASSETS_IGNORE = '_worker.js\n_routes.json\n.assetsignore\n'
17
+
18
+ /** The deploy inputs the Worker answers with a 404 (N1). */
19
+ export const HIDDEN = ['/_worker.js', '/_worker.js/*', '/_routes.json', '/.assetsignore']
20
+
21
+ /** `_routes.json` (R12.1): the prefix itself and everything under it reach the Worker, and so do the
22
+ * deploy inputs (N1): a static host that would otherwise serve `_worker.js/*` as files (the local
23
+ * `wrangler pages dev` does) is answered by the Worker's 404 instead. Pages and assets never do. */
24
+ export function routesJson(prefix: string): string {
25
+ return `${JSON.stringify({ version: 1, include: [prefix, `${prefix}/*`, ...HIDDEN], exclude: [] }, null, 2)}\n`
26
+ }
27
+
28
+ /** `_worker.js/index.js`. Pages' pipeline wants a module object with `fetch`, not the class the core
29
+ * exports (a WorkerEntrypoint whose `fetch` reads `this.env` and `this.ctx`), so the core's method is
30
+ * called with exactly those two. A request that reaches the Worker and is not an action (a path
31
+ * `_routes.json` keeps away, or a probe) falls through to the static files, except the deploy inputs
32
+ * themselves (`_worker.js/*`, `_routes.json`, `.assetsignore`), which are a 404 whatever serves the assets (N1). */
33
+ export function workerSource(main: string, prefix: string): string {
34
+ const q = JSON.stringify
35
+ return `${[
36
+ '// generated by `brust build --target static` (actions on Pages) — do not edit',
37
+ `import Core from ${q(`./core/${main}`)}`,
38
+ `const PREFIX = ${q(prefix)}`,
39
+ 'export default {',
40
+ ' fetch(request, env, ctx) {',
41
+ ' const path = new URL(request.url).pathname',
42
+ ' if (path === PREFIX || path.startsWith(`${PREFIX}/`)) return Core.prototype.fetch.call({ env, ctx }, request)',
43
+ ' let plain = path',
44
+ ' try { plain = decodeURIComponent(path) } catch {}',
45
+ ' if (/^\\/(_worker\\.js(\\/|$)|_routes\\.json$|\\.assetsignore$)/i.test(plain)) return new Response("Not Found", { status: 404 })',
46
+ ' return env.ASSETS.fetch(request)',
47
+ ' },',
48
+ '}',
49
+ ].join('\n')}\n`
50
+ }
51
+
52
+ /** The Pages project file: bindings and secrets are the user's (`wrangler pages` / the dashboard), never baked. */
53
+ export function pagesConfig(p: CfPrepared): string {
54
+ const name = p.cfg.name ?? (p.pkgName ? workerNameOf(p.pkgName) : undefined)
55
+ const compatibilityDate = p.cfg.compatibilityDate ?? p.core.meta.compatibilityDate
56
+ if (compatibilityDate < CF_MIN_COMPAT_DATE) throw new BuildError('config', `compatibility_date ${compatibilityDate} is older than ${CF_MIN_COMPAT_DATE}`)
57
+ const c = { ...(name !== undefined ? { name } : {}), pages_build_output_dir: './static', compatibility_date: compatibilityDate }
58
+ return `// generated by \`brust build --target static\` — bindings and secrets: \`wrangler pages secret put\` / the dashboard (docs/cloudflare.md §12)\n${JSON.stringify(c, null, 2)}\n`
59
+ }
60
+
61
+ /** R12: `[cache]` does not apply to static pages, and the Worker serves actions only, so an adapter
62
+ * that needs a Cloudflare binding (KV, Durable Object) has nowhere to be used: refused before any write. */
63
+ export function assertNoCacheBindings(cache: Pick<CacheRecord, 'adapter' | 'broadcast' | 'options' | 'broadcastOptions'> | null | undefined): void {
64
+ const need = cacheNeeds(cache ?? undefined)
65
+ if (need)
66
+ throw new BuildError(
67
+ 'ssg-actions-cache',
68
+ `[cache] adapter "${cache!.adapter}" needs a Cloudflare binding (${[need.kv && `KV ${need.kv}`, need.do && `Durable Object ${need.do}`].filter(Boolean).join(', ')}), which the static + actions Worker does not carry (static pages are never cached, the Worker serves actions only); drop [cache], or use --target cloudflare`,
69
+ )
70
+ }
71
+
72
+ /** Turns `<dist>/cf/` (built by `buildCloudflare`) into the Pages Worker inside `<dist>/static/`, then
73
+ * drops `cf/`: the build is `--target static`, its only output is `static/`. */
74
+ export function writeStaticWorker(dist: string, actions: { prefix: string }, p: CfPrepared, log: (s: string) => void): void {
75
+ const staticDir = join(dist, 'static')
76
+ const worker = join(dist, 'cf', 'worker')
77
+ if (!existsSync(join(worker, p.core.meta.main))) throw new BuildError('cf-wasm', `the Cloudflare build wrote no worker/${p.core.meta.main}`)
78
+ const out = join(staticDir, '_worker.js')
79
+ rmSync(out, { recursive: true, force: true })
80
+ cpSync(worker, join(out, 'core'), { recursive: true })
81
+ writeFileSync(join(out, 'index.js'), workerSource(p.core.meta.main, actions.prefix))
82
+ writeFileSync(join(staticDir, '_routes.json'), routesJson(actions.prefix))
83
+ // Workers Static Assets uploads the whole directory as public files unless told otherwise; Pages never serves these two.
84
+ writeFileSync(join(staticDir, '.assetsignore'), ASSETS_IGNORE)
85
+ writeFileSync(join(dist, 'wrangler.jsonc'), pagesConfig(p))
86
+ const report = join(staticDir, 'ssg.json')
87
+ const json = JSON.parse(readFileSync(report, 'utf8')) as Record<string, unknown>
88
+ writeFileSync(report, `${JSON.stringify({ ...json, actions: { prefix: actions.prefix, worker: '_worker.js' } }, null, 2)}\n`)
89
+ rmSync(join(dist, 'cf'), { recursive: true, force: true })
90
+ log(`[brust] static: actions under ${actions.prefix} are served by _worker.js (_routes.json keeps pages and assets off the Worker)`)
91
+ }
@@ -0,0 +1,258 @@
1
+ // `brust build --target static` (gaps round L9, R9.1-R9.5): after the normal dist is built, render
2
+ // every planned page through the real server (a child process, `ssg-render.ts`) and write
3
+ // `<out>/static/`: one HTML file per page, `404.html`, the assets the native host serves
4
+ // (`layoutAssets`), `_headers`, `_redirects` and an `ssg.json` report. The layout is what
5
+ // Cloudflare Pages and Workers Static Assets (`not_found_handling = "404-page"`) serve as is.
6
+ import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'
7
+ import { dirname, join } from 'node:path'
8
+ import type { FlatRoute } from '../routes'
9
+ import { layoutAssets } from './cf-assets'
10
+ import { BuildError } from './errors'
11
+ import type { Rendered } from './ssg-render'
12
+ import { assertNoCacheBindings } from './static-worker'
13
+ import { NOT_FOUND_PATH, type PlannedPage, type StaticPlan, paramRoutes, planStatic, ssgOf } from './ssg'
14
+
15
+ export interface StaticOptions {
16
+ /** `--strict`: a loader reading the request fails the build instead of warning. */
17
+ strict: boolean
18
+ }
19
+
20
+ /** The request reads of one cache key expression (the server's grammar, through the addon). */
21
+ export type ExprReads = (expr: string) => string[]
22
+
23
+ /** R9.3/R9.4: everything that refuses a static build, checked before a byte is written; then the
24
+ * resolved plan. `actions`: whether `[actions]` is configured. */
25
+ export async function prepareStatic(
26
+ leaves: FlatRoute[],
27
+ actions: boolean,
28
+ reads: ExprReads,
29
+ log: (s: string) => void,
30
+ cache?: Parameters<typeof assertNoCacheBindings>[0],
31
+ ): Promise<StaticPlan> {
32
+ // L12: `[actions]` makes the output hybrid (static pages + a Pages Worker for the action prefix).
33
+ if (actions) assertNoCacheBindings(cache)
34
+ let cacheInfo = false
35
+ for (const leaf of leaves) {
36
+ const cache = leaf.chain[leaf.chain.length - 1]?.cache
37
+ if (!cache || ssgOf(leaf) === false) continue
38
+ cacheInfo = true
39
+ for (const [field, expr] of [
40
+ ['prefix', cache.prefix],
41
+ ['bypass', typeof cache.bypass === 'string' ? cache.bypass : undefined],
42
+ ] as const) {
43
+ if (expr === undefined) continue
44
+ let r: string[]
45
+ try {
46
+ r = reads(expr)
47
+ } catch (e) {
48
+ throw new BuildError('ssg-varies', `route ${leaf.id} (${leaf.pattern}) cache.${field}: ${(e as Error).message}`)
49
+ }
50
+ if (r.length > 0)
51
+ throw new BuildError(
52
+ 'ssg-varies',
53
+ `route ${leaf.id} (${leaf.pattern}) cache.${field} reads ${r.join(', ')}: the page varies per request, and a static file is one page for everyone (set ssg: false on the route, or drop the read)`,
54
+ )
55
+ }
56
+ }
57
+ if (cacheInfo) log('[brust] static: cache.ttl_seconds does not apply to static files (ignored)')
58
+ const params = new Map<string, unknown>()
59
+ for (const leaf of paramRoutes(leaves)) {
60
+ const ssg = ssgOf(leaf)
61
+ if (!ssg || !ssg.params) continue
62
+ try {
63
+ params.set(leaf.id, await ssg.params())
64
+ } catch (e) {
65
+ throw new BuildError('ssg-params', `route ${leaf.id} (${leaf.pattern}) ssg.params() threw: ${(e as Error).message ?? String(e)}`)
66
+ }
67
+ }
68
+ return planStatic(leaves, params)
69
+ }
70
+
71
+ export interface StaticReport {
72
+ pages: { path: string; file: string; routeId: string }[]
73
+ redirects: { from: string; to: string; status: number }[]
74
+ skipped: { routeId: string; pattern: string }[]
75
+ notFound: { file: '404.html'; routeId: string | null }
76
+ warnings: string[]
77
+ }
78
+
79
+ type SsgRecord =
80
+ | { kind: 'read'; routeId: string; path: string; field: string; key: string }
81
+ | { kind: 'headers'; routeId: string; path: string; names: string[] }
82
+
83
+ const DEFAULT_404 =
84
+ '<!doctype html>\n<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>404 Not Found</title></head><body><h1>404 Not Found</h1></body></html>\n'
85
+
86
+ /** A `_redirects` source as Cloudflare Pages matches it (review N4): the decoded path, with only what
87
+ * the file format or the decoding needs escaped (whitespace and control characters, and `%`, so a
88
+ * literal `%` is not read as an escape). Non-ASCII stays as UTF-8. */
89
+ export function redirectSource(path: string): string {
90
+ let decoded: string
91
+ try {
92
+ decoded = decodeURIComponent(path)
93
+ } catch {
94
+ decoded = path
95
+ }
96
+ return decoded.replace(/[\s%\u0000-\u001f\u007f]/gu, (c) => encodeURIComponent(c))
97
+ }
98
+
99
+ const text = (r: Rendered) => Buffer.from(r.body, 'base64').toString('utf8')
100
+ const excerpt = (s: string) => (s.length > 300 ? `${s.slice(0, 300)}…` : s).replace(/\s+/g, ' ').trim()
101
+
102
+ /** Spawns the render child against the dist at `dist`; the rendered responses in plan order and
103
+ * the loader records. `cwd` is the app root (its `brust.toml` is the server's config). */
104
+ async function render(dist: string, entry: string, cwd: string, paths: string[]): Promise<{ addr: string; rendered: Rendered[]; records: SsgRecord[] }> {
105
+ const stage = join(dist, '.ssg')
106
+ mkdirSync(stage, { recursive: true })
107
+ const plan = join(stage, 'plan.json')
108
+ const out = join(stage, 'rendered.json')
109
+ const logFile = join(stage, 'records.jsonl')
110
+ const progress = join(stage, 'progress.txt')
111
+ writeFileSync(plan, JSON.stringify(paths))
112
+ writeFileSync(logFile, '')
113
+ writeFileSync(progress, '')
114
+ const proc = Bun.spawn([process.execPath, join(import.meta.dir, 'ssg-render.ts')], {
115
+ cwd,
116
+ env: {
117
+ ...process.env,
118
+ BRUST_DIST_DIR: dist,
119
+ BRUST_APP_ENTRY: entry,
120
+ BRUST_SSG: '1',
121
+ BRUST_SSG_PLAN: plan,
122
+ BRUST_SSG_OUT: out,
123
+ BRUST_SSG_LOG: logFile,
124
+ BRUST_SSG_PROGRESS: progress,
125
+ BRUST_ADDR: '127.0.0.1',
126
+ BRUST_PORT: '',
127
+ },
128
+ stdout: 'pipe',
129
+ stderr: 'pipe',
130
+ })
131
+ // Review N3: the whole render is bounded too; past it the child (our own PID) is killed.
132
+ const totalMs = Number(process.env.BRUST_SSG_TIMEOUT_MS) || 600_000
133
+ let timer: ReturnType<typeof setTimeout> | undefined
134
+ const late = new Promise<'late'>((r) => {
135
+ timer = setTimeout(() => r('late'), totalMs)
136
+ })
137
+ const texts = Promise.all([new Response(proc.stdout).text(), new Response(proc.stderr).text()])
138
+ const first = await Promise.race([proc.exited, late])
139
+ clearTimeout(timer)
140
+ if (first === 'late') {
141
+ proc.kill('SIGKILL')
142
+ await proc.exited
143
+ const last = readFileSync(progress, 'utf8').trim().split('\n').pop() || '(before the first page)'
144
+ throw new BuildError('ssg-timeout', `the render took longer than ${totalMs} ms (BRUST_SSG_TIMEOUT_MS); it was rendering ${last}`)
145
+ }
146
+ const code = first
147
+ const [stdout, stderr] = await texts
148
+ const result = existsSync(out) ? (JSON.parse(readFileSync(out, 'utf8')) as { addr: string; pages?: Rendered[]; timeout?: { path: string; ms: number } }) : null
149
+ if (result?.timeout)
150
+ throw new BuildError('ssg-timeout', `GET ${result.timeout.path} did not answer within ${result.timeout.ms} ms (BRUST_SSG_PAGE_TIMEOUT_MS)`)
151
+ if (code !== 0 || !result?.pages) throw new BuildError('ssg-render', `the render server failed (exit ${code}):\n${(stderr || stdout).trim()}`)
152
+ const { addr, pages: rendered } = result as { addr: string; pages: Rendered[] }
153
+ const records = readFileSync(logFile, 'utf8')
154
+ .split('\n')
155
+ .filter((l) => l !== '')
156
+ .map((l) => JSON.parse(l) as SsgRecord)
157
+ rmSync(stage, { recursive: true, force: true })
158
+ return { addr, rendered, records }
159
+ }
160
+
161
+ /** Renders `plan` against the built dist at `dist` and writes `<dist>/static/`. Returns the report. */
162
+ export async function writeStatic(
163
+ dist: string,
164
+ o: { entry: string; appRoot: string; plan: StaticPlan; version: string; strict: boolean; log: (s: string) => void; /** The dir as the user will find it (the build renders into a temp dist). */ shownDir?: string },
165
+ ): Promise<StaticReport> {
166
+ const dir = join(dist, 'static')
167
+ rmSync(dir, { recursive: true, force: true })
168
+ const assetsStage = join(dist, '.ssg-assets')
169
+ const assets = layoutAssets(dist, assetsStage, o.version)
170
+ renameSync(join(assetsStage, 'assets'), dir)
171
+ rmSync(assetsStage, { recursive: true, force: true })
172
+ const warnings = [...assets.warnings]
173
+ const warn = (w: string) => {
174
+ warnings.push(w)
175
+ o.log(w)
176
+ }
177
+ for (const w of assets.warnings) o.log(w)
178
+
179
+ // R9.4: [cache] does not apply to static files, so the render must not need its adapter (a Redis
180
+ // that is not running at build time): the render reads a manifest without `cache`, and the dist
181
+ // keeps the real one for `brust start`.
182
+ const manifestFile = join(dist, 'manifest.json')
183
+ const manifest = readFileSync(manifestFile, 'utf8')
184
+ const parsed = JSON.parse(manifest) as { cache?: unknown }
185
+ if (parsed.cache) {
186
+ o.log('[brust] static: [cache] does not apply to static files (ignored while rendering)')
187
+ writeFileSync(manifestFile, `${JSON.stringify({ ...parsed, cache: null }, null, 2)}\n`)
188
+ }
189
+ let r: Awaited<ReturnType<typeof render>>
190
+ try {
191
+ r = await render(dist, o.entry, o.appRoot, o.plan.pages.map((p) => p.path))
192
+ } finally {
193
+ writeFileSync(manifestFile, manifest)
194
+ }
195
+ const { addr, rendered, records } = r
196
+ const report: StaticReport = { pages: [], redirects: [], skipped: o.plan.skipped, notFound: { file: '404.html', routeId: null }, warnings }
197
+ const write = (file: string, body: Buffer) => {
198
+ mkdirSync(dirname(join(dir, file)), { recursive: true })
199
+ writeFileSync(join(dir, file), body)
200
+ }
201
+ rendered.forEach((r, i) => {
202
+ const page: PlannedPage = o.plan.pages[i]!
203
+ const where = `GET ${page.path} (route ${page.routeId} ${page.pattern})`
204
+ const body = Buffer.from(r.body, 'base64')
205
+ if (text(r).includes(addr) || (r.headers.location ?? '').includes(addr))
206
+ throw new BuildError('ssg-render', `${where}: the response names the render server's loopback origin; a static page must not (build absolute URLs from a configured origin)`)
207
+ if (page.expect === 404) {
208
+ if (r.status !== 404) throw new BuildError('ssg-render', `${where}: the * route answered ${r.status}, want 404: ${excerpt(text(r))}`)
209
+ write('404.html', body)
210
+ report.notFound.routeId = page.routeId
211
+ return
212
+ }
213
+ if (r.status === 200) {
214
+ write(page.file, body)
215
+ report.pages.push({ path: page.path, file: page.file, routeId: page.routeId })
216
+ return
217
+ }
218
+ if (r.status >= 300 && r.status < 400 && r.headers.location) {
219
+ report.redirects.push({ from: page.path, to: r.headers.location, status: r.status })
220
+ return
221
+ }
222
+ throw new BuildError('ssg-render', `${where}: status ${r.status}, want 200 (or a redirect()): ${excerpt(text(r))}`)
223
+ })
224
+ if (o.plan.defaultNotFound) {
225
+ write('404.html', Buffer.from(DEFAULT_404))
226
+ warn("[brust] warning ssg-404 no '*' route: wrote a default 404.html (without one, Cloudflare Pages serves every unknown path as the home page)")
227
+ }
228
+ writeFileSync(join(dir, '_redirects'), report.redirects.map((r) => `${redirectSource(r.from)} ${r.to} ${r.status}\n`).join(''))
229
+
230
+ const seen = new Set<string>()
231
+ const reads: string[] = []
232
+ for (const rec of records) {
233
+ const leaf = o.plan.pages.find((p) => p.routeId === rec.routeId)
234
+ const route = `route ${rec.routeId}${leaf ? ` (${leaf.pattern})` : ''}`
235
+ if (rec.kind === 'headers') {
236
+ const key = `h ${rec.routeId} ${rec.names.join(',')}`
237
+ if (seen.has(key)) continue
238
+ seen.add(key)
239
+ warn(`[brust] warning ssg-headers ${route}: the loader's response headers (${rec.names.join(', ')}) are dropped: a static file carries none`)
240
+ continue
241
+ }
242
+ const key = `r ${rec.routeId} ${rec.field} ${rec.key}`
243
+ if (seen.has(key)) continue
244
+ seen.add(key)
245
+ const what = rec.key === '*' ? `lists req.${rec.field}` : `reads req.${rec.field}[${JSON.stringify(rec.key)}]`
246
+ reads.push(`${route} ${what} (at ${rec.path}): the static page is what a visitor with no headers, cookies or query sees`)
247
+ }
248
+ if (reads.length > 0 && o.strict) throw new BuildError('ssg-request-read', reads.join('\n'))
249
+ for (const r of reads) warn(`[brust] warning ssg-request-read ${r}`)
250
+
251
+ writeFileSync(join(dir, 'ssg.json'), `${JSON.stringify(report, null, 2)}\n`)
252
+ o.log(
253
+ `[brust] static: ${report.pages.length} page(s), ${report.redirects.length} redirect(s), 404.html${report.notFound.routeId ? '' : ' (default)'}${report.skipped.length ? `, ${report.skipped.length} route(s) ssg: false` : ''} -> ${o.shownDir ?? dir}`,
254
+ )
255
+ return report
256
+ }
257
+
258
+ export { NOT_FOUND_PATH }
@@ -0,0 +1,10 @@
1
+ // `buildTime(() => …)`: the explicit opt-in to evaluate a pure call once, at `brust build` (L2/H1).
2
+ // The compiler recognises the call only when it is imported from `@brust/core`; the closure may be
3
+ // `async` and may use package imports. At runtime (a per-request job, the server) it just runs the
4
+ // closure, so behaviour is identical wherever it is not folded away at build. It is a build error
5
+ // in code that reaches the browser.
6
+
7
+ /** Runs `fn`. At build the compiler evaluates it once and bakes the result into the template. */
8
+ export function buildTime<T>(fn: () => T): T {
9
+ return fn()
10
+ }
package/src/cf.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  // `@brust/core` under the `workerd` export condition (M4-CF, ruling c30e2633): the app-facing API a Worker can run.
2
2
  // Same names as `index.ts` minus what needs a host process: no `run`, no `loadConfig`. `cache.invalidate` goes through
3
3
  // the CF bundle's napi stub to the runtime the wasm glue installed at start (`server-handlers` `install`).
4
+ export { buildTime } from './build-time'
4
5
  export { cache } from './cache'
5
6
  export type { ComponentCacheOptions, InvalidateArgs, InvalidateResult } from './cache'
6
7
  export {
@@ -15,4 +16,4 @@ export {
15
16
  Outlet,
16
17
  redirect,
17
18
  } from './routes'
18
- export type { ComponentType, FlatRoute, HttpErrorOpts, HttpErrorTrigger, LoaderCtx, LoaderReq, Route, RouteCacheConfig, Verdict } from './routes'
19
+ export type { ComponentType, FlatRoute, HttpErrorOpts, HttpErrorTrigger, LoaderCtx, LoaderReq, Route, RouteCacheConfig, RouteSsgConfig, Verdict } from './routes'
package/src/cli.ts CHANGED
@@ -3,11 +3,13 @@
3
3
  // Exit codes: 0 ok, 1 build/boot error (`error <rule> <message>` / `[brust] …`), 2 usage.
4
4
  import { parseArgs } from 'node:util'
5
5
  import { BuildError, runBuild } from './build'
6
+ import { runBunDev } from './dev/bun'
6
7
  import { runDev } from './dev'
7
8
  import { run } from './run'
8
9
 
9
10
  const USAGE = `usage:
10
- brust build [entry=routes.tsx] [--out-dir dist] [--force] [--target bun|cloudflare] [--wasm-from-source]
11
+ brust build [entry=routes.tsx] [--out-dir dist] [--force] [--target bun|cloudflare|static] [--actions-only] [--strict] [--wasm-from-source] [--dev]
12
+ brust dev [entry=routes.tsx] [--port N] [--workers N] (Bun target: proxy + hot reload + inline TUI)
11
13
  brust dev [entry=routes.tsx] --target cloudflare [--out-dir dist] [--port N] [--wasm-from-source] [-- <wrangler args>]
12
14
  brust start [--port N] [--workers N] [--dist-dir dist] [--entry routes.tsx]
13
15
 
@@ -51,8 +53,11 @@ export async function main(argv: string[]): Promise<void> {
51
53
  port: { type: 'string' },
52
54
  workers: { type: 'string' },
53
55
  force: { type: 'boolean' },
56
+ strict: { type: 'boolean' },
54
57
  target: { type: 'string' },
55
58
  'wasm-from-source': { type: 'boolean' },
59
+ 'actions-only': { type: 'boolean' },
60
+ dev: { type: 'boolean' },
56
61
  help: { type: 'boolean', short: 'h' },
57
62
  },
58
63
  })
@@ -66,7 +71,10 @@ export async function main(argv: string[]): Promise<void> {
66
71
  }
67
72
  const str = (k: string) => values[k] as string | undefined
68
73
  const target = str('target')
69
- if (target !== undefined && target !== 'bun' && target !== 'cloudflare') usage(`--target must be bun or cloudflare (got ${JSON.stringify(target)})`)
74
+ if (target !== undefined && target !== 'bun' && target !== 'cloudflare' && target !== 'static')
75
+ usage(`--target must be bun, cloudflare or static (got ${JSON.stringify(target)})`)
76
+ if (values['actions-only'] === true && cmd !== 'build') usage('--actions-only only applies to brust build')
77
+ if (values.strict === true && (cmd !== 'build' || target !== 'static')) usage('--strict only applies to brust build --target static')
70
78
 
71
79
  if (cmd === 'build') {
72
80
  if (positionals.length > 1) usage(`build takes one entry (got ${positionals.join(' ')})`)
@@ -77,8 +85,11 @@ export async function main(argv: string[]): Promise<void> {
77
85
  entry: positionals[0] ?? 'routes.tsx',
78
86
  outDir: str('out-dir') ?? 'dist',
79
87
  force: values.force === true,
80
- target: target as 'bun' | 'cloudflare' | undefined,
88
+ target: target as 'bun' | 'cloudflare' | 'static' | undefined,
89
+ strict: values.strict === true,
81
90
  wasmFromSource: values['wasm-from-source'] === true,
91
+ actionsOnly: values['actions-only'] === true,
92
+ dev: values.dev === true,
82
93
  log: (s) => console.log(s),
83
94
  })
84
95
  } catch (e) {
@@ -92,8 +103,12 @@ export async function main(argv: string[]): Promise<void> {
92
103
  }
93
104
  if (cmd === 'dev') {
94
105
  if (positionals.length > 1) usage(`dev takes one entry (got ${positionals.join(' ')})`)
95
- if (target !== 'cloudflare') usage('brust dev: only --target cloudflare in this release')
96
106
  const port = intFlag('port', str('port'), 0)
107
+ if (target !== 'cloudflare') {
108
+ const workers = intFlag('workers', str('workers'), 1)
109
+ if (passthrough.length > 0) usage('brust dev: arguments after -- are for --target cloudflare (wrangler)')
110
+ process.exit(await runBunDev({ appRoot: process.cwd(), entry: positionals[0] ?? 'routes.tsx', ...(port !== undefined && { port }), ...(workers !== undefined && { workers }) }))
111
+ }
97
112
  try {
98
113
  process.exit(
99
114
  await runDev({