@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
package/src/shape.mjs ADDED
@@ -0,0 +1,97 @@
1
+ // A query's result shape from its `output` schema (research 31 §3). The client never gets the schema: the plugin puts
2
+ // this tree in the query's stub, and the server computes the same one, so a streamed fallback hydrates cleanly.
3
+ // @kerf-js/core/shape's `fill` turns a tree into a placeholder value.
4
+
5
+ /** A Standard Schema as JSON Schema (draft 2020-12), or undefined when it has no converter or can't be represented. */
6
+ export function toJson(schema, side) {
7
+ const std = schema?.['~standard']
8
+ try {
9
+ if (std?.jsonSchema) return std.jsonSchema[side]({ target: 'draft-2020-12' })
10
+ if (typeof schema?.toJSONSchema === 'function') return schema.toJSONSchema()
11
+ } catch {}
12
+ }
13
+
14
+ /** Typical lengths by field name, for strings with no hint (research 11 §7.1). */
15
+ const NAMES = {
16
+ title: 40,
17
+ name: 16,
18
+ label: 16,
19
+ email: 22,
20
+ body: 200,
21
+ content: 200,
22
+ text: 120,
23
+ description: 120,
24
+ summary: 120,
25
+ slug: 24,
26
+ url: 40,
27
+ id: 8,
28
+ }
29
+ const FORMATS = { email: 22, uuid: 36, url: 40, uri: 40, 'date-time': 24, date: 10, time: 8 }
30
+ /** A string with no hint: X036 if a skeleton shows one. */
31
+ const UNHINTED = 16
32
+
33
+ function string(s, name) {
34
+ if (s.minLength !== undefined && s.minLength === s.maxLength) return { $s: s.minLength }
35
+ if (s.maxLength !== undefined) return { $s: Math.round(((s.minLength ?? 0) + s.maxLength) / 2) }
36
+ const known = FORMATS[s.format] ?? NAMES[name]
37
+ if (known !== undefined) return { $s: known }
38
+ if (s.minLength !== undefined) return { $s: s.minLength }
39
+ return { $u: UNHINTED }
40
+ }
41
+
42
+ /** JSON Schema → shape tree. `name` is the field it's under. */
43
+ export function schemaTree(s, name = '') {
44
+ if (!s || typeof s !== 'object') return null
45
+ const example = s.example ?? s.examples?.[0]
46
+ if (example !== undefined) return example
47
+ if (s.const !== undefined) return s.const
48
+ if (s.enum) return s.enum[0]
49
+ const union = s.anyOf ?? s.oneOf
50
+ if (union) {
51
+ const some = union.filter((x) => x.type !== 'null')
52
+ return some.length < union.length && !(s.probability >= 0.5) ? null : schemaTree(some[0], name)
53
+ }
54
+ switch (s.type) {
55
+ case 'string':
56
+ return string(s, name)
57
+ case 'number':
58
+ case 'integer':
59
+ return s.minimum ?? 0
60
+ case 'boolean':
61
+ return false
62
+ case 'array':
63
+ return {
64
+ ...(s.maxItems !== undefined ? { $a: s.maxItems } : {}),
65
+ $of: schemaTree(s.items, name),
66
+ }
67
+ case 'object': {
68
+ const out = {}
69
+ for (const [k, v] of Object.entries(s.properties ?? {}))
70
+ if (s.required?.includes(k) || v.probability >= 0.5) out[k] = schemaTree(v, k)
71
+ return out
72
+ }
73
+ }
74
+ return null
75
+ }
76
+
77
+ /** `example` (a declared `shape`) over `tree`. */
78
+ function merge(tree, example) {
79
+ if (example === undefined) return tree
80
+ if (Array.isArray(example))
81
+ return example.length > 1 || !tree?.$of
82
+ ? example
83
+ : { ...tree, $of: merge(tree.$of, example[0]) }
84
+ if (example && typeof example === 'object')
85
+ return Object.fromEntries([
86
+ ...Object.entries(tree ?? {}),
87
+ ...Object.entries(example).map(([k, v]) => [k, merge(tree?.[k], v)]),
88
+ ])
89
+ return example
90
+ }
91
+
92
+ /** A definition's tree: its `output`, with its declared `shape` over it. Undefined when it declares neither. */
93
+ export function shapeTree(def) {
94
+ const json = def.output && toJson(def.output, 'output')
95
+ if (!json) return def.shape
96
+ return merge(schemaTree(json), def.shape)
97
+ }
@@ -0,0 +1,50 @@
1
+ import { NONE } from '@kerf-js/core/interaction'
2
+ import { tab } from '../link'
3
+ import { clients, lines, shown, siblings, tabs, type Client, type Triple } from './state'
4
+
5
+ export function render(key: string) {
6
+ const heard = lines.get(key)
7
+ if (!heard) return
8
+ let hover = 0,
9
+ focus = 0,
10
+ pressed = 0
11
+ const add = (bits: number) => {
12
+ if (bits & 1) hover++
13
+ if (bits & 2) focus++
14
+ if (bits & 4) pressed++
15
+ }
16
+ for (const [t, keys] of tabs) if (t !== tab) add(keys.get(key) ?? 0)
17
+ for (const e of clients.get(key)?.values() ?? []) add(e.bits)
18
+ const was = shown.get(key) ?? NONE
19
+ if (was.hover === hover && was.focus === focus && was.pressed === pressed) return
20
+ const now = hover || focus || pressed ? { hover, focus, pressed } : NONE
21
+ shown.set(key, now)
22
+ heard(now)
23
+ }
24
+ export const renderAll = () => {
25
+ for (const k of lines.keys()) render(k)
26
+ }
27
+
28
+ export function hear(s: Triple[], leading: boolean) {
29
+ const at = Date.now(),
30
+ touched = new Set<string>()
31
+ for (const [id, key, bits] of s) {
32
+ if (siblings.has(id) || (!leading && !lines.has(key))) continue
33
+ let held = clients.get(key)
34
+ if (bits) {
35
+ if (!held) clients.set(key, (held = new Map()))
36
+ held.set(id, { bits, at })
37
+ } else if (!held?.delete(id)) continue
38
+ touched.add(key)
39
+ }
40
+ for (const k of touched) render(k)
41
+ }
42
+
43
+ export function dropClients(which: (e: Client, id: string) => boolean) {
44
+ for (const [key, held] of clients) {
45
+ let changed = false
46
+ for (const [id, e] of held) if (which(e, id)) changed = held.delete(id)
47
+ if (!held.size) clients.delete(key)
48
+ if (changed) render(key)
49
+ }
50
+ }
@@ -0,0 +1,119 @@
1
+ import type { connectBuiltIn } from '../channel'
2
+ import type { shareStats as ShareStats } from '../share'
3
+ import { mine, tabs, type Pair } from './state'
4
+
5
+ type Conn = ReturnType<typeof connectBuiltIn>
6
+
7
+ function changedPairs(o: {
8
+ dirtyNet: Set<string>
9
+ sent: Map<string, number>
10
+ refused: Set<string>
11
+ upstream: (key: string) => number
12
+ BATCH: number
13
+ }) {
14
+ const { dirtyNet, sent, refused, upstream, BATCH } = o
15
+ const e: Pair[] = []
16
+ for (const key of dirtyNet) {
17
+ if (e.length === BATCH) break
18
+ dirtyNet.delete(key)
19
+ if (!sent.has(key) || refused.has(key)) continue
20
+ const bits = upstream(key)
21
+ // Off and on again inside the gap: nothing to say. The latest value is all that's kept.
22
+ if (bits !== sent.get(key)) {
23
+ sent.set(key, bits)
24
+ e.push([key, bits])
25
+ }
26
+ }
27
+ return e
28
+ }
29
+
30
+ export function network({
31
+ connection,
32
+ isOpen,
33
+ sent,
34
+ refused,
35
+ dirtyNet,
36
+ toAdd,
37
+ toDrop,
38
+ upstream,
39
+ shareStats,
40
+ GAP_NET,
41
+ BATCH,
42
+ }: {
43
+ connection: () => Conn | undefined
44
+ isOpen: () => boolean
45
+ sent: Map<string, number>
46
+ refused: Set<string>
47
+ dirtyNet: Set<string>
48
+ toAdd: Set<string>
49
+ toDrop: Set<string>
50
+ upstream: (key: string) => number
51
+ shareStats: typeof ShareStats
52
+ GAP_NET: number
53
+ BATCH: number
54
+ }) {
55
+ let netLast = 0
56
+ let netTimer: ReturnType<typeof setTimeout> | undefined
57
+ /** One frame per GAP_NET, `u` first: the bucket is 20 a second, and a frame carries every key that's waiting. */
58
+ function netTick() {
59
+ netTimer = undefined
60
+ const conn = connection()
61
+ if (!conn || !isOpen()) return
62
+ let name: 'u' | 'set' | undefined,
63
+ msg: unknown,
64
+ size = 0
65
+ if (toAdd.size || toDrop.size) {
66
+ const add = [...toAdd].slice(0, BATCH),
67
+ drop = [...toDrop].slice(0, BATCH - add.length)
68
+ for (const k of add) toAdd.delete(k)
69
+ for (const k of drop) toDrop.delete(k)
70
+ name = 'u'
71
+ msg = { add, drop }
72
+ size = add.length + drop.length
73
+ } else {
74
+ const e = changedPairs({ dirtyNet, sent, refused, upstream, BATCH })
75
+ if (e.length) {
76
+ name = 'set'
77
+ msg = { e }
78
+ size = e.length
79
+ }
80
+ }
81
+ if (name) {
82
+ netLast = performance.now()
83
+ shareStats.frames++
84
+ shareStats.keysSent += size
85
+ conn.send(name as never, msg as never).catch(() => {}) // a dropped link re-says everything
86
+ }
87
+ if (toAdd.size || toDrop.size || dirtyNet.size) netSoon()
88
+ }
89
+ /** Not a timer when the gap has passed: the leader is often a hidden tab, where a timer waits a second or more. */
90
+ function netSoon() {
91
+ const wait = GAP_NET - (performance.now() - netLast)
92
+ if (wait > 0) {
93
+ netTimer ??= setTimeout(netTick, wait)
94
+ return
95
+ }
96
+ clearTimeout(netTimer)
97
+ netTick()
98
+ }
99
+
100
+ const clear = () => {
101
+ clearTimeout(netTimer)
102
+ netTimer = undefined
103
+ }
104
+ return { netSoon, clear }
105
+ }
106
+
107
+ export const upstream = (key: string, locks: boolean) => {
108
+ if (!locks) return mine.get(key) ?? 0
109
+ let bits = 0
110
+ for (const keys of tabs.values()) bits |= keys.get(key) ?? 0
111
+ return bits
112
+ }
113
+
114
+ export function wanted(locks: boolean) {
115
+ if (!locks) return new Set(mine.keys())
116
+ const out = new Set<string>()
117
+ for (const keys of tabs.values()) for (const k of keys.keys()) out.add(k)
118
+ return out
119
+ }
@@ -0,0 +1,70 @@
1
+ import {
2
+ clients,
3
+ siblings,
4
+ tabAt,
5
+ tabs,
6
+ visible,
7
+ type Client,
8
+ type Msg,
9
+ type Triple,
10
+ } from './state'
11
+ import { hear, render, renderAll } from './display'
12
+
13
+ export function receiver({
14
+ dropClients,
15
+ watch,
16
+ reconcile,
17
+ wakeIfLeading,
18
+ leading,
19
+ post,
20
+ announce,
21
+ dropTab,
22
+ link,
23
+ }: {
24
+ dropClients: (test: (e: Client, id: string) => boolean) => void
25
+ watch: (tab: string) => void
26
+ reconcile: () => void
27
+ wakeIfLeading: () => void
28
+ leading: () => boolean
29
+ post: (msg: Msg) => void
30
+ announce: () => void
31
+ dropTab: (tab: string) => void
32
+ link: (up: boolean) => void
33
+ }) {
34
+ return (m: Msg) => {
35
+ if (m.t === 'tab') {
36
+ tabs.set(m.tab, new Map(m.keys))
37
+ tabAt.set(m.tab, Date.now())
38
+ visible.set(m.tab, m.shown)
39
+ if (m.k && !siblings.has(m.k)) {
40
+ siblings.add(m.k)
41
+ dropClients((_, id) => id === m.k)
42
+ }
43
+ watch(m.tab)
44
+ renderAll()
45
+ reconcile()
46
+ if (m.shown) wakeIfLeading()
47
+ // A tab that arrived late has what the socket already heard.
48
+ if (leading()) {
49
+ const s: Triple[] = []
50
+ for (const [key] of m.keys)
51
+ for (const [id, e] of clients.get(key) ?? []) s.push([id, key, e.bits])
52
+ if (s.length) post({ t: 'net', s })
53
+ }
54
+ } else if (m.t === 'bits') {
55
+ const keys = tabs.get(m.tab) ?? new Map<string, number>()
56
+ tabs.set(m.tab, keys)
57
+ tabAt.set(m.tab, Date.now())
58
+ for (const [key, bits] of m.e) keys.set(key, bits)
59
+ watch(m.tab)
60
+ for (const [key] of m.e) render(key)
61
+ reconcile()
62
+ } else if (m.t === 'shown') {
63
+ visible.set(m.tab, m.shown)
64
+ if (m.shown) wakeIfLeading()
65
+ } else if (m.t === 'roll') announce()
66
+ else if (m.t === 'bye') dropTab(m.tab)
67
+ else if (m.t === 'net') hear(m.s, leading())
68
+ else if (m.t === 'link') link(m.up)
69
+ }
70
+ }
@@ -0,0 +1,30 @@
1
+ import type { Counts } from '@kerf-js/core/interaction'
2
+
3
+ export type Pair = [key: string, bits: number]
4
+ export type Triple = [id: string, key: string, bits: number]
5
+ export type Msg =
6
+ | { t: 'tab'; tab: string; keys: Pair[]; shown: boolean; k?: string | undefined }
7
+ | { t: 'bits'; tab: string; e: Pair[] }
8
+ | { t: 'shown'; tab: string; shown: boolean }
9
+ | { t: 'net'; s: Triple[] }
10
+ | { t: 'link'; up: boolean }
11
+ | { t: 'roll' }
12
+ | { t: 'bye'; tab: string }
13
+
14
+ export interface Client {
15
+ bits: number
16
+ at: number
17
+ stale?: boolean
18
+ }
19
+
20
+ export const lines = new Map<string, (c: Counts) => void>()
21
+ export const shown = new Map<string, Counts>()
22
+ /** key → bits, per tab, mine included. */
23
+ export const tabs = new Map<string, Map<string, number>>()
24
+ export const tabAt = new Map<string, number>()
25
+ export const visible = new Map<string, boolean>()
26
+ export const mine = new Map<string, number>()
27
+ export const watched = new Set<string>()
28
+ export const siblings = new Set<string>()
29
+ /** key → other clients. Everything the leader joined; a follower keeps what its own lines want. */
30
+ export const clients = new Map<string, Map<string, Client>>()
@@ -0,0 +1,28 @@
1
+ import type { Msg } from './state'
2
+
3
+ export function tabQueue(
4
+ dirtyTab: Set<string>,
5
+ mine: Map<string, number>,
6
+ post: (msg: Msg) => void,
7
+ tab: string,
8
+ GAP_TAB: number,
9
+ ) {
10
+ let tabLast = 0
11
+ let tabTimer: ReturnType<typeof setTimeout> | undefined
12
+ function flushTab() {
13
+ tabTimer = undefined
14
+ tabLast = performance.now()
15
+ if (dirtyTab.size)
16
+ post({ t: 'bits', tab, e: [...dirtyTab].map((key) => [key, mine.get(key) ?? 0]) })
17
+ dirtyTab.clear()
18
+ }
19
+ function queueTab(key: string) {
20
+ dirtyTab.add(key)
21
+ if (tabTimer !== undefined) return
22
+ const wait = GAP_TAB - (performance.now() - tabLast)
23
+ if (wait <= 0) flushTab()
24
+ else tabTimer = setTimeout(flushTab, wait)
25
+ }
26
+
27
+ return queueTab
28
+ }
@@ -0,0 +1,293 @@
1
+ // The server's half of `interaction({ share })` (research 45 §6, §7). One join per socket, `$share`, and every key goes
2
+ // through `realtime({ share })`: no such option, no join (R011), and a key it refuses gets nothing and can say nothing.
3
+ //
4
+ // rooms 64 hub channels, by a hash of the key, so bus subscriptions stay bounded. One listener per instance: an
5
+ // event costs the keys it names and who holds them, not every socket. A client still receives only its keys.
6
+ // batching one `u` frame adds and drops many keys and one `set` frame carries many bits; each comes back as one frame.
7
+ // snapshot each instance answers for its own sockets, from what those sockets last said, so a joiner costs its
8
+ // holders nothing on the wire. What's held lives and dies with the connection: nothing outlives a socket.
9
+ // rule per key, or `{ keys }` for a whole frame in one call, so a join of up to 400 keys is one database read.
10
+ // leaving `left` says zero for what the socket held. Every event is volatile: no ring, no replay.
11
+ // identity the sender's connection id is stamped here. Bits and an opaque id, nothing else exists to see.
12
+
13
+ import type { Context, Fn, StandardSchemaV1 } from './data'
14
+ import { StartError } from './data'
15
+ import type { Ev, Hub } from './hub'
16
+
17
+ export const SHARE = '$share'
18
+ export const MAX_KEY = 128
19
+ /** Entries one frame may carry. The client chunks to this. */
20
+ export const MAX_BATCH = 400
21
+ const SHARDS = 64
22
+
23
+ /** One key at a time, or `{ keys }` to answer a whole join at once: a rule that reads a database runs once for it. */
24
+ export type ShareRule =
25
+ | ((args: { ctx: Context; key: string }) => boolean | Promise<boolean>)
26
+ | {
27
+ keys: (args: { ctx: Context; keys: string[] }) => Iterable<string> | Promise<Iterable<string>>
28
+ }
29
+
30
+ type Issue = { issues: { message: string }[] }
31
+ type Sent = { add?: unknown; drop?: unknown; e?: unknown } | null | undefined
32
+ const isIssue = (r: unknown): r is Issue => !!(r as Partial<Issue> | null | undefined)?.issues
33
+ const schema = <T>(validate: (v: Sent) => T | Issue): StandardSchemaV1<T, T> => ({
34
+ '~standard': {
35
+ version: 1,
36
+ vendor: 'kerf',
37
+ validate: (v: unknown) => {
38
+ const r = validate(v as Sent)
39
+ return isIssue(r) ? r : { value: r }
40
+ },
41
+ },
42
+ })
43
+
44
+ /** What a handler of the share channel is given. */
45
+ interface Said<M = unknown> {
46
+ msg: M
47
+ id: string
48
+ ctx: Context
49
+ reply: Client['reply']
50
+ }
51
+ const no = (message: string): Issue => ({ issues: [{ message }] })
52
+ const isKey = (k: unknown): k is string =>
53
+ typeof k === 'string' && k.length > 0 && k.length <= MAX_KEY
54
+ const isBits = (b: unknown) => Number.isInteger(b) && (b as number) >= 0 && (b as number) <= 7
55
+ const anything = schema((v) => v)
56
+
57
+ /** Who has `k` in `s`: `[id, key, bits]`. */
58
+ type Triple = [id: string, key: string, bits: number]
59
+ interface Client {
60
+ id: string
61
+ keys: Map<string, number>
62
+ reply(name: string, msg: unknown): void
63
+ }
64
+ interface Shard {
65
+ name: string
66
+ refs: number
67
+ ch: ReturnType<Hub['channel']>
68
+ on: (ev: Ev | null) => void
69
+ }
70
+ interface Sharing {
71
+ clients: Map<string, Client>
72
+ holders: Map<string, Set<Client>>
73
+ shards: Map<number, Shard>
74
+ }
75
+
76
+ const states = new WeakMap<Hub, Sharing>()
77
+ const stateOf = (h: Hub) => {
78
+ let s = states.get(h)
79
+ if (!s) states.set(h, (s = { clients: new Map(), holders: new Map(), shards: new Map() }))
80
+ return s
81
+ }
82
+
83
+ /** FNV-1a. It only has to spread keys, and to agree across instances. */
84
+ function shardOf(key: string) {
85
+ let x = 2166136261
86
+ for (let i = 0; i < key.length; i++) x = Math.imul(x ^ key.charCodeAt(i), 16777619)
87
+ return (x >>> 0) % SHARDS
88
+ }
89
+
90
+ const byShard = <T>(items: T[], key: (item: T) => string) => {
91
+ const out = new Map<number, T[]>()
92
+ for (const item of items) {
93
+ const s = shardOf(key(item))
94
+ const list = out.get(s)
95
+ if (list) list.push(item)
96
+ else out.set(s, [item])
97
+ }
98
+ return out
99
+ }
100
+
101
+ const publish = (h: Hub, shard: number, body: object) =>
102
+ h.bus.publish(`kerf:s:${shard}`, `{"v":1,${JSON.stringify(body).slice(1)}`)
103
+
104
+ function heard(h: Hub, st: Sharing, shard: number, ev: Ev | null) {
105
+ if (!ev) return // the bus lost something: bits are re-said on a beat, and peers age out
106
+ const m = (ev.p ??= JSON.parse(ev.raw)) as {
107
+ f?: string
108
+ e?: [string, number][]
109
+ a?: string
110
+ k?: string[]
111
+ t?: string
112
+ s?: Triple[]
113
+ }
114
+ if (m.t) return m.s && st.clients.get(m.t)?.reply('b', { s: m.s })
115
+ if (m.a) {
116
+ const s: Triple[] = []
117
+ for (const key of m.k ?? [])
118
+ for (const c of st.holders.get(key) ?? []) {
119
+ const bits = c.keys.get(key)
120
+ if (bits && c.id !== m.a) s.push([c.id, key, bits])
121
+ }
122
+ if (s.length) void publish(h, shard, { t: m.a, s })
123
+ return
124
+ }
125
+ // One frame per client per event, whatever it names.
126
+ const each = new Map<Client, Triple[]>()
127
+ for (const [key, bits] of m.e ?? [])
128
+ for (const c of st.holders.get(key) ?? []) {
129
+ if (c.id === m.f) continue
130
+ const list = each.get(c)
131
+ if (list) list.push([m.f!, key, bits])
132
+ else each.set(c, [[m.f!, key, bits]])
133
+ }
134
+ for (const [c, s] of each) c.reply('b', { s })
135
+ }
136
+
137
+ function hold(h: Hub, st: Sharing, c: Client, key: string) {
138
+ if (c.keys.has(key)) return false
139
+ c.keys.set(key, 0)
140
+ let set = st.holders.get(key)
141
+ if (!set) st.holders.set(key, (set = new Set()))
142
+ set.add(c)
143
+ const n = shardOf(key)
144
+ let shard = st.shards.get(n)
145
+ if (!shard) {
146
+ const name = `kerf:s:${n}`,
147
+ ch = h.channel(name),
148
+ on = (ev: Ev | null) => heard(h, st, n, ev)
149
+ ch.listeners.add(on)
150
+ st.shards.set(n, (shard = { name, refs: 0, ch, on }))
151
+ }
152
+ shard.refs++
153
+ return true
154
+ }
155
+
156
+ function unhold(h: Hub, st: Sharing, c: Client, key: string) {
157
+ if (!c.keys.delete(key)) return
158
+ const set = st.holders.get(key)!
159
+ set.delete(c)
160
+ if (!set.size) st.holders.delete(key)
161
+ const n = shardOf(key),
162
+ shard = st.shards.get(n)!
163
+ if (--shard.refs) return
164
+ st.shards.delete(n)
165
+ h.unlisten(shard.ch, shard.on)
166
+ }
167
+
168
+ /** Say zero for what these keys held, then let go of them. */
169
+ function release(h: Hub, st: Sharing, c: Client, keys: string[]) {
170
+ const held = keys.filter((k) => c.keys.get(k))
171
+ for (const k of keys) unhold(h, st, c, k)
172
+ return Promise.all(
173
+ [...byShard(held, (k) => k)].map(([n, list]) =>
174
+ publish(h, n, { f: c.id, e: list.map((k) => [k, 0]) }),
175
+ ),
176
+ )
177
+ }
178
+
179
+ async function allowedKeys(rule: ShareRule, ctx: Context, keys: string[]) {
180
+ if (!keys.length) return keys
181
+ if (typeof rule !== 'function') {
182
+ const yes = await Promise.resolve()
183
+ .then(() => rule.keys({ ctx, keys }))
184
+ .catch(() => [])
185
+ const passed = new Set(yes)
186
+ return keys.filter((k) => passed.has(k))
187
+ }
188
+ const answers = await Promise.all(
189
+ keys.map((key) =>
190
+ Promise.resolve()
191
+ .then(() => rule({ ctx, key }))
192
+ .catch(() => false),
193
+ ),
194
+ )
195
+ return keys.filter((_, i) => answers[i])
196
+ }
197
+
198
+ function clientMessages() {
199
+ return {
200
+ u: schema<{ add: string[]; drop: string[] }>((v) => {
201
+ const add = v?.add ?? [],
202
+ drop = v?.drop ?? []
203
+ return Array.isArray(add) &&
204
+ Array.isArray(drop) &&
205
+ add.length + drop.length <= MAX_BATCH &&
206
+ add.every(isKey) &&
207
+ drop.every(isKey)
208
+ ? { add, drop }
209
+ : no(`\`u\` takes up to ${MAX_BATCH} keys of 1 to ${MAX_KEY} characters`)
210
+ }),
211
+ set: schema<{ e: [string, number][] }>((v) =>
212
+ Array.isArray(v?.e) &&
213
+ v.e.length <= MAX_BATCH &&
214
+ v.e.every((x) => Array.isArray(x) && isKey(x[0]) && isBits(x[1]))
215
+ ? { e: v.e }
216
+ : no('`set` takes `[key, bits]` pairs, bits 0 to 7'),
217
+ ),
218
+ }
219
+ }
220
+
221
+ /** The `channel` behind `share`, made per hub. socket.ts takes it for `$share`, so every limit a channel has applies. */
222
+ export function shareChannel(h: Hub): Fn {
223
+ const rule = h.share
224
+ const st = stateOf(h)
225
+ const client = (id: string, reply: Client['reply']) => {
226
+ let c = st.clients.get(id)
227
+ if (!c) st.clients.set(id, (c = { id, keys: new Map(), reply }))
228
+ return c
229
+ }
230
+ return {
231
+ kind: 'channel',
232
+ $id: SHARE,
233
+ def: {
234
+ authorize() {
235
+ if (rule) return true
236
+ throw new StartError(
237
+ 'R011',
238
+ '`interaction({ share })` crossed to the socket, and nothing allows it',
239
+ 'add `share: ({ ctx, key }) => …` to `realtime()`; `() => true` must be written out',
240
+ )
241
+ },
242
+ client: clientMessages(),
243
+ server: { ok: anything, b: anything },
244
+ on: {
245
+ async u({ msg, id, ctx, reply }: Said<{ add: string[]; drop: string[] }>) {
246
+ const c = client(id, reply)
247
+ await release(h, st, c, msg.drop)
248
+ const room = Math.max(0, h.limits.shareKeys - c.keys.size)
249
+ const fresh = msg.add.filter((k) => !c.keys.has(k))
250
+ const asked = fresh.slice(0, room)
251
+ const ok = await allowedKeys(rule!, ctx, asked)
252
+ if (!st.clients.has(id)) return // it left while the rule ran
253
+ const passed = new Set(ok)
254
+ for (const k of ok) hold(h, st, c, k)
255
+ await Promise.all(
256
+ ok.length
257
+ ? [...byShard<string>(ok, (k) => k)].map(([n, k]) =>
258
+ st.shards.get(n)!.ch.ready.then(() => publish(h, n, { a: id, k })),
259
+ )
260
+ : [],
261
+ )
262
+ reply('ok', { id, no: fresh.filter((k) => !passed.has(k)) })
263
+ },
264
+ set({ msg, id }: Said<{ e: [string, number][] }>) {
265
+ const c = st.clients.get(id)
266
+ if (!c) return
267
+ const known = msg.e.filter(([k]) => c.keys.has(k))
268
+ for (const [k, bits] of known) c.keys.set(k, bits)
269
+ return Promise.all(
270
+ [...byShard(known, (e) => e[0])].map(([n, e]) => publish(h, n, { f: id, e })),
271
+ )
272
+ },
273
+ },
274
+ left({ id }: Pick<Said, 'id'>) {
275
+ const c = st.clients.get(id)
276
+ if (!c) return
277
+ st.clients.delete(id)
278
+ return release(h, st, c, [...c.keys.keys()])
279
+ },
280
+ /** The session again: every key this socket holds goes back through the rule. */
281
+ async recheck({ id, ctx, reply }: Said) {
282
+ const c = st.clients.get(id)
283
+ if (!c || !rule) return
284
+ const keys = [...c.keys.keys()]
285
+ const passed = new Set(await allowedKeys(rule, ctx, keys))
286
+ const gone = keys.filter((k) => !passed.has(k))
287
+ if (!gone.length) return
288
+ await release(h, st, c, gone)
289
+ reply('ok', { id, no: gone })
290
+ },
291
+ },
292
+ } as unknown as Fn
293
+ }