@syncular/client 0.86.0 → 0.90.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 (45) hide show
  1. package/README.md +3 -1
  2. package/dist/blob.d.ts +0 -4
  3. package/dist/blob.js +7 -22
  4. package/dist/client.d.ts +12 -1
  5. package/dist/client.js +441 -422
  6. package/dist/diagnostics.d.ts +2 -4
  7. package/dist/diagnostics.js +3 -17
  8. package/dist/encryption.js +2 -21
  9. package/dist/errors.d.ts +2 -0
  10. package/dist/errors.js +4 -0
  11. package/dist/failed-overlay.js +2 -2
  12. package/dist/local-purge.d.ts +1 -0
  13. package/dist/local-purge.js +1 -1
  14. package/dist/local-rebootstrap-receipt.js +2 -2
  15. package/dist/local-rebootstrap.js +1 -1
  16. package/dist/native-bridge.d.ts +6 -2
  17. package/dist/native-bridge.js +24 -11
  18. package/dist/outcomes.d.ts +11 -0
  19. package/dist/outcomes.js +19 -16
  20. package/dist/previous-version.js +23 -35
  21. package/dist/schema.js +14 -13
  22. package/dist/state.d.ts +16 -4
  23. package/dist/state.js +83 -44
  24. package/dist/worker-core.js +7 -8
  25. package/dist/worker-host.d.ts +5 -2
  26. package/dist/worker-host.js +9 -0
  27. package/dist/worker-protocol.d.ts +2 -1
  28. package/package.json +3 -3
  29. package/src/blob.ts +7 -24
  30. package/src/client.ts +615 -501
  31. package/src/diagnostics.ts +3 -19
  32. package/src/encryption.ts +7 -25
  33. package/src/errors.ts +5 -0
  34. package/src/failed-overlay.ts +2 -6
  35. package/src/local-purge.ts +1 -1
  36. package/src/local-rebootstrap-receipt.ts +2 -5
  37. package/src/local-rebootstrap.ts +1 -2
  38. package/src/native-bridge.ts +35 -13
  39. package/src/outcomes.ts +34 -25
  40. package/src/previous-version.ts +31 -40
  41. package/src/schema.ts +13 -13
  42. package/src/state.ts +107 -64
  43. package/src/worker-core.ts +9 -16
  44. package/src/worker-host.ts +17 -1
  45. package/src/worker-protocol.ts +2 -0
package/dist/state.js CHANGED
@@ -2,7 +2,15 @@ export const META_TABLE = '_syncular_meta';
2
2
  import { PENDING_EVICTIONS } from './window.js';
3
3
  import { WINDOWS_TABLE } from './window.js';
4
4
  export const UNITS_TABLE = '_syncular_units';
5
- import { ClientSyncError } from './errors.js';
5
+ /**
6
+ * Durable unit state (SPEC.md §4.1): per unit its scope map, status, live
7
+ * membership, catch-up cursor and opaque resume token (§4.7), the tables its
8
+ * current bootstrap seeded (§5.6) and the last echo (§4.4) the §3.3 purge
9
+ * contract is keyed on. The replica cursor, the echo digest and the
10
+ * registration digest the server holds live in meta.
11
+ */
12
+ import { definedObject, } from '@syncular/core';
13
+ import { localStateCorrupt } from './errors.js';
6
14
  export const LOCAL_REVISION_KEY = 'localRevision';
7
15
  /** §4.5 replica cursor; absent means `-1`. */
8
16
  export const REPLICA_CURSOR_KEY = 'replicaCursor';
@@ -39,14 +47,16 @@ export function pairScopes(scopes, table, echo) {
39
47
  return effective;
40
48
  }
