@spooky-sync/core 0.0.1-canary.24 → 0.0.1-canary.240

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 (303) hide show
  1. package/AGENTS.md +58 -0
  2. package/coverage/lcov-report/base.css +224 -0
  3. package/coverage/lcov-report/block-navigation.js +87 -0
  4. package/coverage/lcov-report/favicon.png +0 -0
  5. package/coverage/lcov-report/index.html +476 -0
  6. package/coverage/lcov-report/prettify.css +1 -0
  7. package/coverage/lcov-report/prettify.js +2 -0
  8. package/coverage/lcov-report/sort-arrow-sprite.png +0 -0
  9. package/coverage/lcov-report/sorter.js +210 -0
  10. package/coverage/lcov-report/src/boot/auth-flip.saga.ts.html +271 -0
  11. package/coverage/lcov-report/src/boot/boot.saga.ts.html +469 -0
  12. package/coverage/lcov-report/src/boot/bucket-switch.saga.ts.html +430 -0
  13. package/coverage/lcov-report/src/boot/index.html +161 -0
  14. package/coverage/lcov-report/src/boot/preload.saga.ts.html +178 -0
  15. package/coverage/lcov-report/src/client/bucket-handle.ts.html +766 -0
  16. package/coverage/lcov-report/src/client/index.html +161 -0
  17. package/coverage/lcov-report/src/client/router.ts.html +367 -0
  18. package/coverage/lcov-report/src/client/runtime.ts.html +940 -0
  19. package/coverage/lcov-report/src/client/sp00ky-client.ts.html +1531 -0
  20. package/coverage/lcov-report/src/events/index.html +116 -0
  21. package/coverage/lcov-report/src/events/index.ts.html +877 -0
  22. package/coverage/lcov-report/src/index.html +146 -0
  23. package/coverage/lcov-report/src/index.ts.html +202 -0
  24. package/coverage/lcov-report/src/kernel/constants.ts.html +247 -0
  25. package/coverage/lcov-report/src/kernel/effects.ts.html +562 -0
  26. package/coverage/lcov-report/src/kernel/events.ts.html +250 -0
  27. package/coverage/lcov-report/src/kernel/index.html +176 -0
  28. package/coverage/lcov-report/src/kernel/interpreter.ts.html +514 -0
  29. package/coverage/lcov-report/src/kernel/saga.ts.html +304 -0
  30. package/coverage/lcov-report/src/modules/app-release/index.html +116 -0
  31. package/coverage/lcov-report/src/modules/app-release/index.ts.html +712 -0
  32. package/coverage/lcov-report/src/modules/auth/events/index.html +116 -0
  33. package/coverage/lcov-report/src/modules/auth/events/index.ts.html +142 -0
  34. package/coverage/lcov-report/src/modules/auth/index.html +116 -0
  35. package/coverage/lcov-report/src/modules/auth/index.ts.html +1225 -0
  36. package/coverage/lcov-report/src/modules/crdt/crdt-field.ts.html +967 -0
  37. package/coverage/lcov-report/src/modules/crdt/index.html +146 -0
  38. package/coverage/lcov-report/src/modules/crdt/index.ts.html +1474 -0
  39. package/coverage/lcov-report/src/modules/crdt/loro-loader.ts.html +160 -0
  40. package/coverage/lcov-report/src/modules/devtools/flags.ts.html +1132 -0
  41. package/coverage/lcov-report/src/modules/devtools/index.html +161 -0
  42. package/coverage/lcov-report/src/modules/devtools/index.ts.html +2413 -0
  43. package/coverage/lcov-report/src/modules/devtools/storage-info.ts.html +589 -0
  44. package/coverage/lcov-report/src/modules/devtools/versions.ts.html +415 -0
  45. package/coverage/lcov-report/src/modules/feature-flag/index.html +116 -0
  46. package/coverage/lcov-report/src/modules/feature-flag/index.ts.html +1033 -0
  47. package/coverage/lcov-report/src/modules/index.html +116 -0
  48. package/coverage/lcov-report/src/modules/ref-tables.ts.html +349 -0
  49. package/coverage/lcov-report/src/mutation/index.html +191 -0
  50. package/coverage/lcov-report/src/mutation/jobs.ts.html +208 -0
  51. package/coverage/lcov-report/src/mutation/mutation-id.ts.html +190 -0
  52. package/coverage/lcov-report/src/mutation/push.saga.ts.html +730 -0
  53. package/coverage/lcov-report/src/mutation/rows.ts.html +1216 -0
  54. package/coverage/lcov-report/src/mutation/tray.saga.ts.html +229 -0
  55. package/coverage/lcov-report/src/mutation/write.saga.ts.html +583 -0
  56. package/coverage/lcov-report/src/otel/index.html +116 -0
  57. package/coverage/lcov-report/src/otel/index.ts.html +466 -0
  58. package/coverage/lcov-report/src/query/env.ts.html +253 -0
  59. package/coverage/lcov-report/src/query/fetch.saga.ts.html +412 -0
  60. package/coverage/lcov-report/src/query/hash.ts.html +139 -0
  61. package/coverage/lcov-report/src/query/index.html +281 -0
  62. package/coverage/lcov-report/src/query/lifecycle.saga.ts.html +388 -0
  63. package/coverage/lcov-report/src/query/materialize.saga.ts.html +310 -0
  64. package/coverage/lcov-report/src/query/materialize.ts.html +217 -0
  65. package/coverage/lcov-report/src/query/membership.saga.ts.html +709 -0
  66. package/coverage/lcov-report/src/query/membership.ts.html +559 -0
  67. package/coverage/lcov-report/src/query/register.saga.ts.html +655 -0
  68. package/coverage/lcov-report/src/query/render-set.ts.html +265 -0
  69. package/coverage/lcov-report/src/query/sql.ts.html +322 -0
  70. package/coverage/lcov-report/src/query/window-query.ts.html +670 -0
  71. package/coverage/lcov-report/src/services/blobs/blob-cache.ts.html +1894 -0
  72. package/coverage/lcov-report/src/services/blobs/blob-manifest.ts.html +766 -0
  73. package/coverage/lcov-report/src/services/blobs/blob-store.ts.html +1162 -0
  74. package/coverage/lcov-report/src/services/blobs/index.html +161 -0
  75. package/coverage/lcov-report/src/services/blobs/index.ts.html +295 -0
  76. package/coverage/lcov-report/src/services/database/cache-engine.ts.html +664 -0
  77. package/coverage/lcov-report/src/services/database/connection-supervisor.ts.html +1330 -0
  78. package/coverage/lcov-report/src/services/database/database.ts.html +658 -0
  79. package/coverage/lcov-report/src/services/database/engine-factory.ts.html +184 -0
  80. package/coverage/lcov-report/src/services/database/errors.ts.html +187 -0
  81. package/coverage/lcov-report/src/services/database/events/index.html +116 -0
  82. package/coverage/lcov-report/src/services/database/events/index.ts.html +184 -0
  83. package/coverage/lcov-report/src/services/database/index.html +386 -0
  84. package/coverage/lcov-report/src/services/database/index.ts.html +121 -0
  85. package/coverage/lcov-report/src/services/database/local-migrator.ts.html +703 -0
  86. package/coverage/lcov-report/src/services/database/local.ts.html +1633 -0
  87. package/coverage/lcov-report/src/services/database/plan-render.ts.html +409 -0
  88. package/coverage/lcov-report/src/services/database/relation-resolver.ts.html +682 -0
  89. package/coverage/lcov-report/src/services/database/remote.ts.html +1036 -0
  90. package/coverage/lcov-report/src/services/database/sqlite-cache-engine.ts.html +4132 -0
  91. package/coverage/lcov-report/src/services/database/sqlite-lock-verify.ts.html +220 -0
  92. package/coverage/lcov-report/src/services/database/sqlite-open.ts.html +577 -0
  93. package/coverage/lcov-report/src/services/database/sqlite-plan-sql.ts.html +499 -0
  94. package/coverage/lcov-report/src/services/database/sqlite-select.ts.html +478 -0
  95. package/coverage/lcov-report/src/services/database/sqlite-transport.ts.html +757 -0
  96. package/coverage/lcov-report/src/services/database/surql-translate.ts.html +1333 -0
  97. package/coverage/lcov-report/src/services/database/surreal-cache-engine.ts.html +568 -0
  98. package/coverage/lcov-report/src/services/logger/index.html +116 -0
  99. package/coverage/lcov-report/src/services/logger/index.ts.html +154 -0
  100. package/coverage/lcov-report/src/services/persistence/index.html +146 -0
  101. package/coverage/lcov-report/src/services/persistence/localstorage.ts.html +163 -0
  102. package/coverage/lcov-report/src/services/persistence/resilient.ts.html +208 -0
  103. package/coverage/lcov-report/src/services/persistence/surrealdb.ts.html +271 -0
  104. package/coverage/lcov-report/src/services/stream-processor/index.html +146 -0
  105. package/coverage/lcov-report/src/services/stream-processor/index.ts.html +3313 -0
  106. package/coverage/lcov-report/src/services/stream-processor/permissions.ts.html +244 -0
  107. package/coverage/lcov-report/src/services/stream-processor/wasm-types.ts.html +346 -0
  108. package/coverage/lcov-report/src/services/tabs/broker-client.ts.html +934 -0
  109. package/coverage/lcov-report/src/services/tabs/coordinator.ts.html +1984 -0
  110. package/coverage/lcov-report/src/services/tabs/index.html +191 -0
  111. package/coverage/lcov-report/src/services/tabs/leader-locks.ts.html +310 -0
  112. package/coverage/lcov-report/src/services/tabs/protocol.ts.html +871 -0
  113. package/coverage/lcov-report/src/services/tabs/support.ts.html +193 -0
  114. package/coverage/lcov-report/src/services/tabs/tabs-broker-worker.ts.html +2005 -0
  115. package/coverage/lcov-report/src/sp00ky.ts.html +100 -0
  116. package/coverage/lcov-report/src/state/client-state.ts.html +637 -0
  117. package/coverage/lcov-report/src/state/index.html +161 -0
  118. package/coverage/lcov-report/src/state/lifecycle.ts.html +343 -0
  119. package/coverage/lcov-report/src/state/reducers.ts.html +1471 -0
  120. package/coverage/lcov-report/src/state/selectors.ts.html +637 -0
  121. package/coverage/lcov-report/src/sync/connection.saga.ts.html +343 -0
  122. package/coverage/lcov-report/src/sync/index.html +176 -0
  123. package/coverage/lcov-report/src/sync/live.saga.ts.html +232 -0
  124. package/coverage/lcov-report/src/sync/policy.ts.html +1606 -0
  125. package/coverage/lcov-report/src/sync/poll.saga.ts.html +193 -0
  126. package/coverage/lcov-report/src/sync/tabs.saga.ts.html +361 -0
  127. package/coverage/lcov-report/src/types.ts.html +2419 -0
  128. package/coverage/lcov-report/src/utils/blurhash.ts.html +355 -0
  129. package/coverage/lcov-report/src/utils/error-classification.ts.html +244 -0
  130. package/coverage/lcov-report/src/utils/index.html +191 -0
  131. package/coverage/lcov-report/src/utils/index.ts.html +820 -0
  132. package/coverage/lcov-report/src/utils/parser.ts.html +313 -0
  133. package/coverage/lcov-report/src/utils/semver.ts.html +175 -0
  134. package/coverage/lcov-report/src/utils/surql.ts.html +667 -0
  135. package/coverage/lcov.info +19079 -0
  136. package/dist/index.d.ts +2946 -140
  137. package/dist/index.js +13424 -2356
  138. package/dist/otel/index.d.ts +2 -2
  139. package/dist/otel/index.js +6 -6
  140. package/dist/sqlite-open.js +322 -0
  141. package/dist/sqlite-worker.d.ts +1 -0
  142. package/dist/sqlite-worker.js +439 -0
  143. package/dist/tabs-broker-worker.d.ts +8 -0
  144. package/dist/tabs-broker-worker.js +472 -0
  145. package/dist/types.d.ts +769 -11
  146. package/package.json +11 -7
  147. package/scripts/check-broker-bundle.mjs +33 -0
  148. package/skills/{spooky-core → sp00ky-core}/SKILL.md +12 -12
  149. package/skills/{spooky-core → sp00ky-core}/references/auth.md +1 -1
  150. package/skills/{spooky-core → sp00ky-core}/references/config.md +2 -2
  151. package/src/bucket-blurhash.test.ts +148 -0
  152. package/src/build-globals.d.ts +12 -0
  153. package/src/events/events.test.ts +2 -1
  154. package/src/events/index.ts +3 -0
  155. package/src/index.ts +36 -2
  156. package/src/modules/app-release/index.test.ts +125 -0
  157. package/src/modules/app-release/index.ts +201 -0
  158. package/src/modules/auth/auth.local-first.test.ts +141 -0
  159. package/src/modules/auth/events/index.ts +2 -1
  160. package/src/modules/auth/index.ts +138 -25
  161. package/src/modules/cache/cache.relay.test.ts +95 -0
  162. package/src/modules/cache/index.ts +163 -43
  163. package/src/modules/cache/types.ts +2 -2
  164. package/src/modules/crdt/crdt-field.ts +294 -0
  165. package/src/modules/crdt/crdt-hydration.test.ts +210 -0
  166. package/src/modules/crdt/crdt-reconnect.test.ts +195 -0
  167. package/src/modules/crdt/index.ts +463 -0
  168. package/src/modules/crdt/loro-loader.ts +25 -0
  169. package/src/modules/data/data.activity.test.ts +109 -0
  170. package/src/modules/data/data.authority.test.ts +122 -0
  171. package/src/modules/data/data.heartbeat-wake.test.ts +115 -0
  172. package/src/modules/data/data.hydration.test.ts +142 -0
  173. package/src/modules/data/data.membership.test.ts +623 -0
  174. package/src/modules/data/data.notify-table.test.ts +41 -0
  175. package/src/modules/data/data.pending-ids.test.ts +199 -0
  176. package/src/modules/data/data.rebind.test.ts +170 -0
  177. package/src/modules/data/data.rematerialize.test.ts +114 -0
  178. package/src/modules/data/data.run.test.ts +113 -0
  179. package/src/modules/data/data.settled-writes.test.ts +235 -0
  180. package/src/modules/data/data.status.test.ts +249 -0
  181. package/src/modules/data/id-set-plan.test.ts +122 -0
  182. package/src/modules/data/index.ts +2031 -150
  183. package/src/modules/data/mutation-id.test.ts +25 -0
  184. package/src/modules/data/mutation-id.ts +35 -0
  185. package/src/modules/data/window-query.test.ts +52 -0
  186. package/src/modules/data/window-query.ts +194 -0
  187. package/src/modules/devtools/flags.ts +349 -0
  188. package/src/modules/devtools/index.ts +451 -46
  189. package/src/modules/devtools/notify-throttle.test.ts +154 -0
  190. package/src/modules/devtools/state-shape.test.ts +146 -0
  191. package/src/modules/devtools/storage-info.test.ts +79 -0
  192. package/src/modules/devtools/storage-info.ts +168 -0
  193. package/src/modules/devtools/versions.test.ts +74 -0
  194. package/src/modules/devtools/versions.ts +110 -0
  195. package/src/modules/feature-flag/index.test.ts +251 -0
  196. package/src/modules/feature-flag/index.ts +308 -0
  197. package/src/modules/ref-tables.test.ts +91 -0
  198. package/src/modules/ref-tables.ts +88 -0
  199. package/src/modules/sync/engine.ts +170 -86
  200. package/src/modules/sync/events/index.ts +9 -2
  201. package/src/modules/sync/queue/queue-down.test.ts +228 -0
  202. package/src/modules/sync/queue/queue-down.ts +108 -13
  203. package/src/modules/sync/queue/queue-up.forwarded.test.ts +164 -0
  204. package/src/modules/sync/queue/queue-up.ts +241 -57
  205. package/src/modules/sync/scheduler.pause.test.ts +109 -0
  206. package/src/modules/sync/scheduler.retry.test.ts +237 -0
  207. package/src/modules/sync/scheduler.ts +215 -13
  208. package/src/modules/sync/sync.cleanup.test.ts +116 -0
  209. package/src/modules/sync/sync.health.test.ts +167 -0
  210. package/src/modules/sync/sync.heartbeat.test.ts +80 -0
  211. package/src/modules/sync/sync.list-ref-meta.test.ts +193 -0
  212. package/src/modules/sync/sync.live-removal.test.ts +289 -0
  213. package/src/modules/sync/sync.reconnect.test.ts +145 -0
  214. package/src/modules/sync/sync.rematerialize-after-fetch.test.ts +93 -0
  215. package/src/modules/sync/sync.settled-poll.test.ts +58 -0
  216. package/src/modules/sync/sync.subquery.test.ts +82 -0
  217. package/src/modules/sync/sync.tabs.test.ts +249 -0
  218. package/src/modules/sync/sync.ts +2350 -133
  219. package/src/modules/sync/utils.test.ts +322 -2
  220. package/src/modules/sync/utils.ts +286 -16
  221. package/src/otel/index.ts +13 -10
  222. package/src/services/blobs/blob-cache.test.ts +359 -0
  223. package/src/services/blobs/blob-cache.ts +603 -0
  224. package/src/services/blobs/blob-manifest.ts +227 -0
  225. package/src/services/blobs/blob-store.test.ts +77 -0
  226. package/src/services/blobs/blob-store.ts +359 -0
  227. package/src/services/blobs/blob.fixture.ts +90 -0
  228. package/src/services/blobs/index.ts +70 -0
  229. package/src/services/database/cache-engine.ts +193 -0
  230. package/src/services/database/connection-supervisor.test.ts +289 -0
  231. package/src/services/database/connection-supervisor.ts +415 -0
  232. package/src/services/database/database.query-timeout.test.ts +140 -0
  233. package/src/services/database/database.ts +130 -62
  234. package/src/services/database/engine-factory.ts +33 -0
  235. package/src/services/database/errors.ts +34 -0
  236. package/src/services/database/events/index.ts +2 -1
  237. package/src/services/database/index.ts +7 -0
  238. package/src/services/database/local-migrator.ts +30 -27
  239. package/src/services/database/local.test.ts +64 -0
  240. package/src/services/database/local.ts +484 -67
  241. package/src/services/database/plan-render.test.ts +159 -0
  242. package/src/services/database/plan-render.ts +108 -0
  243. package/src/services/database/relation-resolver.test.ts +467 -0
  244. package/src/services/database/relation-resolver.ts +0 -0
  245. package/src/services/database/remote.ts +222 -15
  246. package/src/services/database/sqlite-cache-engine.test.ts +616 -0
  247. package/src/services/database/sqlite-cache-engine.timeout.test.ts +61 -0
  248. package/src/services/database/sqlite-cache-engine.ts +1358 -0
  249. package/src/services/database/sqlite-devtools-queries.integration.test.ts +143 -0
  250. package/src/services/database/sqlite-devtools-queries.test.ts +154 -0
  251. package/src/services/database/sqlite-lock-verify.test.ts +33 -0
  252. package/src/services/database/sqlite-lock-verify.ts +45 -0
  253. package/src/services/database/sqlite-open.test.ts +150 -0
  254. package/src/services/database/sqlite-open.ts +164 -0
  255. package/src/services/database/sqlite-plan-sql.test.ts +104 -0
  256. package/src/services/database/sqlite-plan-sql.ts +138 -0
  257. package/src/services/database/sqlite-projection.test.ts +99 -0
  258. package/src/services/database/sqlite-select.integration.test.ts +185 -0
  259. package/src/services/database/sqlite-select.test.ts +246 -0
  260. package/src/services/database/sqlite-select.ts +131 -0
  261. package/src/services/database/sqlite-transport.fixture.ts +30 -0
  262. package/src/services/database/sqlite-transport.ts +224 -0
  263. package/src/services/database/sqlite-worker.ts +437 -0
  264. package/src/services/database/surql-translate.ts +416 -0
  265. package/src/services/database/surreal-cache-engine.ts +161 -0
  266. package/src/services/logger/index.ts +3 -2
  267. package/src/services/persistence/localstorage.ts +2 -2
  268. package/src/services/persistence/resilient.ts +11 -4
  269. package/src/services/persistence/surrealdb.ts +10 -10
  270. package/src/services/stream-processor/index.ts +796 -84
  271. package/src/services/stream-processor/permissions.test.ts +47 -0
  272. package/src/services/stream-processor/permissions.ts +53 -0
  273. package/src/services/stream-processor/stream-processor.batch.test.ts +186 -0
  274. package/src/services/stream-processor/stream-processor.prime.test.ts +198 -0
  275. package/src/services/stream-processor/stream-processor.reset.test.ts +226 -0
  276. package/src/services/stream-processor/stream-processor.test.ts +1 -1
  277. package/src/services/stream-processor/wasm-types.ts +59 -3
  278. package/src/services/tabs/broker-client.ts +283 -0
  279. package/src/services/tabs/broker.test.ts +327 -0
  280. package/src/services/tabs/coordinator.test.ts +365 -0
  281. package/src/services/tabs/coordinator.ts +633 -0
  282. package/src/services/tabs/fake-ports.fixture.ts +112 -0
  283. package/src/services/tabs/leader-locks.ts +75 -0
  284. package/src/services/tabs/protocol.ts +258 -0
  285. package/src/services/tabs/support.ts +36 -0
  286. package/src/services/tabs/tabs-broker-worker.ts +640 -0
  287. package/src/sp00ky.auth-order.test.ts +112 -0
  288. package/src/sp00ky.init-query.test.ts +183 -0
  289. package/src/sp00ky.local-first.test.ts +60 -0
  290. package/src/sp00ky.ts +1854 -0
  291. package/src/types.ts +548 -13
  292. package/src/utils/blurhash.ts +90 -0
  293. package/src/utils/error-classification.test.ts +54 -0
  294. package/src/utils/error-classification.ts +25 -0
  295. package/src/utils/index.ts +79 -13
  296. package/src/utils/parser.test.ts +49 -120
  297. package/src/utils/parser.ts +32 -2
  298. package/src/utils/semver.test.ts +32 -0
  299. package/src/utils/semver.ts +30 -0
  300. package/src/utils/surql.ts +30 -18
  301. package/src/utils/withRetry.test.ts +1 -1
  302. package/tsdown.config.ts +86 -1
  303. package/src/spooky.ts +0 -395
