@kerf-js/cli 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 (176) hide show
  1. package/LICENSE +16 -0
  2. package/README.md +554 -2
  3. package/bin/kerf.mjs +15 -0
  4. package/docs/async.md +50 -0
  5. package/docs/browser.md +53 -0
  6. package/docs/config.md +127 -0
  7. package/docs/core.md +30 -0
  8. package/docs/deploy.md +108 -0
  9. package/docs/design.md +106 -0
  10. package/docs/entrypoints.md +83 -0
  11. package/docs/fonts.md +118 -0
  12. package/docs/icons.md +108 -0
  13. package/docs/lists.md +25 -0
  14. package/docs/meta.md +92 -0
  15. package/docs/plugins.md +166 -0
  16. package/docs/props.md +88 -0
  17. package/docs/reactivity.md +26 -0
  18. package/docs/rules.md +39 -0
  19. package/docs/rust.md +253 -0
  20. package/docs/start-short.md +10 -0
  21. package/docs/start.md +642 -0
  22. package/docs/state.md +122 -0
  23. package/docs/style.md +82 -0
  24. package/docs/surface.md +158 -0
  25. package/docs/testing.md +81 -0
  26. package/docs/theme.md +263 -0
  27. package/docs/ui-state.md +105 -0
  28. package/docs/verify.md +61 -0
  29. package/package.json +47 -3
  30. package/src/add/config.mjs +93 -0
  31. package/src/add/errors.mjs +2 -0
  32. package/src/add/setup.mjs +88 -0
  33. package/src/add-rust.mjs +178 -0
  34. package/src/add.mjs +392 -0
  35. package/src/agents-md.mjs +240 -0
  36. package/src/alias.mjs +70 -0
  37. package/src/audit/page.mjs +313 -0
  38. package/src/audit/report.mjs +69 -0
  39. package/src/audit/utils.mjs +5 -0
  40. package/src/audit.mjs +319 -0
  41. package/src/browser/cli.mjs +53 -0
  42. package/src/browser/client.mjs +299 -0
  43. package/src/browser/commands.mjs +258 -0
  44. package/src/capture.mjs +21 -0
  45. package/src/catalog/audit.mjs +129 -0
  46. package/src/catalog/auth.mjs +40 -0
  47. package/src/catalog/compiler.mjs +337 -0
  48. package/src/catalog/contracts.mjs +18 -0
  49. package/src/catalog/database.mjs +52 -0
  50. package/src/catalog/deploy.mjs +117 -0
  51. package/src/catalog/design.mjs +159 -0
  52. package/src/catalog/forms.mjs +25 -0
  53. package/src/catalog/hydration.mjs +29 -0
  54. package/src/catalog/icons.mjs +24 -0
  55. package/src/catalog/media.mjs +163 -0
  56. package/src/catalog/metadata.mjs +116 -0
  57. package/src/catalog/plugins.mjs +228 -0
  58. package/src/catalog/realtime.mjs +195 -0
  59. package/src/catalog/rust.mjs +75 -0
  60. package/src/catalog/server-functions.mjs +100 -0
  61. package/src/catalog/state.mjs +39 -0
  62. package/src/catalog/style-groups.mjs +54 -0
  63. package/src/catalog/tests.mjs +127 -0
  64. package/src/catalog/text.mjs +200 -0
  65. package/src/catalog/ui-state.mjs +42 -0
  66. package/src/catalog.mjs +103 -0
  67. package/src/check/runtime.mjs +280 -0
  68. package/src/check.mjs +321 -0
  69. package/src/cli/authoring.mjs +213 -0
  70. package/src/cli/project.mjs +302 -0
  71. package/src/cli.mjs +340 -0
  72. package/src/config.d.ts +1 -0
  73. package/src/config.mjs +5 -0
  74. package/src/contributions.mjs +119 -0
  75. package/src/db-layer.mjs +41 -0
  76. package/src/deploy/cdn.mjs +142 -0
  77. package/src/deploy/files.mjs +266 -0
  78. package/src/deploy/fit.mjs +166 -0
  79. package/src/deploy/hosts.mjs +126 -0
  80. package/src/deploy/index/cli.mjs +20 -0
  81. package/src/deploy/index/environment.mjs +69 -0
  82. package/src/deploy/index/steps.mjs +87 -0
  83. package/src/deploy/index.mjs +387 -0
  84. package/src/deploy/needs.mjs +149 -0
  85. package/src/design-checks/accessible-names.mjs +62 -0
  86. package/src/design-checks/contrast.mjs +43 -0
  87. package/src/design-checks/csp.mjs +60 -0
  88. package/src/design-checks/files.mjs +59 -0
  89. package/src/design-checks/heading-links.mjs +61 -0
  90. package/src/design-checks/interaction.mjs +65 -0
  91. package/src/design-checks/jsx.mjs +67 -0
  92. package/src/design-checks/layout-values.mjs +68 -0
  93. package/src/design-checks/native-controls.mjs +48 -0
  94. package/src/design-checks/outline.mjs +39 -0
  95. package/src/design-checks/reporter.mjs +37 -0
  96. package/src/design-checks/rules.mjs +274 -0
  97. package/src/design-checks/values.mjs +262 -0
  98. package/src/design-checks.mjs +49 -0
  99. package/src/diag.mjs +98 -0
  100. package/src/docs.mjs +228 -0
  101. package/src/doctor.mjs +42 -0
  102. package/src/files.mjs +60 -0
  103. package/src/fix.mjs +48 -0
  104. package/src/gate/after.mjs +40 -0
  105. package/src/gate/before.mjs +54 -0
  106. package/src/gate/classify.mjs +72 -0
  107. package/src/gate/mutation.mjs +209 -0
  108. package/src/gate/resolve-cases.mjs +22 -0
  109. package/src/gate/result.mjs +63 -0
  110. package/src/gate/run.mjs +75 -0
  111. package/src/gate.mjs +178 -0
  112. package/src/index.mjs +9 -0
  113. package/src/infer/box-props.cjs +140 -0
  114. package/src/infer/core-boxes.cjs +46 -0
  115. package/src/infer/derived-writes.cjs +95 -0
  116. package/src/infer/engine/checks.cjs +193 -0
  117. package/src/infer/engine/flow.cjs +293 -0
  118. package/src/infer/engine/report.cjs +158 -0
  119. package/src/infer/engine/utils.cjs +15 -0
  120. package/src/infer/engine.cjs +265 -0
  121. package/src/infer/facts/sites.cjs +114 -0
  122. package/src/infer/facts.cjs +345 -0
  123. package/src/infer/hosts.cjs +161 -0
  124. package/src/infer/lsp.mjs +240 -0
  125. package/src/infer/session.cjs +161 -0
  126. package/src/infer/shadow.cjs +54 -0
  127. package/src/infer/worker.cjs +145 -0
  128. package/src/jsx-scan.mjs +128 -0
  129. package/src/kerf.mjs +98 -0
  130. package/src/load-config/schema.mjs +300 -0
  131. package/src/load-config.mjs +302 -0
  132. package/src/map.mjs +177 -0
  133. package/src/mcp/browser-tools.mjs +155 -0
  134. package/src/mcp.mjs +273 -0
  135. package/src/meta-table.mjs +63 -0
  136. package/src/mutate.mjs +224 -0
  137. package/src/plugin-checks.mjs +118 -0
  138. package/src/plugins.mjs +258 -0
  139. package/src/project.mjs +310 -0
  140. package/src/props-checks.mjs +64 -0
  141. package/src/props-listener.mjs +56 -0
  142. package/src/react-checks.mjs +67 -0
  143. package/src/server-state-checks.mjs +34 -0
  144. package/src/share-checks.mjs +158 -0
  145. package/src/site.mjs +46 -0
  146. package/src/slots.mjs +181 -0
  147. package/src/start/build.mjs +116 -0
  148. package/src/start/routes.mjs +38 -0
  149. package/src/start.mjs +394 -0
  150. package/src/state-checks/core-state.mjs +223 -0
  151. package/src/state-checks/modules.mjs +17 -0
  152. package/src/state-checks/scan.mjs +232 -0
  153. package/src/state-checks/server-graph.mjs +65 -0
  154. package/src/state-checks.mjs +189 -0
  155. package/src/style/find.mjs +121 -0
  156. package/src/style.mjs +327 -0
  157. package/src/surface-checks.mjs +384 -0
  158. package/src/tailwind.mjs +23 -0
  159. package/src/tasks.mjs +261 -0
  160. package/src/test-rules/context.mjs +109 -0
  161. package/src/test-rules/file-rules.mjs +279 -0
  162. package/src/test-rules/rule-helpers.mjs +244 -0
  163. package/src/test-rules/syntax.mjs +223 -0
  164. package/src/test-rules/test-rules.mjs +127 -0
  165. package/src/testdiff.mjs +219 -0
  166. package/src/tests.mjs +120 -0
  167. package/src/text-checks.mjs +332 -0
  168. package/src/tokens.mjs +33 -0
  169. package/src/trust/scan.mjs +95 -0
  170. package/src/trust.mjs +394 -0
  171. package/src/workspace.mjs +182 -0
  172. package/ts-plugin/context.js +57 -0
  173. package/ts-plugin/index.js +17 -0
  174. package/ts-plugin/mapping.js +65 -0
  175. package/ts-plugin/package.json +1 -0
  176. package/ts-plugin/proxy.js +144 -0
