@kerf-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 (236) hide show
  1. package/LICENSE +16 -0
  2. package/README.md +1468 -2
  3. package/crate/Cargo.lock +1347 -0
  4. package/crate/Cargo.toml +72 -0
  5. package/crate/README.md +322 -0
  6. package/crate/rust-toolchain.toml +3 -0
  7. package/crate/src/build/emit.rs +103 -0
  8. package/crate/src/build.rs +367 -0
  9. package/crate/src/ctx.rs +186 -0
  10. package/crate/src/envelope.rs +163 -0
  11. package/crate/src/functions.rs +173 -0
  12. package/crate/src/lib.rs +118 -0
  13. package/crate/src/native.rs +212 -0
  14. package/crate/src/otel.rs +62 -0
  15. package/crate/src/server.rs +203 -0
  16. package/package.json +123 -3
  17. package/src/app.mjs +136 -0
  18. package/src/asset-receipt.d.mts +13 -0
  19. package/src/asset-receipt.mjs +61 -0
  20. package/src/auth/better-auth.ts +280 -0
  21. package/src/auth/drizzle.ts +17 -0
  22. package/src/auth/emails.ts +44 -0
  23. package/src/auth.ts +62 -0
  24. package/src/boot.ts +57 -0
  25. package/src/builtin.tsx +19 -0
  26. package/src/bus/postgres.ts +104 -0
  27. package/src/bus.ts +51 -0
  28. package/src/cache.ts +4 -0
  29. package/src/capture.ts +50 -0
  30. package/src/changes-sql.d.mts +20 -0
  31. package/src/changes-sql.mjs +115 -0
  32. package/src/changes.ts +352 -0
  33. package/src/channel/connections.ts +216 -0
  34. package/src/channel/socket.ts +396 -0
  35. package/src/channel-fake.ts +70 -0
  36. package/src/channel.ts +250 -0
  37. package/src/client.tsx +27 -0
  38. package/src/contract/describe.mjs +237 -0
  39. package/src/contract.mjs +299 -0
  40. package/src/cron.ts +74 -0
  41. package/src/data/after.ts +57 -0
  42. package/src/data/cache.ts +354 -0
  43. package/src/data/definitions.ts +94 -0
  44. package/src/data/draft.ts +104 -0
  45. package/src/data/foundation.ts +95 -0
  46. package/src/data/live-api.ts +22 -0
  47. package/src/data/mutation.ts +138 -0
  48. package/src/data/primitives.ts +135 -0
  49. package/src/data/query.ts +106 -0
  50. package/src/data/transport.ts +123 -0
  51. package/src/data/types.ts +333 -0
  52. package/src/data.ts +125 -0
  53. package/src/db/bun-sqlite.d.ts +13 -0
  54. package/src/db/changes-mysql.ts +126 -0
  55. package/src/db/changes-postgres.ts +238 -0
  56. package/src/db/changes-sqlite.ts +183 -0
  57. package/src/db/core.ts +95 -0
  58. package/src/db/index.ts +43 -0
  59. package/src/db/mysql.ts +84 -0
  60. package/src/db/postgres.ts +102 -0
  61. package/src/db/sqlite.ts +166 -0
  62. package/src/derive.d.mts +19 -0
  63. package/src/derive.mjs +237 -0
  64. package/src/dev-runtime.mjs +46 -0
  65. package/src/email.ts +146 -0
  66. package/src/exec/errors.ts +87 -0
  67. package/src/exec/impl.ts +21 -0
  68. package/src/exec/landing.ts +66 -0
  69. package/src/exec/limit.ts +25 -0
  70. package/src/exec/once.ts +24 -0
  71. package/src/exec/scope.ts +328 -0
  72. package/src/exec/touch.ts +80 -0
  73. package/src/exec/validation.ts +176 -0
  74. package/src/exec/warm.ts +50 -0
  75. package/src/exec.ts +400 -0
  76. package/src/extension.ts +48 -0
  77. package/src/first-paint.ts +74 -0
  78. package/src/form/value.ts +15 -0
  79. package/src/form.tsx +223 -0
  80. package/src/gate.css +6 -0
  81. package/src/hub/channels.ts +102 -0
  82. package/src/hub/connections.ts +147 -0
  83. package/src/hub/delivery.ts +62 -0
  84. package/src/hub/feed.ts +168 -0
  85. package/src/hub/presence.ts +64 -0
  86. package/src/hub/route.ts +159 -0
  87. package/src/hub/subscriptions.ts +213 -0
  88. package/src/hub/topic.ts +98 -0
  89. package/src/hub/tracked.ts +12 -0
  90. package/src/hub/types.ts +190 -0
  91. package/src/hub/view.ts +147 -0
  92. package/src/hub.ts +196 -0
  93. package/src/index.ts +184 -0
  94. package/src/inline.mjs +359 -0
  95. package/src/inspect/compare.mjs +162 -0
  96. package/src/inspect/routes.mjs +154 -0
  97. package/src/inspect/samples.mjs +59 -0
  98. package/src/inspect/url.mjs +2 -0
  99. package/src/inspect.mjs +239 -0
  100. package/src/jobs.ts +223 -0
  101. package/src/link/election.ts +178 -0
  102. package/src/link/lines.ts +27 -0
  103. package/src/link.ts +385 -0
  104. package/src/list-drizzle.ts +136 -0
  105. package/src/list.ts +315 -0
  106. package/src/listen.ts +54 -0
  107. package/src/live/api.ts +18 -0
  108. package/src/live/backoff.ts +6 -0
  109. package/src/live/frames.ts +42 -0
  110. package/src/live/read.ts +77 -0
  111. package/src/live/sub-types.ts +24 -0
  112. package/src/live/transport.ts +86 -0
  113. package/src/live/types.ts +52 -0
  114. package/src/live-fake.ts +57 -0
  115. package/src/live-target.mjs +231 -0
  116. package/src/live.ts +390 -0
  117. package/src/media.ts +50 -0
  118. package/src/migrations.mjs +27 -0
  119. package/src/mux-session.ts +6 -0
  120. package/src/mux.ts +232 -0
  121. package/src/og/DefaultCard.tsx +91 -0
  122. package/src/og/fonts.mjs +72 -0
  123. package/src/og/images.mjs +124 -0
  124. package/src/og/index.mjs +222 -0
  125. package/src/og/native.mjs +36 -0
  126. package/src/range.mjs +31 -0
  127. package/src/router.ts +199 -0
  128. package/src/routes.mjs +193 -0
  129. package/src/run/admission.ts +67 -0
  130. package/src/run/boot.tsx +115 -0
  131. package/src/run/cache-presentation.ts +67 -0
  132. package/src/run/cache.ts +254 -0
  133. package/src/run/helpers.ts +197 -0
  134. package/src/run/listeners.ts +166 -0
  135. package/src/run/navigation.ts +385 -0
  136. package/src/run/page-skeleton.tsx +35 -0
  137. package/src/run/prefetch.ts +129 -0
  138. package/src/run/retain-view.ts +18 -0
  139. package/src/run/shape-preparation.ts +97 -0
  140. package/src/run/shape-styles.ts +72 -0
  141. package/src/run/source-context/pin.ts +124 -0
  142. package/src/run/source-context.ts +311 -0
  143. package/src/run.tsx +74 -0
  144. package/src/rust/common.ts +163 -0
  145. package/src/rust/native.ts +282 -0
  146. package/src/rust.ts +207 -0
  147. package/src/server/background.ts +34 -0
  148. package/src/server/card.tsx +65 -0
  149. package/src/server/compression.ts +115 -0
  150. package/src/server/core.ts +70 -0
  151. package/src/server/cron.ts +49 -0
  152. package/src/server/dispatch.ts +73 -0
  153. package/src/server/form.ts +92 -0
  154. package/src/server/functions.ts +133 -0
  155. package/src/server/handler.ts +57 -0
  156. package/src/server/head.ts +96 -0
  157. package/src/server/health.ts +36 -0
  158. package/src/server/jobs.ts +112 -0
  159. package/src/server/lifecycle.ts +48 -0
  160. package/src/server/log.ts +42 -0
  161. package/src/server/media.ts +61 -0
  162. package/src/server/navigation-cache.ts +75 -0
  163. package/src/server/navigation.tsx +86 -0
  164. package/src/server/page-cold.ts +96 -0
  165. package/src/server/page-stream.tsx +181 -0
  166. package/src/server/page-types.ts +51 -0
  167. package/src/server/page-warm.ts +131 -0
  168. package/src/server/page.ts +69 -0
  169. package/src/server/payload.ts +89 -0
  170. package/src/server/prerender.ts +64 -0
  171. package/src/server/preview.tsx +67 -0
  172. package/src/server/render.ts +197 -0
  173. package/src/server/request.ts +192 -0
  174. package/src/server/resolver.ts +228 -0
  175. package/src/server/routes.ts +150 -0
  176. package/src/server/security.ts +50 -0
  177. package/src/server/services.ts +69 -0
  178. package/src/server/shutdown.ts +23 -0
  179. package/src/server/text.ts +29 -0
  180. package/src/server/types.ts +170 -0
  181. package/src/server.tsx +138 -0
  182. package/src/shape.d.mts +3 -0
  183. package/src/shape.mjs +97 -0
  184. package/src/share/display.ts +50 -0
  185. package/src/share/network.ts +119 -0
  186. package/src/share/receive.ts +70 -0
  187. package/src/share/state.ts +30 -0
  188. package/src/share/tab-queue.ts +28 -0
  189. package/src/share-server.ts +293 -0
  190. package/src/share.ts +397 -0
  191. package/src/sheets.mjs +87 -0
  192. package/src/sidecar/build.mjs +170 -0
  193. package/src/sidecar/cargo.mjs +164 -0
  194. package/src/sidecar/common.mjs +17 -0
  195. package/src/sidecar/dev-build.mjs +91 -0
  196. package/src/sidecar/dev-watch.mjs +88 -0
  197. package/src/sidecar/manifest.mjs +19 -0
  198. package/src/sidecar/process.mjs +58 -0
  199. package/src/sidecar/refresh.mjs +19 -0
  200. package/src/sidecar.mjs +162 -0
  201. package/src/socket/check.ts +50 -0
  202. package/src/socket/deliver.ts +16 -0
  203. package/src/socket/publish.ts +56 -0
  204. package/src/socket/rooms.ts +41 -0
  205. package/src/socket/route.ts +79 -0
  206. package/src/socket/shared.ts +26 -0
  207. package/src/socket/types.ts +48 -0
  208. package/src/socket.ts +400 -0
  209. package/src/stream.ts +22 -0
  210. package/src/verify/app.ts +39 -0
  211. package/src/verify/cleanup.ts +27 -0
  212. package/src/verify/database.ts +11 -0
  213. package/src/verify/live.ts +63 -0
  214. package/src/verify/notify.ts +35 -0
  215. package/src/verify/skip.ts +19 -0
  216. package/src/verify/support.ts +149 -0
  217. package/src/verify/timing.ts +15 -0
  218. package/src/verify/trigger.ts +14 -0
  219. package/src/verify.ts +152 -0
  220. package/src/view.tsx +132 -0
  221. package/src/vite/asset-bytes.mjs +95 -0
  222. package/src/vite/assets.mjs +117 -0
  223. package/src/vite/config-hooks.mjs +166 -0
  224. package/src/vite/dev-hooks.mjs +103 -0
  225. package/src/vite/dev.mjs +102 -0
  226. package/src/vite/entries.mjs +149 -0
  227. package/src/vite/module-hooks.mjs +290 -0
  228. package/src/vite/route-modules.mjs +289 -0
  229. package/src/vite/server-functions.mjs +222 -0
  230. package/src/vite/shape-entry-css.mjs +187 -0
  231. package/src/vite/shape-override.mjs +226 -0
  232. package/src/vite/shared.mjs +55 -0
  233. package/src/vite/sheets.mjs +92 -0
  234. package/src/vite/state.mjs +89 -0
  235. package/src/vite/syntax.mjs +139 -0
  236. package/src/vite.mjs +202 -0
