@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
@@ -1,34 +1,44 @@
1
1
  /**
2
- * The raw-query guard. `client.query()` and the React
3
- * `useRawSql` hook are the untrusted raw-SQL tier: an app hands us a SQL
4
- * string and we run it against the local database. Two rules make that safe
5
- * to expose, enforced HERE in the core (previously they lived in the
6
- * now-removed `@syncular/kysely` read-only driver):
2
+ * The raw-query guard behind `client.query()`, `querySnapshot()` and
3
+ * `snapshotRead()`, the untrusted raw-SQL tier. Each `ClientDatabase` adapter
4
+ * prepares only the first statement and reports what SQLite knows about it:
7
5
  *
8
- * 1. READ-ONLY. Only `select / with / explain / pragma / values` are
9
- * allowed. A write (`insert/update/delete/…`) against the local mirror
10
- * bypasses the outbox (SPEC §7.1) and silently diverges from the
11
- * server — writes MUST go through `client.mutate([...])`.
12
- * 2. ONE STATEMENT. `sqlite-wasm`'s `exec` runs every statement in a
13
- * multi-statement string (`SELECT 1; DROP TABLE t`), while the native
14
- * SQLite adapters prepare only the first. We unify on the strict
15
- * behaviour: exactly one statement per `query()`.
6
+ * 1. READ-ONLY. SQLite decides (`sqlite3_stmt_readonly`, or `query_only`
7
+ * on the first run of a text, `runReadOnly`) and the statement returns
8
+ * columns, which refuses `BEGIN`, `ATTACH` and the other
9
+ * read-only statements that change the connection. A write against the
10
+ * local mirror bypasses the outbox (SPEC §7.1); writes go through
11
+ * `client.mutate([...])`.
12
+ * 2. NO PRAGMA, refused before SQLite compiles anything: SQLite applies a
13
+ * flag pragma such as `query_only` while it compiles the statement, even
14
+ * under `EXPLAIN`. Read a pragma through its table-valued function
15
+ * (`SELECT * FROM pragma_table_info('tasks')`).
16
+ * 3. ONE STATEMENT. Anything but whitespace, comments and semicolons after
17
+ * the first statement is refused, because sqlite-wasm's `exec` runs
18
+ * every statement in the string. The tail is never compiled.
16
19
  *
17
- * The guard only fronts the PUBLIC `client.query()` — engine-internal reads
18
- * call the `ClientDatabase` directly and are trusted, so they are never
19
- * routed through here.
20
- *
21
- * RFC 0005 previously added a third rule here, denying reads of its container
22
- * table by root page. That table now lives in its own database file and is not
23
- * on the connection `query()` uses, so there is nothing left to guard and the
24
- * rule was removed with its EXPLAIN plumbing.
20
+ * Engine-internal reads call the `ClientDatabase` directly and never route
21
+ * here.
25
22
  */
26
23
  /** Raised when `client.query()` is handed SQL it will not run. */
27
24
  export declare class RawSqlError extends Error {
28
25
  readonly name = "RawSqlError";
29
26
  }
30
27
  /**
31
- * Assert `sql` is a single read-only statement, or throw `RawSqlError`.
32
- * Called by `client.query()` before the string reaches the database.
28
+ * Prepare `sql` for the raw-SQL tier or throw `RawSqlError`. `prepare`
29
+ * compiles the first statement only and returns it, the text SQLite compiled
30
+ * for it, and whether SQLite reports it read-only with result columns.
31
+ */
32
+ export declare function prepareReadOnly<S>(sql: string, prepare: () => readonly [statement: S, first: string, reads: boolean]): S;
33
+ /**
34
+ * Run a statement `prepareReadOnly` accepted on an adapter without
35
+ * `sqlite3_stmt_readonly` (bun:sqlite before 1.4.4, node:sqlite). SQLite
36
+ * refuses a write when it runs: under `query_only` a write transaction fails
37
+ * before it changes anything, and `refused` recognizes that error. The
38
+ * verdict depends on the text alone, since a write fails at its write
39
+ * transaction whether or not it touches a row, so a text that completed
40
+ * under `query_only` joins `proven` and later runs skip the pragma: a flag
41
+ * pragma expires every prepared statement of the connection. `proven` is per
42
+ * connection and cleared at 512 texts, so dynamic SQL cannot grow it.
33
43
  */
