@weft-js/start 0.0.0-stage → 0.1.0

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 (75) hide show
  1. package/LICENSE +16 -0
  2. package/README.md +41 -2
  3. package/package.json +107 -4
  4. package/src/app.mjs +82 -0
  5. package/src/auth/better-auth.ts +58 -0
  6. package/src/auth/drizzle.ts +17 -0
  7. package/src/auth.ts +47 -0
  8. package/src/boot.ts +44 -0
  9. package/src/builtin.tsx +19 -0
  10. package/src/bus/postgres.ts +91 -0
  11. package/src/bus.ts +48 -0
  12. package/src/capture.d.mts +1 -0
  13. package/src/capture.mjs +15 -0
  14. package/src/changes-sql.d.mts +14 -0
  15. package/src/changes-sql.mjs +99 -0
  16. package/src/changes.ts +253 -0
  17. package/src/channel-fake.ts +55 -0
  18. package/src/channel.ts +616 -0
  19. package/src/client.tsx +20 -0
  20. package/src/contract.mjs +308 -0
  21. package/src/data.ts +929 -0
  22. package/src/db/bun-sqlite.d.ts +10 -0
  23. package/src/db/changes-mysql.ts +86 -0
  24. package/src/db/changes-postgres.ts +159 -0
  25. package/src/db/changes-sqlite.ts +116 -0
  26. package/src/db/core.ts +63 -0
  27. package/src/db/index.ts +27 -0
  28. package/src/db/mysql.ts +67 -0
  29. package/src/db/postgres.ts +65 -0
  30. package/src/db/sqlite.ts +139 -0
  31. package/src/derive.d.mts +16 -0
  32. package/src/derive.mjs +140 -0
  33. package/src/dev-runtime.mjs +42 -0
  34. package/src/exec.ts +519 -0
  35. package/src/extension.ts +38 -0
  36. package/src/first-paint.ts +57 -0
  37. package/src/form.tsx +134 -0
  38. package/src/gate.css +6 -0
  39. package/src/hub.ts +822 -0
  40. package/src/index.ts +106 -0
  41. package/src/inline.mjs +2 -0
  42. package/src/inspect.mjs +280 -0
  43. package/src/link.ts +456 -0
  44. package/src/list-drizzle.ts +50 -0
  45. package/src/list.ts +224 -0
  46. package/src/listen.ts +28 -0
  47. package/src/live-fake.ts +42 -0
  48. package/src/live-target.mjs +144 -0
  49. package/src/live.ts +499 -0
  50. package/src/media.ts +43 -0
  51. package/src/migrations.mjs +19 -0
  52. package/src/mux-session.ts +6 -0
  53. package/src/mux.ts +135 -0
  54. package/src/og/DefaultCard.tsx +60 -0
  55. package/src/og/fonts.mjs +64 -0
  56. package/src/og/images.mjs +54 -0
  57. package/src/og/index.mjs +146 -0
  58. package/src/og/native.mjs +29 -0
  59. package/src/range.mjs +19 -0
  60. package/src/router.ts +149 -0
  61. package/src/routes.mjs +142 -0
  62. package/src/run.tsx +198 -0
  63. package/src/rust.ts +333 -0
  64. package/src/server.tsx +1014 -0
  65. package/src/shape.d.mts +3 -0
  66. package/src/shape.mjs +73 -0
  67. package/src/share-server.ts +208 -0
  68. package/src/share.ts +503 -0
  69. package/src/sheets.mjs +75 -0
  70. package/src/sidecar.mjs +503 -0
  71. package/src/socket.ts +389 -0
  72. package/src/stream.ts +13 -0
  73. package/src/verify.ts +251 -0
  74. package/src/view.tsx +47 -0
  75. package/src/vite.mjs +899 -0
