@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,39 @@
1
+ import { Broke, subscribe, type Hello } from './support'
2
+
3
+ export async function openApp(o: {
4
+ url: string
5
+ id: string
6
+ input: unknown
7
+ cookie: string | undefined
8
+ signal: AbortSignal
9
+ timeout: number
10
+ }) {
11
+ const { url, id, input, cookie, signal, timeout } = o
12
+ const a = await subscribe(url, id, input, cookie, signal)
13
+ const hi = await a.until((f) => f[0] === 'h', timeout)
14
+ if (!hi) throw new Broke('app', 'the app accepted the connection and said nothing')
15
+ const said = (hi[1] as Hello).l
16
+ if (said?.m !== 'feed' && said?.m !== 'external')
17
+ throw new Broke(
18
+ 'app',
19
+ `the app's live mode is \`${said?.m ?? 'app'}\`, not a feed: its log says why`,
20
+ )
21
+ if (said?.d) throw new Broke('app', "the app's change feed is down")
22
+ const ack = await a.until(
23
+ (f) => (f[0] === 'a' || f[0] === 'e') && (f[1] as unknown[])[0] === 1,
24
+ timeout,
25
+ )
26
+ if (!ack) throw new Broke('app', 'no answer to the subscription')
27
+ const answer = (ack[1] as [number, unknown])[1]
28
+ const failed = answer as { code?: string; message?: string }
29
+ if (ack[0] === 'e')
30
+ throw new Broke(
31
+ 'app',
32
+ failed.code === 'Q009'
33
+ ? `the app doesn't know \`${id}\`: it runs another build`
34
+ : failed.code === 'A002'
35
+ ? `\`${id}\` needs a signed-in user: set \`KERF_STAGING_COOKIE\``
36
+ : `the subscription failed: ${failed.message}`,
37
+ )
38
+ return { ...a, tags: answer as string[] }
39
+ }
@@ -0,0 +1,27 @@
1
+ import type postgres from 'postgres'
2
+ import type { VerifyResult } from '../verify'
3
+ import { Broke, clean, type insert } from './support'
4
+
5
+ export async function cleanup(o: {
6
+ ac: AbortController
7
+ row: Awaited<ReturnType<typeof insert>> | undefined
8
+ ms: VerifyResult['ms']
9
+ sql: postgres.Sql | undefined
10
+ listener: postgres.Sql | undefined
11
+ marker: string
12
+ }) {
13
+ const { ac, row, ms, sql, listener, marker } = o
14
+ let cleaning: unknown
15
+ ac.abort()
16
+ if (row) {
17
+ const t = performance.now()
18
+ try {
19
+ await row.remove()
20
+ ms.cleanup = Math.round(performance.now() - t)
21
+ } catch (e) {
22
+ cleaning = e
23
+ }
24
+ }
25
+ await Promise.all([sql?.end({ timeout: 1 }), listener?.end({ timeout: 1 })]).catch(() => {})
26
+ if (cleaning) throw new Broke('cleanup', `row \`${marker}\` is still there: ${clean(cleaning)}`)
27
+ }
@@ -0,0 +1,11 @@
1
+ import postgres from 'postgres'
2
+
3
+ export function database(db: string | undefined) {
4
+ const sql = db
5
+ ? postgres(db, { max: 3, idle_timeout: 2, connect_timeout: 5, onnotice: () => {} })
6
+ : undefined
7
+ const listener = db
8
+ ? postgres(db, { max: 1, idle_timeout: 2, connect_timeout: 5, onnotice: () => {} })
9
+ : undefined
10
+ return { sql, listener }
11
+ }
@@ -0,0 +1,63 @@
1
+ import type { VerifyOptions } from '../data'
2
+ import type { Link } from '../verify'
3
+ import { Broke, read, type subscribe } from './support'
4
+ import type { openApp } from './app'
5
+
6
+ type Timed = <T>(link: Link, run: () => Promise<T>) => Promise<T>
7
+ type Live = Awaited<ReturnType<typeof openApp>>
8
+ type Denied = Awaited<ReturnType<typeof subscribe>> | undefined
9
+
10
+ export async function checkLive(o: {
11
+ live: Live
12
+ denied: Denied
13
+ timed: Timed
14
+ skip: (links: Link[], why: string) => void
15
+ url: string
16
+ id: string
17
+ input: unknown
18
+ cookie: string | undefined
19
+ other: string | undefined
20
+ marker: string
21
+ timeout: number
22
+ options: VerifyOptions
23
+ }) {
24
+ const { live, denied, timed, skip, url, id, input, cookie, other, marker, timeout, options } = o
25
+ await timed('poke', async () => {
26
+ const p = await live.until(
27
+ (f) => f[0] === 'p' && (f[1] as { t: string[] }).t.some((t) => live.tags.includes(t)),
28
+ timeout,
29
+ )
30
+ if (!p)
31
+ throw new Broke(
32
+ 'poke',
33
+ `the database notified, and the app never poked this subscription within ${timeout} ms: its listener, or a tag the query doesn't declare`,
34
+ )
35
+ })
36
+ await timed('refetch', async () => {
37
+ const end = Date.now() + timeout
38
+ for (;;) {
39
+ const res = await read(url, id, input, cookie)
40
+ if (res.ok && (await res.text()).includes(marker)) return
41
+ if (Date.now() > end)
42
+ throw new Broke(
43
+ 'refetch',
44
+ `poked, and the query didn't return the row within ${timeout} ms${options.row ? '' : ': if it filters by user, say whose it is in `verify.row`'}`,
45
+ )
46
+ await new Promise((ok) => {
47
+ setTimeout(ok, 50)
48
+ })
49
+ }
50
+ })
51
+ if (denied)
52
+ await timed('denied', async () => {
53
+ const res = await read(url, id, input, other)
54
+ const text = await res.text()
55
+ if (text.includes(marker) || denied.frames.some((f) => JSON.stringify(f[1]).includes(marker)))
56
+ throw new Broke('denied', `${other ? 'the other user' : 'a signed-out client'} got the row`)
57
+ })
58
+ else
59
+ skip(
60
+ ['denied'],
61
+ 'a query with no `auth` and no other user to compare: set `KERF_STAGING_OTHER_COOKIE`',
62
+ )
63
+ }
@@ -0,0 +1,35 @@
1
+ import { CHANNEL } from '../changes-sql.mjs'
2
+ import { Broke } from './support'
3
+
4
+ export async function waitNotice(
5
+ heard: string[],
6
+ table: string,
7
+ id: string,
8
+ timeout: number,
9
+ setHearing: (fn: () => void) => void,
10
+ ) {
11
+ const seen = () =>
12
+ heard.some((h) => {
13
+ try {
14
+ const m = JSON.parse(h)
15
+ return m.t === table && (!m.i || m.i.includes(id))
16
+ } catch {
17
+ return false
18
+ }
19
+ })
20
+ if (!seen())
21
+ await new Promise<void>((ok) => {
22
+ const t = setTimeout(ok, timeout)
23
+ setHearing(() => {
24
+ if (seen()) {
25
+ clearTimeout(t)
26
+ ok()
27
+ }
28
+ })
29
+ })
30
+ if (!seen())
31
+ throw new Broke(
32
+ 'notify',
33
+ `the trigger on \`${table}\` sent nothing on \`${CHANNEL}\` within ${timeout} ms`,
34
+ )
35
+ }
@@ -0,0 +1,19 @@
1
+ import type { Link, VerifyResult } from '../verify'
2
+
3
+ export function skipper(untested: VerifyResult['untested']) {
4
+ return (links: Link[], why: string) => {
5
+ for (const link of links) untested.push({ link, why })
6
+ }
7
+ }
8
+
9
+ export function skipWithoutUrl(
10
+ url: string | undefined,
11
+ sql: unknown,
12
+ skip: (links: Link[], why: string) => void,
13
+ ) {
14
+ if (!url)
15
+ skip(
16
+ sql ? ['app', 'poke', 'refetch', 'denied'] : ['app'],
17
+ 'no URL target: the database half was tested, not the running app. Set `KERF_STAGING_URL` or `verify.url`',
18
+ )
19
+ }
@@ -0,0 +1,149 @@
1
+ import type postgres from 'postgres'
2
+ import type { Link } from '../verify'
3
+
4
+ export class Broke extends Error {
5
+ constructor(
6
+ public link: Link,
7
+ why: string,
8
+ ) {
9
+ super(why)
10
+ }
11
+ }
12
+
13
+ export const clean = (s: unknown) =>
14
+ String((s as Error | null | undefined)?.message ?? s).replace(/\/\/[^@/\s]*@/g, '//…@')
15
+
16
+ /** A value for a required column nobody named. Foreign keys can't be guessed: `row` is for those. */
17
+ function made(type: string, marker: string): unknown {
18
+ if (/uuid/.test(type)) return crypto.randomUUID()
19
+ if (/int|serial/.test(type)) return Math.floor(Math.random() * 2_000_000_000)
20
+ if (/numeric|double|real|money/.test(type)) return 0
21
+ if (/bool/.test(type)) return false
22
+ if (/timestamp|date/.test(type)) return new Date().toISOString()
23
+ if (/time/.test(type)) return '00:00:00'
24
+ if (/json/.test(type)) return JSON.stringify({ marker })
25
+ return marker
26
+ }
27
+
28
+ export async function insert(
29
+ sql: postgres.Sql,
30
+ table: string,
31
+ marker: string,
32
+ row: Record<string, unknown>,
33
+ pk: string[],
34
+ ) {
35
+ const cols =
36
+ await sql`select column_name, data_type, is_nullable, column_default, is_identity, is_generated from information_schema.columns where table_schema = current_schema() and table_name = ${table} order by ordinal_position`
37
+ if (!cols.length) throw new Broke('write', `no table \`${table}\` in this database`)
38
+ const values: Record<string, unknown> = { ...row }
39
+ let marked = false
40
+ for (const c of cols) {
41
+ const name = c.column_name as string
42
+ if (name in values) continue
43
+ if (/char|text/.test(c.data_type) && !marked) {
44
+ values[name] = marker
45
+ marked = true
46
+ } else if (
47
+ c.is_nullable === 'NO' &&
48
+ c.column_default === null &&
49
+ c.is_identity === 'NO' &&
50
+ c.is_generated === 'NEVER'
51
+ )
52
+ values[name] = made(c.data_type, marker)
53
+ }
54
+ if (!marked)
55
+ throw new Broke(
56
+ 'write',
57
+ `\`${table}\` has no free text column to mark a row with: name one less in \`row\``,
58
+ )
59
+ const names = Object.keys(values)
60
+ const quoted = (n: string) => `"${n.replaceAll('"', '""')}"`
61
+ const key = pk.length ? pk : names.slice(0, 1)
62
+ const [got] = await sql.unsafe(
63
+ `insert into ${quoted(table)} (${names.map(quoted).join(', ')}) values (${names.map((_, i) => `$${i + 1}`).join(', ')}) returning ${key.map(quoted).join(', ')}`,
64
+ names.map((n) => values[n]) as never[],
65
+ )
66
+ if (!got) throw new Broke('write', `\`${table}\` took the row and returned nothing`)
67
+ const where = key.map((k, i) => `${quoted(k)} = $${i + 1}`).join(' and ')
68
+ return {
69
+ id: key.map((k) => String(got[k])).join(':'),
70
+ remove: () =>
71
+ sql.unsafe(
72
+ `delete from ${quoted(table)} where ${where}`,
73
+ key.map((k) => got[k]),
74
+ ),
75
+ }
76
+ }
77
+
78
+ export async function primaryKey(sql: postgres.Sql, table: string): Promise<string[]> {
79
+ const rows =
80
+ await sql`select a.attname from pg_index i join pg_class c on c.oid = i.indrelid join pg_attribute a on a.attrelid = c.oid and a.attnum = any(i.indkey) where c.relname = ${table} and i.indisprimary`
81
+ return rows.map((r) => r.attname as string)
82
+ }
83
+
84
+ /** One SSE connection to the app, by the protocol a browser's tab speaks. */
85
+ type Frame = [event: string, data: unknown]
86
+ export type Hello = { l?: { m?: string; d?: unknown } }
87
+
88
+ export async function subscribe(
89
+ url: string,
90
+ id: string,
91
+ input: unknown,
92
+ cookie: string | undefined,
93
+ signal: AbortSignal,
94
+ ) {
95
+ const res = await fetch(`${url}/_kerf/rt`, {
96
+ method: 'POST',
97
+ signal,
98
+ headers: {
99
+ 'content-type': 'application/json',
100
+ 'x-kerf': '1',
101
+ accept: 'text/event-stream',
102
+ origin: url,
103
+ ...(cookie && { cookie }),
104
+ },
105
+ body: JSON.stringify({ s: [[1, 'q', id, input]] }),
106
+ })
107
+ if (!res.ok) throw new Error(`\`/_kerf/rt\` answered ${res.status}`)
108
+ const frames: Frame[] = []
109
+ const waiting = new Set<() => void>()
110
+ void (async () => {
111
+ const dec = new TextDecoder()
112
+ let buf = ''
113
+ try {
114
+ for await (const chunk of res.body as unknown as AsyncIterable<Uint8Array>) {
115
+ buf += dec.decode(chunk, { stream: true })
116
+ for (let i; (i = buf.indexOf('\n\n')) >= 0; buf = buf.slice(i + 2)) {
117
+ if (buf[0] === ':') continue
118
+ const line = buf.indexOf('\n')
119
+ frames.push([buf.slice(7, line), JSON.parse(buf.slice(line + 7, i))])
120
+ for (const w of waiting) w()
121
+ }
122
+ }
123
+ } catch {}
124
+ })()
125
+ const until = async (test: (f: Frame) => boolean, ms: number) => {
126
+ const end = Date.now() + ms
127
+ for (;;) {
128
+ const hit = frames.find(test)
129
+ if (hit) return hit
130
+ const left = end - Date.now()
131
+ if (left <= 0) return undefined
132
+ await new Promise<void>((ok) => {
133
+ const t = setTimeout(ok, left)
134
+ waiting.add(() => {
135
+ clearTimeout(t)
136
+ ok()
137
+ })
138
+ })
139
+ waiting.clear()
140
+ }
141
+ }
142
+ return { frames, until }
143
+ }
144
+
145
+ export const read = (url: string, id: string, input: unknown, cookie?: string) =>
146
+ fetch(
147
+ `${url}/_kerf/fn/${id}${input == null ? '' : `?i=${encodeURIComponent(JSON.stringify(input))}`}`,
148
+ { headers: { accept: 'application/json', ...(cookie && { cookie }) } },
149
+ )
@@ -0,0 +1,15 @@
1
+ import type { Link, VerifyResult } from '../verify'
2
+ import { Broke, clean } from './support'
3
+
4
+ export function timer(ms: VerifyResult['ms']) {
5
+ return async <T>(link: Link, run: () => Promise<T>): Promise<T> => {
6
+ const t = performance.now()
7
+ try {
8
+ return await run()
9
+ } catch (e) {
10
+ throw e instanceof Broke ? e : new Broke(link, clean(e))
11
+ } finally {
12
+ ms[link] = Math.round(performance.now() - t)
13
+ }
14
+ }
15
+ }
@@ -0,0 +1,14 @@
1
+ import type postgres from 'postgres'
2
+ import { Broke } from './support'
3
+
4
+ export async function checkTrigger(sql: postgres.Sql, table: string) {
5
+ const [t] =
6
+ await sql`select t.tgenabled from pg_trigger t join pg_class c on c.oid = t.tgrelid where t.tgname = 'kerf_changes_ins' and c.relname = ${table}`
7
+ if (!t)
8
+ throw new Broke(
9
+ 'trigger',
10
+ `\`${table}\` has no change trigger: run \`kerf db live\`, and apply the migration there`,
11
+ )
12
+ if (t.tgenabled === 'D')
13
+ throw new Broke('trigger', `the change trigger on \`${table}\` is disabled`)
14
+ }
package/src/verify.ts ADDED
@@ -0,0 +1,152 @@
1
+ // `live: { required: true, verify: … }`: a real round trip against a target that isn't production, as part of `kerf
2
+ // check` and `kerf build`. A marked row goes in through a connection of its own, as any outside app's would; each link
3
+ // from there to a refetch is timed, and the row comes out again.
4
+ //
5
+ // trigger → write → notify → app → poke → refetch → denied → cleanup
6
+ //
7
+ // A database target tests the first half and a URL target the app's half; with both, the whole chain. Whatever wasn't
8
+ // tested is reported, by name. `live-target.mjs` decides whether a target may be touched at all.
9
+
10
+ import { CHANNEL } from './changes-sql.mjs'
11
+ import type { Context, Fn, VerifyOptions } from './data'
12
+ import type { Source } from './changes'
13
+ import { Broke, clean, insert, primaryKey, subscribe } from './verify/support'
14
+ import { waitNotice } from './verify/notify'
15
+ import { database } from './verify/database'
16
+ import { skipper, skipWithoutUrl } from './verify/skip'
17
+ import { cleanup } from './verify/cleanup'
18
+ import { timer } from './verify/timing'
19
+ import { checkTrigger } from './verify/trigger'
20
+ import { checkLive } from './verify/live'
21
+ import { openApp } from './verify/app'
22
+
23
+ export type { VerifyOptions }
24
+
25
+ /** Each step of the round trip, in order. */
26
+ export const LINKS = [
27
+ 'trigger',
28
+ 'write',
29
+ 'notify',
30
+ 'app',
31
+ 'poke',
32
+ 'refetch',
33
+ 'denied',
34
+ 'cleanup',
35
+ ] as const
36
+ /** One step of the round trip. */
37
+ export type Link = (typeof LINKS)[number]
38
+
39
+ /** How a round trip went: the link it broke at, and what wasn't tested. */
40
+ export interface VerifyResult {
41
+ ok: boolean
42
+ /** The link that broke, and what it said. */
43
+ broke?: { link: Link; why: string }
44
+ ms: Partial<Record<Link, number>>
45
+ untested: { link: Link; why: string }[]
46
+ }
47
+
48
+ /** What `roundTrip` needs: the query, the feed, and where the app is. */
49
+ export interface RoundTrip {
50
+ fn: Fn
51
+ source?: Source
52
+ url?: string
53
+ db?: string
54
+ options: VerifyOptions
55
+ env: Record<string, string | undefined>
56
+ }
57
+
58
+ /** The query's table: the first of its tags `changes` reports. */
59
+ function tableOf(fn: Fn, source: Source | undefined, input: unknown): string | undefined {
60
+ const any = new Proxy({}, { get: (_, k) => (k === Symbol.toPrimitive ? () => '*' : '*') })
61
+ let tags: readonly string[] = []
62
+ try {
63
+ tags =
64
+ typeof fn.def.tags === 'function'
65
+ ? fn.def.tags(input ?? any, any as Context)
66
+ : (fn.def.tags ?? [])
67
+ } catch {}
68
+ const names = tags.map((t) => t.split(':')[0])
69
+ return names.find((t) => t !== undefined && source?.tables.includes(t)) ?? names[0]
70
+ }
71
+
72
+ /** Writes a real row and follows it to a live client, naming the first link that breaks. */
73
+ export async function roundTrip({
74
+ fn,
75
+ source,
76
+ url,
77
+ db,
78
+ options,
79
+ env,
80
+ }: RoundTrip): Promise<VerifyResult> {
81
+ const { input, timeout = 5000 } = options
82
+ const marker = `kerf-verify-${crypto.randomUUID()}` // concurrent builds never touch each other's row
83
+ const ms: VerifyResult['ms'] = {}
84
+ const untested: VerifyResult['untested'] = []
85
+ const cookie = env[options.cookie ?? 'KERF_STAGING_COOKIE']
86
+ const other = env[options.otherCookie ?? 'KERF_STAGING_OTHER_COOKIE']
87
+ const timed = timer(ms)
88
+ const skip = skipper(untested)
89
+ const { sql, listener } = database(db)
90
+ const ac = new AbortController()
91
+ let row: Awaited<ReturnType<typeof insert>> | undefined
92
+ try {
93
+ const table = tableOf(fn, source, input)
94
+ if (!table) throw new Broke('trigger', `\`${fn.$id}\` has no tag naming a table`)
95
+ const heard: string[] = []
96
+ let hearing: (() => void) | undefined
97
+ if (sql) {
98
+ await timed('trigger', () => checkTrigger(sql, table))
99
+ await listener!.listen(CHANNEL, (p) => {
100
+ heard.push(p)
101
+ hearing?.()
102
+ })
103
+ } else
104
+ skip(
105
+ ['trigger', 'write', 'notify', 'poke', 'refetch', 'denied', 'cleanup'],
106
+ 'no database target: nothing wrote a row, so only the app and its feed were checked. Set `STAGING_DATABASE_URL` or `verify.db`',
107
+ )
108
+
109
+ const live = url
110
+ ? await timed('app', () =>
111
+ openApp({ url, id: fn.$id, input, cookie, signal: ac.signal, timeout }),
112
+ )
113
+ : undefined
114
+ skipWithoutUrl(url, sql, skip)
115
+
116
+ if (!sql) {
117
+ if (live) ac.abort()
118
+ return { ok: true, ms, untested }
119
+ }
120
+ const denied =
121
+ url && !(cookie && !other && !(fn.def.auth && fn.def.auth !== 'public'))
122
+ ? await subscribe(url, fn.$id, input, other, ac.signal).catch(() => undefined)
123
+ : undefined
124
+
125
+ const pk = await primaryKey(sql, table)
126
+ row = await timed('write', () => insert(sql, table, marker, options.row ?? {}, pk))
127
+ await timed('notify', () =>
128
+ waitNotice(heard, table, row!.id, timeout, (wake) => (hearing = wake)),
129
+ )
130
+ if (live)
131
+ await checkLive({
132
+ live,
133
+ denied,
134
+ timed,
135
+ skip,
136
+ url: url!,
137
+ id: fn.$id,
138
+ input,
139
+ cookie,
140
+ other,
141
+ marker,
142
+ timeout,
143
+ options,
144
+ })
145
+ return { ok: true, ms, untested }
146
+ } catch (e) {
147
+ const b = e instanceof Broke ? e : new Broke('trigger', clean(e))
148
+ return { ok: false, broke: { link: b.link, why: clean(b.message) }, ms, untested }
149
+ } finally {
150
+ await cleanup({ ac, row, ms, sql, listener, marker })
151
+ }
152
+ }
package/src/view.tsx ADDED
@@ -0,0 +1,132 @@
1
+ // The route views (research 25 §3): `<App>` renders level 0, and each level renders its route's component with the
2
+ // next level as `children`. The same file compiles for the server and the client, so both build the same tree and
3
+ // hydration keys line up. A level's hole reads only its route id: params and data reach the component as live
4
+ // props, so a navigation that keeps the route re-runs only the bindings that read what changed.
5
+
6
+ import { untrack } from '@kerf-js/core'
7
+ import { active, level, type RouteState } from './router'
8
+ import type { PreparedRouteShape } from './run/shape-preparation'
9
+ import { retainRouteView } from './run/retain-view'
10
+
11
+ function ShapeTree(props: { shapes: PreparedRouteShape[]; depth: number }): unknown {
12
+ // A skeleton is a snapshot: the outlet swaps the whole tree when its shapes change.
13
+ const item = untrack(() => props.shapes[props.depth])
14
+ if (!item) return null
15
+ const Shape = item.component as (props: { children: unknown }) => unknown
16
+ return (
17
+ <Shape>
18
+ <ShapeTree shapes={props.shapes} depth={props.depth + 1} />
19
+ </Shape>
20
+ )
21
+ }
22
+
23
+ // The route state travels as a prop, not a context: a level's view runs later, in the hole that shows it, under that
24
+ // hole's owner. `active.route` is the state of the render in progress (a server pass is synchronous; the client has one).
25
+ export function App(props: { route: RouteState }) {
26
+ const route = (active.route = untrack(() => props.route))
27
+ return <Level route={route} depth={0} />
28
+ }
29
+
30
+ export function Level(props: { route: RouteState; depth: number }) {
31
+ const route = untrack(() => props.route)
32
+ const lv = level(
33
+ route,
34
+ untrack(() => props.depth),
35
+ )
36
+ const next = untrack(() => props.depth) + 1
37
+ const view = () => {
38
+ const id = lv.id.value
39
+ if (id === undefined) return null
40
+ const html = route.mount ? lv.html.value : undefined
41
+ if (html !== undefined)
42
+ return route.mount!(
43
+ html,
44
+ untrack(() => props.depth),
45
+ () => <Level route={route} depth={next} />,
46
+ )
47
+ const Route = route.comps[id] as
48
+ | ((props: { params: Record<string, string>; data: unknown; children: unknown }) => unknown)
49
+ | undefined
50
+ if (!Route) return null
51
+ const body = () => (
52
+ <Route params={lv.params.value} data={lv.data.value}>
53
+ <Level route={route} depth={next} />
54
+ </Route>
55
+ )
56
+ return route.around
57
+ ? route.around(
58
+ untrack(() => props.depth),
59
+ id,
60
+ body,
61
+ )
62
+ : body()
63
+ }
64
+ const display = retainRouteView(view, () => {
65
+ const shape = lv.shape.value
66
+ return shape ? (
67
+ <div inert aria-hidden="true" style="display:contents">
68
+ <ShapeTree shapes={shape} depth={0} />
69
+ </div>
70
+ ) : undefined
71
+ })
72
+ return <>{display()}</>
73
+ }
74
+
75
+ /** True when `path` is `href`, or with `section`, any page under it (a top link for `/components` on `/components/modal`). */
76
+ export function isCurrent(path: string, href: string, section = false) {
77
+ if (path === href) return true
78
+ return section && href !== '/' && path.startsWith(`${href.replace(/\/$/, '')}/`)
79
+ }
80
+
81
+ /**
82
+ * `<a>` with `aria-current="page"` while its path is the current one, or with `match="section"` any page under it, as a
83
+ * site's top links want. Any same-origin `<a href>` navigates on the client (start() listens for clicks); Link only
84
+ * adds the current-page state. In a static level the server writes it and start() updates it after a navigation, so a
85
+ * Link needs no code there.
86
+ *
87
+ * @kerf static
88
+ */
89
+ export function Link({
90
+ href,
91
+ match,
92
+ children,
93
+ ...rest
94
+ }: Record<string, unknown> & {
95
+ href: string
96
+ match?: 'page' | 'section'
97
+ class?: string
98
+ rel?: string
99
+ children?: unknown
100
+ }) {
101
+ const route = active.route
102
+ return (
103
+ <a
104
+ {...rest}
105
+ href={href}
106
+ data-match={match === 'section' ? 'section' : undefined}
107
+ aria-current={
108
+ route && isCurrent(route.path.value.replace(/[?#].*/, ''), href, match === 'section')
109
+ ? 'page'
110
+ : undefined
111
+ }
112
+ >
113
+ {children}
114
+ </a>
115
+ )
116
+ }
117
+
118
+ /**
119
+ * The current page's path, without its search or hash: the request's on the server, and on the client the accepted
120
+ * destination from the moment a navigation starts. Reading it is reactive.
121
+ *
122
+ * Use it to keep shared chrome mounted across sections: one layout above them renders the sidebar and picks its items
123
+ * from the path, so moving between sections swaps the items and the page, and the sidebar stays. A layout per section
124
+ * would be replaced, sidebar and all, on every move between them.
125
+ *
126
+ * What reads it runs in the browser, since it changes there: a static level's HTML would be swapped whole on each move.
127
+ *
128
+ * @kerf client
129
+ */
130
+ export function currentPath(): string {
131
+ return active.route?.path.value.replace(/[?#].*/, '') ?? '/'
132
+ }