@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/jobs.ts ADDED
@@ -0,0 +1,223 @@
1
+ // `@kerf-js/start/jobs`: work done after the request that asked for it. `src/jobs.server.ts` default-exports
2
+ // `defineJobs({ name: { input?, run } })`; a mutation calls `jobs.name.enqueue(input)`, and a server preset (node, bun,
3
+ // deno) works the queue: each job runs at least once, is retried with backoff when it throws, and is set aside (J004)
4
+ // when its retries run out.
5
+ import { StartError, type Context, type StandardSchemaV1 } from './data'
6
+
7
+ /** One job as the queue holds it. `attempt` counts the runs started, this one included. */
8
+ export interface QueuedJob {
9
+ id: string
10
+ name: string
11
+ input: unknown
12
+ attempt: number
13
+ /** When it may run next, in ms since the epoch. */
14
+ runAt: number
15
+ }
16
+
17
+ /**
18
+ * Where queued jobs wait: `memoryQueue()` by default (one process, lost on restart), `redisQueue()` from
19
+ * `@kerf-js/realtime-redis` to survive restarts and share the work between instances.
20
+ */
21
+ export interface Queue {
22
+ /** Adds a job. With `key`, false (and nothing added) while a job with that key is still waiting or running. */
23
+ push(job: QueuedJob, key?: string): Promise<boolean>
24
+ /**
25
+ * Up to `max` jobs due at `now`, each counted as one more attempt and hidden until `now + lease` ms: a process that
26
+ * dies mid-job hands it on when the lease ends, so a job runs at least once (and, rarely, more than once).
27
+ */
28
+ claim(now: number, lease: number, max: number): Promise<QueuedJob[]>
29
+ /** It ran: gone, and its key free again. */
30
+ done(job: QueuedJob): Promise<void>
31
+ /** It threw: due again at `runAt`. */
32
+ retry(job: QueuedJob, runAt: number): Promise<void>
33
+ /** Out of retries: off the queue, kept with its error where the queue keeps dead jobs. */
34
+ fail(job: QueuedJob, error: string): Promise<void>
35
+ /** Wakes the runner when a job is added (a queue in this process can say so; a shared one is polled). */
36
+ onPush?(wake: () => void): void
37
+ }
38
+
39
+ /** What a job's `run` gets. */
40
+ export interface JobRun<I> {
41
+ ctx: Context
42
+ input: I
43
+ id: string
44
+ name: string
45
+ attempt: number
46
+ }
47
+
48
+ /** One kind of job: what input it takes, what it does, and how often it's tried. */
49
+ export interface JobDef<I = unknown> {
50
+ /** Checked when it's enqueued (J006), so a bad input fails the caller, not a run later. */
51
+ input?: StandardSchemaV1
52
+ // A method, so a job taking any input fits `JobDefs`.
53
+ run(args: JobRun<I>): unknown
54
+ /** Runs after the first that fail before it's dead. Default 5. */
55
+ retries?: number
56
+ /** Milliseconds to wait after a failed attempt. Default 2^attempt seconds, at most an hour. */
57
+ backoff?: (attempt: number) => number
58
+ }
59
+ /** Jobs by name. */
60
+ export type JobDefs = Record<string, JobDef>
61
+
62
+ /** How a job is enqueued. */
63
+ export interface EnqueueOptions {
64
+ /** Milliseconds before it may run. */
65
+ delay?: number
66
+ /** One job per key until it has run: a second `enqueue` with the same key adds nothing and returns `null`. */
67
+ key?: string
68
+ }
69
+
70
+ type InputOf<D> = D extends { input: StandardSchemaV1<infer I, unknown> }
71
+ ? I
72
+ : D extends { run: (args: JobRun<infer I>) => unknown }
73
+ ? I
74
+ : unknown
75
+
76
+ /** How the runner works the queue. */
77
+ export interface RunnerOptions {
78
+ /** Jobs at once in this process. Default 4. */
79
+ concurrency?: number
80
+ /** How long a claimed job is hidden from other instances, in ms. Default 5 minutes: longer than any job runs. */
81
+ lease?: number
82
+ /** How often a shared queue is checked, in ms. Default 1000. */
83
+ poll?: number
84
+ }
85
+
86
+ const STATE = Symbol.for('kerf.jobs')
87
+ /** What the runner reads off `defineJobs`'s result. */
88
+ export interface JobsState {
89
+ defs: JobDefs
90
+ queue: Queue
91
+ runner: RunnerOptions
92
+ }
93
+ /** What `defineJobs` returns: an `enqueue` per job. `src/jobs.server.ts` default-exports it. */
94
+ export type Jobs<D extends JobDefs = JobDefs> = {
95
+ [K in keyof D]: {
96
+ /** Queues one run; the job's id, or `null` when `key` matched a job still waiting. */
97
+ enqueue(
98
+ ...args: undefined extends InputOf<D[K]>
99
+ ? [input?: InputOf<D[K]>, options?: EnqueueOptions]
100
+ : [input: InputOf<D[K]>, options?: EnqueueOptions]
101
+ ): Promise<string | null>
102
+ }
103
+ } & { readonly [STATE]: JobsState }
104
+
105
+ /** One job, typed: `run` gets what `input`'s schema outputs. */
106
+ export function job<S extends StandardSchemaV1>(
107
+ def: Omit<JobDef, 'input' | 'run'> & {
108
+ input: S
109
+ run: (args: JobRun<NonNullable<S['~standard']['types']>['output']>) => unknown
110
+ },
111
+ ): JobDef & { input: S }
112
+ export function job<I = undefined>(def: JobDef<I>): JobDef<I>
113
+ export function job(def: JobDef): JobDef {
114
+ return def
115
+ }
116
+
117
+ /** The app's jobs, on `queue` (memory by default). */
118
+ export function defineJobs<const D extends JobDefs>(
119
+ defs: D,
120
+ options: RunnerOptions & { queue?: Queue } = {},
121
+ ): Jobs<D> {
122
+ const { queue = memoryQueue(), ...runner } = options
123
+ const out: Record<string, unknown> = {}
124
+ for (const [name, def] of Object.entries(defs))
125
+ out[name] = {
126
+ async enqueue(input?: unknown, opts: EnqueueOptions = {}) {
127
+ let value = input
128
+ if (def.input) {
129
+ const r = await def.input['~standard'].validate(input)
130
+ if (r.issues)
131
+ throw new StartError(
132
+ 'J006',
133
+ `job \`${name}\` rejected its input: ${r.issues.map((i) => i.message).join('; ')}`,
134
+ 'enqueue what its schema accepts',
135
+ { status: 400 },
136
+ )
137
+ value = r.value
138
+ }
139
+ const id = crypto.randomUUID()
140
+ const added = await queue.push(
141
+ { id, name, input: value, attempt: 0, runAt: Date.now() + (opts.delay ?? 0) },
142
+ opts.key,
143
+ )
144
+ return added ? id : null
145
+ },
146
+ }
147
+ Object.defineProperty(out, STATE, { value: { defs, queue, runner } satisfies JobsState })
148
+ return out as Jobs<D>
149
+ }
150
+
151
+ /** The definitions and queue behind `defineJobs`'s result. */
152
+ export function jobsState(jobs: object): JobsState | undefined {
153
+ return (jobs as { [STATE]?: JobsState })[STATE]
154
+ }
155
+
156
+ /** The default wait after attempt `n` fails: 2^n seconds, at most an hour. */
157
+ export const backoff = (attempt: number) => Math.min(3600, 2 ** attempt) * 1000
158
+
159
+ /** A dead job, as `memoryQueue().dead` keeps it. */
160
+ export interface DeadJob extends QueuedJob {
161
+ error: string
162
+ at: number
163
+ }
164
+
165
+ /**
166
+ * The queue in this process: nothing to set up, and nothing survives a restart or reaches another instance. Use
167
+ * `redisQueue()` for jobs that must not be lost. Keeps the last `deadLimit` dead jobs in `dead`.
168
+ */
169
+ export function memoryQueue({ deadLimit = 100 }: { deadLimit?: number } = {}): Queue & {
170
+ dead: DeadJob[]
171
+ size(): number
172
+ } {
173
+ const held = new Map<string, QueuedJob & { key?: string }>()
174
+ const keys = new Map<string, string>()
175
+ const dead: DeadJob[] = []
176
+ const wakes: (() => void)[] = []
177
+ const drop = (queued: QueuedJob) => {
178
+ const key = held.get(queued.id)?.key
179
+ if (key !== undefined) keys.delete(key)
180
+ held.delete(queued.id)
181
+ }
182
+ const done = Promise.resolve()
183
+ return {
184
+ dead,
185
+ size: () => held.size,
186
+ push(queued, key) {
187
+ if (key !== undefined && keys.has(key)) return Promise.resolve(false)
188
+ if (key !== undefined) keys.set(key, queued.id)
189
+ held.set(queued.id, { ...queued, ...(key !== undefined && { key }) })
190
+ for (const wake of wakes) wake()
191
+ return Promise.resolve(true)
192
+ },
193
+ claim(now, lease, max) {
194
+ const out: QueuedJob[] = []
195
+ for (const h of held.values()) {
196
+ if (out.length >= max) break
197
+ if (h.runAt > now) continue
198
+ h.attempt++
199
+ h.runAt = now + lease
200
+ out.push({ id: h.id, name: h.name, input: h.input, attempt: h.attempt, runAt: now })
201
+ }
202
+ return Promise.resolve(out)
203
+ },
204
+ done(queued) {
205
+ drop(queued)
206
+ return done
207
+ },
208
+ retry(queued, runAt) {
209
+ const h = held.get(queued.id)
210
+ if (h) h.runAt = runAt
211
+ return done
212
+ },
213
+ fail(queued, error) {
214
+ drop(queued)
215
+ dead.push({ ...queued, error, at: Date.now() })
216
+ if (dead.length > deadLimit) dead.splice(0, dead.length - deadLimit)
217
+ return done
218
+ },
219
+ onPush(wake) {
220
+ wakes.push(wake)
221
+ },
222
+ }
223
+ }
@@ -0,0 +1,178 @@
1
+ /** Bump when a message here changes shape: tabs of two shapes share nothing, and each is its own client. */
2
+ const WIRE = 1
3
+ export const NAME = `kerf:link:${WIRE}`
4
+ export const BEAT = 5000
5
+ const PONG = 1500
6
+ // getRandomValues, not randomUUID: a page on plain http (a LAN address) has no randomUUID, and this runs on import.
7
+ export const tab =
8
+ typeof crypto === 'undefined' ? '' : crypto.getRandomValues(new Uint32Array(1))[0]!.toString(36)
9
+ const locks = (): LockManager | undefined =>
10
+ typeof navigator !== 'undefined' ? navigator.locks : undefined
11
+ export const shareable = () => !!locks() && typeof BroadcastChannel !== 'undefined'
12
+
13
+ // ---- a lock, a queue and a ping ---------------------------------------------------------------------------------------
14
+
15
+ export interface Campaign {
16
+ probe(): void
17
+ stop(): void
18
+ leading(): boolean
19
+ pinged?: () => void
20
+ }
21
+
22
+ /** `lead` when this tab takes the lock; `lose` when another tab takes it from under this one. */
23
+ export function campaign(
24
+ name: string,
25
+ won: () => void,
26
+ lose: () => void,
27
+ stolen?: () => void,
28
+ ): Campaign {
29
+ const l = locks()
30
+ const lockName = `${name}:leader`
31
+ const state: ElectionState = { on: true, leads: false, waiting: undefined }
32
+ const hold = () => {
33
+ state.leads = true
34
+ clearTimeout(state.waiting) // a ping that went out before there was anyone to answer it
35
+ state.waiting = undefined
36
+ won()
37
+ }
38
+ if (!l || typeof BroadcastChannel === 'undefined') {
39
+ queueMicrotask(() => {
40
+ if (state.on) hold()
41
+ })
42
+ return {
43
+ probe() {},
44
+ leading: () => state.leads,
45
+ stop() {
46
+ state.on = state.leads = false
47
+ },
48
+ }
49
+ }
50
+ return queuedCampaign(name, lockName, l, state, { hold, lose, stolen })
51
+ }
52
+
53
+ interface ElectionState {
54
+ on: boolean
55
+ leads: boolean
56
+ waiting: ReturnType<typeof setTimeout> | undefined
57
+ }
58
+
59
+ function queuedCampaign(
60
+ name: string,
61
+ lockName: string,
62
+ l: LockManager,
63
+ state: ElectionState,
64
+ on: { hold: () => void; lose: () => void; stolen?: (() => void) | undefined },
65
+ ): Campaign {
66
+ const { hold, lose, stolen } = on
67
+ let release: (() => void) | undefined
68
+ let abort: AbortController | undefined
69
+ let pongAt = 0
70
+ const bc = new BroadcastChannel(`${name}:e`)
71
+ const me: Campaign = {
72
+ leading: () => state.leads,
73
+ probe() {
74
+ // Each hover asks, so a recent answer has to do: one message a second, not one a move.
75
+ if (state.leads || state.waiting !== undefined || !state.on || Date.now() - pongAt < 1000)
76
+ return
77
+ bc.postMessage({ ping: tab })
78
+ const asked = Date.now()
79
+ state.waiting = setTimeout(() => {
80
+ state.waiting = undefined
81
+ // Late means this tab was frozen, and the answer is queued behind this timer: ask again.
82
+ if (Date.now() - asked > PONG * 1.5) return me.probe()
83
+ stolen?.()
84
+ const queued = abort
85
+ elect(true)
86
+ queued?.abort()
87
+ }, PONG)
88
+ },
89
+ stop() {
90
+ state.on = false
91
+ state.leads = false
92
+ clearTimeout(state.waiting)
93
+ clearInterval(timer)
94
+ abort?.abort()
95
+ release?.()
96
+ bc.close()
97
+ },
98
+ }
99
+ bc.onmessage = ({ data }) => {
100
+ if (data.ping && state.leads) {
101
+ bc.postMessage({ pong: data.ping })
102
+ me.pinged?.()
103
+ } else if (data.pong === tab) {
104
+ pongAt = Date.now()
105
+ clearTimeout(state.waiting)
106
+ state.waiting = undefined
107
+ }
108
+ }
109
+ function elect(steal = false) {
110
+ const ctl = new AbortController()
111
+ abort = ctl
112
+ l.request(
113
+ lockName,
114
+ steal ? { steal: true } : { signal: ctl.signal },
115
+ // A grant that comes after stop() (a steal can't be aborted) is handed straight back.
116
+ () =>
117
+ state.on
118
+ ? new Promise<void>((ok) => {
119
+ release = ok
120
+ hold()
121
+ })
122
+ : undefined,
123
+ ).catch(() => {
124
+ if (!state.on || abort !== ctl) return // this tab left the queue on purpose
125
+ if (state.leads) {
126
+ state.leads = false
127
+ lose()
128
+ }
129
+ elect()
130
+ })
131
+ }
132
+ const timer = setInterval(() => me.probe(), BEAT)
133
+ elect()
134
+ return me
135
+ }
136
+
137
+ // ---- this tab's own lock ----------------------------------------------------------------------------------------------
138
+
139
+ let tabHeld = false
140
+ let tabFree: (() => void) | undefined
141
+ /** Bumped by freeTab(): a grant for an earlier turn is handed straight back. */
142
+ let tabTurn = 0
143
+ const whenHeld: (() => void)[] = []
144
+
145
+ /** Held before the tab says anything, so a sibling that queues on it can't read a live tab as dead. */
146
+ export function holdTab(then: () => void) {
147
+ if (tabHeld || !locks()) return then()
148
+ whenHeld.push(then)
149
+ if (whenHeld.length > 1) return
150
+ const turn = tabTurn
151
+ locks()!
152
+ .request(`${NAME}:tab:${tab}`, () => {
153
+ if (turn !== tabTurn) return undefined // freed while it was asked for
154
+ return new Promise<void>((ok) => {
155
+ tabFree = ok
156
+ tabHeld = true
157
+ for (const f of whenHeld.splice(0)) f()
158
+ })
159
+ })
160
+ // No lock after all: go on without one rather than leave the callers (and every later one) waiting.
161
+ .catch(() => {
162
+ for (const f of whenHeld.splice(0)) f()
163
+ })
164
+ }
165
+
166
+ /** Comes through when that tab is gone, crash included. */
167
+ export function freeTab() {
168
+ tabTurn++
169
+ tabHeld = false
170
+ whenHeld.length = 0
171
+ tabFree?.()
172
+ tabFree = undefined
173
+ }
174
+
175
+ export const whenGone = (t: string, fn: () => void) =>
176
+ void locks()
177
+ ?.request(`${NAME}:tab:${t}`, () => fn())
178
+ .catch(() => {})
@@ -0,0 +1,27 @@
1
+ export interface Mine {
2
+ id: string
3
+ hello: string
4
+ frame(text: string): void
5
+ closed(code: number, reason?: string): void
6
+ }
7
+
8
+ export const lines = new Map<string, Mine>()
9
+
10
+ export function end(l: Mine, code: number, reason?: string) {
11
+ lines.delete(l.id)
12
+ l.closed(code, reason)
13
+ }
14
+ export const endAll = (code: number) => {
15
+ for (const l of Array.from(lines.values())) end(l, code)
16
+ }
17
+
18
+ export function arrive(text: string) {
19
+ const at = text.indexOf(':', 2)
20
+ const l = lines.get(text.slice(2, at))
21
+ if (!l) return
22
+ if (text[0] === 'x') {
23
+ const split = text.indexOf(':', at + 1)
24
+ return end(l, +text.slice(at + 1, split), text.slice(split + 1))
25
+ }
26
+ l.frame(text.slice(at + 1))
27
+ }