@@ -0,0 +1,503 @@
1
+ // The sidecar supervisor (research 36 §5): what `weft dev`, `weft build`, `weft start` and `weft check` do for the Rust
2
+ // behind `remote()`, and for `native()`'s libraries (research 39). It runs in the CLI, never in the server bundle:
3
+ // `remote()` is only `fetch`, so a built server runs anywhere, and a sidecar deployed on its own is one environment
4
+ // variable away.
5
+ //
6
+ // dev cargo build, then a stable local proxy in front of the current child. A change under the crate, or a contract
7
+ // change from a server module, builds a new binary, starts it, health-checks it and swaps the proxy; the old
8
+ // child drains and goes. A failed build leaves the old child serving and says why.
9
+ // build cargo build --release, then the binaries run while Nitro prerenders (a card's `load` may read one), then
10
+ // they go to `.output/rust/`, with a manifest of each one's contract hash.
11
+ // start each binary on a fixed local port, restarted with backoff if it dies. The web server keeps serving; calls in
12
+ // the gap fail as R107.
13
+ // check cargo check, with errors mapped to the function they belong to (R103).
14
+ //
15
+ // `native()` has no child and no proxy. dev: each build is a new file under `.weft/native/`, and the manifest beside it
16
+ // says which, so the next call loads it in place: an addon can't be unloaded, and needn't be. build: an addon and a
17
+ // `.wasm` next to the server, in `.output/server/rust/`, so whatever moves the server moves them too.
18
+
19
+ import { spawn } from 'node:child_process'
20
+ import { copyFileSync, cpSync, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, watch, writeFileSync } from 'node:fs'
21
+ import { createServer, request as httpRequest, Agent } from 'node:http'
22
+ import { randomBytes } from 'node:crypto'
23
+ import { basename, join, relative, resolve } from 'node:path'
24
+ import { writeContract } from './contract.mjs'
25
+ import { isServerModule } from './vite.mjs'
26
+
27
+ /** The app names a sidecar: a server module imports `remote`. Nothing else here runs for an app that doesn't. */
28
+ export function usesRemote(root) {
29
+ const src = join(root, 'src')
30
+ if (!existsSync(src)) return false
31
+ return readdirSync(src, { recursive: true, withFileTypes: true }).some(f => f.isFile() && /\.[cm]?[jt]sx?$/.test(f.name) && /['"]@weft-js\/start\/rust['"]/.test(readFileSync(join(f.parentPath, f.name), 'utf8')))
32
+ }
33
+
34
+ /** Same spelling as `urlVariable` in rust.ts, which can't share a module with this one: it ships in the server bundle. */
35
+ export const urlVariable = service => `WEFT_RUST_${service.toUpperCase().replaceAll('-', '_')}_URL`
36
+
37
+ const external = (rust, service) => rust?.services?.[service]?.external === true
38
+ /** The crate folder of a service. */
39
+ export const crateDir = (root, rust, service) => resolve(root, rust?.services?.[service]?.crate ?? `crates/${service}`)
40
+
41
+ /** The services in a contract that have a crate here. */
42
+ const buildable = (contract, rust) => Object.keys(contract.services ?? {}).filter(s => !external(rust, s))
43
+ const isNative = (contract, service) => contract.services?.[service]?.kind === 'native'
44
+ const WASM = 'wasm32-unknown-unknown'
45
+
46
+ // ---- cargo --------------------------------------------------------------------------------------------------------
47
+
48
+ function run(cmd, args, { cwd, env, onLine }) {
49
+ return new Promise(ok => {
50
+ let child
51
+ try {
52
+ child = spawn(cmd, args, { cwd, env: { ...process.env, ...env }, stdio: ['ignore', 'pipe', 'pipe'] })
53
+ } catch (e) {
54
+ ok({ code: 127, stdout: '', stderr: e.message, missing: true })
55
+ return
56
+ }
57
+ let stdout = '', stderr = ''
58
+ child.stdout.on('data', d => { stdout += d })
59
+ child.stderr.on('data', d => {
60
+ stderr += d
61
+ onLine?.(`${d}`)
62
+ })
63
+ child.on('error', e => ok({ code: 127, stdout, stderr: e.message, missing: e.code === 'ENOENT' }))
64
+ child.on('close', code => ok({ code, stdout, stderr }))
65
+ })
66
+ }
67
+
68
+ const pascal = name => name[0].toUpperCase() + name.slice(1)
69
+ const snake = name => name.replace(/[A-Z]/g, (c, i) => `${i ? '_' : ''}${c.toLowerCase()}`)
70
+
71
+ /**
72
+ * cargo's JSON messages as diagnostics. An error that names a contract function's types or method is R103, with the
73
+ * function's id, so it points at the TS edit that caused it (research 06 §7); any other is R109.
74
+ */
75
+ export function readCargo(stdout, { contract, service, root, dir }) {
76
+ const fns = (contract?.functions ?? []).filter(f => f.impl?.service === service)
77
+ const names = fns.map(f => ({ id: f.id, re: new RegExp(`\\b(${pascal(f.name)}\\w*|${snake(f.name)})\\b`) }))
78
+ const diagnostics = []
79
+ let exe, lib, ok = false
80
+ for (const line of stdout.split('\n')) {
81
+ if (!line.startsWith('{')) continue
82
+ let m
83
+ try { m = JSON.parse(line) } catch { continue }
84
+ if (m.reason === 'compiler-artifact' && m.executable && m.target?.kind?.includes('bin')) exe = m.executable
85
+ if (m.reason === 'compiler-artifact' && m.target?.kind?.includes('cdylib')) lib = m.filenames?.find(f => /\.(dylib|so|dll|wasm)$/.test(f))
86
+ if (m.reason === 'build-finished') ok = m.success
87
+ if (m.reason !== 'compiler-message' || m.message?.level !== 'error' || !m.message.code) continue
88
+ const text = m.message.rendered ?? m.message.message
89
+ const hit = names.find(n => n.re.test(text))
90
+ const at = m.message.spans?.find(s => s.is_primary) ?? m.message.spans?.[0]
91
+ const file = at && relative(root, resolve(dir, at.file_name)).replaceAll('\\', '/')
92
+ diagnostics.push({
93
+ code: hit ? 'R103' : 'R109', severity: 'error', ...(hit && { function: hit.id }), file: file ?? '.weft/contract.json',
94
+ span: at ? [at.line_start, at.column_start, at.line_end, at.column_end] : [1, 1, 1, 1],
95
+ why: hit ? `\`${hit.id}\`: the Rust no longer matches the contract: ${m.message.message}` : `\`${service}\` doesn't compile: ${m.message.message}`,
96
+ rendered: text,
97
+ })
98
+ }
99
+ return { ok, exe, lib, diagnostics }
100
+ }
101
+
102
+ /** `verb`: `build` or `check`. Failure names what to fix: a build script's panic is already R103 with the fix. */
103
+ export async function cargo(verb, { root, dir, service, contract, release, target, onLine }) {
104
+ const args = [verb, '--message-format=json', ...(release ? ['--release'] : []), ...(target ? ['--target', target] : [])]
105
+ const env = { WEFT_CONTRACT: join(root, '.weft', 'contract.json'), ...(target === WASM && { CARGO_TARGET_WASM32_UNKNOWN_UNKNOWN_RUSTFLAGS: '-C target-feature=+simd128' }) }
106
+ const r = await run('cargo', args, { cwd: dir, env, onLine })
107
+ if (r.missing) return { ok: false, diagnostics: [{ code: 'R109', severity: 'error', file: 'package.json', span: [1, 1, 1, 1], why: `\`${service}\` is Rust you opted into, so it needs \`cargo\`, and it isn't on PATH. Install it from rustup.rs, or set \`external: true\` for a sidecar built elsewhere. The rest of weft doesn't need Rust.` }] }
108
+ const read = readCargo(r.stdout, { contract, service, root, dir })
109
+ if (r.code === 0) return read
110
+ if (!read.diagnostics.length) {
111
+ const panic = /R103: ([^\n]+)/.exec(r.stderr)?.[1]
112
+ read.diagnostics.push({ code: panic ? 'R103' : 'R109', severity: 'error', file: relative(root, dir).replaceAll('\\', '/') + '/Cargo.toml', span: [1, 1, 1, 1], why: panic ?? `cargo ${verb} failed in \`${service}\`:\n${r.stderr.trim().split('\n').slice(-12).join('\n')}` })
113
+ }
114
+ return { ...read, ok: false }
115
+ }
116
+
117
+ /** R104 for a `.wasm` that won't build: a warning unless the build needs it. `error`: the preset has no other way to run. */
118
+ export async function checkWasm({ root, dir, service, contract, preset, rust, build }) {
119
+ if (rust?.services?.[service]?.wasm === false) return { diagnostics: [] }
120
+ const r = await cargo(build ? 'build' : 'check', { root, dir, service, contract, target: WASM, release: build })
121
+ if (r.ok) return { lib: r.lib, diagnostics: [] }
122
+ const missing = r.diagnostics.find(d => /can't find crate for `(std|core)`|target may not be installed/.test(`${d.why}${d.rendered ?? ''}`))
123
+ const why = missing ? `\`rustup target add ${WASM}\`: this toolchain can't build \`${service}\`'s WASM fallback` : `\`${service}\` has no WASM fallback: ${r.diagnostics[0]?.why ?? 'the build failed'}`
124
+ const needed = preset && !/^(node|bun|deno[-_]server)/.test(preset)
125
+ return { diagnostics: [{ code: 'R104', severity: needed ? 'error' : 'warning', file: relative(root, dir).replaceAll('\\', '/') + '/Cargo.toml', span: [1, 1, 1, 1], why: `${why}. An addon loads on this machine, and nothing else can run it. Fix it, or set \`rust.services.${service}.wasm: false\` to say so` }] }
126
+ }
127
+
128
+ const stem = service => service.replaceAll('-', '_')
129
+
130
+ /** Copy, then rename: macOS kills a process that loads a signed binary overwritten in place. */
131
+ function place(from, to) {
132
+ copyFileSync(from, `${to}.tmp`)
133
+ renameSync(`${to}.tmp`, to)
134
+ }
135
+
136
+ // ---- children -----------------------------------------------------------------------------------------------------
137
+
138
+ /** Start a binary and wait until it listens and its health check names `hash`. Rejects with why, and leaves nothing running. */
139
+ function launch({ exe, service, hash, listen, secret, onExit, log }) {
140
+ return new Promise((ok, no) => {
141
+ const child = spawn(exe, [], { env: { ...process.env, WEFT_LISTEN: listen, WEFT_RUST_SECRET: secret }, stdio: ['ignore', 'pipe', 'inherit'] })
142
+ let out = '', ready = false
143
+ const failed = why => {
144
+ clearTimeout(timer)
145
+ child.kill('SIGKILL')
146
+ no(Object.assign(new Error(why), { code: 'R109' }))
147
+ }
148
+ const timer = setTimeout(() => failed(`\`${service}\` didn't listen within 30 s`), 30_000)
149
+ child.on('error', e => failed(`\`${service}\` didn't start: ${e.message}`))
150
+ child.on('exit', (code, signal) => {
151
+ if (!ready) return failed(`\`${service}\` exited before it listened (${signal ?? code})`)
152
+ onExit?.(code, signal)
153
+ })
154
+ child.stdout.on('data', d => void heard(d))
155
+ const heard = async d => {
156
+ if (ready) return void process.stdout.write(d)
157
+ out += d
158
+ const addr = /weft-listening (\S+)/.exec(out)?.[1]
159
+ if (!addr) return
160
+ ready = true
161
+ clearTimeout(timer)
162
+ const url = `http://${addr}`
163
+ try {
164
+ const health = await (await fetch(`${url}/_weft/health`)).json()
165
+ if (health.contract !== hash) {
166
+ ready = false
167
+ return failed(`R103: \`${service}\` was built from contract ${health.contract}, and this app's is ${hash}: rebuild it`)
168
+ }
169
+ log?.(`[weft] ${service}: listening on ${addr}`)
170
+ ok({ child, url, port: Number(addr.split(':').pop()), inflight: 0 })
171
+ } catch (e) {
172
+ ready = false
173
+ failed(`\`${service}\`'s health check failed: ${e.message}`)
174
+ }
175
+ }
176
+ })
177
+ }
178
+
179
+ /** SIGTERM, which the crate drains on; SIGKILL if that takes too long. */
180
+ function stop(p, wait = 5_000) {
181
+ if (!p || p.child.exitCode !== null) return
182
+ p.stopped = true
183
+ p.child.kill('SIGTERM')
184
+ const t = setTimeout(() => p.child.kill('SIGKILL'), wait)
185
+ t.unref()
186
+ p.child.once('exit', () => clearTimeout(t))
187
+ }
188
+
189
+ // ---- dev ----------------------------------------------------------------------------------------------------------
190
+
191
+ /** The stable address the dev server is given: it outlives every child, so a reload moves no one's URL. */
192
+ function proxy(state) {
193
+ const agent = new Agent({ keepAlive: true })
194
+ const server = createServer((req, res) => {
195
+ const to = state.current
196
+ if (!to) {
197
+ if (!state.failure) return void res.destroy() // between crash and restart: `remote()` reports it, R107
198
+ res.writeHead(422, { 'content-type': 'application/json' })
199
+ return res.end(JSON.stringify({ ok: false, error: { code: 'Drift', message: state.failure } }))
200
+ }
201
+ to.inflight++
202
+ res.once('close', () => { if (--to.inflight === 0 && to.retired) stop(to) })
203
+ const up = httpRequest(`${to.url}${req.url}`, { method: req.method, headers: req.headers, agent }, answer => {
204
+ res.writeHead(answer.statusCode, answer.headers)
205
+ answer.pipe(res)
206
+ })
207
+ up.on('error', () => res.destroy())
208
+ req.pipe(up)
209
+ })
210
+ return new Promise(ok => { server.listen(0, '127.0.0.1', () => ok({ server, agent, port: server.address().port })) })
211
+ }
212
+
213
+ /**
214
+ * Build and start every sidecar, and keep them current. Sets `WEFT_RUST_<NAME>_URL` and `WEFT_RUST_SECRET` in this
215
+ * process before the dev server's worker starts, so it inherits them.
216
+ * @returns {Promise<{ attach(server: import('vite').ViteDevServer): void, close(): Promise<void>, ready: Record<string, any> }>}
217
+ */
218
+ export async function devSidecars({ root, site, rust, log = console.log }) {
219
+ root = resolve(root)
220
+ const secret = (process.env.WEFT_RUST_SECRET ||= randomBytes(32).toString('hex'))
221
+ const say = d => log(`[weft] ${d.code} ${d.severity}: ${d.why}${d.rendered ? `\n${d.rendered}` : ''}`)
222
+ let vite, closed = false
223
+ const overlay = message => vite?.ws.send({ type: 'error', err: { message, stack: '', plugin: 'weft:sidecar' } })
224
+ const refresh = async () => {
225
+ const held = process.env.WEFT_BUILD
226
+ process.env.WEFT_BUILD = '1' // the same as a build: server modules load, and nothing connects
227
+ try {
228
+ const { contract, diagnostics } = await writeContract({ root, site, rust })
229
+ diagnostics.filter(d => d.code.startsWith('R1')).forEach(say)
230
+ return { contract, blocked: diagnostics.find(d => /^R10[12]$/.test(d.code) && d.severity === 'error') }
231
+ } finally {
232
+ if (held === undefined) delete process.env.WEFT_BUILD
233
+ else process.env.WEFT_BUILD = held
234
+ }
235
+ }
236
+
237
+ const first = await refresh()
238
+ let contract = first.contract
239
+ const states = new Map()
240
+ const nativeDir = join(root, '.weft', 'native')
241
+ /** What the server's `native()` reads on each call: one rename, so it never sees half of it. */
242
+ const publish = () => {
243
+ const manifest = Object.fromEntries([...states].filter(([k]) => isNative(contract, k)).map(([k, s]) => [k, s.loaded ?? { hash: '', failure: s.failure ?? `\`${k}\` hasn't built` }]))
244
+ writeFileSync(join(nativeDir, 'manifest.tmp'), JSON.stringify(manifest))
245
+ renameSync(join(nativeDir, 'manifest.tmp'), join(nativeDir, 'manifest.json'))
246
+ }
247
+ if (buildable(contract, rust).some(k => isNative(contract, k))) {
248
+ rmSync(nativeDir, { recursive: true, force: true })
249
+ mkdirSync(nativeDir, { recursive: true })
250
+ process.env.WEFT_NATIVE_DIR = nativeDir
251
+ }
252
+
253
+ async function rebuild(service) {
254
+ const s = states.get(service)
255
+ if (s.building) return void (s.again = true)
256
+ s.building = true
257
+ try {
258
+ do {
259
+ s.again = false
260
+ await once(service, s)
261
+ // oxlint-disable-next-line no-unmodified-loop-condition -- `again` and `closed` are set by what arrives during the await
262
+ } while (s.again && !closed)
263
+ } finally {
264
+ s.building = false
265
+ }
266
+ }
267
+
268
+ async function once(service, s) {
269
+ const hash = contract.services?.[service]?.hash
270
+ if (!hash) return
271
+ const dir = crateDir(root, rust, service)
272
+ const t = performance.now()
273
+ const built = await cargo('build', { root, dir, service, contract })
274
+ if (!built.ok || !(built.exe || built.lib)) {
275
+ built.diagnostics.forEach(say)
276
+ s.failure = built.diagnostics.map(d => d.why).join('\n') || `\`${service}\` didn't build`
277
+ overlay(s.failure)
278
+ if (isNative(contract, service) && !s.loaded) publish()
279
+ return
280
+ }
281
+ log(`[weft] ${service}: built in ${Math.round(performance.now() - t)} ms`)
282
+ if (isNative(contract, service)) {
283
+ s.generation = (s.generation ?? 0) + 1
284
+ s.loaded = { hash, addon: `${stem(service)}-${s.generation}.node` }
285
+ s.failure = undefined
286
+ place(built.lib, join(nativeDir, s.loaded.addon))
287
+ return publish()
288
+ }
289
+ let next
290
+ try {
291
+ next = await launch({ exe: built.exe, service, hash, listen: '127.0.0.1:0', secret, log, onExit: (code, signal) => exited(service, s, next, code, signal) })
292
+ } catch (e) {
293
+ s.failure = e.message
294
+ log(`[weft] ${e.message}`)
295
+ return overlay(e.message)
296
+ }
297
+ // The swap: new calls go to `next` from here; the old child finishes what it has, then goes.
298
+ const old = s.current
299
+ s.current = next
300
+ s.failure = undefined
301
+ s.exe = built.exe
302
+ s.crashes = 0
303
+ if (old) {
304
+ old.retired = true
305
+ if (old.inflight === 0) stop(old)
306
+ }
307
+ }
308
+
309
+ function exited(service, s, child, code, signal) {
310
+ if (closed || !child || child.stopped || s.current !== child) return
311
+ s.current = undefined
312
+ const wait = Math.min(100 * 2 ** (s.crashes = (s.crashes ?? 0) + 1), 5_000)
313
+ log(`[weft] ${service} exited (${signal ?? code}): restarting in ${wait} ms`)
314
+ setTimeout(() => {
315
+ if (closed || s.current || s.building) return
316
+ void rebuild(service) // cargo finds nothing to do, and the binary starts again
317
+ }, wait).unref()
318
+ }
319
+
320
+ const watchers = []
321
+ const debounce = (fn, ms = 200) => {
322
+ let t
323
+ return () => { clearTimeout(t); t = setTimeout(() => fn(), ms) }
324
+ }
325
+
326
+ for (const service of buildable(contract, rust)) {
327
+ const dir = crateDir(root, rust, service)
328
+ const s = { current: undefined, failure: existsSync(dir) ? undefined : `\`crates/${service}\` doesn't exist`, building: false }
329
+ states.set(service, s)
330
+ if (!isNative(contract, service)) {
331
+ const p = await proxy(s)
332
+ s.proxy = p
333
+ process.env[urlVariable(service)] = `http://127.0.0.1:${p.port}`
334
+ }
335
+ if (!existsSync(dir)) {
336
+ log(`[weft] R109 error: ${s.failure}. Point \`rust.services.${service}.crate\` at it, or set \`external: true\``)
337
+ if (isNative(contract, service)) publish()
338
+ continue
339
+ }
340
+ if (!first.blocked) await rebuild(service)
341
+ const changed = debounce(() => rebuild(service))
342
+ watchers.push(watch(dir, { recursive: true }, (_, file) => {
343
+ if (file && !/^target([\\/]|$)/.test(file) && !file.endsWith('.lock')) changed()
344
+ }))
345
+ }
346
+
347
+ // A server module's edit may change a schema: the contract is regenerated, and only a change to a service's hash
348
+ // rebuilds it. cargo then stops where the Rust no longer fits.
349
+ const src = join(root, 'src')
350
+ const contractChanged = debounce(async () => {
351
+ try {
352
+ const fresh = await refresh()
353
+ if (fresh.blocked) return overlay(fresh.blocked.why)
354
+ const before = contract
355
+ contract = fresh.contract
356
+ for (const service of buildable(contract, rust)) {
357
+ if (states.has(service) && before.services?.[service]?.hash !== contract.services[service].hash) void rebuild(service)
358
+ }
359
+ } catch (e) {
360
+ log(`[weft] the contract couldn't be regenerated: ${e.message.split('\n')[0]}`)
361
+ }
362
+ })
363
+ if (existsSync(src)) watchers.push(watch(src, { recursive: true }, (_, file) => {
364
+ if (file && isServerModule(`src/${file.replaceAll('\\', '/')}`)) contractChanged()
365
+ }))
366
+
367
+ const killAll = () => {
368
+ closed = true
369
+ for (const s of states.values()) stop(s.current, 1_000)
370
+ }
371
+ process.once('exit', killAll)
372
+ return {
373
+ ready: Object.fromEntries([...states].map(([k, s]) => [k, !!(s.current || s.loaded)])),
374
+ attach(server) { vite = server },
375
+ async close() {
376
+ process.removeListener('exit', killAll)
377
+ killAll()
378
+ for (const w of watchers) w.close()
379
+ for (const s of states.values()) {
380
+ s.proxy?.agent.destroy()
381
+ s.proxy?.server.closeAllConnections()
382
+ await new Promise(ok => { if (s.proxy) s.proxy.server.close(ok); else ok() })
383
+ }
384
+ },
385
+ }
386
+ }
387
+
388
+ // ---- build --------------------------------------------------------------------------------------------------------
389
+
390
+ const BUILT = ['.weft', 'sidecars'] // a build empties `.output`, and these have to run during it
391
+ const SHIPPED = ['.output', 'rust']
392
+ const SHIPPED_NATIVE = ['.output', 'server', 'rust'] // with the server, so a host that moves it moves these
393
+
394
+ /** Release binaries into `.weft/sidecars/`, and what `weft start` needs to run them. */
395
+ export async function buildSidecars({ root, contract, rust, preset, log = () => {} }) {
396
+ root = resolve(root)
397
+ const out = join(root, ...BUILT)
398
+ const services = buildable(contract, rust)
399
+ rmSync(out, { recursive: true, force: true })
400
+ if (!services.length) return { services: [], diagnostics: [] }
401
+ mkdirSync(out, { recursive: true })
402
+ const manifest = {}
403
+ const diagnostics = []
404
+ for (const service of services) {
405
+ const dir = crateDir(root, rust, service)
406
+ if (!existsSync(dir)) {
407
+ diagnostics.push({ code: 'R109', severity: 'error', file: 'weft.config.ts', span: [1, 1, 1, 1], why: `\`rust://${service}\` has no crate at \`${relative(root, dir)}\`. Create it, point \`rust.services.${service}.crate\` at it, or set \`external: true\`.` })
408
+ continue
409
+ }
410
+ log(`building ${service}…`)
411
+ const built = await cargo('build', { root, dir, service, contract, release: true })
412
+ if (!built.ok || !(built.exe || built.lib)) {
413
+ diagnostics.push(...built.diagnostics)
414
+ continue
415
+ }
416
+ if (isNative(contract, service)) {
417
+ const addon = `${stem(service)}.${process.platform}-${process.arch}.node`
418
+ copyFileSync(built.lib, join(out, addon))
419
+ manifest[service] = { kind: 'native', addon, hash: contract.services[service].hash, bytes: statSync(built.lib).size }
420
+ const wasm = await checkWasm({ root, dir, service, contract, preset, rust, build: true })
421
+ diagnostics.push(...wasm.diagnostics)
422
+ if (wasm.lib) {
423
+ copyFileSync(wasm.lib, join(out, `${stem(service)}.wasm`))
424
+ Object.assign(manifest[service], { wasm: `${stem(service)}.wasm`, wasmBytes: statSync(wasm.lib).size })
425
+ }
426
+ continue
427
+ }
428
+ const bin = basename(built.exe)
429
+ copyFileSync(built.exe, join(out, bin))
430
+ manifest[service] = { bin, hash: contract.services[service].hash, bytes: statSync(built.exe).size }
431
+ }
432
+ writeFileSync(join(out, 'manifest.json'), JSON.stringify(manifest, null, 2) + '\n')
433
+ return { services: Object.keys(manifest), diagnostics }
434
+ }
435
+
436
+ /** Into the output, once the server is built. */
437
+ export function shipSidecars(root) {
438
+ const from = join(resolve(root), ...BUILT)
439
+ if (!existsSync(from)) return
440
+ const manifest = JSON.parse(readFileSync(join(from, 'manifest.json'), 'utf8'))
441
+ const natives = Object.entries(manifest).filter(([, m]) => m.kind === 'native')
442
+ const sidecars = Object.entries(manifest).filter(([, m]) => m.kind !== 'native')
443
+ const copy = (list, to, names) => {
444
+ if (!list.length) return
445
+ mkdirSync(to, { recursive: true })
446
+ for (const [, m] of list) for (const f of names(m)) cpSync(join(from, f), join(to, f))
447
+ writeFileSync(join(to, 'manifest.json'), JSON.stringify(Object.fromEntries(list), null, 2) + '\n')
448
+ }
449
+ copy(sidecars, join(resolve(root), ...SHIPPED), m => [m.bin])
450
+ copy(natives, join(resolve(root), ...SHIPPED_NATIVE), m => [m.addon, m.wasm].filter(Boolean))
451
+ }
452
+
453
+ // ---- start --------------------------------------------------------------------------------------------------------
454
+
455
+ /**
456
+ * Run `.output/rust/`'s binaries for `weft start` (or `built`'s, while `weft build` prerenders). A service with `WEFT_RUST_<NAME>_URL` already set is someone else's.
457
+ * Each keeps its port across restarts, so the server's address stays good.
458
+ * @returns {Promise<{ env: Record<string, string>, close(): void }>} `env` for the server process
459
+ */
460
+ export async function startSidecars({ root, built = false, log = console.log }) {
461
+ const dir = join(resolve(root), ...(built ? BUILT : SHIPPED))
462
+ const file = join(dir, 'manifest.json')
463
+ if (!existsSync(file)) return { env: {}, close() {} }
464
+ const manifest = JSON.parse(readFileSync(file, 'utf8'))
465
+ const names = Object.keys(manifest).filter(s => manifest[s].kind !== 'native' && !process.env[urlVariable(s)])
466
+ // While a build prerenders, the libraries aren't next to a server yet.
467
+ const paths = built && Object.values(manifest).some(m => m.kind === 'native') ? { WEFT_NATIVE_DIR: dir } : {}
468
+ if (!names.length) return { env: paths, close() {} }
469
+ const secret = process.env.WEFT_RUST_SECRET || randomBytes(32).toString('hex')
470
+ const env = { ...paths, WEFT_RUST_SECRET: secret }
471
+ let closed = false
472
+ const live = new Map()
473
+
474
+ const supervise = service => {
475
+ const { bin, hash } = manifest[service]
476
+ let listen = '127.0.0.1:0', tries = 0, up
477
+ const begin = async () => {
478
+ up = Date.now()
479
+ const p = await launch({ exe: join(dir, bin), service, hash, listen, secret, log, onExit: (code, signal) => again(`exited (${signal ?? code})`) })
480
+ listen = `127.0.0.1:${p.port}` // restarts rebind what the first start got
481
+ live.set(service, p)
482
+ return p
483
+ }
484
+ const again = why => {
485
+ if (closed) return
486
+ // One that ran for a while starts over; one that dies at once backs off.
487
+ tries = Date.now() - up > 30_000 ? 1 : tries + 1
488
+ const wait = Math.min(100 * 2 ** tries, 5_000)
489
+ log(`[weft] ${service} ${why}: restarting in ${wait} ms`)
490
+ setTimeout(() => { if (!closed) begin().catch(e => again(e.message.split('\n')[0])) }, wait)
491
+ }
492
+ return begin()
493
+ }
494
+
495
+ for (const service of names) env[urlVariable(service)] = (await supervise(service)).url
496
+
497
+ const killAll = () => {
498
+ closed = true
499
+ for (const p of live.values()) stop(p, 1_000)
500
+ }
501
+ process.once('exit', killAll)
502
+ return { env, close: killAll }
503
+ }