@spooky-sync/core 0.0.1-canary.98 → 1.0.0-beta.10

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 (279) hide show
  1. package/AGENTS.md +58 -21
  2. package/README.md +59 -16
  3. package/dist/index.d.ts +2235 -908
  4. package/dist/index.js +20424 -5052
  5. package/dist/live.d.ts +149 -0
  6. package/dist/live.js +739 -0
  7. package/dist/otel/index.d.ts +1 -1
  8. package/dist/pure.d.ts +401 -0
  9. package/dist/pure.js +24 -0
  10. package/dist/rows-worker.d.ts +1 -0
  11. package/dist/rows-worker.js +2639 -0
  12. package/dist/sqlite-open.js +392 -0
  13. package/dist/sqlite-worker.d.ts +1 -0
  14. package/dist/sqlite-worker.js +439 -0
  15. package/dist/sw.d.ts +207 -0
  16. package/dist/sw.js +393 -0
  17. package/dist/tabs-broker-worker.d.ts +8 -0
  18. package/dist/tabs-broker-worker.js +477 -0
  19. package/dist/types.d.ts +2084 -82
  20. package/dist/worker-edges.js +498 -0
  21. package/dist/worker-impersonation.js +60 -0
  22. package/dist/worker-ref-tables.d.ts +48 -0
  23. package/dist/worker-types.d.ts +112 -0
  24. package/dist/worker-types.js +73 -0
  25. package/package.json +39 -8
  26. package/scripts/check-broker-bundle.mjs +33 -0
  27. package/scripts/check-worker-entries.mjs +186 -0
  28. package/skills/sp00ky-core/SKILL.md +44 -8
  29. package/skills/sp00ky-core/references/config.md +8 -2
  30. package/src/boot/auth-flip.saga.test.ts +174 -0
  31. package/src/boot/auth-flip.saga.ts +77 -0
  32. package/src/boot/boot.saga.test.ts +203 -0
  33. package/src/boot/boot.saga.ts +146 -0
  34. package/src/boot/bucket-switch.saga.test.ts +191 -0
  35. package/src/boot/bucket-switch.saga.ts +151 -0
  36. package/src/boot/preload.saga.test.ts +96 -0
  37. package/src/boot/preload.saga.ts +45 -0
  38. package/src/bucket-blurhash.test.ts +148 -0
  39. package/src/client/bucket-handle.test.ts +195 -0
  40. package/src/client/bucket-handle.ts +372 -0
  41. package/src/client/eager-paint.test.ts +82 -0
  42. package/src/client/router.test.ts +59 -0
  43. package/src/client/router.ts +104 -0
  44. package/src/client/runtime.test.ts +319 -0
  45. package/src/client/runtime.ts +307 -0
  46. package/src/client/services.test.ts +74 -0
  47. package/src/client/services.ts +440 -0
  48. package/src/client/sp00ky-client.test.ts +570 -0
  49. package/src/client/sp00ky-client.ts +875 -0
  50. package/src/index.ts +87 -0
  51. package/src/kernel/constants.test.ts +19 -0
  52. package/src/kernel/constants.ts +94 -0
  53. package/src/kernel/effects.test.ts +40 -0
  54. package/src/kernel/effects.ts +181 -0
  55. package/src/kernel/events.ts +60 -0
  56. package/src/kernel/interpreter.test.ts +133 -0
  57. package/src/kernel/interpreter.ts +151 -0
  58. package/src/kernel/saga.test.ts +89 -0
  59. package/src/kernel/saga.ts +73 -0
  60. package/src/live/index.test.ts +512 -0
  61. package/src/live/index.ts +1059 -0
  62. package/src/modules/app-release/index.test.ts +125 -0
  63. package/src/modules/app-release/index.ts +209 -0
  64. package/src/modules/auth/auth.local-first.test.ts +228 -0
  65. package/src/modules/auth/auth.session-recheck.test.ts +140 -0
  66. package/src/modules/auth/events/index.ts +7 -1
  67. package/src/modules/auth/impersonation-banner.ts +443 -0
  68. package/src/modules/auth/impersonation.integration.test.ts +209 -0
  69. package/src/modules/auth/impersonation.test.ts +377 -0
  70. package/src/modules/auth/impersonation.ts +179 -0
  71. package/src/modules/auth/index.ts +516 -34
  72. package/src/modules/channel/channel.test.ts +752 -0
  73. package/src/modules/channel/hub.test.ts +223 -0
  74. package/src/modules/channel/hub.ts +355 -0
  75. package/src/modules/channel/index.ts +1497 -0
  76. package/src/modules/channel/room.test.ts +340 -0
  77. package/src/modules/channel/room.ts +367 -0
  78. package/src/modules/channel/rooms.fixture.ts +383 -0
  79. package/src/modules/channel/share.test.ts +535 -0
  80. package/src/modules/channel/webrtc.ts +472 -0
  81. package/src/modules/crdt/acceptance.ts +75 -0
  82. package/src/modules/crdt/bytes.ts +50 -0
  83. package/src/modules/crdt/crdt-field.ts +82 -238
  84. package/src/modules/crdt/crdt.test.ts +546 -0
  85. package/src/modules/crdt/hash.ts +103 -0
  86. package/src/modules/crdt/index.ts +740 -271
  87. package/src/modules/crdt/loro-loader.ts +25 -0
  88. package/src/modules/crdt/mirror.ts +37 -0
  89. package/src/modules/devtools/flags.ts +349 -0
  90. package/src/modules/devtools/index.ts +661 -99
  91. package/src/modules/devtools/mutations.test.ts +92 -0
  92. package/src/modules/devtools/mutations.ts +160 -0
  93. package/src/modules/devtools/notify-throttle.test.ts +166 -0
  94. package/src/modules/devtools/state-shape.test.ts +263 -0
  95. package/src/modules/devtools/storage-info.test.ts +79 -0
  96. package/src/modules/devtools/storage-info.ts +169 -0
  97. package/src/modules/devtools/versions.ts +29 -0
  98. package/src/modules/feature-flag/index.test.ts +179 -1
  99. package/src/modules/feature-flag/index.ts +117 -10
  100. package/src/modules/ref-tables.test.ts +28 -1
  101. package/src/modules/ref-tables.ts +23 -1
  102. package/src/modules/web-push/index.test.ts +824 -0
  103. package/src/modules/web-push/index.ts +1027 -0
  104. package/src/mutation/ingest-outage.integration.test.ts +400 -0
  105. package/src/mutation/jobs.test.ts +25 -0
  106. package/src/mutation/jobs.ts +41 -0
  107. package/src/mutation/mutation-id.test.ts +37 -0
  108. package/src/mutation/mutation-id.ts +35 -0
  109. package/src/mutation/pending-writes.integration.test.ts +175 -0
  110. package/src/mutation/push.saga.test.ts +361 -0
  111. package/src/mutation/push.saga.ts +245 -0
  112. package/src/mutation/rows.test.ts +278 -0
  113. package/src/mutation/rows.ts +515 -0
  114. package/src/mutation/tray.saga.test.ts +63 -0
  115. package/src/mutation/tray.saga.ts +48 -0
  116. package/src/mutation/write.saga.test.ts +436 -0
  117. package/src/mutation/write.saga.ts +384 -0
  118. package/src/pure.ts +66 -0
  119. package/src/push/types.ts +174 -0
  120. package/src/query/anon-query-isolation.integration.test.ts +531 -0
  121. package/src/query/env.test.ts +23 -0
  122. package/src/query/env.ts +65 -0
  123. package/src/query/fetch.saga.test.ts +199 -0
  124. package/src/query/fetch.saga.ts +120 -0
  125. package/src/query/hash.test.ts +14 -0
  126. package/src/query/hash.ts +18 -0
  127. package/src/query/id-set-plan.test.ts +132 -0
  128. package/src/query/lifecycle.saga.test.ts +274 -0
  129. package/src/query/lifecycle.saga.ts +186 -0
  130. package/src/query/list-ref-live.integration.test.ts +203 -0
  131. package/src/query/materialize.saga.test.ts +216 -0
  132. package/src/query/materialize.saga.ts +83 -0
  133. package/src/query/materialize.test.ts +58 -0
  134. package/src/query/materialize.ts +133 -0
  135. package/src/query/membership.saga.test.ts +514 -0
  136. package/src/query/membership.saga.ts +339 -0
  137. package/src/query/membership.test.ts +151 -0
  138. package/src/query/membership.ts +234 -0
  139. package/src/query/register.saga.test.ts +430 -0
  140. package/src/query/register.saga.ts +330 -0
  141. package/src/query/render-set.test.ts +47 -0
  142. package/src/query/render-set.ts +71 -0
  143. package/src/query/session-guard.integration.test.ts +304 -0
  144. package/src/query/sql.test.ts +118 -0
  145. package/src/query/sql.ts +174 -0
  146. package/src/{modules/data → query}/window-query.test.ts +22 -4
  147. package/src/{modules/data → query}/window-query.ts +86 -8
  148. package/src/services/blobs/blob-cache.test.ts +359 -0
  149. package/src/services/blobs/blob-cache.ts +603 -0
  150. package/src/services/blobs/blob-manifest.ts +227 -0
  151. package/src/services/blobs/blob-store.test.ts +77 -0
  152. package/src/services/blobs/blob-store.ts +359 -0
  153. package/src/services/blobs/blob.fixture.ts +90 -0
  154. package/src/services/blobs/index.ts +70 -0
  155. package/src/services/database/cache-engine.ts +223 -0
  156. package/src/services/database/connection-supervisor.test.ts +318 -0
  157. package/src/services/database/connection-supervisor.ts +422 -0
  158. package/src/services/database/database.query-timeout.test.ts +140 -0
  159. package/src/services/database/database.responses.test.ts +43 -0
  160. package/src/services/database/database.ts +151 -56
  161. package/src/services/database/engine-factory.ts +40 -0
  162. package/src/services/database/errors.ts +34 -0
  163. package/src/services/database/index.ts +8 -0
  164. package/src/services/database/landed-body-clear.integration.test.ts +236 -0
  165. package/src/services/database/local-migrator.integration.test.ts +110 -0
  166. package/src/services/database/local-migrator.ts +54 -9
  167. package/src/services/database/local.test.ts +117 -0
  168. package/src/services/database/local.ts +364 -74
  169. package/src/services/database/plan-render.test.ts +159 -0
  170. package/src/services/database/plan-render.ts +108 -0
  171. package/src/services/database/relation-resolver.test.ts +484 -0
  172. package/src/services/database/relation-resolver.ts +0 -0
  173. package/src/services/database/remote.ts +283 -4
  174. package/src/services/database/rows-cache-engine.test.ts +1014 -0
  175. package/src/services/database/rows-cache-engine.ts +921 -0
  176. package/src/services/database/rows-exec.integration.test.ts +589 -0
  177. package/src/services/database/rows-exec.ts +1027 -0
  178. package/src/services/database/rows-prewarm.ts +225 -0
  179. package/src/services/database/rows-store.test.ts +635 -0
  180. package/src/services/database/rows-store.ts +1208 -0
  181. package/src/services/database/rows-transport.fixture.ts +151 -0
  182. package/src/services/database/rows-worker.ts +588 -0
  183. package/src/services/database/sqlite-cache-engine.test.ts +649 -0
  184. package/src/services/database/sqlite-cache-engine.timeout.test.ts +61 -0
  185. package/src/services/database/sqlite-cache-engine.ts +1422 -0
  186. package/src/services/database/sqlite-column-reset.integration.test.ts +100 -0
  187. package/src/services/database/sqlite-column-reset.ts +91 -0
  188. package/src/services/database/sqlite-devtools-queries.integration.test.ts +143 -0
  189. package/src/services/database/sqlite-devtools-queries.test.ts +154 -0
  190. package/src/services/database/sqlite-lock-verify.test.ts +33 -0
  191. package/src/services/database/sqlite-lock-verify.ts +45 -0
  192. package/src/services/database/sqlite-open.test.ts +150 -0
  193. package/src/services/database/sqlite-open.ts +164 -0
  194. package/src/services/database/sqlite-plan-sql.test.ts +164 -0
  195. package/src/services/database/sqlite-plan-sql.ts +196 -0
  196. package/src/services/database/sqlite-projection.test.ts +121 -0
  197. package/src/services/database/sqlite-select.integration.test.ts +185 -0
  198. package/src/services/database/sqlite-select.test.ts +261 -0
  199. package/src/services/database/sqlite-select.ts +131 -0
  200. package/src/services/database/sqlite-transport.fixture.ts +30 -0
  201. package/src/services/database/sqlite-transport.ts +231 -0
  202. package/src/services/database/sqlite-worker.ts +437 -0
  203. package/src/services/database/surql-translate.ts +417 -0
  204. package/src/services/database/surreal-cache-engine.ts +163 -0
  205. package/src/services/logger/index.test.ts +132 -0
  206. package/src/services/logger/index.ts +187 -6
  207. package/src/services/persistence/surrealdb.ts +2 -2
  208. package/src/services/stream-processor/index.ts +621 -93
  209. package/src/services/stream-processor/stream-processor.batch.test.ts +57 -7
  210. package/src/services/stream-processor/stream-processor.prime.test.ts +234 -0
  211. package/src/services/stream-processor/stream-processor.reset.test.ts +226 -0
  212. package/src/services/stream-processor/wasm-types.ts +41 -1
  213. package/src/services/tabs/broker-client.ts +284 -0
  214. package/src/services/tabs/broker.test.ts +381 -0
  215. package/src/services/tabs/coordinator.test.ts +386 -0
  216. package/src/services/tabs/coordinator.ts +646 -0
  217. package/src/services/tabs/fake-ports.fixture.ts +112 -0
  218. package/src/services/tabs/leader-locks.ts +75 -0
  219. package/src/services/tabs/protocol.ts +262 -0
  220. package/src/services/tabs/support.ts +38 -0
  221. package/src/services/tabs/tabs-broker-worker.ts +652 -0
  222. package/src/sp00ky.ts +5 -648
  223. package/src/state/client-state.ts +231 -0
  224. package/src/state/lifecycle.test.ts +184 -0
  225. package/src/state/lifecycle.ts +127 -0
  226. package/src/state/reducers.test.ts +337 -0
  227. package/src/state/reducers.ts +571 -0
  228. package/src/state/selectors.test.ts +203 -0
  229. package/src/state/selectors.ts +264 -0
  230. package/src/sw/index.test.ts +582 -0
  231. package/src/sw/index.ts +607 -0
  232. package/src/sw/store.ts +96 -0
  233. package/src/sync/connection.saga.test.ts +97 -0
  234. package/src/sync/connection.saga.ts +89 -0
  235. package/src/sync/live.saga.test.ts +229 -0
  236. package/src/sync/live.saga.ts +116 -0
  237. package/src/sync/policy.health.test.ts +56 -0
  238. package/src/{modules/sync/utils.test.ts → sync/policy.test.ts} +96 -11
  239. package/src/{modules/sync/utils.ts → sync/policy.ts} +186 -7
  240. package/src/sync/poll.saga.test.ts +51 -0
  241. package/src/sync/poll.saga.ts +36 -0
  242. package/src/sync/tabs.saga.test.ts +78 -0
  243. package/src/sync/tabs.saga.ts +96 -0
  244. package/src/testing/adapters.ts +137 -0
  245. package/src/testing/build.ts +63 -0
  246. package/src/testing/fake-services.ts +63 -0
  247. package/src/testing/run-pure.test.ts +92 -0
  248. package/src/testing/run-pure.ts +128 -0
  249. package/src/testing/services.ts +17 -0
  250. package/src/types.ts +601 -25
  251. package/src/utils/blurhash.ts +90 -0
  252. package/src/utils/edges.ts +57 -0
  253. package/src/utils/error-classification.test.ts +116 -0
  254. package/src/utils/error-classification.ts +74 -0
  255. package/src/utils/index.ts +58 -3
  256. package/src/utils/parser.test.ts +67 -102
  257. package/src/utils/parser.ts +62 -1
  258. package/src/utils/semver.test.ts +32 -0
  259. package/src/utils/semver.ts +30 -0
  260. package/src/utils/sha256.ts +15 -0
  261. package/src/utils/surql.ts +17 -15
  262. package/src/utils/utils.test.ts +3 -2
  263. package/tsdown.config.ts +105 -4
  264. package/vitest.config.ts +52 -0
  265. package/src/modules/cache/index.ts +0 -253
  266. package/src/modules/cache/types.ts +0 -19
  267. package/src/modules/crdt/crdt-hydration.test.ts +0 -206
  268. package/src/modules/data/data.status.test.ts +0 -108
  269. package/src/modules/data/data.test.ts +0 -58
  270. package/src/modules/data/index.ts +0 -1491
  271. package/src/modules/sync/engine.ts +0 -227
  272. package/src/modules/sync/events/index.ts +0 -84
  273. package/src/modules/sync/index.ts +0 -3
  274. package/src/modules/sync/queue/index.ts +0 -2
  275. package/src/modules/sync/queue/queue-down.ts +0 -90
  276. package/src/modules/sync/queue/queue-up.ts +0 -224
  277. package/src/modules/sync/scheduler.ts +0 -121
  278. package/src/modules/sync/sync.ts +0 -1244
  279. package/src/sp00ky.auth-order.test.ts +0 -65