@@ -0,0 +1,222 @@
1
+ // renderCard for kerf (research 20 §4, §9; promoted from archive/evals-2026-11:spikes/og/card): kerf SSR HTML → PNG/JPEG/WebP/SVG, on
2
+ // Takumi, with what Satori did better added around it:
3
+ // - strict styles: every declaration is checked once against the renderer (an invalid value would fail the whole
4
+ // card, an unknown property is silently dropped) and reported as H005; production drops the bad declaration and
5
+ // renders the rest instead of failing the request
6
+ // - any font format (WOFF too, which Takumi's wasm build can't read), resolved before the first render
7
+ // - SVG output and a ready `Response` with the §4.3 cache headers
8
+ // - a browser preview that matches the PNG: the same preflight (border-box everywhere) and the same font bytes
9
+ // and what neither did: SSR hole comments are removed (both HTML parsers drop text before a comment), and remote
10
+ // images are fetched with a timeout, size cap and host allowlist, cached, and left out (box kept) when they fail.
11
+ import { fromHtml } from '@takumi-rs/helpers/html'
12
+ import { normalizeFonts } from './fonts.mjs'
13
+ import { imageCache, loadImages } from './images.mjs'
14
+ import { native } from './native.mjs'
15
+
16
+ /** Applied to every card, in the PNG and in the preview. Takumi lays out border-box by default; browsers don't. */
17
+ export const PREFLIGHT = '*,*::before,*::after{box-sizing:border-box}'
18
+ /** The size of a generated card. */
19
+ export const SIZE = { width: 1200, height: 630 }
20
+ const TYPES = { png: 'image/png', jpeg: 'image/jpeg', webp: 'image/webp', svg: 'image/svg+xml' }
21
+
22
+ const stripComments = (html) => html.replace(/<!--[\s\S]*?-->/g, '')
23
+ const kebab = (k) =>
24
+ k.replace(/^Webkit/, '-webkit-').replace(/[A-Z]/g, (c) => '-' + c.toLowerCase())
25
+ // A value no CSS grammar accepts: a property the renderer knows rejects it, and one it doesn't know takes anything.
26
+ // (An identifier won't do: `text-overflow`, `grid-template-columns` and `font-family` accept custom idents.)
27
+ const PROBE = '}{'
28
+
29
+ const renderers = new Map() // fonts array → the renderer registered with them
30
+
31
+ /**
32
+ * The one seam the server uses (research 20 §4.2): HTML at `size`, drawn with `fonts`, to PNG bytes. Diagnostics (H005
33
+ * styles, H008 images) go to `onDiagnostic`; `strict` (dev, `kerf build`) throws on an error instead. Native Takumi;
34
+ * the edge build (`@takumi-rs/wasm`) plugs in here when an edge preset needs it.
35
+ *
36
+ * @param {string} html
37
+ * @param {{ width?: number; height?: number }} [size]
38
+ * @param {{ name: string; data: Uint8Array; weight?: number; style?: 'normal' | 'italic' }[]} [fonts]
39
+ * @param {{ strict?: boolean; onDiagnostic?: (d: { code: string; severity: string; message: string }) => void; images?: unknown }} [options]
40
+ */
41
+ export async function renderCard(
42
+ html,
43
+ size = SIZE,
44
+ fonts = [],
45
+ { strict = false, onDiagnostic, images } = {},
46
+ ) {
47
+ let r = renderers.get(fonts)
48
+ if (!r)
49
+ renderers.set(
50
+ fonts,
51
+ (r = native().then((backend) => createCardRenderer({ backend, fonts, images }))),
52
+ )
53
+ const out = await (
54
+ await r
55
+ ).render(html, { width: size.width ?? SIZE.width, height: size.height ?? SIZE.height, strict })
56
+ for (const d of out.diagnostics) onDiagnostic?.(d)
57
+ return out.body
58
+ }
59
+
60
+ /**
61
+ * `backend` is `await native()` (card/native.mjs) or `await wasm(module)` (card/wasm.mjs). `fonts` is `{ name, data, weight?, style? }[]` in TTF, OTF,
62
+ * WOFF or WOFF2. `images` configures `<img>` fetching (see images.mjs).
63
+ */
64
+ export async function createCardRenderer({ backend, fonts = [], images: imageOptions = {} }) {
65
+ const renderer = new backend.Renderer()
66
+ for (const font of await normalizeFonts(fonts)) await renderer.registerFont(font)
67
+ const cache = imageCache(imageOptions.cacheBytes)
68
+ const prepare = createPreparation(renderer)
69
+
70
+ return {
71
+ /** Diagnostics only (`kerf check`, dev): nothing is fetched or rasterized. */
72
+ async check(html) {
73
+ return (await prepare(html)).diagnostics
74
+ },
75
+
76
+ /**
77
+ * Renders a card. Never throws on a card's styles or images: those come back as diagnostics, and the card renders
78
+ * without them. `strict` (dev, `kerf build`) throws on any error-severity diagnostic instead.
79
+ */
80
+ async render(
81
+ html,
82
+ { width = SIZE.width, height = SIZE.height, format = 'png', quality, strict = false } = {},
83
+ ) {
84
+ const { node, css, diagnostics, imageNodes } = await prepare(html)
85
+ const { images, failed } = await loadImages(
86
+ imageNodes.map((n) => n.src),
87
+ { cache, ...imageOptions },
88
+ )
89
+ for (const f of failed) {
90
+ diagnostics.push({
91
+ code: 'H008',
92
+ severity: 'warning',
93
+ message: `Card image ${f.src} didn't load (${f.reason}); the card renders without it.`,
94
+ })
95
+ for (const n of imageNodes)
96
+ if (n.src === f.src)
97
+ Object.assign(n, {
98
+ type: 'container',
99
+ src: undefined,
100
+ style: {
101
+ width: n.width && `${n.width}px`,
102
+ height: n.height && `${n.height}px`,
103
+ ...n.style,
104
+ },
105
+ })
106
+ }
107
+ if (strict && diagnostics.some((d) => d.severity === 'error')) {
108
+ throw Object.assign(
109
+ new Error(
110
+ diagnostics
111
+ .filter((d) => d.severity === 'error')
112
+ .map((d) => `${d.code} ${d.message} (${d.element})`)
113
+ .join('\n'),
114
+ ),
115
+ { diagnostics },
116
+ )
117
+ }
118
+ const options = { width, height, images, css: [PREFLIGHT, ...css] }
119
+ const body =
120
+ format === 'svg'
121
+ ? await renderer.renderSvg(node, options)
122
+ : new Uint8Array(
123
+ await renderer.render(node, {
124
+ ...options,
125
+ format,
126
+ ...(quality != null && { quality }),
127
+ }),
128
+ )
129
+ return { body, type: TYPES[format], diagnostics }
130
+ },
131
+ }
132
+ }
133
+
134
+ function createPreparation(renderer) {
135
+ const verdicts = new Map() // `${prop}\0${value}` → null (fine) | { severity, message }
136
+
137
+ const accepts = async (style) => {
138
+ try {
139
+ await renderer.measure({ type: 'container', style }, { width: 1, height: 1 })
140
+ return true
141
+ } catch {
142
+ return false
143
+ }
144
+ }
145
+ async function judge(prop, value) {
146
+ const key = `${prop}\0${value}`
147
+ if (verdicts.has(key)) return verdicts.get(key)
148
+ let v = null
149
+ if (!(await accepts({ [prop]: value }))) {
150
+ v = {
151
+ severity: 'error',
152
+ message: `\`${kebab(prop)}: ${value}\` isn't a value the card renderer accepts; the declaration is dropped.`,
153
+ }
154
+ } else if (await accepts({ [prop]: PROBE })) {
155
+ v = {
156
+ severity: 'warning',
157
+ message: `\`${kebab(prop)}\` isn't a property the card renderer supports; it has no effect.`,
158
+ }
159
+ }
160
+ verdicts.set(key, v)
161
+ return v
162
+ }
163
+
164
+ /** Walks the tree: checks styles (dropping invalid declarations), and collects image nodes. */
165
+ async function prepare(html) {
166
+ const { node, css } = fromHtml(stripComments(html))
167
+ const diagnostics = [],
168
+ imageNodes = []
169
+ const walk = async (n, path) => {
170
+ if (n.type === 'image') imageNodes.push(n)
171
+ for (const [prop, value] of Object.entries(n.style ?? {})) {
172
+ const v = await judge(prop, value)
173
+ if (!v) continue
174
+ diagnostics.push({ code: 'H005', severity: v.severity, message: v.message, element: path })
175
+ if (v.severity === 'error') delete n.style[prop]
176
+ }
177
+ for (const [i, c] of (n.children ?? []).entries())
178
+ await walk(c, `${path} > ${c.tagName ?? c.type}:nth-child(${i + 1})`)
179
+ }
180
+ await walk(node, node.tagName ?? node.type)
181
+ return { node, css, diagnostics, imageNodes }
182
+ }
183
+
184
+ return prepare
185
+ }
186
+
187
+ /**
188
+ * The HTTP response for `/_kerf/og/<route>.png?v=<hash>` (§4.3): immutable, since the URL is content-addressed, except
189
+ * in dev, where an edit must show on reload.
190
+ */
191
+ export function cardResponse({ body, type }, { dev = false } = {}) {
192
+ return new Response(body, {
193
+ headers: {
194
+ 'content-type': type,
195
+ 'cache-control': dev ? 'no-store' : 'public, max-age=31536000, immutable',
196
+ },
197
+ })
198
+ }
199
+
200
+ /**
201
+ * The card as a page for `kerf open --og`: the same HTML, preflight and font bytes as the PNG, at the card's size, so a
202
+ * browser shows what the renderer draws.
203
+ */
204
+ export function previewHtml(html, { fonts = [], width = SIZE.width, height = SIZE.height } = {}) {
205
+ const faces = fonts
206
+ .map(
207
+ (f) =>
208
+ `@font-face{font-family:"${f.name}";font-weight:${f.weight ?? 400};font-style:${f.style ?? 'normal'};src:url(data:font/${fontMime(f.data)};base64,${base64(f.data)})}`,
209
+ )
210
+ .join('')
211
+ return `<!doctype html><meta charset="utf-8"><style>${faces}${PREFLIGHT}html,body{margin:0}#card{width:${width}px;height:${height}px;overflow:hidden;display:flex}</style><div id="card">${stripComments(html)}</div>`
212
+ }
213
+
214
+ const fontMime = (d) =>
215
+ ({ wOFF: 'woff', wOF2: 'woff2', OTTO: 'otf' })[String.fromCharCode(...d.subarray(0, 4))] ?? 'ttf'
216
+
217
+ function base64(bytes) {
218
+ let s = ''
219
+ for (let i = 0; i < bytes.length; i += 0x8000)
220
+ s += String.fromCharCode(...bytes.subarray(i, i + 0x8000))
221
+ return btoa(s)
222
+ }
@@ -0,0 +1,36 @@
1
+ // `@takumi-rs/core`: Node, Bun and Deno servers, `kerf build`, Vercel and Netlify Node functions. A file of its own so
2
+ // an edge bundle (`@takumi-rs/wasm`, archive/evals-2026-11:spikes/og/card/wasm.mjs) never pulls in the native addon. Both builds draw byte-identical cards (§9.4).
3
+ export async function native() {
4
+ // Takumi's addon in the same process as a later Rolldown pass kills a Windows `kerf build` (0xC0000005) before the
5
+ // server is written. KERF_START_DIR means a build, and the cards come out the same.
6
+ if (globalThis.process?.platform === 'win32' && globalThis.process.env.KERF_START_DIR)
7
+ return wasmBackend(globalThis.process.env.KERF_START_DIR)
8
+ const { Renderer } = await import('@takumi-rs/core').catch(linked)
9
+ return { name: 'native', Renderer }
10
+ }
11
+
12
+ /**
13
+ * A prerender runs from a bundle in the app's `node_modules/.nitro`. An app that links `@kerf-js/start` from a workspace
14
+ * has no hoisted `@takumi-rs/core` there, so a build says where @kerf-js/start is (app.mjs).
15
+ */
16
+ async function linked(error) {
17
+ const from = globalThis.process?.env.KERF_START_DIR
18
+ if (!from) throw error
19
+ const { createRequire } = await import('node:module')
20
+ return createRequire(`${from}/package.json`)('@takumi-rs/core')
21
+ }
22
+
23
+ /** The wasm renderer, found from `start` (the @kerf-js/start directory) because a prerender runs from a bundle. */
24
+ export async function wasmBackend(start) {
25
+ const [{ createRequire }, { readFile }, { dirname, join }, { pathToFileURL }] = await Promise.all(
26
+ ['node:module', 'node:fs/promises', 'node:path', 'node:url'].map(
27
+ (m) => import(/* @vite-ignore */ m),
28
+ ),
29
+ )
30
+ const root = dirname(dirname(createRequire(`${start}/package.json`).resolve('@takumi-rs/wasm')))
31
+ const { default: init, Renderer } = await import(
32
+ /* @vite-ignore */ pathToFileURL(join(root, 'dist/export.mjs')).href
33
+ )
34
+ await init({ module_or_path: await readFile(join(root, 'pkg/takumi_wasm_bg.wasm')) })
35
+ return { name: 'wasm', Renderer }
36
+ }
package/src/range.mjs ADDED
@@ -0,0 +1,31 @@
1
+ // Byte ranges for built video and audio. Nitro's static handler has none and runs before any middleware, and Safari
2
+ // won't play a video without them, so this Nitro plugin answers ranged requests for those files in front of the app.
3
+ export default (nitro) => {
4
+ const app = nitro.fetch
5
+ nitro.fetch = async (request, ...rest) => {
6
+ const range = /^bytes=(\d+)-(\d*)$/.exec(request.headers.get('range') ?? '')
7
+ const id = range && new URL(request.url).pathname
8
+ if (!id?.startsWith('/assets/')) return app(request, ...rest)
9
+ // Lazily: the prerender step builds this file without Nitro's asset table.
10
+ const { getAsset, readAsset } = await import('#nitro/virtual/public-assets')
11
+ const asset = getAsset(id)
12
+ if (!/^(video|audio)\//.test(asset?.type ?? '')) return app(request, ...rest)
13
+ const bytes = Buffer.from(await readAsset(id))
14
+ const start = Number(range[1])
15
+ const end = Math.min(range[2] ? Number(range[2]) : Infinity, bytes.length - 1)
16
+ if (start > end)
17
+ return new Response(null, {
18
+ status: 416,
19
+ headers: { 'content-range': `bytes */${bytes.length}` },
20
+ })
21
+ return new Response(bytes.subarray(start, end + 1), {
22
+ status: 206,
23
+ headers: {
24
+ 'content-type': asset.type,
25
+ 'accept-ranges': 'bytes',
26
+ 'content-range': `bytes ${start}-${end}/${bytes.length}`,
27
+ 'cache-control': 'public, max-age=31536000, immutable',
28
+ },
29
+ })
30
+ }
31
+ }
package/src/router.ts ADDED
@@ -0,0 +1,199 @@
1
+ // The route state both sides render from (research 25 §3). A page is a chain of levels, outer to inner: the root
2
+ // layout, nested layouts, the page. Each level is three boxes: which route it shows, its params and its loader
3
+ // data. Navigating writes only what changed: a level that keeps its route keeps its component and gets new params
4
+ // or data in place (the bindings that read them re-run, nothing remounts); the first level whose route changes
5
+ // renders its new route, and everything inside it goes. One state per request on the server (passed down as a
6
+ // prop), one per tab on the client.
7
+
8
+ import { state, untrack, type State, type SsrData } from '@kerf-js/core'
9
+ import type { Merged } from '@kerf-js/core/ssr'
10
+ import type { Wire } from './data'
11
+ import type { PreparedRouteShape } from './run/shape-preparation'
12
+
13
+ /**
14
+ * One level as the server sends it: `d` lists the data's deferred fields (promises on the server, research 25 §4),
15
+ * `t` the tags of the queries its `load` read (a mutation that invalidates one refreshes the route, research 27 §4).
16
+ */
17
+ export interface Match {
18
+ id: string
19
+ params: Record<string, string>
20
+ data?: unknown
21
+ d?: string[] | undefined
22
+ t?: string[] | undefined
23
+ /** A static level: no client code (PLAN §11). `h`: its HTML (a navigation), `x`: a hash of it, to skip an unchanged one. */
24
+ s?: 1
25
+ h?: string
26
+ x?: string
27
+ }
28
+
29
+ export interface Level {
30
+ id: State<string | undefined>
31
+ params: State<Record<string, string>>
32
+ data: State<unknown>
33
+ /** A static level's HTML: empty for the page's own; undefined for a level with client code. */
34
+ html: State<string | undefined>
35
+ /** A temporary incoming shape for this outlet, while its route is pending. */
36
+ shape: State<PreparedRouteShape[] | undefined>
37
+ x?: string | undefined
38
+ }
39
+
40
+ /** A route, layout or island: its props are its own, so nothing here can call one without a cast. */
41
+ export type Component = (props: never) => unknown
42
+
43
+ /** Sizes are emitted, uncompressed bytes in Vite's recorded static closure. */
44
+ export interface RouteAssetCosts {
45
+ build: string
46
+ scope: 'vite-static-closure'
47
+ levels: { id: string; bytes: number | null }[]
48
+ routeBytes: number | null
49
+ eagerBytes: number | null
50
+ combinedBytes: number | null
51
+ }
52
+
53
+ export interface AssetReceipt {
54
+ build: string | null
55
+ version: 1
56
+ scope: 'vite-static-closure'
57
+ files: Record<string, { bytes: number | null; kind: string }>
58
+ routes: Record<string, { files: string[]; bytes: number | null } | null>
59
+ eager: { files: string[]; bytes: number | null } | null
60
+ }
61
+
62
+ export interface RouteState {
63
+ levels: Level[]
64
+ /** The current path (pathname + search). */
65
+ path: State<string>
66
+ status: State<number>
67
+ /** Loaded route components by id. */
68
+ comps: Record<string, Component>
69
+ /** Cost of the current match, when the client and receipt are from the same build. */
70
+ assetBytes?: RouteAssetCosts | null
71
+ /** Prepare a route's provided shape CSS until the caller releases it. */
72
+ prepareShape?: (id: string) => PreparedRouteShape | null
73
+ /** Client: shows a static level's HTML, with the next level inside it. */
74
+ mount?: (html: string, depth: number, next: () => unknown) => unknown
75
+ /** Around a level's component, at the same point on both sides: the server's markers, the client's key scope. */
76
+ around?: (depth: number, id: string, body: () => unknown) => unknown
77
+ }
78
+
79
+ /** What `/_kerf/data/<path>` answers and what the page carries in `#kerf-route`: the matches, the head, the status. */
80
+ export interface RoutePayload {
81
+ m: Match[]
82
+ p: string
83
+ s: number
84
+ h?: Merged
85
+ /** A redirect (the client navigates there instead). */
86
+ r?: string
87
+ /** The queries the loaders resolved, for the client cache (navigation only; a page carries `#kerf-cache`). */
88
+ c?: Wire[]
89
+ /** The islands in the static levels that can't wait, whose code has to be there first. */
90
+ i?: string[]
91
+ /** A navigation's page data, for those islands. */
92
+ b?: SsrData | null
93
+ /** Emitted asset cost for these levels, when a matching build receipt exists. */
94
+ a?: RouteAssetCosts
95
+ }
96
+
97
+ /** The route state of the render in progress: a server pass sets it as it starts (passes are synchronous). */
98
+ export const active: { route?: RouteState } = {}
99
+
100
+ export function createRouteState(
101
+ payload: RoutePayload,
102
+ comps: Record<string, Component>,
103
+ ): RouteState {
104
+ const r: RouteState = { levels: [], path: state(payload.p), status: state(payload.s), comps }
105
+ payload.m.forEach((m, d) => {
106
+ const lv = level(r, d)
107
+ lv.id.value = m.id
108
+ lv.params.value = m.params
109
+ lv.data.value = m.data
110
+ lv.html.value = m.s ? (m.h ?? '') : undefined
111
+ lv.x = m.x
112
+ })
113
+ return r
114
+ }
115
+
116
+ /** Level `d`, made on first use (an empty level renders nothing). */
117
+ export function level(r: RouteState, d: number): Level {
118
+ return (r.levels[d] ??= {
119
+ id: state<string | undefined>(undefined),
120
+ params: state({}),
121
+ data: state<unknown>(undefined),
122
+ html: state<string | undefined>(undefined),
123
+ shape: state<PreparedRouteShape[] | undefined>(undefined),
124
+ })
125
+ }
126
+
127
+ const same = (a: unknown, b: unknown) => a === b || JSON.stringify(a) === JSON.stringify(b)
128
+
129
+ /**
130
+ * Show `matches`: levels that keep their route get their new params and data (only when they differ, so a shared
131
+ * layout whose data didn't change sees no write at all); the first level whose route changes, and every level after
132
+ * it, switch route.
133
+ */
134
+ export function applyMatches(r: RouteState, matches: Match[], path: string, status: number) {
135
+ untrack(() => {
136
+ const depth = Math.max(matches.length, r.levels.length)
137
+ let fresh = false
138
+ for (let d = 0; d < depth; d++) {
139
+ const m = matches[d]
140
+ const lv = level(r, d)
141
+ if (m) {
142
+ if (!same(lv.params.value, m.params)) lv.params.value = m.params
143
+ if (!same(lv.data.value, m.data)) lv.data.value = m.data
144
+ if (!m.s) lv.html.value = undefined
145
+ else if (fresh || lv.x !== m.x || lv.id.value !== m.id) {
146
+ lv.html.value = m.h
147
+ fresh = true // its markers for the levels below are gone with it, so those can't adopt the page
148
+ }
149
+ lv.x = m.x
150
+ }
151
+ if (lv.id.value !== m?.id) lv.id.value = m?.id
152
+ }
153
+ if (r.path.value !== path) r.path.value = path
154
+ if (r.status.value !== status) r.status.value = status
155
+ })
156
+ }
157
+
158
+ /**
159
+ * The tab's route state and navigation, set by `start()` (client.tsx). Server renders never touch them. The query
160
+ * cache (data.ts, loaded only by apps that use a query) hooks in here, so `start()` doesn't ship it: `seed` takes
161
+ * the entries a navigation brought (`seeds` holds them until it loads), `invalidated` refreshes the route data.
162
+ */
163
+ export const client: {
164
+ route?: RouteState
165
+ navigate?: (
166
+ href: string,
167
+ options?: NavigateOptions & { replace?: boolean | undefined },
168
+ ) => Promise<void>
169
+ /** `since`: what `now` said when the navigation left, so entries a write has passed don't land. */
170
+ seed?: (list: Wire[], since?: number) => void
171
+ seeds?: Wire[] | undefined
172
+ now?: () => number
173
+ invalidated?: (tags: string[]) => void
174
+ /** Clear navigation state before a session-changing reload. */
175
+ sessionChanged?: () => void
176
+ /** Dev: server code changed, so whatever a query read may have too. */
177
+ refreshed?: () => void
178
+ } = {}
179
+
180
+ /** `navigate()`: replace the history entry, and keep the scroll. */
181
+ export interface NavigateOptions {
182
+ /** Replace the history entry instead of pushing one. */
183
+ replace?: boolean | undefined
184
+ /** Keep the scroll position (default: top, or the URL's #hash). */
185
+ scroll?: false
186
+ }
187
+
188
+ /** This tab's line to the app's other tabs: a list of tags a write invalidated, or `0` when the session changed. */
189
+ export const peers =
190
+ typeof document !== 'undefined' && typeof BroadcastChannel !== 'undefined'
191
+ ? new BroadcastChannel('kerf:tags')
192
+ : undefined
193
+
194
+ /** Go to `href` without a page load (a full load before `start()` ran, or for another origin). */
195
+ export function navigate(href: string, options?: NavigateOptions): Promise<void> {
196
+ if (client.navigate) return client.navigate(href, options)
197
+ location.assign(href)
198
+ return Promise.resolve()
199
+ }
package/src/routes.mjs ADDED
@@ -0,0 +1,193 @@
1
+ // File routes (research 25 §2): `src/routes` → a route manifest, plain data that the server, the client table, the
2
+ // Vite plugin and `kerf routes` all read. Conventions:
3
+ //
4
+ // index.tsx /
5
+ // about.tsx /about
6
+ // users/[id].tsx /users/:id (router-core path `/users/$id`)
7
+ // docs/[...rest].tsx /docs/* (router-core splat `$`, the param is `rest`)
8
+ // _layout.tsx wraps every route in its directory and below (the root one wraps the whole app)
9
+ // 404.tsx the not-found page (root only), rendered inside the root layout with status 404
10
+ // _error.tsx the error page (root only), rendered inside the root layout with status 500
11
+ // users/[id].og.tsx the share card of `users/[id]` (research 20 §4); `_default.og.tsx` replaces the built-in card
12
+ //
13
+ // Any other file or directory starting with `_` is ignored, and so are tests. A route module may export `default`
14
+ // (the component), `load`, `meta` and `prerender` (research 20 §3, §4.3).
15
+
16
+ import { existsSync, readdirSync, statSync } from 'node:fs'
17
+ import { join, relative } from 'node:path'
18
+
19
+ const EXT = /\.(tsx|jsx|ts|js)$/
20
+ const posix = (p) => p.split('\\').join('/')
21
+
22
+ /**
23
+ * @typedef {{ id: string, file: string, layouts: string[], path: string, pattern: string, params: string[], splat?: string, rank: number[], card?: string, kind: 'page' | '404' | 'error' }} RouteEntry
24
+ * @typedef {{ id: string, file: string, dir: string, parent?: string }} LayoutEntry
25
+ * @typedef {{ root: string, dir: string, routes: RouteEntry[], layouts: LayoutEntry[], defaultCard?: string, problems: { file: string, message: string }[] }} Manifest
26
+ */
27
+
28
+ /** Scan `<root>/src/routes` (or `dir`). Paths in the manifest are relative to `root`, POSIX-style. */
29
+ export function scanRoutes(root, dir = join(root, 'src', 'routes')) {
30
+ /** @type {Manifest} */
31
+ const out = { root, dir: posix(relative(root, dir)), routes: [], layouts: [], problems: [] }
32
+ if (!existsSync(dir)) return out
33
+ const files = []
34
+ const walk = (d) => {
35
+ for (const name of readdirSync(d).sort()) {
36
+ const abs = join(d, name)
37
+ if (statSync(abs).isDirectory()) {
38
+ if (!name.startsWith('_') && !name.startsWith('.')) walk(abs)
39
+ } else if (EXT.test(name) && !/\.(test|spec)\.|\.d\.ts$/.test(name))
40
+ files.push(posix(relative(dir, abs)))
41
+ }
42
+ }
43
+ walk(dir)
44
+
45
+ const rel = (f) => posix(relative(root, join(dir, f)))
46
+ const layoutFile = new Map() // route dir ('' = root) → its _layout file
47
+ for (const f of files) {
48
+ const m = /^(?:(.*)\/)?_layout\.[jt]sx?$/.exec(f)
49
+ if (m) layoutFile.set(m[1] ?? '', f)
50
+ }
51
+ const layoutOf = new Map([...layoutFile.keys()].map((d) => [d, `layout:${d}`]))
52
+ for (const [d, f] of [...layoutFile].sort((a, b) => a[0].length - b[0].length)) {
53
+ out.layouts.push({
54
+ id: layoutOf.get(d),
55
+ file: rel(f),
56
+ dir: d,
57
+ parent: chain(d, layoutOf).at(-2),
58
+ })
59
+ }
60
+
61
+ const cards = new Map()
62
+ for (const f of files) {
63
+ const m = /^(.*)\.og\.[jt]sx?$/.exec(f)
64
+ if (!m) continue
65
+ if (m[1] === '_default') out.defaultCard = rel(f)
66
+ else cards.set(m[1], rel(f))
67
+ }
68
+
69
+ appendRoutes(files, out, rel, layoutOf, cards)
70
+ out.routes.sort((a, b) => cmpRank(a.rank, b.rank) || a.id.localeCompare(b.id))
71
+ for (const [b, file] of cards)
72
+ if (!out.routes.some((r) => r.card === file))
73
+ out.problems.push({ file, message: `no route \`${b}\` for this card` })
74
+ return out
75
+ }
76
+
77
+ function appendRoutes(files, out, rel, layoutOf, cards) {
78
+ for (const f of files) {
79
+ const base = f.replace(EXT, '')
80
+ const name = base.split('/').pop()
81
+ if (base.endsWith('.og') || name === '_layout' || name === '_default') continue
82
+ const d = base.includes('/') ? base.slice(0, base.lastIndexOf('/')) : ''
83
+ if (name === '404' || name === '_error') {
84
+ if (d) {
85
+ out.problems.push({
86
+ file: rel(f),
87
+ message: `\`${name}\` is only read at the routes root for now; this one is ignored`,
88
+ })
89
+ continue
90
+ }
91
+ out.routes.push({
92
+ id: name === '404' ? '404' : 'error',
93
+ file: rel(f),
94
+ layouts: chain('', layoutOf),
95
+ path: '',
96
+ pattern: '',
97
+ params: [],
98
+ rank: [],
99
+ kind: name === '404' ? '404' : 'error',
100
+ })
101
+ continue
102
+ }
103
+ if (name.startsWith('_') || d.split('/').some((s) => s.startsWith('_'))) continue
104
+ const segs = base === 'index' ? [] : base.split('/')
105
+ if (segs.at(-1) === 'index') segs.pop()
106
+ const params = []
107
+ let splat
108
+ const parts = []
109
+ let bad = false
110
+ for (const s of segs) {
111
+ const p = /^\[(\.\.\.)?([A-Za-z_$][\w$]*)\]$/.exec(s)
112
+ if (p) {
113
+ if (p[1]) splat = p[2]
114
+ params.push(p[2])
115
+ parts.push(p[1] ? '$' : `$${p[2]}`)
116
+ } else if (/[[\]]/.test(s)) bad = true
117
+ else parts.push(s)
118
+ }
119
+ if (bad) {
120
+ out.problems.push({
121
+ file: rel(f),
122
+ message: 'a segment mixes text and a `[param]`; use a whole segment `[name]`',
123
+ })
124
+ continue
125
+ }
126
+ if (splat && parts.at(-1) !== '$') {
127
+ out.problems.push({ file: rel(f), message: '`[...rest]` must be the last segment' })
128
+ continue
129
+ }
130
+ const pattern = '/' + parts.join('/')
131
+ out.routes.push({
132
+ id: pattern,
133
+ file: rel(f),
134
+ layouts: chain(d, layoutOf),
135
+ path: '/' + segs.join('/'),
136
+ pattern,
137
+ params,
138
+ splat,
139
+ // Static segments outrank params, params outrank a splat (router-core's order; the client table uses it).
140
+ rank: parts.map((p) => (p === '$' ? 0 : p.startsWith('$') ? 1 : 2)),
141
+ card: cards.get(base),
142
+ kind: 'page',
143
+ })
144
+ }
145
+ }
146
+
147
+ /** Layout ids from the root down to `d`. */
148
+ function chain(d, layoutOf) {
149
+ const out = []
150
+ const parts = d ? d.split('/') : []
151
+ for (let i = 0; i <= parts.length; i++) {
152
+ const id = layoutOf.get(parts.slice(0, i).join('/'))
153
+ if (id) out.push(id)
154
+ }
155
+ return out
156
+ }
157
+
158
+ function cmpRank(a, b) {
159
+ for (let i = 0; i < Math.max(a.length, b.length); i++) {
160
+ // Shorter after: `/users/new` is tried before `/users/$id/edit`… only on ties. But a splat also matches nothing, so
161
+ // the route it would extend comes first: `/docs` before `/docs/$`, or the splat takes `/docs` itself.
162
+ if (a[i] === undefined) return b[i] === 0 && b.length === i + 1 ? -1 : 1
163
+ if (b[i] === undefined) return a[i] === 0 && a.length === i + 1 ? 1 : -1
164
+ if (a[i] !== b[i]) return b[i] - a[i]
165
+ }
166
+ return 0
167
+ }
168
+
169
+ /** `/users/$id` with `{ id: '42' }` → `/users/42`; a splat fills `$`. */
170
+ export function fillPath(pattern, params) {
171
+ return pattern.replace(/\$([\w$]*)/g, (_, name) => {
172
+ const v = params[name || '_splat'] ?? params[name]
173
+ return name ? encodeURIComponent(String(v)) : String(v ?? '')
174
+ })
175
+ }
176
+
177
+ /** A route's file path as authors write it in types: `src/routes/users/[id].tsx` → `/users/[id]`, `index.tsx` → `/`. */
178
+ export function filePath(manifest, route) {
179
+ return (
180
+ '/' +
181
+ route.file
182
+ .slice(manifest.dir.length + 1)
183
+ .replace(EXT, '')
184
+ .replace(/(^|\/)index$/, '')
185
+ )
186
+ }
187
+
188
+ /** `.kerf/routes.d.ts`: every route path, so `RouteProps<…, '/users/[id]'>` and `Meta<…, path>` only take real ones. */
189
+ export function routeTypes(manifest) {
190
+ const pages = manifest.routes.filter((r) => r.kind === 'page')
191
+ const lines = pages.map((r) => ` '${filePath(manifest, r)}': true`)
192
+ return `// Generated by kerf from ${manifest.dir}. Do not edit.\nimport '@kerf-js/start'\ndeclare module '@kerf-js/start' {\n interface RouteFiles {\n${lines.join('\n')}\n }\n}\n`
193
+ }