@syncular/client 0.58.0 → 0.60.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (99) hide show
  1. package/README.md +34 -34
  2. package/dist/apply.d.ts +24 -14
  3. package/dist/apply.js +119 -70
  4. package/dist/authority.js +21 -16
  5. package/dist/blob.d.ts +17 -9
  6. package/dist/blob.js +5 -6
  7. package/dist/bun-database.d.ts +1 -0
  8. package/dist/bun-database.js +15 -0
  9. package/dist/client.d.ts +83 -75
  10. package/dist/client.js +982 -910
  11. package/dist/database.d.ts +5 -0
  12. package/dist/devtools.d.ts +2 -2
  13. package/dist/devtools.js +3 -3
  14. package/dist/diagnostics.d.ts +17 -28
  15. package/dist/diagnostics.js +1 -2
  16. package/dist/encryption.d.ts +2 -2
  17. package/dist/encryption.js +8 -2
  18. package/dist/errors.d.ts +3 -1
  19. package/dist/errors.js +5 -1
  20. package/dist/failed-overlay.d.ts +0 -1
  21. package/dist/failed-overlay.js +6 -6
  22. package/dist/http.d.ts +4 -1
  23. package/dist/http.js +67 -39
  24. package/dist/index.d.ts +1 -1
  25. package/dist/index.js +1 -1
  26. package/dist/invalidation.d.ts +14 -14
  27. package/dist/invalidation.js +24 -48
  28. package/dist/local-purge.js +9 -12
  29. package/dist/local-rebootstrap.js +2 -2
  30. package/dist/multi-tab.d.ts +89 -1
  31. package/dist/multi-tab.js +70 -31
  32. package/dist/native-bridge.d.ts +226 -0
  33. package/dist/native-bridge.js +764 -0
  34. package/dist/node-database.d.ts +1 -0
  35. package/dist/node-database.js +21 -1
  36. package/dist/outbox.d.ts +9 -12
  37. package/dist/outbox.js +20 -36
  38. package/dist/outcomes.js +3 -3
  39. package/dist/previous-version.js +96 -114
  40. package/dist/progress.d.ts +2 -2
  41. package/dist/query-guard.d.ts +34 -24
  42. package/dist/query-guard.js +61 -186
  43. package/dist/reactive-store.js +55 -13
  44. package/dist/realtime-supervisor.d.ts +9 -2
  45. package/dist/realtime-supervisor.js +31 -7
  46. package/dist/remote.js +19 -23
  47. package/dist/schema.d.ts +3 -2
  48. package/dist/schema.js +43 -22
  49. package/dist/state.d.ts +69 -36
  50. package/dist/state.js +178 -89
  51. package/dist/sync-scheduler.js +28 -2
  52. package/dist/transport.d.ts +19 -4
  53. package/dist/wasm-database.js +58 -21
  54. package/dist/window.d.ts +30 -52
  55. package/dist/window.js +33 -77
  56. package/dist/worker-core.d.ts +5 -0
  57. package/dist/worker-core.js +83 -75
  58. package/dist/worker-host.d.ts +19 -13
  59. package/dist/worker-host.js +75 -18
  60. package/dist/worker-local-authority.js +2 -2
  61. package/dist/worker-protocol.d.ts +15 -10
  62. package/package.json +11 -3
  63. package/src/apply.ts +176 -86
  64. package/src/authority.ts +31 -17
  65. package/src/blob.ts +28 -15
  66. package/src/bun-database.ts +24 -0
  67. package/src/client.ts +1282 -1217
  68. package/src/database.ts +5 -0
  69. package/src/devtools.ts +5 -5
  70. package/src/diagnostics.ts +17 -37
  71. package/src/encryption.ts +10 -5
  72. package/src/errors.ts +9 -1
  73. package/src/failed-overlay.ts +8 -7
  74. package/src/http.ts +95 -79
  75. package/src/index.ts +1 -1
  76. package/src/invalidation.ts +26 -61
  77. package/src/local-purge.ts +11 -13
  78. package/src/local-rebootstrap.ts +2 -3
  79. package/src/multi-tab.ts +88 -30
  80. package/src/native-bridge.ts +1153 -0
  81. package/src/node-database.ts +32 -1
  82. package/src/outbox.ts +20 -41
  83. package/src/outcomes.ts +3 -5
  84. package/src/previous-version.ts +103 -114
  85. package/src/progress.ts +2 -2
  86. package/src/query-guard.ts +77 -177
  87. package/src/reactive-store.ts +52 -12
  88. package/src/realtime-supervisor.ts +37 -12
  89. package/src/remote.ts +23 -31
  90. package/src/schema.ts +67 -25
  91. package/src/state.ts +246 -125
  92. package/src/sync-scheduler.ts +31 -1
  93. package/src/transport.ts +21 -2
  94. package/src/wasm-database.ts +76 -27
  95. package/src/window.ts +55 -134
  96. package/src/worker-core.ts +97 -77
  97. package/src/worker-host.ts +76 -32
  98. package/src/worker-local-authority.ts +2 -5
  99. package/src/worker-protocol.ts +14 -10
