@brust/core 2.0.0-alpha.2 → 2.0.0-alpha.20
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.
- package/README.md +66 -6
- package/native/index.d.ts +89 -4
- package/native/index.js +60 -54
- package/package.json +25 -9
- package/src/actions/client.ts +22 -5
- package/src/actions/load.ts +2 -1
- package/src/actions/prefix.ts +24 -2
- package/src/actions-bridge.ts +29 -11
- package/src/browser.ts +3 -1
- package/src/build/actions-only.ts +86 -0
- package/src/build/build-eval.ts +332 -0
- package/src/build/build-icons.ts +69 -0
- package/src/build/bundle.ts +462 -52
- package/src/build/cf-assets.ts +83 -0
- package/src/build/cf-core.ts +90 -0
- package/src/build/cf-entry.ts +76 -0
- package/src/build/cf-wrangler.ts +169 -0
- package/src/build/cloudflare.ts +320 -0
- package/src/build/compile.ts +114 -5
- package/src/build/config.ts +294 -11
- package/src/build/css.ts +275 -0
- package/src/build/esm-resolve.ts +170 -0
- package/src/build/features.ts +114 -0
- package/src/build/index.ts +264 -20
- package/src/build/manifest.ts +85 -7
- package/src/build/pkg-src.ts +514 -0
- package/src/build/recognised.ts +19 -0
- package/src/build/scan.ts +71 -20
- package/src/build/server-only.ts +39 -0
- package/src/build/ssg-render.ts +65 -0
- package/src/build/ssg.ts +146 -0
- package/src/build/static-worker.ts +91 -0
- package/src/build/static.ts +258 -0
- package/src/build/tailwind.ts +117 -0
- package/src/build/tsconfig-paths.ts +67 -0
- package/src/build-time.ts +10 -0
- package/src/cache-adapter/bridge.ts +91 -0
- package/src/cache-adapter/conformance.ts +226 -0
- package/src/cache-adapter/index.ts +10 -0
- package/src/cache-adapter/load.ts +144 -0
- package/src/cache-adapter/memory.ts +229 -0
- package/src/cache-adapter/runtime.ts +124 -0
- package/src/cache-adapter/types.ts +96 -0
- package/src/cache-adapter/workers.ts +118 -0
- package/src/cache.ts +4 -1
- package/src/cf.ts +19 -0
- package/src/cli.ts +71 -2
- package/src/config.ts +127 -25
- package/src/css-modules.d.ts +8 -0
- package/src/dev/bun.ts +371 -0
- package/src/dev/client.ts +92 -0
- package/src/dev/devtools-data.ts +23 -0
- package/src/dev/devtools.ts +356 -0
- package/src/dev/diag.ts +30 -0
- package/src/dev/proxy.ts +236 -0
- package/src/dev/tui.ts +144 -0
- package/src/dev/watch.ts +130 -0
- package/src/dev.ts +97 -0
- package/src/handlers.ts +282 -0
- package/src/index.ts +3 -1
- package/src/native.ts +38 -1
- package/src/routes.ts +20 -1
- package/src/run.ts +59 -12
- package/src/server-handlers.ts +32 -0
- package/src/shadcn/init.ts +513 -0
- package/src/shadcn/jsonc.ts +129 -0
- package/src/shadcn/registry.ts +149 -0
- package/src/worker.ts +127 -245
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
// F189: `Bun.resolveSync` answers the CJS `main` of a package that has both (recharts: `main` is a CJS build, `module`
|
|
2
|
+
// the ES build), so a package resolved from a directory the bundler does not walk (a package's own, for what its source
|
|
3
|
+
// imports) became a second, CJS copy beside the ESM one every other island imports. Re-implementing the bundler's
|
|
4
|
+
// choice drifts (conditions per target, the `browser` field, `development`, `module` before `import`), so this asks
|
|
5
|
+
// the bundler itself: a throwaway `Bun.build` of a virtual file placed in `from` that imports `spec`, with the same
|
|
6
|
+
// `target`; the first module the build loads from outside that file is the answer. Equal to the native pick by
|
|
7
|
+
// construction. It runs in a child process: a `Bun.build` started inside a plugin callback of another build deadlocks.
|
|
8
|
+
// Anything it cannot resolve falls back to `Bun.resolveSync`, which is today's answer, and says so (F222).
|
|
9
|
+
import { createHash } from 'node:crypto'
|
|
10
|
+
import { existsSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from 'node:fs'
|
|
11
|
+
import { dirname, join, sep } from 'node:path'
|
|
12
|
+
import { BuildError } from './errors'
|
|
13
|
+
|
|
14
|
+
/** A specifier relative to its importer: `./x`, `../x` and the bare `.` / `..` (a directory). The one test every resolver path uses (F218, F244). */
|
|
15
|
+
export const RELATIVE_SPEC = /^\.\.?(\/|$)/
|
|
16
|
+
|
|
17
|
+
export type ResolveTarget = 'bun' | 'browser'
|
|
18
|
+
|
|
19
|
+
/** What a build besides `target` and `define` tells the bundler about resolution, and where the probe runs. */
|
|
20
|
+
export interface ResolveOpts {
|
|
21
|
+
/** The build's `conditions` (`--target cloudflare`: workerd, worker, browser). Part of the answer, so part of the key. */
|
|
22
|
+
conditions?: string[]
|
|
23
|
+
/** The app root: the probe's working directory (F221) and the home of the cross-build cache (F224). */
|
|
24
|
+
appRoot?: string
|
|
25
|
+
/** Kills a probe that does not answer; default `RESOLVE_TIMEOUT_MS`. */
|
|
26
|
+
timeoutMs?: number
|
|
27
|
+
/** Where a fallback is named (F222); default: a `warning` line on stderr. */
|
|
28
|
+
warn?: (message: string) => void
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** `BRUST_RESOLVE_TIMEOUT_MS` or 30 s: a healthy probe answers in well under a second. */
|
|
32
|
+
export const RESOLVE_TIMEOUT_MS = Number(process.env.BRUST_RESOLVE_TIMEOUT_MS) > 0 ? Number(process.env.BRUST_RESOLVE_TIMEOUT_MS) : 30_000
|
|
33
|
+
|
|
34
|
+
const cache = new Map<string, string>()
|
|
35
|
+
|
|
36
|
+
/** Forgets the in-process answers and warnings (tests; the disk cache stays). */
|
|
37
|
+
export function clearResolveCache(): void {
|
|
38
|
+
cache.clear()
|
|
39
|
+
warned.clear()
|
|
40
|
+
disks.clear()
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
// argv: [target, entry, spec, define JSON, conditions JSON]; prints the resolved path. The define is the build's own:
|
|
44
|
+
// `NODE_ENV` flips Bun's `development` condition, so a probe without it picks another file than the build does. The
|
|
45
|
+
// same goes for `conditions`.
|
|
46
|
+
const PROBE = `
|
|
47
|
+
const [target, entry, spec, define, conditions] = process.argv.slice(1)
|
|
48
|
+
const source = 'import ' + JSON.stringify(spec) + '\\n'
|
|
49
|
+
let found
|
|
50
|
+
await Bun.build({
|
|
51
|
+
entrypoints: [entry], target, write: false, define: JSON.parse(define), conditions: JSON.parse(conditions), files: { [entry]: source },
|
|
52
|
+
plugins: [{ name: 'o', setup(b) { b.onLoad({ filter: /./ }, (a) => {
|
|
53
|
+
if (a.path === entry) return { contents: source, loader: 'ts' }
|
|
54
|
+
found ??= a.path
|
|
55
|
+
return { contents: '', loader: 'js' }
|
|
56
|
+
}) } }],
|
|
57
|
+
})
|
|
58
|
+
if (found) process.stdout.write(found)
|
|
59
|
+
`
|
|
60
|
+
|
|
61
|
+
const defaultWarn = (m: string) => console.warn(`warning resolve-fallback ${m}`)
|
|
62
|
+
const warned = new Set<string>()
|
|
63
|
+
|
|
64
|
+
/** `spec` as the bundler of `target` resolves it from the directory `from`. */
|
|
65
|
+
export function resolveNative(spec: string, from: string, target: ResolveTarget, define: Record<string, string> = {}, opts: ResolveOpts = {}): string {
|
|
66
|
+
const defs = JSON.stringify(define)
|
|
67
|
+
const conds = JSON.stringify(opts.conditions ?? [])
|
|
68
|
+
const key = `${target}\0${from}\0${spec}\0${defs}\0${conds}`
|
|
69
|
+
const hit = cache.get(key)
|
|
70
|
+
if (hit !== undefined) return hit
|
|
71
|
+
const disk = opts.appRoot !== undefined ? diskCache(opts.appRoot, `${target}\0${defs}\0${conds}`) : undefined
|
|
72
|
+
const saved = disk?.get(`${from}\0${spec}`, from)
|
|
73
|
+
if (saved !== undefined) {
|
|
74
|
+
cache.set(key, saved)
|
|
75
|
+
return saved
|
|
76
|
+
}
|
|
77
|
+
const timeout = opts.timeoutMs ?? RESOLVE_TIMEOUT_MS
|
|
78
|
+
const r = Bun.spawnSync([process.execPath, '-e', PROBE, target, join(from, '__brust_resolve__.ts'), spec, defs, conds], { cwd: opts.appRoot ?? from, stdout: 'pipe', stderr: 'pipe', timeout, killSignal: 'SIGKILL' })
|
|
79
|
+
const out = r.exitCode === 0 ? r.stdout.toString() : ''
|
|
80
|
+
let path = out
|
|
81
|
+
if (path === '') {
|
|
82
|
+
// The probe did not answer: today's answer (`Bun.resolveSync`) stands, and the build output says why.
|
|
83
|
+
const why = r.exitCode === null || r.signalCode ? `the probe did not answer within ${timeout} ms` : r.exitCode !== 0 ? `the probe failed (${r.stderr.toString().trim().split('\n')[0] || `exit ${r.exitCode}`})` : 'the probe resolved nothing'
|
|
84
|
+
// F242: `Bun.resolveSync` answers with the bun/node conditions. For a browser-target build (client chunks, the Worker)
|
|
85
|
+
// that can be a node-only build of the package, so it is not an answer there.
|
|
86
|
+
if (target === 'browser') throw new BuildError('resolve-fallback', `cannot resolve "${spec}" from ${from} for a browser-target build: ${why}; the runtime resolver would pick the bun/node conditions, so there is no fallback`)
|
|
87
|
+
path = Bun.resolveSync(spec, from)
|
|
88
|
+
const msg = `${spec} from ${from} (${target}): ${why}; used Bun.resolveSync -> ${path}`
|
|
89
|
+
if (!warned.has(msg)) {
|
|
90
|
+
warned.add(msg)
|
|
91
|
+
;(opts.warn ?? defaultWarn)(msg)
|
|
92
|
+
}
|
|
93
|
+
} else disk?.set(`${from}\0${spec}`, path, from)
|
|
94
|
+
cache.set(key, path)
|
|
95
|
+
return path
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
// F224: a probe is a child process plus a `Bun.build`: ~100-300 ms each, once per (package dir, specifier) in a build,
|
|
99
|
+
// and again in every build. The answers are kept across builds in `<appRoot>/.brust/resolve-cache.json`, valid for one
|
|
100
|
+
// lockfile and one Bun, per (target, define, conditions); an entry is dropped when its file is gone or the nearest
|
|
101
|
+
// `package.json` above it changed (a linked workspace package edits without touching the lockfile).
|
|
102
|
+
interface Saved { path: string; pkg: string; mtime: number; from: string; fromMtime: number }
|
|
103
|
+
const LOCKS = ['bun.lock', 'bun.lockb', 'package-lock.json', 'pnpm-lock.yaml', 'yarn.lock']
|
|
104
|
+
const disks = new Map<string, DiskCache | null>()
|
|
105
|
+
|
|
106
|
+
class DiskCache {
|
|
107
|
+
private entries: Record<string, Saved> = {}
|
|
108
|
+
constructor(private file: string, private salt: string, private appRoot: string) {
|
|
109
|
+
try {
|
|
110
|
+
const j = JSON.parse(readFileSync(file, 'utf8'))
|
|
111
|
+
if (j.salt === salt) this.entries = j.entries ?? {}
|
|
112
|
+
} catch {}
|
|
113
|
+
}
|
|
114
|
+
get(k: string, from: string): string | undefined {
|
|
115
|
+
const e = this.entries[k]
|
|
116
|
+
if (!e) return undefined
|
|
117
|
+
try {
|
|
118
|
+
// F245: the file is trusted as written, so every answer is re-validated: it must lie inside the app or in a
|
|
119
|
+
// `node_modules`, and still be a file; else the entry is dropped and the probe asks again.
|
|
120
|
+
const [fromPkg, fromMtime] = nearestPackageJson(from)
|
|
121
|
+
if (this.plausible(e.path) && statSync(e.path).isFile() && (e.pkg === '' || statSync(e.pkg).mtimeMs === e.mtime) && e.from === fromPkg && e.fromMtime === fromMtime) return e.path
|
|
122
|
+
} catch {}
|
|
123
|
+
delete this.entries[k]
|
|
124
|
+
return undefined
|
|
125
|
+
}
|
|
126
|
+
set(k: string, path: string, from: string): void {
|
|
127
|
+
const [pkg, mtime] = nearestPackageJson(dirname(path))
|
|
128
|
+
const [fromPkg, fromMtime] = nearestPackageJson(from)
|
|
129
|
+
this.entries[k] = { path, pkg, mtime, from: fromPkg, fromMtime }
|
|
130
|
+
try {
|
|
131
|
+
mkdirSync(dirname(this.file), { recursive: true })
|
|
132
|
+
const tmp = `${this.file}.${process.pid}.tmp`
|
|
133
|
+
writeFileSync(tmp, JSON.stringify({ salt: this.salt, entries: this.entries }))
|
|
134
|
+
renameSync(tmp, this.file)
|
|
135
|
+
} catch {}
|
|
136
|
+
}
|
|
137
|
+
private plausible(path: string): boolean {
|
|
138
|
+
return path.startsWith(this.appRoot + sep) || path.split(sep).includes('node_modules')
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/** The nearest `package.json` at or above `dir` and its mtime (`['', 0]` when there is none). */
|
|
143
|
+
function nearestPackageJson(dir: string): [string, number] {
|
|
144
|
+
for (let d = dir; ; d = dirname(d)) {
|
|
145
|
+
const p = join(d, 'package.json')
|
|
146
|
+
if (existsSync(p)) return [p, statSync(p).mtimeMs]
|
|
147
|
+
if (dirname(d) === d) return ['', 0]
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** The cache for this app and (target, define, conditions), or none when no lockfile pins the install. */
|
|
152
|
+
function diskCache(appRoot: string, scope: string): DiskCache | undefined {
|
|
153
|
+
const id = `${appRoot}\0${scope}`
|
|
154
|
+
const have = disks.get(id)
|
|
155
|
+
if (have !== undefined) return have ?? undefined
|
|
156
|
+
let lock: string | undefined
|
|
157
|
+
for (let d = appRoot; lock === undefined; d = dirname(d)) {
|
|
158
|
+
lock = LOCKS.map((l) => join(d, l)).find((f) => existsSync(f))
|
|
159
|
+
if (dirname(d) === d) break
|
|
160
|
+
}
|
|
161
|
+
let made: DiskCache | null = null
|
|
162
|
+
if (lock !== undefined) {
|
|
163
|
+
try {
|
|
164
|
+
const salt = createHash('sha256').update(Bun.version).update(readFileSync(lock)).update(scope).digest('hex')
|
|
165
|
+
made = new DiskCache(join(appRoot, '.brust', `resolve-cache-${createHash('sha256').update(scope).digest('hex').slice(0, 8)}.json`), salt, appRoot)
|
|
166
|
+
} catch {}
|
|
167
|
+
}
|
|
168
|
+
disks.set(id, made)
|
|
169
|
+
return made ?? undefined
|
|
170
|
+
}
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
// Which client-runtime feature modules a component needs (L33, R35.2). The compiler's output is the source of truth:
|
|
2
|
+
// a native component's template carries one `x-*` attribute per directive it uses, a react-tier component is an island.
|
|
3
|
+
// The set is written per component into the manifest; the server unions it over a route's components and links the
|
|
4
|
+
// core plus exactly those modules. `packages/runtime-dom/README.md` ("Feature modules") owns the module list and the rule.
|
|
5
|
+
import { BuildError } from './errors'
|
|
6
|
+
|
|
7
|
+
/** Feature modules of `@brust/runtime-dom/features/*` the browser build ships, in load order. */
|
|
8
|
+
export const RUNTIME_FEATURES = ['basics', 'if', 'for', 'model', 'html', 'island', 'collection'] as const
|
|
9
|
+
export type RuntimeFeature = (typeof RUNTIME_FEATURES)[number]
|
|
10
|
+
|
|
11
|
+
/** Directive attribute → the module that binds it. `null`: handled by the core (host, props, inert-markup marker). */
|
|
12
|
+
export function featureOfAttr(attr: string): RuntimeFeature | null | undefined {
|
|
13
|
+
switch (attr) {
|
|
14
|
+
case 'x-data':
|
|
15
|
+
case 'x-props':
|
|
16
|
+
case 'x-props-bind':
|
|
17
|
+
case 'x-raw':
|
|
18
|
+
return null
|
|
19
|
+
case 'x-text':
|
|
20
|
+
case 'x-show':
|
|
21
|
+
case 'x-ref':
|
|
22
|
+
return 'basics'
|
|
23
|
+
case 'x-if':
|
|
24
|
+
case 'x-for':
|
|
25
|
+
case 'x-model':
|
|
26
|
+
case 'x-html':
|
|
27
|
+
return attr.slice(2) as RuntimeFeature
|
|
28
|
+
case 'x-collection-root':
|
|
29
|
+
case 'x-collection-item':
|
|
30
|
+
case 'x-collection-use':
|
|
31
|
+
return 'collection'
|
|
32
|
+
default:
|
|
33
|
+
return /^x-(bind|on|prop)-/.test(attr) ? 'basics' : undefined
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** The template with every jinja tag (`{{ … }}`, `{% … %}`, `{# … #}`) replaced by a space, string literals inside them
|
|
38
|
+
* read as strings: a printed value such as shadcn's `has-[>svg]:px-3` (a folded class, F149) holds a `>` or a quote that
|
|
39
|
+
* would otherwise end the element's tag early and hide the directives after it. A directive is never inside a jinja tag. */
|
|
40
|
+
export function withoutJinja(template: string): string {
|
|
41
|
+
let out = ''
|
|
42
|
+
let i = 0
|
|
43
|
+
while (i < template.length) {
|
|
44
|
+
const open = template.indexOf('{', i)
|
|
45
|
+
const kind = open < 0 ? '' : template[open + 1]
|
|
46
|
+
if (open < 0) {
|
|
47
|
+
out += template.slice(i)
|
|
48
|
+
break
|
|
49
|
+
}
|
|
50
|
+
if (kind !== '{' && kind !== '%' && kind !== '#') {
|
|
51
|
+
out += template.slice(i, open + 1)
|
|
52
|
+
i = open + 1
|
|
53
|
+
continue
|
|
54
|
+
}
|
|
55
|
+
out += template.slice(i, open)
|
|
56
|
+
const close = kind === '{' ? '}}' : `${kind}}`
|
|
57
|
+
let j = open + 2
|
|
58
|
+
let quote = ''
|
|
59
|
+
for (; j < template.length; j++) {
|
|
60
|
+
const ch = template[j]!
|
|
61
|
+
if (quote) {
|
|
62
|
+
if (ch === '\\') j++
|
|
63
|
+
else if (ch === quote) quote = ''
|
|
64
|
+
} else if (kind !== '#' && (ch === '"' || ch === "'")) quote = ch
|
|
65
|
+
else if (template.startsWith(close, j)) break
|
|
66
|
+
}
|
|
67
|
+
out += ' '
|
|
68
|
+
i = j + close.length
|
|
69
|
+
}
|
|
70
|
+
return out
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** The `x-*` attribute names on the elements of a template (tags only: prose that mentions `x-for` binds nothing). */
|
|
74
|
+
export function directiveAttrs(template: string): Set<string> {
|
|
75
|
+
const out = new Set<string>()
|
|
76
|
+
template = withoutJinja(template)
|
|
77
|
+
for (const tag of template.matchAll(/<[a-zA-Z][\w-]*((?:[^>"']|"[^"]*"|'[^']*')*)>/g))
|
|
78
|
+
for (const a of tag[1]!.matchAll(/(?:^|\s)(x-[a-z][a-z0-9-]*)(?==|\s|$|\/)/g)) out.add(a[1]!)
|
|
79
|
+
return out
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* The feature modules `template` needs, sorted in load order (`react` = the component is an island: `island`).
|
|
84
|
+
* An `x-*` attribute no module binds is a build error (a compiler that learned a directive before the runtime did):
|
|
85
|
+
* never a silent no-op in the browser.
|
|
86
|
+
*/
|
|
87
|
+
export function featuresOf(id: string, template: string, react: boolean): RuntimeFeature[] {
|
|
88
|
+
const need = new Set<RuntimeFeature>()
|
|
89
|
+
if (react) need.add('island')
|
|
90
|
+
for (const attr of directiveAttrs(template)) {
|
|
91
|
+
const f = featureOfAttr(attr)
|
|
92
|
+
if (f === undefined) throw new BuildError('runtime-feature-missing', `${id}: the template uses ${attr}, which no client runtime feature binds`)
|
|
93
|
+
if (f !== null) need.add(f)
|
|
94
|
+
}
|
|
95
|
+
return RUNTIME_FEATURES.filter((f) => need.has(f))
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** Matches the `/_brust/<file>` URL of `file` in a built chunk's text. */
|
|
99
|
+
const mentions = (text: string, file: string) => text.includes(`/_brust/${file}`)
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* Whether the built client file `entry` (`client/<file>`) imports the store module `storeFile`, directly or through the
|
|
103
|
+
* shared `chunk-*.js` files it imports. A component whose chunk does gets `store` in its features: the page preloads
|
|
104
|
+
* the module (the chunk imports it itself, so it has no script tag).
|
|
105
|
+
*/
|
|
106
|
+
export function importsStore(read: (rel: string) => string | undefined, entry: string, storeFile: string, seen = new Set<string>()): boolean {
|
|
107
|
+
if (seen.has(entry)) return false
|
|
108
|
+
seen.add(entry)
|
|
109
|
+
const text = read(entry)
|
|
110
|
+
if (text === undefined) return false
|
|
111
|
+
if (mentions(text, storeFile)) return true
|
|
112
|
+
for (const m of text.matchAll(/(?:from|import)\s*"\.\/([^"]+\.js)"/g)) if (importsStore(read, `client/${m[1]}`, storeFile, seen)) return true
|
|
113
|
+
return false
|
|
114
|
+
}
|
package/src/build/index.ts
CHANGED
|
@@ -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 {
|
|
13
|
-
import { type
|
|
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 {
|
|
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
|
|
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
|
-
|
|
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
|
-
|
|
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 {
|
|
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
|
-
|
|
282
|
+
componentIssue: o.componentIssue,
|
|
283
|
+
loadWrites,
|
|
284
|
+
runtimeImport: runtimeUrls.core,
|
|
165
285
|
serverOnly: o.serverOnly,
|
|
166
|
-
|
|
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
|
|
173
|
-
const
|
|
174
|
-
|
|
175
|
-
|
|
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
|
+
}
|