@@ -5,8 +5,19 @@ import {
5
5
  applyRecordVersionDiff,
6
6
  createDiffFromDbOp,
7
7
  ArraySyncer,
8
+ resolveListRefPollInterval,
9
+ DEFAULT_LIST_REF_POLL_INTERVAL_MS,
10
+ buildListRefSelect,
11
+ buildSubqueryListRefSelect,
12
+ buildListRefBatchSelect,
13
+ buildQueryRowCountBatchSelect,
14
+ planListRefPollChunks,
15
+ nextPollDelayMs,
16
+ listRefPollDelayMs,
17
+ LIST_REF_POLL_MAX_INTERVAL_MS,
18
+ recordVersionArraysEqual,
8
19
  } from './utils';
9
- import { RecordVersionArray, RecordVersionDiff } from '../../types';
20
+ import type { RecordVersionArray, RecordVersionDiff } from '../../types';
10
21
  import { encodeRecordId } from '../../utils/index';
11
22
 
12
23
  function rid(table: string, id: string): RecordId<string> {
@@ -305,7 +316,316 @@ describe('ArraySyncer', () => {
305
316
  expect(diff!.removed).toHaveLength(3);
306
317
  // Check they come in sorted order
307
318
  const removedIds = diff!.removed.map((r) => encodeRecordId(r));
308
- const sorted = [...removedIds].sort();
319
+ const sorted = [...removedIds].toSorted();
309
320
  expect(removedIds).toEqual(sorted);
310
321
  });
311
322
  });
