@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,2639 @@
1
+ //# allFunctionsCalledOnLoad
2
+ //#region src/services/database/sqlite-lock-verify.ts
3
+ const LOCK_VERIFY_TIMEOUT_MS = 2e3;
4
+ async function verifyLockStillHeld(locks, name, fence, timeoutMs = LOCK_VERIFY_TIMEOUT_MS, warn = () => {}) {
5
+ if (!locks || !name || typeof locks.query !== "function") return;
6
+ let timer;
7
+ try {
8
+ const state = await Promise.race([locks.query(), new Promise((resolve) => {
9
+ timer = setTimeout(() => resolve(null), timeoutMs);
10
+ })]);
11
+ if (state === null) {
12
+ warn(`lock verification did not answer within ${timeoutMs}ms; trusting the steal callback`);
13
+ return;
14
+ }
15
+ if (!(state.held ?? []).some((l) => l.name === name)) await fence("lock missing after suspected freeze");
16
+ } catch {} finally {
17
+ if (timer) clearTimeout(timer);
18
+ }
19
+ }
20
+
21
+ //#endregion
22
+ //#region src/services/database/rows-store.ts
23
+ /** The OPFS directory that holds a bucket's two files. */
24
+ const bucketDirName = (bucketId) => `sp00ky-rows-${bucketId.replace(/[^A-Za-z0-9_.-]/g, "_")}`;
25
+ /** Body holds `{"__u8": base64}` tags the reader has to turn back into bytes. */
26
+ const FLAG_U8 = 1;
27
+ /** Body is raw bytes, not JSON. */
28
+ const FLAG_RAW = 2;
29
+ const MAGIC = 1380667475;
30
+ const VERSION = 1;
31
+ const SB_SIZE = 256;
32
+ const SB_USED = 64;
33
+ const HEADER_END = 4096;
34
+ const XH = 16;
35
+ /** How much of the tail a replay reads at once. */
36
+ const REPLAY_CHUNK = 1 << 20;
37
+ const X_BATCH = 1;
38
+ const X_BLOCK = 2;
39
+ const X_DIR = 3;
40
+ const R_PUT = 1;
41
+ const R_DEL = 2;
42
+ const R_CLEAR = 3;
43
+ const R_TABLE = 4;
44
+ const ACTIVE = 1;
45
+ const MOVED = 2;
46
+ /** Bytes per row in a block, besides its id. */
47
+ const ROW_BYTES = 25;
48
+ /** Bytes a put record adds around its id and body. */
49
+ const RECORD_BYTES = 18;
50
+ const MAX_ID_BYTES = 65535;
51
+ const COMPACT_CHUNK = 4 << 20;
52
+ /** A batch buffer larger than this is dropped after the write instead of kept. */
53
+ const SCRATCH_KEEP = 8 << 20;
54
+ const LITTLE_ENDIAN = new Uint8Array(new Uint32Array([1]).buffer)[0] === 1;
55
+ const encoder$1 = new TextEncoder();
56
+ const decoder$1 = new TextDecoder();
57
+ const align8 = (n) => n + 7 & -8;
58
+ /**
59
+ * 32-bit hash of a byte range. Not cryptographic: it tells a whole write from
60
+ * a torn one. Reads a word at a time where the bytes allow it.
61
+ */
62
+ function hash32(buf, start = 0, end = buf.length) {
63
+ let h = 2654435761 ^ end - start | 0;
64
+ let i = start;
65
+ const words = end - start >>> 2;
66
+ if (LITTLE_ENDIAN && (buf.byteOffset + start & 3) === 0) {
67
+ const w = new Uint32Array(buf.buffer, buf.byteOffset + start, words);
68
+ for (let k = 0; k < words; k++) {
69
+ h = Math.imul(h ^ w[k], 2246822507);
70
+ h = h << 13 | h >>> 19;
71
+ }
72
+ i = start + words * 4;
73
+ } else for (const stop = start + words * 4; i < stop; i += 4) {
74
+ const x = buf[i] | buf[i + 1] << 8 | buf[i + 2] << 16 | buf[i + 3] << 24;
75
+ h = Math.imul(h ^ x, 2246822507);
76
+ h = h << 13 | h >>> 19;
77
+ }
78
+ for (; i < end; i++) {
79
+ h = Math.imul(h ^ buf[i], 3266489909);
80
+ h = h << 7 | h >>> 25;
81
+ }
82
+ h ^= h >>> 16;
83
+ h = Math.imul(h, 2246822507);
84
+ h ^= h >>> 13;
85
+ h = Math.imul(h, 3266489909);
86
+ h ^= h >>> 16;
87
+ return h >>> 0;
88
+ }
89
+ /** Order of two byte ranges, as `memcmp` then length. */
90
+ function cmpBytes(a, aStart, aEnd, b, bStart, bEnd) {
91
+ const n = Math.min(aEnd - aStart, bEnd - bStart);
92
+ for (let i = 0; i < n; i++) {
93
+ const d = a[aStart + i] - b[bStart + i];
94
+ if (d !== 0) return d;
95
+ }
96
+ return aEnd - aStart - (bEnd - bStart);
97
+ }
98
+ /**
99
+ * Order of two strings by code point, which is the order of their UTF-8
100
+ * bytes. JavaScript's own comparison is by UTF-16 unit and puts a surrogate
101
+ * pair below U+E000, where UTF-8 puts it above.
102
+ */
103
+ function cmpText(a, b) {
104
+ if (a === b) return 0;
105
+ const n = Math.min(a.length, b.length);
106
+ for (let i = 0; i < n; i++) {
107
+ let x = a.charCodeAt(i);
108
+ let y = b.charCodeAt(i);
109
+ if (x === y) continue;
110
+ if (x >= 55296 && y >= 55296) {
111
+ x = x >= 57344 ? x - 2048 : x + 8192;
112
+ y = y >= 57344 ? y - 2048 : y + 8192;
113
+ }
114
+ return x - y;
115
+ }
116
+ return a.length - b.length;
117
+ }
118
+ const NON_ASCII = /[^\x00-\x7f]/;
119
+ function emptyRun() {
120
+ return runFromBuffer(new Uint8Array(0), 0, 0, 0);
121
+ }
122
+ function runFromBuffer(buf, n, heapLen, live) {
123
+ const b = buf.buffer;
124
+ const o = buf.byteOffset;
125
+ return {
126
+ n,
127
+ off: new Float64Array(b, o, n),
128
+ rv: new Float64Array(b, o + 8 * n, n),
129
+ len: new Uint32Array(b, o + 16 * n, n),
130
+ idEnd: new Uint32Array(b, o + 20 * n, n),
131
+ flags: new Uint8Array(b, o + 24 * n, n),
132
+ heap: new Uint8Array(b, o + ROW_BYTES * n, heapLen),
133
+ buf,
134
+ live
135
+ };
136
+ }
137
+ const idStart = (run, i) => i === 0 ? 0 : run.idEnd[i - 1];
138
+ /** The id of row `i` of a run. */
139
+ function runId(run, i) {
140
+ return decoder$1.decode(run.heap.subarray(idStart(run, i), run.idEnd[i]));
141
+ }
142
+ let probe = new Uint8Array(256);
143
+ /** UTF-8 of `id` in the shared probe buffer; returns its length. */
144
+ function encodeProbe(id) {
145
+ if (probe.length < id.length * 3) probe = new Uint8Array(id.length * 3);
146
+ return encoder$1.encodeInto(id, probe).written;
147
+ }
148
+ function runFind(run, id) {
149
+ if (run.n === 0) return -1;
150
+ const len = encodeProbe(id);
151
+ let lo = 0;
152
+ let hi = run.n - 1;
153
+ while (lo <= hi) {
154
+ const mid = lo + hi >>> 1;
155
+ const c = cmpBytes(run.heap, idStart(run, mid), run.idEnd[mid], probe, 0, len);
156
+ if (c === 0) return mid;
157
+ if (c < 0) lo = mid + 1;
158
+ else hi = mid - 1;
159
+ }
160
+ return -1;
161
+ }
162
+ /** First row of `run`, at or after `from`, whose id is not below `key`. */
163
+ function lowerBound(run, from, key, keyLen) {
164
+ let lo = from;
165
+ let hi = run.n;
166
+ while (lo < hi) {
167
+ const mid = lo + hi >>> 1;
168
+ if (cmpBytes(run.heap, idStart(run, mid), run.idEnd[mid], key, 0, keyLen) < 0) lo = mid + 1;
169
+ else hi = mid;
170
+ }
171
+ return lo;
172
+ }
173
+ /**
174
+ * `base` with `delta` applied: overrides replace, `null` removes. The rows
175
+ * between two changed ids are copied as one block, so folding a handful of
176
+ * writes into a large table costs a few searches and a memcpy, not a walk.
177
+ */
178
+ function mergeRun(base, delta) {
179
+ const keys = [...delta.keys()];
180
+ let ascii = true;
181
+ let chars = 0;
182
+ for (const k of keys) {
183
+ chars += k.length;
184
+ if (ascii && NON_ASCII.test(k)) ascii = false;
185
+ }
186
+ if (ascii) keys.sort();
187
+ else keys.sort(cmpText);
188
+ const upper = base.n + keys.length;
189
+ const off = new Float64Array(upper);
190
+ const rv = new Float64Array(upper);
191
+ const len = new Uint32Array(upper);
192
+ const idEnd = new Uint32Array(upper);
193
+ const flags = new Uint8Array(upper);
194
+ const heap = new Uint8Array(base.heap.length + chars * 3);
195
+ let n = 0;
196
+ let h = 0;
197
+ let live = base.live;
198
+ let i = 0;
199
+ /** Copy base rows `[i, to)` to the output. */
200
+ const copy = (to) => {
201
+ if (to <= i) return;
202
+ const count = to - i;
203
+ const s = idStart(base, i);
204
+ const e = base.idEnd[to - 1];
205
+ off.set(base.off.subarray(i, to), n);
206
+ rv.set(base.rv.subarray(i, to), n);
207
+ len.set(base.len.subarray(i, to), n);
208
+ flags.set(base.flags.subarray(i, to), n);
209
+ heap.set(base.heap.subarray(s, e), h);
210
+ const shift = h - s;
211
+ for (let k = 0; k < count; k++) idEnd[n + k] = base.idEnd[i + k] + shift;
212
+ n += count;
213
+ h += e - s;
214
+ i = to;
215
+ };
216
+ for (const key of keys) {
217
+ const keyLen = encodeProbe(key);
218
+ copy(lowerBound(base, i, probe, keyLen));
219
+ if (i < base.n && cmpBytes(base.heap, idStart(base, i), base.idEnd[i], probe, 0, keyLen) === 0) {
220
+ live -= base.len[i];
221
+ i++;
222
+ }
223
+ const entry = delta.get(key);
224
+ if (!entry) continue;
225
+ heap.set(probe.subarray(0, keyLen), h);
226
+ h += keyLen;
227
+ off[n] = entry.off;
228
+ rv[n] = entry.rv;
229
+ len[n] = entry.len;
230
+ flags[n] = entry.flags;
231
+ idEnd[n] = h;
232
+ live += entry.len;
233
+ n++;
234
+ }
235
+ copy(base.n);
236
+ const run = runFromBuffer(new Uint8Array(new ArrayBuffer(ROW_BYTES * n + h)), n, h, live);
237
+ run.off.set(off.subarray(0, n));
238
+ run.rv.set(rv.subarray(0, n));
239
+ run.len.set(len.subarray(0, n));
240
+ run.idEnd.set(idEnd.subarray(0, n));
241
+ run.flags.set(flags.subarray(0, n));
242
+ run.heap.set(heap.subarray(0, h));
243
+ return run;
244
+ }
245
+ function readSuperblock(file) {
246
+ if (file.size() < SB_SIZE) return null;
247
+ const buf = new Uint8Array(SB_SIZE * 2);
248
+ file.read(buf, 0);
249
+ let best = null;
250
+ for (let slot = 0; slot < 2; slot++) {
251
+ const view = new DataView(buf.buffer, slot * SB_SIZE, SB_USED);
252
+ if (view.getUint32(0, true) !== MAGIC || view.getUint32(4, true) !== VERSION) continue;
253
+ if (view.getUint32(60, true) !== hash32(buf, slot * SB_SIZE, slot * SB_SIZE + 60)) continue;
254
+ if (view.getUint32(20, true) === 1 !== LITTLE_ENDIAN) continue;
255
+ const sb = {
256
+ seq: view.getFloat64(8, true),
257
+ state: view.getUint32(16, true),
258
+ dirOff: view.getFloat64(24, true),
259
+ dirLen: view.getUint32(32, true),
260
+ dirSum: view.getUint32(36, true),
261
+ covered: view.getFloat64(40, true),
262
+ gen: view.getFloat64(48, true)
263
+ };
264
+ if (!best || sb.seq > best.seq) best = sb;
265
+ }
266
+ return best;
267
+ }
268
+ function writeSuperblock(file, sb) {
269
+ const buf = new Uint8Array(SB_SIZE);
270
+ const view = new DataView(buf.buffer);
271
+ view.setUint32(0, MAGIC, true);
272
+ view.setUint32(4, VERSION, true);
273
+ view.setFloat64(8, sb.seq, true);
274
+ view.setUint32(16, sb.state, true);
275
+ view.setUint32(20, LITTLE_ENDIAN ? 1 : 0, true);
276
+ view.setFloat64(24, sb.dirOff, true);
277
+ view.setUint32(32, sb.dirLen, true);
278
+ view.setUint32(36, sb.dirSum, true);
279
+ view.setFloat64(40, sb.covered, true);
280
+ view.setFloat64(48, sb.gen, true);
281
+ view.setUint32(60, hash32(buf, 0, 60), true);
282
+ file.write(buf, sb.seq % 2 * SB_SIZE);
283
+ }
284
+ const EMPTY_SUPERBLOCK = {
285
+ seq: 0,
286
+ state: ACTIVE,
287
+ dirOff: 0,
288
+ dirLen: 0,
289
+ dirSum: 0,
290
+ covered: HEADER_END,
291
+ gen: 0
292
+ };
293
+ /** An index block whose bytes are not the ones a checkpoint wrote. */
294
+ var IndexMismatch = class extends Error {
295
+ constructor(table) {
296
+ super(`rows: index block of ${table} does not match its hash`);
297
+ this.name = "IndexMismatch";
298
+ }
299
+ };
300
+ var RowStore = class RowStore {
301
+ tables = /* @__PURE__ */ new Map();
302
+ byTid = /* @__PURE__ */ new Map();
303
+ nextTid = 1;
304
+ scratch = new Uint8Array(65536);
305
+ dirBytes = 0;
306
+ tailOps = 0;
307
+ needsFlush = false;
308
+ rebuilt = false;
309
+ closed = false;
310
+ /**
311
+ * A reader: a second view of a store another `RowStore` is writing through
312
+ * handles of its own (a follower tab reading the leader's file). It never
313
+ * writes a byte. See {@link refresh}.
314
+ */
315
+ reader = false;
316
+ /** Generation of the superblock a reader's index came from; `null` when it found none. */
317
+ readGen = null;
318
+ constructor(io, file, name, other, sb, end) {
319
+ this.io = io;
320
+ this.file = file;
321
+ this.name = name;
322
+ this.other = other;
323
+ this.sb = sb;
324
+ this.end = end;
325
+ }
326
+ static async open(io, opts = {}) {
327
+ if (opts.reader) {
328
+ const store = new RowStore(io, await io.open("a"), "a", await io.open("b"), EMPTY_SUPERBLOCK, HEADER_END);
329
+ store.reader = true;
330
+ store.reload();
331
+ return store;
332
+ }
333
+ const a = await io.open("a");
334
+ let file = a;
335
+ let name = "a";
336
+ let other = null;
337
+ let sb = readSuperblock(a);
338
+ if (!sb || sb.state !== ACTIVE) {
339
+ const b = await io.open("b");
340
+ const sbB = readSuperblock(b);
341
+ if (sbB && sbB.state === ACTIVE) {
342
+ file = b;
343
+ name = "b";
344
+ other = a;
345
+ sb = sbB;
346
+ } else {
347
+ other = b;
348
+ if (a.size() <= HEADER_END && b.size() > HEADER_END) {
349
+ file = b;
350
+ name = "b";
351
+ other = a;
352
+ }
353
+ sb = null;
354
+ }
355
+ }
356
+ const fresh = sb === null;
357
+ const store = new RowStore(io, file, name, other, sb ?? EMPTY_SUPERBLOCK, HEADER_END);
358
+ if (fresh || !store.loadDirectory()) store.resetIndex();
359
+ store.replay(store.sb.covered);
360
+ if (fresh) store.commitSuperblock(0, 0, 0, store.sb.covered);
361
+ return store;
362
+ }
363
+ /** Read the directory the superblock names. False when it cannot be trusted. */
364
+ loadDirectory() {
365
+ const { dirOff, dirLen, dirSum, covered } = this.sb;
366
+ if (covered > Math.max(this.file.size(), HEADER_END)) return false;
367
+ if (dirOff === 0) return true;
368
+ if (dirOff + dirLen > this.file.size()) return false;
369
+ const buf = new Uint8Array(dirLen);
370
+ this.file.read(buf, dirOff);
371
+ if (hash32(buf) !== dirSum) return false;
372
+ let dir;
373
+ try {
374
+ dir = JSON.parse(decoder$1.decode(buf));
375
+ } catch {
376
+ return false;
377
+ }
378
+ this.nextTid = dir.nextTid;
379
+ this.dirBytes = dirLen + XH;
380
+ for (const t of dir.tables) {
381
+ const table = {
382
+ name: t.name,
383
+ tid: t.tid,
384
+ block: t.n > 0 ? {
385
+ off: t.off,
386
+ len: t.len,
387
+ n: t.n,
388
+ heap: t.heap,
389
+ sum: t.sum,
390
+ live: t.live
391
+ } : null,
392
+ run: null,
393
+ delta: /* @__PURE__ */ new Map(),
394
+ unsaved: false
395
+ };
396
+ this.tables.set(t.name, table);
397
+ this.byTid.set(t.tid, table);
398
+ }
399
+ return true;
400
+ }
401
+ /** Forget the index; the next replay starts from the first extent. */
402
+ resetIndex() {
403
+ this.tables.clear();
404
+ this.byTid.clear();
405
+ this.nextTid = 1;
406
+ this.dirBytes = 0;
407
+ this.tailOps = 0;
408
+ this.rebuilt = this.file.size() > HEADER_END;
409
+ this.sb = {
410
+ ...this.sb,
411
+ dirOff: 0,
412
+ dirLen: 0,
413
+ dirSum: 0,
414
+ covered: HEADER_END
415
+ };
416
+ }
417
+ /** Apply every whole batch from `from` on, and cut the file after the last. */
418
+ replay(from) {
419
+ const size = this.file.size();
420
+ let pos = from;
421
+ let chunk = new Uint8Array(0);
422
+ let base = 0;
423
+ let have = 0;
424
+ /** Bytes `[at, at + len)` of the file, from the piece in hand when it covers them. */
425
+ const bytes = (at, len) => {
426
+ if (at < base || at + len > base + have) {
427
+ const want = Math.min(size - at, Math.max(len, REPLAY_CHUNK));
428
+ if (chunk.length < want) chunk = new Uint8Array(new ArrayBuffer(want));
429
+ this.file.read(chunk.subarray(0, want), at);
430
+ base = at;
431
+ have = want;
432
+ }
433
+ return chunk.subarray(at - base, at - base + len);
434
+ };
435
+ while (pos + XH <= size) {
436
+ const head = bytes(pos, XH);
437
+ const headView = new DataView(head.buffer, head.byteOffset, XH);
438
+ const type = headView.getUint32(0, true);
439
+ const len = headView.getUint32(4, true);
440
+ const sum = headView.getUint32(8, true);
441
+ if (type < X_BATCH || type > X_DIR || pos + XH + len > size) break;
442
+ if (type === X_BATCH) {
443
+ const payload = bytes(pos + XH, len);
444
+ if (hash32(payload) !== sum) break;
445
+ this.applyBatch(payload, pos + XH);
446
+ }
447
+ pos = align8(pos + XH + len);
448
+ }
449
+ this.end = pos;
450
+ if (!this.reader && size > this.end) this.file.truncate(this.end);
451
+ }
452
+ /** Take in what the writer did since the last look. A reader calls this before it answers. */
453
+ refresh() {
454
+ if (!this.reader || this.closed) return;
455
+ if (!this.current() || this.end > this.file.size()) this.reload();
456
+ else this.replay(this.end);
457
+ }
458
+ /** Whether the file this reader reads is still the one being written. Checked after a read, it vouches for it. */
459
+ current() {
460
+ if (!this.reader) return true;
461
+ const sb = readSuperblock(this.file);
462
+ if (!sb) return this.readGen === null && this.file.size() <= HEADER_END;
463
+ return sb.state === ACTIVE && sb.gen === this.readGen;
464
+ }
465
+ /** Start over from whichever file is live now. */
466
+ reload() {
467
+ const a = this.name === "a" ? this.file : this.other;
468
+ const b = this.name === "a" ? this.other : this.file;
469
+ const sbA = readSuperblock(a);
470
+ const sbB = sbA?.state === ACTIVE ? null : readSuperblock(b);
471
+ let name = "a";
472
+ let sb = null;
473
+ if (sbA?.state === ACTIVE) sb = sbA;
474
+ else if (sbB?.state === ACTIVE) {
475
+ name = "b";
476
+ sb = sbB;
477
+ } else if (a.size() <= HEADER_END && b.size() > HEADER_END) name = "b";
478
+ this.name = name;
479
+ this.file = name === "a" ? a : b;
480
+ this.other = name === "a" ? b : a;
481
+ this.sb = sb ?? EMPTY_SUPERBLOCK;
482
+ this.readGen = sb ? sb.gen : null;
483
+ this.end = HEADER_END;
484
+ this.tables.clear();
485
+ this.byTid.clear();
486
+ this.nextTid = 1;
487
+ this.dirBytes = 0;
488
+ this.tailOps = 0;
489
+ if (sb === null || !this.loadDirectory()) this.resetIndex();
490
+ this.replay(this.sb.covered);
491
+ }
492
+ mustWrite() {
493
+ if (this.reader) throw new Error("rows: this store only reads");
494
+ }
495
+ applyBatch(buf, fileOff) {
496
+ const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
497
+ let p = 0;
498
+ while (p < buf.length) {
499
+ this.tailOps++;
500
+ const kind = buf[p];
501
+ const flags = buf[p + 1];
502
+ const tid = view.getUint16(p + 2, true);
503
+ if (kind === R_TABLE) {
504
+ const nameLen = view.getUint16(p + 4, true);
505
+ const name = decoder$1.decode(buf.subarray(p + 6, p + 6 + nameLen));
506
+ if (!this.byTid.has(tid)) this.addTable(name, tid);
507
+ p += 6 + nameLen;
508
+ continue;
509
+ }
510
+ const table = this.byTid.get(tid);
511
+ if (!table) throw new Error(`rows: batch names unknown table ${tid}`);
512
+ if (kind === R_CLEAR) {
513
+ this.clearTable(table);
514
+ p += 4;
515
+ continue;
516
+ }
517
+ const idLen = view.getUint16(p + 4, true);
518
+ const id = decoder$1.decode(buf.subarray(p + 6, p + 6 + idLen));
519
+ p += 6 + idLen;
520
+ if (kind === R_DEL) {
521
+ table.delta.set(id, null);
522
+ continue;
523
+ }
524
+ if (kind !== R_PUT) throw new Error(`rows: unknown record kind ${kind}`);
525
+ const rv = view.getFloat64(p, true);
526
+ const len = view.getUint32(p + 8, true);
527
+ table.delta.set(id, {
528
+ off: fileOff + p + 12,
529
+ len,
530
+ rv,
531
+ flags
532
+ });
533
+ p += 12 + len;
534
+ }
535
+ }
536
+ addTable(name, tid) {
537
+ const table = {
538
+ name,
539
+ tid,
540
+ block: null,
541
+ run: null,
542
+ delta: /* @__PURE__ */ new Map(),
543
+ unsaved: false
544
+ };
545
+ this.tables.set(name, table);
546
+ this.byTid.set(tid, table);
547
+ if (tid >= this.nextTid) this.nextTid = tid + 1;
548
+ return table;
549
+ }
550
+ clearTable(table) {
551
+ table.delta.clear();
552
+ table.unsaved = table.unsaved || table.block !== null;
553
+ table.block = null;
554
+ table.run = emptyRun();
555
+ }
556
+ /** The table's run, read from its block on first use. */
557
+ loadRun(table) {
558
+ if (table.run) return table.run;
559
+ const block = table.block;
560
+ if (!block) return table.run = emptyRun();
561
+ const buf = new Uint8Array(new ArrayBuffer(block.len));
562
+ this.file.read(buf, block.off);
563
+ if (hash32(buf) !== block.sum) throw new IndexMismatch(table.name);
564
+ return table.run = runFromBuffer(buf, block.n, block.heap, block.live);
565
+ }
566
+ /**
567
+ * Run `fn`; when it finds an index block that does not match what was
568
+ * written, rebuild the index from the log and run it again. The log still
569
+ * holds every row, so the answer is the same, only later.
570
+ */
571
+ trusted(fn) {
572
+ try {
573
+ return fn();
574
+ } catch (error) {
575
+ if (!(error instanceof IndexMismatch)) throw error;
576
+ if (this.reader) {
577
+ this.reload();
578
+ return fn();
579
+ }
580
+ this.resetIndex();
581
+ this.rebuilt = true;
582
+ this.replay(HEADER_END);
583
+ return fn();
584
+ }
585
+ }
586
+ /** The table's rows in id order, with every write folded in. */
587
+ ordered(name) {
588
+ return this.trusted(() => {
589
+ const table = this.tables.get(name);
590
+ if (!table) return emptyRun();
591
+ const run = this.loadRun(table);
592
+ if (table.delta.size === 0) return run;
593
+ table.run = mergeRun(run, table.delta);
594
+ table.delta.clear();
595
+ table.unsaved = true;
596
+ return table.run;
597
+ });
598
+ }
599
+ find(name, id) {
600
+ return this.trusted(() => {
601
+ const table = this.tables.get(name);
602
+ if (!table) return null;
603
+ const pending = table.delta.get(id);
604
+ if (pending !== void 0) return pending;
605
+ const run = this.loadRun(table);
606
+ const i = runFind(run, id);
607
+ return i < 0 ? null : {
608
+ off: run.off[i],
609
+ len: run.len[i],
610
+ rv: run.rv[i],
611
+ flags: run.flags[i]
612
+ };
613
+ });
614
+ }
615
+ /** Read `len` bytes at `off` into `into`, starting at `at`. */
616
+ readInto(off, len, into, at) {
617
+ this.file.read(into.subarray(at, at + len), off);
618
+ }
619
+ get(name, id) {
620
+ const entry = this.find(name, id);
621
+ if (!entry) return null;
622
+ const body = new Uint8Array(entry.len);
623
+ this.file.read(body, entry.off);
624
+ return {
625
+ body,
626
+ entry
627
+ };
628
+ }
629
+ count(name) {
630
+ return this.ordered(name).n;
631
+ }
632
+ /**
633
+ * The ids of a table that start with `prefix`, in order, with the prefix cut
634
+ * off. Ids are sorted, so this is one search and a walk over the matches:
635
+ * what makes a table of `value\0id` keys work as a secondary index.
636
+ */
637
+ prefix(name, prefix) {
638
+ const run = this.ordered(name);
639
+ const len = encodeProbe(prefix);
640
+ const key = probe.slice(0, len);
641
+ const out = [];
642
+ for (let i = lowerBound(run, 0, key, len); i < run.n; i++) {
643
+ const s = idStart(run, i);
644
+ const e = run.idEnd[i];
645
+ if (e - s < len || cmpBytes(run.heap, s, s + len, key, 0, len) !== 0) break;
646
+ out.push(decoder$1.decode(run.heap.subarray(s + len, e)));
647
+ }
648
+ return out;
649
+ }
650
+ /** `(id, version)` of every row, from the index alone. */
651
+ versions(name) {
652
+ const run = this.ordered(name);
653
+ const out = [];
654
+ for (let i = 0; i < run.n; i++) out.push([runId(run, i), run.rv[i]]);
655
+ return out;
656
+ }
657
+ tableNames() {
658
+ return [...this.tables.keys()].sort();
659
+ }
660
+ table(name) {
661
+ const existing = this.tables.get(name);
662
+ if (existing) return {
663
+ table: existing,
664
+ isNew: false
665
+ };
666
+ return {
667
+ table: this.addTable(name, this.nextTid),
668
+ isNew: true
669
+ };
670
+ }
671
+ /**
672
+ * Apply `ops` as one atomic batch. `sync` flushes before returning; without
673
+ * it the bytes are with the operating system (they survive the tab, not a
674
+ * power cut) until the next {@link flush}.
675
+ */
676
+ write(ops, sync = false) {
677
+ this.mustWrite();
678
+ if (this.closed) throw new Error("rows: store is closed");
679
+ if (ops.length === 0) return;
680
+ let bound = XH + 8;
681
+ for (const op of ops) {
682
+ bound += 12 + op.table.length * 3;
683
+ if (op.t !== "clear") bound += op.id.length * 3 + 6;
684
+ if (op.t === "put") bound += op.body.length + 12;
685
+ }
686
+ if (this.scratch.length < bound) this.scratch = new Uint8Array(Math.max(bound, this.scratch.length * 2));
687
+ const buf = this.scratch;
688
+ const view = new DataView(buf.buffer);
689
+ let p = XH;
690
+ const applied = [];
691
+ const created = [];
692
+ const base = this.end;
693
+ for (const op of ops) {
694
+ const { table, isNew } = this.table(op.table);
695
+ if (isNew) {
696
+ created.push(table);
697
+ buf[p] = R_TABLE;
698
+ buf[p + 1] = 0;
699
+ view.setUint16(p + 2, table.tid, true);
700
+ const written = encoder$1.encodeInto(table.name, buf.subarray(p + 6)).written;
701
+ view.setUint16(p + 4, written, true);
702
+ p += 6 + written;
703
+ }
704
+ if (op.t === "clear") {
705
+ buf[p] = R_CLEAR;
706
+ buf[p + 1] = 0;
707
+ view.setUint16(p + 2, table.tid, true);
708
+ p += 4;
709
+ applied.push(() => this.clearTable(table));
710
+ continue;
711
+ }
712
+ const idLen = encoder$1.encodeInto(op.id, buf.subarray(p + 6)).written;
713
+ if (idLen > MAX_ID_BYTES) throw new Error("rows: id longer than 65535 bytes");
714
+ view.setUint16(p + 2, table.tid, true);
715
+ view.setUint16(p + 4, idLen, true);
716
+ if (op.t === "del") {
717
+ buf[p] = R_DEL;
718
+ buf[p + 1] = 0;
719
+ p += 6 + idLen;
720
+ const id = op.id;
721
+ applied.push(() => table.delta.set(id, null));
722
+ continue;
723
+ }
724
+ buf[p] = R_PUT;
725
+ buf[p + 1] = op.flags;
726
+ p += 6 + idLen;
727
+ view.setFloat64(p, op.rv, true);
728
+ view.setUint32(p + 8, op.body.length, true);
729
+ buf.set(op.body, p + 12);
730
+ const entry = {
731
+ off: base + p + 12,
732
+ len: op.body.length,
733
+ rv: op.rv,
734
+ flags: op.flags
735
+ };
736
+ const id = op.id;
737
+ applied.push(() => table.delta.set(id, entry));
738
+ p += 12 + op.body.length;
739
+ }
740
+ try {
741
+ this.appendExtent(X_BATCH, buf, p);
742
+ } catch (error) {
743
+ for (const table of created) {
744
+ this.tables.delete(table.name);
745
+ this.byTid.delete(table.tid);
746
+ }
747
+ if (created.length > 0) this.nextTid = Math.min(...created.map((t) => t.tid));
748
+ throw error;
749
+ }
750
+ for (const apply of applied) apply();
751
+ this.tailOps += ops.length;
752
+ if (this.scratch.length > SCRATCH_KEEP) this.scratch = new Uint8Array(65536);
753
+ this.needsFlush = true;
754
+ if (sync) this.flush();
755
+ }
756
+ /**
757
+ * Frame `buf[XH..p)` as one extent and append it. `buf` must leave its first
758
+ * `XH` bytes free and have room for the padding.
759
+ */
760
+ appendExtent(type, buf, p) {
761
+ const len = p - XH;
762
+ const total = align8(p);
763
+ buf.fill(0, p, total);
764
+ const view = new DataView(buf.buffer, buf.byteOffset, XH);
765
+ view.setUint32(0, type, true);
766
+ view.setUint32(4, len, true);
767
+ view.setUint32(8, hash32(buf, XH, p), true);
768
+ view.setUint32(12, 0, true);
769
+ this.file.write(buf.subarray(0, total), this.end);
770
+ const at = this.end + XH;
771
+ this.end += total;
772
+ return at;
773
+ }
774
+ flush() {
775
+ if (!this.needsFlush || this.reader) return;
776
+ this.file.flush();
777
+ this.needsFlush = false;
778
+ }
779
+ /** Bytes of batches the next open would have to replay. */
780
+ get tailBytes() {
781
+ return this.end - this.sb.covered;
782
+ }
783
+ /**
784
+ * Persist the index: append the run of every table written since the last
785
+ * checkpoint, then a directory, then flip the superblock. Returns false when
786
+ * there was nothing to persist.
787
+ */
788
+ checkpoint() {
789
+ return this.trusted(() => this.checkpointOnce());
790
+ }
791
+ checkpointOnce() {
792
+ if (this.closed || this.reader) return false;
793
+ let dirty = this.end > this.sb.covered;
794
+ for (const table of this.tables.values()) dirty = dirty || table.delta.size > 0 || table.unsaved;
795
+ if (!dirty) return false;
796
+ for (const table of this.tables.values()) {
797
+ if (table.delta.size === 0 && !table.unsaved) continue;
798
+ const run = this.ordered(table.name);
799
+ table.block = run.n > 0 ? this.appendBlock(run) : null;
800
+ table.unsaved = false;
801
+ }
802
+ const { dirOff, dirLen, dirSum } = this.appendDirectory();
803
+ this.file.flush();
804
+ this.commitSuperblock(dirOff, dirLen, dirSum, this.end);
805
+ return true;
806
+ }
807
+ appendBlock(run) {
808
+ const head = new Uint8Array(XH);
809
+ const view = new DataView(head.buffer);
810
+ const sum = hash32(run.buf);
811
+ view.setUint32(0, X_BLOCK, true);
812
+ view.setUint32(4, run.buf.length, true);
813
+ view.setUint32(8, sum, true);
814
+ this.file.write(head, this.end);
815
+ const off = this.end + XH;
816
+ this.file.write(run.buf, off);
817
+ this.end = align8(off + run.buf.length);
818
+ if (this.file.size() < this.end) this.file.truncate(this.end);
819
+ return {
820
+ off,
821
+ len: run.buf.length,
822
+ n: run.n,
823
+ heap: run.heap.length,
824
+ sum,
825
+ live: run.live
826
+ };
827
+ }
828
+ appendDirectory() {
829
+ const tables = [...this.tables.values()].map((t) => ({
830
+ name: t.name,
831
+ tid: t.tid,
832
+ ...t.block ?? {
833
+ off: 0,
834
+ len: 0,
835
+ n: 0,
836
+ heap: 0,
837
+ sum: 0,
838
+ live: 0
839
+ }
840
+ }));
841
+ const body = encoder$1.encode(JSON.stringify({
842
+ nextTid: this.nextTid,
843
+ tables
844
+ }));
845
+ const buf = new Uint8Array(align8(XH + body.length));
846
+ buf.set(body, XH);
847
+ const dirOff = this.appendExtent(X_DIR, buf, XH + body.length);
848
+ this.dirBytes = body.length + XH;
849
+ return {
850
+ dirOff,
851
+ dirLen: body.length,
852
+ dirSum: hash32(body)
853
+ };
854
+ }
855
+ commitSuperblock(dirOff, dirLen, dirSum, covered) {
856
+ this.sb = {
857
+ ...this.sb,
858
+ seq: this.sb.seq + 1,
859
+ state: ACTIVE,
860
+ dirOff,
861
+ dirLen,
862
+ dirSum,
863
+ covered
864
+ };
865
+ writeSuperblock(this.file, this.sb);
866
+ this.file.flush();
867
+ this.needsFlush = false;
868
+ if (covered === this.end) this.tailOps = 0;
869
+ }
870
+ stats() {
871
+ let liveBytes = 0;
872
+ let indexBytes = this.dirBytes;
873
+ for (const table of this.tables.values()) {
874
+ const block = table.block;
875
+ const run = table.run;
876
+ if (run) liveBytes += run.live + RECORD_BYTES * run.n + run.heap.length;
877
+ else if (block) liveBytes += block.live + RECORD_BYTES * block.n + block.heap;
878
+ if (block) indexBytes += block.len + XH;
879
+ }
880
+ const fileBytes = this.end;
881
+ return {
882
+ file: this.name,
883
+ fileBytes,
884
+ liveBytes,
885
+ indexBytes,
886
+ garbageBytes: Math.max(0, fileBytes - HEADER_END - liveBytes - indexBytes),
887
+ tailBytes: this.tailBytes,
888
+ tailOps: this.tailOps,
889
+ tables: this.tables.size,
890
+ rebuilt: this.rebuilt
891
+ };
892
+ }
893
+ /**
894
+ * Copy every live row into the other file, in id order, and switch to it.
895
+ * The switch is one superblock write in the old file; a crash before it
896
+ * leaves the old file as it was, a crash after it finds the new one whole.
897
+ */
898
+ async compact() {
899
+ this.mustWrite();
900
+ if (this.closed) throw new Error("rows: store is closed");
901
+ for (const name of [...this.tables.keys()]) this.ordered(name);
902
+ const src = this.file;
903
+ const dst = this.other ?? await this.io.open(this.name === "a" ? "b" : "a");
904
+ dst.truncate(0);
905
+ const next = new RowStore(this.io, dst, this.name === "a" ? "b" : "a", src, {
906
+ seq: 0,
907
+ state: ACTIVE,
908
+ dirOff: 0,
909
+ dirLen: 0,
910
+ dirSum: 0,
911
+ covered: HEADER_END,
912
+ gen: this.sb.gen + 1
913
+ }, HEADER_END);
914
+ const chunk = new Uint8Array(COMPACT_CHUNK + XH + 8);
915
+ const view = new DataView(chunk.buffer);
916
+ for (const table of this.tables.values()) {
917
+ const run = this.ordered(table.name);
918
+ const copy = next.addTable(table.name, table.tid);
919
+ const moved = new Uint8Array(new ArrayBuffer(run.buf.length));
920
+ moved.set(run.buf);
921
+ const out = runFromBuffer(moved, run.n, run.heap.length, run.live);
922
+ let p = XH;
923
+ let first = 0;
924
+ const emit = () => {
925
+ if (p === XH) return;
926
+ const at = next.appendExtent(X_BATCH, chunk, p);
927
+ for (let k = first; k < pending; k++) out.off[k] += at - XH;
928
+ first = pending;
929
+ p = XH;
930
+ };
931
+ let pending = 0;
932
+ chunk[p] = R_TABLE;
933
+ chunk[p + 1] = 0;
934
+ view.setUint16(p + 2, table.tid, true);
935
+ const nameLen = encoder$1.encodeInto(table.name, chunk.subarray(p + 6)).written;
936
+ view.setUint16(p + 4, nameLen, true);
937
+ p += 6 + nameLen;
938
+ for (let i = 0; i < run.n; i++) {
939
+ const s = idStart(run, i);
940
+ const idLen = run.idEnd[i] - s;
941
+ const size = RECORD_BYTES + idLen + run.len[i];
942
+ if (size > COMPACT_CHUNK) throw new Error("rows: row larger than a compaction chunk");
943
+ if (p + size > COMPACT_CHUNK + XH) emit();
944
+ chunk[p] = R_PUT;
945
+ chunk[p + 1] = run.flags[i];
946
+ view.setUint16(p + 2, table.tid, true);
947
+ view.setUint16(p + 4, idLen, true);
948
+ chunk.set(run.heap.subarray(s, s + idLen), p + 6);
949
+ p += 6 + idLen;
950
+ view.setFloat64(p, run.rv[i], true);
951
+ view.setUint32(p + 8, run.len[i], true);
952
+ src.read(chunk.subarray(p + 12, p + 12 + run.len[i]), run.off[i]);
953
+ out.off[i] = p + 12;
954
+ p += 12 + run.len[i];
955
+ pending = i + 1;
956
+ }
957
+ emit();
958
+ copy.run = out;
959
+ copy.block = out.n > 0 ? next.appendBlock(out) : null;
960
+ }
961
+ next.nextTid = this.nextTid;
962
+ const { dirOff, dirLen, dirSum } = next.appendDirectory();
963
+ dst.flush();
964
+ next.commitSuperblock(dirOff, dirLen, dirSum, next.end);
965
+ writeSuperblock(src, {
966
+ ...this.sb,
967
+ seq: this.sb.seq + 1,
968
+ state: MOVED
969
+ });
970
+ src.flush();
971
+ src.truncate(HEADER_END);
972
+ this.file = dst;
973
+ this.other = src;
974
+ this.name = next.name;
975
+ this.sb = next.sb;
976
+ this.end = next.end;
977
+ this.tables = next.tables;
978
+ this.byTid = next.byTid;
979
+ this.dirBytes = next.dirBytes;
980
+ this.tailOps = 0;
981
+ this.needsFlush = false;
982
+ }
983
+ close() {
984
+ if (this.closed) return;
985
+ this.flush();
986
+ this.closed = true;
987
+ this.file.close();
988
+ this.other?.close();
989
+ }
990
+ };
991
+ /** A {@link SyncFile} held in memory: tests, and the store's memory mode. */
992
+ var MemoryFile = class MemoryFile {
993
+ bytes = new Uint8Array(65536);
994
+ length = 0;
995
+ flushes = 0;
996
+ read(buffer, at) {
997
+ const n = Math.max(0, Math.min(buffer.length, this.length - at));
998
+ if (n > 0) buffer.set(this.bytes.subarray(at, at + n));
999
+ if (n < buffer.length) buffer.fill(0, n);
1000
+ return n;
1001
+ }
1002
+ write(buffer, at) {
1003
+ const end = at + buffer.length;
1004
+ if (end > this.bytes.length) {
1005
+ const grown = new Uint8Array(Math.max(end, this.bytes.length * 2));
1006
+ grown.set(this.bytes.subarray(0, this.length));
1007
+ this.bytes = grown;
1008
+ }
1009
+ if (at > this.length) this.bytes.fill(0, this.length, at);
1010
+ this.bytes.set(buffer, at);
1011
+ if (end > this.length) this.length = end;
1012
+ return buffer.length;
1013
+ }
1014
+ size() {
1015
+ return this.length;
1016
+ }
1017
+ truncate(size) {
1018
+ if (size > this.bytes.length) {
1019
+ const grown = new Uint8Array(size);
1020
+ grown.set(this.bytes.subarray(0, this.length));
1021
+ this.bytes = grown;
1022
+ }
1023
+ if (size > this.length) this.bytes.fill(0, this.length, size);
1024
+ this.length = size;
1025
+ }
1026
+ flush() {
1027
+ this.flushes++;
1028
+ }
1029
+ close() {}
1030
+ /** The file's bytes, for tests that damage them. */
1031
+ snapshot() {
1032
+ return this.bytes.slice(0, this.length);
1033
+ }
1034
+ static from(bytes) {
1035
+ const file = new MemoryFile();
1036
+ file.write(bytes, 0);
1037
+ return file;
1038
+ }
1039
+ };
1040
+
1041
+ //#endregion
1042
+ //#region src/services/database/cache-engine.ts
1043
+ /** Thrown when relation decomposition nests past {@link MAX_RELATION_DEPTH} —
1044
+ * a guard against a cyclic schema producing unbounded fan-out. */
1045
+ var RelationCycleError = class extends Error {
1046
+ constructor(path) {
1047
+ super(`Relation nesting exceeded safe depth; possible cyclic schema: ${path.join(" -> ")}`);
1048
+ this.name = "RelationCycleError";
1049
+ }
1050
+ };
1051
+ /** Defensive ceiling on relation nesting depth. A finite plan tree never hits
1052
+ * this in practice; it exists so a malformed/cyclic plan fails loudly instead
1053
+ * of running away. */
1054
+ const MAX_RELATION_DEPTH = 12;
1055
+
1056
+ //#endregion
1057
+ //#region src/services/database/relation-resolver.ts
1058
+ /**
1059
+ * Resolve the `.related()` tree of a query by **level-ordered, batched
1060
+ * fan-out** — the engine-neutral replacement for SurrealQL's nested
1061
+ * `(SELECT..) AS alias` projections. One batched fetch per relation per level
1062
+ * (never per-row N+1, never a flat join); grouping, per-parent ORDER/LIMIT and
1063
+ * attachment happen in JS.
1064
+ *
1065
+ * Correlation (mirrors `buildSubquery`):
1066
+ * - `one` → parent[`foreignKeyField`] = child.id → attach `bucket[0] ?? null`
1067
+ * - `many` → child[`foreignKeyField`] = parent.id → attach `bucket`
1068
+ *
1069
+ * Cross-level dependency is handled by ordering: a child's correlation key is a
1070
+ * field on its parent, known only once the parent level has resolved, so each
1071
+ * level's batch runs after the previous level's rows exist. `parents` is
1072
+ * mutated in place — each resolved alias is appended LAST so key order matches
1073
+ * SurrealQL's `SELECT *, <sub> AS alias` (base fields, then alias).
1074
+ *
1075
+ * @throws {RelationCycleError} if nesting exceeds {@link MAX_RELATION_DEPTH}.
1076
+ */
1077
+ async function resolveRelations(parents, relations, fetcher, depth = 0, path = []) {
1078
+ if (!relations || relations.length === 0 || parents.length === 0) return;
1079
+ if (depth >= MAX_RELATION_DEPTH) throw new RelationCycleError([...path, relations.map((r) => r.alias).join("|")]);
1080
+ await Promise.all(relations.map((relation) => resolveOne(parents, relation, fetcher, depth, path)));
1081
+ }
1082
+ async function resolveOne(parents, relation, fetcher, depth, path) {
1083
+ const isOne = relation.cardinality === "one";
1084
+ const matchField = isOne ? "id" : relation.foreignKeyField;
1085
+ const parentKeyOf = (parent) => isOne ? parent[relation.foreignKeyField] : parent["id"];
1086
+ const keySet = /* @__PURE__ */ new Map();
1087
+ for (const parent of parents) {
1088
+ const key = parentKeyOf(parent);
1089
+ if (key == null) continue;
1090
+ if (isOne && !looksLikeRecordId(key)) continue;
1091
+ const k = stableKey(key);
1092
+ if (!keySet.has(k)) keySet.set(k, key);
1093
+ }
1094
+ const grouped = /* @__PURE__ */ new Map();
1095
+ if (keySet.size > 0) {
1096
+ const children = await fetcher.fetchRelation({
1097
+ table: relation.table,
1098
+ matchField,
1099
+ keys: [...keySet.values()],
1100
+ where: relation.where,
1101
+ orderBy: relation.orderBy,
1102
+ select: relation.select
1103
+ });
1104
+ await resolveRelations(children, relation.relations, fetcher, depth + 1, [...path, relation.alias]);
1105
+ for (const child of children) {
1106
+ const k = stableKey(child[matchField]);
1107
+ const bucket = grouped.get(k);
1108
+ if (bucket) bucket.push(child);
1109
+ else grouped.set(k, [child]);
1110
+ }
1111
+ }
1112
+ for (const parent of parents) {
1113
+ const key = parentKeyOf(parent);
1114
+ let bucket = key == null ? [] : grouped.get(stableKey(key)) ?? [];
1115
+ if (relation.orderBy && relation.orderBy.length > 0) bucket = sortRows(bucket, relation.orderBy);
1116
+ if (relation.limit !== void 0) bucket = bucket.slice(0, relation.limit);
1117
+ if (isOne) {
1118
+ const raw = parent[relation.alias];
1119
+ const keepRaw = relation.alias === relation.foreignKeyField && raw != null && !looksLikeRecordId(raw);
1120
+ parent[relation.alias] = bucket[0] ?? (keepRaw ? raw : null);
1121
+ } else parent[relation.alias] = bucket;
1122
+ }
1123
+ }
1124
+ /**
1125
+ * Whether a correlation value can address a record: a RecordId (duck-typed) or
1126
+ * a `table:id` string. Anything else (a plain display string, a number) cannot
1127
+ * be the target of a to-one relation and is skipped rather than fetched.
1128
+ */
1129
+ function looksLikeRecordId(value) {
1130
+ if (value == null) return false;
1131
+ if (typeof value === "string") return /^[A-Za-z_][A-Za-z0-9_]*:.+/.test(value);
1132
+ if (typeof value === "object") return recordIdKey(value) !== null;
1133
+ return false;
1134
+ }
1135
+ /**
1136
+ * The raw `table:id` key of a RecordId, duck-typed: the SDK 1.x shape
1137
+ * `{ tb, id }` or the SDK 2.x one, whose `table` is a `Table` (both behind
1138
+ * getters). `null` for anything else.
1139
+ *
1140
+ * Never the SDK's `toString()`: that is SurrealQL, escaped. SDK 2.1.0 escapes
1141
+ * every key that starts with a digit (`game:⟨476g…⟩`), while the store and
1142
+ * server membership spell the same id `game:476g…`, so a key built from
1143
+ * `toString()` silently missed about a quarter of random ids. A complex
1144
+ * (array/object) key has no raw spelling and returns `null`.
1145
+ */
1146
+ function recordIdKey(value) {
1147
+ const rid = value;
1148
+ if (rid.id === void 0) return null;
1149
+ if (rid.tb !== void 0) return `${String(rid.tb)}:${stableKey(rid.id)}`;
1150
+ const proto = Object.getPrototypeOf(value);
1151
+ if (proto === Object.prototype || proto === null) return null;
1152
+ const name = rid.table?.name;
1153
+ if (typeof rid.table !== "object" || typeof name !== "string") return null;
1154
+ if (typeof rid.id === "string" || typeof rid.id === "number" || typeof rid.id === "bigint") return `${name}:${String(rid.id)}`;
1155
+ return null;
1156
+ }
1157
+ /**
1158
+ * Stable grouping key for a correlation value. A `RecordId` (duck-typed to
1159
+ * avoid a hard surrealdb dependency here) and its `table:id` string form must
1160
+ * collapse to the same key so a parent FK stored either way matches the child.
1161
+ */
1162
+ function stableKey(value) {
1163
+ if (value == null) return "\0null";
1164
+ if (typeof value === "string") return value;
1165
+ if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") return String(value);
1166
+ if (typeof value === "object") {
1167
+ const key = recordIdKey(value);
1168
+ if (key !== null) return key;
1169
+ const rid = value;
1170
+ if (typeof rid.toString === "function") {
1171
+ const s = rid.toString();
1172
+ if (s !== "[object Object]") return s;
1173
+ }
1174
+ return JSON.stringify(value);
1175
+ }
1176
+ return String(value);
1177
+ }
1178
+ /**
1179
+ * Stable, multi-key sort matching SurrealQL `ORDER BY` semantics closely
1180
+ * enough for cache display order: ascending null-last, type-aware compare, and
1181
+ * a stable tiebreak (original index) so equal rows keep input order.
1182
+ */
1183
+ function sortRows(rows, orderBy) {
1184
+ const indexed = rows.map((row, i) => [row, i]);
1185
+ indexed.sort((a, b) => {
1186
+ for (const [field, direction] of orderBy) {
1187
+ const cmp = compareValues(a[0][field], b[0][field]);
1188
+ if (cmp !== 0) return direction === "desc" ? -cmp : cmp;
1189
+ }
1190
+ return a[1] - b[1];
1191
+ });
1192
+ return indexed.map(([row]) => row);
1193
+ }
1194
+ function compareValues(a, b) {
1195
+ if (a == null && b == null) return 0;
1196
+ if (a == null) return 1;
1197
+ if (b == null) return -1;
1198
+ if (typeof a === "number" && typeof b === "number") return a - b;
1199
+ const as = stableKey(a);
1200
+ const bs = stableKey(b);
1201
+ return as < bs ? -1 : as > bs ? 1 : 0;
1202
+ }
1203
+
1204
+ //#endregion
1205
+ //#region src/services/database/sqlite-plan-sql.ts
1206
+ /** A comparable scalar for SQL binding: record links → `table:id`, everything
1207
+ * else passed through (numbers/strings/bools). */
1208
+ function scalar(value) {
1209
+ if (value == null) return null;
1210
+ if (typeof value === "object") return stableKey(value);
1211
+ return value;
1212
+ }
1213
+ function project(row, fields) {
1214
+ const out = {};
1215
+ for (const f of ["id", ...fields]) if (f in row) out[f] = row[f];
1216
+ return out;
1217
+ }
1218
+
1219
+ //#endregion
1220
+ //#region src/services/database/rows-exec.ts
1221
+ const encoder = new TextEncoder();
1222
+ const decoder = new TextDecoder();
1223
+ const MAX_GAP = 4096;
1224
+ const MAX_RANGE = 4 << 20;
1225
+ /** Tables the store keeps for itself start with this; no client table can. */
1226
+ const HIDDEN = "";
1227
+ const META_TABLE = `${HIDDEN}meta`;
1228
+ const INDEXES_ROW = "indexes";
1229
+ const SEP = "\0";
1230
+ const MAX_KEY_CHARS = 200;
1231
+ /** An index build writes its entries in batches of this many. */
1232
+ const INDEX_BATCH = 2e4;
1233
+ /** A value that addresses a record: `table:id`, and not a URL. */
1234
+ const LINK = /^[A-Za-z_][A-Za-z0-9_]*:(?!\/\/).{1,80}$/s;
1235
+ const NO_ENTRY = new Uint8Array(0);
1236
+ const indexTable = (table, field) => `${HIDDEN}i${HIDDEN}${table}${HIDDEN}${field}`;
1237
+ /** Tables that get indexes: the app's own. The client's `_00_` tables are small and read whole. */
1238
+ const isUserTable = (table) => !table.startsWith("_00_") && !table.startsWith(HIDDEN);
1239
+ /** The tables a client may see: everything but the store's own. */
1240
+ const visibleTables = (store) => store.tableNames().filter((t) => !t.startsWith(HIDDEN));
1241
+ /** A value as an index key, or `null` when it is not indexed (NULL, very long, or holding the separator). */
1242
+ function indexKey(value) {
1243
+ if (value === null) return null;
1244
+ const key = typeof value === "number" ? `n${value}` : `s${value}`;
1245
+ return key.length > MAX_KEY_CHARS || key.includes(SEP) ? null : key;
1246
+ }
1247
+ const U8_TAG = "\"__u8\"";
1248
+ function walk(row, field) {
1249
+ if (!field.includes(".") && !field.includes("[")) return row !== null && typeof row === "object" ? row[field] : void 0;
1250
+ let cur = row;
1251
+ for (const part of field.split(".")) {
1252
+ const m = /^([^[]*)((?:\[\d+\])*)$/.exec(part);
1253
+ if (!m) return void 0;
1254
+ if (m[1] !== "") {
1255
+ if (cur === null || typeof cur !== "object" || Array.isArray(cur)) return void 0;
1256
+ cur = cur[m[1]];
1257
+ }
1258
+ for (const idx of m[2].matchAll(/\[(\d+)\]/g)) {
1259
+ if (!Array.isArray(cur)) return void 0;
1260
+ cur = cur[Number(idx[1])];
1261
+ }
1262
+ }
1263
+ return cur;
1264
+ }
1265
+ /** `json_extract(data, '$.<field>')`, or the id column for `id`. */
1266
+ function extract(row, field) {
1267
+ const v = walk(row, field);
1268
+ if (v === null || v === void 0) return null;
1269
+ if (typeof v === "number" || typeof v === "string") return v;
1270
+ if (typeof v === "boolean") return v ? 1 : 0;
1271
+ return JSON.stringify(v);
1272
+ }
1273
+ /** A bound parameter, after `scalar()` and SQLite's binding rules. */
1274
+ function bound(value, forId) {
1275
+ const v = scalar(value);
1276
+ if (v === null || v === void 0) return null;
1277
+ if (typeof v === "boolean") return v ? 1 : 0;
1278
+ if (typeof v === "bigint") return Number(v);
1279
+ if (typeof v === "number") return forId ? String(v) : v;
1280
+ return String(v);
1281
+ }
1282
+ function sqlCompare(a, b) {
1283
+ const an = typeof a === "number";
1284
+ const bn = typeof b === "number";
1285
+ if (an && bn) return a < b ? -1 : a > b ? 1 : 0;
1286
+ if (an) return -1;
1287
+ if (bn) return 1;
1288
+ return cmpText(a, b);
1289
+ }
1290
+ /** The value a comparison binds: the query's own param when it has one, else the baked literal. */
1291
+ function rhsOf(c, params) {
1292
+ return bound(c.paramRef !== void 0 && (c.value === void 0 || Object.prototype.hasOwnProperty.call(params, c.paramRef)) ? params[c.paramRef] : c.value, c.field === "id");
1293
+ }
1294
+ function compileComparison(c, params) {
1295
+ const rhs = rhsOf(c, params);
1296
+ const field = c.field;
1297
+ const sign = c.swap ? -1 : 1;
1298
+ let test;
1299
+ switch (c.op) {
1300
+ case "=":
1301
+ test = (cmp) => cmp === 0;
1302
+ break;
1303
+ case "!=":
1304
+ test = (cmp) => cmp !== 0;
1305
+ break;
1306
+ case "<":
1307
+ test = (cmp) => cmp < 0;
1308
+ break;
1309
+ case "<=":
1310
+ test = (cmp) => cmp <= 0;
1311
+ break;
1312
+ case ">":
1313
+ test = (cmp) => cmp > 0;
1314
+ break;
1315
+ case ">=":
1316
+ test = (cmp) => cmp >= 0;
1317
+ break;
1318
+ default: throw new Error(`rows: unsupported comparison operator ${String(c.op)}`);
1319
+ }
1320
+ if (rhs === null) return () => false;
1321
+ return (row) => {
1322
+ const lhs = extract(row, field);
1323
+ return lhs !== null && test(sign * sqlCompare(lhs, rhs));
1324
+ };
1325
+ }
1326
+ /** The filter a WHERE describes; `null` when there is none. */
1327
+ function compileWhere(nodes, params) {
1328
+ if (!nodes || nodes.length === 0) return null;
1329
+ const tests = nodes.map((node) => {
1330
+ if ("or" in node) {
1331
+ const any = node.or.map((c) => compileComparison(c, params));
1332
+ return (row) => any.some((t) => t(row));
1333
+ }
1334
+ return compileComparison(node, params);
1335
+ });
1336
+ return tests.length === 1 ? tests[0] : (row) => tests.every((t) => t(row));
1337
+ }
1338
+ /** Sort as `ORDER BY json_extract(…)` does; ties fall back to the id. */
1339
+ function sortSql(rows, orderBy) {
1340
+ const keyed = rows.map((row) => ({
1341
+ row,
1342
+ keys: orderBy.map(([field]) => extract(row, field))
1343
+ }));
1344
+ keyed.sort((a, b) => {
1345
+ for (let i = 0; i < orderBy.length; i++) {
1346
+ const x = a.keys[i];
1347
+ const y = b.keys[i];
1348
+ const cmp = x === null ? y === null ? 0 : -1 : y === null ? 1 : sqlCompare(x, y);
1349
+ if (cmp !== 0) return orderBy[i][1] === "desc" ? -cmp : cmp;
1350
+ }
1351
+ return cmpText(String(a.row.id), String(b.row.id));
1352
+ });
1353
+ return keyed.map((k) => k.row);
1354
+ }
1355
+ /** `json_patch(target, patch)`: RFC 7396. A `null` member removes its key. */
1356
+ function mergePatch(target, patch) {
1357
+ if (patch === null || typeof patch !== "object" || Array.isArray(patch)) return patch;
1358
+ const out = target !== null && typeof target === "object" && !Array.isArray(target) ? target : {};
1359
+ for (const key of Object.keys(patch)) {
1360
+ const value = patch[key];
1361
+ if (value === null) delete out[key];
1362
+ else out[key] = mergePatch(out[key], value);
1363
+ }
1364
+ return out;
1365
+ }
1366
+ function toBytes(rows) {
1367
+ const text = JSON.stringify(rows);
1368
+ return {
1369
+ buf: encoder.encode(text).buffer,
1370
+ u8: text.includes(U8_TAG)
1371
+ };
1372
+ }
1373
+ var RowsExec = class {
1374
+ /** table -> field -> `true` indexed, `false` looked at and left to scans. */
1375
+ indexes = /* @__PURE__ */ new Map();
1376
+ /** table -> fields seen holding something that is not a link. Not persisted: a guess that saves a regex per row. */
1377
+ plain = /* @__PURE__ */ new Map();
1378
+ scratch = new Uint8Array(262144);
1379
+ /** Relation fetches of the request in flight, for the engine's stats. */
1380
+ relationFetches = 0;
1381
+ /** Where the registry row read last lies in the file; tells a reader when the writer has changed it. */
1382
+ registryAt = -1;
1383
+ /**
1384
+ * `readOnly` is for a store opened as a reader (a follower tab on the
1385
+ * leader's file): it uses the indexes the writer keeps and builds none.
1386
+ */
1387
+ constructor(store, readOnly = false) {
1388
+ this.store = store;
1389
+ this.readOnly = readOnly;
1390
+ this.syncRegistry();
1391
+ }
1392
+ /** Read the index registry, again when the store's writer has rewritten it. */
1393
+ syncRegistry() {
1394
+ const at = this.store.find(META_TABLE, INDEXES_ROW)?.off ?? -1;
1395
+ if (at === this.registryAt) return;
1396
+ this.registryAt = at;
1397
+ this.indexes.clear();
1398
+ const saved = at < 0 ? null : this.store.get(META_TABLE, INDEXES_ROW);
1399
+ if (!saved) return;
1400
+ try {
1401
+ const parsed = JSON.parse(decoder.decode(saved.body));
1402
+ for (const [table, fields] of Object.entries(parsed)) this.indexes.set(table, new Map(Object.entries(fields)));
1403
+ } catch {}
1404
+ }
1405
+ /** The bodies of `entries` as one JSON array, straight from the file. */
1406
+ concat(entries) {
1407
+ let total = 2;
1408
+ for (const e of entries) total += e.len + 1;
1409
+ if (entries.length > 0) total--;
1410
+ const bytes = new Uint8Array(new ArrayBuffer(Math.max(total, 2)));
1411
+ let p = 0;
1412
+ let u8 = false;
1413
+ bytes[p++] = 91;
1414
+ for (let i = 0; i < entries.length; i++) {
1415
+ const e = entries[i];
1416
+ if (i > 0) bytes[p++] = 44;
1417
+ this.store.readInto(e.off, e.len, bytes, p);
1418
+ p += e.len;
1419
+ if (e.flags & FLAG_U8) u8 = true;
1420
+ }
1421
+ bytes[p] = 93;
1422
+ return {
1423
+ bytes,
1424
+ u8
1425
+ };
1426
+ }
1427
+ raw(entries) {
1428
+ const { bytes, u8 } = this.concat(entries);
1429
+ return {
1430
+ buf: bytes.buffer,
1431
+ u8
1432
+ };
1433
+ }
1434
+ parse(entries) {
1435
+ if (entries.length === 0) return [];
1436
+ return JSON.parse(decoder.decode(this.concat(entries).bytes));
1437
+ }
1438
+ findAll(table, keys) {
1439
+ const out = [];
1440
+ for (const key of keys) {
1441
+ const entry = this.store.find(table, key);
1442
+ if (entry && !(entry.flags & FLAG_RAW)) out.push(entry);
1443
+ }
1444
+ return out;
1445
+ }
1446
+ /**
1447
+ * Visit every row of a table. The file is read in offset order, a range of
1448
+ * megabytes at a time, and each range is parsed in one call: the bytes
1449
+ * between two bodies (record heads, dead rows) are blanked in the buffer and
1450
+ * one of them becomes the comma. `visit` returns false to stop.
1451
+ */
1452
+ scan(table, visit) {
1453
+ const run = this.store.ordered(table);
1454
+ if (run.n === 0) return;
1455
+ const order = run.byOff ?? (run.byOff = byOffset(run));
1456
+ let k = 0;
1457
+ while (k < order.length) {
1458
+ const first = k;
1459
+ const start = run.off[order[k]] - 1;
1460
+ let end = run.off[order[k]] + run.len[order[k]];
1461
+ k++;
1462
+ while (k < order.length) {
1463
+ const i = order[k];
1464
+ if (run.off[i] - end > MAX_GAP || run.off[i] + run.len[i] - start > MAX_RANGE) break;
1465
+ end = run.off[i] + run.len[i];
1466
+ k++;
1467
+ }
1468
+ const size = end - start + 1;
1469
+ if (this.scratch.length < size) this.scratch = new Uint8Array(size);
1470
+ const buf = this.scratch;
1471
+ this.store.readInto(start, end - start, buf, 0);
1472
+ buf[0] = 91;
1473
+ buf[size - 1] = 93;
1474
+ let p = run.off[order[first]] + run.len[order[first]] - start;
1475
+ for (let j = first + 1; j < k; j++) {
1476
+ const rel = run.off[order[j]] - start;
1477
+ buf[p] = 44;
1478
+ buf.fill(32, p + 1, rel);
1479
+ p = rel + run.len[order[j]];
1480
+ }
1481
+ const rows = JSON.parse(decoder.decode(buf.subarray(0, size)));
1482
+ for (let j = first; j < k; j++) if (visit(rows[j - first], order[j], run) === false) return;
1483
+ }
1484
+ if (this.scratch.length > MAX_RANGE * 2) this.scratch = new Uint8Array(262144);
1485
+ }
1486
+ fieldsOf(table) {
1487
+ const fields = this.indexes.get(table);
1488
+ if (!fields) return [];
1489
+ const out = [];
1490
+ for (const [field, on] of fields) if (on) out.push(field);
1491
+ return out;
1492
+ }
1493
+ keysOf(fields, row) {
1494
+ return fields.map((field) => row ? indexKey(extract(row, field)) : null);
1495
+ }
1496
+ /** Move a row's index entries from its old keys to its new ones. */
1497
+ reindex(table, id, fields, before, after, out) {
1498
+ for (let i = 0; i < fields.length; i++) {
1499
+ if (before[i] === after[i]) continue;
1500
+ const index = indexTable(table, fields[i]);
1501
+ if (before[i] !== null) out.push({
1502
+ t: "del",
1503
+ table: index,
1504
+ id: before[i] + SEP + id
1505
+ });
1506
+ if (after[i] !== null) out.push({
1507
+ t: "put",
1508
+ table: index,
1509
+ id: after[i] + SEP + id,
1510
+ rv: 0,
1511
+ flags: FLAG_RAW,
1512
+ body: NO_ENTRY
1513
+ });
1514
+ }
1515
+ }
1516
+ registryOp() {
1517
+ const all = {};
1518
+ for (const [table, fields] of this.indexes) all[table] = Object.fromEntries(fields);
1519
+ return {
1520
+ t: "put",
1521
+ table: META_TABLE,
1522
+ id: INDEXES_ROW,
1523
+ rv: 0,
1524
+ flags: FLAG_RAW,
1525
+ body: encoder.encode(JSON.stringify(all))
1526
+ };
1527
+ }
1528
+ mark(table, field, on) {
1529
+ let fields = this.indexes.get(table);
1530
+ if (!fields) this.indexes.set(table, fields = /* @__PURE__ */ new Map());
1531
+ fields.set(field, on);
1532
+ }
1533
+ /** Fields of `row` that hold a record link and have no index yet: they get one now. */
1534
+ discover(table, row, added) {
1535
+ const fields = this.indexes.get(table);
1536
+ let plain = this.plain.get(table);
1537
+ for (const field in row) {
1538
+ const value = row[field];
1539
+ if (typeof value !== "string" || field === "id" || fields?.has(field) || plain?.has(field)) continue;
1540
+ if (LINK.test(value)) {
1541
+ this.mark(table, field, true);
1542
+ added.push([table, field]);
1543
+ } else {
1544
+ if (!plain) this.plain.set(table, plain = /* @__PURE__ */ new Set());
1545
+ plain.add(field);
1546
+ }
1547
+ }
1548
+ }
1549
+ /**
1550
+ * Whether `field` of `table` has an index, building it if it has none yet:
1551
+ * one scan, written to the store, kept up by every write after. Without
1552
+ * `force`, a field with too few distinct values to be worth one is turned
1553
+ * down, and that answer is remembered too.
1554
+ */
1555
+ ensureIndex(table, field, force) {
1556
+ const known = this.indexes.get(table)?.get(field);
1557
+ if (known === true) return true;
1558
+ if (known === false && !force) return false;
1559
+ if (this.readOnly) return false;
1560
+ const index = indexTable(table, field);
1561
+ const puts = [];
1562
+ const distinct = /* @__PURE__ */ new Set();
1563
+ let rows = 0;
1564
+ this.scan(table, (row) => {
1565
+ rows++;
1566
+ const key = indexKey(extract(row, field));
1567
+ if (key === null) return;
1568
+ distinct.add(key);
1569
+ puts.push({
1570
+ t: "put",
1571
+ table: index,
1572
+ id: key + SEP + String(row.id),
1573
+ rv: 0,
1574
+ flags: FLAG_RAW,
1575
+ body: NO_ENTRY
1576
+ });
1577
+ });
1578
+ const worth = force || rows < 64 || distinct.size >= 8;
1579
+ this.mark(table, field, worth);
1580
+ if (!worth) {
1581
+ this.store.write([this.registryOp()]);
1582
+ return false;
1583
+ }
1584
+ for (let i = 0; i < puts.length; i += INDEX_BATCH) this.store.write(puts.slice(i, i + INDEX_BATCH));
1585
+ this.store.write([this.registryOp()]);
1586
+ return true;
1587
+ }
1588
+ lookup(table, field, key) {
1589
+ return this.store.prefix(indexTable(table, field), key + SEP);
1590
+ }
1591
+ /**
1592
+ * The rows a filter can possibly match, when an index can say so without
1593
+ * reading the table: an `id = …`, or an `=` on an indexed field. In id
1594
+ * order. `null` means read the table.
1595
+ */
1596
+ narrow(table, where, params) {
1597
+ if (!where) return null;
1598
+ for (const node of where) {
1599
+ if ("or" in node || node.op !== "=") continue;
1600
+ const value = rhsOf(node, params);
1601
+ if (value === null) return [];
1602
+ if (node.field === "id") return this.findAll(table, [String(value)]);
1603
+ if (!isUserTable(table)) continue;
1604
+ const key = indexKey(value);
1605
+ if (key === null || !this.ensureIndex(table, node.field, false)) continue;
1606
+ const ids = this.lookup(table, node.field, key);
1607
+ if (ids.length > Math.max(256, this.store.count(table) / 3)) continue;
1608
+ return this.findAll(table, ids);
1609
+ }
1610
+ return null;
1611
+ }
1612
+ /** Rows matching `where`, as (row, entry) in the order SQL would give them. */
1613
+ filtered(table, where, params, orderBy, limit, offset) {
1614
+ const test = compileWhere(where, params);
1615
+ const ordered = orderBy !== void 0 && orderBy.length > 0;
1616
+ const from = offset ?? 0;
1617
+ const to = limit === void 0 ? void 0 : from + limit;
1618
+ const narrowed = this.narrow(table, where, params);
1619
+ if (!narrowed && !ordered && to !== void 0) return this.firstInIdOrder(table, test, from, to);
1620
+ let rows = [];
1621
+ let entries = [];
1622
+ if (narrowed) {
1623
+ const parsed = this.parse(narrowed);
1624
+ for (let i = 0; i < parsed.length; i++) {
1625
+ if (test && !test(parsed[i])) continue;
1626
+ rows.push(parsed[i]);
1627
+ entries.push(narrowed[i]);
1628
+ }
1629
+ } else {
1630
+ const hits = [];
1631
+ let seen = null;
1632
+ this.scan(table, (row, at, run) => {
1633
+ seen = run;
1634
+ if (!test || test(row)) hits.push({
1635
+ row,
1636
+ at
1637
+ });
1638
+ });
1639
+ hits.sort((a, b) => a.at - b.at);
1640
+ const run = seen;
1641
+ rows = hits.map((h) => h.row);
1642
+ entries = run ? hits.map((h) => ({
1643
+ off: run.off[h.at],
1644
+ len: run.len[h.at],
1645
+ rv: run.rv[h.at],
1646
+ flags: run.flags[h.at]
1647
+ })) : [];
1648
+ }
1649
+ if (ordered) {
1650
+ const entryOf = /* @__PURE__ */ new Map();
1651
+ for (let i = 0; i < rows.length; i++) entryOf.set(rows[i], entries[i]);
1652
+ rows = sortSql(rows, orderBy).slice(from, to);
1653
+ return {
1654
+ rows,
1655
+ entries: rows.map((row) => entryOf.get(row))
1656
+ };
1657
+ }
1658
+ return {
1659
+ rows: rows.slice(from, to),
1660
+ entries: entries.slice(from, to)
1661
+ };
1662
+ }
1663
+ /**
1664
+ * The matches numbered `from` to `to` in id order, reading no further than
1665
+ * it has to: an unordered query with a LIMIT stops at its last row instead
1666
+ * of walking the table.
1667
+ */
1668
+ firstInIdOrder(table, test, from, to) {
1669
+ const run = this.store.ordered(table);
1670
+ const rows = [];
1671
+ const entries = [];
1672
+ let i = 0;
1673
+ let step = 64;
1674
+ while (i < run.n && rows.length < to) {
1675
+ const chunk = [];
1676
+ for (; i < run.n && chunk.length < step; i++) {
1677
+ if (run.flags[i] & FLAG_RAW) continue;
1678
+ chunk.push({
1679
+ off: run.off[i],
1680
+ len: run.len[i],
1681
+ rv: run.rv[i],
1682
+ flags: run.flags[i]
1683
+ });
1684
+ }
1685
+ const parsed = this.parse(chunk);
1686
+ for (let j = 0; j < parsed.length && rows.length < to; j++) {
1687
+ if (test && !test(parsed[j])) continue;
1688
+ rows.push(parsed[j]);
1689
+ entries.push(chunk[j]);
1690
+ }
1691
+ step = Math.min(step * 2, 2048);
1692
+ }
1693
+ return {
1694
+ rows: rows.slice(from),
1695
+ entries: entries.slice(from)
1696
+ };
1697
+ }
1698
+ async select(plan, params) {
1699
+ this.relationFetches = 0;
1700
+ const shaped = plan.select !== void 0 || plan.relations !== void 0 && plan.relations.length > 0;
1701
+ let rows;
1702
+ if (plan.ids) {
1703
+ const entries = this.findAll(plan.table, windowOrder(plan.ids.map(stableKey)));
1704
+ const ordered = plan.orderBy !== void 0 && plan.orderBy.length > 0;
1705
+ if (!shaped && !ordered) return {
1706
+ ...this.raw(entries),
1707
+ relationFetches: 0
1708
+ };
1709
+ rows = this.parse(entries);
1710
+ if (ordered) rows = sortSql(rows, plan.orderBy);
1711
+ } else {
1712
+ const hit = this.filtered(plan.table, plan.where, params, plan.orderBy, plan.limit, plan.offset);
1713
+ if (!shaped) return {
1714
+ ...this.raw(hit.entries),
1715
+ relationFetches: 0
1716
+ };
1717
+ rows = hit.rows;
1718
+ }
1719
+ if (plan.select) rows = rows.map((row) => project(row, plan.select));
1720
+ await resolveRelations(rows, plan.relations, { fetchRelation: (req) => {
1721
+ this.relationFetches++;
1722
+ return Promise.resolve(this.relationRows(req));
1723
+ } });
1724
+ return {
1725
+ ...toBytes(rows),
1726
+ relationFetches: this.relationFetches
1727
+ };
1728
+ }
1729
+ byIds(table, ids, select, orderBy) {
1730
+ const entries = this.findAll(table, windowOrder(ids));
1731
+ const ordered = orderBy !== void 0 && orderBy.length > 0;
1732
+ if (!select && !ordered) return this.raw(entries);
1733
+ let rows = this.parse(entries);
1734
+ if (ordered) rows = sortSql(rows, orderBy);
1735
+ return toBytes(select ? rows.map((row) => project(row, select)) : rows);
1736
+ }
1737
+ get(table, id) {
1738
+ const hit = this.store.get(table, id);
1739
+ if (!hit || hit.entry.flags & FLAG_RAW) return {
1740
+ buf: null,
1741
+ u8: false
1742
+ };
1743
+ return {
1744
+ buf: hit.body.buffer,
1745
+ u8: (hit.entry.flags & FLAG_U8) !== 0
1746
+ };
1747
+ }
1748
+ selectTable(table, where, orderBy, limit, start) {
1749
+ return this.raw(this.filtered(table, where, {}, orderBy, limit, start).entries);
1750
+ }
1751
+ count(table, where) {
1752
+ if (!where || where.length === 0) return this.store.count(table);
1753
+ return this.filtered(table, where, {}, void 0, void 0, void 0).rows.length;
1754
+ }
1755
+ relation(req) {
1756
+ return toBytes(this.relationRows(req));
1757
+ }
1758
+ relationRows(req) {
1759
+ const keys = [...new Set(req.keys.map(stableKey))];
1760
+ let rows;
1761
+ if (req.matchField === "id") rows = this.parse(this.findAll(req.table, keys.sort(cmpText)));
1762
+ else {
1763
+ const indexKeys = keys.map((key) => indexKey(key));
1764
+ if (isUserTable(req.table) && indexKeys.every((k) => k !== null) && this.ensureIndex(req.table, req.matchField, true)) {
1765
+ const ids = [];
1766
+ for (const key of indexKeys) for (const id of this.lookup(req.table, req.matchField, key)) ids.push(id);
1767
+ rows = this.parse(this.findAll(req.table, ids.sort(cmpText)));
1768
+ } else {
1769
+ const wanted = new Set(keys);
1770
+ const hits = [];
1771
+ this.scan(req.table, (row, at) => {
1772
+ const value = walk(row, req.matchField);
1773
+ if (typeof value === "string" && wanted.has(value)) hits.push({
1774
+ row,
1775
+ at
1776
+ });
1777
+ });
1778
+ rows = hits.sort((a, b) => a.at - b.at).map((h) => h.row);
1779
+ }
1780
+ }
1781
+ const test = compileWhere(req.where, {});
1782
+ if (test) rows = rows.filter(test);
1783
+ if (req.orderBy && req.orderBy.length > 0) rows = sortSql(rows, req.orderBy);
1784
+ return req.select ? rows.map((row) => project(row, req.select)) : rows;
1785
+ }
1786
+ /**
1787
+ * Apply one batch from the page. A merge reads the stored row, folds the
1788
+ * patch in and writes the result; a row that is not there yet takes the
1789
+ * patch's insert text as it came. Index entries of the app's tables move in
1790
+ * the same batch as the rows they point at.
1791
+ */
1792
+ write(ops, buf, sync) {
1793
+ const bytes = buf ? new Uint8Array(buf) : new Uint8Array(0);
1794
+ const out = [];
1795
+ const pending = /* @__PURE__ */ new Map();
1796
+ const cleared = /* @__PURE__ */ new Set();
1797
+ const touched = /* @__PURE__ */ new Map();
1798
+ const added = [];
1799
+ const note = (table, id, row) => {
1800
+ let rows = touched.get(table);
1801
+ if (!rows) touched.set(table, rows = /* @__PURE__ */ new Map());
1802
+ rows.set(id, row);
1803
+ };
1804
+ for (const op of ops) {
1805
+ const table = op[1];
1806
+ const user = isUserTable(table);
1807
+ if (op[0] === "clear") {
1808
+ out.push({
1809
+ t: "clear",
1810
+ table
1811
+ });
1812
+ if (user) for (const field of this.fieldsOf(table)) out.push({
1813
+ t: "clear",
1814
+ table: indexTable(table, field)
1815
+ });
1816
+ cleared.add(table);
1817
+ for (const key of [...pending.keys()]) if (key.startsWith(table + "\n")) pending.delete(key);
1818
+ touched.get(table)?.clear();
1819
+ continue;
1820
+ }
1821
+ const id = op[2];
1822
+ const key = table + "\n" + id;
1823
+ const stored = () => {
1824
+ const earlier = pending.get(key);
1825
+ if (earlier !== void 0) return earlier;
1826
+ return cleared.has(table) ? null : this.store.get(table, id)?.body ?? null;
1827
+ };
1828
+ if (op[0] === "del") {
1829
+ const fields = user ? this.fieldsOf(table) : [];
1830
+ if (fields.length > 0) {
1831
+ const old = stored();
1832
+ if (old) this.reindex(table, id, fields, this.keysOf(fields, JSON.parse(decoder.decode(old))), this.keysOf(fields, null), out);
1833
+ }
1834
+ out.push({
1835
+ t: "del",
1836
+ table,
1837
+ id
1838
+ });
1839
+ pending.set(key, null);
1840
+ if (user) note(table, id, null);
1841
+ continue;
1842
+ }
1843
+ const insert = bytes.subarray(op[5], op[5] + op[6]);
1844
+ let body = insert;
1845
+ let rv = op[3];
1846
+ let flags = op[4];
1847
+ let next = null;
1848
+ let fields = user ? this.fieldsOf(table) : [];
1849
+ const old = op[0] === "merge" || fields.length > 0 ? stored() : null;
1850
+ const previous = old ? JSON.parse(decoder.decode(old)) : null;
1851
+ const before = this.keysOf(fields, previous);
1852
+ if (op[0] === "merge" && previous) {
1853
+ const patch = op[8] > 0 ? bytes.subarray(op[7], op[7] + op[8]) : insert;
1854
+ next = mergePatch(previous, JSON.parse(decoder.decode(patch)));
1855
+ const text = JSON.stringify(next);
1856
+ body = encoder.encode(text);
1857
+ rv = Number(next?._00_rv) || 0;
1858
+ flags = text.includes(U8_TAG) ? FLAG_U8 : 0;
1859
+ } else if (user) next = JSON.parse(decoder.decode(insert));
1860
+ if (user && next) {
1861
+ const known = added.length;
1862
+ this.discover(table, next, added);
1863
+ if (added.length > known) {
1864
+ fields = this.fieldsOf(table);
1865
+ while (before.length < fields.length) before.push(null);
1866
+ }
1867
+ this.reindex(table, id, fields, before, this.keysOf(fields, next), out);
1868
+ note(table, id, next);
1869
+ }
1870
+ out.push({
1871
+ t: "put",
1872
+ table,
1873
+ id,
1874
+ rv,
1875
+ flags,
1876
+ body
1877
+ });
1878
+ pending.set(key, body);
1879
+ }
1880
+ for (const [table, field] of added) {
1881
+ const index = indexTable(table, field);
1882
+ const mine = touched.get(table);
1883
+ const put = (id, row) => {
1884
+ const k = indexKey(extract(row, field));
1885
+ if (k !== null) out.push({
1886
+ t: "put",
1887
+ table: index,
1888
+ id: k + SEP + id,
1889
+ rv: 0,
1890
+ flags: FLAG_RAW,
1891
+ body: NO_ENTRY
1892
+ });
1893
+ };
1894
+ if (!cleared.has(table)) this.scan(table, (row) => {
1895
+ const id = String(row.id);
1896
+ if (!mine?.has(id)) put(id, row);
1897
+ });
1898
+ if (mine) {
1899
+ for (const [id, row] of mine) if (row) put(id, row);
1900
+ }
1901
+ }
1902
+ if (added.length > 0) out.push(this.registryOp());
1903
+ this.store.write(out, sync);
1904
+ }
1905
+ versions(tables) {
1906
+ const out = {};
1907
+ for (const table of tables) out[table] = this.store.versions(table);
1908
+ return out;
1909
+ }
1910
+ /** Set the cached `_00_rv` of every row of `tables` to 0, except `keep`. Returns the rows rewritten. */
1911
+ resetVersions(tables, keep) {
1912
+ const kept = new Set(keep);
1913
+ const out = [];
1914
+ let rewritten = 0;
1915
+ for (const table of tables) {
1916
+ const fields = isUserTable(table) ? this.fieldsOf(table) : [];
1917
+ this.scan(table, (row, at, run) => {
1918
+ const rv = extract(row, "_00_rv");
1919
+ if (rv === null || rv === 0 || kept.has(String(row.id))) return;
1920
+ const id = runId(run, at);
1921
+ const before = this.keysOf(fields, row);
1922
+ row._00_rv = 0;
1923
+ this.reindex(table, id, fields, before, this.keysOf(fields, row), out);
1924
+ out.push({
1925
+ t: "put",
1926
+ table,
1927
+ id,
1928
+ rv: 0,
1929
+ flags: run.flags[at],
1930
+ body: encoder.encode(JSON.stringify(row))
1931
+ });
1932
+ rewritten++;
1933
+ });
1934
+ }
1935
+ this.store.write(out);
1936
+ return rewritten;
1937
+ }
1938
+ /** A raw blob and the JSON row beside it: the circuit snapshot's two halves. */
1939
+ getBlob(table, key) {
1940
+ const blob = this.store.get(table, key);
1941
+ const meta = this.store.get(table, `${key}:meta`);
1942
+ return {
1943
+ bytes: blob ? blob.body.buffer : null,
1944
+ meta: meta ? decoder.decode(meta.body) : null
1945
+ };
1946
+ }
1947
+ putBlob(table, key, bytes, meta) {
1948
+ this.store.write([{
1949
+ t: "put",
1950
+ table,
1951
+ id: key,
1952
+ rv: 0,
1953
+ flags: FLAG_RAW,
1954
+ body: new Uint8Array(bytes)
1955
+ }, {
1956
+ t: "put",
1957
+ table,
1958
+ id: `${key}:meta`,
1959
+ rv: 0,
1960
+ flags: FLAG_RAW,
1961
+ body: encoder.encode(meta)
1962
+ }]);
1963
+ }
1964
+ deleteBlob(table, key) {
1965
+ this.store.write([{
1966
+ t: "del",
1967
+ table,
1968
+ id: key
1969
+ }, {
1970
+ t: "del",
1971
+ table,
1972
+ id: `${key}:meta`
1973
+ }]);
1974
+ }
1975
+ /**
1976
+ * The tables to read ahead, in the order worth reading them: the app's own
1977
+ * first (its first query is by id or over a window of one of them), then the
1978
+ * indexes over them.
1979
+ */
1980
+ warmOrder() {
1981
+ const names = this.store.tableNames();
1982
+ return [...names.filter((name) => !name.startsWith(HIDDEN)), ...names.filter((name) => name.startsWith(HIDDEN))];
1983
+ }
1984
+ /** Read every table's index into memory, so the first query does not wait for it. */
1985
+ warm() {
1986
+ for (const table of this.warmOrder()) this.store.ordered(table);
1987
+ }
1988
+ };
1989
+ /**
1990
+ * The ids of a window, each once, in the order the SQLite engine restores:
1991
+ * by position in the list, a repeated id counting where it appears last.
1992
+ */
1993
+ function windowOrder(keys) {
1994
+ const position = new Map(keys.map((key, i) => [key, i]));
1995
+ if (position.size === keys.length) return keys;
1996
+ return [...position.keys()].sort((a, b) => position.get(a) - position.get(b));
1997
+ }
1998
+ /** Row positions of a run ordered by where their bodies lie, skipping raw blobs. */
1999
+ function byOffset(run) {
2000
+ let json = 0;
2001
+ let ascending = true;
2002
+ let last = -1;
2003
+ for (let i = 0; i < run.n; i++) {
2004
+ if (run.flags[i] & FLAG_RAW) continue;
2005
+ json++;
2006
+ if (run.off[i] < last) ascending = false;
2007
+ last = run.off[i];
2008
+ }
2009
+ const order = new Uint32Array(json);
2010
+ let k = 0;
2011
+ for (let i = 0; i < run.n; i++) if (!(run.flags[i] & FLAG_RAW)) order[k++] = i;
2012
+ if (!ascending) order.sort((a, b) => run.off[a] - run.off[b]);
2013
+ return order;
2014
+ }
2015
+ /**
2016
+ * Version of what the page and the worker say to each other. A worker that
2017
+ * answers `open` with another number was built from another release (a
2018
+ * prewarmed worker started from a URL remembered across a deploy) and is
2019
+ * replaced by a fresh one.
2020
+ */
2021
+ const ROWS_PROTOCOL = 1;
2022
+ /** Data ops a follower tab may send over its port; the rest belong to the owner. */
2023
+ const ROWS_CLIENT_OPS = new Set([
2024
+ "select",
2025
+ "by-ids",
2026
+ "get",
2027
+ "relation",
2028
+ "select-table",
2029
+ "count",
2030
+ "write",
2031
+ "versions",
2032
+ "reset-versions",
2033
+ "tables",
2034
+ "blob-get",
2035
+ "blob-put",
2036
+ "blob-del"
2037
+ ]);
2038
+ const withBytes = (rows, extra = {}) => ({
2039
+ result: {
2040
+ ...rows,
2041
+ ...extra
2042
+ },
2043
+ transfer: rows.buf ? [rows.buf] : void 0
2044
+ });
2045
+ /**
2046
+ * Answer one data message. Kept apart from the worker so the engine's tests
2047
+ * can run the same code in-process. Returns `null` for a message it does not
2048
+ * know.
2049
+ */
2050
+ /** The ops a reader store answers: the ones that leave the store as it was. */
2051
+ const ROWS_READER_OPS = new Set([
2052
+ "select",
2053
+ "by-ids",
2054
+ "get",
2055
+ "relation",
2056
+ "select-table",
2057
+ "count",
2058
+ "versions",
2059
+ "tables",
2060
+ "blob-get"
2061
+ ]);
2062
+ const READER_ATTEMPTS = 4;
2063
+ /**
2064
+ * {@link handleRowsOp} on a store opened as a reader, beside its writer. The
2065
+ * reader takes in what was appended, answers, and then checks that the file
2066
+ * it read is still the live one (`RowStore.current`): a compaction that
2067
+ * emptied it meanwhile means the answer was read from bytes that are gone,
2068
+ * and it is read again from the file the rows moved to.
2069
+ */
2070
+ async function handleReaderOp(exec, store, type, payload) {
2071
+ if (!ROWS_READER_OPS.has(type)) throw new Error(`rows reader: op ${type} is not a read`);
2072
+ for (let attempt = 1;; attempt++) {
2073
+ store.refresh();
2074
+ exec.syncRegistry();
2075
+ try {
2076
+ const reply = await handleRowsOp(exec, store, type, payload);
2077
+ if (store.current()) return reply;
2078
+ } catch (error) {
2079
+ if (store.current()) throw error;
2080
+ }
2081
+ if (attempt === READER_ATTEMPTS) throw new Error("rows reader: the store kept moving under the read");
2082
+ }
2083
+ }
2084
+ async function handleRowsOp(exec, store, type, payload) {
2085
+ switch (type) {
2086
+ case "select": {
2087
+ const { relationFetches, ...rows } = await exec.select(payload.plan, payload.params ?? {});
2088
+ return withBytes(rows, { relationFetches });
2089
+ }
2090
+ case "by-ids": return withBytes(exec.byIds(payload.table, payload.ids, payload.select, payload.orderBy));
2091
+ case "get": return withBytes(exec.get(payload.table, payload.id));
2092
+ case "relation": return withBytes(exec.relation(payload));
2093
+ case "select-table": return withBytes(exec.selectTable(payload.table, payload.where, payload.orderBy, payload.limit, payload.start));
2094
+ case "count": return { result: { n: exec.count(payload.table, payload.where) } };
2095
+ case "write":
2096
+ exec.write(payload.ops, payload.buf ?? null, payload.sync === true);
2097
+ return { result: {} };
2098
+ case "versions": return { result: { versions: exec.versions(payload.tables) } };
2099
+ case "reset-versions": return { result: { rows: exec.resetVersions(payload.tables, payload.keep ?? []) } };
2100
+ case "tables": return { result: { tables: visibleTables(store) } };
2101
+ case "blob-get": {
2102
+ const blob = exec.getBlob(payload.table, payload.key);
2103
+ return {
2104
+ result: blob,
2105
+ transfer: blob.bytes ? [blob.bytes] : void 0
2106
+ };
2107
+ }
2108
+ case "blob-put":
2109
+ exec.putBlob(payload.table, payload.key, payload.bytes, payload.meta);
2110
+ return { result: {} };
2111
+ case "blob-del":
2112
+ exec.deleteBlob(payload.table, payload.key);
2113
+ return { result: {} };
2114
+ default: return null;
2115
+ }
2116
+ }
2117
+ /**
2118
+ * The log a store may carry past its last checkpoint while it is busy: what
2119
+ * the next open would have to replay if the tab died right now. Past either
2120
+ * bound the index is persisted at once instead of at the next quiet moment.
2121
+ */
2122
+ const CHECKPOINT_TAIL_BYTES = 8 << 20;
2123
+ const CHECKPOINT_TAIL_OPS = 2e4;
2124
+ /**
2125
+ * What the store should do now that it has a quiet moment: persist its index
2126
+ * when writes are waiting on it, compact when dead bytes outweigh live ones.
2127
+ */
2128
+ function maintenance(stats) {
2129
+ if (stats.tailBytes > 0) return "checkpoint";
2130
+ if (stats.garbageBytes > Math.max(4 << 20, stats.liveBytes / 2)) return "compact";
2131
+ return null;
2132
+ }
2133
+
2134
+ //#endregion
2135
+ //#region src/services/database/rows-prewarm.ts
2136
+ /**
2137
+ * Starting the row store ahead of the app. Kept free of imports: a build
2138
+ * script that only wants {@link ROWS_PREWARM_SNIPPET} for the page's `<head>`
2139
+ * loads this file and nothing else of the client.
2140
+ *
2141
+ * What a page load can have done before its bundle has run:
2142
+ *
2143
+ * 1. the worker started and the last bucket's store opened;
2144
+ * 2. the reads the app made in its first seconds last time, asked again
2145
+ * ("read ahead"), their answers waiting in the page;
2146
+ * 3. the tables' indexes read into the worker's memory.
2147
+ *
2148
+ * The engine (`rows-cache-engine.ts`) adopts all three when it connects, and
2149
+ * starts its own worker when anything about them is wrong.
2150
+ */
2151
+ /** localStorage key under which the engine leaves what {@link prewarmRows} needs. */
2152
+ const ROWS_PREWARM_KEY = "sp00ky.rows.prewarm";
2153
+ /** Message id of the open a prewarm sends. */
2154
+ const ROWS_PREWARM_OPEN_ID = -1;
2155
+ /** Read `i` of a prewarm goes out as message `ROWS_AHEAD_ID - i`. The worker answers reads only under these ids. */
2156
+ const ROWS_AHEAD_ID = -10;
2157
+ /** The worker ops a prewarm may ask ahead: the ones that answer rows and change nothing. */
2158
+ const ROWS_AHEAD_OPS = new Set([
2159
+ "select",
2160
+ "by-ids",
2161
+ "relation"
2162
+ ]);
2163
+ /** {@link prewarmRows} as a script to inline in `<head>`, ahead of the app's bundle. */
2164
+ const ROWS_PREWARM_SNIPPET = `(function(){try{var g=globalThis,p=JSON.parse(localStorage.getItem("${ROWS_PREWARM_KEY}")||"null");if(!p||!p.url||!p.bucket||g.__sp00kyRowsPrewarm)return;var r=Array.isArray(p.reads)?p.reads:[],s={worker:new Worker(p.url,{type:"module"}),bucket:p.bucket,failed:false,reads:r,replies:{}};s.worker.onerror=function(){s.failed=true};s.worker.onmessage=function(e){var d=e.data;if(!d)return;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};s.worker.postMessage({id:${ROWS_PREWARM_OPEN_ID},type:"open",payload:{dbName:p.bucket,useOpfs:true,openOptions:{maxAttempts:1,disallowMemoryFallback:true}}});for(var i=0;i<r.length;i++)s.worker.postMessage({id:${ROWS_AHEAD_ID}-i,type:r[i][0],payload:r[i][1]});s.worker.postMessage({id:-2,type:"warm"});g.__sp00kyRowsPrewarm=s}catch(e){}})();`;
2165
+
2166
+ //#endregion
2167
+ //#region src/services/database/rows-worker.ts
2168
+ /**
2169
+ * Dedicated Web Worker that owns a bucket's row store (`rows-store.ts`): the
2170
+ * OPFS sync access handles it reads and writes through exist only in a
2171
+ * dedicated worker, and are exclusive, so one worker per bucket holds them and
2172
+ * every tab's reads and writes go through it.
2173
+ *
2174
+ * It speaks the request/response protocol of the SQLite worker (requests keyed
2175
+ * by `id`, replies on the channel the request came in on), with the same
2176
+ * lifecycle messages, so the engine's transport, its shared-tabs roles and the
2177
+ * leader fencing work unchanged:
2178
+ *
2179
+ * { id, type: 'open', payload: { dbName, useOpfs, workerLockName?, openOptions?, share?, reader? } }
2180
+ * -> { id, ok, persisted, opfsError? }
2181
+ * { id, type: 'close' | 'shutdown' | 'relock' | 'add-client' | 'remove-client' | 'diag' }
2182
+ * every other type is a data op, answered by `handleRowsOp` (rows-exec.ts)
2183
+ *
2184
+ * Rows travel as JSON text in a transferred buffer, in both directions.
2185
+ *
2186
+ * Housekeeping runs on the same chain as the ops, in the quiet after them:
2187
+ * unflushed writes are flushed within {@link FLUSH_LAG_MS}, the index is
2188
+ * persisted after {@link IDLE_MS} without traffic (and at once when the log
2189
+ * written since the last checkpoint grows past its bound), and dead bytes are
2190
+ * compacted away when they outweigh the live ones.
2191
+ */
2192
+ /**
2193
+ * Retry schedule for an open that finds the files held. The usual holder is
2194
+ * this tab's previous worker, whose handles the browser releases a moment
2195
+ * after a reload, so the first retries come within milliseconds: a reload
2196
+ * should not wait a quarter second for a file that is free after five. The
2197
+ * whole ramp still gives another tab about as long as the SQLite worker does
2198
+ * (750 ms) before falling back to memory.
2199
+ */
2200
+ const DEFAULT_BACKOFF_MS = [
2201
+ 4,
2202
+ 8,
2203
+ 16,
2204
+ 32,
2205
+ 64,
2206
+ 128,
2207
+ 250,
2208
+ 250
2209
+ ];
2210
+ const DEFAULT_MAX_ATTEMPTS = DEFAULT_BACKOFF_MS.length + 1;
2211
+ /** How long a write may sit with the operating system before it is flushed. */
2212
+ const FLUSH_LAG_MS = 100;
2213
+ /** Quiet time after which the index is persisted and the store tidied. */
2214
+ const IDLE_MS = 500;
2215
+ var OpfsFile = class {
2216
+ constructor(access) {
2217
+ this.access = access;
2218
+ }
2219
+ read(buffer, at) {
2220
+ return this.access.read(buffer, { at });
2221
+ }
2222
+ write(buffer, at) {
2223
+ const written = this.access.write(buffer, { at });
2224
+ if (written !== buffer.length) throw new Error(`rows: wrote ${written} of ${buffer.length} bytes (storage full?)`);
2225
+ return written;
2226
+ }
2227
+ size() {
2228
+ return this.access.getSize();
2229
+ }
2230
+ truncate(size) {
2231
+ this.access.truncate(size);
2232
+ }
2233
+ flush() {
2234
+ this.access.flush();
2235
+ }
2236
+ close() {
2237
+ this.access.close();
2238
+ }
2239
+ };
2240
+ let store = null;
2241
+ let exec = null;
2242
+ /** The open store is a reader's: it answers reads beside another worker's writes and does no housekeeping. */
2243
+ let reading = false;
2244
+ /** What the open store was opened as, so a second `open` for the same thing is a no-op. */
2245
+ let opened = null;
2246
+ /** Handles held for the open store, closed with it. */
2247
+ let openFiles = [];
2248
+ /**
2249
+ * Whether this browser opens a second `readwrite-unsafe` handle on a file. One
2250
+ * that does not know the option ignores it and hands out the exclusive handle,
2251
+ * so the only way to know is to try, on a file of no importance.
2252
+ */
2253
+ async function canShareFiles(dir) {
2254
+ const handles = [];
2255
+ try {
2256
+ const probe = await dir.getFileHandle("probe", { create: true });
2257
+ const open = () => probe.createSyncAccessHandle({ mode: "readwrite-unsafe" });
2258
+ handles.push(await open());
2259
+ handles.push(await open());
2260
+ return true;
2261
+ } catch {
2262
+ return false;
2263
+ } finally {
2264
+ for (const handle of handles) handle.close();
2265
+ }
2266
+ }
2267
+ async function opfsIo(bucketId, mode = "own") {
2268
+ const dir = await (await navigator.storage.getDirectory()).getDirectoryHandle(bucketDirName(bucketId), { create: true });
2269
+ let shared = false;
2270
+ if (mode !== "own") {
2271
+ shared = await canShareFiles(dir);
2272
+ if (!shared && mode === "reader") throw new Error("Missing required OPFS APIs: shared access handles");
2273
+ }
2274
+ return { open: async (name) => {
2275
+ const handle = await dir.getFileHandle(name, { create: true });
2276
+ const file = new OpfsFile(await (shared ? handle.createSyncAccessHandle({ mode: "readwrite-unsafe" }) : handle.createSyncAccessHandle()));
2277
+ openFiles.push(file);
2278
+ return file;
2279
+ } };
2280
+ }
2281
+ function memoryIo() {
2282
+ const files = {
2283
+ a: new MemoryFile(),
2284
+ b: new MemoryFile()
2285
+ };
2286
+ return { open: (name) => files[name] };
2287
+ }
2288
+ function closeFiles() {
2289
+ for (const file of openFiles) try {
2290
+ file.close();
2291
+ } catch {}
2292
+ openFiles = [];
2293
+ }
2294
+ const errMessage = (e) => e instanceof Error ? e.name && e.name !== "Error" ? `${e.name}: ${e.message}` : e.message : String(e);
2295
+ /**
2296
+ * Open `bucketId`'s store. Sync access handles are exclusive, so a second
2297
+ * worker on the same bucket (another tab that is still closing) fails here:
2298
+ * retry, then fall back to memory and say so loudly, as the SQLite worker
2299
+ * does. A caller that must not run in memory (a shared-tabs leader) gets the
2300
+ * error instead.
2301
+ */
2302
+ async function openStore(bucketId, useOpfs, opts = {}, mode = "own") {
2303
+ reading = false;
2304
+ if (!useOpfs) {
2305
+ store = await RowStore.open(memoryIo());
2306
+ exec = new RowsExec(store);
2307
+ return { persisted: false };
2308
+ }
2309
+ const maxAttempts = Math.max(1, opts.maxAttempts ?? DEFAULT_MAX_ATTEMPTS);
2310
+ const backoffMs = opts.backoffMs ?? DEFAULT_BACKOFF_MS;
2311
+ let lastError = "unknown error";
2312
+ let attempts = 0;
2313
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
2314
+ attempts = attempt;
2315
+ try {
2316
+ if (!navigator.storage?.getDirectory) throw new Error("Missing required OPFS APIs");
2317
+ store = await RowStore.open(await opfsIo(bucketId, mode), { reader: mode === "reader" });
2318
+ exec = new RowsExec(store, mode === "reader");
2319
+ reading = mode === "reader";
2320
+ return { persisted: true };
2321
+ } catch (e) {
2322
+ closeFiles();
2323
+ lastError = errMessage(e);
2324
+ if (attempt === maxAttempts || lastError.includes("Missing required OPFS APIs")) break;
2325
+ await new Promise((resolve) => setTimeout(resolve, backoffMs[Math.min(attempt - 1, backoffMs.length - 1)] ?? 0));
2326
+ }
2327
+ }
2328
+ if (opts.disallowMemoryFallback || mode === "reader") throw new Error(`opfs-unavailable: ${lastError} (after ${attempts} attempts)`);
2329
+ console.error(`[sp00ky] OPFS persistence unavailable for "${bucketId}" after ${attempts} attempt${attempts === 1 ? "" : "s"}: ${lastError}. The local row store is running IN MEMORY, which keeps the whole dataset in RAM and loses every local write on reload. The usual cause is another tab of this app holding the storage lock, so closing the other tabs and reloading restores persistence.`);
2330
+ store = await RowStore.open(memoryIo());
2331
+ exec = new RowsExec(store);
2332
+ return {
2333
+ persisted: false,
2334
+ opfsError: lastError
2335
+ };
2336
+ }
2337
+ /** Persist the index and let go of the files. */
2338
+ function closeStore() {
2339
+ clearTimers();
2340
+ try {
2341
+ store?.checkpoint();
2342
+ } catch {}
2343
+ try {
2344
+ store?.close();
2345
+ } catch {}
2346
+ store = null;
2347
+ exec = null;
2348
+ opened = null;
2349
+ reading = false;
2350
+ warmQueue = null;
2351
+ closeFiles();
2352
+ }
2353
+ let flushTimer = null;
2354
+ let idleTimer = null;
2355
+ function clearTimers() {
2356
+ if (flushTimer) clearTimeout(flushTimer);
2357
+ if (idleTimer) clearTimeout(idleTimer);
2358
+ flushTimer = null;
2359
+ idleTimer = null;
2360
+ }
2361
+ function afterOp(wrote) {
2362
+ if (!store) return;
2363
+ if (wrote) {
2364
+ const stats = store.stats();
2365
+ if (stats.tailBytes > CHECKPOINT_TAIL_BYTES || stats.tailOps > CHECKPOINT_TAIL_OPS) store.checkpoint();
2366
+ else if (!flushTimer) flushTimer = setTimeout(() => {
2367
+ flushTimer = null;
2368
+ enqueue(() => store?.flush());
2369
+ }, FLUSH_LAG_MS);
2370
+ }
2371
+ if (idleTimer) clearTimeout(idleTimer);
2372
+ idleTimer = setTimeout(() => {
2373
+ idleTimer = null;
2374
+ enqueue(tidy);
2375
+ }, IDLE_MS);
2376
+ }
2377
+ async function tidy() {
2378
+ if (!store) return;
2379
+ store.flush();
2380
+ for (let round = 0; round < 3 && store; round++) {
2381
+ const step = maintenance(store.stats());
2382
+ if (!step) break;
2383
+ if (step === "checkpoint") store.checkpoint();
2384
+ else await store.compact();
2385
+ }
2386
+ }
2387
+ let fenced = false;
2388
+ let currentLock = null;
2389
+ function workerLocks() {
2390
+ const nav = globalThis.navigator;
2391
+ return nav?.locks && typeof nav.locks.request === "function" ? nav.locks : null;
2392
+ }
2393
+ function acquireWorkerLock(name) {
2394
+ const locks = workerLocks();
2395
+ if (!locks) return Promise.resolve({
2396
+ name,
2397
+ release() {}
2398
+ });
2399
+ return new Promise((resolve) => {
2400
+ let granted = false;
2401
+ let intentional = false;
2402
+ let releaseGrant = null;
2403
+ locks.request(name, {
2404
+ mode: "exclusive",
2405
+ ifAvailable: true
2406
+ }, (lock) => {
2407
+ if (!lock) {
2408
+ resolve(null);
2409
+ return;
2410
+ }
2411
+ granted = true;
2412
+ resolve({
2413
+ name,
2414
+ release() {
2415
+ intentional = true;
2416
+ releaseGrant?.();
2417
+ }
2418
+ });
2419
+ return new Promise((release) => {
2420
+ releaseGrant = release;
2421
+ });
2422
+ }).then(() => {
2423
+ if (granted && !intentional) fence("worker lock stolen");
2424
+ }, () => {
2425
+ if (granted && !intentional) fence("worker lock request failed");
2426
+ });
2427
+ });
2428
+ }
2429
+ function releaseHeldLock() {
2430
+ currentLock?.release();
2431
+ currentLock = null;
2432
+ }
2433
+ /** Terminal: close the files without another write, tell the owner, stop. */
2434
+ function fence(reason) {
2435
+ if (fenced) return;
2436
+ fenced = true;
2437
+ console.error(`[sp00ky] row store worker fenced (${reason}): leadership was taken over, closing the store and refusing further ops.`);
2438
+ clearTimers();
2439
+ store = null;
2440
+ exec = null;
2441
+ opened = null;
2442
+ closeFiles();
2443
+ try {
2444
+ self.postMessage({
2445
+ type: "lock-lost",
2446
+ reason
2447
+ });
2448
+ } catch {}
2449
+ releaseHeldLock();
2450
+ self.close();
2451
+ }
2452
+ const FREEZE_SUSPECT_MS = 1e4;
2453
+ let lastTickAt = performance.now();
2454
+ let thawVerification = null;
2455
+ function noteTick() {
2456
+ const now = performance.now();
2457
+ const gap = now - lastTickAt;
2458
+ lastTickAt = now;
2459
+ if (gap > FREEZE_SUSPECT_MS && currentLock && !fenced && !thawVerification) thawVerification = verifyLockStillHeld(workerLocks(), currentLock?.name, (reason) => Promise.resolve(fence(reason)), void 0, (msg) => console.warn(`[rows-worker] ${msg}`)).finally(() => {
2460
+ thawVerification = null;
2461
+ });
2462
+ }
2463
+ setInterval(noteTick, 1e3);
2464
+ const clients = /* @__PURE__ */ new Map();
2465
+ /** One chain for every op from every channel, housekeeping included. */
2466
+ let opChain = Promise.resolve();
2467
+ /** Ops queued or running, and when the last one finished. */
2468
+ let pendingOps = 0;
2469
+ let lastOpAt = 0;
2470
+ function enqueue(fn) {
2471
+ pendingOps++;
2472
+ const result = opChain.then(fn, fn);
2473
+ const settle = () => {
2474
+ pendingOps--;
2475
+ lastOpAt = performance.now();
2476
+ };
2477
+ opChain = result.then(() => settle(), () => settle());
2478
+ return result;
2479
+ }
2480
+ const WARM_QUIET_MS = 15;
2481
+ /** Tables whose index is still to be read; null when there is nothing to warm. */
2482
+ let warmQueue = null;
2483
+ let warmTimer = null;
2484
+ function warmSoon(delay) {
2485
+ if (warmTimer === null) warmTimer = setTimeout(warmStep, delay);
2486
+ }
2487
+ function warmStep() {
2488
+ warmTimer = null;
2489
+ if (!warmQueue || !store || fenced) {
2490
+ warmQueue = null;
2491
+ return;
2492
+ }
2493
+ if (pendingOps > 0 || performance.now() - lastOpAt < WARM_QUIET_MS) return warmSoon(WARM_QUIET_MS);
2494
+ const table = warmQueue.shift();
2495
+ if (table === void 0) {
2496
+ warmQueue = null;
2497
+ return;
2498
+ }
2499
+ try {
2500
+ store.ordered(table);
2501
+ } catch {}
2502
+ warmSoon(0);
2503
+ }
2504
+ async function handle(type, payload, source) {
2505
+ if (fenced) throw new Error("rows: fenced, leadership was taken over");
2506
+ if (source === "client" && !ROWS_CLIENT_OPS.has(type)) throw new Error(`rows worker: op ${type} is not allowed on a client port`);
2507
+ switch (type) {
2508
+ case "open": {
2509
+ if (payload.workerLockName) {
2510
+ const lock = await acquireWorkerLock(payload.workerLockName);
2511
+ if (!lock) throw new Error("worker-lock-unavailable");
2512
+ releaseHeldLock();
2513
+ currentLock = lock;
2514
+ }
2515
+ const mode = payload.reader ? "reader" : payload.share ? "share" : "own";
2516
+ if (!(store !== null && opened !== null && opened.dbName === payload.dbName && opened.useOpfs === payload.useOpfs && opened.mode === mode)) {
2517
+ closeStore();
2518
+ const result = await openStore(payload.dbName, payload.useOpfs, payload.openOptions, mode);
2519
+ opened = {
2520
+ dbName: payload.dbName,
2521
+ useOpfs: payload.useOpfs,
2522
+ mode,
2523
+ result
2524
+ };
2525
+ }
2526
+ return { result: {
2527
+ ...opened.result,
2528
+ proto: ROWS_PROTOCOL,
2529
+ workerUrl: self.location.href
2530
+ } };
2531
+ }
2532
+ case "warm":
2533
+ warmQueue = exec ? exec.warmOrder() : null;
2534
+ warmSoon(WARM_QUIET_MS);
2535
+ return { result: {} };
2536
+ case "relock": {
2537
+ const lock = await acquireWorkerLock(payload.workerLockName);
2538
+ if (!lock) throw new Error("worker-lock-unavailable");
2539
+ releaseHeldLock();
2540
+ currentLock = lock;
2541
+ return { result: {} };
2542
+ }
2543
+ case "close":
2544
+ closeStore();
2545
+ releaseHeldLock();
2546
+ return { result: {} };
2547
+ case "shutdown":
2548
+ closeStore();
2549
+ releaseHeldLock();
2550
+ queueMicrotask(() => self.close());
2551
+ return { result: {} };
2552
+ case "remove-client":
2553
+ clients.get(payload.clientId)?.close();
2554
+ clients.delete(payload.clientId);
2555
+ return { result: {} };
2556
+ case "diag":
2557
+ if (!store) throw new Error("rows: store not open");
2558
+ store.refresh();
2559
+ return { result: {
2560
+ stats: store.stats(),
2561
+ tableCounts: payload?.tableCounts ? visibleTables(store).map((table) => ({
2562
+ table,
2563
+ rows: store.count(table)
2564
+ })) : void 0
2565
+ } };
2566
+ default: {
2567
+ if (!store || !exec) throw new Error("rows: store not open");
2568
+ if (reading) {
2569
+ const answer = await handleReaderOp(exec, store, type, payload);
2570
+ if (!answer) throw new Error(`rows worker: unknown message ${type}`);
2571
+ return answer;
2572
+ }
2573
+ const reply = await handleRowsOp(exec, store, type, payload);
2574
+ if (!reply) throw new Error(`rows worker: unknown message ${type}`);
2575
+ afterOp(type === "write" || type === "reset-versions" || type === "blob-put" || type === "blob-del");
2576
+ return reply;
2577
+ }
2578
+ }
2579
+ }
2580
+ function dispatch(target, data, source) {
2581
+ const { id, type, payload } = data ?? {};
2582
+ noteTick();
2583
+ if (typeof id === "number" && id <= ROWS_AHEAD_ID && !ROWS_AHEAD_OPS.has(type)) {
2584
+ target.postMessage({
2585
+ id,
2586
+ ok: false,
2587
+ error: "rows worker: only reads may be asked ahead"
2588
+ });
2589
+ return;
2590
+ }
2591
+ enqueue(async () => {
2592
+ const t0 = performance.now();
2593
+ try {
2594
+ if (thawVerification) await thawVerification;
2595
+ const { result, transfer } = await handle(type, payload, source);
2596
+ target.postMessage({
2597
+ id,
2598
+ ok: true,
2599
+ wt: performance.now() - t0,
2600
+ ...result
2601
+ }, transfer ?? []);
2602
+ } catch (err) {
2603
+ target.postMessage({
2604
+ id,
2605
+ ok: false,
2606
+ error: err instanceof Error ? err.message : String(err)
2607
+ });
2608
+ }
2609
+ });
2610
+ }
2611
+ self.onmessage = (ev) => {
2612
+ const data = ev.data ?? {};
2613
+ if (data.type === "add-client") {
2614
+ const port = ev.ports?.[0];
2615
+ const clientId = data.payload?.clientId;
2616
+ if (!port || !clientId) {
2617
+ self.postMessage({
2618
+ id: data.id,
2619
+ ok: false,
2620
+ error: "rows worker: add-client needs a clientId and a transferred port"
2621
+ });
2622
+ return;
2623
+ }
2624
+ clients.get(clientId)?.close();
2625
+ clients.set(clientId, port);
2626
+ port.onmessage = (pe) => dispatch(port, pe.data, "client");
2627
+ port.start?.();
2628
+ self.postMessage({
2629
+ id: data.id,
2630
+ ok: true,
2631
+ wt: 0
2632
+ });
2633
+ return;
2634
+ }
2635
+ dispatch(self, data, "owner");
2636
+ };
2637
+
2638
+ //#endregion
2639
+ export { };