@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,328 @@
1
+ import type { MediaAsset } from '@kerf-js/core/media'
2
+ import type { ServerExtension } from '../extension'
3
+ import { StartError, type Context } from '../data'
4
+ import { dbError } from './errors'
5
+
6
+ export interface ScopeEntry {
7
+ id: string
8
+ input: unknown
9
+ p: Promise<ScopeEntry>
10
+ /** A render's read of it (`landed`). */
11
+ read?: Promise<unknown>
12
+ done?: boolean
13
+ v?: unknown
14
+ e?: unknown
15
+ tags: string[]
16
+ }
17
+
18
+ export interface Scope {
19
+ request: Request
20
+ /** This request's id: the `x-request-id` response header, and on every diagnostic it raises. */
21
+ requestId?: string
22
+ entries: Map<string, ScopeEntry>
23
+ /** Tags a mutation or `invalidate()` dropped during this request. */
24
+ invalidated: Set<string>
25
+ /** Response headers the functions set (cookies), merged into the response. */
26
+ headers: Headers
27
+ /** The page's first byte went out: a redirect can't change the status any more (Q007). */
28
+ started?: boolean
29
+ /** The tags of the queries a route level's `load` read (a frame per loader; research 27 §4). */
30
+ tags?: Set<string>
31
+ /** Dev: the tables this function's statements read and wrote (a frame per `run`; research 28 §2). */
32
+ touched?: Touched
33
+ /** A no-JS form POST that failed: `<Form>` renders it into the page (research 29 §5). */
34
+ form?: FormFailure
35
+ /** Failure messages meant for the visitor, the only ones a production page may carry (`shown`). */
36
+ said: Set<string>
37
+ /** The render read a live query or a stream: the page carries the realtime cursor (research 30 §1). */
38
+ live?: boolean
39
+ /** A preview (the `kerf-preview` cookie, `preview.start`): its queries never read or write the shared cache, so what
40
+ * it sees (a draft, applied in a transaction the app rolls back) can't reach anyone else. */
41
+ preview: boolean
42
+ /** Work for when the response is finished (`after`): a rollback, a snapshot, a push. */
43
+ after: (() => unknown)[]
44
+ /** The response is finished and `after` has run: a later `after` runs at once. */
45
+ finished?: boolean
46
+ ctx(): Promise<Context>
47
+ options: ScopeOptions
48
+ }
49
+
50
+ export interface Touched {
51
+ read: Set<string>
52
+ write: Set<string>
53
+ }
54
+
55
+ export interface FormFailure {
56
+ id: string
57
+ key?: string
58
+ values: Record<string, unknown>
59
+ errors: Record<string, string>
60
+ message?: string | undefined
61
+ status: number
62
+ }
63
+
64
+ /** The `media.server@1` provider (`@kerf-js/media/server`, research 29 §6). */
65
+ export interface MediaServer {
66
+ ingest(bytes: Uint8Array, options: { name?: string }): Promise<MediaAsset>
67
+ serve(want: { hash: string; width: number; format: string; accept: string }): Promise<{
68
+ bytes: Uint8Array
69
+ type: string
70
+ width: number
71
+ format: string
72
+ negotiated: boolean
73
+ temporary?: boolean
74
+ } | null>
75
+ }
76
+
77
+ export interface ScopeOptions {
78
+ /** The app's context (`src/context.server.ts`). */
79
+ context?: ((args: { request: Request }) => object | Promise<object>) | undefined
80
+ store?: Store | undefined
81
+ /** Tests (@kerf-js/core/test `net.handle`): a replacement `run` by function id. */
82
+ handlers?: Map<string, (input: unknown, ctx: Context) => unknown>
83
+ onDiagnostic?: ((d: { code: string; severity: string; message: string }) => void) | undefined
84
+ dev?: boolean | undefined
85
+ media?: (() => Promise<MediaServer> | undefined) | undefined
86
+ /** What plugins add through `server.extension` (extension.ts). */
87
+ extensions?: ServerExtension[] | undefined
88
+ }
89
+
90
+ /** The cookie `preview.start` sets. Its value is the app's (a draft's id); kerf only reads that it's there. */
91
+ export const PREVIEW_COOKIE = 'kerf-preview'
92
+ const PREVIEW = /(?:^|;\s*)kerf-preview=[^;]/
93
+
94
+ export function createScope(request: Request, options: ScopeOptions = {}): Scope {
95
+ const headers = new Headers()
96
+ let ctx: Promise<Context> | undefined
97
+ return {
98
+ request,
99
+ entries: new Map(),
100
+ invalidated: new Set(),
101
+ headers,
102
+ options,
103
+ said: new Set(),
104
+ preview: PREVIEW.test(request.headers.get('cookie') ?? ''),
105
+ after: [],
106
+ // oxlint-disable typescript/no-unnecessary-type-assertion -- needed where a plugin such as pay adds required fields to Context
107
+ ctx: () =>
108
+ (ctx ??= Promise.resolve()
109
+ .then(() => options.context?.({ request }) ?? {})
110
+ .then(
111
+ async (app) =>
112
+ await extended(
113
+ {
114
+ ...app,
115
+ request,
116
+ response: { headers },
117
+ media: mediaApi(options),
118
+ } /* oxlint-enable typescript/no-unnecessary-type-assertion */ as Context,
119
+ options,
120
+ ),
121
+ (e) => {
122
+ throw dbError(e)
123
+ },
124
+ )),
125
+ }
126
+ }
127
+
128
+ /**
129
+ * Each extension's part of `ctx`, once the app's is there: an extension reads `ctx.user` to say what it adds. One may
130
+ * look something up first (an agent's token), so each is awaited, in order.
131
+ */
132
+ async function extended(ctx: Context, options: ScopeOptions): Promise<Context> {
133
+ for (const e of options.extensions ?? []) Object.assign(ctx, await e.context?.(ctx))
134
+ return ctx
135
+ }
136
+
137
+ /** `ctx.media`. A refusal is the user's answer, with its own status; `<Form>` shows it. */
138
+ const mediaApi = (options: ScopeOptions): Context['media'] => ({
139
+ async ingest(file, { name } = {}) {
140
+ const server = await options.media?.()
141
+ if (!server)
142
+ throw new StartError(
143
+ 'M017',
144
+ '`ctx.media` needs a `media.server` provider',
145
+ 'add `media()` from `@kerf-js/media` to `plugins` in kerf.config.ts',
146
+ { status: 500 },
147
+ )
148
+ const bytes = file instanceof Uint8Array ? file : new Uint8Array(await file.arrayBuffer())
149
+ try {
150
+ return await server.ingest(bytes, { name: name ?? (file as File).name })
151
+ } catch (e) {
152
+ const { code, message } = e as Error & { code?: string }
153
+ throw code ? new StartError(code, message, undefined, { status: 422 }) : e
154
+ }
155
+ },
156
+ })
157
+
158
+ /** A child scope for one loader: the same entries, its own `tags` collector. */
159
+ export const frame = (scope: Scope): Scope =>
160
+ Object.create(scope, { tags: { value: new Set<string>() } })
161
+
162
+ // ---- the shared tagged cache --------------------------------------------------------------------------------------
163
+
164
+ /**
165
+ * Where `cache: { life }` values live: memory by default, or what `src/cache.server.ts` exports (`redisStore()` from
166
+ * `@kerf-js/realtime-redis`, so every server reads the same values and an invalidation reaches all of them).
167
+ */
168
+ export interface Store {
169
+ get(key: string): Stored | undefined | Promise<Stored | undefined>
170
+ set(key: string, value: Stored): void | Promise<void>
171
+ /** The current version of each tag (0 for one never bumped). */
172
+ versions(tags: string[]): number[] | Promise<number[]>
173
+ bump(tags: string[]): void | Promise<void>
174
+ /**
175
+ * Count one call against `key` in a fixed window of `window` seconds: allowed while the count is at most `max`,
176
+ * else how many seconds until the window ends. Server functions' `limit` uses it; a store without it limits nothing.
177
+ */
178
+ consume?(
179
+ key: string,
180
+ rule: { window: number; max: number },
181
+ ):
182
+ | { allowed: boolean; retryAfter: number | null }
183
+ | Promise<{ allowed: boolean; retryAfter: number | null }>
184
+ }
185
+ /** One value in the shared cache: the result, its tags and their versions when it ran, and when it expires. */
186
+ export interface Stored {
187
+ v: unknown
188
+ tags: string[]
189
+ versions: number[]
190
+ expires: number
191
+ }
192
+
193
+ /** How much `memoryStore` keeps: values (least recently used go first) and tag versions. */
194
+ export interface MemoryLimits {
195
+ values?: number
196
+ tags?: number
197
+ }
198
+
199
+ /**
200
+ * One process's store, bounded: past `values` entries the least recently used goes, an expired value goes when it's
201
+ * read, and past `tags` versions they all start over. Versions come from one counter that never repeats, and a tag
202
+ * nobody has bumped since the restart reads as the counter's value then, so a value stored before can never match.
203
+ */
204
+ export function memoryStore({
205
+ values: most = 10_000,
206
+ tags: mostTags = 100_000,
207
+ }: MemoryLimits = {}): Store {
208
+ const values = new Map<string, Stored>()
209
+ const tags = new Map<string, number>()
210
+ let counter = 0
211
+ let floor = 0
212
+ const counts = new Map<string, { n: number; until: number }>()
213
+ return {
214
+ consume(key, { window, max }) {
215
+ const now = Date.now()
216
+ let c = counts.get(key)
217
+ if (!c || c.until <= now) {
218
+ counts.delete(key)
219
+ // Full: expired windows go first, then the oldest, so a flood of new keys can't grow it without end.
220
+ if (counts.size >= most)
221
+ for (const [k, old] of counts)
222
+ if (old.until <= now || counts.size >= most) counts.delete(k)
223
+ c = { n: 0, until: now + window * 1000 }
224
+ counts.set(key, c)
225
+ }
226
+ c.n++
227
+ return c.n <= max
228
+ ? { allowed: true, retryAfter: null }
229
+ : { allowed: false, retryAfter: Math.max(1, Math.ceil((c.until - now) / 1000)) }
230
+ },
231
+ get(k) {
232
+ const hit = values.get(k)
233
+ if (!hit) return undefined
234
+ values.delete(k)
235
+ if (hit.expires <= Date.now()) return undefined
236
+ values.set(k, hit)
237
+ return hit
238
+ },
239
+ set(k, v) {
240
+ values.delete(k)
241
+ values.set(k, v)
242
+ for (const old of values.keys()) {
243
+ if (values.size <= most) break
244
+ values.delete(old)
245
+ }
246
+ },
247
+ versions: (t) => t.map((x) => tags.get(x) ?? floor),
248
+ bump(t) {
249
+ if (tags.size + t.length > mostTags) {
250
+ tags.clear()
251
+ floor = ++counter
252
+ }
253
+ for (const x of t) tags.set(x, ++counter)
254
+ },
255
+ }
256
+ }
257
+
258
+ export const defaultStore = memoryStore()
259
+
260
+ /**
261
+ * The GET a mutation's refreshes read as, when a preview is involved: the browser's next request, with the preview
262
+ * cookie this response sets or clears, so what comes back is what the next page shows. Undefined when no preview is.
263
+ */
264
+ export function rereads(scope: Scope): Request | undefined {
265
+ const set = scope.headers.getSetCookie().findLast((c) => c.startsWith(`${PREVIEW_COOKIE}=`))
266
+ if (!set && !scope.preview) return undefined
267
+ const cookies = (scope.request.headers.get('cookie') ?? '')
268
+ .split(/;\s*/)
269
+ .filter((c) => c && !c.startsWith(`${PREVIEW_COOKIE}=`))
270
+ const pair = set ? set.split(';')[0]! : `${PREVIEW_COOKIE}=${previewValue(scope)}`
271
+ if (!set || !/max-age=0/i.test(set)) cookies.push(pair)
272
+ const headers = new Headers(scope.request.headers)
273
+ for (const h of ['content-type', 'content-length']) headers.delete(h)
274
+ headers.set('cookie', cookies.join('; '))
275
+ return new Request(scope.request.url, { method: 'GET', headers })
276
+ }
277
+
278
+ const previewValue = (scope: Scope) =>
279
+ /(?:^|;\s*)kerf-preview=([^;]+)/.exec(scope.request.headers.get('cookie') ?? '')?.[1] ?? ''
280
+
281
+ /** The response is done: run what `after` queued, each once, a failure a diagnostic that stops none of the rest. */
282
+ export async function finishScope(scope: Scope) {
283
+ if (scope.finished) return
284
+ scope.finished = true
285
+ for (const fn of scope.after.splice(0))
286
+ try {
287
+ await fn()
288
+ } catch (e) {
289
+ scope.options.onDiagnostic?.({
290
+ code: 'E_AFTER',
291
+ severity: 'error',
292
+ message: `an \`after()\` task failed: ${e instanceof Error ? e.message : String(e)}`,
293
+ })
294
+ }
295
+ }
296
+
297
+ /**
298
+ * `response` with `finishScope` run when its body has been read to the end, failed, or been abandoned by the client.
299
+ * A response whose request queued nothing, and isn't a preview, goes out untouched (a preview's context may queue its
300
+ * rollback while the page is still streaming).
301
+ */
302
+ export function finishing(response: Response, scope: Scope): Response {
303
+ if (!response.body || (!scope.after.length && !scope.preview)) {
304
+ void finishScope(scope)
305
+ return response
306
+ }
307
+ const reader = response.body.getReader()
308
+ const end = () => void finishScope(scope)
309
+ const body = new ReadableStream<Uint8Array>({
310
+ async pull(c) {
311
+ try {
312
+ const { value, done } = await reader.read()
313
+ if (done) {
314
+ c.close()
315
+ end()
316
+ } else c.enqueue(value)
317
+ } catch (e) {
318
+ c.error(e)
319
+ end()
320
+ }
321
+ },
322
+ cancel(reason) {
323
+ end()
324
+ return reader.cancel(reason)
325
+ },
326
+ })
327
+ return new Response(body, response)
328
+ }
@@ -0,0 +1,80 @@
1
+ import type { Fn } from '../data'
2
+ import type { Scope, ScopeOptions, Touched } from './scope'
3
+
4
+ export const tracker = (scope: Scope): Touched | undefined =>
5
+ scope.options.dev ? { read: new Set(), write: new Set() } : undefined
6
+
7
+ /** R105 (dev, once per function): a cached Rust query with tags that named no table, so Q011 has nothing to check it by. */
8
+ export function untouched(fn: Fn, read: Set<string>, tags: readonly string[], scope: Scope) {
9
+ if (!fn.def.impl || !fn.def.cache || read.size || !tags.length || warned.has(`${fn.$id}:R105`))
10
+ return
11
+ warned.add(`${fn.$id}:R105`)
12
+ scope.options.onDiagnostic?.({
13
+ code: 'R105',
14
+ severity: 'warning',
15
+ message: `\`${fn.$id}\` is cached under ${tags.map((t) => `\`${t}\``).join(', ')} and reported no table: nothing can tell whether those tags cover what it reads. Call \`ctx.touch("table")\` in the Rust, or drop \`tags\` if it reads none`,
16
+ })
17
+ }
18
+
19
+ /** Q011 (dev, once per function and table): a table the function touched that no tag names (PLAN §4). */
20
+ export function missedTags(
21
+ fn: Fn,
22
+ verb: 'read' | 'write',
23
+ tables: Set<string>,
24
+ tags: readonly string[],
25
+ scope: Scope,
26
+ ) {
27
+ for (const t of tables) {
28
+ const key = `${fn.$id}:${t}`
29
+ if (warned.has(key) || tags.some((x) => x === t || x.startsWith(`${t}:`))) continue
30
+ warned.add(key)
31
+ const list = fn.kind === 'query' ? '`tags`' : '`invalidates`'
32
+ scope.options.onDiagnostic?.({
33
+ code: 'Q011',
34
+ severity: 'warning',
35
+ message: `\`${fn.$id}\` ${verb === 'read' ? 'reads' : 'writes'} table \`${t}\`, but its ${list} don't name it: ${fn.kind === 'query' ? "a mutation of that table won't refresh it" : 'queries of that table stay stale'}. Add \`'${t}'\` to ${list}`,
36
+ })
37
+ }
38
+ }
39
+ const warned = new Set<string>()
40
+
41
+ /** Dev: the tables each query last read, and the tags of the queries read with `.live()` (the hub fills it). */
42
+ export const reads = new Map<string, Set<string>>()
43
+ export const liveQueries = new Map<string, string[]>()
44
+
45
+ /** R003 (dev, once per pair): this mutation wrote what a live query reads, and pokes none of its tags. */
46
+ export function missedPokes(fn: Fn, write: Set<string>, tags: string[], scope: Scope) {
47
+ for (const [id, own] of liveQueries) {
48
+ const table = [...(reads.get(id) ?? [])].find((t) => write.has(t))
49
+ const key = `${fn.$id}>${id}`
50
+ if (!table || warned.has(key) || own.some((t) => tags.includes(t))) continue
51
+ warned.add(key)
52
+ scope.options.onDiagnostic?.({
53
+ code: 'R003',
54
+ severity: 'warning',
55
+ message: `\`${fn.$id}\` writes table \`${table}\`, which live query \`${id}\` reads, but their tags don't intersect (${JSON.stringify(tags)} and ${JSON.stringify(own)}): open pages won't update. Add one of the query's tags to \`invalidates\``,
56
+ })
57
+ }
58
+ }
59
+
60
+ /** R012 (dev, once per query and table): a live query whose tags won't hear what `changes` reports, or a table it doesn't report. */
61
+ export function missedFeed(
62
+ fn: Fn,
63
+ tags: string[],
64
+ tables: string[],
65
+ report: ScopeOptions['onDiagnostic'],
66
+ ) {
67
+ for (const t of reads.get(fn.$id) ?? []) {
68
+ const key = `${fn.$id}~${t}`
69
+ const named = tags.some((x) => x === t || x.startsWith(`${t}:`))
70
+ if (warned.has(key) || (named && tables.includes(t))) continue
71
+ warned.add(key)
72
+ report?.({
73
+ code: 'R012',
74
+ severity: 'warning',
75
+ message: tables.includes(t)
76
+ ? `live query \`${fn.$id}\` reads table \`${t}\`, but no tag names it: writes from outside the app won't refresh it. Add \`'${t}'\` to its \`tags\``
77
+ : `live query \`${fn.$id}\` reads table \`${t}\`, which \`changes\` doesn't list: only mutations refresh it, not writes from outside the app. Add the table to \`dbChanges\``,
78
+ })
79
+ }
80
+ }
@@ -0,0 +1,176 @@
1
+ import { fns, StartError, type Fn, type SchemaIssue } from '../data'
2
+ import type { Scope } from './scope'
3
+
4
+ type Obj = Record<PropertyKey, unknown>
5
+
6
+ // ---- validation and checks ------------------------------------------------------------------------------------
7
+
8
+ export async function validate(fn: Fn, input: unknown): Promise<unknown> {
9
+ const schema = fn.def.input
10
+ if (!schema) return input
11
+ const r = await schema['~standard'].validate(input)
12
+ if (!r.issues) return r.value
13
+ throw rejected(fn, r.issues)
14
+ }
15
+
16
+ const plainPath = (i: SchemaIssue) => (i.path ?? []).map((p) => (typeof p === 'object' ? p.key : p))
17
+
18
+ function rejected(fn: Fn, list: readonly SchemaIssue[]) {
19
+ const issues = list.map((i) => ({
20
+ message: i.message,
21
+ path: i.path && plainPath(i),
22
+ })) as (SchemaIssue & { path?: PropertyKey[] })[]
23
+ const where = issues
24
+ .map((i) => `${i.path?.length ? i.path.map(String).join('.') + ': ' : ''}${i.message}`)
25
+ .join('; ')
26
+ return new StartError(
27
+ 'Q002',
28
+ `\`${fn.$id}\` rejected its input: ${where}`,
29
+ 'pass what the schema accepts',
30
+ { status: 400, issues },
31
+ )
32
+ }
33
+ /** A form's string as the type it may stand for (research 29 §5): the schema says whether it was wrong. */
34
+ function reading(s: string): unknown {
35
+ if (s === '') return undefined
36
+ if (s === 'on' || s === 'true') return true
37
+ if (s === 'false') return false
38
+ return /^-?\d+(\.\d+)?$/.test(s) ? Number(s) : s
39
+ }
40
+ /**
41
+ * A form sends strings and a schema may want numbers or booleans, and Standard Schema can't say which: each issue
42
+ * on a string tries its obvious reading, then the input is validated again. Fields a reading fixed report nothing; the
43
+ * rest report what the schema says of what was typed (an empty field: its "required", not "expected a string").
44
+ */
45
+ export async function formInput(fn: Fn, input: unknown): Promise<unknown> {
46
+ const schema = fn.def.input
47
+ if (!schema || !input || typeof input !== 'object') return validate(fn, input)
48
+ const value: Obj = { ...input }
49
+ let left: readonly SchemaIssue[] = []
50
+ for (let i = 0; i < 3; i++) {
51
+ const r = await schema['~standard'].validate(value)
52
+ if (!r.issues) return r.value
53
+ left = r.issues
54
+ let changed = false
55
+ for (const issue of r.issues) {
56
+ const path = plainPath(issue)
57
+ if (!path.length) continue
58
+ let at: Obj | undefined = value
59
+ for (const p of path.slice(0, -1)) {
60
+ const inner: unknown = at?.[p]
61
+ if (!inner || typeof inner !== 'object') {
62
+ at = undefined
63
+ break
64
+ }
65
+ at = at[p] = (Array.isArray(inner) ? [...inner] : { ...inner }) as Obj
66
+ }
67
+ const k = path.at(-1)!
68
+ const typed = at?.[k]
69
+ if (typeof typed !== 'string') continue
70
+ const next = reading(typed)
71
+ if (next === typed) continue
72
+ if (next === undefined) delete at![k]
73
+ else at![k] = next
74
+ changed = true
75
+ }
76
+ if (!changed) break
77
+ }
78
+ const first = await schema['~standard'].validate(input)
79
+ const where = (i: SchemaIssue) => JSON.stringify(plainPath(i))
80
+ throw rejected(
81
+ fn,
82
+ left.map((i) => first.issues?.find((o) => where(o) === where(i)) ?? i),
83
+ )
84
+ }
85
+ /** Dev and tests: the value against `output` (C002), and what JSON would change (Q005). */
86
+ export async function checked(v: unknown, fn: Fn, scope: Scope) {
87
+ serializable(v, fn, scope)
88
+ const schema = fn.def.output
89
+ if (!schema || fn.def.impl) return // `impl`: rust.ts checked what came back, on every call
90
+ const r = await schema['~standard'].validate(v)
91
+ if (r.issues)
92
+ throw new StartError(
93
+ 'C002',
94
+ `\`${fn.$id}\` returned a value its \`output\` schema rejects: ${r.issues.map((i) => `${i.path?.map((p) => (typeof p === 'object' ? p.key : p)).join('.') ?? ''}: ${i.message}`).join('; ')}`,
95
+ 'fix `run`, or the schema',
96
+ { status: 500 },
97
+ )
98
+ }
99
+ /** Q005 (dev): what JSON would change on the way to the client. */
100
+ function serializable(v: unknown, fn: Fn, scope: Scope) {
101
+ const bad = (x: unknown, path: string): string | undefined => {
102
+ if (x === null || typeof x === 'string' || typeof x === 'boolean') return undefined
103
+ if (typeof x === 'number') return Number.isFinite(x) ? undefined : `${path} is ${x}`
104
+ if (x === undefined) return undefined
105
+ if (typeof x !== 'object') return `${path} is a ${typeof x}`
106
+ if (Array.isArray(x)) {
107
+ for (let i = 0; i < x.length; i++) {
108
+ if (x[i] === undefined) return `${path}[${i}] is undefined (JSON sends null)`
109
+ const b = bad(x[i], `${path}[${i}]`)
110
+ if (b) return b
111
+ }
112
+ return undefined
113
+ }
114
+ const proto: unknown = Object.getPrototypeOf(x)
115
+ if (proto !== Object.prototype && proto !== null)
116
+ return `${path} is a ${(x as { constructor?: { name?: string } }).constructor?.name ?? 'class instance'}`
117
+ for (const k of Object.keys(x)) {
118
+ const b = bad((x as Obj)[k], `${path}.${k}`)
119
+ if (b) return b
120
+ }
121
+ return undefined
122
+ }
123
+ const b = bad(v, 'result')
124
+ if (b)
125
+ scope.options.onDiagnostic?.({
126
+ code: 'Q005',
127
+ severity: 'warning',
128
+ message: `\`${fn.$id}\`'s ${b}: the client gets a different value than the server rendered with. Send plain data (ISO strings, arrays, objects)`,
129
+ })
130
+ }
131
+ /**
132
+ * Q008 (dev, once): each mutation's static `invalidates` against the tags queries declare. A tags function is called
133
+ * with an input whose every field reads `*`, so `todo:${id}` declares `todo:*`.
134
+ */
135
+ export function checkTags(
136
+ report: (d: { code: string; severity: string; message: string }) => void,
137
+ ) {
138
+ const star: unknown = new Proxy(
139
+ {},
140
+ { get: (_, k) => (k === Symbol.toPrimitive ? () => '*' : '*') },
141
+ )
142
+ const declared: string[] = []
143
+ for (const f of fns.values()) {
144
+ if (f.kind !== 'query') continue
145
+ try {
146
+ declared.push(...(typeof f.def.tags === 'function' ? f.def.tags(star) : (f.def.tags ?? [])))
147
+ } catch {}
148
+ }
149
+ const matches = (tag: string) =>
150
+ declared.some(
151
+ (d) =>
152
+ d === tag ||
153
+ (d.includes('*') &&
154
+ new RegExp(`^${d.replace(/[.+?^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '[^]*')}$`).test(
155
+ tag,
156
+ )) ||
157
+ (tag.includes('*') && d.startsWith(tag.slice(0, tag.indexOf('*')))),
158
+ )
159
+ for (const f of fns.values()) {
160
+ if (f.kind !== 'mutation' || !f.def.invalidates) continue
161
+ let tags: readonly string[]
162
+ try {
163
+ tags =
164
+ typeof f.def.invalidates === 'function' ? f.def.invalidates(star, star) : f.def.invalidates
165
+ } catch {
166
+ continue
167
+ }
168
+ for (const t of tags)
169
+ if (!matches(t))
170
+ report({
171
+ code: 'Q008',
172
+ severity: 'warning',
173
+ message: `\`${f.$id}\` invalidates \`${t}\`, a tag no query declares: nothing refreshes. Fix the tag, or add it to the query's \`tags\``,
174
+ })
175
+ }
176
+ }
@@ -0,0 +1,50 @@
1
+ // Warm on invalidate: a `cache: { warm: true }` query runs again in the background the moment a change invalidates it,
2
+ // so the shared store holds the new value before the next visitor asks. The visitor after an edit gets a hit, not the
3
+ // edit's cost. Only queries every visitor shares (no `auth`, no `scope: 'user'`) qualify: a warm run has no user.
4
+ import type { Fn } from '../data'
5
+ import type { Scope } from './scope'
6
+ import { signedIn } from './errors'
7
+
8
+ type Warm = { fn: Fn; input: unknown; tags: string[] }
9
+
10
+ /** What was stored warm, by its store key. Bounded: a query keyed by free input can't grow it without end. */
11
+ const known = new Map<string, Warm>()
12
+ const MOST = 500
13
+
14
+ /** Whether `fn`'s stored value should come back warm after an invalidation. */
15
+ export const warms = (fn: Fn) => !!fn.def.cache?.warm && !fn.def.cache.scope && !signedIn(fn)
16
+
17
+ export function remember(key: string, fn: Fn, input: unknown, tags: string[]) {
18
+ known.delete(key)
19
+ known.set(key, { fn, input, tags })
20
+ if (known.size > MOST) known.delete(known.keys().next().value!)
21
+ }
22
+
23
+ /**
24
+ * After `tags` were bumped: run each remembered query that reads one of them again, in a scope of its own (no cookies,
25
+ * so no user and no preview), once the current task is done. A failure is a diagnostic; the next visitor runs it then.
26
+ */
27
+ export function rewarm(
28
+ scope: Scope,
29
+ tags: string[],
30
+ run: (scope: Scope, fn: Fn, input: unknown) => Promise<unknown>,
31
+ make: (request: Request) => Scope,
32
+ ) {
33
+ const due = [...known].filter(([, w]) => w.tags.some((t) => tags.includes(t)))
34
+ if (!due.length) return
35
+ for (const [k] of due) known.delete(k) // the run stores, and remembers, it again
36
+ const request = new Request(new URL('/', scope.request.url))
37
+ setTimeout(() => {
38
+ for (const [, w] of due)
39
+ run(make(request), w.fn, w.input).catch((e: unknown) =>
40
+ scope.options.onDiagnostic?.({
41
+ code: 'E_WARM',
42
+ severity: 'warning',
43
+ message: `warming \`${w.fn.$id}\` after ${tags.join(', ')} failed: ${e instanceof Error ? e.message : String(e)}`,
44
+ }),
45
+ )
46
+ })
47
+ }
48
+
49
+ /** Tests: forget what was remembered. */
50
+ export const forgetWarm = () => known.clear()