@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,102 @@
1
+ // Postgres for `@kerf-js/start` (research 28 §2): Drizzle on postgres.js, pure JS on Node, Bun and Deno. The client
2
+ // connects on the first statement, so `kerf build` and a page with no queries need no database. Migrations hold an
3
+ // advisory lock, so instances starting together apply each file once.
4
+
5
+ import postgres from 'postgres'
6
+ import { drizzle, type PostgresJsDatabase } from 'drizzle-orm/postgres-js'
7
+ import { StartError } from '../data'
8
+ import { gate, register, statements, touch, type DbHandle, type Migration } from './core'
9
+
10
+ /** `createDb` on Postgres: the schema, the URL, and whether to migrate on first use. */
11
+ export interface PostgresOptions<S extends Record<string, unknown>> {
12
+ schema: S
13
+ /** `postgres://user:pass@host:5432/db`. */
14
+ url: string
15
+ /** Apply `drizzle/` before the first statement a request runs (default true). */
16
+ migrate?: boolean
17
+ /** Pool size (default 10). */
18
+ max?: number
19
+ /**
20
+ * Keep each statement prepared on its connection (default true). Drizzle asks for neither, and an unprepared statement
21
+ * with parameters is two round trips, a describe before every bind. Off behind a pooler in transaction mode. A long
22
+ * list isn't kept: each length is a statement of its own, and each statement stays in the connection's memory.
23
+ */
24
+ prepare?: boolean
25
+ }
26
+
27
+ /** Drizzle on postgres.js, with `$kerf` for the framework's own needs. */
28
+ export type PostgresDb<S extends Record<string, unknown>> = PostgresJsDatabase<S> & {
29
+ $kerf: DbHandle
30
+ }
31
+
32
+ const LOCK = 7_301_986
33
+ /** The most parameters a statement that's kept takes. Past it, `inArray` over a growing list is what's asking. */
34
+ const KEPT = 32
35
+
36
+ /** A pooled Drizzle client on Postgres, with this app's migrations and write tracking. */
37
+ export function createDb<S extends Record<string, unknown>>({
38
+ schema,
39
+ url,
40
+ migrate = true,
41
+ max = 10,
42
+ prepare = true,
43
+ }: PostgresOptions<S>): PostgresDb<S> {
44
+ if (!url && process.env.KERF_BUILD) url = 'postgres://localhost/build' // a build loads this module and never connects
45
+ if (!/^postgres(ql)?:\/\//.test(url ?? ''))
46
+ throw new StartError(
47
+ 'Q013',
48
+ `\`@kerf-js/start/db/postgres\` needs a \`postgres://\` URL, not \`${(url ?? '').replace(/\/\/.*@/, '//…@')}\``,
49
+ 'set `DATABASE_URL`, or `createDb` from `@kerf-js/start/db/sqlite` for a file',
50
+ )
51
+ // Idle connections close, so a stopped server can exit.
52
+ const client = postgres(url, { max, idle_timeout: 20, onnotice: () => {} })
53
+ const handle: DbHandle = {
54
+ dialect: 'postgresql',
55
+ exempt: new Set(),
56
+ ping: () => client.unsafe('select 1'),
57
+ async migrate(list: Migration[]) {
58
+ await client.begin(async (tx) => {
59
+ await tx.unsafe(`select pg_advisory_xact_lock(${LOCK})`)
60
+ await tx.unsafe(
61
+ 'create table if not exists __kerf_migrations (tag text primary key, at timestamptz not null default now())',
62
+ )
63
+ const done = new Set(
64
+ (await tx.unsafe('select tag from __kerf_migrations')).map((r) => r.tag),
65
+ )
66
+ for (const m of list) {
67
+ if (done.has(m.tag)) continue
68
+ for (const s of statements(m.sql)) await tx.unsafe(s)
69
+ await tx.unsafe('insert into __kerf_migrations (tag) values ($1)', [m.tag])
70
+ }
71
+ })
72
+ },
73
+ changes: (tables, o) =>
74
+ import('./changes-postgres').then((m) => m.postgresChanges({ ...o, url, client, tables })),
75
+ }
76
+ const ready = gate(handle, migrate)
77
+ // All Drizzle sends goes through `unsafe` and `begin`, so holding those holds it; `handle.migrate` keeps the plain client.
78
+ const held = new Proxy(client, {
79
+ get(t, key) {
80
+ if (key === 'begin')
81
+ return async (...a: Parameters<typeof t.begin>) => (await ready(), t.begin(...a))
82
+ if (key !== 'unsafe') return Reflect.get(t, key)
83
+ return (
84
+ text: string,
85
+ params?: postgres.ParameterOrJSON<never>[],
86
+ options?: postgres.UnsafeQueryOptions,
87
+ ) => {
88
+ const send = () =>
89
+ t.unsafe(text, params, { ...options, prepare: prepare && (params?.length ?? 0) <= KEPT })
90
+ const after = <T>(go: () => PromiseLike<T>) => Promise.resolve(ready()).then(go)
91
+ // oxlint-disable unicorn/no-thenable -- postgres.js's query is a lazy thenable, and Drizzle awaits it as one
92
+ return {
93
+ values: () => after(() => send().values()),
94
+ then: <A, B>(ok: (rows: unknown) => A, no: (e: unknown) => B) =>
95
+ after(send).then(ok, no) /* oxlint-enable unicorn/no-thenable */,
96
+ }
97
+ }
98
+ },
99
+ })
100
+ const db = drizzle(held, { schema, logger: { logQuery: (sql) => touch(handle, sql) } })
101
+ return register(db, handle)
102
+ }
@@ -0,0 +1,166 @@
1
+ // SQLite for `@kerf-js/start` (research 28 §1): Node's and Deno's `node:sqlite` or Bun's `bun:sqlite` behind Drizzle's
2
+ // proxy driver, so no native binary and the same async API as Postgres. One connection, opened on the first statement
3
+ // (`kerf build` loads this module and must not touch a file). A transaction's body is async, so it holds a gate:
4
+ // statements outside it wait, or a rollback would take another request's writes with it.
5
+
6
+ // oxlint-disable-next-line typescript/triple-slash-reference -- an installed app's tsc doesn't include this file by itself, and it declares a module, so nothing can import it
7
+ /// <reference path="./bun-sqlite.d.ts" />
8
+ import { AsyncLocalStorage } from 'node:async_hooks'
9
+ import { mkdirSync } from 'node:fs'
10
+ import { dirname } from 'node:path'
11
+ import type { SQLInputValue } from 'node:sqlite'
12
+ import { drizzle, type SqliteRemoteDatabase } from 'drizzle-orm/sqlite-proxy'
13
+ import { StartError } from '../data'
14
+ import { gate, register, statements, touch, type DbHandle, type Migration } from './core'
15
+
16
+ /** How Drizzle's proxy driver asks for rows. */
17
+ export type Method = 'run' | 'all' | 'values' | 'get'
18
+
19
+ interface Conn {
20
+ /** Array rows, as the proxy driver wants them. */
21
+ query(sql: string, params: unknown[], method: Method): unknown
22
+ exec(sql: string): void
23
+ close?(): void
24
+ }
25
+
26
+ /** The file open on this runtime's driver: Bun's, or `node:sqlite`. */
27
+ export async function open(path: string): Promise<Conn> {
28
+ if (path !== ':memory:') mkdirSync(dirname(path), { recursive: true })
29
+ const pick = (rows: unknown[][], method: Method) => (method === 'get' ? rows[0] : rows)
30
+ let conn: Conn
31
+ if ('Bun' in globalThis) {
32
+ const { Database } = await import('bun:sqlite')
33
+ const db = new Database(path, { create: true })
34
+ conn = {
35
+ query: (sql, params, method) =>
36
+ method === 'run'
37
+ ? void db.prepare(sql).run(...params)
38
+ : pick(db.prepare(sql).values(...params), method),
39
+ exec: (sql) => void db.run(sql),
40
+ close: () => db.close(),
41
+ }
42
+ } else {
43
+ const { DatabaseSync } = await import('node:sqlite')
44
+ const db = new DatabaseSync(path)
45
+ conn = {
46
+ query: (sql, params, method) => {
47
+ const s = db.prepare(sql)
48
+ if (method === 'run') return void s.run(...(params as SQLInputValue[]))
49
+ s.setReturnArrays(true)
50
+ return pick(s.all(...(params as SQLInputValue[])) as unknown as unknown[][], method)
51
+ },
52
+ exec: (sql) => db.exec(sql),
53
+ close: () => db.close(),
54
+ }
55
+ }
56
+ if (path !== ':memory:') conn.exec('pragma journal_mode = wal')
57
+ conn.exec('pragma foreign_keys = on; pragma busy_timeout = 5000')
58
+ return conn
59
+ }
60
+
61
+ async function migrateSqlite(connect: () => Promise<Conn>, list: Migration[]) {
62
+ const c = await connect()
63
+ c.exec('create table if not exists __kerf_migrations (tag text primary key, at integer not null)')
64
+ const done = new Set(
65
+ (c.query('select tag from __kerf_migrations', [], 'values') as string[][]).map((r) => r[0]),
66
+ )
67
+ for (const m of list) {
68
+ if (done.has(m.tag)) continue
69
+ c.exec('begin')
70
+ try {
71
+ for (const s of statements(m.sql)) c.exec(s)
72
+ c.query('insert into __kerf_migrations values (?, ?)', [m.tag, Date.now()], 'run')
73
+ c.exec('commit')
74
+ } catch (e) {
75
+ c.exec('rollback')
76
+ throw e
77
+ }
78
+ }
79
+ }
80
+
81
+ /** `createDb` on SQLite: the schema, the file, and whether to migrate on first use. */
82
+ export interface SqliteOptions<S extends Record<string, unknown>> {
83
+ schema: S
84
+ /** `file:.data/app.db` (the default), a path, or `:memory:`. */
85
+ url?: string
86
+ /** Apply `drizzle/` before the first statement a request runs (default true). */
87
+ migrate?: boolean
88
+ }
89
+
90
+ /** Drizzle over a local file, with `$kerf` for the framework's own needs. */
91
+ export type SqliteDb<S extends Record<string, unknown>> = SqliteRemoteDatabase<S> & {
92
+ $kerf: DbHandle
93
+ }
94
+
95
+ /** A Drizzle client on a SQLite file, with this app's migrations and write tracking. */
96
+ export function createDb<S extends Record<string, unknown>>({
97
+ schema,
98
+ url = 'file:.data/app.db',
99
+ migrate = true,
100
+ }: SqliteOptions<S>): SqliteDb<S> {
101
+ if (/^[a-z][a-z0-9+.-]+:\/\//i.test(url) && !url.startsWith('file:'))
102
+ throw new StartError(
103
+ 'Q013',
104
+ `\`@kerf-js/start/db/sqlite\` can't open \`${url.replace(/\/\/.*@/, '//…@')}\``,
105
+ 'use `file:<path>`, or `createDb` from `@kerf-js/start/db/postgres` for a Postgres URL',
106
+ )
107
+ const path = url.replace(/^file:/, '')
108
+ let conn: Promise<Conn> | undefined
109
+ const connect = () =>
110
+ (conn ??= open(path).catch((e) => {
111
+ conn = undefined
112
+ throw e
113
+ }))
114
+ const inside = new AsyncLocalStorage<boolean>()
115
+ let held: Promise<unknown> = Promise.resolve()
116
+ const handle: DbHandle = {
117
+ dialect: 'sqlite',
118
+ exempt: new Set(),
119
+ ping: async () => (await connect()).query('select 1', [], 'all'),
120
+ migrate: (list) => migrateSqlite(connect, list),
121
+ changes: (tables, o) =>
122
+ import('./changes-sqlite').then((m) => m.sqliteChanges({ ...o, path, open, tables })),
123
+ }
124
+ const ready = gate(handle, migrate)
125
+ const run = async (sql: string, params: unknown[], method: Method) => {
126
+ touch(handle, sql)
127
+ await ready()
128
+ const c = await connect()
129
+ if (!inside.getStore()) await held
130
+ return { rows: c.query(sql, params, method) as unknown[] }
131
+ }
132
+ const batch = async (list: { sql: string; params: unknown[]; method: Method }[]) => {
133
+ await ready()
134
+ const c = await connect()
135
+ await held
136
+ c.exec('begin')
137
+ try {
138
+ const out = list.map(
139
+ (q) => (touch(handle, q.sql), { rows: c.query(q.sql, q.params, q.method) as unknown[] }),
140
+ )
141
+ c.exec('commit')
142
+ return out
143
+ } catch (e) {
144
+ c.exec('rollback')
145
+ throw e
146
+ }
147
+ }
148
+ const db = drizzle(run, batch, { schema })
149
+ const transaction = db.transaction.bind(db)
150
+ db.transaction = (async (...args: Parameters<typeof transaction>) => {
151
+ if (inside.getStore()) return transaction(...args)
152
+ await ready()
153
+ const before = held
154
+ let release!: () => void
155
+ held = new Promise<void>((ok) => {
156
+ release = ok
157
+ })
158
+ await before
159
+ try {
160
+ return await inside.run(true, () => transaction(...args))
161
+ } finally {
162
+ release()
163
+ }
164
+ }) as typeof db.transaction
165
+ return register(db, handle)
166
+ }
@@ -0,0 +1,19 @@
1
+ /** The text with HTML entities decoded. */
2
+ export function decode(text: string): string
3
+ /** One line of plain text: whitespace collapsed, no list marker in front. */
4
+ export function cleanText(text: string): string
5
+ /** At most `max` characters, cut at a sentence or a word. */
6
+ export function truncate(text: string, max?: number): string
7
+ /** `undefined`, or why this text isn't a description a person would read. */
8
+ export function descriptionProblem(text: string): string | undefined
9
+ /** A page's title and description, as a person would pick them out of its HTML. */
10
+ export function pageText(html: string): { title?: string; description?: string }
11
+ /** The site's URL, from its config or from what the host says about this deploy. */
12
+ export function deployUrl(
13
+ site: { url?: string | undefined } | undefined,
14
+ env?: Record<string, string | undefined>,
15
+ ): string | undefined
16
+ /** The card title's font size, smaller for a longer title. */
17
+ export function cardTitleSize(title: string): number
18
+ /** `paths` in pages that each fit in a response header. */
19
+ export function pathPages(paths: string[], max?: number): string[][]
package/src/derive.mjs ADDED
@@ -0,0 +1,237 @@
1
+ // What a page's HTML says about itself (research 20 §10): the automatic layer under route `meta`. A route that sets no
2
+ // title gets its `h1`, one that sets no description gets its first real paragraph, cleaned and cut at a sentence. Pure
3
+ // functions on a string, server-side only: `kerf check` runs the same `descriptionProblem` on what a route wrote.
4
+
5
+ const SKIP = new Set([
6
+ 'script',
7
+ 'style',
8
+ 'template',
9
+ 'noscript',
10
+ 'svg',
11
+ 'math',
12
+ 'nav',
13
+ 'aside',
14
+ 'footer',
15
+ 'pre',
16
+ 'figure',
17
+ 'table',
18
+ 'ul',
19
+ 'ol',
20
+ 'dl',
21
+ 'details',
22
+ 'button',
23
+ 'select',
24
+ 'textarea',
25
+ 'form',
26
+ 'dialog',
27
+ 'iframe',
28
+ 'canvas',
29
+ 'object',
30
+ ])
31
+ const VOID = new Set([
32
+ 'area',
33
+ 'base',
34
+ 'br',
35
+ 'col',
36
+ 'embed',
37
+ 'hr',
38
+ 'img',
39
+ 'input',
40
+ 'link',
41
+ 'meta',
42
+ 'source',
43
+ 'track',
44
+ 'wbr',
45
+ ])
46
+ const ENTITIES = {
47
+ amp: '&',
48
+ lt: '<',
49
+ gt: '>',
50
+ quot: '"',
51
+ apos: "'",
52
+ nbsp: ' ',
53
+ mdash: '—',
54
+ ndash: '–',
55
+ hellip: '…',
56
+ rsquo: '’',
57
+ lsquo: '‘',
58
+ ldquo: '“',
59
+ rdquo: '”',
60
+ middot: '·',
61
+ copy: '©',
62
+ reg: '®',
63
+ trade: '™',
64
+ times: '×',
65
+ rarr: '→',
66
+ larr: '←',
67
+ }
68
+
69
+ /** `&amp;`, `&#39;`, `&#x27;` → their characters. An unknown name stays as written. */
70
+ export const decode = (text) =>
71
+ text.replace(/&(#\d+|#x[\da-f]+|[a-z]+);/gi, (all, e) => {
72
+ if (e[0] !== '#') return ENTITIES[e] ?? all
73
+ const n = e[1] === 'x' || e[1] === 'X' ? parseInt(e.slice(2), 16) : Number(e.slice(1))
74
+ return n > 0 && n <= 0x10ffff ? String.fromCodePoint(n) : ''
75
+ })
76
+
77
+ /** One line of plain text: whitespace collapsed, no list marker in front, no space before punctuation. */
78
+ export const cleanText = (text) =>
79
+ text
80
+ .replace(/\s+/g, ' ')
81
+ .replace(/\s+([.,;:!?)])(?=\s|$)/g, '$1')
82
+ .trim()
83
+ .replace(/^(?:[-*•‣–—]\s+|\d{1,3}[.)]\s+)+/, '')
84
+
85
+ /** Not the end of a sentence, though it ends in a full stop. */
86
+ const ABBREVIATION = /(?:^|[\s(])(?:e\.g|i\.e|etc|vs|cf|approx|no|fig|[A-Z])\.$/
87
+
88
+ /**
89
+ * At most `max` characters: whole sentences when the first ones fit (past a third of `max`, so one short sentence
90
+ * isn't all that's left), else whole words and an ellipsis. Never cuts inside a word.
91
+ */
92
+ export function truncate(text, max = 155) {
93
+ if (text.length <= max) return text
94
+ const head = text.slice(0, max + 1)
95
+ let end = -1
96
+ for (const m of head.matchAll(/[.!?…]["'”’)]?(?=\s)/g)) {
97
+ const at = m.index + m[0].length
98
+ if (at >= max / 3 && at <= max && !ABBREVIATION.test(head.slice(0, at))) end = at
99
+ }
100
+ if (end > 0) return head.slice(0, end)
101
+ const cut = head.slice(0, max).replace(/\s+\S*$/, '')
102
+ return cut.replace(/[\s,;:(–—-]+$/, '') + '…'
103
+ }
104
+
105
+ /** `undefined`, or why this text isn't a description a person would read: markup, code, a list item or a fragment. */
106
+ export function descriptionProblem(text) {
107
+ const s = text.trim()
108
+ if (/^(?:[-*•+]\s|\d{1,3}[.)]\s|#{1,6}\s|>\s)/.test(s))
109
+ return 'it starts with a markdown list marker or heading'
110
+ if (/<\/?[a-z][^>]*>?|\/>|=>|\w\(\)|[{}]|`|\]\(|\bx = </i.test(s))
111
+ return 'it holds code or markup'
112
+ if ((s.match(/[<>=;$[\]{}()|\\]/g)?.length ?? 0) / Math.max(s.length, 1) > 0.05)
113
+ return 'it is mostly symbols, which reads as code'
114
+ if (/\s[.,;:!?)](?=\s|$)/.test(s))
115
+ return 'it has a space before punctuation, the mark of inline code that was stripped out'
116
+ if (s.length && !/[.!?…"'”’)]$/.test(s) && s.length > 100) return 'it stops mid-sentence'
117
+ if (/^[a-z]/.test(s) && !/^[a-z][\w.-]*[A-Z@/:]|^[a-z]+:/.test(s))
118
+ return 'it starts in lower case, like a fragment of a longer sentence'
119
+ return undefined
120
+ }
121
+
122
+ /** A paragraph worth quoting: prose of some length, with no code in it. */
123
+ const prose = (text) =>
124
+ text.length >= 40 && text.includes(' ') && !descriptionProblem(truncate(text))
125
+
126
+ function tokens(html) {
127
+ const out = []
128
+ const re = /<!--[\s\S]*?-->|<(\/?)([a-zA-Z][\w:-]*)((?:[^>"']|"[^"]*"|'[^']*')*)>/g
129
+ let at = 0
130
+ for (let m; (m = re.exec(html)); at = re.lastIndex) {
131
+ if (m.index > at) out.push({ text: html.slice(at, m.index) })
132
+ if (m[2]) out.push({ close: !!m[1], tag: m[2].toLowerCase(), attrs: m[3] })
133
+ }
134
+ if (at < html.length) out.push({ text: html.slice(at) })
135
+ return out
136
+ }
137
+
138
+ const hidden = (attrs) => /\s(?:hidden|aria-hidden=(?:"true"|'true'|true))(?:[\s/]|$)/.test(attrs)
139
+
140
+ /**
141
+ * The page's own words: `{ title, description }`, either missing when the page doesn't have one. Reads `<main>` when
142
+ * there is one, so a header or a footer in a layout can't speak for the page. The title is the `h1`, or with none the
143
+ * first `h2` or `h3`; the description is the first paragraph after the `h1` that reads as prose.
144
+ */
145
+ export function pageText(html) {
146
+ const open = /<main\b/i.exec(html)
147
+ const end = html.toLowerCase().lastIndexOf('</main>')
148
+ const region = open ? html.slice(open.index, end > open.index ? end : undefined) : html
149
+ let title,
150
+ heading,
151
+ description,
152
+ skip,
153
+ grab,
154
+ buffer = ''
155
+ const done = (t) => {
156
+ const text = cleanText(decode(buffer))
157
+ grab = undefined
158
+ if (t === 'p') {
159
+ if (prose(text)) description ??= truncate(text)
160
+ } else if (t !== 'h1') heading ??= text || undefined
161
+ else if (text && !title) {
162
+ title = text
163
+ description = undefined
164
+ } // the description is what follows the title
165
+ }
166
+ for (const t of tokens(region)) {
167
+ if (skip) {
168
+ if (t.tag === skip.tag && !VOID.has(t.tag) && !/\/\s*$/.test(t.attrs ?? ''))
169
+ skip.depth += t.close ? -1 : 1
170
+ if (!skip.depth) skip = undefined
171
+ continue
172
+ }
173
+ if (t.text !== undefined) {
174
+ if (grab) buffer += t.text
175
+ continue
176
+ }
177
+ if (
178
+ !t.close &&
179
+ (SKIP.has(t.tag) || hidden(t.attrs)) &&
180
+ !VOID.has(t.tag) &&
181
+ !/\/\s*$/.test(t.attrs)
182
+ ) {
183
+ skip = { tag: t.tag, depth: 1 }
184
+ continue
185
+ }
186
+ if (grab) {
187
+ if (t.close && t.tag === grab) done(t.tag)
188
+ else if (t.tag === 'br') buffer += ' '
189
+ continue
190
+ }
191
+ if (!t.close && /^(?:h1|h2|h3|p)$/.test(t.tag)) {
192
+ grab = t.tag
193
+ buffer = ''
194
+ }
195
+ if (title && description) break
196
+ }
197
+ return { title: title ?? heading, description }
198
+ }
199
+
200
+ /**
201
+ * The site's public origin, when something says what it is: `site.url`, `KERF_SITE_URL`, or what the host sets on a
202
+ * deploy. No request is involved, so the answer can be trusted and written into a page a CDN keeps.
203
+ */
204
+ export function deployUrl(site, env = {}) {
205
+ if (site?.url) return site.url
206
+ const https = (host) => host && `https://${host}`
207
+ return (
208
+ env.KERF_SITE_URL ||
209
+ https(env.VERCEL_PROJECT_PRODUCTION_URL) ||
210
+ https(env.VERCEL_URL) ||
211
+ env.URL || // Netlify
212
+ env.CF_PAGES_URL ||
213
+ env.RENDER_EXTERNAL_URL ||
214
+ https(env.RAILWAY_PUBLIC_DOMAIN) ||
215
+ (env.FLY_APP_NAME && `https://${env.FLY_APP_NAME}.fly.dev`) ||
216
+ undefined
217
+ )
218
+ }
219
+
220
+ /** The built-in card's title size: bigger type for a shorter title. */
221
+ export const cardTitleSize = (title) =>
222
+ title.length <= 24 ? 92 : title.length <= 44 ? 76 : title.length <= 70 ? 62 : 52
223
+
224
+ /** `paths` in pages that each fit in a response header, with room for the link to the next page. */
225
+ export function pathPages(paths, max = 6000) {
226
+ const pages = [[]]
227
+ let size = 0
228
+ for (const p of paths) {
229
+ if (size + p.length + 1 > max) {
230
+ pages.push([])
231
+ size = 0
232
+ }
233
+ pages.at(-1).push(p)
234
+ size += p.length + 1
235
+ }
236
+ return pages
237
+ }
@@ -0,0 +1,46 @@
1
+ // `kerf dev` for an app with sockets on Bun and Deno. Nitro's dev server assumes a Node worker for websockets: its
2
+ // entry takes crossws's Node adapter, which refuses to load there, and a worker on either runtime can't take the
3
+ // upgrade. So the app runs in Vite's own process (the `self` runner), where Vite's HTTP server hands the upgrade over
4
+ // and the adapter works. Node, and any app without a channel or sharedState, gets none of this.
5
+
6
+ const alternate = Boolean(process.versions.bun || process.versions.deno)
7
+
8
+ export const devRunner = (sockets) => (alternate && sockets ? 'self' : undefined)
9
+
10
+ const GUARD = /if \("Deno" in globalThis \|\| "Bun" in globalThis\) throw new Error\([^)]*\);?/
11
+
12
+ export const devSockets = () => ({
13
+ name: 'kerf:dev-sockets',
14
+ apply: 'serve',
15
+ enforce: 'post',
16
+ configResolved(config) {
17
+ for (const [name, environment] of Object.entries(config.environments)) {
18
+ const create = environment.dev?.createEnvironment
19
+ if (!create || environment.consumer !== 'server') continue
20
+ const release = hold(name)
21
+ environment.dev.createEnvironment = async (...args) => release(await create(...args))
22
+ }
23
+ },
24
+ transform: {
25
+ filter: { id: /crossws/, code: 'incompatible environment' },
26
+ handler: (code) => code.replace(GUARD, ''),
27
+ },
28
+ })
29
+
30
+ // Nitro can name an environment to the runner before Vite has made it. Across a process that takes long enough, but
31
+ // `self` answers at once: the first request goes to nothing and the environment hangs for good. So each one is held
32
+ // until it exists, and `init` names it again. (The worker keeps these on globalThis, and `self` is this process.)
33
+ const HELD = {
34
+ hasEvaluated: () => false,
35
+ reload: async () => {},
36
+ fetch: () => Promise.resolve(new Response('starting', { status: 503 })),
37
+ }
38
+
39
+ function hold(name) {
40
+ const environments = (globalThis.__nitro_vite_envs__ ??= {})
41
+ environments[name] = HELD
42
+ return (environment) => {
43
+ environments[name] = undefined
44
+ return environment
45
+ }
46
+ }