@@ -0,0 +1,225 @@
1
+ /**
2
+ * Starting the row store ahead of the app. Kept free of imports: a build
3
+ * script that only wants {@link ROWS_PREWARM_SNIPPET} for the page's `<head>`
4
+ * loads this file and nothing else of the client.
5
+ *
6
+ * What a page load can have done before its bundle has run:
7
+ *
8
+ * 1. the worker started and the last bucket's store opened;
9
+ * 2. the reads the app made in its first seconds last time, asked again
10
+ * ("read ahead"), their answers waiting in the page;
11
+ * 3. the tables' indexes read into the worker's memory.
12
+ *
13
+ * The engine (`rows-cache-engine.ts`) adopts all three when it connects, and
14
+ * starts its own worker when anything about them is wrong.
15
+ */
16
+
17
+ /** localStorage key under which the engine leaves what {@link prewarmRows} needs. */
18
+ export const ROWS_PREWARM_KEY = 'sp00ky.rows.prewarm';
19
+
20
+ /** Message id of the open a prewarm sends. */
21
+ export const ROWS_PREWARM_OPEN_ID = -1;
22
+ /** Read `i` of a prewarm goes out as message `ROWS_AHEAD_ID - i`. The worker answers reads only under these ids. */
23
+ export const ROWS_AHEAD_ID = -10;
24
+
25
+ /** The worker ops a prewarm may ask ahead: the ones that answer rows and change nothing. */
26
+ export const ROWS_AHEAD_OPS: ReadonlySet<string> = new Set(['select', 'by-ids', 'relation']);
27
+
28
+ /** What the engine saves for the next page load. */
29
+ export interface PrewarmRecord {
30
+ url: string;
31
+ bucket: string;
32
+ /** `[op, payload]` of the reads to ask ahead; JSON all the way down. */
33
+ reads?: [string, unknown][];
34
+ }
35
+
36
+ /** A worker's reply as it arrives: the transport's envelope around an op's result. */
37
+ export interface PrewarmReply {
38
+ id: number;
39
+ ok: boolean;
40
+ error?: string;
41
+ [field: string]: unknown;
42
+ }
43
+
44
+ export interface Prewarmed {
45
+ worker: Worker;
46
+ bucket: string;
47
+ failed: boolean;
48
+ /** The worker's answer to the open it was started with, once it has come. */
49
+ opened?: PrewarmReply;
50
+ /** The reads asked ahead, and the answers that have come, by position. */
51
+ reads: [string, unknown][];
52
+ replies: Record<number, PrewarmReply>;
53
+ }
54
+
55
+ type PrewarmGlobal = { __sp00kyRowsPrewarm?: Prewarmed };
56
+
57
+ /**
58
+ * Start the row store's worker and open the last bucket NOW, before the app
59
+ * has loaded. A worker takes about 10 ms to start and the store a few more to
60
+ * open; started from the first bytes of the page, that happens while the
61
+ * bundle downloads and parses, and by the time the client connects the store
62
+ * is open, its indexes are in memory and the answers to the app's first reads
63
+ * are already in the page. The engine finds the worker and adopts it; if
64
+ * anything about it is wrong (a new release, another bucket, a failed start)
65
+ * it starts its own, as it would have without this.
66
+ *
67
+ * Call it as early as the app can, or inline {@link ROWS_PREWARM_SNIPPET} in
68
+ * the page's `<head>`, which is this function without the bundle. A no-op on
69
+ * a first visit: the worker's URL is learned from the engine's first open.
70
+ */
71
+ export function prewarmRows(): void {
72
+ try {
73
+ const g = globalThis as PrewarmGlobal;
74
+ const saved = JSON.parse(localStorage.getItem(ROWS_PREWARM_KEY) ?? 'null') as Partial<PrewarmRecord> | null;
75
+ if (!saved?.url || !saved.bucket || g.__sp00kyRowsPrewarm) return;
76
+ const reads = Array.isArray(saved.reads) ? saved.reads : [];
77
+ const pre: Prewarmed = {
78
+ worker: new Worker(saved.url, { type: 'module' }),
79
+ bucket: saved.bucket,
80
+ failed: false,
81
+ reads,
82
+ replies: {},
83
+ };
84
+ pre.worker.onerror = () => {
85
+ pre.failed = true;
86
+ };
87
+ // Kept for the engine: with the worker's answers in hand it does not ask
88
+ // again, and its first reads cost no trip to the worker at all.
89
+ pre.worker.onmessage = (ev: MessageEvent) => {
90
+ const data = ev.data as PrewarmReply | null;
91
+ if (!data) return;
92
+ if (data.id === ROWS_PREWARM_OPEN_ID) {
93
+ if (data.ok === true) pre.opened = data;
94
+ } else if (data.id <= ROWS_AHEAD_ID) pre.replies[ROWS_AHEAD_ID - data.id] = data;
95
+ };
96
+ // One attempt and no memory fallback: if the files are held (another tab
97
+ // leads), the engine's own open sorts it out.
98
+ pre.worker.postMessage({
99
+ id: ROWS_PREWARM_OPEN_ID,
100
+ type: 'open',
101
+ payload: { dbName: saved.bucket, useOpfs: true, openOptions: { maxAttempts: 1, disallowMemoryFallback: true } },
102
+ });
103
+ for (let i = 0; i < reads.length; i++) pre.worker.postMessage({ id: ROWS_AHEAD_ID - i, type: reads[i][0], payload: reads[i][1] });
104
+ pre.worker.postMessage({ id: -2, type: 'warm' });
105
+ g.__sp00kyRowsPrewarm = pre;
106
+ } catch {
107
+ // No storage, no workers, a blocked URL: the engine starts its own worker.
108
+ }
109
+ }
110
+
111
+ /** {@link prewarmRows} as a script to inline in `<head>`, ahead of the app's bundle. */
112
+ export const ROWS_PREWARM_SNIPPET =
113
+ `(function(){try{var g=globalThis,p=JSON.parse(localStorage.getItem("${ROWS_PREWARM_KEY}")||"null");` +
114
+ `if(!p||!p.url||!p.bucket||g.__sp00kyRowsPrewarm)return;` +
115
+ `var r=Array.isArray(p.reads)?p.reads:[],s={worker:new Worker(p.url,{type:"module"}),bucket:p.bucket,failed:false,reads:r,replies:{}};` +
116
+ `s.worker.onerror=function(){s.failed=true};` +
117
+ `s.worker.onmessage=function(e){var d=e.data;if(!d)return;` +
118
+ `if(d.id===${ROWS_PREWARM_OPEN_ID}){if(d.ok===true)s.opened=d}else if(d.id<=${ROWS_AHEAD_ID})s.replies[${ROWS_AHEAD_ID}-d.id]=d};` +
119
+ `s.worker.postMessage({id:${ROWS_PREWARM_OPEN_ID},type:"open",payload:{dbName:p.bucket,useOpfs:true,openOptions:{maxAttempts:1,disallowMemoryFallback:true}}});` +
120
+ `for(var i=0;i<r.length;i++)s.worker.postMessage({id:${ROWS_AHEAD_ID}-i,type:r[i][0],payload:r[i][1]});` +
121
+ `s.worker.postMessage({id:-2,type:"warm"});g.__sp00kyRowsPrewarm=s}catch(e){}})();`;
122
+
123
+ /** The prewarmed worker, once: whoever takes it owns it. */
124
+ export function takePrewarmed(): Prewarmed | null {
125
+ const g = globalThis as PrewarmGlobal;
126
+ const pre = g.__sp00kyRowsPrewarm ?? null;
127
+ delete g.__sp00kyRowsPrewarm;
128
+ return pre;
129
+ }
130
+
131
+ /** How a read is told from another: its op and its payload, as JSON. */
132
+ export const aheadKey = (type: string, payload: unknown): string => `${type}\n${JSON.stringify(payload)}`;
133
+
134
+ /**
135
+ * Whether `value` is the same thing after a trip through JSON. Only such a
136
+ * payload may be saved and asked again: a `Date` would come back as a string,
137
+ * and the worker would answer another question under the same key.
138
+ */
139
+ export function jsonSafe(value: unknown): boolean {
140
+ if (value === null || typeof value === 'string' || typeof value === 'boolean') return true;
141
+ if (typeof value === 'number') return Number.isFinite(value);
142
+ if (typeof value !== 'object') return false;
143
+ if (Array.isArray(value)) return value.every(jsonSafe);
144
+ const proto = Object.getPrototypeOf(value) as unknown;
145
+ if (proto !== Object.prototype && proto !== null) return false;
146
+ // An `undefined` property is one JSON leaves out, as if it had not been set.
147
+ return Object.values(value).every((v) => v === undefined || jsonSafe(v));
148
+ }
149
+
150
+ /**
151
+ * The answers a prewarmed worker gave, or is about to give, to the reads the
152
+ * last session made at startup. The engine takes one when it is about to ask
153
+ * the worker the very same thing, and so does not ask.
154
+ *
155
+ * Why the answer is the one the worker would give now: it read the store
156
+ * after opening it and before this page asked for anything, and nothing has
157
+ * written since. The engine drops everything left here the moment it sends a
158
+ * write (or anything else that is not a plain read), and never uses this at
159
+ * all when other tabs write through the same worker.
160
+ */
161
+ export class ReadAhead {
162
+ private wanted = new Map<string, number>();
163
+ private waiting = new Map<number, (reply: PrewarmReply | null) => void>();
164
+
165
+ /** Call once the transport has taken the worker: answers on their way pass through here first. */
166
+ constructor(
167
+ private pre: Prewarmed,
168
+ private waitMs: number
169
+ ) {
170
+ pre.reads.forEach((read, i) => {
171
+ if (Array.isArray(read) && ROWS_AHEAD_OPS.has(read[0])) this.wanted.set(aheadKey(read[0], read[1]), i);
172
+ });
173
+ const worker = pre.worker;
174
+ const inner = worker.onmessage;
175
+ worker.onmessage = (ev: MessageEvent) => {
176
+ const data = ev.data as PrewarmReply | null;
177
+ if (typeof data?.id === 'number' && data.id < 0) this.arrived(data);
178
+ else inner?.call(worker, ev);
179
+ };
180
+ }
181
+
182
+ private arrived(data: PrewarmReply): void {
183
+ if (data.id > ROWS_AHEAD_ID) return;
184
+ const i = ROWS_AHEAD_ID - data.id;
185
+ const waiter = this.waiting.get(i);
186
+ if (waiter) waiter(data.ok ? data : null);
187
+ else if (this.wanted.size > 0) this.pre.replies[i] = data;
188
+ }
189
+
190
+ /**
191
+ * The answer to this read if it was asked ahead: a promise of the reply,
192
+ * or of `null` when it failed or does not come. `null` when it was not
193
+ * asked ahead (or was taken already): ask the worker.
194
+ */
195
+ take(type: string, payload: unknown): Promise<PrewarmReply | null> | null {
196
+ if (this.wanted.size === 0) return null;
197
+ const key = aheadKey(type, payload);
198
+ const i = this.wanted.get(key);
199
+ if (i === undefined) return null;
200
+ this.wanted.delete(key);
201
+ const here = this.pre.replies[i];
202
+ if (here) {
203
+ delete this.pre.replies[i];
204
+ return Promise.resolve(here.ok ? here : null);
205
+ }
206
+ // Sent before the app existed, so it is ahead of anything sent now:
207
+ // waiting for it is never slower than asking again. Not forever, though.
208
+ return new Promise((resolve) => {
209
+ const settle = (reply: PrewarmReply | null): void => {
210
+ clearTimeout(timer);
211
+ this.waiting.delete(i);
212
+ resolve(reply);
213
+ };
214
+ const timer = setTimeout(() => settle(null), this.waitMs);
215
+ this.waiting.set(i, settle);
216
+ });
217
+ }
218
+
219
+ /** Forget every answer not taken yet: the store is about to change, or the session has moved on. */
220
+ drop(): void {
221
+ this.wanted.clear();
222
+ this.pre.replies = {};
223
+ for (const settle of [...this.waiting.values()]) settle(null);
224
+ }
225
+ }