@rdlabo/ionic-angular-kit 21.5.39 → 21.6.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.
@@ -1,5 +1,5 @@
1
1
  import * as i0 from '@angular/core';
2
- import { InjectionToken, inject, Injectable, signal, computed, ErrorHandler, effect, makeEnvironmentProviders, provideAppInitializer } from '@angular/core';
2
+ import { InjectionToken, inject, Injectable, signal, computed, ErrorHandler, effect, untracked, makeEnvironmentProviders, provideAppInitializer } from '@angular/core';
3
3
  import { KitStorageService } from '@rdlabo/ionic-angular-kit';
4
4
  import { toObservable } from '@angular/core/rxjs-interop';
5
5
  import { map, distinctUntilChanged } from 'rxjs/operators';
@@ -897,6 +897,16 @@ const OFFLINE_COMMAND_HOOKS = new InjectionToken('OFFLINE_COMMAND_HOOKS', {
897
897
  /** DI token for product-independent offline persistence settings. */
898
898
  const OFFLINE_KIT_OPTIONS = new InjectionToken('OFFLINE_KIT_OPTIONS');
899
899
 
900
+ /**
901
+ * Returns a command whose only changed field is `baseRevision`.
902
+ *
903
+ * Payload and every other field are copied unchanged. Kit uses this when a
904
+ * newer server revision is known, and passes `null` after a generated remote
905
+ * identity is released.
906
+ */
907
+ function offlineCommandWithBaseRevision(command, baseRevision) {
908
+ return { ...command, baseRevision };
909
+ }
900
910
  /** DI token for the product-specific command transport adapter. */
901
911
  const OFFLINE_COMMAND_EXECUTOR = new InjectionToken('OFFLINE_COMMAND_EXECUTOR');
902
912
  /** DI token for authenticated synchronization context. */
@@ -916,6 +926,14 @@ function offlineCommandLookupIdentity(identity) {
916
926
  return { kind: 'natural', naturalKey: identity.naturalKey };
917
927
  }
918
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
+
919
937
  /** Current durable storage schema used by both web and native repositories. */
920
938
  const OFFLINE_SCHEMA_VERSION = 2;
921
939
  /** Canonical physical key shared by every repository and replica transaction coordinator. */
@@ -942,6 +960,8 @@ const CURSORS_KEY = 'offline:replica:cursors';
942
960
  const OUTBOX_KEY = 'offline:outbox:commands';
943
961
  const REPLICA_TRANSACTION_KEY = 'offline:replica:transaction';
944
962
  const REPLICA_SCHEMA_MIGRATION_KEY = 'offline:replica:schema-migration';
963
+ // Legacy marker storage is no longer read or written. Keep cleanup support for
964
+ // databases created by released versions that persisted this key.
945
965
  const RECONCILIATION_SCOPES_KEY = 'offline:replica:reconciliation-scopes';
946
966
  const PULL_ATTENTIONS_KEY = 'offline:replica:pull-attentions';
947
967
  function compareOfflineCommands$1(left, right) {
@@ -1005,9 +1025,6 @@ class IonicOfflineRepository {
1005
1025
  async getReplicaCursor(scope) {
1006
1026
  return this.#withCommittedRead(() => this.#readReplicaCursor(scope));
1007
1027
  }
1008
- async getReconciliationScopes(userId) {
1009
- return this.#withCommittedRead(() => this.#readReconciliationScopes(userId));
1010
- }
1011
1028
  async getPullAttentions(userId) {
1012
1029
  return this.#withCommittedRead(() => this.#readPullAttentions(userId));
1013
1030
  }
@@ -1076,10 +1093,6 @@ class IonicOfflineRepository {
1076
1093
  const cursor = cursors[this.#cursorKey(scope)];
1077
1094
  return cursor === undefined ? null : { ...scope, cursor };
1078
1095
  }
1079
- async #readReconciliationScopes(userId) {
1080
- const scopes = await this.#readRecord(RECONCILIATION_SCOPES_KEY);
1081
- return Object.values(scopes).filter((scope) => scope.userId === userId);
1082
- }
1083
1096
  async #readPullAttentions(userId) {
1084
1097
  const attentions = await this.#readRecord(PULL_ATTENTIONS_KEY);
1085
1098
  return Object.values(attentions)
@@ -1114,7 +1127,6 @@ class IonicOfflineRepository {
1114
1127
  },
1115
1128
  getReplicaRowByRemoteIdentity: (scope, sourceKey, identity) => this.#readReplicaRowByRemoteIdentity(scope, sourceKey, identity),
1116
1129
  getReplicaCursor: (scope) => this.#readReplicaCursor(scope),
1117
- getReconciliationScopes: (userId) => this.#readReconciliationScopes(userId),
1118
1130
  getPullAttentions: (userId) => this.#readPullAttentions(userId),
1119
1131
  getCommands: (scope) => this.#readCommands(scope),
1120
1132
  getCommandsForUser: (userId) => this.#readCommandsForUser(userId),
@@ -1384,11 +1396,10 @@ class IonicOfflineRepository {
1384
1396
  await this.#assertReplicaSchemaLocked();
1385
1397
  for (const row of transaction.putRows ?? [])
1386
1398
  this.#validateReplicaRow(row);
1387
- const [rows, commands, cursors, reconciliationScopes, pullAttentions] = await Promise.all([
1399
+ const [rows, commands, cursors, pullAttentions] = await Promise.all([
1388
1400
  this.#readRecord(ROWS_KEY),
1389
1401
  this.#readRecord(OUTBOX_KEY),
1390
1402
  this.#readRecord(CURSORS_KEY),
1391
- this.#readRecord(RECONCILIATION_SCOPES_KEY),
1392
1403
  this.#readRecord(PULL_ATTENTIONS_KEY),
1393
1404
  ]);
1394
1405
  const identityCheckRows = { ...rows };
@@ -1440,12 +1451,6 @@ class IonicOfflineRepository {
1440
1451
  for (const cursor of transaction.putCursors ?? []) {
1441
1452
  cursors[this.#cursorKey(cursor)] = cursor.cursor;
1442
1453
  }
1443
- for (const scope of transaction.putReconciliationScopes ?? []) {
1444
- reconciliationScopes[this.#cursorKey(scope)] = scope;
1445
- }
1446
- for (const scope of transaction.removeReconciliationScopes ?? []) {
1447
- delete reconciliationScopes[this.#cursorKey(scope)];
1448
- }
1449
1454
  for (const attention of transaction.putPullAttentions ?? []) {
1450
1455
  pullAttentions[this.#cursorKey(attention)] = attention;
1451
1456
  }
@@ -1456,7 +1461,6 @@ class IonicOfflineRepository {
1456
1461
  this.#storage.set(ROWS_KEY, rows),
1457
1462
  this.#storage.set(OUTBOX_KEY, commands),
1458
1463
  this.#storage.set(CURSORS_KEY, cursors),
1459
- this.#storage.set(RECONCILIATION_SCOPES_KEY, reconciliationScopes),
1460
1464
  this.#storage.set(PULL_ATTENTIONS_KEY, pullAttentions),
1461
1465
  ]);
1462
1466
  await this.#writeAffectedRowPartitions(rows, transaction);
@@ -1758,12 +1762,18 @@ function compareUtf8Binary(left, right) {
1758
1762
  * method does not acquire the lane itself.
1759
1763
  */
1760
1764
  class OfflineReplicaMutationCoordinator {
1765
+ #repository = inject(OFFLINE_REPOSITORY, { optional: true });
1761
1766
  #projector = inject(OFFLINE_AGGREGATE_INTENT_PROJECTOR, { optional: true });
1762
1767
  #options = inject(OFFLINE_KIT_OPTIONS, { optional: true });
1763
1768
  #tail = Promise.resolve();
1764
1769
  /** Enqueues one local replica critical section behind any in-flight mutation. */
1765
1770
  run(operation) {
1766
- const mutation = this.#tail.then(operation);
1771
+ const mutation = this.#tail.then(() => {
1772
+ if (!this.#repository)
1773
+ throw new Error('Offline repository is not configured.');
1774
+ const atomicMutation = this.#repository?.[OFFLINE_REPOSITORY_ATOMIC_MUTATION];
1775
+ return atomicMutation ? atomicMutation.call(this.#repository, operation) : operation(this.#repository);
1776
+ });
1767
1777
  this.#tail = mutation.then(() => undefined, () => undefined);
1768
1778
  return mutation;
1769
1779
  }
@@ -1973,7 +1983,6 @@ class OfflineReplicaPullService {
1973
1983
  #options = inject(OFFLINE_KIT_OPTIONS);
1974
1984
  #puller = inject(OFFLINE_REPLICA_PULLER);
1975
1985
  #projector = inject(OFFLINE_REPLICA_PROJECTOR, { optional: true });
1976
- #executor = inject(OFFLINE_COMMAND_EXECUTOR);
1977
1986
  #hooks = inject(OFFLINE_COMMAND_HOOKS);
1978
1987
  #replicaMutations = inject(OfflineReplicaMutationCoordinator);
1979
1988
  #schemaHash = null;
@@ -2014,18 +2023,16 @@ class OfflineReplicaPullService {
2014
2023
  requestCursor = page.nextCursor;
2015
2024
  continue;
2016
2025
  }
2017
- const applied = await this.#replicaMutations.run(async () => {
2018
- const currentCursor = (await this.#repository.getReplicaCursor(scope))?.cursor ?? '';
2026
+ const applied = await this.#replicaMutations.run(async (repository) => {
2027
+ const currentCursor = (await repository.getReplicaCursor(scope))?.cursor ?? '';
2019
2028
  if (currentCursor !== persistedCursor)
2020
2029
  return currentCursor;
2021
- const scopeCommands = await this.#repository.getCommands(scope);
2022
- const userCommands = this.#repository.getCommandsForUser ? await this.#repository.getCommandsForUser(scope.userId) : scopeCommands;
2030
+ const scopeCommands = await repository.getCommands(scope);
2031
+ const userCommands = repository.getCommandsForUser ? await repository.getCommandsForUser(scope.userId) : scopeCommands;
2023
2032
  const changes = this.#collapseChanges(page.changes);
2024
2033
  const projection = await this.#projector?.project({
2025
2034
  scope,
2026
2035
  changes,
2027
- commands: scopeCommands,
2028
- repository: this.#repository,
2029
2036
  });
2030
2037
  this.#assertProjection(scope, projection);
2031
2038
  const putRows = [];
@@ -2112,6 +2119,7 @@ class OfflineReplicaPullService {
2112
2119
  for (const command of related) {
2113
2120
  putCommands.set(command.commandId, { ...command, state: 'conflict', retryAt: null, lastErrorCode: 'remote_deleted' });
2114
2121
  }
2122
+ rematerializeAfter.push(related[0]);
2115
2123
  continue;
2116
2124
  }
2117
2125
  const confirmedValues = this.#validatedValues(schema, change);
@@ -2143,7 +2151,7 @@ class OfflineReplicaPullService {
2143
2151
  if (remaining.length > 0)
2144
2152
  rematerializeAfter.push(remaining[0]);
2145
2153
  for (const command of remaining) {
2146
- putCommands.set(command.commandId, this.#executor.withServerRevision(command, change.serverRevision));
2154
+ putCommands.set(command.commandId, offlineCommandWithBaseRevision(command, change.serverRevision));
2147
2155
  }
2148
2156
  }
2149
2157
  const confirmedAndProjected = this.#mergeRowMutations([
@@ -2156,7 +2164,7 @@ class OfflineReplicaPullService {
2156
2164
  .map((commandId) => userCommands.find((command) => command.commandId === commandId) ??
2157
2165
  scopeCommands.find((command) => command.commandId === commandId))
2158
2166
  .filter((command) => command != null);
2159
- await this.#repository.transactReplica({
2167
+ await repository.transactReplica({
2160
2168
  putRows: finalRows.putRows,
2161
2169
  removeRows: finalRows.removeRows,
2162
2170
  putCommands: [...putCommands.values()],
@@ -2480,9 +2488,9 @@ class OfflineReplicaPullService {
2480
2488
  const acknowledgementSuperseded = (change.acknowledgementOrdinals[lastAcknowledgedCommand.commandId] ?? -1) < change.collapsedOrdinal;
2481
2489
  const following = related
2482
2490
  .slice(lastAcknowledgedIndex + 1)
2483
- .map((command) => acknowledgementSuperseded
2491
+ .map((command) => acknowledgementSuperseded || change.deleted
2484
2492
  ? { ...command, state: 'conflict', retryAt: null, lastErrorCode: change.deleted ? 'remote_deleted' : 'remote_revision' }
2485
- : this.#executor.withServerRevision(command, change.serverRevision));
2493
+ : offlineCommandWithBaseRevision(command, change.serverRevision));
2486
2494
  for (const command of following)
2487
2495
  putCommands.set(command.commandId, command);
2488
2496
  for (const command of related.slice(0, lastAcknowledgedIndex + 1)) {
@@ -2495,15 +2503,10 @@ class OfflineReplicaPullService {
2495
2503
  ...row,
2496
2504
  confirmedValues: null,
2497
2505
  serverRevision: change.serverRevision,
2498
- syncState: acknowledgementSuperseded ? 'conflict' : 'pending',
2506
+ syncState: 'conflict',
2499
2507
  visibility: following.at(-1).replicaMutation === 'delete' ? 'pending_delete' : 'present',
2500
2508
  fetchedAt: Date.now(),
2501
2509
  });
2502
- if (acknowledgementSuperseded) {
2503
- for (const command of following) {
2504
- putCommands.set(command.commandId, { ...command, state: 'conflict', lastErrorCode: 'remote_deleted' });
2505
- }
2506
- }
2507
2510
  }
2508
2511
  else {
2509
2512
  removeRows.push({ ...row, identity: row.identity });
@@ -2856,7 +2859,7 @@ class OfflineSyncService {
2856
2859
  #commands;
2857
2860
  #pullAttentions;
2858
2861
  #knownScopes;
2859
- /** ACKed scopes whose authoritative post-send pull has not completed yet. */
2862
+ /** In-memory scheduling cache for scopes whose authoritative post-send pull has not completed yet. */
2860
2863
  #pendingPullScopes;
2861
2864
  #activeUserId;
2862
2865
  #flushPromise;
@@ -2870,7 +2873,6 @@ class OfflineSyncService {
2870
2873
  #foregroundScopePolicy;
2871
2874
  #initialized;
2872
2875
  #lastCommandCreatedAt;
2873
- #coldReconciliationRequired;
2874
2876
  constructor() {
2875
2877
  this.#network = inject(OfflineNetworkService);
2876
2878
  this.#repository = inject(OFFLINE_REPOSITORY);
@@ -2885,7 +2887,7 @@ class OfflineSyncService {
2885
2887
  this.#commands = signal([], ...(ngDevMode ? [{ debugName: "#commands" }] : /* istanbul ignore next */ []));
2886
2888
  this.#pullAttentions = signal([], ...(ngDevMode ? [{ debugName: "#pullAttentions" }] : /* istanbul ignore next */ []));
2887
2889
  this.#knownScopes = new Map();
2888
- /** ACKed scopes whose authoritative post-send pull has not completed yet. */
2890
+ /** In-memory scheduling cache for scopes whose authoritative post-send pull has not completed yet. */
2889
2891
  this.#pendingPullScopes = new Map();
2890
2892
  this.#activeUserId = null;
2891
2893
  this.#flushPromise = null;
@@ -2899,7 +2901,6 @@ class OfflineSyncService {
2899
2901
  this.#foregroundScopePolicy = null;
2900
2902
  this.#initialized = false;
2901
2903
  this.#lastCommandCreatedAt = 0;
2902
- this.#coldReconciliationRequired = this.#repository.getReconciliationScopes === undefined;
2903
2904
  this.pendingCommands = this.#commands.asReadonly();
2904
2905
  this.pendingCount = computed(() => this.pendingCommands().length, ...(ngDevMode ? [{ debugName: "pendingCount" }] : /* istanbul ignore next */ []));
2905
2906
  this.conflicts = computed(() => this.#commands().filter((command) => command.state === 'conflict'), ...(ngDevMode ? [{ debugName: "conflicts" }] : /* istanbul ignore next */ []));
@@ -2920,7 +2921,11 @@ class OfflineSyncService {
2920
2921
  }, ...(ngDevMode ? [{ debugName: "syncState" }] : /* istanbul ignore next */ []));
2921
2922
  effect(() => {
2922
2923
  const connected = this.#network.connected();
2923
- if (this.#initialized && connected)
2924
+ // The network transition may be observed after an explicit flush has already
2925
+ // persisted a fatal pull attention. Do not let that stale transition restart
2926
+ // the intentionally stopped loop; auth/session refresh remains able to retry.
2927
+ const hasFatalPullAttention = untracked(() => this.#pullAttentions().length > 0);
2928
+ if (this.#initialized && connected && !hasFatalPullAttention)
2924
2929
  this.#flushInBackground();
2925
2930
  });
2926
2931
  }
@@ -2984,7 +2989,7 @@ class OfflineSyncService {
2984
2989
  }
2985
2990
  enqueue(request, options = {}) {
2986
2991
  const generation = this.#generation;
2987
- return this.#serializeReplicaMutation(() => this.#enqueue(request, options, generation));
2992
+ return this.#serializeReplicaMutation((repository) => this.#enqueue(request, options, generation, undefined, repository));
2988
2993
  }
2989
2994
  /**
2990
2995
  * Reads, derives, and commits one Outbox command, then rematerializes its
@@ -2992,12 +2997,12 @@ class OfflineSyncService {
2992
2997
  */
2993
2998
  enqueuePrepared(prepare, options = {}) {
2994
2999
  const generation = this.#generation;
2995
- return this.#serializeReplicaMutation(async () => {
3000
+ return this.#serializeReplicaMutation(async (repository) => {
2996
3001
  await this.initialize();
2997
3002
  if (!this.#isCurrent(generation))
2998
3003
  throw new Error('Offline session changed before prepared enqueue.');
2999
- const prepared = await prepare(this.#repository);
3000
- return this.#enqueue(prepared.request, options, generation);
3004
+ const prepared = await prepare(repository);
3005
+ return this.#enqueue(prepared.request, options, generation, undefined, repository);
3001
3006
  });
3002
3007
  }
3003
3008
  /**
@@ -3010,12 +3015,12 @@ class OfflineSyncService {
3010
3015
  */
3011
3016
  enqueuePreparedBatch(prepare, options = {}) {
3012
3017
  const generation = this.#generation;
3013
- return this.#serializeReplicaMutation(async () => {
3018
+ return this.#serializeReplicaMutation(async (repository) => {
3014
3019
  await this.initialize();
3015
3020
  if (!this.#isCurrent(generation))
3016
3021
  throw new Error('Offline session changed before prepared batch enqueue.');
3017
- const prepared = await prepare(this.#repository);
3018
- return this.#enqueuePreparedBatch(prepared, options, generation);
3022
+ const prepared = await prepare(repository);
3023
+ return this.#enqueuePreparedBatch(prepared, options, generation, repository);
3019
3024
  });
3020
3025
  }
3021
3026
  /**
@@ -3027,7 +3032,7 @@ class OfflineSyncService {
3027
3032
  */
3028
3033
  replacePrepared(commandId, prepare, options = {}) {
3029
3034
  const generation = this.#generation;
3030
- return this.#serializeReplicaMutation(async () => {
3035
+ return this.#serializeReplicaMutation(async (repository) => {
3031
3036
  await this.initialize();
3032
3037
  if (!this.#isCurrent(generation))
3033
3038
  throw new Error('Offline session changed before prepared replacement.');
@@ -3039,8 +3044,8 @@ class OfflineSyncService {
3039
3044
  if (knownCommands.some((command) => command.commandId !== commandId && this.#aggregateKey(command) === this.#aggregateKey(replaced))) {
3040
3045
  throw new Error('Offline replacement requires the command to be the only pending intent for its aggregate.');
3041
3046
  }
3042
- const prepared = await prepare(this.#repository);
3043
- return this.#enqueue(prepared.request, options, generation, replaced);
3047
+ const prepared = await prepare(repository);
3048
+ return this.#enqueue(prepared.request, options, generation, replaced, repository);
3044
3049
  });
3045
3050
  }
3046
3051
  /**
@@ -3052,7 +3057,7 @@ class OfflineSyncService {
3052
3057
  */
3053
3058
  replacePreparedAggregate(commandId, prepare, options = {}) {
3054
3059
  const generation = this.#generation;
3055
- return this.#serializeReplicaMutation(async () => {
3060
+ return this.#serializeReplicaMutation(async (repository) => {
3056
3061
  await this.initialize();
3057
3062
  if (!this.#isCurrent(generation))
3058
3063
  throw new Error('Offline session changed before prepared aggregate replacement.');
@@ -3063,7 +3068,7 @@ class OfflineSyncService {
3063
3068
  const aggregateKey = this.#aggregateKey(selected);
3064
3069
  const replaced = knownCommands.filter((command) => this.#aggregateKey(command) === aggregateKey);
3065
3070
  this.#assertDiscardable(replaced);
3066
- const prepared = await prepare(this.#repository, replaced);
3071
+ const prepared = await prepare(repository, replaced);
3067
3072
  if (prepared.length !== replaced.length) {
3068
3073
  throw new Error('Offline aggregate replacement must preserve the ordered intent count.');
3069
3074
  }
@@ -3077,7 +3082,7 @@ class OfflineSyncService {
3077
3082
  this.#assertDistinctBatchFootprints(materializations, retained, true);
3078
3083
  await this.#assertOutboxCapacity(session.userId, materializations.map((item) => item.command), replaced.map((command) => command.commandId), knownCommands);
3079
3084
  options.assertCurrent?.();
3080
- await this.#commitMaterializedEnqueues(materializations, generation, options, replaced.map((command) => command.commandId));
3085
+ await this.#commitMaterializedEnqueues(materializations, generation, options, replaced.map((command) => command.commandId), repository);
3081
3086
  return materializations.map((item) => item.command.commandId);
3082
3087
  });
3083
3088
  }
@@ -3098,11 +3103,11 @@ class OfflineSyncService {
3098
3103
  */
3099
3104
  runSerializedReplicaMutation(operation) {
3100
3105
  const generation = this.#generation;
3101
- return this.#serializeReplicaMutation(async () => {
3106
+ return this.#serializeReplicaMutation(async (repository) => {
3102
3107
  await this.initialize();
3103
3108
  if (!this.#isCurrent(generation))
3104
3109
  throw new Error('Offline session changed before serialized replica mutation.');
3105
- const result = await operation(this.#repository);
3110
+ const result = await operation(repository);
3106
3111
  if (this.#isCurrent(generation))
3107
3112
  await this.#refreshState(generation);
3108
3113
  return result;
@@ -3111,7 +3116,7 @@ class OfflineSyncService {
3111
3116
  #serializeReplicaMutation(operation) {
3112
3117
  return this.#replicaMutations.run(operation);
3113
3118
  }
3114
- async #enqueue(request, options, generation, replaced) {
3119
+ async #enqueue(request, options, generation, replaced, repository = this.#repository) {
3115
3120
  const session = await this.#beginEnqueueSession(generation);
3116
3121
  this.#assertEnqueueScope(session, request.scopeId);
3117
3122
  const materialization = await this.#materializeEnqueue(session.userId, request, replaced);
@@ -3119,10 +3124,10 @@ class OfflineSyncService {
3119
3124
  const retainedCommands = replaced ? currentCommands.filter((command) => command.commandId !== replaced.commandId) : currentCommands;
3120
3125
  this.#assertDistinctBatchFootprints([materialization], retainedCommands);
3121
3126
  await this.#assertOutboxCapacity(session.userId, [materialization.command], replaced ? [replaced.commandId] : undefined, currentCommands);
3122
- await this.#commitMaterializedEnqueues([materialization], generation, options, replaced ? [replaced.commandId] : undefined);
3127
+ await this.#commitMaterializedEnqueues([materialization], generation, options, replaced ? [replaced.commandId] : undefined, repository);
3123
3128
  return materialization.command.commandId;
3124
3129
  }
3125
- async #enqueuePreparedBatch(prepared, options, generation) {
3130
+ async #enqueuePreparedBatch(prepared, options, generation, repository) {
3126
3131
  if (prepared.length === 0) {
3127
3132
  throw new Error('Prepared offline batch must contain at least one command.');
3128
3133
  }
@@ -3139,7 +3144,7 @@ class OfflineSyncService {
3139
3144
  this.#assertDistinctBatchFootprints(materializations, currentCommands);
3140
3145
  await this.#assertOutboxCapacity(session.userId, materializations.map((item) => item.command), undefined, currentCommands);
3141
3146
  options.assertCurrent?.();
3142
- await this.#commitMaterializedEnqueues(materializations, generation, options);
3147
+ await this.#commitMaterializedEnqueues(materializations, generation, options, undefined, repository);
3143
3148
  return materializations.map((item) => item.command.commandId);
3144
3149
  }
3145
3150
  async #beginEnqueueSession(generation) {
@@ -3182,7 +3187,6 @@ class OfflineSyncService {
3182
3187
  operation: request.operation,
3183
3188
  payload: normalized.payload,
3184
3189
  replicaMutation: request.replicaMutation ?? 'upsert',
3185
- payloadHash: await this.#payloadHash(normalized.payload),
3186
3190
  baseRevision: normalized.baseRevision,
3187
3191
  state: 'pending',
3188
3192
  attempts: 0,
@@ -3315,7 +3319,7 @@ class OfflineSyncService {
3315
3319
  : { kind: 'natural', naturalKey: command.identity.naturalKey };
3316
3320
  return [this.#replicaRowKey({ ...command, identity }), ...commandFootprintKeys(command).map((key) => this.#replicaRowKey(key))];
3317
3321
  }
3318
- async #commitMaterializedEnqueues(entries, generation, options, removeCommandIds) {
3322
+ async #commitMaterializedEnqueues(entries, generation, options, removeCommandIds, repository = this.#repository) {
3319
3323
  if (generation !== this.#generation) {
3320
3324
  throw new Error('Offline session changed before the command could be persisted');
3321
3325
  }
@@ -3332,7 +3336,7 @@ class OfflineSyncService {
3332
3336
  seeds.set(this.#aggregateKey(entry.command), entry.seedBaseRow);
3333
3337
  }
3334
3338
  const rematerialized = await this.#rematerializeAffectedAggregates(affected, remaining, seeds);
3335
- await this.#repository.transactReplica({
3339
+ await repository.transactReplica({
3336
3340
  putRows: rematerialized.putRows,
3337
3341
  removeRows: rematerialized.removeRows,
3338
3342
  putCommands: entries.map((entry) => entry.command),
@@ -3414,13 +3418,13 @@ class OfflineSyncService {
3414
3418
  // and project the discard inside the same local mutation lane used by
3415
3419
  // enqueue, ACK, and pull application so an old before-image cannot replace
3416
3420
  // a newer authoritative row after its cursor has advanced.
3417
- const command = await this.#replicaMutations.run(async () => {
3421
+ const command = await this.#replicaMutations.run(async (repository) => {
3418
3422
  const current = (await this.#readKnownCommands()).find((item) => item.commandId === commandId);
3419
3423
  if (!current)
3420
3424
  return null;
3421
3425
  this.#assertDiscardable([current]);
3422
3426
  this.#invalidateFlush();
3423
- await this.#discardCommands([current]);
3427
+ await this.#discardCommands([current], repository);
3424
3428
  return current;
3425
3429
  });
3426
3430
  if (!command)
@@ -3460,11 +3464,11 @@ class OfflineSyncService {
3460
3464
  }
3461
3465
  async discardAllPending() {
3462
3466
  await this.initialize();
3463
- const commands = await this.#replicaMutations.run(async () => {
3467
+ const commands = await this.#replicaMutations.run(async (repository) => {
3464
3468
  const current = await this.#readKnownCommands();
3465
3469
  this.#assertDiscardable(current);
3466
3470
  this.#invalidateFlush();
3467
- await this.#discardCommands(current);
3471
+ await this.#discardCommands(current, repository);
3468
3472
  return current;
3469
3473
  });
3470
3474
  await this.#refreshState();
@@ -3483,7 +3487,7 @@ class OfflineSyncService {
3483
3487
  return this.#beginFlush(true);
3484
3488
  }
3485
3489
  #beginFlush(explicitFull) {
3486
- const isPartial = !explicitFull && !this.#coldReconciliationRequired && this.#foregroundScopePolicy !== null;
3490
+ const isPartial = !explicitFull && this.#foregroundScopePolicy !== null;
3487
3491
  if (this.#flushPromise) {
3488
3492
  if (explicitFull && this.#partialFlushInFlight) {
3489
3493
  if (!this.#chainedFullFlush) {
@@ -3618,7 +3622,7 @@ class OfflineSyncService {
3618
3622
  await this.#refreshState(generation);
3619
3623
  if (fatalPullFailure !== null) {
3620
3624
  // Auth/upgrade recovery only — never arm the 1s automatic flush retry.
3621
- // Post-send ACK already removed the command; reconciliation markers remain for later recovery.
3625
+ // Transported commands remain awaiting_pull for later auth/upgrade recovery.
3622
3626
  // Only the owning generation may clear the timer — a stale fatal must not disarm a
3623
3627
  // newer session's already-armed retry_wait / post-pull retry.
3624
3628
  if (this.#isCurrent(generation))
@@ -3634,8 +3638,6 @@ class OfflineSyncService {
3634
3638
  }
3635
3639
  throw failures[0];
3636
3640
  }
3637
- if (this.#isCurrent(generation))
3638
- this.#coldReconciliationRequired = false;
3639
3641
  if (this.#isCurrent(generation)) {
3640
3642
  for (const command of await this.#readKnownCommands()) {
3641
3643
  if (command.state !== 'awaiting_pull')
@@ -3795,36 +3797,17 @@ class OfflineSyncService {
3795
3797
  }
3796
3798
  async #normalizeEnqueueRequest(scope, request, commandIdentity) {
3797
3799
  let baseRevision = request.baseRevision ?? null;
3798
- let payload = request.payload;
3799
3800
  const sourceKey = this.#hooks.entityType(request);
3800
3801
  const row = await this.#getReplicaRowForSync(scope, sourceKey, commandIdentity);
3801
3802
  if (row?.serverRevision != null && row.serverRevision !== baseRevision) {
3802
- const rebased = this.#executor.withServerRevision({
3803
- ...scope,
3804
- commandId: '',
3805
- aggregateType: request.aggregateType,
3806
- sourceKey,
3807
- identity: commandIdentity,
3808
- operation: request.operation,
3809
- payload,
3810
- replicaMutation: request.replicaMutation ?? 'upsert',
3811
- payloadHash: '',
3812
- baseRevision,
3813
- state: 'pending',
3814
- attempts: 0,
3815
- retryAt: null,
3816
- createdAt: 0,
3817
- lastErrorCode: null,
3818
- }, row.serverRevision);
3819
3803
  baseRevision = row.serverRevision;
3820
- payload = rebased.payload;
3821
3804
  }
3822
- return { payload, baseRevision };
3805
+ return { payload: request.payload, baseRevision };
3823
3806
  }
3824
3807
  async #completeCommand(commands, command, result, generation) {
3825
- return this.#serializeReplicaMutation(() => this.#completeCommandLocked(commands, command, result, generation));
3808
+ return this.#serializeReplicaMutation((repository) => this.#completeCommandLocked(commands, command, result, generation, repository));
3826
3809
  }
3827
- async #completeCommandLocked(commands, command, result, generation) {
3810
+ async #completeCommandLocked(commands, command, result, generation, repository) {
3828
3811
  if (result.clearRemoteId === true && result.remoteId !== undefined) {
3829
3812
  throw new Error('Offline command cannot return remoteId and clearRemoteId together.');
3830
3813
  }
@@ -3838,15 +3821,10 @@ class OfflineSyncService {
3838
3821
  const revision = result.serverRevision;
3839
3822
  const following = latestCommands.slice(latestIndex + 1);
3840
3823
  const rebased = result.clearRemoteId === true
3841
- ? following.map((item) => {
3842
- if (!this.#executor.withoutServerRevision) {
3843
- throw new Error('Offline command executor must implement withoutServerRevision to recreate a deleted remoteId row.');
3844
- }
3845
- return this.#executor.withoutServerRevision(item);
3846
- })
3824
+ ? following.map((item) => offlineCommandWithBaseRevision(item, null))
3847
3825
  : revision === undefined
3848
3826
  ? following
3849
- : following.map((item) => this.#executor.withServerRevision(item, revision));
3827
+ : following.map((item) => offlineCommandWithBaseRevision(item, revision));
3850
3828
  const current = await this.#rowForCommand(command);
3851
3829
  if (!this.#isCurrent(generation))
3852
3830
  return;
@@ -3891,7 +3869,7 @@ class OfflineSyncService {
3891
3869
  const rematerialized = await this.#rematerializeAggregate(awaitingPull, latestCommands, identityUpdatedBase);
3892
3870
  if (!this.#isCurrent(generation))
3893
3871
  return;
3894
- await this.#repository.transactReplica({
3872
+ await repository.transactReplica({
3895
3873
  putRows: rematerialized.putRows,
3896
3874
  releaseRemoteIds: result.clearRemoteId === true && current.identity.kind === 'generated' && current.identity.remoteId !== null
3897
3875
  ? [
@@ -3906,7 +3884,6 @@ class OfflineSyncService {
3906
3884
  : undefined,
3907
3885
  removeRows: rematerialized.removeRows,
3908
3886
  putCommands: [awaitingPull, ...rebased],
3909
- putReconciliationScopes: [{ userId: command.userId, scopeId: command.scopeId }],
3910
3887
  });
3911
3888
  const scope = { userId: command.userId, scopeId: command.scopeId };
3912
3889
  this.#pendingPullScopes.set(this.#scopeKey(scope), scope);
@@ -3935,7 +3912,7 @@ class OfflineSyncService {
3935
3912
  throw new Error(`Unknown offline replica source key "${sourceKey}".`);
3936
3913
  return schema;
3937
3914
  }
3938
- async #discardCommands(discarded) {
3915
+ async #discardCommands(discarded, repository) {
3939
3916
  const all = await this.#readKnownCommands();
3940
3917
  const discardedIds = new Set(discarded.map((command) => command.commandId));
3941
3918
  const affected = new Map();
@@ -3943,7 +3920,7 @@ class OfflineSyncService {
3943
3920
  affected.set(this.#aggregateKey(command), command);
3944
3921
  const remaining = all.filter((item) => !discardedIds.has(item.commandId));
3945
3922
  const rematerialized = await this.#rematerializeAffectedAggregates(affected, remaining);
3946
- await this.#repository.transactReplica({
3923
+ await repository.transactReplica({
3947
3924
  putRows: rematerialized.putRows,
3948
3925
  removeRows: rematerialized.removeRows,
3949
3926
  removeCommandIds: [...discardedIds],
@@ -4019,18 +3996,20 @@ class OfflineSyncService {
4019
3996
  }
4020
3997
  async #persistFailedCommand(command, error, generation, row, serverCommitUnknown = true) {
4021
3998
  const failed = this.#failedCommand(command, error, serverCommitUnknown);
4022
- const current = row === undefined ? await this.#rowForCommand(command) : row;
4023
- if (!this.#isCurrent(generation))
4024
- return;
4025
- if (current) {
4026
- await this.#repository.transactReplica({
4027
- putRows: [{ ...current, syncState: this.#replicaState(failed.state) }],
4028
- putCommands: [failed],
4029
- });
4030
- }
4031
- else {
4032
- await this.#repository.putCommand(failed);
4033
- }
3999
+ await this.#serializeReplicaMutation(async (repository) => {
4000
+ const current = row === undefined ? await this.#rowForCommand(command) : row;
4001
+ if (!this.#isCurrent(generation))
4002
+ return;
4003
+ if (current) {
4004
+ await repository.transactReplica({
4005
+ putRows: [{ ...current, syncState: this.#replicaState(failed.state) }],
4006
+ putCommands: [failed],
4007
+ });
4008
+ }
4009
+ else {
4010
+ await repository.putCommand(failed);
4011
+ }
4012
+ });
4034
4013
  if (!this.#isCurrent(generation))
4035
4014
  return;
4036
4015
  if (failed.state === 'retry_wait')
@@ -4230,7 +4209,7 @@ class OfflineSyncService {
4230
4209
  })));
4231
4210
  }
4232
4211
  #claimSendingCommand(command, generation) {
4233
- const transition = this.#serializeReplicaMutation(async () => {
4212
+ const transition = this.#serializeReplicaMutation(async (repository) => {
4234
4213
  if (!this.#isCurrent(generation))
4235
4214
  return null;
4236
4215
  const scope = { userId: command.userId, scopeId: command.scopeId };
@@ -4244,7 +4223,7 @@ class OfflineSyncService {
4244
4223
  retryAt: null,
4245
4224
  lastErrorCode: null,
4246
4225
  };
4247
- await this.#repository.putCommand(sending);
4226
+ await repository.putCommand(sending);
4248
4227
  return sending;
4249
4228
  });
4250
4229
  this.#sendingTransitions.add(transition);
@@ -4252,7 +4231,7 @@ class OfflineSyncService {
4252
4231
  return transition;
4253
4232
  }
4254
4233
  #markTransportStarted(command, generation) {
4255
- return this.#serializeReplicaMutation(async () => {
4234
+ return this.#serializeReplicaMutation(async (repository) => {
4256
4235
  if (!this.#isCurrent(generation))
4257
4236
  return null;
4258
4237
  const scope = { userId: command.userId, scopeId: command.scopeId };
@@ -4260,28 +4239,21 @@ class OfflineSyncService {
4260
4239
  if (!current || current.state !== 'sending')
4261
4240
  return null;
4262
4241
  const transportCommand = { ...current, serverCommitUnknown: true };
4263
- await this.#repository.putCommand(transportCommand);
4242
+ await repository.putCommand(transportCommand);
4264
4243
  return transportCommand;
4265
4244
  });
4266
4245
  }
4267
4246
  async #restorePendingPullScopes(userId, generation) {
4268
- if (!this.#repository.getReconciliationScopes)
4269
- return;
4270
- const durableScopes = await this.#repository.getReconciliationScopes(userId);
4247
+ const commands = await this.#readKnownCommands();
4271
4248
  if (!this.#isCurrent(generation) || this.#activeUserId !== userId)
4272
4249
  return;
4273
- const currentKeys = new Set(this.#knownScopes.keys());
4274
4250
  this.#pendingPullScopes.clear();
4275
- const revoked = [];
4276
- for (const scope of durableScopes) {
4251
+ for (const command of commands) {
4252
+ if (command.state !== 'awaiting_pull')
4253
+ continue;
4254
+ const scope = { userId: command.userId, scopeId: command.scopeId };
4277
4255
  const key = this.#scopeKey(scope);
4278
- if (scope.userId === userId && currentKeys.has(key))
4279
- this.#pendingPullScopes.set(key, scope);
4280
- else
4281
- revoked.push(scope);
4282
- }
4283
- if (revoked.length > 0) {
4284
- await this.#repository.transactReplica({ removeReconciliationScopes: revoked });
4256
+ this.#pendingPullScopes.set(key, scope);
4285
4257
  }
4286
4258
  }
4287
4259
  async #prunePullAttentions(userId, generation) {
@@ -4300,7 +4272,6 @@ class OfflineSyncService {
4300
4272
  if (!this.#isCurrent(generation))
4301
4273
  return;
4302
4274
  await this.#repository.transactReplica({
4303
- removeReconciliationScopes: [scope],
4304
4275
  removePullAttentions: [scope],
4305
4276
  });
4306
4277
  if (!this.#isCurrent(generation))
@@ -4310,10 +4281,6 @@ class OfflineSyncService {
4310
4281
  async #waitForSendingTransitions() {
4311
4282
  await Promise.allSettled([...this.#sendingTransitions]);
4312
4283
  }
4313
- async #payloadHash(payload) {
4314
- const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(this.#canonicalJson(payload)));
4315
- return [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, '0')).join('');
4316
- }
4317
4284
  #canonicalJson(value) {
4318
4285
  if (Array.isArray(value))
4319
4286
  return `[${value.map((item) => this.#canonicalJson(item)).join(',')}]`;
@@ -4887,6 +4854,12 @@ class SqliteOfflineRepository {
4887
4854
  #activeReaders = 0;
4888
4855
  #readersIdle = Promise.resolve();
4889
4856
  #resolveReadersIdle = null;
4857
+ #atomicMutationRevision = null;
4858
+ #atomicMutationCommitted = false;
4859
+ #atomicOperations = Promise.resolve();
4860
+ #readSnapshotActive = false;
4861
+ #atomicIdle = Promise.resolve();
4862
+ #resolveAtomicIdle = null;
4890
4863
  initialize() {
4891
4864
  this.#initialization ??= this.#open();
4892
4865
  return this.#initialization;
@@ -4931,9 +4904,6 @@ class SqliteOfflineRepository {
4931
4904
  async getReplicaCursor(scope) {
4932
4905
  return this.#withCommittedRead(() => this.#readReplicaCursor(scope));
4933
4906
  }
4934
- async getReconciliationScopes(userId) {
4935
- return this.#withCommittedRead(() => this.#readReconciliationScopes(userId));
4936
- }
4937
4907
  async getPullAttentions(userId) {
4938
4908
  return this.#withCommittedRead(() => this.#readPullAttentions(userId));
4939
4909
  }
@@ -4944,7 +4914,48 @@ class SqliteOfflineRepository {
4944
4914
  return this.#withCommittedRead(() => this.#readCommandsForUser(userId));
4945
4915
  }
4946
4916
  async runReadSnapshot(read) {
4947
- return this.#withCommittedRead(() => read(this.#reader()));
4917
+ if (this.#atomicMutationRevision !== null) {
4918
+ throw new Error('Use the repository passed to an atomic mutation for snapshot reads.');
4919
+ }
4920
+ return this.#transaction(async () => {
4921
+ this.#readSnapshotActive = true;
4922
+ try {
4923
+ return await read(this.#reader());
4924
+ }
4925
+ finally {
4926
+ this.#readSnapshotActive = false;
4927
+ }
4928
+ });
4929
+ }
4930
+ async [OFFLINE_REPOSITORY_ATOMIC_MUTATION](operation) {
4931
+ await this.initialize();
4932
+ await this.#writes;
4933
+ if (this.#atomicMutationRevision !== null) {
4934
+ throw new Error('Nested offline replica atomic mutations are not supported.');
4935
+ }
4936
+ this.#beginReaders();
4937
+ try {
4938
+ const databaseId = await this.#databaseConnection();
4939
+ this.#atomicOperations = Promise.resolve();
4940
+ this.#atomicMutationCommitted = false;
4941
+ this.#atomicIdle = new Promise((resolve) => {
4942
+ this.#resolveAtomicIdle = resolve;
4943
+ });
4944
+ this.#atomicMutationRevision = await this.#nativeTransaction(databaseId, () => this.#dataVersion(databaseId));
4945
+ const result = await operation(this.#atomicRepository());
4946
+ await this.#atomicOperations;
4947
+ if (!this.#atomicMutationCommitted) {
4948
+ await this.#queueAtomicOperation(() => this.#atomicTransaction(databaseId, async () => undefined, false));
4949
+ }
4950
+ return result;
4951
+ }
4952
+ finally {
4953
+ this.#atomicMutationRevision = null;
4954
+ this.#endReaders();
4955
+ this.#resolveAtomicIdle?.();
4956
+ this.#resolveAtomicIdle = null;
4957
+ this.#atomicIdle = Promise.resolve();
4958
+ }
4948
4959
  }
4949
4960
  async putCommand(command) {
4950
4961
  await this.#queueWrite((databaseId) => this.#putCommand(databaseId, command));
@@ -4971,98 +4982,92 @@ class SqliteOfflineRepository {
4971
4982
  ]);
4972
4983
  }
4973
4984
  async clearUser(userId) {
4974
- await this.#transaction(async (database) => {
4975
- const principal = canonicalOfflinePrincipalId(userId);
4976
- await this.#execute(database, 'DELETE FROM offline_session_manifests WHERE user_id = ?', [principal]);
4977
- await this.#execute(database, 'DELETE FROM offline_sync_commands WHERE user_id = ?', [principal]);
4978
- await this.#execute(database, 'DELETE FROM offline_replica_cursors WHERE user_id = ?', [principal]);
4979
- await this.#execute(database, 'DELETE FROM offline_reconciliation_scopes WHERE user_id = ?', [principal]);
4980
- await this.#execute(database, 'DELETE FROM offline_pull_attentions WHERE user_id = ?', [principal]);
4981
- for (const entity of this.#options.replicaSchema.entities) {
4982
- await this.#execute(database, `DELETE FROM ${entity.tableName} WHERE _offline_user_id = ?`, [principal]);
4983
- }
4984
- await this.#execute(database, 'UPDATE offline_metadata SET last_user_id = NULL WHERE id = 1 AND last_user_id = ?', [principal]);
4985
- });
4985
+ await this.#transaction((database) => this.#clearUser(database, userId));
4986
+ }
4987
+ async #clearUser(database, userId) {
4988
+ const principal = canonicalOfflinePrincipalId(userId);
4989
+ await this.#execute(database, 'DELETE FROM offline_session_manifests WHERE user_id = ?', [principal]);
4990
+ await this.#execute(database, 'DELETE FROM offline_sync_commands WHERE user_id = ?', [principal]);
4991
+ await this.#execute(database, 'DELETE FROM offline_replica_cursors WHERE user_id = ?', [principal]);
4992
+ await this.#execute(database, 'DELETE FROM offline_reconciliation_scopes WHERE user_id = ?', [principal]);
4993
+ await this.#execute(database, 'DELETE FROM offline_pull_attentions WHERE user_id = ?', [principal]);
4994
+ for (const entity of this.#options.replicaSchema.entities) {
4995
+ await this.#execute(database, `DELETE FROM ${entity.tableName} WHERE _offline_user_id = ?`, [principal]);
4996
+ }
4997
+ await this.#execute(database, 'UPDATE offline_metadata SET last_user_id = NULL WHERE id = 1 AND last_user_id = ?', [principal]);
4986
4998
  }
4987
4999
  async clearScope(scope) {
4988
- await this.#transaction(async (database) => {
4989
- const values = [canonicalOfflinePrincipalId(scope.userId), scope.scopeId];
4990
- const partitionSourceKeys = this.#options.replicaSchema.entities
4991
- .filter((entity) => entity.scope === 'partition')
4992
- .map((entity) => entity.sourceKey);
4993
- if (partitionSourceKeys.length > 0) {
4994
- await this.#execute(database, `DELETE FROM offline_sync_commands
5000
+ await this.#transaction((database) => this.#clearScope(database, scope));
5001
+ }
5002
+ async #clearScope(database, scope) {
5003
+ const values = [canonicalOfflinePrincipalId(scope.userId), scope.scopeId];
5004
+ const partitionSourceKeys = this.#options.replicaSchema.entities
5005
+ .filter((entity) => entity.scope === 'partition')
5006
+ .map((entity) => entity.sourceKey);
5007
+ if (partitionSourceKeys.length > 0) {
5008
+ await this.#execute(database, `DELETE FROM offline_sync_commands
4995
5009
  WHERE user_id = ? AND scope_id = ? AND source_key IN (${partitionSourceKeys.map(() => '?').join(', ')})`, [...values, ...partitionSourceKeys]);
4996
- }
4997
- await this.#execute(database, 'DELETE FROM offline_replica_cursors WHERE user_id = ? AND scope_id = ?', values);
4998
- await this.#execute(database, 'DELETE FROM offline_reconciliation_scopes WHERE user_id = ? AND scope_id = ?', values);
4999
- await this.#execute(database, 'DELETE FROM offline_pull_attentions WHERE user_id = ? AND scope_id = ?', values);
5000
- for (const entity of this.#options.replicaSchema.entities) {
5001
- if (entity.scope !== 'partition')
5002
- continue;
5003
- await this.#execute(database, `DELETE FROM ${entity.tableName} WHERE _offline_user_id = ? AND _offline_scope_id = ?`, values);
5004
- }
5005
- });
5010
+ }
5011
+ await this.#execute(database, 'DELETE FROM offline_replica_cursors WHERE user_id = ? AND scope_id = ?', values);
5012
+ await this.#execute(database, 'DELETE FROM offline_reconciliation_scopes WHERE user_id = ? AND scope_id = ?', values);
5013
+ await this.#execute(database, 'DELETE FROM offline_pull_attentions WHERE user_id = ? AND scope_id = ?', values);
5014
+ for (const entity of this.#options.replicaSchema.entities) {
5015
+ if (entity.scope !== 'partition')
5016
+ continue;
5017
+ await this.#execute(database, `DELETE FROM ${entity.tableName} WHERE _offline_user_id = ? AND _offline_scope_id = ?`, values);
5018
+ }
5006
5019
  }
5007
5020
  async transactReplica(transaction) {
5008
5021
  for (const row of transaction.putRows ?? [])
5009
5022
  this.#validateReplicaRow(row);
5010
- await this.#transaction(async (databaseId) => {
5011
- const releases = new Map();
5012
- for (const release of transaction.releaseRemoteIds ?? []) {
5013
- this.#assertValidReleaseRemoteId(release.remoteId);
5014
- const key = this.#replicaRowKey(release);
5015
- if (releases.has(key)) {
5016
- throw new Error(`Offline replica remoteId release is duplicated for ${release.sourceKey}/${canonicalOfflineReplicaIdentity(release.identity)}.`);
5017
- }
5018
- releases.set(key, release);
5019
- }
5020
- const consumedReleases = new Set();
5021
- for (const row of transaction.putRows ?? []) {
5022
- const key = this.#replicaRowKey(row);
5023
- const release = releases.get(key);
5024
- await this.#putReplicaRow(databaseId, row, release);
5025
- if (release)
5026
- consumedReleases.add(key);
5027
- }
5028
- if (consumedReleases.size !== releases.size) {
5029
- throw new Error('Offline replica remoteId release must match an existing row in putRows.');
5030
- }
5031
- for (const row of transaction.removeRows ?? [])
5032
- await this.#removeReplicaRow(databaseId, row);
5033
- for (const command of transaction.putCommands ?? [])
5034
- await this.#putCommand(databaseId, command);
5035
- for (const commandId of transaction.removeCommandIds ?? []) {
5036
- await this.#execute(databaseId, 'DELETE FROM offline_sync_commands WHERE command_id = ?', [commandId]);
5037
- }
5038
- for (const cursor of transaction.putCursors ?? [])
5039
- await this.#putReplicaCursor(databaseId, cursor);
5040
- for (const scope of transaction.putReconciliationScopes ?? []) {
5041
- await this.#execute(databaseId, `INSERT INTO offline_reconciliation_scopes (user_id, scope_id) VALUES (?, ?)
5042
- ON CONFLICT(user_id, scope_id) DO NOTHING`, [canonicalOfflinePrincipalId(scope.userId), scope.scopeId]);
5043
- }
5044
- for (const scope of transaction.removeReconciliationScopes ?? []) {
5045
- await this.#execute(databaseId, 'DELETE FROM offline_reconciliation_scopes WHERE user_id = ? AND scope_id = ?', [
5046
- canonicalOfflinePrincipalId(scope.userId),
5047
- scope.scopeId,
5048
- ]);
5023
+ const apply = (databaseId) => this.#applyReplicaTransaction(databaseId, transaction);
5024
+ await this.#transaction(apply);
5025
+ }
5026
+ async #applyReplicaTransaction(databaseId, transaction) {
5027
+ const releases = new Map();
5028
+ for (const release of transaction.releaseRemoteIds ?? []) {
5029
+ this.#assertValidReleaseRemoteId(release.remoteId);
5030
+ const key = this.#replicaRowKey(release);
5031
+ if (releases.has(key)) {
5032
+ throw new Error(`Offline replica remoteId release is duplicated for ${release.sourceKey}/${canonicalOfflineReplicaIdentity(release.identity)}.`);
5049
5033
  }
5050
- for (const attention of transaction.putPullAttentions ?? []) {
5051
- await this.#execute(databaseId, `INSERT INTO offline_pull_attentions (user_id, scope_id, reason, status) VALUES (?, ?, ?, ?)
5034
+ releases.set(key, release);
5035
+ }
5036
+ const consumedReleases = new Set();
5037
+ for (const row of transaction.putRows ?? []) {
5038
+ const key = this.#replicaRowKey(row);
5039
+ const release = releases.get(key);
5040
+ await this.#putReplicaRow(databaseId, row, release);
5041
+ if (release)
5042
+ consumedReleases.add(key);
5043
+ }
5044
+ if (consumedReleases.size !== releases.size) {
5045
+ throw new Error('Offline replica remoteId release must match an existing row in putRows.');
5046
+ }
5047
+ for (const row of transaction.removeRows ?? [])
5048
+ await this.#removeReplicaRow(databaseId, row);
5049
+ for (const command of transaction.putCommands ?? [])
5050
+ await this.#putCommand(databaseId, command);
5051
+ for (const commandId of transaction.removeCommandIds ?? []) {
5052
+ await this.#execute(databaseId, 'DELETE FROM offline_sync_commands WHERE command_id = ?', [commandId]);
5053
+ }
5054
+ for (const cursor of transaction.putCursors ?? [])
5055
+ await this.#putReplicaCursor(databaseId, cursor);
5056
+ for (const attention of transaction.putPullAttentions ?? []) {
5057
+ await this.#execute(databaseId, `INSERT INTO offline_pull_attentions (user_id, scope_id, reason, status) VALUES (?, ?, ?, ?)
5052
5058
  ON CONFLICT(user_id, scope_id) DO UPDATE SET reason = excluded.reason, status = excluded.status`, [
5053
- canonicalOfflinePrincipalId(attention.userId),
5054
- attention.scopeId,
5055
- attention.reason,
5056
- attention.status === undefined ? null : attention.status,
5057
- ]);
5058
- }
5059
- for (const scope of transaction.removePullAttentions ?? []) {
5060
- await this.#execute(databaseId, 'DELETE FROM offline_pull_attentions WHERE user_id = ? AND scope_id = ?', [
5061
- canonicalOfflinePrincipalId(scope.userId),
5062
- scope.scopeId,
5063
- ]);
5064
- }
5065
- });
5059
+ canonicalOfflinePrincipalId(attention.userId),
5060
+ attention.scopeId,
5061
+ attention.reason,
5062
+ attention.status === undefined ? null : attention.status,
5063
+ ]);
5064
+ }
5065
+ for (const scope of transaction.removePullAttentions ?? []) {
5066
+ await this.#execute(databaseId, 'DELETE FROM offline_pull_attentions WHERE user_id = ? AND scope_id = ?', [
5067
+ canonicalOfflinePrincipalId(scope.userId),
5068
+ scope.scopeId,
5069
+ ]);
5070
+ }
5066
5071
  }
5067
5072
  async #open() {
5068
5073
  try {
@@ -5175,8 +5180,9 @@ class SqliteOfflineRepository {
5175
5180
  async #nativeTransaction(databaseId, run) {
5176
5181
  await this.#sqlite.beginTransaction({ databaseId });
5177
5182
  try {
5178
- await run();
5183
+ const result = await run();
5179
5184
  await this.#sqlite.commitTransaction({ databaseId });
5185
+ return result;
5180
5186
  }
5181
5187
  catch (error) {
5182
5188
  await this.#sqlite.rollbackTransaction({ databaseId });
@@ -5257,12 +5263,6 @@ class SqliteOfflineRepository {
5257
5263
  return null;
5258
5264
  return { ...scope, cursor: this.#string(row['cursor']) };
5259
5265
  }
5260
- async #readReconciliationScopes(userId) {
5261
- const rows = await this.#query('SELECT scope_id FROM offline_reconciliation_scopes WHERE user_id = ? ORDER BY scope_id', [
5262
- canonicalOfflinePrincipalId(userId),
5263
- ]);
5264
- return rows.map((row) => ({ userId, scopeId: this.#string(row['scope_id']) }));
5265
- }
5266
5266
  async #readPullAttentions(userId) {
5267
5267
  const rows = await this.#query('SELECT scope_id, reason, status FROM offline_pull_attentions WHERE user_id = ? ORDER BY scope_id', [
5268
5268
  canonicalOfflinePrincipalId(userId),
@@ -5303,14 +5303,52 @@ class SqliteOfflineRepository {
5303
5303
  },
5304
5304
  getReplicaRowByRemoteIdentity: (scope, sourceKey, identity) => this.#readReplicaRowByRemoteIdentity(scope, sourceKey, identity),
5305
5305
  getReplicaCursor: (scope) => this.#readReplicaCursor(scope),
5306
- getReconciliationScopes: (userId) => this.#readReconciliationScopes(userId),
5307
5306
  getPullAttentions: (userId) => this.#readPullAttentions(userId),
5308
5307
  getCommands: (scope) => this.#readCommands(scope),
5309
5308
  getCommandsForUser: (userId) => this.#readCommandsForUser(userId),
5310
5309
  };
5311
5310
  }
5311
+ #atomicRepository() {
5312
+ const reader = this.#reader();
5313
+ const atomicTransaction = (run, marksCommit = true) => this.#queueAtomicOperation(() => this.#atomicTransaction(this.#databaseId, run, marksCommit));
5314
+ return {
5315
+ initialize: () => Promise.resolve(),
5316
+ ...reader,
5317
+ runReadSnapshot: (read) => this.#queueAtomicOperation(() => this.#nativeTransaction(this.#databaseId, async () => {
5318
+ this.#readSnapshotActive = true;
5319
+ try {
5320
+ return await read(reader);
5321
+ }
5322
+ finally {
5323
+ this.#readSnapshotActive = false;
5324
+ }
5325
+ })),
5326
+ putCommand: (command) => atomicTransaction((databaseId) => this.#putCommand(databaseId, command)),
5327
+ replaceCommand: (command) => atomicTransaction((databaseId) => this.#putCommand(databaseId, command)),
5328
+ removeCommand: (commandId) => atomicTransaction((databaseId) => this.#execute(databaseId, 'DELETE FROM offline_sync_commands WHERE command_id = ?', [commandId])),
5329
+ putPullAttention: (attention) => atomicTransaction((databaseId) => this.#applyReplicaTransaction(databaseId, { putPullAttentions: [attention] })),
5330
+ removePullAttention: (scope) => atomicTransaction((databaseId) => this.#applyReplicaTransaction(databaseId, { removePullAttentions: [scope] })),
5331
+ setLastUserId: (userId) => atomicTransaction((databaseId) => this.#execute(databaseId, `INSERT INTO offline_metadata (id, schema_version, last_user_id) VALUES (1, ?, ?)
5332
+ ON CONFLICT(id) DO UPDATE SET schema_version = excluded.schema_version, last_user_id = excluded.last_user_id`, [OFFLINE_SCHEMA_VERSION, canonicalOfflinePrincipalId(userId)])),
5333
+ putSessionManifest: (userId, value) => atomicTransaction((databaseId) => this.#execute(databaseId, `INSERT INTO offline_session_manifests (user_id, value_json) VALUES (?, ?)
5334
+ ON CONFLICT(user_id) DO UPDATE SET value_json = excluded.value_json`, [canonicalOfflinePrincipalId(userId), JSON.stringify(value)])),
5335
+ clearUser: (userId) => atomicTransaction((databaseId) => this.#clearUser(databaseId, userId)),
5336
+ clearScope: (scope) => atomicTransaction((databaseId) => this.#clearScope(databaseId, scope)),
5337
+ transactReplica: (transaction) => {
5338
+ for (const row of transaction.putRows ?? [])
5339
+ this.#validateReplicaRow(row);
5340
+ return atomicTransaction((databaseId) => this.#applyReplicaTransaction(databaseId, transaction));
5341
+ },
5342
+ };
5343
+ }
5312
5344
  async #withCommittedRead(operation) {
5313
5345
  await this.initialize();
5346
+ if (this.#readSnapshotActive) {
5347
+ return operation();
5348
+ }
5349
+ if (this.#atomicMutationRevision !== null) {
5350
+ return this.#queueAtomicOperation(operation);
5351
+ }
5314
5352
  await this.#writes;
5315
5353
  this.#beginReaders();
5316
5354
  try {
@@ -5343,6 +5381,9 @@ class SqliteOfflineRepository {
5343
5381
  return this.#queueWrite((databaseId) => this.#execute(databaseId, statement, values));
5344
5382
  }
5345
5383
  #queueWrite(run) {
5384
+ if (this.#atomicMutationRevision !== null) {
5385
+ return this.#atomicIdle.then(() => this.#queueWrite(run));
5386
+ }
5346
5387
  const write = this.#writes.then(async () => {
5347
5388
  if (this.#activeReaders > 0)
5348
5389
  await this.#readersIdle;
@@ -5352,22 +5393,45 @@ class SqliteOfflineRepository {
5352
5393
  return write;
5353
5394
  }
5354
5395
  #transaction(run) {
5355
- const write = this.#writes.then(async () => {
5396
+ if (this.#atomicMutationRevision !== null) {
5397
+ return this.#atomicIdle.then(() => this.#transaction(run));
5398
+ }
5399
+ const transaction = this.#writes.then(async () => {
5356
5400
  if (this.#activeReaders > 0)
5357
5401
  await this.#readersIdle;
5358
5402
  const databaseId = await this.#databaseConnection();
5359
- await this.#sqlite.beginTransaction({ databaseId });
5360
- try {
5361
- await run(databaseId);
5362
- await this.#sqlite.commitTransaction({ databaseId });
5363
- }
5364
- catch (error) {
5365
- await this.#sqlite.rollbackTransaction({ databaseId });
5366
- throw error;
5367
- }
5403
+ return this.#nativeTransaction(databaseId, () => run(databaseId));
5368
5404
  });
5369
- this.#writes = write.catch(() => undefined);
5370
- return write;
5405
+ this.#writes = transaction.then(() => undefined, () => undefined);
5406
+ return transaction;
5407
+ }
5408
+ async #atomicTransaction(databaseId, run, marksCommit = true) {
5409
+ const expected = this.#atomicMutationRevision;
5410
+ if (expected === null)
5411
+ throw new Error('Offline replica atomic mutation is not active.');
5412
+ const result = await this.#nativeTransaction(databaseId, async () => {
5413
+ // A write, even when it leaves the value unchanged, obtains SQLite's
5414
+ // RESERVED lock before the revision check. No second connection can
5415
+ // commit between this check and the transaction commit.
5416
+ await this.#execute(databaseId, 'UPDATE offline_metadata SET schema_version = schema_version WHERE id = 1');
5417
+ const actual = await this.#dataVersion(databaseId);
5418
+ if (actual !== expected) {
5419
+ throw new Error('Offline replica changed through another SQLite connection; retry the operation from fresh state.');
5420
+ }
5421
+ return run(databaseId);
5422
+ });
5423
+ if (marksCommit)
5424
+ this.#atomicMutationCommitted = true;
5425
+ return result;
5426
+ }
5427
+ #queueAtomicOperation(run) {
5428
+ const operation = this.#atomicOperations.then(run);
5429
+ this.#atomicOperations = operation.then(() => undefined, () => undefined);
5430
+ return operation;
5431
+ }
5432
+ async #dataVersion(databaseId) {
5433
+ const rows = await this.#queryDatabase(databaseId, 'PRAGMA data_version');
5434
+ return this.#number(rows[0]?.['data_version']);
5371
5435
  }
5372
5436
  #command(row) {
5373
5437
  return {
@@ -5383,7 +5447,6 @@ class SqliteOfflineRepository {
5383
5447
  ? {}
5384
5448
  : { localOnlyFootprint: this.#parse(row['local_only_footprint_json']) }),
5385
5449
  replicaMutation: this.#string(row['replica_mutation']),
5386
- payloadHash: this.#string(row['payload_hash']),
5387
5450
  baseRevision: this.#parseNullable(row['base_revision_json']),
5388
5451
  state: this.#string(row['state']),
5389
5452
  attempts: this.#number(row['attempts']),
@@ -5423,7 +5486,7 @@ class SqliteOfflineRepository {
5423
5486
  JSON.stringify(command.payload),
5424
5487
  command.localOnlyFootprint === undefined ? null : JSON.stringify(command.localOnlyFootprint),
5425
5488
  command.replicaMutation ?? 'upsert',
5426
- command.payloadHash,
5489
+ '',
5427
5490
  this.#stringifyNullable(command.baseRevision),
5428
5491
  command.state,
5429
5492
  command.attempts,
@@ -5748,7 +5811,6 @@ const READ_CACHE_ONLY_COMMAND_EXECUTOR = {
5748
5811
  execute: async () => {
5749
5812
  throw new Error('This offline provider is configured as a read-only cache.');
5750
5813
  },
5751
- withServerRevision: (command) => command,
5752
5814
  };
5753
5815
  const READ_CACHE_ONLY_REPLICA_PULLER = {
5754
5816
  pull: async (request) => ({
@@ -5944,5 +6006,5 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.17", ngImpo
5944
6006
  * Generated bundle index. Do not edit.
5945
6007
  */
5946
6008
 
5947
- export { COMMUNITY_SQLITE, DEFAULT_OFFLINE_COMMAND_HOOKS, IonicOfflineRepository, OFFLINE_AGGREGATE_INTENT_PROJECTOR, OFFLINE_BYPASS, OFFLINE_COMMAND_EXECUTOR, OFFLINE_COMMAND_HOOKS, OFFLINE_KIT_OPTIONS, OFFLINE_MUTATION_REQUEST_POLICIES, OFFLINE_REPLICA_PROJECTOR, OFFLINE_REPLICA_PULLER, OFFLINE_REPOSITORY, OFFLINE_REQUEST_POLICIES, OFFLINE_RESPONSE_HEADER, OFFLINE_RETRY_RANDOM, OFFLINE_SCHEMA_VERSION, OFFLINE_SYNC_CONTEXT, OfflineCommandInFlightError, OfflineCoordinatorService, OfflineMutationPolicyConflictError, OfflineMutationProtocolError, OfflineMutationRequestPolicyRegistry, OfflineNetworkService, OfflineOutboxCapacityError, OfflinePayloadValidationError, OfflineReplicaMutationCoordinator, OfflineReplicaPullService, OfflineReplicaSchemaMismatchError, OfflineRequestFallbackService, OfflineRequestPolicyRegistry, OfflineSessionService, OfflineStorageUnavailableError, OfflineSyncService, SqliteOfflineRepository, assertOfflineLocalId, assertOfflineReplicaGeneratedRemoteId, assertOfflineReplicaNaturalKeyBaseline, assertSupportedOfflineMode, booleanColumn, canonicalOfflineCommandIdentity, canonicalOfflinePrincipalId, canonicalOfflineRemoteIdentity, canonicalOfflineReplicaIdentity, canonicalOfflineReplicaRowKey, commandFootprintKeys, commandIdentityFromReplicaIdentity, commandIdentityMatchesReplicaRow, createCommunitySqliteDriver, createOfflineAuthBridge, createRandomOfflineEncryptionKey, datetime, decodeOfflineReplicaValues, defineOfflineReplicaSchema, defineReplicaEntity, encodeOfflineReplicaValues, generatedId, ignored, integer, isOfflineAggregateIntentConflict, isOfflineFallbackError, isOfflineStorageUnavailableError, json, localOnly, naturalKey, normalizeOfflineNaturalKey, normalizeOfflineReplicaPullPage, nullable, offlineAggregateIntentMutations, offlineCommandLookupIdentity, offlineCommandTargetFromReplicaRow, offlineGeneratedReplicaIdentity, offlineInterceptor, offlineNaturalKeyFromValues, offlineNaturalReplicaIdentity, offlineReplicaRemoteIdentity, offlineRetryDelayMs, offlineSessionManifestAllows, parseOfflineCommandIdentity, parseOfflineMutationEnvelope, parseOfflinePrincipalId, projectOfflineReplicaValues, provideOffline, provideOfflineMutationRequestPolicy, provideOfflineRequestPolicy, real, replicaAddressFromIdentity, requirePositiveOfflineInteger, selectOfflineRepository, serializeOfflineCommandIdentity, sha256OfflineReplicaSchema, supportsSynchronizedOfflineRepository, text };
6009
+ export { COMMUNITY_SQLITE, DEFAULT_OFFLINE_COMMAND_HOOKS, IonicOfflineRepository, OFFLINE_AGGREGATE_INTENT_PROJECTOR, OFFLINE_BYPASS, OFFLINE_COMMAND_EXECUTOR, OFFLINE_COMMAND_HOOKS, OFFLINE_KIT_OPTIONS, OFFLINE_MUTATION_REQUEST_POLICIES, OFFLINE_REPLICA_PROJECTOR, OFFLINE_REPLICA_PULLER, OFFLINE_REPOSITORY, OFFLINE_REQUEST_POLICIES, OFFLINE_RESPONSE_HEADER, OFFLINE_RETRY_RANDOM, OFFLINE_SCHEMA_VERSION, OFFLINE_SYNC_CONTEXT, OfflineCommandInFlightError, OfflineCoordinatorService, OfflineMutationPolicyConflictError, OfflineMutationProtocolError, OfflineMutationRequestPolicyRegistry, OfflineNetworkService, OfflineOutboxCapacityError, OfflinePayloadValidationError, OfflineReplicaMutationCoordinator, OfflineReplicaPullService, OfflineReplicaSchemaMismatchError, OfflineRequestFallbackService, OfflineRequestPolicyRegistry, OfflineSessionService, OfflineStorageUnavailableError, OfflineSyncService, SqliteOfflineRepository, assertOfflineLocalId, assertOfflineReplicaGeneratedRemoteId, assertOfflineReplicaNaturalKeyBaseline, assertSupportedOfflineMode, booleanColumn, canonicalOfflineCommandIdentity, canonicalOfflinePrincipalId, canonicalOfflineRemoteIdentity, canonicalOfflineReplicaIdentity, canonicalOfflineReplicaRowKey, commandFootprintKeys, commandIdentityFromReplicaIdentity, commandIdentityMatchesReplicaRow, createCommunitySqliteDriver, createOfflineAuthBridge, createRandomOfflineEncryptionKey, datetime, decodeOfflineReplicaValues, defineOfflineReplicaSchema, defineReplicaEntity, encodeOfflineReplicaValues, generatedId, ignored, integer, isOfflineAggregateIntentConflict, isOfflineFallbackError, isOfflineStorageUnavailableError, json, localOnly, naturalKey, normalizeOfflineNaturalKey, normalizeOfflineReplicaPullPage, nullable, offlineAggregateIntentMutations, offlineCommandLookupIdentity, offlineCommandTargetFromReplicaRow, offlineCommandWithBaseRevision, offlineGeneratedReplicaIdentity, offlineInterceptor, offlineNaturalKeyFromValues, offlineNaturalReplicaIdentity, offlineReplicaRemoteIdentity, offlineRetryDelayMs, offlineSessionManifestAllows, parseOfflineCommandIdentity, parseOfflineMutationEnvelope, parseOfflinePrincipalId, projectOfflineReplicaValues, provideOffline, provideOfflineMutationRequestPolicy, provideOfflineRequestPolicy, real, replicaAddressFromIdentity, requirePositiveOfflineInteger, selectOfflineRepository, serializeOfflineCommandIdentity, sha256OfflineReplicaSchema, supportsSynchronizedOfflineRepository, text };
5948
6010
  //# sourceMappingURL=rdlabo-ionic-angular-kit-offline.mjs.map