package/docs/start.md ADDED
@@ -0,0 +1,642 @@
1
+ # Full stack: `@kerf-js/start`
2
+
3
+ Needs one of Node, Bun or Deno, and no Rust (`kerf docs rust` is opt-in). An app builds for and runs on all three.
4
+
5
+ ## Files
6
+
7
+ ```
8
+ src/routes/** file routes: _layout.tsx, index.tsx,
9
+ [id].tsx, [...rest].tsx, 404.tsx,
10
+ _error.tsx
11
+ src/server/** queries and mutations (client gets stubs);
12
+ a Rust body: `kerf docs rust`
13
+ src/db/schema.ts Drizzle tables; safe to import anywhere
14
+ src/db/index.server.ts the database client
15
+ src/auth.server.ts auth provider (Better Auth by default),
16
+ mounted at /api/auth/*
17
+ src/context.server.ts what `ctx` holds
18
+ ```
19
+
20
+ Any auth provider works: `defineAuth` from `@kerf-js/start/auth` takes a `handler(request)` for `/api/auth/*` and a
21
+ `session(request)` that returns `{ user, session }`. `ctx.user` and `auth: 'user'` come from those two.
22
+
23
+ ## Routes
24
+
25
+ <!-- example: skip needs the app's own getList query -->
26
+ ```tsx
27
+ // src/routes/lists/[id].tsx
28
+ import type { LoadArgs, Meta, RouteProps } from '@kerf-js/start'
29
+ import { getList } from '#/server/lists'
30
+
31
+ export const load = async ({ params }: LoadArgs<'/lists/[id]'>) => ({
32
+ list: await getList.fetch({ id: params.id }),
33
+ })
34
+ export const meta: Meta<typeof load> = ({ data }) => ({
35
+ title: data.list.name,
36
+ })
37
+ export default function List(
38
+ props: RouteProps<typeof load, '/lists/[id]'>,
39
+ ) {
40
+ const { data } = props
41
+ return <h1>{data.list.name}</h1>
42
+ }
43
+ ```
44
+
45
+ `props.data` and `const { data } = props` stay live; compute from them in JSX or `derived`, not in the component body (W001).
46
+
47
+ Import your own code as `#/server/todos`, which is `src/server/todos`. That alias is `paths` in `tsconfig.json`: change it or add your own there, and Vite and `kerf check` follow. Generated files have their own prefix: `kerf:slot/<id>` and `kerf:tokens/<name>`.
48
+
49
+ `load` and `meta` never ship to the client. A layout's `load` runs before its children's, so it's where a guard goes.
50
+ A layout's `params` are its page's, a `[...rest]` included, so a layout can mark the page it shows.
51
+ Set `meta` on every page as part of building it: a title and one plain sentence from what is on the page. On a param
52
+ route build it from `data` and `params`. `kerf docs meta` has the rest.
53
+ Links are `<Link href>`; code navigates with `navigate(href)`.
54
+
55
+ Navigation is instant: the URL and `aria-current` change on click, kept layouts stay, and the level that changes shows a
56
+ skeleton made from its markup until its data arrives. Never build a loading state for a route change yourself. When the
57
+ made one doesn't fit (a page that is one big component, a hero), name a function of plain markup and export it:
58
+
59
+ ```tsx
60
+ function HomeSkeleton() {
61
+ return (
62
+ <section data-site="hero">
63
+ <h1>Your headline</h1>
64
+ <p data-skeleton></p>
65
+ </section>
66
+ )
67
+ }
68
+ export const skeleton = HomeSkeleton
69
+ ```
70
+
71
+ It runs before the page's code loads, so only `div span section article main header footer p h1-h6 ul ol li`, string
72
+ `class`/`data-*` attributes and text; anything else warns and leaves no skeleton. `export const skeleton = false` keeps
73
+ the old page up instead.
74
+
75
+ Chrome shared by several sections (a sidebar, section tabs) goes in the one layout above them, following the URL with
76
+ `currentPath()` from `@kerf-js/start`. A `_layout.tsx` per section is replaced, chrome and all, whenever you move
77
+ between sections, so the sidebar flashes and is rebuilt. Keep `{props.children}` in the same parent on every page.
78
+
79
+ ## Server functions
80
+
81
+ ```ts
82
+ // src/server/todos.ts
83
+ import { mutation, query } from '@kerf-js/start'
84
+ import { schemasOf } from '@kerf-js/start/db'
85
+ import { eq } from 'drizzle-orm'
86
+ import { z } from 'zod'
87
+ import * as schema from '#/db/schema'
88
+
89
+ const { todos } = schema
90
+ const schemas = schemasOf(schema, {
91
+ todos: { title: (s: z.ZodString) => s.trim().min(1) },
92
+ })
93
+
94
+ export const listTodos = query({
95
+ tags: ['todos'], // what invalidates it
96
+ auth: 'user', // anyone else gets A002; ctx.user is non-null
97
+ run: ({ ctx }) => ctx.db
98
+ .select()
99
+ .from(todos)
100
+ .where(eq(todos.userId, ctx.user.id)),
101
+ })
102
+
103
+ export const addTodo = mutation({
104
+ input: schemas.todos.insert.pick({ title: true }),
105
+ auth: 'user',
106
+ invalidates: ['todos'], // tagged queries return in the response
107
+ optimistic: ({ input }, cache) => {
108
+ return cache.update(listTodos, undefined, l => void l.push({
109
+ id: `tmp:${input.title}`,
110
+ title: input.title,
111
+ done: false,
112
+ userId: '',
113
+ createdAt: 0,
114
+ }))
115
+ },
116
+ run: async ({ input, ctx }) => {
117
+ const [row] = await ctx.db
118
+ .insert(todos)
119
+ .values({
120
+ id: crypto.randomUUID(),
121
+ userId: ctx.user.id,
122
+ createdAt: Date.now(),
123
+ ...input,
124
+ })
125
+ .returning()
126
+ return row
127
+ },
128
+ })
129
+ ```
130
+
131
+ - `q()` in a component or `defineState` setup: a `Resource`. `(q().value ?? []).map(…)`. `q(() => (id.value ? { id: id.value } : skip))` for a tracked input. Created inside a `<Boundary pending={…}>`, the server streams it; created outside one, the first byte waits for it.
132
+ - `await q.fetch(input)` in `load`, handlers and other server functions (Q001 otherwise).
133
+ - `m(input)` in handlers. `m.pending.value`, `m.error.value`. It rejects with an `FnError`: `.message`, `.code`, `.status`, `.issues`.
134
+ - Refuse with `throw new FnError({ message: 'Not yours' }, 403)`, a user-facing message and a status.
135
+ - `redirect('/x')` in `load` (307) or `run` (the client follows).
136
+ - `tags: ({ id }) => ['todos', `todo:${id}`]` and `invalidates: ({ id }) => […]` take the input.
137
+ - `cache: { life: 'minutes' }` shares a value across requests, so it can't read `ctx.user` (Q006); add `scope: 'user'` for one value per user.
138
+ - `output: schema` is checked in dev (C002) and goes in `.kerf/contract.json`.
139
+
140
+ A table a function touches must be in its `tags`/`invalidates` (Q011): a tag named after the table, or `table:…`.
141
+
142
+ **`auth: 'user'` says who is calling, not what they may touch.** A `run` taking a row's id must check that row belongs
143
+ to `ctx.user`. `and(eq(todos.id, input.id), eq(todos.userId, ctx.user.id))` in the `where` is the usual way.
144
+
145
+ ## Publishing
146
+
147
+ For content an owner edits and every visitor reads (a menu, settings, pages, a search index). Visitors read from the
148
+ shared cache, edits go to a draft the owner can preview, and publishing refreshes the cache before the next visitor
149
+ arrives.
150
+
151
+ ```ts
152
+ // what every visitor reads: cached, and re-run in the
153
+ // background the moment an edit invalidates it
154
+ export const menu = query({
155
+ tags: ['menu'],
156
+ cache: { life: 'hours', warm: true },
157
+ run: ({ ctx }) => readMenu(ctx.db),
158
+ })
159
+
160
+ // the owner previews a draft; publishing applies it
161
+ export const startPreview = mutation({
162
+ input: z.object({ draft: z.int() }),
163
+ auth: 'user',
164
+ run: ({ input }) => preview.start(String(input.draft)),
165
+ })
166
+ export const publish = mutation({
167
+ input: z.object({ draft: z.int() }),
168
+ auth: 'user',
169
+ invalidates: ['menu'],
170
+ run: async ({ input, ctx }) => {
171
+ await applyDraft(ctx.db, input.draft)
172
+ preview.stop()
173
+ // once the response is out: the owner never waits
174
+ after(() => writeSnapshot())
175
+ },
176
+ })
177
+ ```
178
+
179
+ - `warm: true` is for values that every visitor shares: no `auth` and no `scope: 'user'`.
180
+ - `preview.start(value)` sets an http-only cookie. While it's there, every query on that browser runs fresh and is
181
+ never written to the shared cache, so draft data can't leak to anyone else. What the value means is the app's:
182
+ `src/context.server.ts` reads `preview.id()`, checks that `ctx.user` may see that draft, and gives `run` a `db`
183
+ with the draft applied (for example, a transaction that `after()` rolls back).
184
+ - A mutation's refreshes read as the browser's next GET will, with the preview cookie the mutation set or cleared.
185
+ The admin sees its draft as it saves, and its live data again right after `preview.stop()`.
186
+ - `after(fn)` runs once the response has finished streaming or the call has answered, including when the visitor
187
+ leaves early. Use it for a rollback, a snapshot, a git push or an email. A failure is reported as `E_AFTER` and
188
+ doesn't stop the rest.
189
+
190
+ ## Form fields
191
+
192
+ `form.field(name)` restores the raw submitted value, which can
193
+ be a string or an array for repeated names. Pass `'text'` or
194
+ `'email'` as the second argument for a string-valued input:
195
+ `form.field('email', 'email')`. If a name was repeated, these
196
+ modes restore its first value. Pass `'multiple'` to restore an
197
+ array, including when only one value was submitted. Missing
198
+ values stay absent. Use the raw default for checkbox and radio
199
+ fields when their submitted values need no projection.
200
+ `form.value(name)` always reads the raw restored value.
201
+
202
+ ## Database
203
+
204
+ Drizzle, async on every driver: `await ctx.db.select()…`, `const [row] = await ….returning()`,
205
+ `await ctx.db.transaction(async tx => …)`. Change `src/db/schema.ts`, run `kerf db generate` (Q015 until
206
+ you do), reload: migrations apply before the next statement a request runs (Q014 names a missing table). Never edit
207
+ `drizzle/` by hand. A page with no queries needs no database: with it down it still serves, and a request that does use
208
+ it answers 503 with Q016, then works once the database is back, no restart.
209
+
210
+ Access beyond ownership goes in the `where`, so a stranger's id matches no row: `and(eq(todos.id, input.id),
211
+ or(eq(todos.userId, ctx.user.id), exists(ctx.db.select({ one: sql\`1\` }).from(shares).where(…))))`. A mutation touching
212
+ two queries' rows calls `cache.update` once for each in `optimistic`, and names both tags in `invalidates`. Tags are
213
+ tables' names: Q011 checks them at run time, in `kerf dev`, not in `kerf check`.
214
+
215
+ ## Auth
216
+
217
+ `ctx.user` and `ctx.session` come from `session(auth, request)` (`@kerf-js/start/auth`) in `src/context.server.ts`. Sign-in is a mutation:
218
+
219
+ ```ts
220
+ // src/server/session.ts
221
+ import { mutation, redirect } from '@kerf-js/start'
222
+ import { forward } from '@kerf-js/start/auth'
223
+ import { z } from 'zod'
224
+ import auth from '#/auth.server'
225
+
226
+ export const signIn = mutation({
227
+ auth: 'public',
228
+ input: z.object({ email: z.email(), password: z.string().min(8) }),
229
+ run: async ({ input, ctx }) => {
230
+ await forward(ctx, auth.api.signInEmail({
231
+ body: input,
232
+ headers: ctx.request.headers,
233
+ asResponse: true,
234
+ }))
235
+ // A new session needs a full load; cached data won't survive.
236
+ redirect('/todos') // A004 without a full load
237
+ },
238
+ })
239
+ ```
240
+
241
+ A guard: `export const load = ({ ctx }: LoadArgs) => ctx.user ?? redirect('/login')` in the layout above the pages.
242
+
243
+ `BETTER_AUTH_URL` in `.env` must match where the app runs: on another port (`kerf dev --port`), sign-in answers
244
+ `INVALID_ORIGIN`.
245
+
246
+ **Login is an opaque token in the database, not a JWT.** The HTTP-only cookie holds a random token, so a session can be
247
+ revoked by deleting its row, and nothing about it can outlive that. A JWT can't be taken back before it expires.
248
+
249
+ **The session cache.** `createAuth` turns on Better Auth's cookie cache: an HTTP-only `session_data` cookie (`compact`:
250
+ signed, not encrypted) that spares a page and a query their two
251
+ session reads for **5 minutes**. So a revoked session can still be shown pages for up to 5 minutes. It can't write: a
252
+ mutation, a realtime connection and Better Auth's own routes always read the database, without you asking, and
253
+ sign-out and a password change clear the cookie. A request past the window reads the database and renews it.
254
+
255
+ ```ts
256
+ // A shorter window
257
+ createAuth({
258
+ db, secret,
259
+ options: { database, session: { cookieCache: { maxAge: 60 } } },
260
+ })
261
+ // Every request reads the database
262
+ createAuth({
263
+ db, secret,
264
+ options: {
265
+ database, session: { cookieCache: { enabled: false } },
266
+ },
267
+ })
268
+ ```
269
+
270
+ A hand-written provider follows the same rule: its `session` may cache for GET, never for another method.
271
+
272
+ **API access.** JWTs are for other services and API clients only, and never log a browser in. `GET /api/auth/token`, with a
273
+ live session, gives a token good for 15 minutes; `GET /api/auth/jwks` is public, so a service verifies it with the public
274
+ keys and no database (`iss` and `aud` are `BETTER_AUTH_URL`). Signing keys live in the `jwks` table of the auth schema. A
275
+ function takes a token only if it's listed, and `auth: 'user'` still applies:
276
+
277
+ ```ts
278
+ createAuth({
279
+ db, secret, options,
280
+ api: {
281
+ functions: () => [orders, shipOrder],
282
+ jwt: {
283
+ audience: 'https://api.example.com', expirationTime: '15m',
284
+ },
285
+ },
286
+ })
287
+ ```
288
+
289
+ GET /_kerf/fn/<id>?i=<json> authorization: Bearer <token>
290
+ POST /_kerf/fn/<id> authorization: Bearer <token>, content-type: application/json, x-kerf: 1, body {"i": input}
291
+
292
+ `<id>` is `fnOf(orders).$id`. `ctx.user` is what the token says and `ctx.session` is `null`. An unlisted function ignores the
293
+ token. A token can't be revoked, so reads last until it expires; a mutation also checks that its session still exists.
294
+ With no `BETTER_AUTH_URL` or fixed `baseURL`, no token is accepted, since nothing could check `iss` and `aud`.
295
+ `api: false` removes all of this.
296
+
297
+ ## Runtimes
298
+
299
+ The CLI runs on whichever of the three starts it, with none of the others installed: `bun --bun`, or `deno run -A
300
+ npm:@kerf-js/cli`. `npm create kerf`, `bun create kerf` and `deno run -A npm:create-kerf` each scaffold for their own runtime
301
+ and package manager. HMR and sockets in `kerf dev` work on all three.
302
+
303
+ A save in `kerf dev` keeps the page: a component or route swaps in place with its `state`, typed input, focus and scroll;
304
+ CSS updates; a change to `load`, `meta` or server code refetches the page's data in place. `state` keeps its value while
305
+ its name and initializer stay the same. Adding or removing a route, or a module that exports more than components with
306
+ nothing above it to take the update, is a full reload, and the terminal says why. A tab that hit a syntax error comes back
307
+ when it's fixed.
308
+
309
+ `kerf build` targets `runtime` in kerf.config.ts (`node`, `bun`, `deno`; `--runtime` overrides), which is the runtime
310
+ that ran it if unset, and writes `.output/` and `.kerf/contract.json`. Runtime-specific APIs (`Bun.*`, `Deno.*`, `better-sqlite3`) in server
311
+ code break the other targets; `node:` modules and web APIs work on all three.
312
+
313
+ ## Realtime
314
+
315
+ Never poll, and never open a socket yourself (R007, T013): a live query, a `stream` and a `channel` reconnect, resume and
316
+ clean up for you.
317
+
318
+ **Live queries need no server code.** Tags are the contract: any mutation that invalidates one of the query's tags,
319
+ on any tab, refetches it for every reader. Unchanged rows keep their identity, so the page writes what changed.
320
+
321
+ ```tsx
322
+ // Same Resource as listTodos(), plus todos.live.value
323
+ const todos = listTodos.live()
324
+ // 'connecting' | 'live' | 'degraded' | 'reconnecting' | 'offline'
325
+ <p>{todos.live.value}</p>
326
+ ```
327
+
328
+ A live query needs `tags` (W053), and its mutations need one of them in `invalidates` (R003 in dev).
329
+
330
+ **Topics and streams carry messages.** Define them in server modules, next to queries:
331
+
332
+ ```ts
333
+ // src/server/prices.ts
334
+ import { stream, topic } from '@kerf-js/start'
335
+ import { z } from 'zod'
336
+
337
+ const Price = z.object({ symbol: z.string(), price: z.number() })
338
+
339
+ export const priceTopic = topic('prices', {
340
+ key: z.string().max(12), message: Price,
341
+ })
342
+ export const prices = stream({
343
+ // Bound the input (R005).
344
+ input: z.object({ symbols: z.array(z.string().max(12)).max(50) }),
345
+ message: Price,
346
+ auth: 'user', // optional; re-checked every 5 minutes
347
+ async *run({ input, signal, lastEventId }) {
348
+ // Subscribe first (R006).
349
+ yield* priceTopic.subscribe(input.symbols, {
350
+ signal, after: lastEventId,
351
+ })
352
+ },
353
+ })
354
+ // Anywhere on the server:
355
+ // await priceTopic.publish('AAPL', { symbol: 'AAPL', price: 1 })
356
+ ```
357
+
358
+ ```tsx
359
+ const tick = prices({ symbols: ['AAPL'] }) // latest: tick.value
360
+ // Input is tracked; `skip` works.
361
+ const board = prices(() => ({ symbols: syms.value }), {
362
+ fold: (acc, m) => ({ ...acc, [m.symbol]: m }),
363
+ initial: {}, keep: '30s',
364
+ })
365
+ ```
366
+
367
+ Never fold a stream with `watch` into `state` (W052): that list dies with the component. `fold` lives in the cache, so
368
+ a remount within `keep` finds it. Without `fold` you get the latest value, and a slow client skips messages.
369
+ `yield tracked(row.id, row)` from your own source gives a resumed `run` that id as `lastEventId`. `lastEventId` is
370
+ undefined after a reset: start again, or read from the database.
371
+
372
+ **One instance needs nothing.** Several need a bus: `kerf build` refuses the memory bus on a multi-instance preset (R002).
373
+
374
+ ```ts
375
+ // src/realtime.server.ts
376
+ import { realtime } from '@kerf-js/start'
377
+ import { postgresBus } from '@kerf-js/start/bus/postgres'
378
+
379
+ export default realtime({
380
+ bus: postgresBus({ url: process.env.DATABASE_URL! }),
381
+ origins: ['https://other.example'],
382
+ maxDuration: 300,
383
+ })
384
+ ```
385
+
386
+ `postgresBus` needs a direct connection: pgBouncer in transaction mode breaks LISTEN. `maxDuration` is the platform's
387
+ response limit in seconds: streams end 10 s earlier and resume. `stale` is true when the server runs a newer build
388
+ than this tab: offer a reload.
389
+
390
+ `kerf add @kerf-js/realtime-redis` or `@kerf-js/realtime-nats` puts a bus in `plugins`, on `REDIS_URL` or `NATS_URL`; a `bus` set here
391
+ still wins. `durableObjectBus({ namespace })` (`@kerf-js/realtime-durable-object`, the `cloudflare_durable` preset only) needs a
392
+ binding, so it's set here.
393
+
394
+ Payments: `kerf add pay`, then `ctx.entitlements` and `requires: ['pro']` on any function. `kerf docs pay`. A query's `tags`
395
+ can take `ctx`, for one user's tag: `tags: (_, ctx) => [`orders:${ctx.user.id}`]`.
396
+
397
+ **Testing** uses the real hub and client over `@kerf-js/core/test`'s fake transport: `await net.settle()`, then
398
+ `await net.push(prices, message)`, `await net.poke('todos')`, `await net.drop()`, `net.offline()`, `net.reconnects()`,
399
+ `net.subscriptions()`.
400
+
401
+ ## Writes from outside the app
402
+
403
+ `.live()` already follows mutations. A cron job, `psql`, a worker or another service writes nowhere near them: give the database's writes to `realtime` and they reach the same queries, the same way.
404
+
405
+ <!-- example: skip needs a notes table in the app's schema -->
406
+ ```ts
407
+ // src/realtime.server.ts
408
+ import { realtime } from '@kerf-js/start'
409
+ import { dbChanges } from '@kerf-js/start/changes'
410
+ import { db } from '#/db/index.server'
411
+ import { notes } from '#/db/schema'
412
+
413
+ export default realtime({ changes: dbChanges(db, [notes]) })
414
+ ```
415
+
416
+ <!-- example: skip needs a notes table in the app's schema -->
417
+ ```ts
418
+ // src/server/notes.ts
419
+ import { query } from '@kerf-js/start'
420
+ import { eq } from 'drizzle-orm'
421
+ import { notes } from '#/db/schema'
422
+
423
+ export const myNotes = query({
424
+ tags: ['notes'], // table name, or `notes:${id}` for one row
425
+ auth: 'user',
426
+ live: { required: true, verify: 'staging' }, // both optional
427
+ run: ({ ctx }) => ctx.db
428
+ .select()
429
+ .from(notes)
430
+ .where(eq(notes.owner, ctx.user.id)),
431
+ })
432
+ ```
433
+
434
+ Then `kerf db live` writes the migration (triggers for SQLite, MySQL and Postgres), and you apply it. Tags are `notes` and `notes:<pk>`; a compound key joins with `:`. `dbChanges(db, tables, { tagged })` maps a change to your own tags, and for MongoDB it's `mongoChanges(db, collections)` from `@kerf-js/db/mongo`.
435
+
436
+ A notification carries a table and primary keys, never a column. Each client refetches through its own `query`, so `auth` and every filter run for that user: someone who can't see a row gets the same answer as before. An app's own write is not poked twice, and a bulk write is one refetch: over 32 ids in a statement it's a table-level change, which reaches `notes` and every `notes:…`. Limits: at most one flush per 250 ms; a dropped feed pokes every table when it's back.
437
+
438
+ **What you get depends on where it runs**, so ask: `kerf doctor` (`--preset vercel`) says what works for a target, and `kerf check` warns about it. At startup the server tries the real thing, settles on a mode, and logs it once. The same answer is on the page:
439
+
440
+ ```tsx
441
+ const notes = myNotes.live()
442
+ // 'degraded': connected; outside writes arrive late or not at all
443
+ notes.live.value
444
+ notes.liveMode.value // 'feed' | 'external' | 'poll' | 'app' | 'off'
445
+ ```
446
+
447
+ | Mode | Means |
448
+ |---|---|
449
+ | `feed` | This server hears every change. |
450
+ | `external` | A separate listener hears them, and publishes to the bus. |
451
+ | `poll` | A fallback: late, and by table only. `degraded`. |
452
+ | `app` | No `changes`: mutations only. Not degraded; it's what you asked for. |
453
+ | `off` | There's nothing to read: mutations only. `degraded`. |
454
+
455
+ | Database | How | Limits |
456
+ |---|---|---|
457
+ | Postgres | Triggers and NOTIFY, on one held connection | A pooler in transaction mode loses it: the probe finds that out by trying, and falls to `postgres-stats`. Give it a direct connection with `{ listenUrl }`. Applying the migration needs TRIGGER; NOTIFY is limited to 8000 bytes, so big keys are table-level. Row-level security is yours: triggers fire regardless, and the refetch applies it. |
458
+ | SQLite | `PRAGMA data_version` every 100 ms on a second connection, then the triggers' log. This is polling, of the cheapest read there is | Same host only: a network file system turns it `off`. The log holds 4096 rows; a reader past that pokes every table. With no triggers, any commit pokes every listed table. Instances on other machines can't share the file anyway. |
459
+ | MySQL | The triggers' log, read every 500 ms | Polling, with a row in the log per row written. No in-order commit guarantee, so it reads a window of 512 back. Each server prunes old rows from `__kerf_changes`. |
460
+ | MongoDB | A change stream | Needs a replica set: a standalone is `off`. Barriers use a capped `__kerf_barrier`, about 120 ms slower per change. |
461
+
462
+ Polling here is the framework's watcher, in one place on the server. R007 and T013 still hold for your code: never poll in it.
463
+
464
+ **On Vercel, Netlify, Lambda, Azure Functions, Firebase, Cloudflare and Deno Deploy** a process ends with its request, so nothing can hold a connection. Mutations still work, and `.live()` shows `degraded` (R014). Two ways to get the feed: deploy to a server preset, or run one always-on listener anywhere, with a bus both can reach:
465
+
466
+ <!-- example: skip two files in one block; needs a notes table -->
467
+ ```ts
468
+ // listener.ts: on a VPS, Fly or Railway. `kerf db listen` runs it.
469
+ export default realtime({
470
+ bus: postgresBus({ url: env.DATABASE_URL }),
471
+ changes: dbChanges(db, [notes]),
472
+ })
473
+ // the app, on Vercel
474
+ export default realtime({
475
+ bus: postgresBus({ url: env.DATABASE_URL }),
476
+ changes: dbChanges(db, [notes], { listener: 'external' }),
477
+ })
478
+ ```
479
+
480
+ `kerf db listen` loads your server modules from source, so it runs from a checkout with dependencies installed, and with the same env as the app. A listener that stops is noticed: its heartbeat ends, and within a minute `.live()` shows `reconnecting`.
481
+
482
+ **`live: { required: true }`** (or `q.live(input, { required: true })`) refuses to ship a page that only looks live. `kerf check` and `kerf build` fail with R013 when the target can't do it. What only a running server can know fails at startup with R015: the process stops rather than serve stale data, and in dev it says so instead. For a health route, `liveHealth()` from `@kerf-js/start` answers `ok: false` while a required query has no working feed. An outage after a good start reports there too, and doesn't stop the server: restarting wouldn't bring the database back, and the feed recovers by itself.
483
+
484
+ **`verify`** proves the chain end to end on every `kerf check` and `kerf build`, cached by query and contract:
485
+
486
+ ```ts
487
+ live: { required: true, verify: 'staging' } // name in config
488
+ live: { verify: { url: 'https://staging.example.dev' } } // app
489
+ // A database, as an outside writer
490
+ live: { verify: { db: process.env.STAGING_DATABASE_URL } }
491
+ // Finds KERF_STAGING_URL or STAGING_DATABASE_URL
492
+ live: { verify: true }
493
+ ```
494
+
495
+ Setup, once:
496
+
497
+ ```ts
498
+ // kerf.config.ts
499
+ live: {
500
+ targets: { staging: {
501
+ url: 'https://staging.example.dev',
502
+ db: 'STAGING_DATABASE_URL',
503
+ production: false,
504
+ } },
505
+ }
506
+ ```
507
+
508
+ Set `STAGING_DATABASE_URL`, and `KERF_STAGING_COOKIE` and `KERF_STAGING_OTHER_COOKIE` for a signed-in user and one who shouldn't see the row. If the query's table has a required column, say what to write: `verify: { target: 'staging', row: { owner: 'alice' } }`.
509
+
510
+ It writes one marked row through a separate connection, then checks each link: `trigger`, `write`, `notify`, `app`, `poke`, `refetch`, `denied`, `cleanup`. It reports each one's time, and a failure names the link. Both `url` and `db` test the whole chain; with one, it says which links it didn't (R023). Postgres only for now.
511
+
512
+ A target must be named with `production: false`, or have a host that says staging, and anything that looks like production is refused either way (R022). It touches only its own row, marked uniquely so builds don't collide, and removes it even on failure. The row can't sit in a transaction, because NOTIFY only fires on commit. A password in source is an error (R020): read it from the environment. A target that isn't available fails `kerf build`, and warns and skips in `kerf check` and dev (R021).
513
+
514
+ ## Channels
515
+
516
+ `channel` is a WebSocket with named messages each way, for what the client sends often: chat, typing, cursors. For
517
+ anything else use a mutation and `.live()`. Define it in a server module. `authorize` is required (R001), and runs on
518
+ every join and every 5 minutes.
519
+
520
+ <!-- example: skip needs the app's own Message schema, isMember and insertMessage -->
521
+ ```ts
522
+ // src/server/chat.ts
523
+ import { channel } from '@kerf-js/start'
524
+ import { z } from 'zod'
525
+ import { isMember, insertMessage, Message } from '#/server/messages'
526
+
527
+ export const room = channel({
528
+ params: z.object({ roomId: z.string().max(64) }),
529
+ // False gives status 'unauthorized' (R011).
530
+ authorize: ({ ctx, params }) => isMember(ctx.user, params.roomId),
531
+ // Always validated; bound messages (R005).
532
+ client: { say: z.object({ text: z.string().min(1).max(2000) }) },
533
+ server: { said: Message }, // validated in dev and tests
534
+ on: {
535
+ say: async ({ msg, ctx, params, room }) => {
536
+ // Throw StartError or FnError to refuse `send`.
537
+ const row = await insertMessage(ctx, params.roomId, msg.text)
538
+ // { exceptSelf: true } skips the sender.
539
+ await room.publish('said', row)
540
+ },
541
+ },
542
+ limits: { perSecond: 10 }, // default 20 a second per socket
543
+ })
544
+ // From a mutation or a job:
545
+ // await room.in({ roomId }).publish('said', row)
546
+ ```
547
+
548
+ ```tsx
549
+ // Tracked; `skip` leaves; { keep: '30s' }
550
+ const chat = room.connect(() => ({ roomId: props.roomId }))
551
+ // Derived<Message[]>, kept in the cache
552
+ const said = chat.collect('said', { max: 200, key: m => m.id })
553
+ chat.on('typing', ({ userId }) => show(userId)) // owner removes it
554
+ // Resolves on the server's ack; rejects with the refusal
555
+ await chat.send('say', { text })
556
+ // 'connecting' | 'open' | 'reconnecting' | 'closed' | 'unauthorized'
557
+ chat.status.value
558
+ ```
559
+
560
+ **The channel is a wire, not a log.** A reconnect replays what the last 60 s or 256 messages hold, per instance. Past
561
+ that, or on a new server, `collect` empties, `chat.resets` ticks and `chat.onReset(fn)` runs. So what must survive goes
562
+ in the database: read history with a query, `chat.collect` the new messages with `key`, and invalidate the query on a
563
+ reset.
564
+
565
+ <!-- example: skip continues the chat example above -->
566
+ ```tsx
567
+ import { derived } from '@kerf-js/core'
568
+ import { invalidate } from '@kerf-js/start'
569
+ const history = listMessages({ roomId })
570
+ const said = chat.collect('said', { key: m => m.id })
571
+ chat.onReset(() => invalidate('messages'))
572
+ const all = derived(() =>
573
+ dedupe([...(history.value ?? []), ...said.value]),
574
+ )
575
+ ```
576
+
577
+ A refused join is only known once the socket is up, and `status` is `'connecting'` on the server. To render "not
578
+ allowed" on the server, share one function between `authorize` and the route's `load` (`allowed: mayEnter(ctx.user, id)`).
579
+ `authorize` doesn't narrow types: `ctx.user` in `on` is still nullable. Ephemeral messages such as `typing` go with
580
+ `{ exceptSelf: true }`, sent at most once a second.
581
+
582
+ In JSX leave a handler's `e` unannotated. A separate handler takes `Event & { currentTarget: HTMLInputElement }`: `input`
583
+ is a plain `Event` in TypeScript's DOM types, not `InputEvent`.
584
+
585
+ `send` has no offline queue. While the socket reconnects it waits up to 10 s, then rejects. A `send` in flight when the
586
+ socket dies rejects too, because it may or may not have arrived: put an id in the message if a retry must not double.
587
+
588
+ **Origin:** the socket takes the app's own origin and `realtime({ origins })`, exactly (R010, R004). There's nothing
589
+ else to configure, and no handler of your own (R004, R007). `invalidate('session:' + userId)` after a sign-out or a
590
+ kick re-checks that user's sockets at once. A user whose session ended is closed with 4401, and `status` is
591
+ `unauthorized`.
592
+
593
+ **Shared state** is one value per key, last writer wins, as a box. A write is optimistic. A refused one goes back and
594
+ sets `.error`.
595
+
596
+ <!-- example: skip needs the app's isParticipant and isPresenter rules -->
597
+ ```ts
598
+ import { sharedState, skip } from '@kerf-js/start'
599
+ import { z } from 'zod'
600
+
601
+ export const deckSlide = sharedState('deck-slide', {
602
+ key: z.string().max(64),
603
+ value: z.number().int().max(999),
604
+ initial: 0,
605
+ // Both ({ ctx, key }) => boolean functions are required.
606
+ authorize: { read: isParticipant, write: isPresenter },
607
+ })
608
+ await deckSlide.in(id).set(3) // on the server
609
+ // In defineState: State<number> & { status, error }
610
+ const slide = deckSlide.connect(() => (id.value ? id.value : skip))
611
+ ```
612
+
613
+ Its value lives in server memory: it survives a restart only while another instance runs. What must last is a mutation.
614
+
615
+ **Tabs** need no server: `tabs.channel` is in `kerf docs browser`, and a box kept the same in every tab
616
+ (`sync: 'tabs'`) is in `kerf docs state`.
617
+
618
+ **Testing:** `room.connect` runs the real server code over the fake socket: `await net.settle()`, then
619
+ `await net.publish(room, { roomId }, 'said', row)`, `net.sent(room)`, `await net.drop()`, `await net.offline()`,
620
+ `await net.session({ user })`. From `@kerf-js/core/test`, `tabs.post(name, msg)` and `tabs.posted(name)` play another tab, and two
621
+ `render()`s sharing one `storage` are two tabs.
622
+
623
+ ## CSS on a page
624
+
625
+ A built page carries the CSS its first paint needs in a `<style>`, and links the rest at the end of its shell, where it blocks nothing above it. The links are at most two hashed files: one with what every route shares, one with the rest of that route. Client navigation loads each chunk's own CSS and waits for it.
626
+
627
+ The server finds the first-paint CSS by reading the page's HTML against a table from the build, with lookups and no CSS parsing. So the same HTML always gets the same CSS. Nothing depends on what rendered it: a prerendered page, a `@kerf static` level, a page from a cache and a live render take one path, and there is no `Vary`. A streamed chunk carries only the styles that response hasn't sent.
628
+
629
+ Rules for hover, focus and other states aren't in the first paint, so they work once the late sheet lands. A class a head script sets isn't in the HTML: name it in `site.criticalKeep`. A dial value a head script sets with `dataset.x = 'y'` is found by itself. A stored dial choice the head doesn't name shows the default until the sheet lands.
630
+
631
+ If part of a page must not show before the late sheet, mark it:
632
+
633
+ ```tsx
634
+ <section data-kerf="styled">…</section>
635
+ ```
636
+
637
+ It keeps its room, stays hidden until the sheet lands, and shows anyway after 3 s with no JavaScript, so a missing file can't hide it for good. Assistive tech doesn't see it while hidden. `kerf check` warns on this mark on main content or an `h1` (D040). Nothing adds the mark for you: the first paint already holds every rule that matches the HTML.
638
+
639
+ `site.criticalCss: false` goes back to one sheet per chunk, inlined up to 48 KB and linked past that. `site.inlineCss: false` keeps plain links.
640
+
641
+ **Deploying.** A page cached before a deploy links the sheets it was built with, so `kerf build` keeps old combined sheets for 30 days in `.kerf/sheets`. Keep that folder between builds, or the old files go: a cached page then paints from its own `<style>`, without hover and focus styles until it is cached again. The folder is copied into the build's assets, so a preset that serves those assets needs nothing else.
642
+