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

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 (261) hide show
  1. package/AGENTS.md +57 -21
  2. package/README.md +59 -16
  3. package/dist/index.d.ts +2096 -929
  4. package/dist/index.js +18217 -5019
  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/sqlite-open.js +392 -0
  11. package/dist/sqlite-worker.d.ts +1 -0
  12. package/dist/sqlite-worker.js +439 -0
  13. package/dist/sw.d.ts +207 -0
  14. package/dist/sw.js +393 -0
  15. package/dist/tabs-broker-worker.d.ts +8 -0
  16. package/dist/tabs-broker-worker.js +477 -0
  17. package/dist/types.d.ts +1968 -82
  18. package/dist/worker-edges.js +498 -0
  19. package/dist/worker-impersonation.js +60 -0
  20. package/dist/worker-ref-tables.d.ts +48 -0
  21. package/dist/worker-types.d.ts +112 -0
  22. package/dist/worker-types.js +73 -0
  23. package/package.json +34 -8
  24. package/scripts/check-broker-bundle.mjs +33 -0
  25. package/scripts/check-worker-entries.mjs +173 -0
  26. package/skills/sp00ky-core/SKILL.md +42 -8
  27. package/skills/sp00ky-core/references/config.md +8 -2
  28. package/src/boot/auth-flip.saga.test.ts +174 -0
  29. package/src/boot/auth-flip.saga.ts +77 -0
  30. package/src/boot/boot.saga.test.ts +203 -0
  31. package/src/boot/boot.saga.ts +146 -0
  32. package/src/boot/bucket-switch.saga.test.ts +191 -0
  33. package/src/boot/bucket-switch.saga.ts +151 -0
  34. package/src/boot/preload.saga.test.ts +96 -0
  35. package/src/boot/preload.saga.ts +45 -0
  36. package/src/bucket-blurhash.test.ts +148 -0
  37. package/src/client/bucket-handle.test.ts +195 -0
  38. package/src/client/bucket-handle.ts +352 -0
  39. package/src/client/router.test.ts +59 -0
  40. package/src/client/router.ts +104 -0
  41. package/src/client/runtime.test.ts +319 -0
  42. package/src/client/runtime.ts +307 -0
  43. package/src/client/services.test.ts +74 -0
  44. package/src/client/services.ts +437 -0
  45. package/src/client/sp00ky-client.test.ts +428 -0
  46. package/src/client/sp00ky-client.ts +737 -0
  47. package/src/index.ts +78 -0
  48. package/src/kernel/constants.test.ts +19 -0
  49. package/src/kernel/constants.ts +94 -0
  50. package/src/kernel/effects.test.ts +40 -0
  51. package/src/kernel/effects.ts +171 -0
  52. package/src/kernel/events.ts +60 -0
  53. package/src/kernel/interpreter.test.ts +116 -0
  54. package/src/kernel/interpreter.ts +148 -0
  55. package/src/kernel/saga.test.ts +89 -0
  56. package/src/kernel/saga.ts +73 -0
  57. package/src/live/index.test.ts +512 -0
  58. package/src/live/index.ts +1059 -0
  59. package/src/modules/app-release/index.test.ts +125 -0
  60. package/src/modules/app-release/index.ts +209 -0
  61. package/src/modules/auth/auth.local-first.test.ts +228 -0
  62. package/src/modules/auth/auth.session-recheck.test.ts +140 -0
  63. package/src/modules/auth/events/index.ts +7 -1
  64. package/src/modules/auth/impersonation-banner.ts +443 -0
  65. package/src/modules/auth/impersonation.integration.test.ts +209 -0
  66. package/src/modules/auth/impersonation.test.ts +377 -0
  67. package/src/modules/auth/impersonation.ts +179 -0
  68. package/src/modules/auth/index.ts +516 -34
  69. package/src/modules/channel/channel.test.ts +752 -0
  70. package/src/modules/channel/index.ts +1153 -0
  71. package/src/modules/channel/webrtc.ts +472 -0
  72. package/src/modules/crdt/acceptance.ts +75 -0
  73. package/src/modules/crdt/bytes.ts +50 -0
  74. package/src/modules/crdt/crdt-field.ts +82 -238
  75. package/src/modules/crdt/crdt.test.ts +546 -0
  76. package/src/modules/crdt/hash.ts +103 -0
  77. package/src/modules/crdt/index.ts +740 -271
  78. package/src/modules/crdt/loro-loader.ts +25 -0
  79. package/src/modules/crdt/mirror.ts +37 -0
  80. package/src/modules/devtools/flags.ts +349 -0
  81. package/src/modules/devtools/index.ts +661 -99
  82. package/src/modules/devtools/mutations.test.ts +92 -0
  83. package/src/modules/devtools/mutations.ts +160 -0
  84. package/src/modules/devtools/notify-throttle.test.ts +166 -0
  85. package/src/modules/devtools/state-shape.test.ts +263 -0
  86. package/src/modules/devtools/storage-info.test.ts +79 -0
  87. package/src/modules/devtools/storage-info.ts +168 -0
  88. package/src/modules/devtools/versions.ts +29 -0
  89. package/src/modules/feature-flag/index.test.ts +179 -1
  90. package/src/modules/feature-flag/index.ts +117 -10
  91. package/src/modules/ref-tables.test.ts +28 -1
  92. package/src/modules/ref-tables.ts +23 -1
  93. package/src/modules/web-push/index.test.ts +824 -0
  94. package/src/modules/web-push/index.ts +1027 -0
  95. package/src/mutation/ingest-outage.integration.test.ts +400 -0
  96. package/src/mutation/jobs.test.ts +25 -0
  97. package/src/mutation/jobs.ts +41 -0
  98. package/src/mutation/mutation-id.test.ts +37 -0
  99. package/src/mutation/mutation-id.ts +35 -0
  100. package/src/mutation/pending-writes.integration.test.ts +175 -0
  101. package/src/mutation/push.saga.test.ts +361 -0
  102. package/src/mutation/push.saga.ts +245 -0
  103. package/src/mutation/rows.test.ts +278 -0
  104. package/src/mutation/rows.ts +515 -0
  105. package/src/mutation/tray.saga.test.ts +63 -0
  106. package/src/mutation/tray.saga.ts +48 -0
  107. package/src/mutation/write.saga.test.ts +436 -0
  108. package/src/mutation/write.saga.ts +384 -0
  109. package/src/pure.ts +66 -0
  110. package/src/push/types.ts +174 -0
  111. package/src/query/anon-query-isolation.integration.test.ts +531 -0
  112. package/src/query/env.test.ts +23 -0
  113. package/src/query/env.ts +65 -0
  114. package/src/query/fetch.saga.test.ts +199 -0
  115. package/src/query/fetch.saga.ts +120 -0
  116. package/src/query/hash.test.ts +14 -0
  117. package/src/query/hash.ts +18 -0
  118. package/src/query/id-set-plan.test.ts +132 -0
  119. package/src/query/lifecycle.saga.test.ts +274 -0
  120. package/src/query/lifecycle.saga.ts +186 -0
  121. package/src/query/list-ref-live.integration.test.ts +203 -0
  122. package/src/query/materialize.saga.test.ts +200 -0
  123. package/src/query/materialize.saga.ts +102 -0
  124. package/src/query/materialize.test.ts +58 -0
  125. package/src/query/materialize.ts +57 -0
  126. package/src/query/membership.saga.test.ts +514 -0
  127. package/src/query/membership.saga.ts +339 -0
  128. package/src/query/membership.test.ts +151 -0
  129. package/src/query/membership.ts +234 -0
  130. package/src/query/register.saga.test.ts +369 -0
  131. package/src/query/register.saga.ts +293 -0
  132. package/src/query/render-set.test.ts +47 -0
  133. package/src/query/render-set.ts +71 -0
  134. package/src/query/session-guard.integration.test.ts +304 -0
  135. package/src/query/sql.test.ts +118 -0
  136. package/src/query/sql.ts +174 -0
  137. package/src/{modules/data → query}/window-query.test.ts +22 -4
  138. package/src/{modules/data → query}/window-query.ts +86 -8
  139. package/src/services/blobs/blob-cache.test.ts +359 -0
  140. package/src/services/blobs/blob-cache.ts +603 -0
  141. package/src/services/blobs/blob-manifest.ts +227 -0
  142. package/src/services/blobs/blob-store.test.ts +77 -0
  143. package/src/services/blobs/blob-store.ts +359 -0
  144. package/src/services/blobs/blob.fixture.ts +90 -0
  145. package/src/services/blobs/index.ts +70 -0
  146. package/src/services/database/cache-engine.ts +209 -0
  147. package/src/services/database/connection-supervisor.test.ts +318 -0
  148. package/src/services/database/connection-supervisor.ts +422 -0
  149. package/src/services/database/database.query-timeout.test.ts +140 -0
  150. package/src/services/database/database.responses.test.ts +43 -0
  151. package/src/services/database/database.ts +151 -56
  152. package/src/services/database/engine-factory.ts +33 -0
  153. package/src/services/database/errors.ts +34 -0
  154. package/src/services/database/index.ts +7 -0
  155. package/src/services/database/landed-body-clear.integration.test.ts +236 -0
  156. package/src/services/database/local-migrator.integration.test.ts +110 -0
  157. package/src/services/database/local-migrator.ts +54 -9
  158. package/src/services/database/local.test.ts +117 -0
  159. package/src/services/database/local.ts +364 -74
  160. package/src/services/database/plan-render.test.ts +159 -0
  161. package/src/services/database/plan-render.ts +108 -0
  162. package/src/services/database/relation-resolver.test.ts +484 -0
  163. package/src/services/database/relation-resolver.ts +0 -0
  164. package/src/services/database/remote.ts +283 -4
  165. package/src/services/database/sqlite-cache-engine.test.ts +628 -0
  166. package/src/services/database/sqlite-cache-engine.timeout.test.ts +61 -0
  167. package/src/services/database/sqlite-cache-engine.ts +1401 -0
  168. package/src/services/database/sqlite-column-reset.integration.test.ts +100 -0
  169. package/src/services/database/sqlite-column-reset.ts +91 -0
  170. package/src/services/database/sqlite-devtools-queries.integration.test.ts +143 -0
  171. package/src/services/database/sqlite-devtools-queries.test.ts +154 -0
  172. package/src/services/database/sqlite-lock-verify.test.ts +33 -0
  173. package/src/services/database/sqlite-lock-verify.ts +45 -0
  174. package/src/services/database/sqlite-open.test.ts +150 -0
  175. package/src/services/database/sqlite-open.ts +164 -0
  176. package/src/services/database/sqlite-plan-sql.test.ts +164 -0
  177. package/src/services/database/sqlite-plan-sql.ts +196 -0
  178. package/src/services/database/sqlite-projection.test.ts +121 -0
  179. package/src/services/database/sqlite-select.integration.test.ts +185 -0
  180. package/src/services/database/sqlite-select.test.ts +261 -0
  181. package/src/services/database/sqlite-select.ts +131 -0
  182. package/src/services/database/sqlite-transport.fixture.ts +30 -0
  183. package/src/services/database/sqlite-transport.ts +229 -0
  184. package/src/services/database/sqlite-worker.ts +437 -0
  185. package/src/services/database/surql-translate.ts +417 -0
  186. package/src/services/database/surreal-cache-engine.ts +163 -0
  187. package/src/services/logger/index.test.ts +132 -0
  188. package/src/services/logger/index.ts +187 -6
  189. package/src/services/persistence/surrealdb.ts +2 -2
  190. package/src/services/stream-processor/index.ts +621 -93
  191. package/src/services/stream-processor/stream-processor.batch.test.ts +57 -7
  192. package/src/services/stream-processor/stream-processor.prime.test.ts +234 -0
  193. package/src/services/stream-processor/stream-processor.reset.test.ts +226 -0
  194. package/src/services/stream-processor/wasm-types.ts +41 -1
  195. package/src/services/tabs/broker-client.ts +284 -0
  196. package/src/services/tabs/broker.test.ts +381 -0
  197. package/src/services/tabs/coordinator.test.ts +386 -0
  198. package/src/services/tabs/coordinator.ts +646 -0
  199. package/src/services/tabs/fake-ports.fixture.ts +112 -0
  200. package/src/services/tabs/leader-locks.ts +75 -0
  201. package/src/services/tabs/protocol.ts +262 -0
  202. package/src/services/tabs/support.ts +36 -0
  203. package/src/services/tabs/tabs-broker-worker.ts +652 -0
  204. package/src/sp00ky.ts +5 -648
  205. package/src/state/client-state.ts +231 -0
  206. package/src/state/lifecycle.test.ts +184 -0
  207. package/src/state/lifecycle.ts +127 -0
  208. package/src/state/reducers.test.ts +337 -0
  209. package/src/state/reducers.ts +571 -0
  210. package/src/state/selectors.test.ts +203 -0
  211. package/src/state/selectors.ts +264 -0
  212. package/src/sw/index.test.ts +582 -0
  213. package/src/sw/index.ts +607 -0
  214. package/src/sw/store.ts +96 -0
  215. package/src/sync/connection.saga.test.ts +97 -0
  216. package/src/sync/connection.saga.ts +89 -0
  217. package/src/sync/live.saga.test.ts +229 -0
  218. package/src/sync/live.saga.ts +116 -0
  219. package/src/sync/policy.health.test.ts +56 -0
  220. package/src/{modules/sync/utils.test.ts → sync/policy.test.ts} +96 -11
  221. package/src/{modules/sync/utils.ts → sync/policy.ts} +186 -7
  222. package/src/sync/poll.saga.test.ts +51 -0
  223. package/src/sync/poll.saga.ts +36 -0
  224. package/src/sync/tabs.saga.test.ts +78 -0
  225. package/src/sync/tabs.saga.ts +96 -0
  226. package/src/testing/adapters.ts +137 -0
  227. package/src/testing/build.ts +63 -0
  228. package/src/testing/fake-services.ts +63 -0
  229. package/src/testing/run-pure.test.ts +92 -0
  230. package/src/testing/run-pure.ts +128 -0
  231. package/src/testing/services.ts +17 -0
  232. package/src/types.ts +568 -25
  233. package/src/utils/blurhash.ts +90 -0
  234. package/src/utils/edges.ts +57 -0
  235. package/src/utils/error-classification.test.ts +116 -0
  236. package/src/utils/error-classification.ts +74 -0
  237. package/src/utils/index.ts +58 -3
  238. package/src/utils/parser.test.ts +67 -102
  239. package/src/utils/parser.ts +62 -1
  240. package/src/utils/semver.test.ts +32 -0
  241. package/src/utils/semver.ts +30 -0
  242. package/src/utils/sha256.ts +15 -0
  243. package/src/utils/surql.ts +17 -15
  244. package/src/utils/utils.test.ts +3 -2
  245. package/tsdown.config.ts +64 -4
  246. package/vitest.config.ts +48 -0
  247. package/src/modules/cache/index.ts +0 -253
  248. package/src/modules/cache/types.ts +0 -19
  249. package/src/modules/crdt/crdt-hydration.test.ts +0 -206
  250. package/src/modules/data/data.status.test.ts +0 -108
  251. package/src/modules/data/data.test.ts +0 -58
  252. package/src/modules/data/index.ts +0 -1491
  253. package/src/modules/sync/engine.ts +0 -227
  254. package/src/modules/sync/events/index.ts +0 -84
  255. package/src/modules/sync/index.ts +0 -3
  256. package/src/modules/sync/queue/index.ts +0 -2
  257. package/src/modules/sync/queue/queue-down.ts +0 -90
  258. package/src/modules/sync/queue/queue-up.ts +0 -224
  259. package/src/modules/sync/scheduler.ts +0 -121
  260. package/src/modules/sync/sync.ts +0 -1244
  261. package/src/sp00ky.auth-order.test.ts +0 -65