41
49
  /** §3.3 row ownership: the pair scopes of every owner of `table` but one.
42
- * A bootstrapping unit owns the tables its current bootstrap seeded. */
50
+ * A bootstrapping unit owns the tables its current bootstrap seeded, and a
51
+ * restricted one the tables outside its restriction. */
43
52
  export function unitOwners(units, table, exceptId) {
44
53
  return units.flatMap((unit) => {
45
54
  const scopes = unit.id !== exceptId &&
46
55
  (owning(unit) ||
47
56
  (unit.status === 'active' &&
48
57
  unit.echo !== undefined &&
49
- unit.seeded.includes(table.name))) &&
58
+ (unit.seeded.includes(table.name) ||
59
+ unit.restrict?.tables.includes(table.name) === false))) &&
50
60
  covers(table, unit.scopes)
51
61
  ? pairScopes(unit.scopes, table.name, unit.echo)
52
62
  : undefined;
@@ -55,29 +65,30 @@ export function unitOwners(units, table, exceptId) {
55
65
  }
56
66
  /** A unit row; every persisted field must have its stored type and shape,
57
67
  * otherwise the row is `sync.local_corrupt` (§7.5). */
68
+ export const unitStateCorrupt = () => localStateCorrupt('persisted unit state is invalid');
58
69
  function rowToRecord(row) {
59
- const corrupt = () => new ClientSyncError('sync.local_corrupt', 'persisted unit state is invalid');
60
70
  const json = (raw) => {
61
71
  if (typeof raw !== 'string')
62
- throw corrupt();
72
+ throw unitStateCorrupt();
63
73
  try {
64
74
  return JSON.parse(raw);
65
75
  }
66
76
  catch {
67
- throw corrupt();
77
+ throw unitStateCorrupt();
68
78
  }
69
79
  };
70
80
  const isMap = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
71
81
  const isStrings = (value) => Array.isArray(value) && value.every((item) => typeof item === 'string');
72
82
  const optionalText = (value) => {
73
83
  if (value !== null && typeof value !== 'string')
74
- throw corrupt();
84
+ throw unitStateCorrupt();
75
85
  return value ?? undefined;
76
86
  };
77
87
  const scopes = json(row.scopes);
78
88
  const seeded = json(row.seeded);
79
89
  const echo = row.echo === null ? undefined : json(row.echo);
80
90
  const applied = row.applied === null ? undefined : json(row.applied);
91
+ const restrict = row.restriction === null ? undefined : json(row.restriction);
81
92
  const { id, status, cursor } = row;
82
93
  if (typeof id !== 'string' ||
83
94
  !isMap(scopes) ||
@@ -93,27 +104,31 @@ function rowToRecord(row) {
93
104
  (record.status === 'active' || record.status === 'revoked') &&
94
105
  isMap(record.scopes) &&
95
106
  Object.values(record.scopes).every(isStrings)))))
96
- throw corrupt();
97
- const record = {
107
+ throw unitStateCorrupt();
108
+ let restriction;
109
+ if (restrict !== undefined) {
110
+ if (!isMap(restrict) ||
111
+ !Number.isInteger(restrict.cursor) ||
112
+ !isStrings(restrict.tables))
113
+ throw unitStateCorrupt();
114
+ restriction = {
115
+ cursor: restrict.cursor,
116
+ tables: restrict.tables,
117
+ };
118
+ }
119
+ return definedObject({
98
120
  id,
99
121
  scopes: scopes,
100
122
  explicit: row.explicit === 1,
101
123
  status,
102
124
  seeded,
103
- };
104
- const reasonCode = optionalText(row.reason_code);
105
- if (reasonCode !== undefined)
106
- record.reasonCode = reasonCode;
107
- if (typeof cursor === 'number')
108
- record.cursor = cursor;
109
- const bootstrapState = optionalText(row.bootstrap_state);
110
- if (bootstrapState !== undefined)
111
- record.bootstrapState = bootstrapState;
112
- if (echo !== undefined)
113
- record.echo = echo;
114
- if (applied !== undefined)
115
- record.applied = applied;
116
- return record;
125
+ reasonCode: optionalText(row.reason_code),
126
+ cursor: typeof cursor === 'number' ? cursor : undefined,
127
+ bootstrapState: optionalText(row.bootstrap_state),
128
+ echo: echo,
129
+ applied: applied,
130
+ restrict: restriction,
131
+ });
117
132
  }
118
133
  /** Every unit in registration order (§4.1). */