package/dist/authority.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { ClientSyncError } from './errors.js';
2
2
  import { listOutbox, listOutboxBeforeImages } from './outbox.js';
3
3
  import { RETAINED_ROWS } from './failed-overlay.js';
4
- import { getLocalRevision, getMeta, loadSubscriptions } from './state.js';
4
+ import { bootstrapping, covers, getLocalRevision, getMeta, loadUnits, pairScopes, replicaCursor, } from './state.js';
5
5
  import { fromSqlValue, quoteIdent, SYNC_VERSION_COLUMN } from './schema.js';
6
6
  function validateAuthorityReads(schema, declarations) {
7
7
  if (!Array.isArray(declarations))
@@ -55,7 +55,8 @@ function readAuthoritySnapshot(db, schema, declarations) {
55
55
  BigInt(raw) > 18446744073709551615n)
56
56
  throw new ClientSyncError('sync.local_corrupt', 'authority revision is missing or invalid');
57
57
  const revision = getLocalRevision(db);
58
- const subscriptions = loadSubscriptions(db);
58
+ const units = loadUnits(db);
59
+ const cursor = replicaCursor(db);
59
60
  const tables = declarations.map((read) => {
60
61
  const table = schema.tables.get(read.table);
61
62
  const columns = [
@@ -150,27 +151,31 @@ function readAuthoritySnapshot(db, schema, declarations) {
150
151
  },
151
152
  ];
152
153
  });
153
- const persisted = subscriptions
154
- .filter((s) => s.table === read.table)
155
- .map((s) => {
156
- const effective = s.effectiveScopes;
157
- const complete = effective !== undefined &&
158
- Object.keys(effective).length === Object.keys(read.scopes).length &&
159
- s.status === 'active' &&
160
- s.cursor >= 0 &&
161
- s.bootstrapState === undefined &&
162
- s.params === undefined;
154
+ // Every unit covering the table, as its (unit, table) pair (§4.4).
155
+ const persisted = units
156
+ .filter((unit) => covers(table, unit.scopes))
157
+ .map((unit) => {
158
+ const effective = unit.echo === undefined
159
+ ? undefined
160
+ : pairScopes(unit.scopes, read.table, unit.echo);
163
161
  return {
164
- requestedScopes: Object.fromEntries(Object.keys(read.scopes).map((v) => [v, s.scopes[v] ?? []])),
165
- status: s.status,
166
- cursor: s.cursor,
162
+ requestedScopes: Object.fromEntries(Object.keys(read.scopes).map((v) => [
163
+ v,
164
+ unit.scopes[v] === undefined ? [] : [unit.scopes[v]],
165
+ ])),
166
+ status: unit.status,
167
+ cursor: unit.cursor ?? cursor,
167
168
  effectiveScopes: effective === undefined
168
169
  ? null
169
170
  : Object.fromEntries(Object.keys(read.scopes).map((v) => [
170
171
  v,
171
172
  effective[v] ?? [],
172
173
  ])),
173
- complete,
174
+ complete: effective !== undefined &&
175
+ Object.keys(effective).length ===
176
+ Object.keys(read.scopes).length &&
177
+ unit.status === 'active' &&
178
+ !bootstrapping(unit),
174
179
  };
175
180
  });
176
181
  const selectors = Object.entries(read.scopes);
package/dist/blob.d.ts CHANGED
@@ -39,35 +39,43 @@ export type BlobUploadGrant = {
39
39
  } | {
40
40
  readonly kind: 'none';
41
41
  };
42
- /** The transport seam for blob upload/download (§5.9.3/§5.9.5). */
42
+ /**
43
+ * The transport seam for blob upload/download (§5.9.3/§5.9.5). The upload
44
+ * calls receive the round's `signal`, which aborts when the `syncUntilIdle`
45
+ * deadline elapses (§7.8).
46
+ */
43
47
  export interface BlobTransport {
44
48
  /** `PUT <mount>/blobs/{blobId}` — host-authenticated direct upload (§5.9.3). */
45
- upload(blobId: string, bytes: Uint8Array, mediaType?: string): Promise<void>;
49
+ upload(blobId: string, bytes: Uint8Array, mediaType?: string, signal?: AbortSignal): Promise<void>;
46
50
  /**
47
51
  * `GET <mount>/blobs/{blobId}` — re-authorized (§5.9.5). Returns inline
48
52
  * bytes, or a presigned `url` the client core fetches via `fetchUrl`.
53
+ * `byteLength` is the BlobRef's declared size when the caller passed one;
54
+ * reading inline bytes stops once the body exceeds it.
49
55
  */
50
- download(blobId: string): Promise<BlobDownloadResponse>;
56
+ download(blobId: string, byteLength?: number): Promise<BlobDownloadResponse>;
51
57
  /**
52
58
  * §5.9.5 presigned-download fetch: a bare GET of the signed `url`. Present
53
59
  * iff the transport can consume URLs. MUST attach NO host authentication —
54
60
  * the URL is the entire grant (§5.4). Only called when `download` returned
55
- * a `url` arm.
61
+ * a `url` arm. Reading stops once the body exceeds `byteLength`.
56
62
  */
57
- fetchUrl?(url: string): Promise<Uint8Array>;
63
+ fetchUrl?(url: string, byteLength?: number): Promise<Uint8Array>;
58
64
  /**
59
65
  * §5.9.3 presigned-upload grant: `POST /blobs/{blobId}/upload-grant` with
60
66
  * the declared size. Present iff the transport supports the grant flow;
61
67
  * absent ⇒ the client always streams through `upload`. A `url` grant is
62
68
  * PUT via `uploadToUrl`.
63
69
  */
64
- uploadGrant?(blobId: string, byteLength: number, mediaType?: string): Promise<BlobUploadGrant>;
70
+ uploadGrant?(blobId: string, byteLength: number, mediaType?: string, signal?: AbortSignal): Promise<BlobUploadGrant>;
65
71
  /**
66
72
  * §5.9.3 direct-to-storage PUT of the granted `url`. MUST attach NO host
67
- * authentication — the presigned URL is the entire grant (§5.4). Only
68
- * called when `uploadGrant` returned a `url` arm.
73
+ * authentication — the presigned URL is the entire grant (§5.4) — and MUST
74
+ * send `x-amz-checksum-sha256` (base64 of the digest `blobId` names), which
75
+ * the grant signs beside `content-length`. Only called when `uploadGrant`
76
+ * returned a `url` arm.
69
77
  */
70
- uploadToUrl?(url: string, bytes: Uint8Array, mediaType?: string): Promise<void>;
78
+ uploadToUrl?(blobId: string, url: string, bytes: Uint8Array, mediaType?: string, signal?: AbortSignal): Promise<void>;
71
79
  }
72
80
  export interface CachedBlob {
73
81
  readonly blobId: string;
package/dist/blob.js CHANGED
@@ -71,7 +71,7 @@ export function enforceBlobCacheCap(db, schema, maxBytes) {
71
71
  if (total <= maxBytes)
72
72
  return [];
73
73
  // Oldest eligible body first, with blob ID as a stable tie.
74
- const candidates = db.query(`SELECT blob_id,byte_length FROM _syncular_blobs WHERE blob_id NOT IN(SELECT blob_id FROM _syncular_blob_uploads)AND blob_id NOT IN(SELECT blob_id FROM ${BLOB_COMMIT_REFS})AND blob_id NOT IN(${visibleBlobIdsSql(schema)})ORDER BY created_at_ms ASC,blob_id ASC`);
74
+ const candidates = db.query(`SELECT blob_id,byte_length ${unreferencedBlobsSql(schema)}ORDER BY created_at_ms ASC,blob_id ASC`);
75
75
  const evicted = [];
76
76
  db.transaction(() => {
77
77
  for (const row of candidates) {
@@ -126,7 +126,8 @@ export function schemaHasBlobs(schema) {
126
126
  }
127
127
  return false;
128
128
  }
129
- function visibleBlobIdsSql(schema) {
129
+ /** The cached bodies no upload, pending commit, or visible row references. */
130
+ function unreferencedBlobsSql(schema) {
130
131
  const selects = [];
131
132
  for (const [tableName, columns] of blobRefColumnsBySchema(schema)) {
132
133
  for (const column of columns) {
@@ -134,11 +135,9 @@ function visibleBlobIdsSql(schema) {
134
135
  selects.push(`SELECT json_extract(${identifier},'$.blobId')AS blob_id FROM ${quoteIdent(tableName)} WHERE typeof(${identifier})='text' AND json_valid(${identifier})AND json_type(${identifier},'$.blobId')='text'`);
135
136
  }
136
137
  }
137
- return selects.length === 0
138
- ? 'SELECT NULL AS blob_id WHERE 0'
139
- : selects.join(' UNION ');
138
+ return `FROM _syncular_blobs WHERE blob_id NOT IN(SELECT blob_id FROM _syncular_blob_uploads)AND blob_id NOT IN(SELECT blob_id FROM ${BLOB_COMMIT_REFS})AND blob_id NOT IN(${selects.length === 0 ? 'SELECT NULL AS blob_id WHERE 0' : selects.join(' UNION ')})`;
140
139
  }
141
140
  export function deleteUnreferencedCachedBlobs(db, schema) {
142
- db.exec(`DELETE FROM _syncular_blobs WHERE blob_id NOT IN(SELECT blob_id FROM _syncular_blob_uploads)AND blob_id NOT IN(SELECT blob_id FROM ${BLOB_COMMIT_REFS})AND blob_id NOT IN(${visibleBlobIdsSql(schema)})`);
141
+ db.exec(`DELETE ${unreferencedBlobsSql(schema)}`);
143
142
  }
144
143
  export { parseBlobRef, serializeBlobRef };
@@ -16,6 +16,7 @@ export declare class BunClientDatabase implements ClientDatabase {
16
16
  constructor(path?: string);
17
17
  exec(sql: string, params?: readonly SqlValue[]): void;
18
18
  query(sql: string, params?: readonly SqlValue[]): SqlRow[];
19
+ queryReadOnly(sql: string, params?: readonly SqlValue[]): SqlRow[];
19
20
  /** RFC 0005: a sibling file beside the replica, e.g. `<path>.prev-context`. */
20
21
  openSibling(name: string): SiblingDatabase;
21
22
  siblingExists(name: string): boolean;
@@ -8,6 +8,7 @@ import { existsSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
8
8
  import { tmpdir } from 'node:os';
9
9
  import { join } from 'node:path';
10
10
  import { assertImageAlias, runTransaction, } from './database.js';
11
+ import { prepareReadOnly, runReadOnly } from './query-guard.js';
11
12
  function coerceParams(params) {
12
13
  return params.map((value) => {
13
14
  if (typeof value === 'boolean')
@@ -18,6 +19,7 @@ function coerceParams(params) {
18
19
  export class BunClientDatabase {
19
20
  db;
20
21
  #path;
22
+ #proven = new Set();
21
23
  #tx = { depth: 0 };
22
24
  constructor(path = ':memory:') {
23
25
  this.#path = path;
@@ -45,6 +47,19 @@ export class BunClientDatabase {
45
47
  query(sql, params = []) {
46
48
  return this.db.query(sql).all(...coerceParams(params));
47
49
  }
50
+ queryReadOnly(sql, params = []) {
51
+ const statement = prepareReadOnly(sql, () => {
52
+ const prepared = this.db.query(sql);
53
+ // bun:sqlite exposes no `sqlite3_sql`, so the first statement ends at
54
+ // the first `;` outside literals, identifiers and comments.
55
+ return [
56
+ prepared,
57
+ /^(?:'[^']*'|"[^"]*"|`[^`]*`|\[[^\]]*\]|--[^\n]*|\/\*(?:[^*]|\*(?!\/))*(?:\*\/|$)|[^;])*/.exec(sql)[0],
58
+ prepared.columnNames.length > 0,
59
+ ];
60
+ });
61
+ return runReadOnly(this.#proven, sql, (pragma) => this.db.run(pragma), (error) => error.code === 'SQLITE_READONLY', () => statement.all(...coerceParams(params)));
62
+ }
48
63
  /** RFC 0005: a sibling file beside the replica, e.g. `<path>.prev-context`. */
49
64
  openSibling(name) {
50
65
  const siblingPath = this.#path === ':memory:' ? ':memory:' : `${this.#path}.${name}`;
package/dist/client.d.ts CHANGED
@@ -9,11 +9,11 @@ import { type SyncProgress, type SyncProgressListener } from './progress.js';
9
9
  * ownership behind `LeaderLock`. One combined push+pull request per
10
10
  * `sync()` round (§7.2); local reads go straight to the database.
11
11
  */
12
- import { type ScopeMap, type WakeReason } from '@syncular/core';
12
+ import { type PresenceErrorCode, type UnitScopes, type WakeReason } from '@syncular/core';
13
13
  import { type BlobRef, type BlobTransport, type CachedBlob } from './blob.js';
14
14
  import type { ClientDatabase, SqlRow, SqlValue } from './database.js';
15
15
  import type { DevtoolsRegistrar } from './devtools.js';
16
- import { type ClientDiagnosticsListener, type ClientDiagnosticsRequest, type ClientDiagnosticsSnapshot, type RealtimePolicy } from './diagnostics.js';
16
+ import { type ClientDiagnosticsListener, type ClientDiagnosticsSnapshot, type RealtimePolicy } from './diagnostics.js';
17
17
  import type { EncryptionConfig } from './encryption.js';
18
18
  import { type ClientChangeListener, type CommandResult, type InvalidationListener, type LocalRevision, type SyncIntent, type SyncStatusSnapshot } from './invalidation.js';
19
19
  import { type LeaderLock } from './leader-lock.js';
@@ -23,7 +23,7 @@ import { type OutboxCommit } from './outbox.js';
23
23
  import { type CommitOutcome, type CommitOutcomeQuery, type ConflictRecord, type RejectionRecord, type RetainedCommitRow, type ResolveCommitOutcomeInput } from './outcomes.js';
24
24
  import { type PreviousVersionAudit, type PreviousVersionReadSpec, type PreviousVersionSnapshot } from './previous-version.js';
25
25
  import { type ClientSchema } from './schema.js';
26
- import { type SubscriptionRecord } from './state.js';
26
+ import { type UnitRecord } from './state.js';
27
27
  import type { RealtimeConnector, SegmentDownloader, SyncTransport } from './transport.js';
28
28
  import { type WindowBase } from './window.js';
29
29
  export type MutationInput = {
@@ -72,14 +72,14 @@ export interface SyncSummary {
72
72
  readonly commitsApplied: number;
73
73
  /** Snapshot rows applied from segments. */
74
74
  readonly segmentRowsApplied: number;
75
- /** Subscriptions still mid-bootstrap (resume token pending). */
75
+ /** Ids of the units still catching up after the round (§4.1). */
76
76
  readonly bootstrapping: readonly string[];
77
- /** Subscriptions reset via `sync.cursor_expired` (re-pull needed). */
77
+ /** Units reset via `sync.cursor_expired` (§4.6). */
78
78
  readonly resets: readonly string[];
79
- /** Subscriptions revoked this round (§3.3 purge ran). */
79
+ /** Units revoked this round (§3.3 purge ran). */
80
80
  readonly revoked: readonly string[];
81
- /** Subscriptions stopped by a fatal configuration error (§3.3/§5.6
82
- * fail-closed: no local scope-column mapping). */
81
+ /** Units stopped by a fatal configuration error (§3.3/§5.6 fail-closed:
82
+ * no local scope-column mapping). */
83
83
  readonly failed: readonly string[];
84
84
  /** Present when the server declared a schema floor — syncing stopped. */
85
85
  readonly schemaFloor?: SchemaFloor;
@@ -97,7 +97,7 @@ export interface SyncIdleResult extends SyncSummary {
97
97
  readonly budgetExhausted: boolean;
98
98
  }
99
99
  export interface SyncIdleOptions {
100
- /** §7.7: a strict positive round count. Default: 20. */
100
+ /** §7.8: a strict positive round count. Default: 20. */
101
101
  readonly maxRounds?: number;
102
102
  /**
103
103
  * Total wall-clock budget for one drive, across every round. When it
@@ -120,7 +120,7 @@ export interface SyncClientLimits {
120
120
  /**
121
121
  * §4.2 accept bitmask; defaults to inline + external rows (0b0011)
122
122
  * plus SQLite images and signed URLs when supported. Both image chunks
123
- * and rows blocks commit before yielding to local reads (§7.7).
123
+ * and rows blocks commit before yielding to local reads (§7.8).
124
124
  */
125
125
  readonly accept?: number;
126
126
  /**
@@ -139,7 +139,8 @@ export interface SyncClientLimits {
139
139
  readonly maxPushOperationsPerRequest?: number;
140
140
  /**
141
141
  * §7.1: maximum bytes of the complete encoded SSP2 request (8-byte
142
- * envelope, request header, push commits, pull header, subscriptions,
142
+ * envelope, request header, push commits, pull header, unit and progress
143
+ * frames,
143
144
  * framing, and any §5.11 ciphertext). Default: unbounded. A request whose
144
145
  * fixed frames alone exceed it, or whose first commit alone does not fit,
145
146
  * raises `client.push_request_too_large` and stays queued.
@@ -176,6 +177,15 @@ export interface SyncClientConfig {
176
177
  * `required` without a `realtime` connector is refused at construction.
177
178
  */
178
179
  readonly realtimePolicy?: RealtimePolicy;
180
+ /**
181
+ * SPEC §8.5: the server's heartbeat interval in ms, default 30,000. The
182
+ * socket's first `heartbeat` event arms a watchdog; once armed, twice the
183
+ * interval without an inbound frame loses the socket with
184
+ * `transport.timeout` (`causeKind` `heartbeat`).
185
+ */
186
+ readonly realtimeHeartbeatMs?: number;
187
+ /** Timer seam for the heartbeat watchdog; defaults to `setTimeout`. */
188
+ readonly schedule?: (callback: () => void, delayMs: number) => () => void;
179
189
  /** Stable per-device id (§1.5); defaults to a persisted random UUID. */
180
190
  readonly clientId?: string;
181
191
  readonly leaderLock?: LeaderLock;
@@ -197,9 +207,11 @@ export interface SyncClientConfig {
197
207
  /**
198
208
  * §8.6 presence: a scope-mate's presence on a key this client holds
199
209
  * changed (join/update/leave). Fired after the local presence map is
200
- * updated — the app's cue to re-render who's-online.
210
+ * updated — the app's cue to re-render who's-online. `error` is set when
211
+ * the server refused this client's own publish on `scopeKey` (§8.6.2);
212
+ * the map is unchanged then.
201
213
  */
202
- readonly onPresence?: (scopeKey: string) => void;
214
+ readonly onPresence?: (scopeKey: string, error?: PresenceErrorCode) => void;
203
215
  /**
204
216
  * §5.11 client-side encryption. Supplies the key material (`keyProvider`)
205
217
  * and key selection (`keyIdFor`) for columns the generated schema marks
@@ -260,12 +272,6 @@ export interface PresencePeer {
260
272
  readonly clientId: string;
261
273
  readonly doc: Record<string, unknown>;
262
274
  }
263
- export interface SubscribeInput {
264
- readonly id: string;
265
- readonly table: string;
266
- readonly scopes: ScopeMap;
267
- readonly params?: string;
268
- }
269
275
  /**
270
276
  * The live state of a window base (§4.8) — the completeness oracle (I3),
271
277
  * as plain serializable data so it crosses the worker/follower boundary
@@ -278,11 +284,10 @@ export interface WindowState {
278
284
  /** Windowed-in units for this base, ordered by value. */
279
285
  readonly units: readonly string[];
280
286
  /**
281
- * Registered units whose bootstrap has not yet completed (§4.8): the
282
- * unit's subscription still has `cursor: -1` (never synced) or holds a
283
- * resume token (mid-bootstrap). Between `setWindow` and the bootstrap
284
- * landing, the local replica for a pending unit may be empty or partial —
285
- * it MUST NOT be rendered as complete.
287
+ * Windowed-in values whose unit is not complete (§4.8): bootstrapping
288
+ * (cursor `-1` or a resume token), revoked or failed. Between `setWindow`
289
+ * and the bootstrap landing, the local replica for a pending value may be
290
+ * empty or partial; it MUST NOT be rendered as complete.
286
291
  */
287
292
  readonly pending: readonly string[];
288
293
  }
@@ -326,26 +331,25 @@ export interface SnapshotStatement {
326
331
  readonly params?: readonly SqlValue[];
327
332
  }
328
333
  /**
329
- * §7.5: the catch-up state of one subscription as persisted in the snapshot,
330
- * never the mutable owner cache. `unknown` means the client does not currently
331
- * hold the subscription (never registered, forgotten, or removed) and carries
332
- * no fabricated table or cursor.
334
+ * §7.5: the catch-up state of one unit as persisted in the snapshot, never
335
+ * the mutable owner cache. `unknown` means the client does not currently hold
336
+ * the unit (never registered, released, or removed).
333
337
  */
334
- export type SubscriptionCatchup = {
338
+ export type UnitCatchup = {
335
339
  readonly state: 'unknown';
336
340
  readonly id: string;
337
341
  } | {
338
342
  readonly state: 'known';
339
343
  readonly id: string;
340
- readonly table: string;
341
344
  readonly status: 'active' | 'revoked' | 'failed';
345
+ readonly live: boolean;
346
+ /** The unit's cursor while it catches up, the replica cursor while live. */
342
347
  readonly cursor: number;
343
348
  readonly hasResumeToken: boolean;
344
- /** True only for `active` with `cursor >= 0` and no resume token. */
349
+ /** True only for an `active` unit that is live or post-bootstrap. */
345
350
  readonly bootstrapComplete: boolean;
346
- /** True only for `active` while a resume token remains or `cursor < 0`. */
351
+ /** True only for an `active` unit with cursor `-1` or a resume token. */
347
352
  readonly knownPendingPages: boolean;
348
- readonly effectiveScopes?: unknown;
349
353
  readonly reasonCode?: string;
350
354
  };
351
355
  /**
@@ -369,7 +373,8 @@ export type CommitDelivery = {
369
373
  export interface SnapshotReadRequest {
370
374
  readonly statements: readonly SnapshotStatement[];
371
375
  readonly coverage?: readonly WindowCoverage[];
372
- readonly subscriptions?: readonly string[];
376
+ /** Unit ids whose catch-up state the read reports. */
377
+ readonly units?: readonly string[];
373
378
  readonly commitIds?: readonly string[];
374
379
  /** §7.5 owner: a failed owned read is reported in `queryFailures`. */
375
380
  readonly owner?: QueryOwner;
@@ -380,7 +385,7 @@ export interface SnapshotRead<Row = SqlRow> {
380
385
  readonly revision: LocalRevision;
381
386
  readonly queries: readonly (readonly Row[])[];
382
387
  readonly coverage: CoverageSnapshot;
383
- readonly subscriptions: readonly SubscriptionCatchup[];
388
+ readonly units: readonly UnitCatchup[];
384
389
  readonly deliveries: readonly CommitDelivery[];
385
390
  }
386
391
  /**
@@ -433,8 +438,8 @@ export declare class SyncClient {
433
438
  /** The underlying database: raw SQL is the local query API. */
434
439
  get database(): ClientDatabase;
435
440
  /**
436
- * The raw-SQL read tier. Guarded (query-guard.ts): a single read-only
437
- * statement only — writes must go through `mutate()` so they hit the
441
+ * The raw-SQL read tier. Guarded (query-guard.ts): a single statement
442
+ * SQLite reports read-only — writes must go through `mutate()` so they hit the
438
443
  * outbox (SPEC §7.1). Reserved `_sync_*` columns are stripped from the
439
444
  * result, so a `SELECT *` row is safe to feed back into `mutate()`
440
445
  * values; alias explicitly (`_sync_version AS v`) to read one. Engine
@@ -452,15 +457,15 @@ export declare class SyncClient {
452
457
  */
453
458
  querySnapshot<Row = SqlRow>(spec: QueryReadSpec): QuerySnapshot<Row>;
454
459
  /**
455
- * §7.5: resolve several read-only statements, window coverage, subscription
460
+ * §7.5: resolve several read-only statements, window coverage, unit
456
461
  * catch-up states, and commit deliveries from one SQLite read transaction
457
462
  * and one revision. A host that needs those together reads them together;
458
463
  * every statement passes the read-only guard and any failure rolls the whole
459
464
  * read back.
460
465
  */
461
466
  snapshotRead<Row = SqlRow>(spec: SnapshotReadRequest): SnapshotRead<Row>;
462
- /** §7.5: one subscription's persisted catch-up state (never the owner cache). */
463
- subscriptionCatchup(id: string): SubscriptionCatchup;
467
+ /** §7.5: one unit's persisted catch-up state (never the owner cache). */
468
+ unitCatchup(id: string): UnitCatchup;
464
469
  /** §7.5: one client commit's delivery status: pending, its retained outcome,
465
470
  * or an explicit unknown (never held, or pruned by retention). */
466
471
  commitDelivery(id: string): CommitDelivery;
@@ -511,7 +516,7 @@ export declare class SyncClient {
511
516
  * One atomic support/product-health view. It never returns scope values,
512
517
  * rows, SQL, paths, auth material, lease ids, keys, or mutation bodies.
513
518
  */
514
- diagnosticsSnapshot(request?: ClientDiagnosticsRequest): ClientDiagnosticsSnapshot;
519
+ diagnosticsSnapshot(): ClientDiagnosticsSnapshot;
515
520
  /** One call for the complete status domain used by reactive hosts. */
516
521
  statusSnapshot(): SyncStatusSnapshot;
517
522
  /**
@@ -534,7 +539,11 @@ export declare class SyncClient {
534
539
  * Accepts a raw `blob_ref` column string or a bare `blobId`.
535
540
  */
536
541
  fetchBlob(blobIdOrRef: string): Promise<CachedBlob>;
537
- /** Flush any queued blob uploads (§5.9.7 B4); safe to call standalone. */
542
+ /**
543
+ * Flush any queued blob uploads (§5.9.7 B4); safe to call standalone. It
544
+ * runs on the round's operation chain because a refused upload drops
545
+ * outbox commits a round may have captured.
546
+ */
538
547
  flushBlobUploads(): Promise<void>;
539
548
  conflicts(): readonly ConflictRecord[];
540
549
  rejections(): readonly RejectionRecord[];
@@ -565,12 +574,14 @@ export declare class SyncClient {
565
574
  /** Every scope key this client currently has presence state for. */
566
575
  presenceKeys(): string[];
567
576
  /**
568
- * §8.6: subscribe to presence changes (join/update/leave on any held key).
569
- * The subscribable twin of the `onPresence` config callback — React's
570
- * `usePresence` targets this so many components can watch one client.
577
+ * §8.6: subscribe to presence changes (join/update/leave on any held key)
578
+ * and to the server's refusal of this client's own publish (`error`,
579
+ * §8.6.2). The subscribable twin of the `onPresence` config callback —
580
+ * React's `usePresence` targets this so many components can watch one
581
+ * client.
571
582
  * Returns an unsubscribe function.
572
583
  */
573
- onPresence(listener: (scopeKey: string) => void): () => void;
584
+ onPresence(listener: (scopeKey: string, error?: PresenceErrorCode) => void): () => void;
574
585
  /**
575
586
  * §8.6.2 publish (or clear, `doc: null`) this client's presence document
576
587
  * for `scopeKey`. Requires a live socket; the document is ephemeral and
@@ -579,44 +590,41 @@ export declare class SyncClient {
579
590
  * by the server with `presence.forbidden`.
580
591
  */
581
592
  setPresence(scopeKey: string, doc: Record<string, unknown> | null): void;
582
- subscriptions(): SubscriptionRecord[];
583
- subscription(id: string): SubscriptionRecord | undefined;
593
+ /** Every unit in registration order (§4.1), including revoked and failed. */
594
+ units(): UnitRecord[];
595
+ unit(id: string): UnitRecord | undefined;
584
596
  pendingCommits(): OutboxCommit[];
585
- subscribe(input: SubscribeInput): void;
597
+ /** Register one unit (§4.1) and return its id. */
598
+ subscribe(scopes: UnitScopes): string;
586
599
  /**
587
- * Register several subscriptions in one local transaction: the same rules
588
- * as `subscribe` for each input, and one commit for all of them (on OPFS a
589
- * commit costs milliseconds, so a cold start with hundreds of
590
- * registrations pays it once). An error rolls back every registration of
591
- * the call.
600
+ * Register several units in one local transaction and return their ids:
601
+ * one commit for all of them (on OPFS a commit costs milliseconds, so a
602
+ * cold start with hundreds of units pays it once). An error rolls back every
603
+ * registration of the call. Registering an active unit again changes
604
+ * nothing; a revoked unit re-arms (§3.3).
605
+ */
606
+ subscribeMany(units: readonly UnitScopes[]): string[];
607
+ /**
608
+ * Release the explicit reference to a unit. The unit leaves the
609
+ * registration list when no window base holds it (§4.1); its rows stay.
592
610
  */
593
- subscribeMany(inputs: readonly SubscribeInput[]): void;
594
611
  unsubscribe(id: string): void;
595
612
  /**
596
- * Set the live window units for a base (§4.8): a value-sharded family of
597
- * subscriptions, one per unit. Computes the diff against the registry —
598
- * added units get fresh subscriptions (image-lane bootstrap on the next
599
- * sync); removed units are unsubscribed with their first eviction chunk
600
- * in one local transaction (E1–E4). Idempotent: calling with the same units is a
601
- * no-op. Re-entry (a unit removed then re-added) cancels any deferred
602
- * eviction and fresh-bootstraps.
603
- *
604
- * The change takes effect on the next `sync()`/socket round — the pull's
605
- * subscription list (now with the added unit, without the removed one)
606
- * re-registers realtime at round end (§8.7). No socket cycle needed.
613
+ * Set the windowed-in values of a base (§4.8): one unit per value. Added
614
+ * values take a reference on their unit (a new unit bootstraps on the next
615
+ * sync); removed values release theirs, and a unit no reference holds leaves
616
+ * the registration list fused with its first eviction chunk (E1–E4).
617
+ * Idempotent; re-entry cancels a deferred eviction and fresh-bootstraps.
618
+ * The change reaches the server with the next round's list (§8.7).
607
619
  */
608
620
  setWindow(base: WindowBase, units: readonly string[]): Promise<void>;
609
621
  /** Exact core command result consumed by automatic host loops (§7.5). */
610
622
  setWindowCommand(base: WindowBase, units: readonly string[]): Promise<CommandResult<void>>;
611
623
  /**
612
- * The completeness oracle (§4.8 I3): which units of a base are windowed-in
613
- * locally, which of those are still bootstrap-pending, and thereby the
614
- * per-unit verdict a live query renders "may be partial" from. A query
615
- * whose scope footprint includes an un-windowed OR still-pending unit is
616
- * NOT answerable in full — the host widens or shows partial, never
617
- * silently-complete. Registration alone is not completeness: a unit is
618
- * pending until its subscription completes a bootstrap round (cursor
619
- * advances past -1 with no resume token held).
624
+ * The completeness oracle (§4.8): which values of a base are windowed-in
625
+ * and which of those are pending. A value is complete once its unit is
626
+ * active and no longer bootstrapping; registration alone is not
627
+ * completeness.
620
628
  */
621
629
  windowState(base: WindowBase): WindowState;
622
630
  /**
@@ -686,7 +694,7 @@ export declare class SyncClient {
686
694
  * Callers that arrive during the same drive with the same budget share that
687
695
  * single follow-up. `sync()` keeps rejecting a concurrent `sync()`.
688
696
  *
689
- * §7.7: one drive is bounded by a total deadline (`timeoutMs`, default
697
+ * §7.8: one drive is bounded by a total deadline (`timeoutMs`, default
690
698
  * 60 s). A drive that reaches it rejects with `sync.idle_timeout` and
691
699
  * aborts a socket round in flight; the round budget does not bound elapsed
692
700
  * time, and a transport that never answers must not hang the caller.