34
- export declare function assertReadOnlyQuery(sql: string): void;
44
+ export declare function runReadOnly<R>(proven: Set<string>, sql: string, pragma: (sql: string) => void, refused: (error: unknown) => boolean, run: () => R): R;
@@ -1,205 +1,80 @@
1
1
  /**
2
- * The raw-query guard. `client.query()` and the React
3
- * `useRawSql` hook are the untrusted raw-SQL tier: an app hands us a SQL
4
- * string and we run it against the local database. Two rules make that safe
5
- * to expose, enforced HERE in the core (previously they lived in the
6
- * now-removed `@syncular/kysely` read-only driver):
2
+ * The raw-query guard behind `client.query()`, `querySnapshot()` and
3
+ * `snapshotRead()`, the untrusted raw-SQL tier. Each `ClientDatabase` adapter
4
+ * prepares only the first statement and reports what SQLite knows about it:
7
5
  *
8
- * 1. READ-ONLY. Only `select / with / explain / pragma / values` are
9
- * allowed. A write (`insert/update/delete/…`) against the local mirror
10
- * bypasses the outbox (SPEC §7.1) and silently diverges from the
11
- * server — writes MUST go through `client.mutate([...])`.
12
- * 2. ONE STATEMENT. `sqlite-wasm`'s `exec` runs every statement in a
13
- * multi-statement string (`SELECT 1; DROP TABLE t`), while the native
14
- * SQLite adapters prepare only the first. We unify on the strict
15
- * behaviour: exactly one statement per `query()`.
6
+ * 1. READ-ONLY. SQLite decides (`sqlite3_stmt_readonly`, or `query_only`
7
+ * on the first run of a text, `runReadOnly`) and the statement returns
8
+ * columns, which refuses `BEGIN`, `ATTACH` and the other
9
+ * read-only statements that change the connection. A write against the
10
+ * local mirror bypasses the outbox (SPEC §7.1); writes go through
11
+ * `client.mutate([...])`.
12
+ * 2. NO PRAGMA, refused before SQLite compiles anything: SQLite applies a
13
+ * flag pragma such as `query_only` while it compiles the statement, even
14
+ * under `EXPLAIN`. Read a pragma through its table-valued function
15
+ * (`SELECT * FROM pragma_table_info('tasks')`).
16
+ * 3. ONE STATEMENT. Anything but whitespace, comments and semicolons after
17
+ * the first statement is refused, because sqlite-wasm's `exec` runs
18
+ * every statement in the string. The tail is never compiled.
16
19
  *
17
- * The guard only fronts the PUBLIC `client.query()` — engine-internal reads
18
- * call the `ClientDatabase` directly and are trusted, so they are never
19
- * routed through here.
20
- *
21
- * RFC 0005 previously added a third rule here, denying reads of its container
22
- * table by root page. That table now lives in its own database file and is not
23
- * on the connection `query()` uses, so there is nothing left to guard and the
24
- * rule was removed with its EXPLAIN plumbing.
20
+ * Engine-internal reads call the `ClientDatabase` directly and never route
21
+ * here.
25
22
  */
26
- /** Verbs a read-only query may begin with (lowercased). */
27
- const READ_ONLY_VERBS = new Set([
28
- 'select',
29
- 'with',
30
- 'explain',
31
- 'pragma',
32
- 'values',
33
- ]);
34
23
  /** Raised when `client.query()` is handed SQL it will not run. */
35
24
  export class RawSqlError extends Error {
36
25
  name = 'RawSqlError';
37
26
  }