119
134
  export function loadUnits(db) {
@@ -128,7 +143,7 @@ export function getUnit(db, id) {
128
143
  /** Insert or update in place: an update keeps the registration order. The
129
144
  * §5.6 applied-segment record ends when the cursor or the token changes. */
130
145
  export function saveUnit(db, record) {
131
- db.exec(`INSERT INTO ${UNITS_TABLE}(id,scopes,explicit,status,reason_code,cursor,bootstrap_state,seeded,echo)VALUES(?,?,?,?,?,?,?,?,?)ON CONFLICT(id)DO UPDATE SET explicit=excluded.explicit,status=excluded.status,reason_code=excluded.reason_code,cursor=excluded.cursor,bootstrap_state=excluded.bootstrap_state,seeded=excluded.seeded,echo=excluded.echo,applied=iif((cursor,bootstrap_state)IS(excluded.cursor,excluded.bootstrap_state),applied,NULL)`, [
146
+ db.exec(`INSERT INTO ${UNITS_TABLE}(id,scopes,explicit,status,reason_code,cursor,bootstrap_state,seeded,echo,restriction)VALUES(?,?,?,?,?,?,?,?,?,?)ON CONFLICT(id)DO UPDATE SET explicit=excluded.explicit,status=excluded.status,reason_code=excluded.reason_code,cursor=excluded.cursor,bootstrap_state=excluded.bootstrap_state,seeded=excluded.seeded,echo=excluded.echo,restriction=excluded.restriction,applied=iif((cursor,bootstrap_state)IS(excluded.cursor,excluded.bootstrap_state),applied,NULL)`, [
132
147
  record.id,
133
148
  JSON.stringify(record.scopes),
134
149
  record.explicit ? 1 : 0,
@@ -138,6 +153,7 @@ export function saveUnit(db, record) {
138
153
  record.bootstrapState ?? null,
139
154
  JSON.stringify(record.seeded),
140
155
  record.echo === undefined ? null : JSON.stringify(record.echo),
156
+ record.restrict === undefined ? null : JSON.stringify(record.restrict),
141
157
  ]);
142
158
  }
143
159
  /** §5.6: `rows` rows of `segmentId` applied at the unit's position. Runs
@@ -152,11 +168,17 @@ export function deleteUnit(db, id) {
152
168
  * §7.4.3 reset, §2.1 log reset and local rebootstrap: keep the unit
153
169
  * registrations (the app's declared intent) and discard the synced state of
154
170
  * every unit outside `keep`, so the next round sends the list and
155
- * fresh-bootstraps those units. The replica cursor survives only while a
171
+ * fresh-bootstraps those units. A bump (`restricts` given) keeps every echo
172
+ * and restricts the units it names. The replica cursor survives only while a
156
173
  * kept unit is live. Caller owns the transaction.
157
174
  */
158
- export function resetUnits(db, keep = []) {
159
- db.exec(`UPDATE ${UNITS_TABLE} SET status='active',reason_code=NULL,cursor=-1,bootstrap_state=NULL,seeded='[]',echo=NULL,applied=NULL WHERE id NOT IN(${keep.map(() => '?').join(',')})`, [...keep]);
175
+ export function resetUnits(db, keep = [], restricts) {
176
+ db.exec(`UPDATE ${UNITS_TABLE} SET status='active',reason_code=NULL,cursor=-1,bootstrap_state=NULL,seeded='[]',${restricts ? '' : 'echo=NULL,'}applied=NULL,restriction=NULL WHERE id NOT IN(${keep.map(() => '?').join(',')})`, [...keep]);
177
+ for (const [id, restrict] of restricts ?? [])
178
+ db.exec(`UPDATE ${UNITS_TABLE} SET restriction=? WHERE id=?`, [
179
+ JSON.stringify(restrict),
180
+ id,
181
+ ]);
160
182
  db.exec(`DELETE FROM ${META_TABLE} WHERE key IN(?,?) OR key=? AND NOT EXISTS(SELECT 1 FROM ${UNITS_TABLE} WHERE cursor IS NULL)`, [ECHO_DIGEST_KEY, REGISTERED_DIGEST_KEY, REPLICA_CURSOR_KEY]);
161
183
  }
162
184
  /** §4.5: the replica cursor, `-1` while no unit is live. */
@@ -204,7 +226,7 @@ export function pruneUnknownUnits(db, schema, bump = false) {
204
226
  generations === null ||
205
227
  Array.isArray(generations) ||
206
228
  Object.values(generations).some((value) => typeof value !== 'string'))
207
- throw new ClientSyncError('sync.local_corrupt', 'invalid persisted table generations');
229
+ throw localStateCorrupt('invalid persisted table generations');
208
230
  const kept = new Set([...schema.tables.values()]
209
231
  .filter((table) => table.generation !== undefined &&
210
232
  generations[table.name] ===
@@ -251,14 +273,33 @@ export function pruneUnknownUnits(db, schema, bump = false) {
251
273
  db.exec(`DELETE FROM ${PENDING_EVICTIONS} WHERE unit_id=?`, [id]);
252
274
  deleteUnit(db, id);
253
275
  }
254
- return {
255
- tables: kept,
256
- units: loadUnits(db)
257
- .filter(({ scopes }) => Object.entries(previous ?? {}).every(([name, old]) => kept.has(name) ||
258
- !Object.keys(scopes).every((v) => old[v] !== undefined)) &&
259
- [...schema.tables.values()].every((table) => kept.has(table.name) || !covers(table, scopes)))
260
- .map((unit) => unit.id),
261
- };
276
+ const units = [];
277
+ const restricts = new Map();
278
+ for (const unit of loadUnits(db)) {
279
+ const covered = [...schema.tables.values()]
280
+ .filter((table) => covers(table, unit.scopes))
281
+ .map((table) => table.name);
282
+ if (Object.entries(previous ?? {}).every(([name, old]) => kept.has(name) ||
283
+ !Object.keys(unit.scopes).every((v) => old[v] !== undefined)) &&
284
+ covered.every((name) => kept.has(name))) {
285
+ units.push(unit.id);
286
+ continue;
287
+ }
288
+ // §7.4.3 restriction: a live, post-bootstrap or restricted unit keeps its
289
+ // rows of kept tables through its kept cursor and bootstraps the rest.
290
+ const tables = covered
291
+ .filter((name) => !kept.has(name) || unit.restrict?.tables.includes(name))
292
+ .sort();
293
+ const cursor = unit.restrict?.cursor ??
294
+ (bootstrapping(unit) ? -1 : (unit.cursor ?? replicaCursor(db)));
295
+ if (bump &&
296
+ unit.status === 'active' &&
297
+ cursor >= 0 &&
298
+ tables.length > 0 &&
299
+ tables.length < covered.length)
300
+ restricts.set(unit.id, { cursor, tables });
301
+ }
302
+ return { tables: kept, units, restricts };
262
303
  }
263
304
  export function getMeta(db, key) {
264
305
  const row = db.query(`SELECT value FROM ${META_TABLE} WHERE key=?`, [key])[0];
@@ -275,14 +316,12 @@ export function getLocalRevision(db) {
275
316
  const raw = getMeta(db, LOCAL_REVISION_KEY);
276
317
  if (raw === undefined)
277
318
  return 0n;
278
- if (typeof raw !== 'string' || !/^(0|[1-9][0-9]*)$/.test(raw)) {
279
- throw new ClientSyncError('sync.local_corrupt', 'persisted local revision is invalid');
280
- }
281
- const revision = BigInt(raw);
282
- if (revision > MAX_U64) {
283
- throw new ClientSyncError('sync.local_corrupt', 'persisted local revision is invalid');
319
+ if (typeof raw !== 'string' ||
320
+ !/^(0|[1-9][0-9]*)$/.test(raw) ||
321
+ BigInt(raw) > MAX_U64) {
322
+ throw localStateCorrupt('persisted local revision is invalid');
284
323
  }
285
- return revision;
324
+ return BigInt(raw);
286
325
  }
287
326
  /**
288
327
  * Increment the durable revision. The caller MUST own the same transaction as
@@ -291,7 +330,7 @@ export function getLocalRevision(db) {
291
330
  export function bumpLocalRevision(db) {
292
331
  const current = getLocalRevision(db);
293
332
  if (current === MAX_U64) {
294
- throw new ClientSyncError('sync.local_corrupt', 'local revision exhausted u64');
333
+ throw localStateCorrupt('local revision exhausted u64');
295
334
  }
296
335
  const next = current + 1n;
297
336
  setMeta(db, LOCAL_REVISION_KEY, next.toString());
@@ -352,6 +352,8 @@ export function startSyncWorkerCore(overrides, createLocalAuthority) {
352
352
  'commitOutcome',
353
353
  'commitOutcomes',
354
354
  'resolveCommitOutcome',
355
+ 'commitDelivery',
356
+ 'replaceCommitOutcome',
355
357
  'pendingCommits',
356
358
  'units',
357
359
  'unit',
@@ -376,11 +378,9 @@ export function startSyncWorkerCore(overrides, createLocalAuthority) {
376
378
  await requireClient().beginSecurityPreflight();
377
379
  },
378
380
  activateSecurity: async (options = {}) => {
379
- await requireClient().activateSecurity({
380
- ...(options.encryption !== undefined
381
- ? { encryption: encryptionConfigFromKeyring(options.encryption) }
382
- : {}),
383
- });
381
+ await requireClient().activateSecurity(options.encryption === undefined
382
+ ? {}
383
+ : { encryption: encryptionConfigFromKeyring(options.encryption) });
384
384
  },
385
385
  setWindow: async (base, units) => {
386
386
  await requireClient().setWindowCommand(base, units);
@@ -391,8 +391,7 @@ export function startSyncWorkerCore(overrides, createLocalAuthority) {
391
391
  patch: (table, rowId, partial, options) => {
392
392
  // Same §8.4 rule as `mutate`: a local write must push without the app
393
393
  // orchestrating sync, so consume the core's immediate intent.
394
- const result = requireClient().patchCommand(table, rowId, partial, options);
395
- return result.value;
394
+ return requireClient().patchCommand(table, rowId, partial, options).value;
396
395
  },
397
396
  sync: () => {
398
397
  const running = requireClient();
@@ -469,7 +468,7 @@ export function startSyncWorkerCore(overrides, createLocalAuthority) {
469
468
  void (async () => {
470
469
  try {
471
470
  const value = await fn();
472
- post({ t: 'result', id, value }, transfer !== undefined ? transfer(value) : undefined);
471
+ post({ t: 'result', id, value }, transfer?.(value));
473
472
  }
474
473
  catch (error) {
475
474
  post({ t: 'error', id, error: toErrorShape(error) });
@@ -1,5 +1,5 @@
1
1
  import { type SyncProgress, type SyncProgressListener } from './progress.js';
2
- import type { PromiseMethods } from './client.js';
2
+ import type { CommitDelivery, PromiseMethods } from './client.js';
3
3
  /**
4
4
  * Main-thread side of the worker mode and the
5
5
  * multi-tab topology.
@@ -25,7 +25,7 @@ import type { PromiseMethods } from './client.js';
25
25
  */
26
26
  import { type PresenceErrorCode, type WakeReason } from '@syncular/core';
27
27
  import type { BlobRef, CachedBlob } from './blob.js';
28
- import type { ConflictRecord, CurrentBaseProof, MutationInput, PresencePeer, QueryReadSpec, QuerySnapshot, RejectionRecord, SecurityLifecycle, SnapshotRead, SnapshotReadRequest, SyncClientConfig, SyncClientLimits, SyncSummary, SyncIdleOptions, SyncIdleResult, WindowState } from './client.js';
28
+ import type { ConflictRecord, CurrentBaseProof, MutationInput, ReplaceCommitOutcomeInput, PresencePeer, QueryReadSpec, QuerySnapshot, RejectionRecord, SecurityLifecycle, SnapshotRead, SnapshotReadRequest, SyncClientConfig, SyncClientLimits, SyncSummary, SyncIdleOptions, SyncIdleResult, WindowState } from './client.js';
29
29
  import type { SqlRow, SqlValue } from './database.js';
30
30
  import type { DevtoolsRegistrar } from './devtools.js';
31
31
  import { ClientDiagnosticsEmitter, type ClientDiagnosticsListener, type ClientDiagnosticsSnapshot, type RealtimePolicy } from './diagnostics.js';
@@ -311,6 +311,9 @@ export declare class SyncClientHandle implements PromiseMethods<WorkerApi> {
311
311
  commitOutcome(clientCommitId: string): Promise<CommitOutcome | undefined>;
312
312
  commitOutcomes(query?: CommitOutcomeQuery): Promise<readonly CommitOutcome[]>;
313
313
  resolveCommitOutcome(input: ResolveCommitOutcomeInput): Promise<CommitOutcome>;
314
+ commitDelivery(id: string): Promise<CommitDelivery>;
315
+ /** §7.2.2: record a decision as a replacement held for a proven base. */
316
+ replaceCommitOutcome({ clientCommitId, sequence, replacement, }: ReplaceCommitOutcomeInput): Promise<string>;
314
317
  /** §7.4.5: true while a schema-bump reset + first re-bootstrap runs. */
315
318
  pendingCommits(): Promise<OutboxCommit[]>;
316
319
  units(): Promise<UnitRecord[]>;
@@ -450,6 +450,15 @@ export class SyncClientHandle {
450
450
  resolveCommitOutcome(input) {
451
451
  return this.#call('resolveCommitOutcome', [input]);
452
452
  }
453
+ commitDelivery(id) {
454
+ return this.#call('commitDelivery', [id]);
455
+ }
456
+ /** §7.2.2: record a decision as a replacement held for a proven base. */
457
+ replaceCommitOutcome({ clientCommitId, sequence, replacement, }) {
458
+ return this.#call('replaceCommitOutcome', [
459
+ { clientCommitId, sequence, replacement },
460
+ ]);
461
+ }
453
462
  /** §7.4.5: true while a schema-bump reset + first re-bootstrap runs. */
454
463
  pendingCommits() {
455
464
  return this.#call('pendingCommits', []);
@@ -19,7 +19,7 @@ import type { SyncProgress } from './progress.js';
19
19
  */
20
20
  import type { PresenceErrorCode, WakeReason } from '@syncular/core';
21
21
  import type { BlobRef, CachedBlob } from './blob.js';
22
- import type { ConflictRecord, CurrentBaseProof, ClientSnapshotMethods, MutationInput, PresencePeer, QueryReadSpec, QuerySnapshot, SecurityLifecycle, SyncClientConfig, SyncClientLimits, SyncSummary, SyncIdleOptions, SyncIdleResult, WindowState } from './client.js';
22
+ import type { ConflictRecord, CurrentBaseProof, ClientSnapshotMethods, ReplaceCommitOutcomeInput, MutationInput, PresencePeer, QueryReadSpec, QuerySnapshot, SecurityLifecycle, SyncClientConfig, SyncClientLimits, SyncSummary, SyncIdleOptions, SyncIdleResult, WindowState } from './client.js';
23
23
  import type { SqlRow, SqlValue } from './database.js';
24
24
  import type { ClientDiagnosticsSnapshot, RealtimePolicy } from './diagnostics.js';
25
25
  import type { EncryptionKeyringConfig } from './encryption.js';
@@ -166,6 +166,7 @@ export interface WorkerApi extends Omit<ClientSnapshotMethods, 'querySnapshot'>
166
166
  sync(): Promise<SyncSummary>;
167
167
  syncUntilIdle(options?: number | SyncIdleOptions): Promise<SyncIdleResult>;
168
168
  proveCurrentBase(outcome: Pick<CommitOutcome, 'clientCommitId' | 'sequence'>, maxRounds?: number): Promise<CurrentBaseProof>;
169
+ replaceCommitOutcome(input: ReplaceCommitOutcomeInput): string;
169
170
  resetClientId(): string;
170
171
  query(sql: string, params?: readonly SqlValue[]): SqlRow[];
171
172
  authoritySnapshot(): import('./authority.js').AuthoritySnapshot;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@syncular/client",
3
- "version": "0.86.0",
3
+ "version": "0.90.0",
4
4
  "description": "Syncular TypeScript client core — offline-first sync over SQLite (WASM/OPFS, Bun, Node)",
5
5
  "license": "Apache-2.0",
6
6
  "author": "Benjamin Kniffler",
@@ -121,11 +121,11 @@
121
121
  },
122
122
  "dependencies": {
123
123
  "@sqlite.org/sqlite-wasm": "^3.53.0-build1",
124
- "@syncular/core": "0.86.0"
124
+ "@syncular/core": "0.90.0"
125
125
  },
126
126
  "devDependencies": {
127
127
  "@electric-sql/pglite": "^0.5.4",
128
- "@syncular/server": "0.86.0",
128
+ "@syncular/server": "0.90.0",
129
129
  "playwright": "1.63.0",
130
130
  "vite": "8.3.4"
131
131
  }
package/src/blob.ts CHANGED
@@ -8,9 +8,9 @@ export const BLOB_COMMIT_REFS = '_syncular_blob_commit_refs';
8
8
  */
9
9
  import { type BlobRef, parseBlobRef, serializeBlobRef } from '@syncular/core';
10
10
  import type { ClientDatabase } from './database';
11
- import { ClientSyncError } from './errors';
11
+ import { ClientSyncError, localStateCorrupt } from './errors';
12
12
  import type { CompiledClientSchema } from './schema';
13
- import { quoteIdent, tableExists } from './schema';
13
+ import { bytesToHex, quoteIdent, tableExists } from './schema';
14
14
 
15
15
  /**
16
16
  * A blob download result (§5.9.5). The authorized endpoint either serves the
@@ -114,10 +114,7 @@ export async function computeBlobId(bytes: Uint8Array): Promise<string> {
114
114
  'SHA-256',
115
115
  input as Uint8Array<ArrayBuffer>,
116
116
  );
117
- const hex = [...new Uint8Array(digest)]
118
- .map((b) => b.toString(16).padStart(2, '0'))
119
- .join('');
120
- return `sha256:${hex}`;
117
+ return `sha256:${bytesToHex(new Uint8Array(digest))}`;
121
118
  }
122
119
 
123
120
  export function ensureBlobSchema(db: ClientDatabase): void {
@@ -126,16 +123,8 @@ export function ensureBlobSchema(db: ClientDatabase): void {
126
123
  .query('PRAGMA table_info(_syncular_blobs)')
127
124
  .map((row) => row.name)
128
125
  .sort();
129
- const expected = [
130
- 'blob_id',
131
- 'byte_length',
132
- 'bytes',
133
- 'created_at_ms',
134
- 'media_type',
135
- ].sort();
136
126
  if (
137
- columns.length !== expected.length ||
138
- columns.some((column, index) => column !== expected[index])
127
+ columns.join() !== 'blob_id,byte_length,bytes,created_at_ms,media_type'
139
128
  ) {
140
129
  throw new ClientSyncError(
141
130
  'sync.schema_mismatch',
@@ -228,10 +217,7 @@ export function listPendingUploads(
228
217
  typeof row.blob_id !== 'string' ||
229
218
  (row.media_type !== null && typeof row.media_type !== 'string')
230
219
  ) {
231
- throw new ClientSyncError(
232
- 'sync.local_corrupt',
233
- 'Pending blob upload metadata is invalid',
234
- );
220
+ throw localStateCorrupt('Pending blob upload metadata is invalid');
235
221
  }
236
222
  return {
237
223
  blobId: row.blob_id,
@@ -259,7 +245,7 @@ export function clearPendingUpload(db: ClientDatabase, blobId: string): void {
259
245
  /**
260
246
  * All `blob_ref` column names per table.
261
247
  */
262
- export function blobRefColumnsBySchema(
248
+ function blobRefColumnsBySchema(
263
249
  schema: CompiledClientSchema,
264
250
  ): Map<string, string[]> {
265
251
  const out = new Map<string, string[]>();
@@ -273,10 +259,7 @@ export function blobRefColumnsBySchema(
273
259
  }
274
260
 
275
261
  export function schemaHasBlobs(schema: CompiledClientSchema): boolean {
276
- for (const table of schema.tables.values()) {
277
- if (table.columns.some((c) => c.type === 'blob_ref')) return true;
278
- }
279
- return false;
262
+ return blobRefColumnsBySchema(schema).size > 0;
280
263
  }
281
264
 
282
265
  /** The cached bodies no upload, pending commit, or visible row references. */