323
+
324
+ describe('resolveListRefPollInterval', () => {
325
+ it('returns the default when no option is provided', () => {
326
+ expect(resolveListRefPollInterval()).toBe(DEFAULT_LIST_REF_POLL_INTERVAL_MS);
327
+ expect(resolveListRefPollInterval(undefined)).toBe(
328
+ DEFAULT_LIST_REF_POLL_INTERVAL_MS
329
+ );
330
+ });
331
+
332
+ it('respects a positive override', () => {
333
+ expect(resolveListRefPollInterval(1000)).toBe(1000);
334
+ expect(resolveListRefPollInterval(5000)).toBe(5000);
335
+ });
336
+
337
+ it('falls back to default for zero, negative, NaN, or Infinity', () => {
338
+ // Accepting these would either silently disable polling or busy-loop
339
+ // the event loop, so they fall back to the default.
340
+ expect(resolveListRefPollInterval(0)).toBe(DEFAULT_LIST_REF_POLL_INTERVAL_MS);
341
+ expect(resolveListRefPollInterval(-500)).toBe(
342
+ DEFAULT_LIST_REF_POLL_INTERVAL_MS
343
+ );
344
+ expect(resolveListRefPollInterval(NaN)).toBe(
345
+ DEFAULT_LIST_REF_POLL_INTERVAL_MS
346
+ );
347
+ expect(resolveListRefPollInterval(Infinity)).toBe(
348
+ DEFAULT_LIST_REF_POLL_INTERVAL_MS
349
+ );
350
+ });
351
+
352
+ it('locks the default at 500ms so accidental tuning trips this test', () => {
353
+ expect(DEFAULT_LIST_REF_POLL_INTERVAL_MS).toBe(500);
354
+ });
355
+ });
356
+
357
+ describe('buildListRefSelect', () => {
358
+ it('substitutes the table name', () => {
359
+ expect(buildListRefSelect('_00_list_ref')).toContain('FROM _00_list_ref ');
360
+ expect(buildListRefSelect('_00_list_ref_user_abc')).toContain(
361
+ 'FROM _00_list_ref_user_abc '
362
+ );
363
+ });
364
+
365
+ it('filters by the bound query id', () => {
366
+ expect(buildListRefSelect('_00_list_ref')).toContain('WHERE in = $in');
367
+ });
368
+
369
+ it('excludes subquery rows via parent IS NONE', () => {
370
+ // Without this predicate the poll would surface child records (the
371
+ // subquery-projection rows the SSP also writes into list_ref) as
372
+ // spurious "added" diffs against `localArray` every tick.
373
+ expect(buildListRefSelect('_00_list_ref')).toContain('parent IS NONE');
374
+ });
375
+
376
+ it('selects only `out` and `version`', () => {
377
+ // The diff only needs the record id and its version; pulling more
378
+ // fields would bloat the per-tick query traffic.
379
+ const sql = buildListRefSelect('_00_list_ref');
380
+ expect(sql.startsWith('SELECT out, version FROM ')).toBe(true);
381
+ });
382
+ });
383
+
384
+ describe('buildSubqueryListRefSelect', () => {
385
+ it('substitutes the table name', () => {
386
+ expect(buildSubqueryListRefSelect('_00_list_ref')).toContain('FROM _00_list_ref ');
387
+ expect(buildSubqueryListRefSelect('_00_list_ref_user_abc')).toContain(
388
+ 'FROM _00_list_ref_user_abc '
389
+ );
390
+ });
391
+
392
+ it('filters by the bound query id', () => {
393
+ expect(buildSubqueryListRefSelect('_00_list_ref')).toContain('WHERE in = $in');
394
+ });
395
+
396
+ it('selects ONLY subquery child rows via parent IS NOT NONE', () => {
397
+ // The mirror of `buildListRefSelect`'s `parent IS NONE`: the SSP writes
398
+ // `.related()` child rows into list_ref tagged with `parent`/`parent_rel`;
399
+ // this select pulls exactly those so their bodies can be synced into the
400
+ // local cache (separately from the primary window) and the correlated
401
+ // surql re-materializes with related data on a cold reload.
402
+ const sql = buildSubqueryListRefSelect('_00_list_ref');
403
+ expect(sql).toContain('parent IS NOT NONE');
404
+ expect(sql).not.toContain('parent IS NONE ');
405
+ });
406
+
407
+ it('selects only `out` and `version`', () => {
408
+ const sql = buildSubqueryListRefSelect('_00_list_ref');
409
+ expect(sql.startsWith('SELECT out, version FROM ')).toBe(true);
410
+ });
411
+ });
412
+
413
+ describe('nextPollDelayMs', () => {
414
+ it('returns the base interval when LIVE has never delivered', () => {
415
+ expect(
416
+ nextPollDelayMs({
417
+ now: 10_000,
418
+ lastLiveEventAt: null,
419
+ baseIntervalMs: 500,
420
+ })
421
+ ).toBe(500);
422
+ });
423
+
424
+ it('returns the healthy interval when a LIVE event fired within the cooldown', () => {
425
+ expect(
426
+ nextPollDelayMs({
427
+ now: 10_000,
428
+ lastLiveEventAt: 8_000, // 2s ago, well within 5s cooldown
429
+ baseIntervalMs: 500,
430
+ })
431
+ ).toBe(5_000);
432
+ });
433
+
434
+ it('snaps back to the base interval after the cooldown elapses', () => {
435
+ expect(
436
+ nextPollDelayMs({
437
+ now: 20_000,
438
+ lastLiveEventAt: 10_000, // 10s ago, well past cooldown
439
+ baseIntervalMs: 500,
440
+ })
441
+ ).toBe(500);
442
+ });
443
+
444
+ it('treats the cooldown boundary as expired (>= cooldownMs returns base)', () => {
445
+ // Exactly at the boundary, the LIVE feed is considered cold so we
446
+ // resume the aggressive cadence. Picks the same direction as
447
+ // `if (sinceLive >= cooldownMs)`.
448
+ expect(
449
+ nextPollDelayMs({
450
+ now: 15_000,
451
+ lastLiveEventAt: 10_000, // exactly 5s ago
452
+ baseIntervalMs: 500,
453
+ cooldownMs: 5_000,
454
+ })
455
+ ).toBe(500);
456
+ });
457
+
458
+ it('clamps a clock-skew negative sinceLive to the base interval', () => {
459
+ // If a stale timestamp puts the LIVE event in the future, we
460
+ // should not interpret that as "LIVE healthy" — treat it as
461
+ // unknown and use the conservative aggressive cadence.
462
+ expect(
463
+ nextPollDelayMs({
464
+ now: 10_000,
465
+ lastLiveEventAt: 20_000, // future timestamp
466
+ baseIntervalMs: 500,
467
+ })
468
+ ).toBe(500);
469
+ });
470
+
471
+ it('never widens below an aggressively-configured base interval', () => {
472
+ // If the caller picked a faster base (e.g. 100ms) on purpose,
473
+ // the healthy path should not silently slow things back to 5s.
474
+ // The healthy interval is clamped to at least base.
475
+ expect(
476
+ nextPollDelayMs({
477
+ now: 10_000,
478
+ lastLiveEventAt: 9_500,
479
+ baseIntervalMs: 8_000,
480
+ })
481
+ ).toBe(8_000);
482
+ });
483
+
484
+ it('respects custom cooldown and healthy-interval values', () => {
485
+ expect(
486
+ nextPollDelayMs({
487
+ now: 10_000,
488
+ lastLiveEventAt: 9_500, // 0.5s ago
489
+ baseIntervalMs: 250,
490
+ cooldownMs: 1_000,
491
+ healthyIntervalMs: 2_000,
492
+ })
493
+ ).toBe(2_000);
494
+ expect(
495
+ nextPollDelayMs({
496
+ now: 10_000,
497
+ lastLiveEventAt: 8_500, // 1.5s ago > cooldown
498
+ baseIntervalMs: 250,
499
+ cooldownMs: 1_000,
500
+ healthyIntervalMs: 2_000,
501
+ })
502
+ ).toBe(250);
503
+ });
504
+ });
505
+
506
+ describe('listRefPollDelayMs', () => {
507
+ it('returns the base interval at idle streak 0 (something just happened)', () => {
508
+ expect(listRefPollDelayMs({ idleStreak: 0, baseIntervalMs: 500 })).toBe(500);
509
+ // Negative streak is defensively treated as "active" too.
510
+ expect(listRefPollDelayMs({ idleStreak: -3, baseIntervalMs: 500 })).toBe(500);
511
+ });
512
+
513
+ it('doubles per idle streak (exponential backoff)', () => {
514
+ expect(listRefPollDelayMs({ idleStreak: 1, baseIntervalMs: 500 })).toBe(1_000);
515
+ expect(listRefPollDelayMs({ idleStreak: 2, baseIntervalMs: 500 })).toBe(2_000);
516
+ expect(listRefPollDelayMs({ idleStreak: 3, baseIntervalMs: 500 })).toBe(4_000);
517
+ });
518
+
519
+ it('caps at LIST_REF_POLL_MAX_INTERVAL_MS (5s) once the doubling exceeds it', () => {
520
+ // streak 4 would be 8000ms uncapped → clamped to 5000.
521
+ expect(listRefPollDelayMs({ idleStreak: 4, baseIntervalMs: 500 })).toBe(5_000);
522
+ expect(listRefPollDelayMs({ idleStreak: 50, baseIntervalMs: 500 })).toBe(5_000);
523
+ expect(LIST_REF_POLL_MAX_INTERVAL_MS).toBe(5_000);
524
+ });
525
+
526
+ it('never returns below the configured base, even when base exceeds the cap', () => {
527
+ // An aggressively-large base must not be implicitly shrunk by the cap.
528
+ expect(listRefPollDelayMs({ idleStreak: 0, baseIntervalMs: 8_000 })).toBe(8_000);
529
+ expect(listRefPollDelayMs({ idleStreak: 5, baseIntervalMs: 8_000 })).toBe(8_000);
530
+ });
531
+
532
+ it('respects a custom max interval', () => {
533
+ expect(
534
+ listRefPollDelayMs({ idleStreak: 10, baseIntervalMs: 500, maxIntervalMs: 3_000 })
535
+ ).toBe(3_000);
536
+ });
537
+
538
+ it('does not overflow for a very long idle streak', () => {
539
+ // 2^1000 would be Infinity; the exponent clamp keeps it finite and capped.
540
+ expect(listRefPollDelayMs({ idleStreak: 1_000, baseIntervalMs: 500 })).toBe(5_000);
541
+ });
542
+ });
543
+
544
+ describe('recordVersionArraysEqual', () => {
545
+ it('treats the same reference and identical contents as equal', () => {
546
+ const a: RecordVersionArray = [['game:1', 1], ['game:2', 3]];
547
+ expect(recordVersionArraysEqual(a, a)).toBe(true);
548
+ expect(recordVersionArraysEqual(a, [['game:1', 1], ['game:2', 3]])).toBe(true);
549
+ });
550
+
551
+ it('is order-insensitive (the list_ref SELECT has no ORDER BY)', () => {
552
+ expect(
553
+ recordVersionArraysEqual(
554
+ [['game:1', 1], ['game:2', 3]],
555
+ [['game:2', 3], ['game:1', 1]]
556
+ )
557
+ ).toBe(true);
558
+ });
559
+
560
+ it('returns false when a version differs for the same id', () => {
561
+ expect(
562
+ recordVersionArraysEqual([['game:1', 1]], [['game:1', 2]])
563
+ ).toBe(false);
564
+ });
565
+
566
+ it('returns false on length mismatch', () => {
567
+ expect(
568
+ recordVersionArraysEqual([['game:1', 1]], [['game:1', 1], ['game:2', 1]])
569
+ ).toBe(false);
570
+ });
571
+
572
+ it('returns false when an id is present in one but not the other', () => {
573
+ expect(
574
+ recordVersionArraysEqual([['game:1', 1]], [['game:2', 1]])
575
+ ).toBe(false);
576
+ });
577
+
578
+ it('treats two empty arrays as equal', () => {
579
+ expect(recordVersionArraysEqual([], [])).toBe(true);
580
+ });
581
+ });
582
+
583
+ describe('list_ref poll batching', () => {
584
+ it('reads many queries in one statement and their rowCounts keyed by id', () => {
585
+ expect(buildListRefBatchSelect('_00_list_ref_user_abc')).toBe(
586
+ 'SELECT in, out, version, parent FROM _00_list_ref_user_abc WHERE in IN $ins'
587
+ );
588
+ expect(buildQueryRowCountBatchSelect()).toBe(
589
+ 'SELECT VALUE { id: id, rowCount: rowCount, state: state } FROM $ins'
590
+ );
591
+ });
592
+
593
+ it('packs due queries oldest-first under the row budget', () => {
594
+ const chunks = planListRefPollChunks(
595
+ [
596
+ { hash: 'a', rows: 600, lastPolledAt: 300 },
597
+ { hash: 'b', rows: 600, lastPolledAt: 100 },
598
+ { hash: 'c', rows: 0, lastPolledAt: 0 },
599
+ { hash: 'd', rows: 900, lastPolledAt: 200 },
600
+ ],
601
+ { now: 1_000, rowBudget: 1_400 }
602
+ );
603
+ // c (never polled) first, then b, d, a by age; d does not fit next to b.
604
+ expect(chunks).toEqual([['c', 'b'], ['d'], ['a']]);
605
+ });
606
+
607
+ it('never splits below one query and always refreshes a lone huge view', () => {
608
+ expect(
609
+ planListRefPollChunks([{ hash: 'big', rows: 10_000, lastPolledAt: 0 }], {
610
+ now: 100_000,
611
+ rowBudget: 100,
612
+ })
613
+ ).toEqual([['big']]);
614
+ });
615
+
616
+ it('defers large views until their minimum age has passed', () => {
617
+ const large = { hash: 'large', rows: 5_000, lastPolledAt: 990_000 };
618
+ const small = { hash: 'small', rows: 10, lastPolledAt: 990_000 };
619
+ expect(
620
+ planListRefPollChunks([large, small], { now: 1_000_000, largeViewRows: 1_000, largeViewMinAgeMs: 15_000 })
621
+ ).toEqual([['small']]);
622
+ expect(
623
+ planListRefPollChunks([large, small], { now: 1_006_000, largeViewRows: 1_000, largeViewMinAgeMs: 15_000 })
624
+ // Same age: hash order breaks the tie, and the large view fills its own chunk.
625
+ ).toEqual([['large'], ['small']]);
626
+ });
627
+
628
+ it('returns no chunks when nothing is due', () => {
629
+ expect(planListRefPollChunks([], { now: 1 })).toEqual([]);
630
+ });
631
+ });
@@ -1,5 +1,5 @@
1
- import { RecordId } from 'surrealdb';
2
- import { RecordVersionArray, RecordVersionDiff } from '../../types';
1
+ import type { RecordId } from 'surrealdb';
2
+ import type { RecordVersionArray, RecordVersionDiff } from '../../types';
3
3
  import { parseRecordIdString, encodeRecordId } from '../../utils/index';