@@ -1,5 +1,5 @@
1
1
  import type { ColumnSchema} from '@spooky-sync/query-builder';
2
- import { RecordId } from '@spooky-sync/query-builder';
2
+ import { RecordId, baseFieldOfParam } from '@spooky-sync/query-builder';
3
3
  import { parseRecordIdString } from './index';
4
4
  import { DateTime } from 'surrealdb';
5
5
 
@@ -16,6 +16,42 @@ export function cleanRecord(
16
16
  return cleaned;
17
17
  }
18
18
 
19
+ /**
20
+ * The OPTIONAL schema columns a full server row does not carry, each mapped to
21
+ * `undefined`, for spreading into a body that is landed with MERGE.
22
+ *
23
+ * The server omits an optional field that is unset (`UPDATE t UNSET club`
24
+ * leaves no `club` key in `SELECT *` or the SSP body), and MERGE keeps every
25
+ * key the patch does not mention, so without this the local store held on to
26
+ * a cleared value forever. `undefined` is the one representation both engines
27
+ * read as "remove": the SurrealDB SDK encodes it as NONE, which MERGE removes
28
+ * (NULL would be a type error on an `option<record<...>>` field), and the
29
+ * SQLite engine turns it into the `null` member that `json_patch` removes (see
30
+ * `serializeMergeRow`).
31
+ *
32
+ * Required columns are left alone. A SCHEMAFULL server cannot hold NONE in
33
+ * one, so its absence means the row was not readable in full (a field
34
+ * permission), not that it was cleared, and NONE in a typed local store is a
35
+ * coercion error that would fail the whole chunk's transaction. `id` and the
36
+ * local-only `_00_*` bookkeeping are never touched.
37
+ */
38
+ export function absentOptionalColumns(
39
+ tableSchema: Record<string, ColumnSchema> | undefined,
40
+ record: Record<string, unknown>
41
+ ): Record<string, undefined> {
42
+ const cleared: Record<string, undefined> = {};
43
+ if (!tableSchema) return cleared;
44
+ for (const [key, column] of Object.entries(tableSchema)) {
45
+ if (key === 'id' || key.startsWith('_00_') || column?.optional !== true) continue;
46
+ if (record[key] === undefined) cleared[key] = undefined;
47
+ }
48
+ return cleared;
49
+ }
50
+
51
+ /**
52
+ * Parse a RECORD's fields against the table schema. Anything the schema does not
53
+ * know is dropped, which is what keeps a stray field out of a write.
54
+ */
19
55
  export function parseParams(
20
56
  tableSchema: Record<string, ColumnSchema>,
21
57
  params: Record<string, any>
@@ -31,6 +67,31 @@ export function parseParams(
31
67
  return parsedParams;
32
68
  }
33
69
 
70
+ /**
71
+ * Parse a QUERY's params. Unlike a record's fields, a param name is not always a
72
+ * column: an `_or` branch binds under a synthetic `white__or0` (see
73
+ * `orParamName` in @spooky-sync/query-builder), and the surql that references it
74
+ * is already written. So resolve the column through the synthetic name, and keep
75
+ * a param we cannot type rather than dropping it.
76
+ *
77
+ * Dropping was the bug: `parseParams` kept only column-named params, so every
78
+ * `_or` query registered with `$or0`/`$or1` unbound and matched no rows at all,
79
+ * silently (rowCount 0, errorCount 0).
80
+ */
81
+ export function parseQueryParams(
82
+ tableSchema: Record<string, ColumnSchema>,
83
+ params: Record<string, any>
84
+ ) {
85
+ const parsedParams: Record<string, any> = {};
86
+ for (const [key, value] of Object.entries(params)) {
87
+ if (value === undefined) continue;
88
+ const column = tableSchema[key] ?? tableSchema[baseFieldOfParam(key)];
89
+ parsedParams[key] = column ? parseValue(key, column, value) : value;
90
+ }
91
+
92
+ return parsedParams;
93
+ }
94
+
34
95
  function parseValue(name: string, column: ColumnSchema, value: any) {
35
96
  if (column.recordId) {
36
97
  if (value instanceof RecordId) return value;
@@ -0,0 +1,32 @@
1
+ import { describe, it, expect } from 'vitest';
2
+ import { semverGt } from './semver';
3
+
4
+ describe('semverGt', () => {
5
+ it('compares strictly greater', () => {
6
+ expect(semverGt('1.0.1', '1.0.0')).toBe(true);
7
+ expect(semverGt('1.1.0', '1.0.9')).toBe(true);
8
+ expect(semverGt('2.0.0', '1.9.9')).toBe(true);
9
+ expect(semverGt('1.10.0', '1.9.0')).toBe(true); // numeric, not lexicographic
10
+ });
11
+
12
+ it('equal and lower are not greater', () => {
13
+ expect(semverGt('1.0.0', '1.0.0')).toBe(false);
14
+ expect(semverGt('1.0.0', '1.0.1')).toBe(false);
15
+ expect(semverGt('0.9.9', '1.0.0')).toBe(false);
16
+ });
17
+
18
+ it('missing parts default to zero', () => {
19
+ expect(semverGt('1.2', '1.2.0')).toBe(false);
20
+ expect(semverGt('1.2.1', '1.2')).toBe(true);
21
+ expect(semverGt('2', '1.9.9')).toBe(true);
22
+ });
23
+
24
+ it('junk never compares greater', () => {
25
+ expect(semverGt('abc', '1.0.0')).toBe(false);
26
+ expect(semverGt('1.0.0', 'abc')).toBe(false);
27
+ expect(semverGt('', '0.0.0')).toBe(false);
28
+ expect(semverGt(null, undefined)).toBe(false);
29
+ expect(semverGt('1.0.0-beta', '0.9.0')).toBe(false); // prerelease unsupported
30
+ expect(semverGt('1.2.3.4', '1.0.0')).toBe(false);
31
+ });
32
+ });
@@ -0,0 +1,30 @@
1
+ // Minimal semver comparison for app-release version checks. "X.Y.Z" numeric
2
+ // with missing parts read as 0 ("1.2" == "1.2.0"); any malformed input never
3
+ // compares greater, so a bad release row can never nag (or force-reload)
4
+ // every client.
5
+
6
+ function parse(v: unknown): [number, number, number] | null {
7
+ const parts = String(v ?? '')
8
+ .trim()
9
+ .split('.');
10
+ if (parts.length === 0 || parts.length > 3 || parts[0] === '') return null;
11
+ const nums: number[] = [];
12
+ for (let i = 0; i < 3; i++) {
13
+ const raw = parts[i] ?? '0';
14
+ if (!/^\d+$/.test(raw)) return null;
15
+ nums.push(parseInt(raw, 10));
16
+ }
17
+ return nums as [number, number, number];
18
+ }
19
+
20
+ /** True when `a` is a valid version strictly greater than valid version `b`. */
21
+ export function semverGt(a: unknown, b: unknown): boolean {
22
+ const pa = parse(a);
23
+ const pb = parse(b);
24
+ if (!pa || !pb) return false;
25
+ for (let i = 0; i < 3; i++) {
26
+ if (pa[i] > pb[i]) return true;
27
+ if (pa[i] < pb[i]) return false;
28
+ }
29
+ return false;
30
+ }
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Lowercase hex SHA-256 of a UTF-8 string, through WebCrypto.
3
+ *
4
+ * Pure and dependency free so it can live in `@spooky-sync/core/pure` and run
5
+ * in a service worker, a dedicated worker or Node (`globalThis.crypto` is
6
+ * there on Node 19+). Query keys are `sha256Hex(JSON.stringify(..))`, see
7
+ * `query/hash.ts`.
8
+ */
9
+ export async function sha256Hex(input: string): Promise<string> {
10
+ const bytes = new TextEncoder().encode(input);
11
+ const digest = await crypto.subtle.digest('SHA-256', bytes);
12
+ return Array.from(new Uint8Array(digest))
13
+ .map((b) => b.toString(16).padStart(2, '0'))
14
+ .join('');
15
+ }
@@ -91,17 +91,9 @@ export const surql: SurqlHelper = {
91
91
  returnValues: ({ field: string; alias: string } | string)[]
92
92
  ) {
93
93
  return `SELECT ${returnValues
94
- .map((rv) =>
95
- typeof rv === 'string'
96
- ? rv
97
- : `${rv.field} as ${rv.alias}`
98
- )
94
+ .map((rv) => (typeof rv === 'string' ? rv : `${rv.field} as ${rv.alias}`))
99
95
  .join(',')} FROM ${table} WHERE ${whereVar
100
- .map((wv) =>
101
- typeof wv === 'string'
102
- ? `${wv} = $${wv}`
103
- : `${wv.field} = $${wv.variable}`
104
- )
96
+ .map((wv) => (typeof wv === 'string' ? `${wv} = $${wv}` : `${wv.field} = $${wv.variable}`))
105
97
  .join(' AND ')}`;
106
98
  },
107
99
 
@@ -128,10 +120,9 @@ export const surql: SurqlHelper = {
128
120
  return `UPSERT ONLY $${idVar} REPLACE $${dataVar}`;
129
121
  },
130
122
 
131
- // Use this for sync-down ingestion: the remote payload omits local-only
132
- // fields injected by the CLI's local-schema setup (`_00_crdt`,
133
- // `_00_cursor`), and REPLACE would wipe them on every round-trip and
134
- // break offline reload of CRDT state.
123
+ // Use this for sync-down ingestion: the remote payload can omit local-only
124
+ // fields injected by the CLI's local-schema setup, and REPLACE would wipe
125
+ // them on every round-trip.
135
126
  upsertMerge(idVar: string, dataVar: string) {
136
127
  return `UPSERT ONLY $${idVar} MERGE $${dataVar}`;
137
128
  },
@@ -172,7 +163,18 @@ export const surql: SurqlHelper = {
172
163
  ) {
173
164
  switch (t) {
174
165
  case 'create':
175
- return `CREATE ONLY $${mutationIdVar} SET mutationType = 'create', recordId = $${recordIdVar}`;
166
+ // `data` is REQUIRED here, not decorative. The outbox row is the only
167
+ // copy of a pending create once the in-memory UpEvent is gone (reload,
168
+ // or a shared-tabs follower whose row is replayed by the leader). This
169
+ // used to drop `dataVar` on the floor, so every replayed create arrived
170
+ // with `data: undefined` and `processUpEvent` threw on
171
+ // `Object.keys(event.data)` before it ever reached the network: the
172
+ // create was unsendable AND it sat at the head of the queue blocking
173
+ // every later mutation. The payload was simply never persisted, so
174
+ // those creates were unrecoverable.
175
+ return dataVar
176
+ ? `CREATE ONLY $${mutationIdVar} SET mutationType = 'create', recordId = $${recordIdVar}, data = $${dataVar}`
177
+ : `CREATE ONLY $${mutationIdVar} SET mutationType = 'create', recordId = $${recordIdVar}`;
176
178
  case 'update': {
177
179
  let stmt = `CREATE ONLY $${mutationIdVar} SET mutationType = 'update', recordId = $${recordIdVar}, data = $${dataVar}`;
178
180
  if (beforeRecordVar) {
@@ -9,6 +9,7 @@ import {
9
9
  generateId,
10
10
  parseDuration,
11
11
  } from './index';
12
+ import type { QueryTimeToLive } from '../types';
12
13
 
13
14
  describe('compareRecordIds', () => {
14
15
  it('returns true for equal strings', () => {
@@ -104,7 +105,7 @@ describe('parseRecordIdString', () => {
104
105
 
105
106
  it('parses id containing colons', () => {
106
107
  const rid = parseRecordIdString('table:part1:part2');
107
- expect(rid.table.toString()).toBe('table');
108
+ expect(rid.table.name).toBe('table');
108
109
  expect(rid.id).toBe('part1:part2');
109
110
  });
110
111
  });
@@ -123,7 +124,7 @@ describe('generateId', () => {
123
124
 
124
125
  describe('parseDuration', () => {
125
126
  it('parses seconds', () => {
126
- expect(parseDuration('30s')).toBe(30000);
127
+ expect(parseDuration('30s' as QueryTimeToLive)).toBe(30000);
127
128
  });
128
129
 
129
130
  it('parses minutes', () => {
package/tsdown.config.ts CHANGED
@@ -53,11 +53,71 @@ const versionDefinePlugin = {
53
53
  },
54
54
  };
55
55
 
56
- export default defineConfig({
57
- entry: ['src/index.ts', 'src/otel/index.ts'],
56
+ // Worker URLs are written as `./<name>.ts` in source so Vite's src-bundling
57
+ // consumers (the example app aliases core to `src`) resolve them. In the
58
+ // published build each worker is emitted at `dist/<name>.js`, so rewrite the
59
+ // references to `.js` here — otherwise the flat `dist/index.js` carries
60
+ // dangling `.ts` URLs that a consumer's bundler can't resolve.
61
+ const workerUrlPlugin = {
62
+ name: 'sp00ky-worker-url',
63
+ transform(code: string) {
64
+ if (!code.includes('sqlite-worker.ts') && !code.includes('tabs-broker-worker.ts')) return null;
65
+ return code
66
+ .split('sqlite-worker.ts')
67
+ .join('sqlite-worker.js')
68
+ .split('tabs-broker-worker.ts')
69
+ .join('tabs-broker-worker.js');
70
+ },
71
+ };
72
+
73
+ export default defineConfig([
74
+ {
75
+ // `sqlite-worker` is emitted at `dist/sqlite-worker.js` (top level, NOT under
76
+ // services/database) so the `new URL('./sqlite-worker.js', import.meta.url)`
77
+ // in `SqliteCacheEngine` — which gets bundled into the flat `dist/index.js` —
78
+ // resolves correctly. It (and `@sqlite.org/sqlite-wasm`) load lazily in the
79
+ // Worker; never pulled into the main bundle unless `localEngine: 'sqlite'`.
80
+ entry: {
81
+ index: 'src/index.ts',
82
+ 'otel/index': 'src/otel/index.ts',
83
+ 'sqlite-worker': 'src/services/database/sqlite-worker.ts',
84
+ // The shared-tabs broker MUST stay a self-contained emit (no chunk
85
+ // imports): bundlers cannot trace `new SharedWorker(url)` graphs, so a
86
+ // relative chunk import would 404 in consumers. The source keeps zero
87
+ // runtime imports and scripts/check-broker-bundle.mjs enforces it.
88
+ 'tabs-broker-worker': 'src/services/tabs/tabs-broker-worker.ts',
89
+ },
58
90
  format: ['esm'],
59
91
  dts: true,
60
92
  clean: true,
61
93
  hash: false,
62
- plugins: [versionDefinePlugin],
63
- });
94
+ plugins: [versionDefinePlugin, workerUrlPlugin],
95
+ },
96
+ // The wasm-free entries a service worker, a dedicated worker or Node can
97
+ // import: `/pure` (protocol builders), `/live` (the live feed over the
98
+ // pure-JS `surrealdb` SDK) and `/sw` (push handlers). Built separately so
99
+ // they never share a chunk with `index` (whose graph holds the wasm engines)
100
+ // and so `dist/index.js` stays one flat file. They may share chunks among
101
+ // themselves; scripts/check-worker-entries.mjs walks those too and fails
102
+ // the build on any wasm/pino import or top-level window/document access.
103
+ {
104
+ entry: {
105
+ pure: 'src/pure.ts',
106
+ live: 'src/live/index.ts',
107
+ sw: 'src/sw/index.ts',
108
+ },
109
+ format: ['esm'],
110
+ dts: true,
111
+ clean: false,
112
+ hash: false,
113
+ // Own prefix so a chunk of this build never overwrites one of the first
114
+ // (both write `dist/`; `types.d.ts` collided).
115
+ // The entries' own declaration files arrive as chunks named `<entry>.d`
116
+ // and must keep their plain name.
117
+ outputOptions: {
118
+ chunkFileNames: (chunk: { name: string }) =>
119
+ ['pure.d', 'live.d', 'sw.d'].includes(chunk.name) ? '[name].js' : 'worker-[name].js',
120
+ },
121
+ plugins: [versionDefinePlugin],
122
+ },
123
+ ]);
@@ -0,0 +1,48 @@
1
+ import { defineConfig } from 'vitest/config';
2
+
3
+ // Thresholds start at the numbers the suite hits today and are ratcheted per
4
+ // directory as the saga core lands (see the plan's commit 10). Exclusions:
5
+ // *.fixture.ts / src/testing/** test-only harness code
6
+ // sqlite-worker.ts runs inside a Worker (sqlite-wasm + OPFS +
7
+ // postMessage globals); covered by the sqlite
8
+ // integration tests and the build check
9
+ // client/services.ts constructs the real adapters (SurrealDB
10
+ // WASM store, socket, SharedWorker broker,
11
+ // OPFS blob cache); exercised by the example
12
+ // app and the WhitePawn A/B, not by vitest
13
+ export default defineConfig({
14
+ test: {
15
+ environment: 'node',
16
+ include: ['src/**/*.test.ts'],
17
+ coverage: {
18
+ provider: 'v8',
19
+ all: true,
20
+ reporter: ['text-summary', 'lcov'],
21
+ include: ['src/**/*.ts'],
22
+ exclude: [
23
+ 'src/**/*.test.ts',
24
+ 'src/**/*.d.ts',
25
+ 'src/**/*.fixture.ts',
26
+ 'src/testing/**',
27
+ 'src/services/database/sqlite-worker.ts',
28
+ 'src/client/services.ts',
29
+ ],
30
+ thresholds: {
31
+ // Global numbers are held back by the legacy adapters (devtools,
32
+ // sqlite engine, tabs broker, blobs, crdt); the saga core below is 100%.
33
+ lines: 75,
34
+ functions: 82,
35
+ branches: 87,
36
+ statements: 75,
37
+ 'src/kernel/**': { lines: 100, functions: 100, branches: 100, statements: 100 },
38
+ 'src/state/**': { lines: 100, functions: 100, branches: 100, statements: 100 },
39
+ 'src/query/**': { lines: 100, functions: 100, branches: 100, statements: 100 },
40
+ 'src/mutation/**': { lines: 100, functions: 100, branches: 100, statements: 100 },
41
+ 'src/sync/**': { lines: 100, functions: 100, branches: 100, statements: 100 },
42
+ 'src/boot/**': { lines: 100, functions: 100, branches: 100, statements: 100 },
43
+ // The facade's shared-tabs host callbacks need a SharedWorker broker to fire.
44
+ 'src/client/**': { lines: 93, functions: 92, branches: 89, statements: 93 },
45
+ },
46
+ },
47
+ },
48
+ });
@@ -1,253 +0,0 @@
1
- import type { LocalDatabaseService } from '../../services/database/index';
2
- import type {
3
- StreamProcessorService,
4
- StreamUpdate,
5
- StreamUpdateReceiver,
6
- } from '../../services/stream-processor/index';
7
- import type { Logger } from '../../services/logger/index';
8
- import { parseRecordIdString, encodeRecordId, surql } from '../../utils/index';
9
- import type { CacheRecord, QueryConfig } from './types';
10
- import type { RecordVersionArray } from '../../types';
11
-
12
- export * from './types';
13
-
14
- /**
15
- * CacheModule - Centralized storage and DBSP ingestion
16
- *
17
- * Single responsibility: Handle all local storage operations and DBSP ingestion.
18
- * This module acts as the bridge between data operations and persistence.
19
- */
20
- export class CacheModule implements StreamUpdateReceiver {
21
- private logger: Logger;
22
- private streamUpdateCallback: (update: StreamUpdate) => void;
23
- private versionLookups: Record<string, number> = {};
24
-
25
- constructor(
26
- private local: LocalDatabaseService,
27
- private streamProcessor: StreamProcessorService,
28
- streamUpdateCallback: (update: StreamUpdate) => void,
29
- logger: Logger
30
- ) {
31
- this.logger = logger.child({ service: 'CacheModule' });
32
- this.streamUpdateCallback = streamUpdateCallback;
33
- // Register as receiver for DBSP stream updates
34
- this.streamProcessor.addReceiver(this);
35
- }
36
-
37
- /**
38
- * Implements StreamUpdateReceiver interface
39
- * Called directly by StreamProcessor when views change
40
- */
41
- onStreamUpdate(update: StreamUpdate): void {
42
- this.logger.debug(
43
- {
44
- queryHash: update.queryHash,
45
- arrayLength: update.localArray?.length,
46
- Category: 'sp00ky-client::CacheModule::onStreamUpdate',
47
- },
48
- 'Stream update received'
49
- );
50
- this.streamUpdateCallback(update);
51
- }
52
-
53
- public lookup(recordId: string): number {
54
- return this.versionLookups[recordId] ?? 0;
55
- }
56
-
57
- /**
58
- * Save a single record to local DB and ingest into DBSP
59
- * Used by mutations (create/update)
60
- */
61
- async save(cacheRecord: CacheRecord, skipDbInsert: boolean = false): Promise<void> {
62
- return this.saveBatch([cacheRecord], skipDbInsert);
63
- }
64
-
65
- /**
66
- * Save multiple records in a batch
67
- * More efficient than calling save() multiple times
68
- * Used by sync operations
69
- */
70
- async saveBatch(records: CacheRecord[], skipDbInsert: boolean = false): Promise<void> {
71
- if (records.length === 0) return;
72
-
73
- this.logger.debug(
74
- {
75
- count: records.length,
76
- Category: 'sp00ky-client::CacheModule::saveBatch',
77
- },
78
- 'Saving record batch'
79
- );
80
-
81
- try {
82
- const populatedRecords = records.map((record) => {
83
- if (!record.version) throw new Error('Record version is required');
84
- return {
85
- ...record,
86
- record: {
87
- ...record.record,
88
- _00_rv: record.version,
89
- },
90
- };
91
- });
92
-
93
- if (!skipDbInsert) {
94
- const query = surql.seal<void>(
95
- surql.tx(
96
- populatedRecords.map((_, i) => {
97
- // MERGE, not REPLACE: the remote payload omits local-only
98
- // fields (`_00_crdt`, `_00_cursor`) injected by the CLI's
99
- // local schema, so REPLACE would wipe the persisted CRDT
100
- // snapshot on every sync-down round-trip and break offline
101
- // reload of formatted text.
102
- return surql.upsertMerge(`id${i}`, `content${i}`);
103
- })
104
- )
105
- );
106
-
107
- const params = populatedRecords.reduce(
108
- (acc, record, i) => {
109
- const { id, ...content } = record.record;
110
- return {
111
- ...acc,
112
- [`id${i}`]: id,
113
- [`content${i}`]: content,
114
- };
115
- },
116
- {} as Record<string, any>
117
- );
118
-
119
- await this.local.execute(query, params);
120
- }
121
-
122
- // 2. Bulk ingest into DBSP (use populatedRecords which has _00_rv set).
123
- // ingestMany coalesces the per-record stream updates into a single
124
- // notification per affected query — the UI then updates once, after the
125
- // whole batch is ingested, instead of row-by-row.
126
- const bulk = populatedRecords.map((record) => {
127
- const recordId = encodeRecordId(record.record.id);
128
- this.versionLookups[recordId] = record.version;
129
- return { table: record.table, op: record.op, id: recordId, record: record.record };
130
- });
131
- this.streamProcessor.ingestMany(bulk);
132
-
133
- this.logger.debug(
134
- { count: records.length, Category: 'sp00ky-client::CacheModule::saveBatch' },
135
- 'Batch saved successfully'
136
- );
137
- } catch (err) {
138
- this.logger.error(
139
- { err, count: records.length, Category: 'sp00ky-client::CacheModule::saveBatch' },
140
- 'Failed to save batch'
141
- );
142
- throw err;
143
- }
144
- }
145
-
146
- /**
147
- * Delete a record from local DB and ingest deletion into DBSP
148
- */
149
- async delete(table: string, id: string, skipDbDelete: boolean = false, recordData: Record<string, any> = {}): Promise<void> {
150
- this.logger.debug(
151
- { table, id, Category: 'sp00ky-client::CacheModule::delete' },
152
- 'Deleting record'
153
- );
154
-
155
- try {
156
- // 1. Delete from local database
157
- if (!skipDbDelete) {
158
- await this.local.query('DELETE $id', { id: parseRecordIdString(id) });
159
- }
160
-
161
- // 2. Ingest deletion into DBSP (pass record data so predicates can be matched)
162
- delete this.versionLookups[id];
163
- this.streamProcessor.ingest(table, 'DELETE', id, recordData);
164
-
165
- this.logger.debug(
166
- { table, id, Category: 'sp00ky-client::CacheModule::delete' },
167
- 'Record deleted successfully'
168
- );
169
- } catch (err) {
170
- this.logger.error(
171
- { err, table, id, Category: 'sp00ky-client::CacheModule::delete' },
172
- 'Failed to delete record'
173
- );
174
- throw err;
175
- }
176
- }
177
-
178
- /**
179
- * Register a query with DBSP to create a materialized view
180
- * Returns the initial result array
181
- */
182
- registerQuery(config: QueryConfig): {
183
- localArray: RecordVersionArray;
184
- registrationTimings?: { parseMs: number; planMs: number; snapshotMs: number };
185
- } {
186
- this.logger.debug(
187
- {
188
- queryHash: config.queryHash,
189
- surql: config.surql,
190
- Category: 'sp00ky-client::CacheModule::registerQuery',
191
- },
192
- 'Registering query'
193
- );
194
-
195
- try {
196
- const update = this.streamProcessor.registerQueryPlan({
197
- queryHash: config.queryHash,
198
- surql: config.surql,
199
- params: config.params,
200
- ttl: config.ttl,
201
- lastActiveAt: config.lastActiveAt,
202
- localArray: [],
203
- remoteArray: [],
204
- meta: {
205
- tableName: '',
206
- },
207
- });
208
-
209
- if (!update) {
210
- throw new Error('Failed to register query with DBSP');
211
- }
212
-
213
- this.logger.debug(
214
- {
215
- queryHash: config.queryHash,
216
- arrayLength: update.localArray?.length,
217
- Category: 'sp00ky-client::CacheModule::registerQuery',
218
- },
219
- 'Query registered successfully'
220
- );
221
-
222
- return { localArray: update.localArray, registrationTimings: update.registration };
223
- } catch (err) {
224
- this.logger.error(
225
- { err, queryHash: config.queryHash, Category: 'sp00ky-client::CacheModule::registerQuery' },
226
- 'Failed to register query'
227
- );
228
- throw err;
229
- }
230
- }
231
-
232
- /**
233
- * Unregister a query from DBSP
234
- */
235
- unregisterQuery(queryHash: string): void {
236
- this.logger.debug(
237
- { queryHash, Category: 'sp00ky-client::CacheModule::unregisterQuery' },
238
- 'Unregistering query'
239
- );
240
- try {
241
- this.streamProcessor.unregisterQueryPlan(queryHash);
242
- this.logger.debug(
243
- { queryHash, Category: 'sp00ky-client::CacheModule::unregisterQuery' },
244
- 'Query unregistered successfully'
245
- );
246
- } catch (err) {
247
- this.logger.error(
248
- { err, queryHash, Category: 'sp00ky-client::CacheModule::unregisterQuery' },
249
- 'Failed to unregister query'
250
- );
251
- }
252
- }
253
- }
@@ -1,19 +0,0 @@
1
- import type { RecordId, Duration } from 'surrealdb';
2
- import type { QueryTimeToLive } from '../../types';
3
-
4
- export type RecordWithId = Record<string, any> & { id: RecordId<string> };
5
-
6
- export interface QueryConfig {
7
- queryHash: string;
8
- surql: string;
9
- params: Record<string, any>;
10
- ttl: QueryTimeToLive | Duration;
11
- lastActiveAt: Date;
12
- }
13
-
14
- export interface CacheRecord {
15
- table: string;
16
- op: 'CREATE' | 'UPDATE' | 'DELETE';
17
- record: RecordWithId;
18
- version: number;
19
- }