@rdlabo/ionic-angular-kit 21.5.40 → 21.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -926,8 +926,17 @@ function offlineCommandLookupIdentity(identity) {
926
926
  return { kind: 'natural', naturalKey: identity.naturalKey };
927
927
  }
928
928
 
929
+ /**
930
+ * Internal repository capability used to detect commits made through another
931
+ * native SQLite connection during a local read/derive/write operation.
932
+ *
933
+ * This symbol is intentionally not re-exported from the package entry point.
934
+ */
935
+ const OFFLINE_REPOSITORY_ATOMIC_MUTATION = Symbol('OFFLINE_REPOSITORY_ATOMIC_MUTATION');
936
+
929
937
  /** Current durable storage schema used by both web and native repositories. */
930
938
  const OFFLINE_SCHEMA_VERSION = 2;
939
+ const settledRepositoryOperation = async () => undefined;
931
940
  /** Canonical physical key shared by every repository and replica transaction coordinator. */
932
941
  function canonicalOfflineReplicaRowKey(schema, row) {
933
942
  const partition = schema.scope === 'user' ? 'user' : String(row.scopeId);
@@ -952,6 +961,8 @@ const CURSORS_KEY = 'offline:replica:cursors';
952
961
  const OUTBOX_KEY = 'offline:outbox:commands';
953
962
  const REPLICA_TRANSACTION_KEY = 'offline:replica:transaction';
954
963
  const REPLICA_SCHEMA_MIGRATION_KEY = 'offline:replica:schema-migration';
964
+ // Legacy marker storage is no longer read or written. Keep cleanup support for
965
+ // databases created by released versions that persisted this key.
955
966
  const RECONCILIATION_SCOPES_KEY = 'offline:replica:reconciliation-scopes';
956
967
  const PULL_ATTENTIONS_KEY = 'offline:replica:pull-attentions';
957
968
  function compareOfflineCommands$1(left, right) {
@@ -962,9 +973,9 @@ class IonicOfflineRepository {
962
973
  #storage = inject(KitStorageService);
963
974
  #options = inject(OFFLINE_KIT_OPTIONS);
964
975
  #initialization = null;
965
- #writes = Promise.resolve();
976
+ #writes = settledRepositoryOperation();
966
977
  #activeReaders = 0;
967
- #readersIdle = Promise.resolve();
978
+ #readersIdle = settledRepositoryOperation();
968
979
  #resolveReadersIdle = null;
969
980
  #rowIndexBuild = null;
970
981
  initialize() {
@@ -1015,9 +1026,6 @@ class IonicOfflineRepository {
1015
1026
  async getReplicaCursor(scope) {
1016
1027
  return this.#withCommittedRead(() => this.#readReplicaCursor(scope));
1017
1028
  }
1018
- async getReconciliationScopes(userId) {
1019
- return this.#withCommittedRead(() => this.#readReconciliationScopes(userId));
1020
- }
1021
1029
  async getPullAttentions(userId) {
1022
1030
  return this.#withCommittedRead(() => this.#readPullAttentions(userId));
1023
1031
  }
@@ -1086,10 +1094,6 @@ class IonicOfflineRepository {
1086
1094
  const cursor = cursors[this.#cursorKey(scope)];
1087
1095
  return cursor === undefined ? null : { ...scope, cursor };
1088
1096
  }
1089
- async #readReconciliationScopes(userId) {
1090
- const scopes = await this.#readRecord(RECONCILIATION_SCOPES_KEY);
1091
- return Object.values(scopes).filter((scope) => scope.userId === userId);
1092
- }
1093
1097
  async #readPullAttentions(userId) {
1094
1098
  const attentions = await this.#readRecord(PULL_ATTENTIONS_KEY);
1095
1099
  return Object.values(attentions)
@@ -1124,7 +1128,6 @@ class IonicOfflineRepository {
1124
1128
  },
1125
1129
  getReplicaRowByRemoteIdentity: (scope, sourceKey, identity) => this.#readReplicaRowByRemoteIdentity(scope, sourceKey, identity),
1126
1130
  getReplicaCursor: (scope) => this.#readReplicaCursor(scope),
1127
- getReconciliationScopes: (userId) => this.#readReconciliationScopes(userId),
1128
1131
  getPullAttentions: (userId) => this.#readPullAttentions(userId),
1129
1132
  getCommands: (scope) => this.#readCommands(scope),
1130
1133
  getCommandsForUser: (userId) => this.#readCommandsForUser(userId),
@@ -1137,12 +1140,8 @@ class IonicOfflineRepository {
1137
1140
  await this.#ensureRowPartitionsReady();
1138
1141
  await this.#writes;
1139
1142
  this.#beginReaders();
1140
- try {
1141
- return await operation();
1142
- }
1143
- finally {
1144
- this.#endReaders();
1145
- }
1143
+ const read = async () => operation();
1144
+ return read().finally(() => this.#endReaders());
1146
1145
  }
1147
1146
  #beginReaders() {
1148
1147
  if (this.#activeReaders === 0) {
@@ -1157,7 +1156,7 @@ class IonicOfflineRepository {
1157
1156
  if (this.#activeReaders === 0) {
1158
1157
  this.#resolveReadersIdle?.();
1159
1158
  this.#resolveReadersIdle = null;
1160
- this.#readersIdle = Promise.resolve();
1159
+ this.#readersIdle = settledRepositoryOperation();
1161
1160
  }
1162
1161
  }
1163
1162
  async putCommand(command) {
@@ -1312,7 +1311,7 @@ class IonicOfflineRepository {
1312
1311
  targetVersion,
1313
1312
  targetHash,
1314
1313
  });
1315
- try {
1314
+ const commitMigration = async () => {
1316
1315
  const transformedRows = {};
1317
1316
  for (const row of Object.values(rows)) {
1318
1317
  let current = this.#toWebMigrationRow(row);
@@ -1356,8 +1355,8 @@ class IonicOfflineRepository {
1356
1355
  replicaSchemaHash: targetHash,
1357
1356
  });
1358
1357
  await this.#storage.remove(REPLICA_SCHEMA_MIGRATION_KEY);
1359
- }
1360
- catch (error) {
1358
+ };
1359
+ await commitMigration().catch(async (error) => {
1361
1360
  await this.#recoverReplicaSchemaMigration({
1362
1361
  originalRows,
1363
1362
  fromVersion,
@@ -1366,7 +1365,7 @@ class IonicOfflineRepository {
1366
1365
  targetHash,
1367
1366
  });
1368
1367
  throw error;
1369
- }
1368
+ });
1370
1369
  });
1371
1370
  }
1372
1371
  #toWebMigrationRow(row) {
@@ -1394,11 +1393,10 @@ class IonicOfflineRepository {
1394
1393
  await this.#assertReplicaSchemaLocked();
1395
1394
  for (const row of transaction.putRows ?? [])
1396
1395
  this.#validateReplicaRow(row);
1397
- const [rows, commands, cursors, reconciliationScopes, pullAttentions] = await Promise.all([
1396
+ const [rows, commands, cursors, pullAttentions] = await Promise.all([
1398
1397
  this.#readRecord(ROWS_KEY),
1399
1398
  this.#readRecord(OUTBOX_KEY),
1400
1399
  this.#readRecord(CURSORS_KEY),
1401
- this.#readRecord(RECONCILIATION_SCOPES_KEY),
1402
1400
  this.#readRecord(PULL_ATTENTIONS_KEY),
1403
1401
  ]);
1404
1402
  const identityCheckRows = { ...rows };
@@ -1450,12 +1448,6 @@ class IonicOfflineRepository {
1450
1448
  for (const cursor of transaction.putCursors ?? []) {
1451
1449
  cursors[this.#cursorKey(cursor)] = cursor.cursor;
1452
1450
  }
1453
- for (const scope of transaction.putReconciliationScopes ?? []) {
1454
- reconciliationScopes[this.#cursorKey(scope)] = scope;
1455
- }
1456
- for (const scope of transaction.removeReconciliationScopes ?? []) {
1457
- delete reconciliationScopes[this.#cursorKey(scope)];
1458
- }
1459
1451
  for (const attention of transaction.putPullAttentions ?? []) {
1460
1452
  pullAttentions[this.#cursorKey(attention)] = attention;
1461
1453
  }
@@ -1466,7 +1458,6 @@ class IonicOfflineRepository {
1466
1458
  this.#storage.set(ROWS_KEY, rows),
1467
1459
  this.#storage.set(OUTBOX_KEY, commands),
1468
1460
  this.#storage.set(CURSORS_KEY, cursors),
1469
- this.#storage.set(RECONCILIATION_SCOPES_KEY, reconciliationScopes),
1470
1461
  this.#storage.set(PULL_ATTENTIONS_KEY, pullAttentions),
1471
1462
  ]);
1472
1463
  await this.#writeAffectedRowPartitions(rows, transaction);
@@ -1758,6 +1749,7 @@ function compareUtf8Binary(left, right) {
1758
1749
  return leftBytes.length < rightBytes.length ? -1 : leftBytes.length > rightBytes.length ? 1 : 0;
1759
1750
  }
1760
1751
 
1752
+ const settledMutation = async () => undefined;
1761
1753
  /**
1762
1754
  * Serializes only local replica read/derive/write critical sections. Network
1763
1755
  * transport must stay outside this coordinator so synchronization never holds
@@ -1768,12 +1760,18 @@ function compareUtf8Binary(left, right) {
1768
1760
  * method does not acquire the lane itself.
1769
1761
  */
1770
1762
  class OfflineReplicaMutationCoordinator {
1763
+ #repository = inject(OFFLINE_REPOSITORY, { optional: true });
1771
1764
  #projector = inject(OFFLINE_AGGREGATE_INTENT_PROJECTOR, { optional: true });
1772
1765
  #options = inject(OFFLINE_KIT_OPTIONS, { optional: true });
1773
- #tail = Promise.resolve();
1766
+ #tail = settledMutation();
1774
1767
  /** Enqueues one local replica critical section behind any in-flight mutation. */
1775
1768
  run(operation) {
1776
- const mutation = this.#tail.then(operation);
1769
+ const mutation = this.#tail.then(() => {
1770
+ if (!this.#repository)
1771
+ throw new Error('Offline repository is not configured.');
1772
+ const atomicMutation = this.#repository?.[OFFLINE_REPOSITORY_ATOMIC_MUTATION];
1773
+ return atomicMutation ? atomicMutation.call(this.#repository, operation) : operation(this.#repository);
1774
+ });
1777
1775
  this.#tail = mutation.then(() => undefined, () => undefined);
1778
1776
  return mutation;
1779
1777
  }
@@ -2023,12 +2021,12 @@ class OfflineReplicaPullService {
2023
2021
  requestCursor = page.nextCursor;
2024
2022
  continue;
2025
2023
  }
2026
- const applied = await this.#replicaMutations.run(async () => {
2027
- const currentCursor = (await this.#repository.getReplicaCursor(scope))?.cursor ?? '';
2024
+ const applied = await this.#replicaMutations.run(async (repository) => {
2025
+ const currentCursor = (await repository.getReplicaCursor(scope))?.cursor ?? '';
2028
2026
  if (currentCursor !== persistedCursor)
2029
2027
  return currentCursor;
2030
- const scopeCommands = await this.#repository.getCommands(scope);
2031
- const userCommands = this.#repository.getCommandsForUser ? await this.#repository.getCommandsForUser(scope.userId) : scopeCommands;
2028
+ const scopeCommands = await repository.getCommands(scope);
2029
+ const userCommands = repository.getCommandsForUser ? await repository.getCommandsForUser(scope.userId) : scopeCommands;
2032
2030
  const changes = this.#collapseChanges(page.changes);
2033
2031
  const projection = await this.#projector?.project({
2034
2032
  scope,
@@ -2164,7 +2162,7 @@ class OfflineReplicaPullService {
2164
2162
  .map((commandId) => userCommands.find((command) => command.commandId === commandId) ??
2165
2163
  scopeCommands.find((command) => command.commandId === commandId))
2166
2164
  .filter((command) => command != null);
2167
- await this.#repository.transactReplica({
2165
+ await repository.transactReplica({
2168
2166
  putRows: finalRows.putRows,
2169
2167
  removeRows: finalRows.removeRows,
2170
2168
  putCommands: [...putCommands.values()],
@@ -2859,7 +2857,7 @@ class OfflineSyncService {
2859
2857
  #commands;
2860
2858
  #pullAttentions;
2861
2859
  #knownScopes;
2862
- /** ACKed scopes whose authoritative post-send pull has not completed yet. */
2860
+ /** In-memory scheduling cache for scopes whose authoritative post-send pull has not completed yet. */
2863
2861
  #pendingPullScopes;
2864
2862
  #activeUserId;
2865
2863
  #flushPromise;
@@ -2873,7 +2871,6 @@ class OfflineSyncService {
2873
2871
  #foregroundScopePolicy;
2874
2872
  #initialized;
2875
2873
  #lastCommandCreatedAt;
2876
- #coldReconciliationRequired;
2877
2874
  constructor() {
2878
2875
  this.#network = inject(OfflineNetworkService);
2879
2876
  this.#repository = inject(OFFLINE_REPOSITORY);
@@ -2888,7 +2885,7 @@ class OfflineSyncService {
2888
2885
  this.#commands = signal([], ...(ngDevMode ? [{ debugName: "#commands" }] : /* istanbul ignore next */ []));
2889
2886
  this.#pullAttentions = signal([], ...(ngDevMode ? [{ debugName: "#pullAttentions" }] : /* istanbul ignore next */ []));
2890
2887
  this.#knownScopes = new Map();
2891
- /** ACKed scopes whose authoritative post-send pull has not completed yet. */
2888
+ /** In-memory scheduling cache for scopes whose authoritative post-send pull has not completed yet. */
2892
2889
  this.#pendingPullScopes = new Map();
2893
2890
  this.#activeUserId = null;
2894
2891
  this.#flushPromise = null;
@@ -2902,7 +2899,6 @@ class OfflineSyncService {
2902
2899
  this.#foregroundScopePolicy = null;
2903
2900
  this.#initialized = false;
2904
2901
  this.#lastCommandCreatedAt = 0;
2905
- this.#coldReconciliationRequired = this.#repository.getReconciliationScopes === undefined;
2906
2902
  this.pendingCommands = this.#commands.asReadonly();
2907
2903
  this.pendingCount = computed(() => this.pendingCommands().length, ...(ngDevMode ? [{ debugName: "pendingCount" }] : /* istanbul ignore next */ []));
2908
2904
  this.conflicts = computed(() => this.#commands().filter((command) => command.state === 'conflict'), ...(ngDevMode ? [{ debugName: "conflicts" }] : /* istanbul ignore next */ []));
@@ -2991,7 +2987,7 @@ class OfflineSyncService {
2991
2987
  }
2992
2988
  enqueue(request, options = {}) {
2993
2989
  const generation = this.#generation;
2994
- return this.#serializeReplicaMutation(() => this.#enqueue(request, options, generation));
2990
+ return this.#serializeReplicaMutation((repository) => this.#enqueue(request, options, generation, undefined, repository));
2995
2991
  }
2996
2992
  /**
2997
2993
  * Reads, derives, and commits one Outbox command, then rematerializes its
@@ -2999,12 +2995,12 @@ class OfflineSyncService {
2999
2995
  */
3000
2996
  enqueuePrepared(prepare, options = {}) {
3001
2997
  const generation = this.#generation;
3002
- return this.#serializeReplicaMutation(async () => {
2998
+ return this.#serializeReplicaMutation(async (repository) => {
3003
2999
  await this.initialize();
3004
3000
  if (!this.#isCurrent(generation))
3005
3001
  throw new Error('Offline session changed before prepared enqueue.');
3006
- const prepared = await prepare(this.#repository);
3007
- return this.#enqueue(prepared.request, options, generation);
3002
+ const prepared = await prepare(repository);
3003
+ return this.#enqueue(prepared.request, options, generation, undefined, repository);
3008
3004
  });
3009
3005
  }
3010
3006
  /**
@@ -3017,12 +3013,12 @@ class OfflineSyncService {
3017
3013
  */
3018
3014
  enqueuePreparedBatch(prepare, options = {}) {
3019
3015
  const generation = this.#generation;
3020
- return this.#serializeReplicaMutation(async () => {
3016
+ return this.#serializeReplicaMutation(async (repository) => {
3021
3017
  await this.initialize();
3022
3018
  if (!this.#isCurrent(generation))
3023
3019
  throw new Error('Offline session changed before prepared batch enqueue.');
3024
- const prepared = await prepare(this.#repository);
3025
- return this.#enqueuePreparedBatch(prepared, options, generation);
3020
+ const prepared = await prepare(repository);
3021
+ return this.#enqueuePreparedBatch(prepared, options, generation, repository);
3026
3022
  });
3027
3023
  }
3028
3024
  /**
@@ -3034,7 +3030,7 @@ class OfflineSyncService {
3034
3030
  */
3035
3031
  replacePrepared(commandId, prepare, options = {}) {
3036
3032
  const generation = this.#generation;
3037
- return this.#serializeReplicaMutation(async () => {
3033
+ return this.#serializeReplicaMutation(async (repository) => {
3038
3034
  await this.initialize();
3039
3035
  if (!this.#isCurrent(generation))
3040
3036
  throw new Error('Offline session changed before prepared replacement.');
@@ -3046,8 +3042,8 @@ class OfflineSyncService {
3046
3042
  if (knownCommands.some((command) => command.commandId !== commandId && this.#aggregateKey(command) === this.#aggregateKey(replaced))) {
3047
3043
  throw new Error('Offline replacement requires the command to be the only pending intent for its aggregate.');
3048
3044
  }
3049
- const prepared = await prepare(this.#repository);
3050
- return this.#enqueue(prepared.request, options, generation, replaced);
3045
+ const prepared = await prepare(repository);
3046
+ return this.#enqueue(prepared.request, options, generation, replaced, repository);
3051
3047
  });
3052
3048
  }
3053
3049
  /**
@@ -3059,7 +3055,7 @@ class OfflineSyncService {
3059
3055
  */
3060
3056
  replacePreparedAggregate(commandId, prepare, options = {}) {
3061
3057
  const generation = this.#generation;
3062
- return this.#serializeReplicaMutation(async () => {
3058
+ return this.#serializeReplicaMutation(async (repository) => {
3063
3059
  await this.initialize();
3064
3060
  if (!this.#isCurrent(generation))
3065
3061
  throw new Error('Offline session changed before prepared aggregate replacement.');
@@ -3070,7 +3066,7 @@ class OfflineSyncService {
3070
3066
  const aggregateKey = this.#aggregateKey(selected);
3071
3067
  const replaced = knownCommands.filter((command) => this.#aggregateKey(command) === aggregateKey);
3072
3068
  this.#assertDiscardable(replaced);
3073
- const prepared = await prepare(this.#repository, replaced);
3069
+ const prepared = await prepare(repository, replaced);
3074
3070
  if (prepared.length !== replaced.length) {
3075
3071
  throw new Error('Offline aggregate replacement must preserve the ordered intent count.');
3076
3072
  }
@@ -3084,7 +3080,7 @@ class OfflineSyncService {
3084
3080
  this.#assertDistinctBatchFootprints(materializations, retained, true);
3085
3081
  await this.#assertOutboxCapacity(session.userId, materializations.map((item) => item.command), replaced.map((command) => command.commandId), knownCommands);
3086
3082
  options.assertCurrent?.();
3087
- await this.#commitMaterializedEnqueues(materializations, generation, options, replaced.map((command) => command.commandId));
3083
+ await this.#commitMaterializedEnqueues(materializations, generation, options, replaced.map((command) => command.commandId), repository);
3088
3084
  return materializations.map((item) => item.command.commandId);
3089
3085
  });
3090
3086
  }
@@ -3105,11 +3101,11 @@ class OfflineSyncService {
3105
3101
  */
3106
3102
  runSerializedReplicaMutation(operation) {
3107
3103
  const generation = this.#generation;
3108
- return this.#serializeReplicaMutation(async () => {
3104
+ return this.#serializeReplicaMutation(async (repository) => {
3109
3105
  await this.initialize();
3110
3106
  if (!this.#isCurrent(generation))
3111
3107
  throw new Error('Offline session changed before serialized replica mutation.');
3112
- const result = await operation(this.#repository);
3108
+ const result = await operation(repository);
3113
3109
  if (this.#isCurrent(generation))
3114
3110
  await this.#refreshState(generation);
3115
3111
  return result;
@@ -3118,7 +3114,7 @@ class OfflineSyncService {
3118
3114
  #serializeReplicaMutation(operation) {
3119
3115
  return this.#replicaMutations.run(operation);
3120
3116
  }
3121
- async #enqueue(request, options, generation, replaced) {
3117
+ async #enqueue(request, options, generation, replaced, repository = this.#repository) {
3122
3118
  const session = await this.#beginEnqueueSession(generation);
3123
3119
  this.#assertEnqueueScope(session, request.scopeId);
3124
3120
  const materialization = await this.#materializeEnqueue(session.userId, request, replaced);
@@ -3126,10 +3122,10 @@ class OfflineSyncService {
3126
3122
  const retainedCommands = replaced ? currentCommands.filter((command) => command.commandId !== replaced.commandId) : currentCommands;
3127
3123
  this.#assertDistinctBatchFootprints([materialization], retainedCommands);
3128
3124
  await this.#assertOutboxCapacity(session.userId, [materialization.command], replaced ? [replaced.commandId] : undefined, currentCommands);
3129
- await this.#commitMaterializedEnqueues([materialization], generation, options, replaced ? [replaced.commandId] : undefined);
3125
+ await this.#commitMaterializedEnqueues([materialization], generation, options, replaced ? [replaced.commandId] : undefined, repository);
3130
3126
  return materialization.command.commandId;
3131
3127
  }
3132
- async #enqueuePreparedBatch(prepared, options, generation) {
3128
+ async #enqueuePreparedBatch(prepared, options, generation, repository) {
3133
3129
  if (prepared.length === 0) {
3134
3130
  throw new Error('Prepared offline batch must contain at least one command.');
3135
3131
  }
@@ -3146,7 +3142,7 @@ class OfflineSyncService {
3146
3142
  this.#assertDistinctBatchFootprints(materializations, currentCommands);
3147
3143
  await this.#assertOutboxCapacity(session.userId, materializations.map((item) => item.command), undefined, currentCommands);
3148
3144
  options.assertCurrent?.();
3149
- await this.#commitMaterializedEnqueues(materializations, generation, options);
3145
+ await this.#commitMaterializedEnqueues(materializations, generation, options, undefined, repository);
3150
3146
  return materializations.map((item) => item.command.commandId);
3151
3147
  }
3152
3148
  async #beginEnqueueSession(generation) {
@@ -3321,7 +3317,7 @@ class OfflineSyncService {
3321
3317
  : { kind: 'natural', naturalKey: command.identity.naturalKey };
3322
3318
  return [this.#replicaRowKey({ ...command, identity }), ...commandFootprintKeys(command).map((key) => this.#replicaRowKey(key))];
3323
3319
  }
3324
- async #commitMaterializedEnqueues(entries, generation, options, removeCommandIds) {
3320
+ async #commitMaterializedEnqueues(entries, generation, options, removeCommandIds, repository = this.#repository) {
3325
3321
  if (generation !== this.#generation) {
3326
3322
  throw new Error('Offline session changed before the command could be persisted');
3327
3323
  }
@@ -3338,7 +3334,7 @@ class OfflineSyncService {
3338
3334
  seeds.set(this.#aggregateKey(entry.command), entry.seedBaseRow);
3339
3335
  }
3340
3336
  const rematerialized = await this.#rematerializeAffectedAggregates(affected, remaining, seeds);
3341
- await this.#repository.transactReplica({
3337
+ await repository.transactReplica({
3342
3338
  putRows: rematerialized.putRows,
3343
3339
  removeRows: rematerialized.removeRows,
3344
3340
  putCommands: entries.map((entry) => entry.command),
@@ -3420,13 +3416,13 @@ class OfflineSyncService {
3420
3416
  // and project the discard inside the same local mutation lane used by
3421
3417
  // enqueue, ACK, and pull application so an old before-image cannot replace
3422
3418
  // a newer authoritative row after its cursor has advanced.
3423
- const command = await this.#replicaMutations.run(async () => {
3419
+ const command = await this.#replicaMutations.run(async (repository) => {
3424
3420
  const current = (await this.#readKnownCommands()).find((item) => item.commandId === commandId);
3425
3421
  if (!current)
3426
3422
  return null;
3427
3423
  this.#assertDiscardable([current]);
3428
3424
  this.#invalidateFlush();
3429
- await this.#discardCommands([current]);
3425
+ await this.#discardCommands([current], repository);
3430
3426
  return current;
3431
3427
  });
3432
3428
  if (!command)
@@ -3466,11 +3462,11 @@ class OfflineSyncService {
3466
3462
  }
3467
3463
  async discardAllPending() {
3468
3464
  await this.initialize();
3469
- const commands = await this.#replicaMutations.run(async () => {
3465
+ const commands = await this.#replicaMutations.run(async (repository) => {
3470
3466
  const current = await this.#readKnownCommands();
3471
3467
  this.#assertDiscardable(current);
3472
3468
  this.#invalidateFlush();
3473
- await this.#discardCommands(current);
3469
+ await this.#discardCommands(current, repository);
3474
3470
  return current;
3475
3471
  });
3476
3472
  await this.#refreshState();
@@ -3483,13 +3479,13 @@ class OfflineSyncService {
3483
3479
  }
3484
3480
  }
3485
3481
  #flushInBackground() {
3486
- void this.#beginFlush(false).catch((error) => this.#errorHandler.handleError(error));
3482
+ void this.#beginFlush(false).catch((error) => this.#reportError(error));
3487
3483
  }
3488
3484
  flush() {
3489
3485
  return this.#beginFlush(true);
3490
3486
  }
3491
3487
  #beginFlush(explicitFull) {
3492
- const isPartial = !explicitFull && !this.#coldReconciliationRequired && this.#foregroundScopePolicy !== null;
3488
+ const isPartial = !explicitFull && this.#foregroundScopePolicy !== null;
3493
3489
  if (this.#flushPromise) {
3494
3490
  if (explicitFull && this.#partialFlushInFlight) {
3495
3491
  if (!this.#chainedFullFlush) {
@@ -3544,17 +3540,18 @@ class OfflineSyncService {
3544
3540
  for (const scope of pullScopes) {
3545
3541
  if (!this.#isCurrent(generation) || !this.#network.connected())
3546
3542
  return;
3547
- try {
3543
+ const pullScope = async () => {
3548
3544
  await this.#pull.pull(scope);
3549
3545
  await this.#markScopeReconciled(scope, generation);
3550
3546
  pulledScopeKeys.add(this.#scopeKey(scope));
3551
- }
3552
- catch (error) {
3553
- prePullFailures.push(error);
3554
- if (this.#isFatalPullFailure(error)) {
3547
+ };
3548
+ const pull = await pullScope().then(() => ({ status: 'fulfilled' }), (error) => ({ status: 'rejected', error }));
3549
+ if (pull.status === 'rejected') {
3550
+ prePullFailures.push(pull.error);
3551
+ if (this.#isFatalPullFailure(pull.error)) {
3555
3552
  // Auth/upgrade-driven recovery only: stop remaining scopes immediately.
3556
- fatalPullFailure = fatalPullFailure ?? error;
3557
- await this.#persistFatalPullAttentions(error, scope, pullScopes, generation);
3553
+ fatalPullFailure = fatalPullFailure ?? pull.error;
3554
+ await this.#persistFatalPullAttentions(pull.error, scope, pullScopes, generation);
3558
3555
  break;
3559
3556
  }
3560
3557
  if (this.#pendingPullScopes.has(this.#scopeKey(scope))) {
@@ -3604,27 +3601,27 @@ class OfflineSyncService {
3604
3601
  for (const scope of postPullScopes) {
3605
3602
  if (!this.#isCurrent(generation) || !this.#network.connected())
3606
3603
  break;
3607
- try {
3608
- // A command response may contain only the aggregate's base row. Pull
3609
- // once per dirty scope so sibling-table journal entries are visible
3610
- // before the completed Outbox state is exposed to product UI.
3604
+ // A command response may contain only the aggregate's base row. Pull once per dirty scope so
3605
+ // sibling-table journal entries are visible before completed Outbox state reaches product UI.
3606
+ const pullScope = async () => {
3611
3607
  await this.#pull.pull(scope);
3612
3608
  await this.#markScopeReconciled(scope, generation);
3613
- }
3614
- catch (error) {
3615
- if (this.#isFatalPullFailure(error)) {
3616
- fatalPullFailure = fatalPullFailure ?? error;
3617
- await this.#persistFatalPullAttentions(error, scope, postPullScopes, generation);
3609
+ };
3610
+ const pull = await pullScope().then(() => ({ status: 'fulfilled' }), (error) => ({ status: 'rejected', error }));
3611
+ if (pull.status === 'rejected') {
3612
+ if (this.#isFatalPullFailure(pull.error)) {
3613
+ fatalPullFailure = fatalPullFailure ?? pull.error;
3614
+ await this.#persistFatalPullAttentions(pull.error, scope, postPullScopes, generation);
3618
3615
  break;
3619
3616
  }
3620
- postPullFailures.push(error);
3617
+ postPullFailures.push(pull.error);
3621
3618
  }
3622
3619
  }
3623
3620
  }
3624
3621
  await this.#refreshState(generation);
3625
3622
  if (fatalPullFailure !== null) {
3626
3623
  // Auth/upgrade recovery only — never arm the 1s automatic flush retry.
3627
- // Post-send ACK already removed the command; reconciliation markers remain for later recovery.
3624
+ // Transported commands remain awaiting_pull for later auth/upgrade recovery.
3628
3625
  // Only the owning generation may clear the timer — a stale fatal must not disarm a
3629
3626
  // newer session's already-armed retry_wait / post-pull retry.
3630
3627
  if (this.#isCurrent(generation))
@@ -3640,8 +3637,6 @@ class OfflineSyncService {
3640
3637
  }
3641
3638
  throw failures[0];
3642
3639
  }
3643
- if (this.#isCurrent(generation))
3644
- this.#coldReconciliationRequired = false;
3645
3640
  if (this.#isCurrent(generation)) {
3646
3641
  for (const command of await this.#readKnownCommands()) {
3647
3642
  if (command.state !== 'awaiting_pull')
@@ -3747,16 +3742,16 @@ class OfflineSyncService {
3747
3742
  await this.#refreshState(generation);
3748
3743
  if (!this.#isCurrent(generation))
3749
3744
  return;
3750
- let row;
3751
- try {
3752
- row = await this.#rowForCommand(sending);
3753
- }
3754
- catch (error) {
3745
+ const claimedCommand = sending;
3746
+ const readRow = async () => this.#rowForCommand(claimedCommand);
3747
+ const rowResult = await readRow().then((row) => ({ status: 'fulfilled', row }), (error) => ({ status: 'rejected', error }));
3748
+ if (rowResult.status === 'rejected') {
3755
3749
  if (!this.#isCurrent(generation))
3756
3750
  return;
3757
- await this.#persistFailedCommand(sending, error, generation, null, sending.serverCommitUnknown === true);
3758
- throw error;
3751
+ await this.#persistFailedCommand(sending, rowResult.error, generation, null, sending.serverCommitUnknown === true);
3752
+ throw rowResult.error;
3759
3753
  }
3754
+ const row = rowResult.row;
3760
3755
  if (!row) {
3761
3756
  const error = new Error(`Offline replica row not found: ${sending.aggregateType}/${canonicalOfflineCommandIdentity(sending.identity)}`);
3762
3757
  await this.#persistFailedCommand(sending, error, generation, null, sending.serverCommitUnknown === true);
@@ -3767,31 +3762,29 @@ class OfflineSyncService {
3767
3762
  if (!transportCommand)
3768
3763
  return;
3769
3764
  sending = transportCommand;
3770
- let result;
3771
- try {
3772
- result = await this.#executor.execute(sending, offlineCommandTargetFromReplicaRow(row));
3773
- }
3774
- catch (error) {
3765
+ const executeCommand = async () => this.#executor.execute(sending, offlineCommandTargetFromReplicaRow(row));
3766
+ const execution = await executeCommand().then((result) => ({ status: 'fulfilled', result }), (error) => ({ status: 'rejected', error }));
3767
+ if (execution.status === 'rejected') {
3775
3768
  if (!this.#isCurrent(generation))
3776
3769
  return;
3777
- const commitUnknown = this.#executor.provesCommandNotCommitted?.(error, sending)
3770
+ const commitUnknown = this.#executor.provesCommandNotCommitted?.(execution.error, sending)
3778
3771
  ? false
3779
- : priorCommitUnknown || this.#serverCommitCouldBeUnknown(error);
3780
- await this.#persistFailedCommand(sending, error, generation, row, commitUnknown);
3781
- if (!this.#isClassifiableTransportError(error))
3782
- throw error;
3772
+ : priorCommitUnknown || this.#serverCommitCouldBeUnknown(execution.error);
3773
+ await this.#persistFailedCommand(sending, execution.error, generation, row, commitUnknown);
3774
+ if (!this.#isClassifiableTransportError(execution.error))
3775
+ throw execution.error;
3783
3776
  break;
3784
3777
  }
3778
+ const result = execution.result;
3785
3779
  if (!this.#isCurrent(generation))
3786
3780
  return;
3787
- try {
3788
- await this.#completeCommand(commands, sending, result, generation);
3789
- }
3790
- catch (error) {
3781
+ const completeCommand = async () => this.#completeCommand(commands, sending, result, generation);
3782
+ const completion = await completeCommand().then(() => ({ status: 'fulfilled' }), (error) => ({ status: 'rejected', error }));
3783
+ if (completion.status === 'rejected') {
3791
3784
  if (!this.#isCurrent(generation))
3792
3785
  return;
3793
- await this.#persistFailedCommand(sending, error, generation, row, true);
3794
- throw error;
3786
+ await this.#persistFailedCommand(sending, completion.error, generation, row, true);
3787
+ throw completion.error;
3795
3788
  }
3796
3789
  if (this.#isCurrent(generation)) {
3797
3790
  const scope = { userId: sending.userId, scopeId: sending.scopeId };
@@ -3809,9 +3802,9 @@ class OfflineSyncService {
3809
3802
  return { payload: request.payload, baseRevision };
3810
3803
  }
3811
3804
  async #completeCommand(commands, command, result, generation) {
3812
- return this.#serializeReplicaMutation(() => this.#completeCommandLocked(commands, command, result, generation));
3805
+ return this.#serializeReplicaMutation((repository) => this.#completeCommandLocked(commands, command, result, generation, repository));
3813
3806
  }
3814
- async #completeCommandLocked(commands, command, result, generation) {
3807
+ async #completeCommandLocked(commands, command, result, generation, repository) {
3815
3808
  if (result.clearRemoteId === true && result.remoteId !== undefined) {
3816
3809
  throw new Error('Offline command cannot return remoteId and clearRemoteId together.');
3817
3810
  }
@@ -3873,7 +3866,7 @@ class OfflineSyncService {
3873
3866
  const rematerialized = await this.#rematerializeAggregate(awaitingPull, latestCommands, identityUpdatedBase);
3874
3867
  if (!this.#isCurrent(generation))
3875
3868
  return;
3876
- await this.#repository.transactReplica({
3869
+ await repository.transactReplica({
3877
3870
  putRows: rematerialized.putRows,
3878
3871
  releaseRemoteIds: result.clearRemoteId === true && current.identity.kind === 'generated' && current.identity.remoteId !== null
3879
3872
  ? [
@@ -3888,7 +3881,6 @@ class OfflineSyncService {
3888
3881
  : undefined,
3889
3882
  removeRows: rematerialized.removeRows,
3890
3883
  putCommands: [awaitingPull, ...rebased],
3891
- putReconciliationScopes: [{ userId: command.userId, scopeId: command.scopeId }],
3892
3884
  });
3893
3885
  const scope = { userId: command.userId, scopeId: command.scopeId };
3894
3886
  this.#pendingPullScopes.set(this.#scopeKey(scope), scope);
@@ -3917,7 +3909,7 @@ class OfflineSyncService {
3917
3909
  throw new Error(`Unknown offline replica source key "${sourceKey}".`);
3918
3910
  return schema;
3919
3911
  }
3920
- async #discardCommands(discarded) {
3912
+ async #discardCommands(discarded, repository) {
3921
3913
  const all = await this.#readKnownCommands();
3922
3914
  const discardedIds = new Set(discarded.map((command) => command.commandId));
3923
3915
  const affected = new Map();
@@ -3925,7 +3917,7 @@ class OfflineSyncService {
3925
3917
  affected.set(this.#aggregateKey(command), command);
3926
3918
  const remaining = all.filter((item) => !discardedIds.has(item.commandId));
3927
3919
  const rematerialized = await this.#rematerializeAffectedAggregates(affected, remaining);
3928
- await this.#repository.transactReplica({
3920
+ await repository.transactReplica({
3929
3921
  putRows: rematerialized.putRows,
3930
3922
  removeRows: rematerialized.removeRows,
3931
3923
  removeCommandIds: [...discardedIds],
@@ -4001,18 +3993,20 @@ class OfflineSyncService {
4001
3993
  }
4002
3994
  async #persistFailedCommand(command, error, generation, row, serverCommitUnknown = true) {
4003
3995
  const failed = this.#failedCommand(command, error, serverCommitUnknown);
4004
- const current = row === undefined ? await this.#rowForCommand(command) : row;
4005
- if (!this.#isCurrent(generation))
4006
- return;
4007
- if (current) {
4008
- await this.#repository.transactReplica({
4009
- putRows: [{ ...current, syncState: this.#replicaState(failed.state) }],
4010
- putCommands: [failed],
4011
- });
4012
- }
4013
- else {
4014
- await this.#repository.putCommand(failed);
4015
- }
3996
+ await this.#serializeReplicaMutation(async (repository) => {
3997
+ const current = row === undefined ? await this.#rowForCommand(command) : row;
3998
+ if (!this.#isCurrent(generation))
3999
+ return;
4000
+ if (current) {
4001
+ await repository.transactReplica({
4002
+ putRows: [{ ...current, syncState: this.#replicaState(failed.state) }],
4003
+ putCommands: [failed],
4004
+ });
4005
+ }
4006
+ else {
4007
+ await repository.putCommand(failed);
4008
+ }
4009
+ });
4016
4010
  if (!this.#isCurrent(generation))
4017
4011
  return;
4018
4012
  if (failed.state === 'retry_wait')
@@ -4036,9 +4030,19 @@ class OfflineSyncService {
4036
4030
  return status === 0 || status === 429 || status >= 500;
4037
4031
  }
4038
4032
  #reportError(error) {
4039
- void Promise.resolve()
4040
- .then(() => this.#errorHandler.handleError(error))
4041
- .catch(() => undefined);
4033
+ queueMicrotask(() => this.#dispatchError(error));
4034
+ }
4035
+ #dispatchError(error) {
4036
+ let result;
4037
+ try {
4038
+ result = this.#errorHandler.handleError(error);
4039
+ }
4040
+ catch {
4041
+ return;
4042
+ }
4043
+ if (result instanceof Promise) {
4044
+ void result.catch(() => undefined);
4045
+ }
4042
4046
  }
4043
4047
  #assertServerRevision(revision) {
4044
4048
  if (typeof revision === 'number' && !Number.isFinite(revision)) {
@@ -4212,7 +4216,7 @@ class OfflineSyncService {
4212
4216
  })));
4213
4217
  }
4214
4218
  #claimSendingCommand(command, generation) {
4215
- const transition = this.#serializeReplicaMutation(async () => {
4219
+ const transition = this.#serializeReplicaMutation(async (repository) => {
4216
4220
  if (!this.#isCurrent(generation))
4217
4221
  return null;
4218
4222
  const scope = { userId: command.userId, scopeId: command.scopeId };
@@ -4226,7 +4230,7 @@ class OfflineSyncService {
4226
4230
  retryAt: null,
4227
4231
  lastErrorCode: null,
4228
4232
  };
4229
- await this.#repository.putCommand(sending);
4233
+ await repository.putCommand(sending);
4230
4234
  return sending;
4231
4235
  });
4232
4236
  this.#sendingTransitions.add(transition);
@@ -4234,7 +4238,7 @@ class OfflineSyncService {
4234
4238
  return transition;
4235
4239
  }
4236
4240
  #markTransportStarted(command, generation) {
4237
- return this.#serializeReplicaMutation(async () => {
4241
+ return this.#serializeReplicaMutation(async (repository) => {
4238
4242
  if (!this.#isCurrent(generation))
4239
4243
  return null;
4240
4244
  const scope = { userId: command.userId, scopeId: command.scopeId };
@@ -4242,28 +4246,21 @@ class OfflineSyncService {
4242
4246
  if (!current || current.state !== 'sending')
4243
4247
  return null;
4244
4248
  const transportCommand = { ...current, serverCommitUnknown: true };
4245
- await this.#repository.putCommand(transportCommand);
4249
+ await repository.putCommand(transportCommand);
4246
4250
  return transportCommand;
4247
4251
  });
4248
4252
  }
4249
4253
  async #restorePendingPullScopes(userId, generation) {
4250
- if (!this.#repository.getReconciliationScopes)
4251
- return;
4252
- const durableScopes = await this.#repository.getReconciliationScopes(userId);
4254
+ const commands = await this.#readKnownCommands();
4253
4255
  if (!this.#isCurrent(generation) || this.#activeUserId !== userId)
4254
4256
  return;
4255
- const currentKeys = new Set(this.#knownScopes.keys());
4256
4257
  this.#pendingPullScopes.clear();
4257
- const revoked = [];
4258
- for (const scope of durableScopes) {
4258
+ for (const command of commands) {
4259
+ if (command.state !== 'awaiting_pull')
4260
+ continue;
4261
+ const scope = { userId: command.userId, scopeId: command.scopeId };
4259
4262
  const key = this.#scopeKey(scope);
4260
- if (scope.userId === userId && currentKeys.has(key))
4261
- this.#pendingPullScopes.set(key, scope);
4262
- else
4263
- revoked.push(scope);
4264
- }
4265
- if (revoked.length > 0) {
4266
- await this.#repository.transactReplica({ removeReconciliationScopes: revoked });
4263
+ this.#pendingPullScopes.set(key, scope);
4267
4264
  }
4268
4265
  }
4269
4266
  async #prunePullAttentions(userId, generation) {
@@ -4282,7 +4279,6 @@ class OfflineSyncService {
4282
4279
  if (!this.#isCurrent(generation))
4283
4280
  return;
4284
4281
  await this.#repository.transactReplica({
4285
- removeReconciliationScopes: [scope],
4286
4282
  removePullAttentions: [scope],
4287
4283
  });
4288
4284
  if (!this.#isCurrent(generation))
@@ -4327,6 +4323,7 @@ function compareOfflineCommands(left, right) {
4327
4323
  return left.createdAt - right.createdAt || (left.commandId < right.commandId ? -1 : left.commandId > right.commandId ? 1 : 0);
4328
4324
  }
4329
4325
 
4326
+ const settledTransition = async () => undefined;
4330
4327
  /** Coordinates local persistence, session boundaries, network state, and outbox synchronization. */
4331
4328
  class OfflineCoordinatorService {
4332
4329
  constructor() {
@@ -4337,7 +4334,7 @@ class OfflineCoordinatorService {
4337
4334
  this.#options = inject(OFFLINE_KIT_OPTIONS);
4338
4335
  this.#storageState = signal({ status: 'initializing' }, ...(ngDevMode ? [{ debugName: "#storageState" }] : /* istanbul ignore next */ []));
4339
4336
  this.#transitionRevision = 0;
4340
- this.#transitionTail = Promise.resolve();
4337
+ this.#transitionTail = settledTransition();
4341
4338
  /**
4342
4339
  * Local storage readiness after {@link initialize}.
4343
4340
  *
@@ -4372,10 +4369,8 @@ class OfflineCoordinatorService {
4372
4369
  */
4373
4370
  async initialize() {
4374
4371
  const networkReady = this.#network.initialize();
4375
- try {
4376
- await this.#repository.initialize();
4377
- }
4378
- catch (error) {
4372
+ const initializeRepository = async () => this.#repository.initialize();
4373
+ const repositoryReady = await initializeRepository().then(() => true, async (error) => {
4379
4374
  await networkReady;
4380
4375
  const typed = this.#asStorageUnavailable(error);
4381
4376
  this.#storageState.set({ status: 'unavailable', error: typed });
@@ -4383,8 +4378,10 @@ class OfflineCoordinatorService {
4383
4378
  if (!onUnavailable)
4384
4379
  throw typed;
4385
4380
  await onUnavailable(typed);
4381
+ return false;
4382
+ });
4383
+ if (!repositoryReady)
4386
4384
  return;
4387
- }
4388
4385
  await networkReady;
4389
4386
  this.#storageState.set({ status: 'ready' });
4390
4387
  await this.#session.initialize();
@@ -4396,9 +4393,9 @@ class OfflineCoordinatorService {
4396
4393
  await this.resumeRemoteSession();
4397
4394
  }
4398
4395
  /** Installs a remotely verified identity without starting pull or outbox replay. */
4399
- prepareRemoteSession(userId, scopeIds, authSubject, authLease) {
4396
+ async prepareRemoteSession(userId, scopeIds, authSubject, authLease) {
4400
4397
  if (this.#storageUnavailable())
4401
- return Promise.resolve(true);
4398
+ return true;
4402
4399
  const revision = ++this.#transitionRevision;
4403
4400
  const lease = this.#lease(revision, authLease);
4404
4401
  return this.#enqueueTransition(async () => {
@@ -4418,9 +4415,9 @@ class OfflineCoordinatorService {
4418
4415
  /**
4419
4416
  * Activates a restored identity for local replica/outbox use without enabling transport sync.
4420
4417
  */
4421
- activateOfflineSession(authSubject, authLease) {
4418
+ async activateOfflineSession(authSubject, authLease) {
4422
4419
  if (this.#storageUnavailable())
4423
- return Promise.resolve(null);
4420
+ return null;
4424
4421
  const revision = ++this.#transitionRevision;
4425
4422
  const lease = this.#lease(revision, authLease);
4426
4423
  return this.#enqueueTransition(async () => {
@@ -4433,9 +4430,9 @@ class OfflineCoordinatorService {
4433
4430
  return lease.isCurrent() ? manifest : null;
4434
4431
  });
4435
4432
  }
4436
- clearActiveSession() {
4433
+ async clearActiveSession() {
4437
4434
  if (this.#storageUnavailable())
4438
- return Promise.resolve();
4435
+ return;
4439
4436
  this.#sync.revokeSession();
4440
4437
  this.#session.revokeAccess();
4441
4438
  ++this.#transitionRevision;
@@ -4456,9 +4453,9 @@ class OfflineCoordinatorService {
4456
4453
  await this.#sync.flush();
4457
4454
  return this.#sync.pendingCount() === 0;
4458
4455
  }
4459
- flush() {
4456
+ async flush() {
4460
4457
  if (this.#storageUnavailable())
4461
- return Promise.resolve();
4458
+ return;
4462
4459
  return this.#sync.flush();
4463
4460
  }
4464
4461
  #asStorageUnavailable(error) {
@@ -4753,10 +4750,11 @@ const COMMUNITY_SQLITE = new InjectionToken('COMMUNITY_SQLITE', {
4753
4750
  * The returned lower-case hexadecimal value is suitable for
4754
4751
  * `OfflineKitOptions.createEncryptionKey` and contains no device or user identifiers.
4755
4752
  */
4756
- function createRandomOfflineEncryptionKey() {
4753
+ async function createRandomOfflineEncryptionKey() {
4757
4754
  const bytes = crypto.getRandomValues(new Uint8Array(32));
4758
- return Promise.resolve(Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join(''));
4755
+ return Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('');
4759
4756
  }
4757
+ const settledSqliteOperation = async () => undefined;
4760
4758
  /** Create the standard encrypted `@capacitor-community/sqlite` driver. */
4761
4759
  function createCommunitySqliteDriver(connection) {
4762
4760
  const databases = new Map();
@@ -4861,10 +4859,16 @@ class SqliteOfflineRepository {
4861
4859
  #options = inject(OFFLINE_KIT_OPTIONS);
4862
4860
  #databaseId = null;
4863
4861
  #initialization = null;
4864
- #writes = Promise.resolve();
4862
+ #writes = settledSqliteOperation();
4865
4863
  #activeReaders = 0;
4866
- #readersIdle = Promise.resolve();
4864
+ #readersIdle = settledSqliteOperation();
4867
4865
  #resolveReadersIdle = null;
4866
+ #atomicMutationRevision = null;
4867
+ #atomicMutationCommitted = false;
4868
+ #atomicOperations = settledSqliteOperation();
4869
+ #readSnapshotActive = false;
4870
+ #atomicIdle = settledSqliteOperation();
4871
+ #resolveAtomicIdle = null;
4868
4872
  initialize() {
4869
4873
  this.#initialization ??= this.#open();
4870
4874
  return this.#initialization;
@@ -4909,9 +4913,6 @@ class SqliteOfflineRepository {
4909
4913
  async getReplicaCursor(scope) {
4910
4914
  return this.#withCommittedRead(() => this.#readReplicaCursor(scope));
4911
4915
  }
4912
- async getReconciliationScopes(userId) {
4913
- return this.#withCommittedRead(() => this.#readReconciliationScopes(userId));
4914
- }
4915
4916
  async getPullAttentions(userId) {
4916
4917
  return this.#withCommittedRead(() => this.#readPullAttentions(userId));
4917
4918
  }
@@ -4922,7 +4923,44 @@ class SqliteOfflineRepository {
4922
4923
  return this.#withCommittedRead(() => this.#readCommandsForUser(userId));
4923
4924
  }
4924
4925
  async runReadSnapshot(read) {
4925
- return this.#withCommittedRead(() => read(this.#reader()));
4926
+ if (this.#atomicMutationRevision !== null) {
4927
+ throw new Error('Use the repository passed to an atomic mutation for snapshot reads.');
4928
+ }
4929
+ return this.#transaction(async () => {
4930
+ this.#readSnapshotActive = true;
4931
+ const executeRead = async () => read(this.#reader());
4932
+ return executeRead().finally(() => (this.#readSnapshotActive = false));
4933
+ });
4934
+ }
4935
+ async [OFFLINE_REPOSITORY_ATOMIC_MUTATION](operation) {
4936
+ await this.initialize();
4937
+ await this.#writes;
4938
+ if (this.#atomicMutationRevision !== null) {
4939
+ throw new Error('Nested offline replica atomic mutations are not supported.');
4940
+ }
4941
+ this.#beginReaders();
4942
+ const executeAtomicMutation = async () => {
4943
+ const databaseId = await this.#databaseConnection();
4944
+ this.#atomicOperations = settledSqliteOperation();
4945
+ this.#atomicMutationCommitted = false;
4946
+ this.#atomicIdle = new Promise((resolve) => {
4947
+ this.#resolveAtomicIdle = resolve;
4948
+ });
4949
+ this.#atomicMutationRevision = await this.#nativeTransaction(databaseId, () => this.#dataVersion(databaseId));
4950
+ const result = await operation(this.#atomicRepository());
4951
+ await this.#atomicOperations;
4952
+ if (!this.#atomicMutationCommitted) {
4953
+ await this.#queueAtomicOperation(() => this.#atomicTransaction(databaseId, async () => undefined, false));
4954
+ }
4955
+ return result;
4956
+ };
4957
+ return executeAtomicMutation().finally(() => {
4958
+ this.#atomicMutationRevision = null;
4959
+ this.#endReaders();
4960
+ this.#resolveAtomicIdle?.();
4961
+ this.#resolveAtomicIdle = null;
4962
+ this.#atomicIdle = settledSqliteOperation();
4963
+ });
4926
4964
  }
4927
4965
  async putCommand(command) {
4928
4966
  await this.#queueWrite((databaseId) => this.#putCommand(databaseId, command));
@@ -4949,129 +4987,123 @@ class SqliteOfflineRepository {
4949
4987
  ]);
4950
4988
  }
4951
4989
  async clearUser(userId) {
4952
- await this.#transaction(async (database) => {
4953
- const principal = canonicalOfflinePrincipalId(userId);
4954
- await this.#execute(database, 'DELETE FROM offline_session_manifests WHERE user_id = ?', [principal]);
4955
- await this.#execute(database, 'DELETE FROM offline_sync_commands WHERE user_id = ?', [principal]);
4956
- await this.#execute(database, 'DELETE FROM offline_replica_cursors WHERE user_id = ?', [principal]);
4957
- await this.#execute(database, 'DELETE FROM offline_reconciliation_scopes WHERE user_id = ?', [principal]);
4958
- await this.#execute(database, 'DELETE FROM offline_pull_attentions WHERE user_id = ?', [principal]);
4959
- for (const entity of this.#options.replicaSchema.entities) {
4960
- await this.#execute(database, `DELETE FROM ${entity.tableName} WHERE _offline_user_id = ?`, [principal]);
4961
- }
4962
- await this.#execute(database, 'UPDATE offline_metadata SET last_user_id = NULL WHERE id = 1 AND last_user_id = ?', [principal]);
4963
- });
4990
+ await this.#transaction((database) => this.#clearUser(database, userId));
4991
+ }
4992
+ async #clearUser(database, userId) {
4993
+ const principal = canonicalOfflinePrincipalId(userId);
4994
+ await this.#execute(database, 'DELETE FROM offline_session_manifests WHERE user_id = ?', [principal]);
4995
+ await this.#execute(database, 'DELETE FROM offline_sync_commands WHERE user_id = ?', [principal]);
4996
+ await this.#execute(database, 'DELETE FROM offline_replica_cursors WHERE user_id = ?', [principal]);
4997
+ await this.#execute(database, 'DELETE FROM offline_reconciliation_scopes WHERE user_id = ?', [principal]);
4998
+ await this.#execute(database, 'DELETE FROM offline_pull_attentions WHERE user_id = ?', [principal]);
4999
+ for (const entity of this.#options.replicaSchema.entities) {
5000
+ await this.#execute(database, `DELETE FROM ${entity.tableName} WHERE _offline_user_id = ?`, [principal]);
5001
+ }
5002
+ await this.#execute(database, 'UPDATE offline_metadata SET last_user_id = NULL WHERE id = 1 AND last_user_id = ?', [principal]);
4964
5003
  }
4965
5004
  async clearScope(scope) {
4966
- await this.#transaction(async (database) => {
4967
- const values = [canonicalOfflinePrincipalId(scope.userId), scope.scopeId];
4968
- const partitionSourceKeys = this.#options.replicaSchema.entities
4969
- .filter((entity) => entity.scope === 'partition')
4970
- .map((entity) => entity.sourceKey);
4971
- if (partitionSourceKeys.length > 0) {
4972
- await this.#execute(database, `DELETE FROM offline_sync_commands
5005
+ await this.#transaction((database) => this.#clearScope(database, scope));
5006
+ }
5007
+ async #clearScope(database, scope) {
5008
+ const values = [canonicalOfflinePrincipalId(scope.userId), scope.scopeId];
5009
+ const partitionSourceKeys = this.#options.replicaSchema.entities
5010
+ .filter((entity) => entity.scope === 'partition')
5011
+ .map((entity) => entity.sourceKey);
5012
+ if (partitionSourceKeys.length > 0) {
5013
+ await this.#execute(database, `DELETE FROM offline_sync_commands
4973
5014
  WHERE user_id = ? AND scope_id = ? AND source_key IN (${partitionSourceKeys.map(() => '?').join(', ')})`, [...values, ...partitionSourceKeys]);
4974
- }
4975
- await this.#execute(database, 'DELETE FROM offline_replica_cursors WHERE user_id = ? AND scope_id = ?', values);
4976
- await this.#execute(database, 'DELETE FROM offline_reconciliation_scopes WHERE user_id = ? AND scope_id = ?', values);
4977
- await this.#execute(database, 'DELETE FROM offline_pull_attentions WHERE user_id = ? AND scope_id = ?', values);
4978
- for (const entity of this.#options.replicaSchema.entities) {
4979
- if (entity.scope !== 'partition')
4980
- continue;
4981
- await this.#execute(database, `DELETE FROM ${entity.tableName} WHERE _offline_user_id = ? AND _offline_scope_id = ?`, values);
4982
- }
4983
- });
5015
+ }
5016
+ await this.#execute(database, 'DELETE FROM offline_replica_cursors WHERE user_id = ? AND scope_id = ?', values);
5017
+ await this.#execute(database, 'DELETE FROM offline_reconciliation_scopes WHERE user_id = ? AND scope_id = ?', values);
5018
+ await this.#execute(database, 'DELETE FROM offline_pull_attentions WHERE user_id = ? AND scope_id = ?', values);
5019
+ for (const entity of this.#options.replicaSchema.entities) {
5020
+ if (entity.scope !== 'partition')
5021
+ continue;
5022
+ await this.#execute(database, `DELETE FROM ${entity.tableName} WHERE _offline_user_id = ? AND _offline_scope_id = ?`, values);
5023
+ }
4984
5024
  }
4985
5025
  async transactReplica(transaction) {
4986
5026
  for (const row of transaction.putRows ?? [])
4987
5027
  this.#validateReplicaRow(row);
4988
- await this.#transaction(async (databaseId) => {
4989
- const releases = new Map();
4990
- for (const release of transaction.releaseRemoteIds ?? []) {
4991
- this.#assertValidReleaseRemoteId(release.remoteId);
4992
- const key = this.#replicaRowKey(release);
4993
- if (releases.has(key)) {
4994
- throw new Error(`Offline replica remoteId release is duplicated for ${release.sourceKey}/${canonicalOfflineReplicaIdentity(release.identity)}.`);
4995
- }
4996
- releases.set(key, release);
4997
- }
4998
- const consumedReleases = new Set();
4999
- for (const row of transaction.putRows ?? []) {
5000
- const key = this.#replicaRowKey(row);
5001
- const release = releases.get(key);
5002
- await this.#putReplicaRow(databaseId, row, release);
5003
- if (release)
5004
- consumedReleases.add(key);
5005
- }
5006
- if (consumedReleases.size !== releases.size) {
5007
- throw new Error('Offline replica remoteId release must match an existing row in putRows.');
5008
- }
5009
- for (const row of transaction.removeRows ?? [])
5010
- await this.#removeReplicaRow(databaseId, row);
5011
- for (const command of transaction.putCommands ?? [])
5012
- await this.#putCommand(databaseId, command);
5013
- for (const commandId of transaction.removeCommandIds ?? []) {
5014
- await this.#execute(databaseId, 'DELETE FROM offline_sync_commands WHERE command_id = ?', [commandId]);
5015
- }
5016
- for (const cursor of transaction.putCursors ?? [])
5017
- await this.#putReplicaCursor(databaseId, cursor);
5018
- for (const scope of transaction.putReconciliationScopes ?? []) {
5019
- await this.#execute(databaseId, `INSERT INTO offline_reconciliation_scopes (user_id, scope_id) VALUES (?, ?)
5020
- ON CONFLICT(user_id, scope_id) DO NOTHING`, [canonicalOfflinePrincipalId(scope.userId), scope.scopeId]);
5021
- }
5022
- for (const scope of transaction.removeReconciliationScopes ?? []) {
5023
- await this.#execute(databaseId, 'DELETE FROM offline_reconciliation_scopes WHERE user_id = ? AND scope_id = ?', [
5024
- canonicalOfflinePrincipalId(scope.userId),
5025
- scope.scopeId,
5026
- ]);
5028
+ const apply = (databaseId) => this.#applyReplicaTransaction(databaseId, transaction);
5029
+ await this.#transaction(apply);
5030
+ }
5031
+ async #applyReplicaTransaction(databaseId, transaction) {
5032
+ const releases = new Map();
5033
+ for (const release of transaction.releaseRemoteIds ?? []) {
5034
+ this.#assertValidReleaseRemoteId(release.remoteId);
5035
+ const key = this.#replicaRowKey(release);
5036
+ if (releases.has(key)) {
5037
+ throw new Error(`Offline replica remoteId release is duplicated for ${release.sourceKey}/${canonicalOfflineReplicaIdentity(release.identity)}.`);
5027
5038
  }
5028
- for (const attention of transaction.putPullAttentions ?? []) {
5029
- await this.#execute(databaseId, `INSERT INTO offline_pull_attentions (user_id, scope_id, reason, status) VALUES (?, ?, ?, ?)
5039
+ releases.set(key, release);
5040
+ }
5041
+ const consumedReleases = new Set();
5042
+ for (const row of transaction.putRows ?? []) {
5043
+ const key = this.#replicaRowKey(row);
5044
+ const release = releases.get(key);
5045
+ await this.#putReplicaRow(databaseId, row, release);
5046
+ if (release)
5047
+ consumedReleases.add(key);
5048
+ }
5049
+ if (consumedReleases.size !== releases.size) {
5050
+ throw new Error('Offline replica remoteId release must match an existing row in putRows.');
5051
+ }
5052
+ for (const row of transaction.removeRows ?? [])
5053
+ await this.#removeReplicaRow(databaseId, row);
5054
+ for (const command of transaction.putCommands ?? [])
5055
+ await this.#putCommand(databaseId, command);
5056
+ for (const commandId of transaction.removeCommandIds ?? []) {
5057
+ await this.#execute(databaseId, 'DELETE FROM offline_sync_commands WHERE command_id = ?', [commandId]);
5058
+ }
5059
+ for (const cursor of transaction.putCursors ?? [])
5060
+ await this.#putReplicaCursor(databaseId, cursor);
5061
+ for (const attention of transaction.putPullAttentions ?? []) {
5062
+ await this.#execute(databaseId, `INSERT INTO offline_pull_attentions (user_id, scope_id, reason, status) VALUES (?, ?, ?, ?)
5030
5063
  ON CONFLICT(user_id, scope_id) DO UPDATE SET reason = excluded.reason, status = excluded.status`, [
5031
- canonicalOfflinePrincipalId(attention.userId),
5032
- attention.scopeId,
5033
- attention.reason,
5034
- attention.status === undefined ? null : attention.status,
5035
- ]);
5036
- }
5037
- for (const scope of transaction.removePullAttentions ?? []) {
5038
- await this.#execute(databaseId, 'DELETE FROM offline_pull_attentions WHERE user_id = ? AND scope_id = ?', [
5039
- canonicalOfflinePrincipalId(scope.userId),
5040
- scope.scopeId,
5041
- ]);
5042
- }
5043
- });
5064
+ canonicalOfflinePrincipalId(attention.userId),
5065
+ attention.scopeId,
5066
+ attention.reason,
5067
+ attention.status === undefined ? null : attention.status,
5068
+ ]);
5069
+ }
5070
+ for (const scope of transaction.removePullAttentions ?? []) {
5071
+ await this.#execute(databaseId, 'DELETE FROM offline_pull_attentions WHERE user_id = ? AND scope_id = ?', [
5072
+ canonicalOfflinePrincipalId(scope.userId),
5073
+ scope.scopeId,
5074
+ ]);
5075
+ }
5044
5076
  }
5045
5077
  async #open() {
5046
- try {
5047
- if (!this.#sqlite) {
5048
- throw new OfflineStorageUnavailableError('storage_unavailable', 'Native offline storage requires a community SQLite connection');
5049
- }
5050
- const { databaseId } = await this.#sqlite.open({
5051
- databaseName: this.#options.databaseName,
5052
- createEncryptionKey: this.#wrapCreateEncryptionKey(this.#options.createEncryptionKey),
5053
- });
5054
- this.#databaseId = databaseId;
5055
- for (const statement of SCHEMA)
5056
- await this.#execute(databaseId, statement);
5057
- const metadata = await this.#queryDatabase(databaseId, 'SELECT schema_version FROM offline_metadata WHERE id = 1');
5058
- if (metadata.length === 0) {
5059
- await this.#execute(databaseId, 'INSERT INTO offline_metadata (id, schema_version, last_user_id) VALUES (1, ?, NULL)', [
5060
- OFFLINE_SCHEMA_VERSION,
5061
- ]);
5062
- }
5063
- else {
5064
- const storedVersion = this.#number(metadata[0]['schema_version']);
5065
- if (storedVersion !== OFFLINE_SCHEMA_VERSION) {
5066
- throw new OfflineStorageUnavailableError('core_schema_incompatible', `Unsupported offline storage schema version ${storedVersion}; expected ${OFFLINE_SCHEMA_VERSION}. ` +
5067
- 'A lossless core schema migration is required before this database can be opened.');
5068
- }
5069
- }
5070
- await this.#initializeReplicaSchema(databaseId);
5071
- }
5072
- catch (error) {
5078
+ await this.#openDatabase().catch((error) => {
5073
5079
  throw this.#mapInitializationError(error);
5080
+ });
5081
+ }
5082
+ async #openDatabase() {
5083
+ if (!this.#sqlite) {
5084
+ throw new OfflineStorageUnavailableError('storage_unavailable', 'Native offline storage requires a community SQLite connection');
5085
+ }
5086
+ const { databaseId } = await this.#sqlite.open({
5087
+ databaseName: this.#options.databaseName,
5088
+ createEncryptionKey: this.#wrapCreateEncryptionKey(this.#options.createEncryptionKey),
5089
+ });
5090
+ this.#databaseId = databaseId;
5091
+ for (const statement of SCHEMA)
5092
+ await this.#execute(databaseId, statement);
5093
+ const metadata = await this.#queryDatabase(databaseId, 'SELECT schema_version FROM offline_metadata WHERE id = 1');
5094
+ if (metadata.length === 0) {
5095
+ await this.#execute(databaseId, 'INSERT INTO offline_metadata (id, schema_version, last_user_id) VALUES (1, ?, NULL)', [
5096
+ OFFLINE_SCHEMA_VERSION,
5097
+ ]);
5098
+ }
5099
+ else {
5100
+ const storedVersion = this.#number(metadata[0]['schema_version']);
5101
+ if (storedVersion !== OFFLINE_SCHEMA_VERSION) {
5102
+ throw new OfflineStorageUnavailableError('core_schema_incompatible', `Unsupported offline storage schema version ${storedVersion}; expected ${OFFLINE_SCHEMA_VERSION}. ` +
5103
+ 'A lossless core schema migration is required before this database can be opened.');
5104
+ }
5074
5105
  }
5106
+ await this.#initializeReplicaSchema(databaseId);
5075
5107
  }
5076
5108
  async #initializeReplicaSchema(databaseId) {
5077
5109
  const bundle = this.#options.replicaSchema;
@@ -5113,19 +5145,19 @@ class SqliteOfflineRepository {
5113
5145
  #wrapCreateEncryptionKey(createEncryptionKey) {
5114
5146
  if (!createEncryptionKey)
5115
5147
  return undefined;
5116
- return async () => {
5117
- try {
5148
+ return () => {
5149
+ const create = async () => {
5118
5150
  const encryptionKey = await createEncryptionKey();
5119
5151
  if (!encryptionKey) {
5120
5152
  throw new OfflineStorageUnavailableError('encryption_key_unavailable', 'Native offline storage requires a non-empty encryption key on first open');
5121
5153
  }
5122
5154
  return encryptionKey;
5123
- }
5124
- catch (error) {
5155
+ };
5156
+ return create().catch((error) => {
5125
5157
  if (error instanceof OfflineStorageUnavailableError)
5126
5158
  throw error;
5127
5159
  throw new OfflineStorageUnavailableError('encryption_key_unavailable', error instanceof Error ? error.message : 'Offline encryption key is unavailable.', { cause: error });
5128
- }
5160
+ });
5129
5161
  };
5130
5162
  }
5131
5163
  #mapInitializationError(error) {
@@ -5152,14 +5184,21 @@ class SqliteOfflineRepository {
5152
5184
  }
5153
5185
  async #nativeTransaction(databaseId, run) {
5154
5186
  await this.#sqlite.beginTransaction({ databaseId });
5155
- try {
5156
- await run();
5187
+ const execute = async () => run();
5188
+ return execute()
5189
+ .then(async (result) => {
5157
5190
  await this.#sqlite.commitTransaction({ databaseId });
5158
- }
5159
- catch (error) {
5160
- await this.#sqlite.rollbackTransaction({ databaseId });
5191
+ return result;
5192
+ })
5193
+ .catch(async (error) => {
5194
+ const rollback = await this.#sqlite.rollbackTransaction({ databaseId }).then(() => ({ status: 'fulfilled' }), (rollbackError) => ({ status: 'rejected', rollbackError }));
5195
+ if (rollback.status === 'rejected') {
5196
+ throw new AggregateError([error, rollback.rollbackError], 'Offline SQLite transaction and rollback both failed.', {
5197
+ cause: error,
5198
+ });
5199
+ }
5161
5200
  throw error;
5162
- }
5201
+ });
5163
5202
  }
5164
5203
  async #databaseConnection() {
5165
5204
  await this.initialize();
@@ -5235,12 +5274,6 @@ class SqliteOfflineRepository {
5235
5274
  return null;
5236
5275
  return { ...scope, cursor: this.#string(row['cursor']) };
5237
5276
  }
5238
- async #readReconciliationScopes(userId) {
5239
- const rows = await this.#query('SELECT scope_id FROM offline_reconciliation_scopes WHERE user_id = ? ORDER BY scope_id', [
5240
- canonicalOfflinePrincipalId(userId),
5241
- ]);
5242
- return rows.map((row) => ({ userId, scopeId: this.#string(row['scope_id']) }));
5243
- }
5244
5277
  async #readPullAttentions(userId) {
5245
5278
  const rows = await this.#query('SELECT scope_id, reason, status FROM offline_pull_attentions WHERE user_id = ? ORDER BY scope_id', [
5246
5279
  canonicalOfflinePrincipalId(userId),
@@ -5281,22 +5314,52 @@ class SqliteOfflineRepository {
5281
5314
  },
5282
5315
  getReplicaRowByRemoteIdentity: (scope, sourceKey, identity) => this.#readReplicaRowByRemoteIdentity(scope, sourceKey, identity),
5283
5316
  getReplicaCursor: (scope) => this.#readReplicaCursor(scope),
5284
- getReconciliationScopes: (userId) => this.#readReconciliationScopes(userId),
5285
5317
  getPullAttentions: (userId) => this.#readPullAttentions(userId),
5286
5318
  getCommands: (scope) => this.#readCommands(scope),
5287
5319
  getCommandsForUser: (userId) => this.#readCommandsForUser(userId),
5288
5320
  };
5289
5321
  }
5322
+ #atomicRepository() {
5323
+ const reader = this.#reader();
5324
+ const atomicTransaction = (run, marksCommit = true) => this.#queueAtomicOperation(() => this.#atomicTransaction(this.#databaseId, run, marksCommit));
5325
+ return {
5326
+ initialize: settledSqliteOperation,
5327
+ ...reader,
5328
+ runReadSnapshot: (read) => this.#queueAtomicOperation(() => this.#nativeTransaction(this.#databaseId, async () => {
5329
+ this.#readSnapshotActive = true;
5330
+ const executeRead = async () => read(reader);
5331
+ return executeRead().finally(() => (this.#readSnapshotActive = false));
5332
+ })),
5333
+ putCommand: (command) => atomicTransaction((databaseId) => this.#putCommand(databaseId, command)),
5334
+ replaceCommand: (command) => atomicTransaction((databaseId) => this.#putCommand(databaseId, command)),
5335
+ removeCommand: (commandId) => atomicTransaction((databaseId) => this.#execute(databaseId, 'DELETE FROM offline_sync_commands WHERE command_id = ?', [commandId])),
5336
+ putPullAttention: (attention) => atomicTransaction((databaseId) => this.#applyReplicaTransaction(databaseId, { putPullAttentions: [attention] })),
5337
+ removePullAttention: (scope) => atomicTransaction((databaseId) => this.#applyReplicaTransaction(databaseId, { removePullAttentions: [scope] })),
5338
+ setLastUserId: (userId) => atomicTransaction((databaseId) => this.#execute(databaseId, `INSERT INTO offline_metadata (id, schema_version, last_user_id) VALUES (1, ?, ?)
5339
+ ON CONFLICT(id) DO UPDATE SET schema_version = excluded.schema_version, last_user_id = excluded.last_user_id`, [OFFLINE_SCHEMA_VERSION, canonicalOfflinePrincipalId(userId)])),
5340
+ putSessionManifest: (userId, value) => atomicTransaction((databaseId) => this.#execute(databaseId, `INSERT INTO offline_session_manifests (user_id, value_json) VALUES (?, ?)
5341
+ ON CONFLICT(user_id) DO UPDATE SET value_json = excluded.value_json`, [canonicalOfflinePrincipalId(userId), JSON.stringify(value)])),
5342
+ clearUser: (userId) => atomicTransaction((databaseId) => this.#clearUser(databaseId, userId)),
5343
+ clearScope: (scope) => atomicTransaction((databaseId) => this.#clearScope(databaseId, scope)),
5344
+ transactReplica: (transaction) => {
5345
+ for (const row of transaction.putRows ?? [])
5346
+ this.#validateReplicaRow(row);
5347
+ return atomicTransaction((databaseId) => this.#applyReplicaTransaction(databaseId, transaction));
5348
+ },
5349
+ };
5350
+ }
5290
5351
  async #withCommittedRead(operation) {
5291
5352
  await this.initialize();
5292
- await this.#writes;
5293
- this.#beginReaders();
5294
- try {
5295
- return await operation();
5353
+ if (this.#readSnapshotActive) {
5354
+ return operation();
5296
5355
  }
5297
- finally {
5298
- this.#endReaders();
5356
+ if (this.#atomicMutationRevision !== null) {
5357
+ return this.#queueAtomicOperation(operation);
5299
5358
  }
5359
+ await this.#writes;
5360
+ this.#beginReaders();
5361
+ const read = async () => operation();
5362
+ return read().finally(() => this.#endReaders());
5300
5363
  }
5301
5364
  #beginReaders() {
5302
5365
  if (this.#activeReaders === 0) {
@@ -5311,7 +5374,7 @@ class SqliteOfflineRepository {
5311
5374
  if (this.#activeReaders === 0) {
5312
5375
  this.#resolveReadersIdle?.();
5313
5376
  this.#resolveReadersIdle = null;
5314
- this.#readersIdle = Promise.resolve();
5377
+ this.#readersIdle = settledSqliteOperation();
5315
5378
  }
5316
5379
  }
5317
5380
  async #query(statement, values = []) {
@@ -5321,6 +5384,9 @@ class SqliteOfflineRepository {
5321
5384
  return this.#queueWrite((databaseId) => this.#execute(databaseId, statement, values));
5322
5385
  }
5323
5386
  #queueWrite(run) {
5387
+ if (this.#atomicMutationRevision !== null) {
5388
+ return this.#atomicIdle.then(() => this.#queueWrite(run));
5389
+ }
5324
5390
  const write = this.#writes.then(async () => {
5325
5391
  if (this.#activeReaders > 0)
5326
5392
  await this.#readersIdle;
@@ -5330,22 +5396,45 @@ class SqliteOfflineRepository {
5330
5396
  return write;
5331
5397
  }
5332
5398
  #transaction(run) {
5333
- const write = this.#writes.then(async () => {
5399
+ if (this.#atomicMutationRevision !== null) {
5400
+ return this.#atomicIdle.then(() => this.#transaction(run));
5401
+ }
5402
+ const transaction = this.#writes.then(async () => {
5334
5403
  if (this.#activeReaders > 0)
5335
5404
  await this.#readersIdle;
5336
5405
  const databaseId = await this.#databaseConnection();
5337
- await this.#sqlite.beginTransaction({ databaseId });
5338
- try {
5339
- await run(databaseId);
5340
- await this.#sqlite.commitTransaction({ databaseId });
5341
- }
5342
- catch (error) {
5343
- await this.#sqlite.rollbackTransaction({ databaseId });
5344
- throw error;
5345
- }
5406
+ return this.#nativeTransaction(databaseId, () => run(databaseId));
5346
5407
  });
5347
- this.#writes = write.catch(() => undefined);
5348
- return write;
5408
+ this.#writes = transaction.then(() => undefined, () => undefined);
5409
+ return transaction;
5410
+ }
5411
+ async #atomicTransaction(databaseId, run, marksCommit = true) {
5412
+ const expected = this.#atomicMutationRevision;
5413
+ if (expected === null)
5414
+ throw new Error('Offline replica atomic mutation is not active.');
5415
+ const result = await this.#nativeTransaction(databaseId, async () => {
5416
+ // A write, even when it leaves the value unchanged, obtains SQLite's
5417
+ // RESERVED lock before the revision check. No second connection can
5418
+ // commit between this check and the transaction commit.
5419
+ await this.#execute(databaseId, 'UPDATE offline_metadata SET schema_version = schema_version WHERE id = 1');
5420
+ const actual = await this.#dataVersion(databaseId);
5421
+ if (actual !== expected) {
5422
+ throw new Error('Offline replica changed through another SQLite connection; retry the operation from fresh state.');
5423
+ }
5424
+ return run(databaseId);
5425
+ });
5426
+ if (marksCommit)
5427
+ this.#atomicMutationCommitted = true;
5428
+ return result;
5429
+ }
5430
+ #queueAtomicOperation(run) {
5431
+ const operation = this.#atomicOperations.then(run);
5432
+ this.#atomicOperations = operation.then(() => undefined, () => undefined);
5433
+ return operation;
5434
+ }
5435
+ async #dataVersion(databaseId) {
5436
+ const rows = await this.#queryDatabase(databaseId, 'PRAGMA data_version');
5437
+ return this.#number(rows[0]?.['data_version']);
5349
5438
  }
5350
5439
  #command(row) {
5351
5440
  return {