38
- /**
39
- * Split `sql` into top-level statements at unquoted `;`, skipping over
40
- * string literals ('…'), quoted/bracketed identifiers ("…", `…`, […]) and
41
- * comments (-- …, /* … *​/) so a `;` inside any of them is not a boundary.
42
- * Returns the non-empty statements (comment/whitespace-only trailers drop).
43
- */
44
- function splitStatements(sql) {
45
- const statements = [];
46
- let start = 0;
47
- let i = 0;
48
- const n = sql.length;
49
- const pushIfNonEmpty = (end) => {
50
- const stripped = stripLeading(sql.slice(start, end));
51
- if (stripped.length > 0)
52
- statements.push(sql.slice(start, end));
53
- start = end + 1;
54
- };
55
- while (i < n) {
56
- const c = sql[i];
57
- if (c === '-' && sql[i + 1] === '-') {
58
- const nl = sql.indexOf('\n', i + 2);
59
- i = nl === -1 ? n : nl + 1;
60
- }
61
- else if (c === '/' && sql[i + 1] === '*') {
62
- const close = sql.indexOf('*/', i + 2);
63
- i = close === -1 ? n : close + 2;
64
- }
65
- else if (c === "'" || c === '"' || c === '`') {
66
- i = skipQuoted(sql, i, c);
67
- }
68
- else if (c === '[') {
69
- const close = sql.indexOf(']', i + 1);
70
- i = close === -1 ? n : close + 1;
71
- }
72
- else if (c === ';') {
73
- pushIfNonEmpty(i);
74
- i += 1;
75
- }
76
- else {
77
- i += 1;
78
- }
79
- }
80
- pushIfNonEmpty(n);
81
- return statements;
82
- }
83
- /** Advance past a quoted run opened at `open`; SQL doubles the quote to escape it. */
84
- function skipQuoted(sql, open, quote) {
85
- let i = open + 1;
86
- const n = sql.length;
87
- while (i < n) {
88
- if (sql[i] === quote) {
89
- if (sql[i + 1] === quote)
90
- i += 2;
91
- else
92
- return i + 1;
93
- }
94
- else {
95
- i += 1;
96
- }
97
- }
98
- return n;
99
- }
100
- /** Strip leading whitespace and comments, returning the remainder. */
101
- function stripLeading(sql) {
102
- return sql
103
- .replace(/^\s*(?:--[^\n]*(?:\n|$)|\/\*[\s\S]*?\*\/|\s)+/, '')
104
- .trimStart();
105
- }
106
- function firstWords(sql) {
107
- const trimmed = sql.trim().replace(/\s+/g, ' ');
108
- return trimmed.length > 72 ? `${trimmed.slice(0, 72)}…` : trimmed;
27
+ /** Refuse a statement the raw-SQL tier does not run. */
28
+ function refuseRawSql() {
29
+ throw new RawSqlError('client.query() runs read-only statements and no PRAGMA; write through client.mutate() so the outbox records it (SPEC §7.1).');
109
30
  }
110
31
  /**
111
- * The main verb of a `WITH …` statement: SQLite allows a with-clause before
112
- * SELECT **and before INSERT/UPDATE/DELETE**, so `WITH t AS (…) DELETE …`
113
- * must not slip through the verb allowlist. CTE bodies live inside
114
- * parentheses, and a bare keyword cannot be a CTE name, so the first
115
- * paren-depth-0 keyword after the clause IS the main verb.
32
+ * Prepare `sql` for the raw-SQL tier or throw `RawSqlError`. `prepare`
33
+ * compiles the first statement only and returns it, the text SQLite compiled
34
+ * for it, and whether SQLite reports it read-only with result columns.
116
35
  */
117
- function mainVerbAfterWith(sql) {
118
- const MAIN_VERBS = new Set([
119
- 'select',
120
- 'values',
121
- 'insert',
122
- 'update',
123
- 'delete',
124
- 'replace',
125
- ]);
126
- let depth = 0;
127
- let i = 0;
128
- const n = sql.length;
129
- let sawWith = false;
130
- while (i < n) {
131
- const c = sql[i];
132
- if (c === '-' && sql[i + 1] === '-') {
133
- const nl = sql.indexOf('\n', i + 2);
134
- i = nl === -1 ? n : nl + 1;
135
- }
136
- else if (c === '/' && sql[i + 1] === '*') {
137
- const close = sql.indexOf('*/', i + 2);
138
- i = close === -1 ? n : close + 2;
139
- }
140
- else if (c === "'" || c === '"' || c === '`') {
141
- i = skipQuoted(sql, i, c);
142
- }
143
- else if (c === '[') {
144
- const close = sql.indexOf(']', i + 1);
145
- i = close === -1 ? n : close + 1;
146
- }
147
- else if (c === '(') {
148
- depth += 1;
149
- i += 1;
150
- }
151
- else if (c === ')') {
152
- depth -= 1;
153
- i += 1;
154
- }
155
- else if (/[A-Za-z_]/.test(c)) {
156
- let j = i + 1;
157
- while (j < n && /[A-Za-z0-9_]/.test(sql[j]))
158
- j += 1;
159
- const word = sql.slice(i, j).toLowerCase();
160
- if (depth === 0) {
161
- if (!sawWith && word === 'with')
162
- sawWith = true;
163
- else if (sawWith && MAIN_VERBS.has(word))
164
- return word;
165
- }
166
- i = j;
167
- }
168
- else {
169
- i += 1;
170
- }
36
+ export function prepareReadOnly(sql, prepare) {
37
+ if (/^(?:[\s;]|--[^\n]*(?:\n|$)|\/\*(?:[^*]|\*(?!\/))*(?:\*\/|$)|explain\b|query\b|plan\b)*pragma\b/i.test(sql)) {
38
+ refuseRawSql();
39
+ }
40
+ const [statement, first, reads] = prepare();
41
+ if (sql
42
+ .slice(first.length)
43
+ .replace(/^(?:[\s;]|--[^\n]*(?:\n|$)|\/\*(?:[^*]|\*(?!\/))*(?:\*\/|$))*/, '') !== '') {
44
+ throw new RawSqlError('client.query() runs one statement per call.');
171
45
  }
172
- return undefined;
46
+ if (!reads)
47
+ refuseRawSql();
48
+ return statement;
173
49
  }
174
50
  /**
175
- * Assert `sql` is a single read-only statement, or throw `RawSqlError`.
176
- * Called by `client.query()` before the string reaches the database.
51
+ * Run a statement `prepareReadOnly` accepted on an adapter without
52
+ * `sqlite3_stmt_readonly` (bun:sqlite before 1.4.4, node:sqlite). SQLite
53
+ * refuses a write when it runs: under `query_only` a write transaction fails
54
+ * before it changes anything, and `refused` recognizes that error. The
55
+ * verdict depends on the text alone, since a write fails at its write
56
+ * transaction whether or not it touches a row, so a text that completed
57
+ * under `query_only` joins `proven` and later runs skip the pragma: a flag
58
+ * pragma expires every prepared statement of the connection. `proven` is per
59
+ * connection and cleared at 512 texts, so dynamic SQL cannot grow it.
177
60
  */
178
- export function assertReadOnlyQuery(sql) {
179
- const statements = splitStatements(sql);
180
- if (statements.length === 0) {
181
- throw new RawSqlError('client.query() was given an empty statement.');
61
+ export function runReadOnly(proven, sql, pragma, refused, run) {
62
+ if (proven.has(sql))
63
+ return run();
64
+ pragma('PRAGMA query_only = ON');
65
+ try {
66
+ const result = run();
67
+ if (proven.size >= 512)
68
+ proven.clear();
69
+ proven.add(sql);
70
+ return result;
182
71
  }
183
- if (statements.length > 1) {
184
- throw new RawSqlError(`client.query() runs a single statement, but ${statements.length} were ` +
185
- 'given. Split them into separate query() calls. ' +
186
- `First: ${firstWords(statements[0] ?? '')}`);
72
+ catch (error) {
73
+ if (refused(error))
74
+ refuseRawSql();
75
+ throw error;
187
76
  }
188
- const statement = stripLeading(statements[0] ?? '');
189
- const verb = statement.match(/^([a-zA-Z]+)/)?.[1]?.toLowerCase();
190
- const rejectWrite = () => {
191
- throw new RawSqlError('client.query() is read-only — this statement writes the local ' +
192
- 'database directly, which bypasses the sync outbox (SPEC §7.1). Use ' +
193
- '`client.mutate([...])` for inserts/updates/deletes. ' +
194
- `Rejected: ${firstWords(sql)}`);
195
- };
196
- if (verb === undefined || !READ_ONLY_VERBS.has(verb))
197
- rejectWrite();
198
- if (verb === 'with') {
199
- // SQLite allows `WITH … DELETE/INSERT/UPDATE`; only a SELECT/VALUES
200
- // main statement is a read.
201
- const main = mainVerbAfterWith(statement);
202
- if (main !== 'select' && main !== 'values')
203
- rejectWrite();
77
+ finally {
78
+ pragma('PRAGMA query_only = OFF');
204
79
  }
205
80
  }
@@ -237,6 +237,10 @@ class ObservationCache {
237
237
  for (const entry of this.#active)
238
238
  entry.reclaim?.();
239
239
  }
240
+ reread() {
241
+ for (const entry of this.#active)
242
+ entry.reread();
243
+ }
240
244
  clear() {
241
245
  for (const entry of this.#entries.values())
242
246
  entry.dispose();
@@ -400,7 +404,7 @@ class QueryEntry {
400
404
  this.store.releaseWindowClaims(this.#owner);
401
405
  this.reset();
402
406
  }
403
- /** SPEC §7.7: a rejected claim is claimed again; its stored error would
407
+ /** SPEC §7.8: a rejected claim is claimed again; its stored error would
404
408
  * fail every read until the last subscriber leaves. */
405
409
  reclaim() {
406
410
  if (this.#delegate !== undefined || this.#claimError === undefined)
@@ -409,6 +413,14 @@ class QueryEntry {
409
413
  this.#claimCoverage();
410
414
  this.#requestRead();
411
415
  }
416
+ /** A read that ran against a departed leader, or failed with it, runs on
417
+ * the leader that serves this tab now. */
418
+ reread() {
419
+ if (this.#claimError !== undefined)
420
+ this.reclaim();
421
+ else
422
+ this.#requestRead();
423
+ }
412
424
  onChange(batch) {
413
425
  if (!batchMatches(batch, this.spec))
414
426
  return;
@@ -608,10 +620,14 @@ class QueryEntry {
608
620
  }
609
621
  }
610
622
  }
623
+ /** A value read in full by `read`. Refreshes requested while a read runs
624
+ * coalesce into one more read after it, whose result alone is published. */
611
625
  class ValueEntry {
612
626
  value;
613
627
  read;
614
628
  #generation = 0;
629
+ #reading = false;
630
+ #stale = false;
615
631
  #listeners = new Set();
616
632
  constructor(value, read) {
617
633
  this.value = value;
@@ -623,14 +639,29 @@ class ValueEntry {
623
639
  return () => this.#listeners.delete(listener);
624
640
  };
625
641
  refresh = () => {
626
- const generation = ++this.#generation;
627
- void this.read().then((next) => {
628
- if (generation === this.#generation)
629
- this.set(next);
630
- });
642
+ this.#stale = true;
643
+ if (!this.#reading)
644
+ void this.#readLoop();
631
645
  };
646
+ async #readLoop() {
647
+ this.#reading = true;
648
+ try {
649
+ while (this.#stale) {
650
+ this.#stale = false;
651
+ const generation = this.#generation;
652
+ const next = await this.read();
653
+ if (generation === this.#generation && !this.#stale)
654
+ this.set(next);
655
+ }
656
+ }
657
+ finally {
658
+ this.#reading = false;
659
+ }
660
+ }
661
+ /** Discard the running read and every refresh requested before now. */
632
662
  invalidate() {
633
663
  this.#generation += 1;
664
+ this.#stale = false;
634
665
  }
635
666
  set(next) {
636
667
  this.invalidate();
@@ -698,6 +729,9 @@ class WindowEntry {
698
729
  this.#listeners.clear();
699
730
  this.reset();
700
731
  }
732
+ reread() {
733
+ this.refresh();
734
+ }
701
735
  onChange(batch) {
702
736
  if (batch.windows.some((change) => change.baseKey === this.baseKey) &&
703
737
  this.#listeners.size > 0) {
@@ -1014,7 +1048,7 @@ export class ReactiveClientStore {
1014
1048
  const roundFailure = this.roundFailure;
1015
1049
  let claimedAttempt;
1016
1050
  this.#offProgress = this.client.onProgress((progress) => {
1017
- // A new sync attempt is the client's retry schedule (§7.6): window
1051
+ // A new sync attempt is the client's retry schedule (§7.7): window
1018
1052
  // claims that failed are claimed again once per attempt.
1019
1053
  if (progress.state === 'running' && progress.attempt !== claimedAttempt) {
1020
1054
  claimedAttempt = progress.attempt;
@@ -1034,12 +1068,20 @@ export class ReactiveClientStore {
1034
1068
  ...previous,
1035
1069
  leadership,
1036
1070
  });
1037
- if (previous.isLoading)
1038
- this.status.refresh();
1039
- // Window edits that failed while no leader served this tab apply now;
1040
- // an applied group compares equal and makes no call.
1041
- if (leadership.state === 'leader' || leadership.state === 'follower')
1042
- this.#reclaimWindows();
1071
+ if (leadership.state !== 'leader' && leadership.state !== 'follower') {
1072
+ if (previous.isLoading)
1073
+ this.status.refresh();
1074
+ return;
1075
+ }
1076
+ // A leader serves this tab again. Reads that failed while none did, or
1077
+ // that a handover rejected, run on it; window edits that failed apply
1078
+ // now, and an applied group compares equal and makes no call.
1079
+ this.#reclaimWindows();
1080
+ this.#queries.reread();
1081
+ this.#windows.reread();
1082
+ this.status.refresh();
1083
+ this.conflicts.refresh();
1084
+ this.outcomes.refresh();
1043
1085
  });
1044
1086
  this.status.refresh();
1045
1087
  this.conflicts.refresh();
@@ -25,7 +25,12 @@ export interface RealtimeSupervisorSnapshot {
25
25
  readonly retryDelayMs?: number;
26
26
  }
27
27
  export interface RealtimeSupervisorOptions {
28
- /** Host online/offline evidence. Unknown remains connectable and observable. */
28
+ /**
29
+ * Host online/offline evidence, the only connectivity the supervisor
30
+ * trusts: a failed round does not suspend it. Unknown remains connectable
31
+ * and observable. Each `online` report drives `syncUntilIdle`, so work a
32
+ * failed round left behind resumes without realtime.
33
+ */
29
34
  readonly connectivity?: RealtimeSupervisorSignal<ClientDiagnosticsConnectivity>;
30
35
  /** Browser/native foreground evidence. Background suspends a tab-owned
31
36
  * socket; with `sharedTransport` it only serves as a resume nudge. */
@@ -71,7 +76,9 @@ export declare function documentLifecycleSignal(options?: DocumentLifecycleSigna
71
76
  * Supported host policy for Syncular's explicit realtime transport. It owns
72
77
  * exactly one connect attempt, runs an explicit catch-up round before claiming
73
78
  * connected, retries transient loss with bounded exponential jitter, and
74
- * suspends across offline, background, or protected-preflight state.
79
+ * suspends across offline, background, or protected-preflight state. A host
80
+ * `online` report also drives `syncUntilIdle` when realtime is unsupported
81
+ * or disabled.
75
82
  */
76
83
  export declare class RealtimeSupervisor {
77
84
  #private;
@@ -104,7 +104,9 @@ export function documentLifecycleSignal(options = {}) {
104
104
  * Supported host policy for Syncular's explicit realtime transport. It owns
105
105
  * exactly one connect attempt, runs an explicit catch-up round before claiming
106
106
  * connected, retries transient loss with bounded exponential jitter, and
107
- * suspends across offline, background, or protected-preflight state.
107
+ * suspends across offline, background, or protected-preflight state. A host
108
+ * `online` report also drives `syncUntilIdle` when realtime is unsupported
109
+ * or disabled.
108
110
  */
109
111
  export class RealtimeSupervisor {
110
112
  #client;
@@ -124,7 +126,8 @@ export class RealtimeSupervisor {
124
126
  #transportConnected = false;
125
127
  #connecting = false;
126
128
  #realtimeSupported = true;
127
- #diagnosticConnectivity = 'unknown';
129
+ /** The client refused a connect with `sync.offline`: its transport gate is closed. */
130
+ #gateClosed = false;
128
131
  #diagnosticSecurity = 'unknown';
129
132
  #attempt = 0;
130
133
  #generation = 0;
@@ -157,7 +160,17 @@ export class RealtimeSupervisor {
157
160
  return;
158
161
  this.#started = true;
159
162
  this.#unsubscribeDiagnostics = this.#client.onDiagnostics((snapshot) => this.#observeDiagnostics(snapshot));
160
- this.#unsubscribeConnectivity = this.#connectivity?.subscribe(() => this.#reconcileHostState());
163
+ this.#unsubscribeConnectivity = this.#connectivity?.subscribe(() => {
164
+ // §1.8: the host's connectivity signal re-arms the drive a failed
165
+ // round left behind. The drive does not wait for the socket, so a
166
+ // socket that cannot connect does not hold back an HTTP round.
167
+ if (this.#connectivity?.current() === 'online' && !this.#hostBlock()) {
168
+ void Promise.resolve()
169
+ .then(() => this.#client.syncUntilIdle())
170
+ .catch(() => undefined);
171
+ }
172
+ this.#reconcileHostState();
173
+ });
161
174
  this.#unsubscribeLifecycle = this.#lifecycle?.subscribe(() => this.#reconcileHostState());
162
175
  this.#unsubscribeProtection = this.#protection?.subscribe(() => this.#reconcileHostState());
163
176
  this.#reconcileHostState();
@@ -207,8 +220,9 @@ export class RealtimeSupervisor {
207
220
  (this.#protection !== undefined && protection !== 'active')) {
208
221
  return 'protected';
209
222
  }
210
- if (this.#diagnosticConnectivity === 'offline' ||
211
- this.#connectivity?.current() === 'offline') {
223
+ // Host evidence only: a failed round is not connectivity evidence, and
224
+ // treating it as such would hold the supervisor offline after recovery.
225
+ if (this.#gateClosed || this.#connectivity?.current() === 'offline') {
212
226
  return 'offline';
213
227
  }
214
228
  if (!this.#sharedTransport && this.#lifecycle?.current() === 'background') {
@@ -317,11 +331,15 @@ export class RealtimeSupervisor {
317
331
  }
318
332
  await this.#catchUpConnectedTransport(generation);
319
333
  }
320
- catch {
334
+ catch (error) {
321
335
  if (generation !== this.#generation) {
322
336
  this.#releaseSupersededSocket();
323
337
  return;
324
338
  }
339
+ this.#gateClosed =
340
+ error instanceof Error &&
341
+ 'code' in error &&
342
+ error.code === 'sync.offline';
325
343
  failed = true;
326
344
  this.#connected = false;
327
345
  this.#transportConnected = false;
@@ -382,7 +400,6 @@ export class RealtimeSupervisor {
382
400
  #observeDiagnostics(snapshot, initial = false) {
383
401
  if (this.#stopped)
384
402
  return;
385
- this.#diagnosticConnectivity = snapshot.host.connectivity;
386
403
  this.#diagnosticSecurity = snapshot.securityLifecycle;
387
404
  if (snapshot.host.realtime === 'unsupported' ||
388
405
  snapshot.host.realtime === 'disabled') {
@@ -406,6 +423,13 @@ export class RealtimeSupervisor {
406
423
  return;
407
424
  this.#realtimeSupported = true;
408
425
  }
426
+ if (this.#gateClosed && snapshot.host.connectivity !== 'offline') {
427
+ // A closed transport gate always reports offline, so any other report
428
+ // means the app reopened it.
429
+ this.#gateClosed = false;
430
+ this.#reconcileHostState();
431
+ return;
432
+ }
409
433
  const block = this.#hostBlock();
410
434
  if (block) {
411
435
  this.#suspend(block);