@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,299 @@
1
+ // `.kerf/contract.json` (PLAN §4.1, research 28 §4): every query and mutation as JSON Schema, with tags, cache and auth
2
+ // scope. `kerf build` writes it; the OpenAPI export, the MCP server and Rust codegen read it. The server modules are
3
+ // loaded through Vite, never run: creating a database client connects to nothing.
4
+
5
+ import { createHash } from 'node:crypto'
6
+ import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'
7
+ import { join, resolve } from 'node:path'
8
+ import { createServer } from 'vite'
9
+ import kerf from '@kerf-js/core/vite'
10
+ import {
11
+ holdsSockets,
12
+ literalSecrets,
13
+ liveTarget,
14
+ livePlan,
15
+ refusal,
16
+ resolveTarget,
17
+ scanRequired,
18
+ } from './live-target.mjs'
19
+ import { readMigrations } from './migrations.mjs'
20
+ import { shapeTree } from './shape.mjs'
21
+ import { describe } from './contract/describe.mjs'
22
+ import kerfStart, { startDir } from './vite.mjs'
23
+
24
+ export { describe }
25
+
26
+ const NO_FILES = /^(cloudflare|vercel[-_]edge|netlify[-_]edge|deno[-_]deploy|bunny|fastly)/
27
+ /** Presets that run where they were built, so the addon from this machine is the right one. */
28
+ const LOCAL = /^(node|bun|deno[-_]server)/
29
+
30
+ /** R104 for a build: `native()` on a preset that has no way to run it. */
31
+ export function nativeProblem({ service, preset, wasm }) {
32
+ if (preset && NO_FILES.test(preset))
33
+ return `\`native('${service}')\` can't load on the \`${preset}\` preset: it has no file system, so neither an addon nor a \`.wasm\` file reaches it. Use \`remote('rust://${service}')\`, which is the same crate behind \`kerf::router\``
34
+ if (wasm === false && preset && !LOCAL.test(preset))
35
+ return `\`native('${service}')\` has no WASM, and an addon built here may not fit the \`${preset}\` preset's machines. Drop \`wasm: false\` from \`rust.services.${service}\`, or use \`remote()\``
36
+ }
37
+
38
+ /** Presets that run many instances: a process-local bus reaches a fraction of the clients (R002). */
39
+ const MULTI =
40
+ /^(vercel|netlify|aws[-_]|azure|cloudflare|firebase|deno[-_]deploy|digitalocean|render|koyeb|zeabur)/
41
+
42
+ const usesLive = (root) => {
43
+ const walk = (dir) =>
44
+ readdirSync(dir, { withFileTypes: true }).some((d) => {
45
+ const f = join(dir, d.name)
46
+ return d.isDirectory()
47
+ ? walk(f)
48
+ : /\.[cm]?[jt]sx?$/.test(d.name) && /[\w)\]]\.live\(/.test(readFileSync(f, 'utf8'))
49
+ })
50
+ return existsSync(join(root, 'src')) && walk(join(root, 'src'))
51
+ }
52
+
53
+ /**
54
+ * R002 for one build: `bus` is the configured bus's name.
55
+ * @returns {string | undefined} the message when this build would drop messages
56
+ */
57
+ export const busProblem = ({ preset, bus, streams, root }) =>
58
+ bus === 'durable-object' && preset !== 'cloudflare_durable'
59
+ ? `\`durableObjectBus\` holds a socket open, and on the \`${preset}\` preset that socket dies with the request that opened it: use the \`cloudflare_durable\` preset`
60
+ : bus === 'memory' && MULTI.test(preset ?? '') && (streams || usesLive(root))
61
+ ? `the \`${preset}\` preset runs many instances, and the memory bus only reaches clients on its own: pokes and messages would be lost`
62
+ : undefined
63
+
64
+ /** What this deploy gets from live data, with the config loaded. R018 is a table `changes` lists and no migration covers. */
65
+ function planOf({ root, preset, realtime }) {
66
+ const source = realtime?.changes
67
+ const plan = livePlan({
68
+ preset,
69
+ source: source && { name: source.name, external: source.external, tables: source.tables },
70
+ required: scanRequired(root),
71
+ })
72
+ if (source?.dialect) {
73
+ const sql = readMigrations(root)
74
+ .map((m) => m.sql)
75
+ .join('\n')
76
+ const missing = source.tables.filter(
77
+ (t) =>
78
+ !new RegExp(
79
+ `kerf_changes_(${t.replace(/\W/g, '_')}_)?upd\\b[^;]*["\`\\s]${t}["\`\\s]`,
80
+ ).test(sql),
81
+ )
82
+ if (missing.length)
83
+ plan.diagnostics.push({
84
+ code: 'R018',
85
+ severity: 'warning',
86
+ why: `no migration adds change triggers to ${missing.map((t) => `\`${t}\``).join(', ')}: run \`kerf db live\`. Until then the server falls back to polling.`,
87
+ })
88
+ }
89
+ return plan
90
+ }
91
+
92
+ const verifiedFile = (root) => join(root, '.kerf', 'verify.json')
93
+ const readVerified = (root) => {
94
+ try {
95
+ return JSON.parse(readFileSync(verifiedFile(root), 'utf8'))
96
+ } catch {
97
+ return {}
98
+ }
99
+ }
100
+
101
+ /**
102
+ * Every query's `live.verify`, run. `strict` is a build: a target that isn't reachable from here fails it, where a
103
+ * check warns and goes on. A pass is kept by the query's contract entry and target, so an unchanged query runs once.
104
+ * @returns {Promise<{ diagnostics: any[], verified: any[] }>}
105
+ */
106
+ async function verifyAll({ root, fns, realtime, server, live, strict }) {
107
+ const diagnostics = [],
108
+ verified = []
109
+ for (const hit of literalSecrets(root))
110
+ diagnostics.push({
111
+ code: 'R020',
112
+ severity: 'error',
113
+ file: hit.file,
114
+ why: `${hit.file}:${hit.line} has a connection string with a password in it: it would be committed. Read it from the environment: \`verify: { db: process.env.STAGING_DATABASE_URL }\`, or \`db: 'STAGING_DATABASE_URL'\` in a target.`,
115
+ })
116
+ const queries = [...fns.values()].filter((f) => f.kind === 'query' && f.def.live?.verify)
117
+ if (!queries.length) return { diagnostics, verified }
118
+ const { roundTrip } = await server.ssrLoadModule(join(startDir, 'verify.ts'))
119
+ const cache = readVerified(root)
120
+ const contract = describe(fns).functions
121
+ const { env } = process
122
+ for (const f of queries) {
123
+ const name = f.$id.replace(/\..*$/, '')
124
+ const v = f.def.live.verify
125
+ const options = typeof v === 'object' ? v : {}
126
+ const target = resolveTarget(v, { targets: live?.targets, env })
127
+ if (target.missing) {
128
+ diagnostics.push({
129
+ code: 'R021',
130
+ severity: strict ? 'error' : 'warning',
131
+ why: `\`${name}\` can't be verified on this machine: ${target.missing}${strict ? ' A build needs it, because the query declares it.' : ' Skipped.'}`,
132
+ })
133
+ continue
134
+ }
135
+ const stop = refusal(target, { targets: live?.targets })
136
+ if (stop) {
137
+ diagnostics.push({ code: 'R022', severity: 'error', why: `\`${name}\`: ${stop}.` })
138
+ continue
139
+ }
140
+ const key = createHash('sha256')
141
+ .update(
142
+ JSON.stringify([
143
+ contract.find((c) => c.id === f.$id),
144
+ realtime?.changes?.tables,
145
+ target.name,
146
+ target.url ?? '',
147
+ !!target.db,
148
+ ]),
149
+ )
150
+ .digest('hex')
151
+ .slice(0, 16)
152
+ if (cache[f.$id]?.key === key && !env.KERF_VERIFY_FRESH) {
153
+ verified.push({ name, cached: true, ...cache[f.$id].result })
154
+ continue
155
+ }
156
+ const result = await roundTrip({
157
+ fn: f,
158
+ source: realtime?.changes,
159
+ url: target.url,
160
+ db: target.db,
161
+ options,
162
+ env,
163
+ })
164
+ verified.push({ name, ...result })
165
+ if (result.ok) cache[f.$id] = { key, result, at: new Date().toISOString() }
166
+ else {
167
+ delete cache[f.$id]
168
+ diagnostics.push({
169
+ code: 'R019',
170
+ severity: 'error',
171
+ why: `\`${name}\` failed its live round trip at \`${result.broke.link}\`: ${result.broke.why}.`,
172
+ })
173
+ }
174
+ if (result.ok && result.untested.length)
175
+ diagnostics.push({
176
+ code: 'R023',
177
+ severity: 'warning',
178
+ why: `\`${name}\` passed, with ${result.untested.map((u) => `\`${u.link}\``).join(', ')} untested: ${[...new Set(result.untested.map((u) => u.why))].join(' ')}`,
179
+ })
180
+ }
181
+ mkdirSync(join(root, '.kerf'), { recursive: true })
182
+ writeFileSync(verifiedFile(root), JSON.stringify(cache, null, 2) + '\n')
183
+ return { diagnostics, verified }
184
+ }
185
+
186
+ /** The deploy's live plan on its own, for `kerf check` and `kerf doctor`: no contract is written. */
187
+ export const readLivePlan = ({ root, site, preset, live, verify = true }) => {
188
+ root = resolve(root)
189
+ return withFns({ root, site }, async (fns, server) => {
190
+ const realtime = (await server.ssrLoadModule('virtual:kerf/realtime')).default
191
+ const plan = planOf({ root, preset, realtime })
192
+ if (!verify) return { ...plan, verified: [] }
193
+ const { diagnostics, verified } = await verifyAll({
194
+ root,
195
+ fns,
196
+ realtime,
197
+ server,
198
+ live,
199
+ strict: false,
200
+ })
201
+ return { ...plan, diagnostics: [...plan.diagnostics, ...diagnostics], verified }
202
+ })
203
+ }
204
+
205
+ /** `src/realtime.server.ts` loaded, for `kerf db live` and `kerf db listen`. `fn` holds it open as long as it needs. */
206
+ export const withRealtime = ({ root, site }, fn) =>
207
+ withFns({ root: resolve(root), site }, async (_, server) =>
208
+ fn((await server.ssrLoadModule('virtual:kerf/realtime')).default ?? {}, server),
209
+ )
210
+
211
+ /** Every query's shape tree (research 31 §3), by id. */
212
+ export function shapeTable(fns) {
213
+ const table = {}
214
+ for (const f of fns.values()) {
215
+ const tree = f.kind === 'query' ? shapeTree(f.def) : undefined
216
+ if (tree !== undefined) table[f.$id] = tree
217
+ }
218
+ return table
219
+ }
220
+
221
+ /**
222
+ * `fn(fns, server)` with every server module loaded through a private Vite server. A dev server sets `NODE_ENV` to
223
+ * development when nothing had: that's put back after, or `kerf build`, which reads the live plan first, would build
224
+ * with `import.meta.env.DEV` on and ship every dev-only diagnostic.
225
+ */
226
+ async function withFns({ root, site = {} }, fn) {
227
+ const env = process.env.NODE_ENV
228
+ let server
229
+ try {
230
+ server = await createServer({
231
+ root,
232
+ configFile: false,
233
+ logLevel: 'silent',
234
+ appType: 'custom',
235
+ server: { middlewareMode: true, hmr: false, ws: false },
236
+ plugins: [kerf({ hydratable: true, csp: site?.csp }), kerfStart({ root, site })],
237
+ })
238
+ await server.ssrLoadModule('virtual:kerf/fns')
239
+ const { fns } = await server.ssrLoadModule(join(startDir, 'data.ts'))
240
+ return await fn(fns, server)
241
+ } finally {
242
+ await server?.close()
243
+ if (env === undefined) delete process.env.NODE_ENV
244
+ else process.env.NODE_ENV = env
245
+ }
246
+ }
247
+
248
+ /** The shape table at build: nothing is running yet, so the server modules load the way the contract's do. */
249
+ export const readShapes = (options) =>
250
+ withFns({ ...options, root: resolve(options.root) }, shapeTable)
251
+
252
+ /** Load every server module and write `.kerf/contract.json`. */
253
+ export function writeContract({ root, site = {}, preset, rust, live, verify }) {
254
+ root = resolve(root)
255
+ return withFns({ root, site }, async (fns, server) => {
256
+ const { diagnostics, ...contract } = describe(fns, rust)
257
+ const mod = await server.ssrLoadModule('virtual:kerf/realtime')
258
+ const socket = [...fns.values()].find((f) => f.kind === 'channel' || f.kind === 'shared')
259
+ // a channel needs the socket itself: on a function host no bus helps, so R024 says where it can run instead of R002
260
+ const unheld = socket && !holdsSockets(preset)
261
+ if (unheld)
262
+ diagnostics.push({
263
+ code: 'R024',
264
+ severity: 'error',
265
+ why: `\`${socket.$id.replace(/\..*$/, '')}\` is a ${socket.kind === 'shared' ? 'shared state' : 'channel'}, which needs a WebSocket, and ${liveTarget(preset).host} on \`${preset}\` can't hold one: the page loads, and the channel says \`unavailable\`. \`kerf deploy hosts\` lists the hosts that can (Fly, Render).`,
266
+ })
267
+ const bus = busProblem({
268
+ preset,
269
+ bus: mod.default?.bus?.name ?? 'memory',
270
+ streams: [...fns.values()].some(
271
+ (f) => f.kind === 'stream' || (!unheld && (f.kind === 'channel' || f.kind === 'shared')),
272
+ ),
273
+ root,
274
+ })
275
+ if (bus)
276
+ diagnostics.push({
277
+ code: 'R002',
278
+ severity: 'error',
279
+ why: `${bus}. Add \`@kerf-js/realtime-redis\` or \`@kerf-js/realtime-nats\` to \`plugins\`, or set \`postgresBus\` in \`src/realtime.server.ts\`.`,
280
+ })
281
+ diagnostics.push(...planOf({ root, preset, realtime: mod.default }).diagnostics)
282
+ let verified = []
283
+ if (verify) {
284
+ const done = await verifyAll({ root, fns, realtime: mod.default, server, live, strict: true })
285
+ diagnostics.push(...done.diagnostics)
286
+ verified = done.verified
287
+ }
288
+ for (const [service, s] of Object.entries(contract.services ?? {})) {
289
+ const why =
290
+ s.kind === 'native' &&
291
+ nativeProblem({ service, preset, wasm: rust?.services?.[service]?.wasm })
292
+ if (why) diagnostics.push({ code: 'R104', severity: 'error', why })
293
+ }
294
+ mkdirSync(join(root, '.kerf'), { recursive: true })
295
+ const path = join(root, '.kerf', 'contract.json')
296
+ writeFileSync(path, JSON.stringify(contract, null, 2) + '\n')
297
+ return { path, functions: contract.functions.length, diagnostics, contract, verified }
298
+ })
299
+ }
package/src/cron.ts ADDED
@@ -0,0 +1,74 @@
1
+ // `@kerf-js/start/cron`: jobs on a schedule. `src/cron.server.ts` default-exports `defineCron({ name: { schedule, run } })`;
2
+ // a server preset (node, bun, deno) runs each at its minute, in UTC, on one instance at a time.
3
+ import { StartError, type Context } from './data'
4
+
5
+ /** One scheduled job: a 5-field cron schedule in UTC (`'0 3 * * *'` is 03:00 every day) and what it runs. */
6
+ export interface CronJob {
7
+ schedule: string
8
+ /** Runs with the app's `ctx` (no request user). A failure is logged (J001); the next minute it's due runs again. */
9
+ run: (args: { ctx: Context; name: string; at: Date }) => unknown
10
+ }
11
+ /** What `src/cron.server.ts` default-exports: jobs by name. */
12
+ export type CronJobs = Record<string, CronJob>
13
+
14
+ /** The jobs, checked: a schedule that doesn't parse is J002 when the server starts, not a silent no-op. */
15
+ export function defineCron<J extends CronJobs>(jobs: J): J {
16
+ for (const [name, job] of Object.entries(jobs)) matcher(job.schedule, name)
17
+ return jobs
18
+ }
19
+
20
+ const FIELDS = [
21
+ { name: 'minute', min: 0, max: 59 },
22
+ { name: 'hour', min: 0, max: 23 },
23
+ { name: 'day of month', min: 1, max: 31 },
24
+ { name: 'month', min: 1, max: 12 },
25
+ { name: 'day of week', min: 0, max: 7 },
26
+ ] as const
27
+
28
+ function field(
29
+ text: string,
30
+ { name, min, max }: (typeof FIELDS)[number],
31
+ job: string,
32
+ ): Set<number> {
33
+ const out = new Set<number>()
34
+ for (const part of text.split(',')) {
35
+ const m = /^(\*|(\d+)(?:-(\d+))?)(?:\/(\d+))?$/.exec(part)
36
+ const lo = m?.[1] === '*' ? min : Number(m?.[2])
37
+ const hi = m?.[1] === '*' ? max : m?.[3] !== undefined ? Number(m[3]) : m?.[4] ? max : lo
38
+ const step = m?.[4] !== undefined ? Number(m[4]) : 1
39
+ if (!m || lo < min || hi > max || lo > hi || step < 1)
40
+ throw new StartError(
41
+ 'J002',
42
+ `cron job \`${job}\`: \`${part}\` isn't a ${name} (${min}–${max})`,
43
+ 'five fields: minute hour day-of-month month day-of-week, with `*`, `*/n`, `a-b` and lists',
44
+ )
45
+ for (let v = lo; v <= hi; v += step) out.add(name === 'day of week' && v === 7 ? 0 : v)
46
+ }
47
+ return out
48
+ }
49
+
50
+ /** A schedule as a test for one minute (UTC). Day of month and day of week, both set, match either (as cron does). */
51
+ export function matcher(schedule: string, job = 'job'): (at: Date) => boolean {
52
+ const parts = schedule.trim().split(/\s+/)
53
+ if (parts.length !== 5)
54
+ throw new StartError(
55
+ 'J002',
56
+ `cron job \`${job}\`: \`${schedule}\` has ${parts.length} fields, not 5`,
57
+ 'minute hour day-of-month month day-of-week, e.g. `0 3 * * *`',
58
+ )
59
+ const [mi, h, dom, mo, dow] = parts.map((p, i) => field(p, FIELDS[i]!, job))
60
+ const anyDom = parts[2] === '*',
61
+ anyDow = parts[4] === '*'
62
+ return (at) => {
63
+ const day =
64
+ anyDom || anyDow
65
+ ? dom!.has(at.getUTCDate()) && dow!.has(at.getUTCDay())
66
+ : dom!.has(at.getUTCDate()) || dow!.has(at.getUTCDay())
67
+ return (
68
+ mi!.has(at.getUTCMinutes()) &&
69
+ h!.has(at.getUTCHours()) &&
70
+ mo!.has(at.getUTCMonth() + 1) &&
71
+ day
72
+ )
73
+ }
74
+ }
@@ -0,0 +1,57 @@
1
+ // Two request-level helpers for publishing flows: `after` (work once the response is out) and `preview` (a visitor who
2
+ // sees a draft: their reads skip the shared cache, so nothing they see reaches anyone else).
3
+ import { server } from './foundation'
4
+ import { StartError } from './primitives'
5
+
6
+ const COOKIE = 'kerf-preview'
7
+
8
+ /**
9
+ * Run `fn` once this response is finished: after the page has streamed or the call has answered. The visitor never
10
+ * waits for it. A preview's rollback, a snapshot to write, a push to send. Outside a request it runs at once.
11
+ */
12
+ export function after(fn: () => unknown): void {
13
+ const scope = server()
14
+ if (!scope || scope.finished) {
15
+ queueMicrotask(() => void fn())
16
+ return
17
+ }
18
+ scope.after.push(fn)
19
+ }
20
+
21
+ const here = (what: string) => {
22
+ const scope = server()
23
+ if (!scope)
24
+ throw new StartError(
25
+ 'Q017',
26
+ `\`preview.${what}\` needs a request`,
27
+ 'call it in a server function or a `load`',
28
+ )
29
+ return scope
30
+ }
31
+
32
+ /**
33
+ * Preview mode, on a cookie. `start(value)` turns it on for this browser (the value is the app's: a draft's id), `stop()`
34
+ * turns it off, `id()` reads it. While it's on, every query runs fresh: no shared cache read or written. Deciding who may
35
+ * preview, and what the value shows, is the app's (its context reads `preview.id()` and checks the user).
36
+ */
37
+ export const preview = {
38
+ id(): string | undefined {
39
+ const scope = server()
40
+ const m = scope?.request.headers.get('cookie')?.match(/(?:^|;\s*)kerf-preview=([^;]+)/)
41
+ return m ? decodeURIComponent(m[1]!) : undefined
42
+ },
43
+ start(value: string) {
44
+ const scope = here('start')
45
+ const secure = scope.request.url.startsWith('https:') ? '; Secure' : ''
46
+ scope.headers.append(
47
+ 'set-cookie',
48
+ `${COOKIE}=${encodeURIComponent(value)}; Path=/; HttpOnly; SameSite=Lax${secure}`,
49
+ )
50
+ },
51
+ stop() {
52
+ here('stop').headers.append(
53
+ 'set-cookie',
54
+ `${COOKIE}=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0`,
55
+ )
56
+ },
57
+ }