@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,198 +1,98 @@
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
 
27
- /** Verbs a read-only query may begin with (lowercased). */
28
- const READ_ONLY_VERBS = new Set([
29
- 'select',
30
- 'with',
31
- 'explain',
32
- 'pragma',
33
- 'values',
34
- ]);
35
-
36
24
  /** Raised when `client.query()` is handed SQL it will not run. */
37
25
  export class RawSqlError extends Error {
38
26
  override readonly name = 'RawSqlError';
39
27
  }
40
28
 
41
- /**
42
- * Split `sql` into top-level statements at unquoted `;`, skipping over
43
- * string literals ('…'), quoted/bracketed identifiers ("…", `…`, […]) and
44
- * comments (-- …, /* … *​/) so a `;` inside any of them is not a boundary.
45
- * Returns the non-empty statements (comment/whitespace-only trailers drop).
46
- */
47
- function splitStatements(sql: string): string[] {
48
- const statements: string[] = [];
49
- let start = 0;
50
- let i = 0;
51
- const n = sql.length;
52
-
53
- const pushIfNonEmpty = (end: number) => {
54
- const stripped = stripLeading(sql.slice(start, end));
55
- if (stripped.length > 0) statements.push(sql.slice(start, end));
56
- start = end + 1;
57
- };
58
-
59
- while (i < n) {
60
- const c = sql[i];
61
- if (c === '-' && sql[i + 1] === '-') {
62
- const nl = sql.indexOf('\n', i + 2);
63
- i = nl === -1 ? n : nl + 1;
64
- } else if (c === '/' && sql[i + 1] === '*') {
65
- const close = sql.indexOf('*/', i + 2);
66
- i = close === -1 ? n : close + 2;
67
- } else if (c === "'" || c === '"' || c === '`') {
68
- i = skipQuoted(sql, i, c as "'" | '"' | '`');
69
- } else if (c === '[') {
70
- const close = sql.indexOf(']', i + 1);
71
- i = close === -1 ? n : close + 1;
72
- } else if (c === ';') {
73
- pushIfNonEmpty(i);
74
- i += 1;
75
- } else {
76
- i += 1;
77
- }
78
- }
79
- pushIfNonEmpty(n);
80
- return statements;
81
- }
82
-
83
- /** Advance past a quoted run opened at `open`; SQL doubles the quote to escape it. */
84
- function skipQuoted(sql: string, open: number, quote: "'" | '"' | '`'): number {
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) i += 2;
90
- else return i + 1;
91
- } else {
92
- i += 1;
93
- }
94
- }
95
- return n;
96
- }
97
-
98
- /** Strip leading whitespace and comments, returning the remainder. */
99
- function stripLeading(sql: string): string {
100
- return sql
101
- .replace(/^\s*(?:--[^\n]*(?:\n|$)|\/\*[\s\S]*?\*\/|\s)+/, '')
102
- .trimStart();
103
- }
104
-
105
- function firstWords(sql: string): string {
106
- const trimmed = sql.trim().replace(/\s+/g, ' ');
107
- return trimmed.length > 72 ? `${trimmed.slice(0, 72)}…` : trimmed;
29
+ /** Refuse a statement the raw-SQL tier does not run. */
30
+ function refuseRawSql(): never {
31
+ throw new RawSqlError(
32
+ 'client.query() runs read-only statements and no PRAGMA; write through client.mutate() so the outbox records it (SPEC §7.1).',
33
+ );
108
34
  }
109
35
 
110
36
  /**
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.
37
+ * Prepare `sql` for the raw-SQL tier or throw `RawSqlError`. `prepare`
38
+ * compiles the first statement only and returns it, the text SQLite compiled
39
+ * for it, and whether SQLite reports it read-only with result columns.
116
40
  */
117
- function mainVerbAfterWith(sql: string): string | undefined {
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] as string;
132
- if (c === '-' && sql[i + 1] === '-') {
133
- const nl = sql.indexOf('\n', i + 2);
134
- i = nl === -1 ? n : nl + 1;
135
- } else if (c === '/' && sql[i + 1] === '*') {
136
- const close = sql.indexOf('*/', i + 2);
137
- i = close === -1 ? n : close + 2;
138
- } else if (c === "'" || c === '"' || c === '`') {
139
- i = skipQuoted(sql, i, c as "'" | '"' | '`');
140
- } else if (c === '[') {
141
- const close = sql.indexOf(']', i + 1);
142
- i = close === -1 ? n : close + 1;
143
- } else if (c === '(') {
144
- depth += 1;
145
- i += 1;
146
- } else if (c === ')') {
147
- depth -= 1;
148
- i += 1;
149
- } else if (/[A-Za-z_]/.test(c)) {
150
- let j = i + 1;
151
- while (j < n && /[A-Za-z0-9_]/.test(sql[j] as string)) j += 1;
152
- const word = sql.slice(i, j).toLowerCase();
153
- if (depth === 0) {
154
- if (!sawWith && word === 'with') sawWith = true;
155
- else if (sawWith && MAIN_VERBS.has(word)) return word;
156
- }
157
- i = j;
158
- } else {
159
- i += 1;
160
- }
41
+ export function prepareReadOnly<S>(
42
+ sql: string,
43
+ prepare: () => readonly [statement: S, first: string, reads: boolean],
44
+ ): S {
45
+ if (
46
+ /^(?:[\s;]|--[^\n]*(?:\n|$)|\/\*(?:[^*]|\*(?!\/))*(?:\*\/|$)|explain\b|query\b|plan\b)*pragma\b/i.test(
47
+ sql,
48
+ )
49
+ ) {
50
+ refuseRawSql();
51
+ }
52
+ const [statement, first, reads] = prepare();
53
+ if (
54
+ sql
55
+ .slice(first.length)
56
+ .replace(
57
+ /^(?:[\s;]|--[^\n]*(?:\n|$)|\/\*(?:[^*]|\*(?!\/))*(?:\*\/|$))*/,
58
+ '',
59
+ ) !== ''
60
+ ) {
61
+ throw new RawSqlError('client.query() runs one statement per call.');
161
62
  }
162
- return undefined;
63
+ if (!reads) refuseRawSql();
64
+ return statement;
163
65
  }
164
66
 
165
67
  /**
166
- * Assert `sql` is a single read-only statement, or throw `RawSqlError`.
167
- * Called by `client.query()` before the string reaches the database.
68
+ * Run a statement `prepareReadOnly` accepted on an adapter without
69
+ * `sqlite3_stmt_readonly` (bun:sqlite before 1.4.4, node:sqlite). SQLite
70
+ * refuses a write when it runs: under `query_only` a write transaction fails
71
+ * before it changes anything, and `refused` recognizes that error. The
72
+ * verdict depends on the text alone, since a write fails at its write
73
+ * transaction whether or not it touches a row, so a text that completed
74
+ * under `query_only` joins `proven` and later runs skip the pragma: a flag
75
+ * pragma expires every prepared statement of the connection. `proven` is per
76
+ * connection and cleared at 512 texts, so dynamic SQL cannot grow it.
168
77
  */
169
- export function assertReadOnlyQuery(sql: string): void {
170
- const statements = splitStatements(sql);
171
- if (statements.length === 0) {
172
- throw new RawSqlError('client.query() was given an empty statement.');
173
- }
174
- if (statements.length > 1) {
175
- throw new RawSqlError(
176
- `client.query() runs a single statement, but ${statements.length} were ` +
177
- 'given. Split them into separate query() calls. ' +
178
- `First: ${firstWords(statements[0] ?? '')}`,
179
- );
180
- }
181
- const statement = stripLeading(statements[0] ?? '');
182
- const verb = statement.match(/^([a-zA-Z]+)/)?.[1]?.toLowerCase();
183
- const rejectWrite = (): never => {
184
- throw new RawSqlError(
185
- 'client.query() is read-only — this statement writes the local ' +
186
- 'database directly, which bypasses the sync outbox (SPEC §7.1). Use ' +
187
- '`client.mutate([...])` for inserts/updates/deletes. ' +
188
- `Rejected: ${firstWords(sql)}`,
189
- );
190
- };
191
- if (verb === undefined || !READ_ONLY_VERBS.has(verb)) rejectWrite();
192
- if (verb === 'with') {
193
- // SQLite allows `WITH … DELETE/INSERT/UPDATE`; only a SELECT/VALUES
194
- // main statement is a read.
195
- const main = mainVerbAfterWith(statement);
196
- if (main !== 'select' && main !== 'values') rejectWrite();
78
+ export function runReadOnly<R>(
79
+ proven: Set<string>,
80
+ sql: string,
81
+ pragma: (sql: string) => void,
82
+ refused: (error: unknown) => boolean,
83
+ run: () => R,
84
+ ): R {
85
+ if (proven.has(sql)) return run();
86
+ pragma('PRAGMA query_only = ON');
87
+ try {
88
+ const result = run();
89
+ if (proven.size >= 512) proven.clear();
90
+ proven.add(sql);
91
+ return result;
92
+ } catch (error) {
93
+ if (refused(error)) refuseRawSql();
94
+ throw error;
95
+ } finally {
96
+ pragma('PRAGMA query_only = OFF');
197
97
  }
198
98
  }
@@ -315,8 +315,10 @@ function reconcileRows<Row>(
315
315
 
316
316
  interface CachedObservation {
317
317
  onChange(batch: ClientChangeBatch): void;
318
- /** A leader serves this tab again (it leads or follows a bound leader). */
318
+ /** Claim again after a rejected claim. */
319
319
  reclaim?(): void;
320
+ /** A leader serves this tab again (it leads or follows a bound leader). */
321
+ reread(): void;
320
322
  reset(): void;
321
323
  dispose(): void;
322
324
  }
@@ -361,6 +363,9 @@ class ObservationCache {
361
363
  reclaim(): void {
362
364
  for (const entry of this.#active) entry.reclaim?.();
363
365
  }
366
+ reread(): void {
367
+ for (const entry of this.#active) entry.reread();
368
+ }
364
369
  clear(): void {
365
370
  for (const entry of this.#entries.values()) entry.dispose();
366
371
  this.#entries.clear();
@@ -540,7 +545,7 @@ class QueryEntry<Row> implements ExternalStoreEntry<LiveQueryResult<Row>> {
540
545
  this.reset();
541
546
  }
542
547
 
543
- /** SPEC §7.7: a rejected claim is claimed again; its stored error would
548
+ /** SPEC §7.8: a rejected claim is claimed again; its stored error would
544
549
  * fail every read until the last subscriber leaves. */
545
550
  reclaim(): void {
546
551
  if (this.#delegate !== undefined || this.#claimError === undefined) return;
@@ -549,6 +554,13 @@ class QueryEntry<Row> implements ExternalStoreEntry<LiveQueryResult<Row>> {
549
554
  this.#requestRead();
550
555
  }
551
556
 
557
+ /** A read that ran against a departed leader, or failed with it, runs on
558
+ * the leader that serves this tab now. */
559
+ reread(): void {
560
+ if (this.#claimError !== undefined) this.reclaim();
561
+ else this.#requestRead();
562
+ }
563
+
552
564
  onChange(batch: ClientChangeBatch): void {
553
565
  if (!batchMatches(batch, this.spec)) return;
554
566
  if (batch.revision > this.#desiredRevision) {
@@ -759,8 +771,12 @@ class QueryEntry<Row> implements ExternalStoreEntry<LiveQueryResult<Row>> {
759
771
  }
760
772
  }
761
773
 
774
+ /** A value read in full by `read`. Refreshes requested while a read runs
775
+ * coalesce into one more read after it, whose result alone is published. */
762
776
  class ValueEntry<T> implements ExternalStoreEntry<T> {
763
777
  #generation = 0;
778
+ #reading = false;
779
+ #stale = false;
764
780
  readonly #listeners = new Set<() => void>();
765
781
  constructor(
766
782
  private value: T,
@@ -772,13 +788,26 @@ class ValueEntry<T> implements ExternalStoreEntry<T> {
772
788
  return () => this.#listeners.delete(listener);
773
789
  };
774
790
  refresh = (): void => {
775
- const generation = ++this.#generation;
776
- void this.read().then((next) => {
777
- if (generation === this.#generation) this.set(next);
778
- });
791
+ this.#stale = true;
792
+ if (!this.#reading) void this.#readLoop();
779
793
  };
794
+ async #readLoop(): Promise<void> {
795
+ this.#reading = true;
796
+ try {
797
+ while (this.#stale) {
798
+ this.#stale = false;
799
+ const generation = this.#generation;
800
+ const next = await this.read();
801
+ if (generation === this.#generation && !this.#stale) this.set(next);
802
+ }
803
+ } finally {
804
+ this.#reading = false;
805
+ }
806
+ }
807
+ /** Discard the running read and every refresh requested before now. */
780
808
  invalidate(): void {
781
809
  this.#generation += 1;
810
+ this.#stale = false;
782
811
  }
783
812
  set(next: T): void {
784
813
  this.invalidate();
@@ -855,6 +884,9 @@ class WindowEntry implements ExternalStoreEntry<WindowState> {
855
884
  this.#listeners.clear();
856
885
  this.reset();
857
886
  }
887
+ reread(): void {
888
+ this.refresh();
889
+ }
858
890
  onChange(batch: ClientChangeBatch): void {
859
891
  if (
860
892
  batch.windows.some((change) => change.baseKey === this.baseKey) &&
@@ -1199,7 +1231,7 @@ export class ReactiveClientStore {
1199
1231
  >;
1200
1232
  let claimedAttempt: number | undefined;
1201
1233
  this.#offProgress = this.client.onProgress((progress) => {
1202
- // A new sync attempt is the client's retry schedule (§7.6): window
1234
+ // A new sync attempt is the client's retry schedule (§7.7): window
1203
1235
  // claims that failed are claimed again once per attempt.
1204
1236
  if (progress.state === 'running' && progress.attempt !== claimedAttempt) {
1205
1237
  claimedAttempt = progress.attempt;
@@ -1227,11 +1259,19 @@ export class ReactiveClientStore {
1227
1259
  ...previous,
1228
1260
  leadership,
1229
1261
  });
1230
- if (previous.isLoading) this.status.refresh();
1231
- // Window edits that failed while no leader served this tab apply now;
1232
- // an applied group compares equal and makes no call.
1233
- if (leadership.state === 'leader' || leadership.state === 'follower')
1234
- this.#reclaimWindows();
1262
+ if (leadership.state !== 'leader' && leadership.state !== 'follower') {
1263
+ if (previous.isLoading) this.status.refresh();
1264
+ return;
1265
+ }
1266
+ // A leader serves this tab again. Reads that failed while none did, or
1267
+ // that a handover rejected, run on it; window edits that failed apply
1268
+ // now, and an applied group compares equal and makes no call.
1269
+ this.#reclaimWindows();
1270
+ this.#queries.reread();
1271
+ this.#windows.reread();
1272
+ this.status.refresh();
1273
+ this.conflicts.refresh();
1274
+ this.outcomes.refresh();
1235
1275
  });
1236
1276
  this.status.refresh();
1237
1277
  this.conflicts.refresh();
@@ -48,7 +48,12 @@ export interface RealtimeSupervisorSnapshot {
48
48
  }
49
49
 
50
50
  export interface RealtimeSupervisorOptions {
51
- /** Host online/offline evidence. Unknown remains connectable and observable. */
51
+ /**
52
+ * Host online/offline evidence, the only connectivity the supervisor
53
+ * trusts: a failed round does not suspend it. Unknown remains connectable
54
+ * and observable. Each `online` report drives `syncUntilIdle`, so work a
55
+ * failed round left behind resumes without realtime.
56
+ */
52
57
  readonly connectivity?: RealtimeSupervisorSignal<ClientDiagnosticsConnectivity>;
53
58
  /** Browser/native foreground evidence. Background suspends a tab-owned
54
59
  * socket; with `sharedTransport` it only serves as a resume nudge. */
@@ -209,7 +214,9 @@ export function documentLifecycleSignal(
209
214
  * Supported host policy for Syncular's explicit realtime transport. It owns
210
215
  * exactly one connect attempt, runs an explicit catch-up round before claiming
211
216
  * connected, retries transient loss with bounded exponential jitter, and
212
- * suspends across offline, background, or protected-preflight state.
217
+ * suspends across offline, background, or protected-preflight state. A host
218
+ * `online` report also drives `syncUntilIdle` when realtime is unsupported
219
+ * or disabled.
213
220
  */
214
221
  export class RealtimeSupervisor {
215
222
  readonly #client: RealtimeSupervisorClient;
@@ -230,7 +237,8 @@ export class RealtimeSupervisor {
230
237
  #transportConnected = false;
231
238
  #connecting = false;
232
239
  #realtimeSupported = true;
233
- #diagnosticConnectivity: ClientDiagnosticsConnectivity = 'unknown';
240
+ /** The client refused a connect with `sync.offline`: its transport gate is closed. */
241
+ #gateClosed = false;
234
242
  #diagnosticSecurity: RealtimeSupervisorProtectionState = 'unknown';
235
243
  #attempt = 0;
236
244
  #generation = 0;
@@ -277,9 +285,17 @@ export class RealtimeSupervisor {
277
285
  this.#unsubscribeDiagnostics = this.#client.onDiagnostics((snapshot) =>
278
286
  this.#observeDiagnostics(snapshot),
279
287
  );
280
- this.#unsubscribeConnectivity = this.#connectivity?.subscribe(() =>
281
- this.#reconcileHostState(),
282
- );
288
+ this.#unsubscribeConnectivity = this.#connectivity?.subscribe(() => {
289
+ // §1.8: the host's connectivity signal re-arms the drive a failed
290
+ // round left behind. The drive does not wait for the socket, so a
291
+ // socket that cannot connect does not hold back an HTTP round.
292
+ if (this.#connectivity?.current() === 'online' && !this.#hostBlock()) {
293
+ void Promise.resolve()
294
+ .then(() => this.#client.syncUntilIdle())
295
+ .catch(() => undefined);
296
+ }
297
+ this.#reconcileHostState();
298
+ });
283
299
  this.#unsubscribeLifecycle = this.#lifecycle?.subscribe(() =>
284
300
  this.#reconcileHostState(),
285
301
  );
@@ -334,10 +350,9 @@ export class RealtimeSupervisor {
334
350
  ) {
335
351
  return 'protected';
336
352
  }
337
- if (
338
- this.#diagnosticConnectivity === 'offline' ||
339
- this.#connectivity?.current() === 'offline'
340
- ) {
353
+ // Host evidence only: a failed round is not connectivity evidence, and
354
+ // treating it as such would hold the supervisor offline after recovery.
355
+ if (this.#gateClosed || this.#connectivity?.current() === 'offline') {
341
356
  return 'offline';
342
357
  }
343
358
  if (!this.#sharedTransport && this.#lifecycle?.current() === 'background') {
@@ -464,11 +479,15 @@ export class RealtimeSupervisor {
464
479
  return;
465
480
  }
466
481
  await this.#catchUpConnectedTransport(generation);
467
- } catch {
482
+ } catch (error) {
468
483
  if (generation !== this.#generation) {
469
484
  this.#releaseSupersededSocket();
470
485
  return;
471
486
  }
487
+ this.#gateClosed =
488
+ error instanceof Error &&
489
+ 'code' in error &&
490
+ error.code === 'sync.offline';
472
491
  failed = true;
473
492
  this.#connected = false;
474
493
  this.#transportConnected = false;
@@ -527,7 +546,6 @@ export class RealtimeSupervisor {
527
546
  initial = false,
528
547
  ): void {
529
548
  if (this.#stopped) return;
530
- this.#diagnosticConnectivity = snapshot.host.connectivity;
531
549
  this.#diagnosticSecurity = snapshot.securityLifecycle;
532
550
  if (
533
551
  snapshot.host.realtime === 'unsupported' ||
@@ -552,6 +570,13 @@ export class RealtimeSupervisor {
552
570
  if (snapshot.host.realtime !== 'connected') return;
553
571
  this.#realtimeSupported = true;
554
572
  }
573
+ if (this.#gateClosed && snapshot.host.connectivity !== 'offline') {
574
+ // A closed transport gate always reports offline, so any other report
575
+ // means the app reopened it.
576
+ this.#gateClosed = false;
577
+ this.#reconcileHostState();
578
+ return;
579
+ }
555
580
  const block = this.#hostBlock();
556
581
  if (block) {
557
582
  this.#suspend(block);