4
4
 
5
5
  export class ArraySyncer {
@@ -8,8 +8,8 @@ export class ArraySyncer {
8
8
  private needsSort = false;
9
9
 
10
10
  constructor(localArray: RecordVersionArray, remoteArray: RecordVersionArray) {
11
- this.remoteArray = remoteArray.sort((a, b) => a[0].localeCompare(b[0]));
12
- this.localArray = localArray.sort((a, b) => a[0].localeCompare(b[0]));
11
+ this.remoteArray = remoteArray.toSorted((a, b) => a[0].localeCompare(b[0]));
12
+ this.localArray = localArray.toSorted((a, b) => a[0].localeCompare(b[0]));
13
13
  }
14
14
 
15
15
  /**
@@ -92,10 +92,12 @@ export function diffRecordVersionArray(
92
92
  return {
93
93
  added: added.map((id) => ({
94
94
  id: parseRecordIdString(id),
95
+ // oxlint-disable-next-line no-non-null-assertion
95
96
  version: remoteMap.get(id)!,
96
97
  })),
97
98
  updated: updated.map((id) => ({
98
99
  id: parseRecordIdString(id),
100
+ // oxlint-disable-next-line no-non-null-assertion
99
101
  version: remoteMap.get(id)!,
100
102
  })),
101
103
  removed: removed.map(parseRecordIdString),
@@ -126,7 +128,7 @@ export function applyRecordVersionDiff(
126
128
  currentMap.set(encodeRecordId(item.id), item.version);
127
129
  }
128
130
 
129
- return Array.from(currentMap).sort((a, b) => a[0].localeCompare(b[0]));
131
+ return Array.from(currentMap).toSorted((a, b) => a[0].localeCompare(b[0]));
130
132
  }
131
133
 
132
134
  export function createDiffFromDbOp(
@@ -135,17 +137,14 @@ export function createDiffFromDbOp(
135
137
  version: number,
136
138
  versions?: RecordVersionArray
137
139
  ): RecordVersionDiff {
138
- // Version guard: skip stale CREATE/UPDATE, but always process DELETE
139
- if (op !== 'DELETE') {
140
- const old = versions?.find((record) => record[0] === encodeRecordId(recordId));
141
-
142
- if (old && old[1] >= version) {
143
- return {
144
- added: [],
145
- updated: [],
146
- removed: [],
147
- };
148
- }
140
+ const old = versions?.find((record) => record[0] === encodeRecordId(recordId));
141
+
142
+ if (old && old[1] >= version) {
143
+ return {
144
+ added: [],
145
+ updated: [],
146
+ removed: [],
147
+ };
149
148
  }
150
149
 
151
150
  if (op === 'CREATE') {
@@ -168,3 +167,274 @@ export function createDiffFromDbOp(
168
167
  };
169
168
  }
170
169
  }
170
+
171
+ /**
172
+ * Default cadence for the `_00_list_ref_user_<id>` poll fallback. The
173
+ * poll is the safety net for SurrealDB v3's occasionally-dropped LIVE
174
+ * deliveries; 500ms is aggressive enough to feel real-time on the
175
+ * happy path while keeping the per-session query load bounded.
176
+ */
177
+ export const DEFAULT_LIST_REF_POLL_INTERVAL_MS = 500;
178
+
179
+ /**
180
+ * Build the SurrealQL select that powers both the initial-fetch and
181
+ * the periodic poll of `_00_list_ref[_user_<id>]`. The `parent IS NONE`
182
+ * predicate excludes subquery entries (rows with `parent_rel` set)
183
+ * because the client's `RecordVersionArray` only tracks primary rows;
184
+ * including subquery rows would surface them as spurious "added"
185
+ * diffs every tick.
186
+ */
187
+ export function buildListRefSelect(table: string): string {
188
+ return `SELECT out, version FROM ${table} WHERE in = $in AND parent IS NONE`;
189
+ }
190
+
191
+ /**
192
+ * Build the select that says whether an EMPTY id-set means "this query has no
193
+ * rows" or "the server has not published them yet".
194
+ *
195
+ * The SSP writes `rowCount` onto the `_00_query` row in the same statement that
196
+ * registers the view — synchronously, and BEFORE it hands the view's initial
197
+ * edges to the coalescing edge flusher. So the two are not interchangeable:
198
+ * `rowCount > 0` with no edges is the flush window, and only `rowCount === 0`
199
+ * is a genuinely empty query. Polling the edges alone cannot tell those apart
200
+ * no matter how long it waits, which is why this is read alongside them rather
201
+ * than a retry counter.
202
+ *
203
+ * `state` rides along: the SSP writes `materializing` when it hands a full
204
+ * publish to its edge flusher and flips it to `ready` INSIDE the transaction
205
+ * that writes the edges. So `ready` + no edges + `rowCount 0` is a real empty
206
+ * result, `materializing` + no edges is "still publishing", and a missing row
207
+ * (the whole object is `NONE`) is "the server no longer has this view". A
208
+ * server that predates the marker returns `state: NONE` and callers fall back
209
+ * to `rowCount` alone.
210
+ *
211
+ * Returns `NONE` (→ null) when the row is not readable or does not exist yet;
212
+ * callers must treat that as "unknown", not as zero.
213
+ */
214
+ export function buildQueryRowCountSelect(): string {
215
+ return 'SELECT VALUE { rowCount: rowCount, state: state } FROM ONLY $in';
216
+ }
217
+
218
+ /**
219
+ * Build the SurrealQL select for a query's SUBQUERY child edges — the
220
+ * mirror of {@link buildListRefSelect}. `.related()` queries register a
221
+ * correlated subquery; the SSP materializes each matched child as a
222
+ * `_00_list_ref` edge tagged with `parent`/`parent_rel` (see
223
+ * `apps/ssp` edge writer). `parent IS NONE` (the primary select) drops
224
+ * these, so their bodies never reach the local cache and a cold-reload
225
+ * re-materialization of the correlated surql yields empty related
226
+ * fields. This `parent IS NOT NONE` variant pulls the child `out`+`version`
227
+ * pairs (any nesting depth) so we can sync their bodies into the local
228
+ * store SEPARATELY from the primary window array.
229
+ */
230
+ export function buildSubqueryListRefSelect(table: string): string {
231
+ return `SELECT out, version FROM ${table} WHERE in = $in AND parent IS NOT NONE`;
232
+ }
233
+
234
+ /**
235
+ * One round trip for the edges of MANY queries: primary and subquery rows
236
+ * together, split client-side on `parent`. Replaces two selects per query per
237
+ * poll tick, which on a page with 20+ live queries was ~50 serialized round
238
+ * trips per cycle and kept the remote busy full-time.
239
+ */
240
+ export function buildListRefBatchSelect(table: string): string {
241
+ return `SELECT in, out, version, parent FROM ${table} WHERE in IN $ins`;
242
+ }
243
+
244
+ /**
245
+ * `rowCount` for many `_00_query` rows at once, keyed by id so the caller does
246
+ * not depend on the array order. Same semantics as
247
+ * {@link buildQueryRowCountSelect}: a row the session cannot read comes back
248
+ * without an id and must be treated as "unknown".
249
+ */
250
+ export function buildQueryRowCountBatchSelect(): string {
251
+ return 'SELECT VALUE { id: id, rowCount: rowCount, state: state } FROM $ins';
252
+ }
253
+
254
+ /** Known edges one poll round trip may carry before the cycle is split. */
255
+ export const LIST_REF_POLL_ROW_BUDGET = 1_500;
256
+ /** A view at or past this many edges is "large": it rides on LIVE and is only
257
+ * re-polled every {@link LIST_REF_POLL_LARGE_VIEW_MIN_AGE_MS}. */
258
+ export const LIST_REF_POLL_LARGE_VIEW_ROWS = 1_000;
259
+ export const LIST_REF_POLL_LARGE_VIEW_MIN_AGE_MS = 15_000;
260
+
261
+ export interface ListRefPollCandidate {
262
+ hash: string;
263
+ /** Edges the client currently holds for the query (`remoteArray.length`). */
264
+ rows: number;
265
+ /** When the query was last refreshed by the poll; `0` = never. */
266
+ lastPolledAt: number;
267
+ }
268
+
269
+ /**
270
+ * Split the active queries into the round trips of one poll cycle.
271
+ *
272
+ * Every query that is due is refreshed once per cycle, oldest refresh first,
273
+ * packed greedily into chunks of at most `rowBudget` known edges so one
274
+ * response never carries a whole page's worth of ids at once. A view with
275
+ * `largeViewRows` or more edges is only due once `largeViewMinAgeMs` has
276
+ * passed since its last refresh (LIVE remains its primary path); a chunk
277
+ * always holds at least one query, so a single huge view still refreshes.
278
+ */
279
+ export function planListRefPollChunks(
280
+ candidates: ListRefPollCandidate[],
281
+ opts: { now: number; rowBudget?: number; largeViewRows?: number; largeViewMinAgeMs?: number }
282
+ ): string[][] {
283
+ const {
284
+ now,
285
+ rowBudget = LIST_REF_POLL_ROW_BUDGET,
286
+ largeViewRows = LIST_REF_POLL_LARGE_VIEW_ROWS,
287
+ largeViewMinAgeMs = LIST_REF_POLL_LARGE_VIEW_MIN_AGE_MS,
288
+ } = opts;
289
+ const due = candidates
290
+ .filter((c) => c.rows < largeViewRows || now - c.lastPolledAt >= largeViewMinAgeMs)
291
+ .sort(
292
+ (a, b) => a.lastPolledAt - b.lastPolledAt || (a.hash < b.hash ? -1 : a.hash > b.hash ? 1 : 0)
293
+ );
294
+ const chunks: string[][] = [];
295
+ let current: string[] = [];
296
+ let currentRows = 0;
297
+ for (const c of due) {
298
+ const cost = Math.max(1, c.rows);
299
+ if (current.length > 0 && currentRows + cost > rowBudget) {
300
+ chunks.push(current);
301
+ current = [];
302
+ currentRows = 0;
303
+ }
304
+ current.push(c.hash);
305
+ currentRows += cost;
306
+ }
307
+ if (current.length > 0) chunks.push(current);
308
+ return chunks;
309
+ }
310
+
311
+ /**
312
+ * Resolve the effective list-ref poll interval. Negative or zero
313
+ * values fall back to the default — accepting them would either
314
+ * disable polling silently or busy-loop the event loop.
315
+ */
316
+ export function resolveListRefPollInterval(opt?: number): number {
317
+ if (typeof opt !== 'number' || !Number.isFinite(opt) || opt <= 0) {
318
+ return DEFAULT_LIST_REF_POLL_INTERVAL_MS;
319
+ }
320
+ return opt;
321
+ }
322
+
323
+ /**
324
+ * When the LIVE feed has delivered an event within this window, treat
325
+ * the LIVE subscription as healthy and back the poll off to
326
+ * {@link LIVE_HEALTHY_POLL_INTERVAL_MS}. As soon as LIVE quiets for
327
+ * longer than this, the poll snaps back to the aggressive default.
328
+ */
329
+ export const LIVE_HEALTHY_COOLDOWN_MS = 5_000;
330
+
331
+ /**
332
+ * Poll interval while LIVE is delivering events. The aggressive
333
+ * default 500ms costs ~120 queries / minute / session — wasted work
334
+ * when LIVE is already covering us. 5s keeps the safety net in place
335
+ * at 1/10th the load.
336
+ */
337
+ export const LIVE_HEALTHY_POLL_INTERVAL_MS = 5_000;
338
+
339
+ /**
340
+ * Pick the next poll delay based on whether LIVE has been healthy
341
+ * recently. If a LIVE event fired within `cooldownMs`, use the slow
342
+ * (`healthyIntervalMs`) cadence; otherwise the fast (`baseIntervalMs`)
343
+ * cadence. Pure so it's unit-testable; `Sp00kySync.startListRefPoll`
344
+ * calls it from a self-rescheduling timer.
345
+ *
346
+ * The healthy interval is clamped to at least `baseIntervalMs` so
347
+ * configuring an aggressive base (e.g. 100ms) never gets implicitly
348
+ * widened by this helper.
349
+ *
350
+ * @deprecated Superseded by {@link listRefPollDelayMs}, which backs the
351
+ * poll off based on observed change activity (LIVE *or* poll-detected)
352
+ * rather than LIVE liveness alone — the cross-session LIVE-permission gap
353
+ * means LIVE often never fires, so this helper would keep the poll pinned
354
+ * at the aggressive base forever even on a fully idle page. Kept (and
355
+ * tested) for reference.
356
+ */
357
+ export function nextPollDelayMs(args: {
358
+ now: number;
359
+ lastLiveEventAt: number | null;
360
+ baseIntervalMs: number;
361
+ cooldownMs?: number;
362
+ healthyIntervalMs?: number;
363
+ }): number {
364
+ const {
365
+ now,
366
+ lastLiveEventAt,
367
+ baseIntervalMs,
368
+ cooldownMs = LIVE_HEALTHY_COOLDOWN_MS,
369
+ healthyIntervalMs = LIVE_HEALTHY_POLL_INTERVAL_MS,
370
+ } = args;
371
+ if (lastLiveEventAt === null) return baseIntervalMs;
372
+ const sinceLive = now - lastLiveEventAt;
373
+ if (sinceLive < 0 || sinceLive >= cooldownMs) return baseIntervalMs;
374
+ return Math.max(healthyIntervalMs, baseIntervalMs);
375
+ }
376
+
377
+ /**
378
+ * Ceiling for the adaptive list_ref poll backoff. An idle page (no LIVE
379
+ * events, no poll-detected list_ref changes) coasts up to this cadence;
380
+ * the existing healthy-LIVE safety net runs at the same 5s, so this keeps
381
+ * the worst-case catch-up latency for a missed cross-session change at the
382
+ * cadence the codebase already treats as acceptable.
383
+ */
384
+ export const LIST_REF_POLL_MAX_INTERVAL_MS = 5_000;
385
+
386
+ /**
387
+ * Adaptive poll delay: stay at the responsive `baseIntervalMs` while
388
+ * changes are arriving, and exponentially back off toward `maxIntervalMs`
389
+ * while the `_00_list_ref` is quiet.
390
+ *
391
+ * `idleStreak` is the count of consecutive poll cycles that observed *no*
392
+ * change. `Sp00kySync` resets it to 0 whenever a poll detects a real
393
+ * remoteArray change OR a LIVE event lands, so any activity snaps the poll
394
+ * straight back to `baseIntervalMs`. A streak of 0 (something just
395
+ * happened) → base; otherwise `base * 2^streak` capped at `maxIntervalMs`.
396
+ *
397
+ * This replaces {@link nextPollDelayMs}: the old helper slowed the poll
398
+ * only while LIVE was *delivering*, but the cross-session LIVE-permission
399
+ * gap means LIVE frequently never fires here, so it left a fully idle page
400
+ * polling every `base` ms forever (the "continuous queries while idle"
401
+ * symptom). Backing off on observed idleness instead covers the
402
+ * LIVE-healthy case for free (LIVE applies the change → the next poll sees
403
+ * nothing new → the streak grows → it backs off).
404
+ */
405
+ export function listRefPollDelayMs(args: {
406
+ idleStreak: number;
407
+ baseIntervalMs: number;
408
+ maxIntervalMs?: number;
409
+ }): number {
410
+ const { idleStreak, baseIntervalMs, maxIntervalMs = LIST_REF_POLL_MAX_INTERVAL_MS } = args;
411
+ const cap = Math.max(baseIntervalMs, maxIntervalMs);
412
+ if (idleStreak <= 0) return baseIntervalMs;
413
+ // 2^streak grows fast; clamp the exponent so it can't overflow on a
414
+ // page left idle for a very long time.
415
+ const exponent = Math.min(idleStreak, 30);
416
+ return Math.min(baseIntervalMs * 2 ** exponent, cap);
417
+ }
418
+
419
+ /**
420
+ * Order-insensitive equality for two `RecordVersionArray`s (each a list of
421
+ * `[recordIdString, version]`). The `_00_list_ref` SELECT has no `ORDER
422
+ * BY`, so row order can differ between polls without anything having
423
+ * actually changed — comparing as an id→version map avoids false
424
+ * "changed" verdicts that would defeat the idle backoff. Record ids are
425
+ * unique within a query's list_ref, so a map is a faithful representation.
426
+ */
427
+ export function recordVersionArraysEqual(
428
+ a: RecordVersionArray,
429
+ b: RecordVersionArray
430
+ ): boolean {
431
+ if (a === b) return true;
432
+ if (a.length !== b.length) return false;
433
+ const byId = new Map<string, number>();
434
+ for (const [id, version] of a) byId.set(id, version);
435
+ for (const [id, version] of b) {
436
+ // `get` returns undefined for a missing id, which never === a number.
437
+ if (byId.get(id) !== version) return false;
438
+ }
439
+ return true;
440
+ }