@rdlabo/ionic-angular-kit 22.0.0-8 → 22.0.0-beta.pr102.sha1c53fd4f57fa

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.
@@ -7,7 +7,7 @@ import { App } from '@capacitor/app';
7
7
  import { Network } from '@capacitor/network';
8
8
  import { Capacitor } from '@capacitor/core';
9
9
  import { HttpErrorResponse, HttpContextToken, HttpResponse } from '@angular/common/http';
10
- import { defer, from, map as map$1, catchError, throwError, concatMap, materialize, connect, concat, of, ReplaySubject, take, Observable, dematerialize, EMPTY, tap } from 'rxjs';
10
+ import { defer, from, map as map$1, concatMap, EMPTY, of, catchError, throwError, materialize, connect, concat, ReplaySubject, filter, NEVER, race, take, Observable, dematerialize, tap } from 'rxjs';
11
11
 
12
12
  const MAX_OFFLINE_NATURAL_KEY_TEXT_BYTES = 1024;
13
13
  const IDENTIFIER_PATTERN = /^[a-z][a-z0-9_]*$/;
@@ -933,6 +933,47 @@ function offlineCommandLookupIdentity(identity) {
933
933
  * This symbol is intentionally not re-exported from the package entry point.
934
934
  */
935
935
  const OFFLINE_REPOSITORY_ATOMIC_MUTATION = Symbol('OFFLINE_REPOSITORY_ATOMIC_MUTATION');
936
+ /** Internal typed boundary for a local write that is safe to recompute once from a fresh snapshot. */
937
+ class OfflineReplicaTransientWriteError extends Error {
938
+ constructor(reason, message, options) {
939
+ super(message, options);
940
+ this.reason = reason;
941
+ this.name = 'OfflineReplicaTransientWriteError';
942
+ }
943
+ }
944
+ function transientSqliteLockReason(error) {
945
+ const code = typeof error === 'object' && error !== null && typeof error.code === 'string'
946
+ ? error.code.toUpperCase()
947
+ : '';
948
+ const message = error instanceof Error ? error.message : typeof error === 'string' ? error : '';
949
+ const normalizedMessage = message.toUpperCase();
950
+ if (code.includes('SQLITE_BUSY') || normalizedMessage.includes('SQLITE_BUSY')) {
951
+ return 'sqlite_busy';
952
+ }
953
+ if (code.includes('SQLITE_LOCKED') ||
954
+ normalizedMessage.includes('SQLITE_LOCKED') ||
955
+ message.includes('database is locked') ||
956
+ message.includes('database table is locked')) {
957
+ return 'sqlite_locked';
958
+ }
959
+ return null;
960
+ }
961
+ /** Returns whether SQLite reported a transient busy/locked condition in any supported error shape. */
962
+ function isTransientSqliteLockError(error) {
963
+ return error instanceof OfflineReplicaTransientWriteError
964
+ ? error.reason === 'sqlite_busy' || error.reason === 'sqlite_locked'
965
+ : transientSqliteLockReason(error) !== null;
966
+ }
967
+ function normalizeOfflineReplicaTransientWriteError(error) {
968
+ if (error instanceof OfflineReplicaTransientWriteError)
969
+ return error;
970
+ const reason = transientSqliteLockReason(error);
971
+ if (reason) {
972
+ const message = error instanceof Error ? error.message : typeof error === 'string' ? error : '';
973
+ return new OfflineReplicaTransientWriteError(reason, message || (reason === 'sqlite_busy' ? 'SQLite is busy.' : 'SQLite database is locked.'), { cause: error });
974
+ }
975
+ return error;
976
+ }
936
977
 
937
978
  /** Current durable storage schema used by both web and native repositories. */
938
979
  const OFFLINE_SCHEMA_VERSION = 2;
@@ -1171,29 +1212,21 @@ class IonicOfflineRepository {
1171
1212
  return commands;
1172
1213
  });
1173
1214
  }
1215
+ /** @deprecated Use {@link transactReplica} with `putCommands`. */
1174
1216
  replaceCommand(command) {
1175
1217
  return this.putCommand(command);
1176
1218
  }
1177
- async removeCommand(commandId) {
1178
- await this.initialize();
1179
- await this.#mutateRecord(OUTBOX_KEY, (commands) => {
1180
- delete commands[commandId];
1181
- return commands;
1182
- });
1219
+ /** @deprecated Use {@link transactReplica} with `removeCommandIds`. */
1220
+ removeCommand(commandId) {
1221
+ return this.transactReplica({ removeCommandIds: [commandId] });
1183
1222
  }
1184
- async putPullAttention(attention) {
1185
- await this.initialize();
1186
- await this.#mutateRecord(PULL_ATTENTIONS_KEY, (attentions) => {
1187
- attentions[this.#cursorKey(attention)] = attention;
1188
- return attentions;
1189
- });
1223
+ /** @deprecated Use {@link transactReplica} with `putPullAttentions`. */
1224
+ putPullAttention(attention) {
1225
+ return this.transactReplica({ putPullAttentions: [attention] });
1190
1226
  }
1191
- async removePullAttention(scope) {
1192
- await this.initialize();
1193
- await this.#mutateRecord(PULL_ATTENTIONS_KEY, (attentions) => {
1194
- delete attentions[this.#cursorKey(scope)];
1195
- return attentions;
1196
- });
1227
+ /** @deprecated Use {@link transactReplica} with `removePullAttentions`. */
1228
+ removePullAttention(scope) {
1229
+ return this.transactReplica({ removePullAttentions: [scope] });
1197
1230
  }
1198
1231
  async clearUser(userId) {
1199
1232
  await this.initialize();
@@ -1794,7 +1827,7 @@ class OfflineReplicaMutationCoordinator {
1794
1827
  return this.#enqueue(() => {
1795
1828
  if (!this.#repository)
1796
1829
  throw new Error('Offline repository is not configured.');
1797
- const atomicMutation = this.#repository?.[OFFLINE_REPOSITORY_ATOMIC_MUTATION];
1830
+ const atomicMutation = this.#repository[OFFLINE_REPOSITORY_ATOMIC_MUTATION];
1798
1831
  return atomicMutation ? atomicMutation.call(this.#repository, operation) : operation(this.#repository);
1799
1832
  });
1800
1833
  }
@@ -2228,7 +2261,7 @@ class OfflineReplicaPullService {
2228
2261
  { putRows, removeRows },
2229
2262
  { putRows: projection?.putRows ?? [], removeRows: projection?.removeRows ?? [] },
2230
2263
  ]);
2231
- const rematerialized = await this.#rematerializePendingAggregates(scope, userCommands, scopeCommands, confirmedAndProjected, putCommands, removeCommandIds, rematerializeAfter);
2264
+ const rematerialized = await this.#rematerializePendingAggregates(userCommands, scopeCommands, confirmedAndProjected, putCommands, removeCommandIds, rematerializeAfter);
2232
2265
  const finalRows = this.#mergeRowMutations([confirmedAndProjected, rematerialized]);
2233
2266
  const removedCommands = [...removeCommandIds]
2234
2267
  .map((commandId) => userCommands.find((command) => command.commandId === commandId) ??
@@ -2369,7 +2402,7 @@ class OfflineReplicaPullService {
2369
2402
  this.#assertPullChange(change, index);
2370
2403
  }
2371
2404
  }
2372
- async #rematerializePendingAggregates(scope, userCommands, scopeCommands, currentRows, putCommands, removeCommandIds, seeds) {
2405
+ async #rematerializePendingAggregates(userCommands, scopeCommands, currentRows, putCommands, removeCommandIds, seeds) {
2373
2406
  const remaining = [...userCommands, ...scopeCommands]
2374
2407
  .filter((command, index, all) => all.findIndex((candidate) => candidate.commandId === command.commandId) === index)
2375
2408
  .filter((command) => !removeCommandIds.has(command.commandId))
@@ -2433,7 +2466,6 @@ class OfflineReplicaPullService {
2433
2466
  putRows.push(...(mutations.putRows ?? []));
2434
2467
  removeRows.push(...(mutations.removeRows ?? []));
2435
2468
  }
2436
- void scope;
2437
2469
  return { putRows, removeRows };
2438
2470
  }
2439
2471
  async #overlayBaseRow(command, overlay, removed) {
@@ -2824,6 +2856,15 @@ class OfflinePayloadValidationError extends Error {
2824
2856
  this.name = 'OfflinePayloadValidationError';
2825
2857
  }
2826
2858
  }
2859
+ /** A foreground durable-command send reached a terminal server-side state. */
2860
+ class OfflineImmediateCommandRejectedError extends Error {
2861
+ constructor(state, code) {
2862
+ super(`Immediate offline command delivery ended in ${state}${code ? ` (${code})` : ''}.`);
2863
+ this.state = state;
2864
+ this.code = code;
2865
+ this.name = 'OfflineImmediateCommandRejectedError';
2866
+ }
2867
+ }
2827
2868
  /** Raised before persistence when retaining another command would exceed the configured durable Outbox capacity. */
2828
2869
  class OfflineOutboxCapacityError extends Error {
2829
2870
  constructor(reason, currentCommands, currentBytes) {
@@ -2896,6 +2937,7 @@ class OfflineSyncService {
2896
2937
  #flushTransitions;
2897
2938
  #generation;
2898
2939
  #sendingTransitions;
2940
+ #commandSendTransitions;
2899
2941
  #retryTimer;
2900
2942
  /** When non-null, automatic flushes pull only foreground scopes plus Outbox scopes. */
2901
2943
  #foregroundScopePolicy;
@@ -2930,6 +2972,7 @@ class OfflineSyncService {
2930
2972
  this.#flushTransitions = new Set();
2931
2973
  this.#generation = 0;
2932
2974
  this.#sendingTransitions = new Set();
2975
+ this.#commandSendTransitions = new Map();
2933
2976
  this.#retryTimer = null;
2934
2977
  /** When non-null, automatic flushes pull only foreground scopes plus Outbox scopes. */
2935
2978
  this.#foregroundScopePolicy = null;
@@ -3098,7 +3141,7 @@ class OfflineSyncService {
3098
3141
  await this.#ensureInitialized();
3099
3142
  if (!this.#isCurrent(generation))
3100
3143
  throw new Error('Offline session changed before prepared replacement.');
3101
- const knownCommands = await this.#readKnownCommands();
3144
+ const knownCommands = await this.#readKnownCommands(repository);
3102
3145
  const replaced = knownCommands.find((command) => command.commandId === commandId);
3103
3146
  if (!replaced)
3104
3147
  throw new Error(`Offline command ${commandId} no longer exists.`);
@@ -3123,7 +3166,7 @@ class OfflineSyncService {
3123
3166
  await this.#ensureInitialized();
3124
3167
  if (!this.#isCurrent(generation))
3125
3168
  throw new Error('Offline session changed before prepared aggregate replacement.');
3126
- const knownCommands = await this.#readKnownCommands();
3169
+ const knownCommands = await this.#readKnownCommands(repository);
3127
3170
  const selected = knownCommands.find((command) => command.commandId === commandId);
3128
3171
  if (!selected)
3129
3172
  throw new Error(`Offline command ${commandId} no longer exists.`);
@@ -3138,7 +3181,7 @@ class OfflineSyncService {
3138
3181
  const materializations = [];
3139
3182
  for (const [index, entry] of prepared.entries()) {
3140
3183
  this.#assertEnqueueScope(session, entry.request.scopeId);
3141
- materializations.push(await this.#materializeEnqueue(session.userId, entry.request, replaced[index]));
3184
+ materializations.push(await this.#materializeEnqueue(session.userId, entry.request, repository, replaced[index]));
3142
3185
  }
3143
3186
  const retained = knownCommands.filter((command) => !replaced.some((item) => item.commandId === command.commandId));
3144
3187
  this.#assertDistinctBatchFootprints(materializations, retained, true);
@@ -3171,7 +3214,7 @@ class OfflineSyncService {
3171
3214
  throw new Error('Offline session changed before serialized replica mutation.');
3172
3215
  const result = await operation(repository);
3173
3216
  if (this.#isCurrent(generation))
3174
- await this.#refreshState(generation);
3217
+ await this.#refreshState(generation, repository);
3175
3218
  return result;
3176
3219
  });
3177
3220
  }
@@ -3181,8 +3224,8 @@ class OfflineSyncService {
3181
3224
  async #enqueue(request, options, generation, replaced, repository = this.#repository) {
3182
3225
  const session = await this.#beginEnqueueSession(generation);
3183
3226
  this.#assertEnqueueScope(session, request.scopeId);
3184
- const materialization = await this.#materializeEnqueue(session.userId, request, replaced);
3185
- const currentCommands = await this.#commandsForUser(session.userId);
3227
+ const materialization = await this.#materializeEnqueue(session.userId, request, repository, replaced);
3228
+ const currentCommands = await this.#commandsForUser(session.userId, repository);
3186
3229
  const retainedCommands = replaced ? currentCommands.filter((command) => command.commandId !== replaced.commandId) : currentCommands;
3187
3230
  this.#assertDistinctBatchFootprints([materialization], retainedCommands);
3188
3231
  await this.#assertOutboxCapacity(session.userId, [materialization.command], replaced ? [replaced.commandId] : undefined, currentCommands);
@@ -3194,14 +3237,14 @@ class OfflineSyncService {
3194
3237
  throw new Error('Prepared offline batch must contain at least one command.');
3195
3238
  }
3196
3239
  const session = await this.#beginEnqueueSession(generation);
3197
- const currentCommands = await this.#commandsForUser(session.userId);
3240
+ const currentCommands = await this.#commandsForUser(session.userId, repository);
3198
3241
  this.#rememberCreatedAt(currentCommands);
3199
3242
  const firstCreatedAt = Math.max(Date.now(), this.#lastCommandCreatedAt + 1);
3200
3243
  this.#lastCommandCreatedAt = firstCreatedAt + prepared.length - 1;
3201
3244
  const materializations = [];
3202
3245
  for (const [index, entry] of prepared.entries()) {
3203
3246
  this.#assertEnqueueScope(session, entry.request.scopeId);
3204
- materializations.push(await this.#materializeEnqueue(session.userId, entry.request, undefined, firstCreatedAt + index));
3247
+ materializations.push(await this.#materializeEnqueue(session.userId, entry.request, repository, undefined, firstCreatedAt + index));
3205
3248
  }
3206
3249
  this.#assertDistinctBatchFootprints(materializations, currentCommands);
3207
3250
  await this.#assertOutboxCapacity(session.userId, materializations.map((item) => item.command), undefined, currentCommands);
@@ -3230,12 +3273,15 @@ class OfflineSyncService {
3230
3273
  }
3231
3274
  this.noteScope({ userId: session.userId, scopeId });
3232
3275
  }
3233
- async #materializeEnqueue(userId, request, replaced, createdAt) {
3276
+ async #materializeEnqueue(userId, request, repository, replaced, createdAt) {
3234
3277
  const scope = { userId, scopeId: request.scopeId };
3235
3278
  this.noteScope(scope);
3236
3279
  const commandIdentity = offlineCommandLookupIdentity(request.identity);
3237
- const normalized = await this.#normalizeEnqueueRequest(scope, request, commandIdentity);
3238
- const commandId = crypto.randomUUID();
3280
+ const commandId = request.commandId ?? crypto.randomUUID();
3281
+ if (typeof commandId !== 'string' || commandId.length === 0 || commandId.length > 255) {
3282
+ throw new Error('Offline command id must contain between 1 and 255 characters.');
3283
+ }
3284
+ assertOfflinePayload(request.payload);
3239
3285
  const sourceKey = this.#hooks.entityType(request);
3240
3286
  const localOnlyFootprint = this.#normalizedLocalOnlyFootprint(scope, request.localOnlyFootprint);
3241
3287
  if (replaced)
@@ -3247,13 +3293,13 @@ class OfflineSyncService {
3247
3293
  sourceKey,
3248
3294
  identity: commandIdentity,
3249
3295
  operation: request.operation,
3250
- payload: normalized.payload,
3296
+ payload: request.payload,
3251
3297
  replicaMutation: request.replicaMutation ?? 'upsert',
3252
- baseRevision: normalized.baseRevision,
3298
+ baseRevision: request.baseRevision ?? null,
3253
3299
  state: 'pending',
3254
3300
  attempts: 0,
3255
3301
  retryAt: null,
3256
- createdAt: replaced?.createdAt ?? createdAt ?? (await this.#nextCommandCreatedAt(userId)),
3302
+ createdAt: replaced?.createdAt ?? createdAt ?? (await this.#nextCommandCreatedAt(userId, repository)),
3257
3303
  lastErrorCode: null,
3258
3304
  };
3259
3305
  if (localOnlyFootprint.length > 0)
@@ -3266,21 +3312,23 @@ class OfflineSyncService {
3266
3312
  canonicalOfflineCommandIdentity(replaced.identity) !== canonicalOfflineCommandIdentity(command.identity))) {
3267
3313
  throw new Error('Offline replacement command must address the same aggregate and replica identity.');
3268
3314
  }
3269
- const entityType = command.sourceKey;
3270
- const schema = this.#entitySchema(entityType);
3315
+ const schema = this.#entitySchema(sourceKey);
3271
3316
  if (schema.identity.kind === 'localOnly') {
3272
- throw new Error(`Offline replica source "${entityType}" is local-only and cannot be added to the Outbox.`);
3317
+ throw new Error(`Offline replica source "${sourceKey}" is local-only and cannot be added to the Outbox.`);
3273
3318
  }
3274
3319
  if (schema.identity.kind === 'generated' && request.identity.kind !== 'generated') {
3275
- throw new Error(`Offline replica source "${entityType}" requires generated identity.`);
3320
+ throw new Error(`Offline replica source "${sourceKey}" requires generated identity.`);
3276
3321
  }
3277
3322
  if (schema.identity.kind === 'naturalKey' && request.identity.kind !== 'natural') {
3278
- throw new Error(`Offline replica source "${entityType}" requires natural identity.`);
3323
+ throw new Error(`Offline replica source "${sourceKey}" requires natural identity.`);
3279
3324
  }
3280
- if (request.replicaMutation === 'delete' && !this.#repository.getReplicaRowIncludingPendingDelete) {
3325
+ if (request.replicaMutation === 'delete' && !repository.getReplicaRowIncludingPendingDelete) {
3281
3326
  throw new Error('Offline repository does not support durable replica delete tombstones.');
3282
3327
  }
3283
- const existing = await this.#getReplicaRowForSync(scope, entityType, commandIdentity);
3328
+ const existing = await this.#getReplicaRowForSync(scope, sourceKey, commandIdentity, repository);
3329
+ if (existing?.serverRevision != null && existing.serverRevision !== command.baseRevision) {
3330
+ command = { ...command, baseRevision: existing.serverRevision };
3331
+ }
3284
3332
  const generatedIdentity = request.identity.kind === 'generated' ? request.identity : null;
3285
3333
  const initialRemoteId = this.#initialRemoteId(schema, existing?.identity.kind === 'generated' ? existing.identity.remoteId : null, generatedIdentity?.remoteId);
3286
3334
  this.#assertRemoteIdHint(schema, existing?.identity.kind === 'generated' ? existing.identity.remoteId : null, generatedIdentity?.remoteIdHint);
@@ -3293,7 +3341,7 @@ class OfflineSyncService {
3293
3341
  request.identity.kind === 'natural' &&
3294
3342
  canonicalOfflineRemoteIdentity(schema, { naturalKey: request.identity.naturalKey }) !==
3295
3343
  canonicalOfflineRemoteIdentity(schema, { naturalKey: naturalKey })) {
3296
- throw new Error(`Offline command naturalKey must match replica identity for "${entityType}".`);
3344
+ throw new Error(`Offline command naturalKey must match replica identity for "${sourceKey}".`);
3297
3345
  }
3298
3346
  const remoteIdentity = schema.identity.kind === 'generated'
3299
3347
  ? initialRemoteId === null
@@ -3308,11 +3356,11 @@ class OfflineSyncService {
3308
3356
  canonicalOfflineRemoteIdentity(schema, {
3309
3357
  naturalKey: existing.identity.kind === 'natural' ? existing.identity.naturalKey : offlineNaturalKeyFromValues(schema, existing.values),
3310
3358
  }) !== canonicalValuesKey) {
3311
- throw new Error(`Offline replica naturalKey is immutable and must match command identity for "${entityType}".`);
3359
+ throw new Error(`Offline replica naturalKey is immutable and must match command identity for "${sourceKey}".`);
3312
3360
  }
3313
3361
  }
3314
3362
  if (remoteIdentity !== null) {
3315
- const mapped = await this.#repository.getReplicaRowByRemoteIdentity(scope, entityType, remoteIdentity);
3363
+ const mapped = await repository.getReplicaRowByRemoteIdentity(scope, sourceKey, remoteIdentity);
3316
3364
  if (mapped !== null && !commandIdentityMatchesReplicaRow(schema, mapped, commandIdentity)) {
3317
3365
  if ('remoteId' in remoteIdentity) {
3318
3366
  throw new Error(`Offline replica remote id ${String(remoteIdentity.remoteId)} is already mapped to another row.`);
@@ -3320,7 +3368,6 @@ class OfflineSyncService {
3320
3368
  throw new Error(`Offline replica remote identity is already mapped to another row.`);
3321
3369
  }
3322
3370
  }
3323
- this.#canonicalJson(normalized.payload);
3324
3371
  const seedBaseRow = existing
3325
3372
  ? undefined
3326
3373
  : request.identity.kind === 'generated'
@@ -3351,6 +3398,7 @@ class OfflineSyncService {
3351
3398
  #assertDistinctBatchFootprints(entries, existingCommands, allowOneAggregate = false) {
3352
3399
  const aggregates = new Set();
3353
3400
  const replicaKeys = new Set();
3401
+ const commandIds = new Set(existingCommands.map((command) => command.commandId));
3354
3402
  const existingFootprints = new Map();
3355
3403
  for (const command of existingCommands) {
3356
3404
  const aggregate = this.#aggregateKey(command);
@@ -3358,6 +3406,10 @@ class OfflineSyncService {
3358
3406
  existingFootprints.set(key, aggregate);
3359
3407
  }
3360
3408
  for (const entry of entries) {
3409
+ if (commandIds.has(entry.command.commandId)) {
3410
+ throw new Error(`Offline command id ${entry.command.commandId} is already in use.`);
3411
+ }
3412
+ commandIds.add(entry.command.commandId);
3361
3413
  const aggregate = this.#aggregateKey(entry.command);
3362
3414
  if (aggregates.has(aggregate) && !allowOneAggregate) {
3363
3415
  throw new Error('Prepared offline batch contains overlapping aggregate intents.');
@@ -3385,7 +3437,9 @@ class OfflineSyncService {
3385
3437
  if (generation !== this.#generation) {
3386
3438
  throw new Error('Offline session changed before the command could be persisted');
3387
3439
  }
3388
- const known = await this.#readKnownCommands();
3440
+ const known = await this.#readKnownCommands(repository);
3441
+ const putCommandIds = new Set(entries.map((entry) => entry.command.commandId));
3442
+ const effectiveRemoveCommandIds = removeCommandIds?.filter((commandId) => !putCommandIds.has(commandId));
3389
3443
  const remaining = [
3390
3444
  ...known.filter((command) => !(removeCommandIds ?? []).includes(command.commandId)),
3391
3445
  ...entries.map((entry) => entry.command),
@@ -3397,14 +3451,14 @@ class OfflineSyncService {
3397
3451
  if (entry.seedBaseRow !== undefined)
3398
3452
  seeds.set(this.#aggregateKey(entry.command), entry.seedBaseRow);
3399
3453
  }
3400
- const rematerialized = await this.#rematerializeAffectedAggregates(affected, remaining, seeds);
3454
+ const rematerialized = await this.#rematerializeAffectedAggregates(affected, remaining, seeds, repository);
3401
3455
  await repository.transactReplica({
3402
3456
  putRows: rematerialized.putRows,
3403
3457
  removeRows: rematerialized.removeRows,
3404
3458
  putCommands: entries.map((entry) => entry.command),
3405
- removeCommandIds,
3459
+ removeCommandIds: effectiveRemoveCommandIds,
3406
3460
  });
3407
- await this.#refreshState().catch((error) => this.#reportError(error));
3461
+ await this.#refreshState(generation, repository).catch((error) => this.#reportError(error));
3408
3462
  if (options.flush !== false && this.#canSynchronize())
3409
3463
  this.#flushInBackground();
3410
3464
  }
@@ -3466,10 +3520,10 @@ class OfflineSyncService {
3466
3520
  throw new OfflineOutboxCapacityError('serialized_bytes', commands.length, currentBytes);
3467
3521
  }
3468
3522
  }
3469
- async #commandsForUser(userId) {
3470
- return this.#repository.getCommandsForUser
3471
- ? this.#repository.getCommandsForUser(userId)
3472
- : (await Promise.all([...this.#knownScopes.values()].filter((scope) => scope.userId === userId).map((scope) => this.#repository.getCommands(scope)))).flat();
3523
+ async #commandsForUser(userId, repository = this.#repository) {
3524
+ return repository.getCommandsForUser
3525
+ ? repository.getCommandsForUser(userId)
3526
+ : (await Promise.all([...this.#knownScopes.values()].filter((scope) => scope.userId === userId).map((scope) => repository.getCommands(scope)))).flat();
3473
3527
  }
3474
3528
  #serializedOutboxBytes(commands) {
3475
3529
  return new TextEncoder().encode(JSON.stringify(commands)).byteLength;
@@ -3483,7 +3537,7 @@ class OfflineSyncService {
3483
3537
  // enqueue, ACK, and pull application so an old before-image cannot replace
3484
3538
  // a newer authoritative row after its cursor has advanced.
3485
3539
  const command = await this.#replicaMutations.run(async (repository) => {
3486
- const current = (await this.#readKnownCommands()).find((item) => item.commandId === commandId);
3540
+ const current = (await this.#readKnownCommands(repository)).find((item) => item.commandId === commandId);
3487
3541
  if (!current)
3488
3542
  return null;
3489
3543
  this.#assertDiscardable([current]);
@@ -3511,7 +3565,7 @@ class OfflineSyncService {
3511
3565
  // Re-read only after every interrupted transport transition has settled.
3512
3566
  // An ACK may have removed the command while retryNow was waiting; never
3513
3567
  // resurrect such a command from an object captured before invalidation.
3514
- const current = (await this.#readKnownCommands()).find((item) => item.commandId === commandId);
3568
+ const current = (await this.#readKnownCommands(repository)).find((item) => item.commandId === commandId);
3515
3569
  if (!current)
3516
3570
  return false;
3517
3571
  if (current.state !== 'retry_wait' && current.state !== 'blocked_auth' && current.serverCommitUnknown !== true) {
@@ -3533,7 +3587,7 @@ class OfflineSyncService {
3533
3587
  if (!(await this.#restoreCurrentGeneration(generation)))
3534
3588
  return;
3535
3589
  const commands = await this.#replicaMutations.run(async (repository) => {
3536
- const current = await this.#readKnownCommands();
3590
+ const current = await this.#readKnownCommands(repository);
3537
3591
  this.#assertDiscardable(current);
3538
3592
  this.#invalidateFlush();
3539
3593
  await this.#discardCommands(current, repository);
@@ -3555,11 +3609,148 @@ class OfflineSyncService {
3555
3609
  const generation = this.#generation;
3556
3610
  return this.#flushAfterInitialization(generation);
3557
3611
  }
3612
+ /**
3613
+ * Sends one newly-created generated aggregate immediately after its durable
3614
+ * enqueue, without waiting for a pre-send pull.
3615
+ *
3616
+ * This fast path is deliberately narrow: the command must still be pending,
3617
+ * have no remote id or confirmed baseline, and be the first intent for its
3618
+ * aggregate. Existing aggregates continue through {@link flush}, where the
3619
+ * pre-pull conflict barrier remains mandatory. Authoritative pull
3620
+ * reconciliation is scheduled in the background after the local transport
3621
+ * acknowledgement has been committed.
3622
+ *
3623
+ * @returns The generated remote id when transport completed locally, or
3624
+ * `null` when transport is unavailable or did not produce a confirmed id.
3625
+ */
3626
+ async sendGeneratedCommandNow(commandId, locator) {
3627
+ const generation = this.#generation;
3628
+ if (!(await this.#restoreCurrentGeneration(generation)))
3629
+ return null;
3630
+ const userId = this.#activeUserId;
3631
+ if (userId === null)
3632
+ return null;
3633
+ return this.#beginGeneratedCommandSend(commandId, locator, generation, userId);
3634
+ }
3558
3635
  async #flushAfterInitialization(generation) {
3559
3636
  if (!(await this.#restoreCurrentGeneration(generation)))
3560
3637
  return;
3561
3638
  return this.#beginFlush(true);
3562
3639
  }
3640
+ #beginGeneratedCommandSend(commandId, locator, generation, userId) {
3641
+ const result = this.#runGeneratedCommandSend(commandId, locator, generation, userId);
3642
+ let requiresReconciliation = false;
3643
+ const transition = result
3644
+ .then((remoteId) => {
3645
+ requiresReconciliation = remoteId !== null;
3646
+ }, () => undefined)
3647
+ .finally(() => {
3648
+ this.#flushTransitions.delete(transition);
3649
+ if (requiresReconciliation && this.#canSynchronize() && this.#isCurrentUser(generation, userId)) {
3650
+ // A normal flush may already be in its post-pull phase. Ensure the
3651
+ // newly acknowledged command receives a later reconciliation pass.
3652
+ if (this.#flushPromise)
3653
+ this.#resumeAfterFlush = true;
3654
+ queueMicrotask(() => this.#flushInBackground());
3655
+ }
3656
+ });
3657
+ this.#flushTransitions.add(transition);
3658
+ return result;
3659
+ }
3660
+ async #runGeneratedCommandSend(commandId, locator, generation, userId) {
3661
+ if (!this.#isCurrentUser(generation, userId))
3662
+ return null;
3663
+ if (!this.#canSynchronize()) {
3664
+ await this.#refreshState(generation);
3665
+ return null;
3666
+ }
3667
+ if (this.#pullAttentions().length > 0)
3668
+ return null;
3669
+ if (!(await this.#discoverScopes(generation)))
3670
+ return null;
3671
+ if (!this.#isCurrentUser(generation, userId))
3672
+ return null;
3673
+ const known = await this.#readKnownCommands();
3674
+ if (!this.#isCurrentUser(generation, userId))
3675
+ return null;
3676
+ const command = known.find((candidate) => candidate.commandId === commandId);
3677
+ if (!command)
3678
+ return this.#generatedRemoteId(locator, userId, generation);
3679
+ if (command.userId !== userId)
3680
+ return null;
3681
+ if (command.scopeId !== locator.scopeId ||
3682
+ command.sourceKey !== locator.sourceKey ||
3683
+ command.identity.kind !== 'generated' ||
3684
+ command.identity.localId !== locator.localId) {
3685
+ throw new Error('Immediate generated command locator does not match the durable command.');
3686
+ }
3687
+ if (command.state === 'awaiting_pull') {
3688
+ return this.#commandReconciliationRemoteId(command) ?? this.#generatedRemoteId(locator, userId, generation);
3689
+ }
3690
+ if (command.state === 'sending') {
3691
+ const activeSend = this.#commandSendTransitions.get(this.#commandSendKey(command, generation));
3692
+ if (activeSend)
3693
+ await activeSend;
3694
+ return this.#generatedCommandOutcome(commandId, locator, generation, userId);
3695
+ }
3696
+ if (command.state !== 'pending')
3697
+ return null;
3698
+ const aggregate = known.filter((candidate) => this.#aggregateKey(candidate) === this.#aggregateKey(command));
3699
+ if (aggregate[0]?.commandId !== command.commandId) {
3700
+ throw new Error('Immediate generated command delivery requires the first aggregate intent.');
3701
+ }
3702
+ const row = await this.#rowForCommand(command);
3703
+ if (!row ||
3704
+ row.identity.kind !== 'generated' ||
3705
+ row.identity.remoteId !== null ||
3706
+ row.confirmedValues !== null ||
3707
+ command.identity.kind !== 'generated' ||
3708
+ command.baseRevision !== null ||
3709
+ command.replicaMutation === 'delete') {
3710
+ throw new Error('Immediate generated command delivery requires a new unconfirmed aggregate.');
3711
+ }
3712
+ const scope = { userId: command.userId, scopeId: command.scopeId };
3713
+ const scopeKey = this.#scopeKey(scope);
3714
+ if (!this.#knownScopes.has(scopeKey))
3715
+ return null;
3716
+ const dirtyScopes = new Map();
3717
+ await this.#sendAggregate([command], generation, dirtyScopes, new Set([scopeKey]));
3718
+ if (!this.#isCurrentUser(generation, userId))
3719
+ return null;
3720
+ for (const dirtyScope of dirtyScopes.values()) {
3721
+ this.#pendingPullScopes.set(this.#scopeKey(dirtyScope), dirtyScope);
3722
+ }
3723
+ return this.#generatedCommandOutcome(commandId, locator, generation, userId);
3724
+ }
3725
+ async #generatedCommandOutcome(commandId, locator, generation, userId) {
3726
+ if (!this.#isCurrentUser(generation, userId))
3727
+ return null;
3728
+ await this.#refreshState(generation);
3729
+ if (!this.#isCurrentUser(generation, userId))
3730
+ return null;
3731
+ const completed = (await this.#readKnownCommands()).find((candidate) => candidate.commandId === commandId);
3732
+ if (!this.#isCurrentUser(generation, userId))
3733
+ return null;
3734
+ if (completed && ['blocked_auth', 'rejected', 'conflict'].includes(completed.state)) {
3735
+ throw new OfflineImmediateCommandRejectedError(completed.state, completed.lastErrorCode);
3736
+ }
3737
+ return completed
3738
+ ? (this.#commandReconciliationRemoteId(completed) ?? this.#generatedRemoteId(locator, userId, generation))
3739
+ : this.#generatedRemoteId(locator, userId, generation);
3740
+ }
3741
+ async #generatedRemoteId(locator, userId, generation) {
3742
+ if (!this.#isCurrentUser(generation, userId))
3743
+ return null;
3744
+ const row = await this.#repository.getReplicaRow({ userId, scopeId: locator.scopeId }, locator.sourceKey, {
3745
+ kind: 'generated',
3746
+ localId: locator.localId,
3747
+ });
3748
+ return this.#isCurrentUser(generation, userId) && row?.identity.kind === 'generated' ? row.identity.remoteId : null;
3749
+ }
3750
+ #commandReconciliationRemoteId(command) {
3751
+ const identity = command.reconciliationIdentity;
3752
+ return identity && 'remoteId' in identity ? (identity.remoteId ?? null) : null;
3753
+ }
3563
3754
  #beginFlush(explicitFull) {
3564
3755
  const lifecycleRevision = this.#lifecycleRevision();
3565
3756
  const isPartial = !explicitFull && this.#foregroundScopePolicy !== null;
@@ -3829,88 +4020,110 @@ class OfflineSyncService {
3829
4020
  }
3830
4021
  async #sendAggregate(commands, generation, dirtyScopes, pulledScopeKeys) {
3831
4022
  for (const command of commands) {
3832
- if (!this.#isCurrent(generation))
3833
- return;
3834
- if (command.state === 'awaiting_pull')
3835
- continue;
3836
- if (command.state === 'retry_wait' && (command.retryAt ?? 0) > Date.now())
3837
- break;
3838
- if (!['pending', 'retry_wait'].includes(command.state))
4023
+ if (!(await this.#sendCommandOnce(commands, command, generation, dirtyScopes, pulledScopeKeys)))
3839
4024
  break;
3840
- // User-scoped aggregates ignore scopeId in the FIFO key, so later commands may
3841
- // belong to scopes that failed pre-pull even when the head was admitted.
3842
- if (!pulledScopeKeys.has(this.#scopeKey({ userId: command.userId, scopeId: command.scopeId })))
3843
- break;
3844
- let sending = await this.#claimSendingCommand(command, generation);
3845
- if (!sending)
3846
- return;
4025
+ }
4026
+ }
4027
+ #sendCommandOnce(aggregateCommands, command, generation, dirtyScopes, pulledScopeKeys) {
4028
+ const transitionKey = this.#commandSendKey(command, generation);
4029
+ const active = this.#commandSendTransitions.get(transitionKey);
4030
+ if (active)
4031
+ return active;
4032
+ const transition = this.#sendCommand(aggregateCommands, command, generation, dirtyScopes, pulledScopeKeys).finally(() => {
4033
+ if (this.#commandSendTransitions.get(transitionKey) === transition) {
4034
+ this.#commandSendTransitions.delete(transitionKey);
4035
+ }
4036
+ });
4037
+ this.#commandSendTransitions.set(transitionKey, transition);
4038
+ return transition;
4039
+ }
4040
+ #commandSendKey(command, generation) {
4041
+ return JSON.stringify([generation, canonicalOfflinePrincipalId(command.userId), command.commandId]);
4042
+ }
4043
+ async #sendCommand(aggregateCommands, command, generation, dirtyScopes, pulledScopeKeys) {
4044
+ if (!this.#isCurrent(generation))
4045
+ return false;
4046
+ if (command.state === 'awaiting_pull')
4047
+ return true;
4048
+ if (command.state === 'retry_wait' && (command.retryAt ?? 0) > Date.now())
4049
+ return false;
4050
+ if (!['pending', 'retry_wait'].includes(command.state))
4051
+ return false;
4052
+ // User-scoped aggregates ignore scopeId in the FIFO key, so later commands may
4053
+ // belong to scopes that failed pre-pull even when the head was admitted.
4054
+ if (!pulledScopeKeys.has(this.#scopeKey({ userId: command.userId, scopeId: command.scopeId })))
4055
+ return false;
4056
+ let sending = await this.#claimSendingCommand(command, generation);
4057
+ if (!sending || !this.#isCurrent(generation))
4058
+ return false;
4059
+ await this.#refreshState(generation);
4060
+ if (!this.#isCurrent(generation))
4061
+ return false;
4062
+ const claimedCommand = sending;
4063
+ const readRow = async () => this.#rowForCommand(claimedCommand);
4064
+ const rowResult = await readRow().then((row) => ({ status: 'fulfilled', row }), (error) => ({ status: 'rejected', error }));
4065
+ if (rowResult.status === 'rejected') {
3847
4066
  if (!this.#isCurrent(generation))
3848
- return;
3849
- await this.#refreshState(generation);
4067
+ return false;
4068
+ await this.#persistFailedCommand(sending, rowResult.error, generation, null, sending.serverCommitUnknown === true);
4069
+ throw rowResult.error;
4070
+ }
4071
+ const row = rowResult.row;
4072
+ if (!row) {
4073
+ const error = new Error(`Offline replica row not found: ${sending.aggregateType}/${canonicalOfflineCommandIdentity(sending.identity)}`);
4074
+ await this.#persistFailedCommand(sending, error, generation, null, sending.serverCommitUnknown === true);
4075
+ throw error;
4076
+ }
4077
+ const priorCommitUnknown = sending.serverCommitUnknown === true;
4078
+ const transportCommand = await this.#markTransportStarted(sending, generation);
4079
+ if (!transportCommand)
4080
+ return false;
4081
+ sending = transportCommand;
4082
+ const executeCommand = async () => this.#executor.execute(sending, offlineCommandTargetFromReplicaRow(row));
4083
+ const execution = await executeCommand().then((result) => ({ status: 'fulfilled', result }), (error) => ({ status: 'rejected', error }));
4084
+ if (execution.status === 'rejected') {
3850
4085
  if (!this.#isCurrent(generation))
3851
- return;
3852
- const claimedCommand = sending;
3853
- const readRow = async () => this.#rowForCommand(claimedCommand);
3854
- const rowResult = await readRow().then((row) => ({ status: 'fulfilled', row }), (error) => ({ status: 'rejected', error }));
3855
- if (rowResult.status === 'rejected') {
3856
- if (!this.#isCurrent(generation))
3857
- return;
3858
- await this.#persistFailedCommand(sending, rowResult.error, generation, null, sending.serverCommitUnknown === true);
3859
- throw rowResult.error;
3860
- }
3861
- const row = rowResult.row;
3862
- if (!row) {
3863
- const error = new Error(`Offline replica row not found: ${sending.aggregateType}/${canonicalOfflineCommandIdentity(sending.identity)}`);
3864
- await this.#persistFailedCommand(sending, error, generation, null, sending.serverCommitUnknown === true);
3865
- throw error;
3866
- }
3867
- const priorCommitUnknown = sending.serverCommitUnknown === true;
3868
- const transportCommand = await this.#markTransportStarted(sending, generation);
3869
- if (!transportCommand)
3870
- return;
3871
- sending = transportCommand;
3872
- const executeCommand = async () => this.#executor.execute(sending, offlineCommandTargetFromReplicaRow(row));
3873
- const execution = await executeCommand().then((result) => ({ status: 'fulfilled', result }), (error) => ({ status: 'rejected', error }));
3874
- if (execution.status === 'rejected') {
3875
- if (!this.#isCurrent(generation))
3876
- return;
3877
- const commitUnknown = this.#executor.provesCommandNotCommitted?.(execution.error, sending)
3878
- ? false
3879
- : priorCommitUnknown || this.#serverCommitCouldBeUnknown(execution.error);
3880
- await this.#persistFailedCommand(sending, execution.error, generation, row, commitUnknown);
3881
- if (!this.#isClassifiableTransportError(execution.error))
3882
- throw execution.error;
3883
- break;
3884
- }
3885
- const result = execution.result;
4086
+ return false;
4087
+ const commitUnknown = this.#executor.provesCommandNotCommitted?.(execution.error, sending)
4088
+ ? false
4089
+ : priorCommitUnknown || this.#serverCommitCouldBeUnknown(execution.error);
4090
+ await this.#persistFailedCommand(sending, execution.error, generation, row, commitUnknown);
4091
+ if (!this.#isClassifiableTransportError(execution.error))
4092
+ throw execution.error;
4093
+ return false;
4094
+ }
4095
+ const result = execution.result;
4096
+ if (!this.#isCurrent(generation))
4097
+ return false;
4098
+ const completeCommand = async () => this.#completeCommandWithRetry(aggregateCommands, sending, result, generation);
4099
+ const completion = await completeCommand().then(() => ({ status: 'fulfilled' }), (error) => ({ status: 'rejected', error }));
4100
+ if (completion.status === 'rejected') {
3886
4101
  if (!this.#isCurrent(generation))
3887
- return;
3888
- const completeCommand = async () => this.#completeCommand(commands, sending, result, generation);
3889
- const completion = await completeCommand().then(() => ({ status: 'fulfilled' }), (error) => ({ status: 'rejected', error }));
3890
- if (completion.status === 'rejected') {
3891
- if (!this.#isCurrent(generation))
3892
- return;
3893
- await this.#persistFailedCommand(sending, completion.error, generation, row, true);
3894
- throw completion.error;
3895
- }
3896
- if (this.#isCurrent(generation)) {
3897
- const scope = { userId: sending.userId, scopeId: sending.scopeId };
3898
- dirtyScopes.set(this.#scopeKey(scope), scope);
3899
- }
4102
+ return false;
4103
+ await this.#persistFailedCommand(sending, completion.error, generation, row, true);
4104
+ throw completion.error;
3900
4105
  }
3901
- }
3902
- async #normalizeEnqueueRequest(scope, request, commandIdentity) {
3903
- let baseRevision = request.baseRevision ?? null;
3904
- const sourceKey = this.#hooks.entityType(request);
3905
- const row = await this.#getReplicaRowForSync(scope, sourceKey, commandIdentity);
3906
- if (row?.serverRevision != null && row.serverRevision !== baseRevision) {
3907
- baseRevision = row.serverRevision;
4106
+ if (this.#isCurrent(generation)) {
4107
+ const scope = { userId: sending.userId, scopeId: sending.scopeId };
4108
+ dirtyScopes.set(this.#scopeKey(scope), scope);
3908
4109
  }
3909
- return { payload: request.payload, baseRevision };
4110
+ return true;
3910
4111
  }
3911
4112
  async #completeCommand(commands, command, result, generation) {
3912
4113
  return this.#serializeReplicaMutation((repository) => this.#completeCommandLocked(commands, command, result, generation, repository));
3913
4114
  }
4115
+ async #completeCommandWithRetry(commands, command, result, generation) {
4116
+ return this.#completeCommand(commands, command, result, generation).catch(async (firstError) => {
4117
+ if (!isRetryableLocalCompletionError(firstError))
4118
+ throw firstError;
4119
+ const retry = await this.#completeCommand(commands, command, result, generation).then(() => ({ status: 'fulfilled' }), (error) => ({ status: 'rejected', error }));
4120
+ if (retry.status === 'fulfilled')
4121
+ return;
4122
+ if (!isRetryableLocalCompletionError(retry.error))
4123
+ throw retry.error;
4124
+ throw new OfflineLocalCompletionError(retry.error, firstError);
4125
+ });
4126
+ }
3914
4127
  async #completeCommandLocked(commands, command, result, generation, repository) {
3915
4128
  if (result.clearRemoteId === true && result.remoteId !== undefined) {
3916
4129
  throw new Error('Offline command cannot return remoteId and clearRemoteId together.');
@@ -3918,7 +4131,7 @@ class OfflineSyncService {
3918
4131
  if (result.clearRemoteId === true && result.serverRevision !== undefined) {
3919
4132
  throw new Error('Offline command cannot return serverRevision and clearRemoteId together.');
3920
4133
  }
3921
- const latestCommands = (await this.#readKnownCommands()).filter((candidate) => this.#aggregateKey(candidate) === this.#aggregateKey(command));
4134
+ const latestCommands = (await this.#readKnownCommands(repository)).filter((candidate) => this.#aggregateKey(candidate) === this.#aggregateKey(command));
3922
4135
  const latestIndex = latestCommands.findIndex((candidate) => candidate.commandId === command.commandId);
3923
4136
  if (latestIndex < 0)
3924
4137
  return;
@@ -3929,7 +4142,7 @@ class OfflineSyncService {
3929
4142
  : revision === undefined
3930
4143
  ? following
3931
4144
  : following.map((item) => offlineCommandWithBaseRevision(item, revision));
3932
- const current = await this.#rowForCommand(command);
4145
+ const current = await this.#rowForCommand(command, repository);
3933
4146
  if (!this.#isCurrent(generation))
3934
4147
  return;
3935
4148
  if (!current) {
@@ -3970,7 +4183,7 @@ class OfflineSyncService {
3970
4183
  serverRevision: result.clearRemoteId === true ? null : (revision ?? current.serverRevision),
3971
4184
  fetchedAt: Date.now(),
3972
4185
  };
3973
- const rematerialized = await this.#rematerializeAggregate(awaitingPull, latestCommands, identityUpdatedBase);
4186
+ const rematerialized = await this.#rematerializeAggregate(awaitingPull, latestCommands, identityUpdatedBase, latestCommands, repository);
3974
4187
  if (!this.#isCurrent(generation))
3975
4188
  return;
3976
4189
  await repository.transactReplica({
@@ -3993,14 +4206,13 @@ class OfflineSyncService {
3993
4206
  this.#pendingPullScopes.set(this.#scopeKey(scope), scope);
3994
4207
  commands.splice(0, commands.length, ...latestCommands);
3995
4208
  }
3996
- async #rowForCommand(command) {
4209
+ async #rowForCommand(command, repository = this.#repository) {
3997
4210
  const scope = { userId: command.userId, scopeId: command.scopeId };
3998
4211
  const entityType = this.#entityType(command);
3999
- return this.#getReplicaRowForSync(scope, entityType, command.identity);
4212
+ return this.#getReplicaRowForSync(scope, entityType, command.identity, repository);
4000
4213
  }
4001
- #getReplicaRowForSync(scope, sourceKey, identity) {
4002
- return (this.#repository.getReplicaRowIncludingPendingDelete?.(scope, sourceKey, identity) ??
4003
- this.#repository.getReplicaRow(scope, sourceKey, identity));
4214
+ #getReplicaRowForSync(scope, sourceKey, identity, repository = this.#repository) {
4215
+ return (repository.getReplicaRowIncludingPendingDelete?.(scope, sourceKey, identity) ?? repository.getReplicaRow(scope, sourceKey, identity));
4004
4216
  }
4005
4217
  #replicaState(state) {
4006
4218
  if (state === 'blocked_auth' || state === 'rejected' || state === 'conflict')
@@ -4017,36 +4229,36 @@ class OfflineSyncService {
4017
4229
  return schema;
4018
4230
  }
4019
4231
  async #discardCommands(discarded, repository) {
4020
- const all = await this.#readKnownCommands();
4232
+ const all = await this.#readKnownCommands(repository);
4021
4233
  const discardedIds = new Set(discarded.map((command) => command.commandId));
4022
4234
  const affected = new Map();
4023
4235
  for (const command of discarded)
4024
4236
  affected.set(this.#aggregateKey(command), command);
4025
4237
  const remaining = all.filter((item) => !discardedIds.has(item.commandId));
4026
- const rematerialized = await this.#rematerializeAffectedAggregates(affected, remaining);
4238
+ const rematerialized = await this.#rematerializeAffectedAggregates(affected, remaining, new Map(), repository);
4027
4239
  await repository.transactReplica({
4028
4240
  putRows: rematerialized.putRows,
4029
4241
  removeRows: rematerialized.removeRows,
4030
4242
  removeCommandIds: [...discardedIds],
4031
4243
  });
4032
4244
  }
4033
- async #rematerializeAffectedAggregates(affected, remaining, seeds = new Map()) {
4245
+ async #rematerializeAffectedAggregates(affected, remaining, seeds = new Map(), repository = this.#repository) {
4034
4246
  const putRows = [];
4035
4247
  const removeRows = [];
4036
4248
  for (const [key, command] of affected) {
4037
4249
  const remainingForAggregate = remaining.filter((item) => this.#aggregateKey(item) === key);
4038
4250
  const footprintCommands = [...remainingForAggregate, ...[...affected.values()].filter((item) => this.#aggregateKey(item) === key)];
4039
- const rematerialized = await this.#rematerializeAggregate(command, remainingForAggregate, seeds.has(key) ? seeds.get(key) : undefined, footprintCommands);
4251
+ const rematerialized = await this.#rematerializeAggregate(command, remainingForAggregate, seeds.has(key) ? seeds.get(key) : undefined, footprintCommands, repository);
4040
4252
  putRows.push(...(rematerialized.putRows ?? []));
4041
4253
  removeRows.push(...(rematerialized.removeRows ?? []));
4042
4254
  }
4043
4255
  return { putRows, removeRows };
4044
4256
  }
4045
- async #rematerializeAggregate(command, remaining, baseRow = undefined, footprintCommands = remaining) {
4046
- const current = baseRow === undefined ? await this.#rowForCommand(command) : baseRow;
4257
+ async #rematerializeAggregate(command, remaining, baseRow = undefined, footprintCommands = remaining, repository = this.#repository) {
4258
+ const current = baseRow === undefined ? await this.#rowForCommand(command, repository) : baseRow;
4047
4259
  const projection = this.#replicaMutations.projectAggregateIntent({
4048
4260
  baseRow: current,
4049
- localOnlyRows: await this.#localOnlyRowsForCommands(footprintCommands),
4261
+ localOnlyRows: await this.#localOnlyRowsForCommands(footprintCommands, repository),
4050
4262
  commands: remaining,
4051
4263
  trigger: 'local',
4052
4264
  });
@@ -4055,20 +4267,20 @@ class OfflineSyncService {
4055
4267
  }
4056
4268
  return offlineAggregateIntentMutations(projection, current);
4057
4269
  }
4058
- async #localOnlyRowsForCommands(commands) {
4270
+ async #localOnlyRowsForCommands(commands, repository = this.#repository) {
4059
4271
  const keys = new Map();
4060
4272
  for (const command of commands) {
4061
4273
  for (const key of commandFootprintKeys(command)) {
4062
4274
  keys.set(this.#replicaRowKey(key), key);
4063
4275
  }
4064
4276
  }
4065
- const rows = await Promise.all([...keys.values()].map((key) => this.#getLocalOnlyRow(key)));
4277
+ const rows = await Promise.all([...keys.values()].map((key) => this.#getLocalOnlyRow(key, repository)));
4066
4278
  return rows.filter((row) => row !== null);
4067
4279
  }
4068
- #getLocalOnlyRow(key) {
4280
+ #getLocalOnlyRow(key, repository = this.#repository) {
4069
4281
  const scope = { userId: key.userId, scopeId: key.scopeId };
4070
- return (this.#repository.getReplicaRowIncludingPendingDelete?.(scope, key.sourceKey, key.identity) ??
4071
- this.#repository.getReplicaRow(scope, key.sourceKey, key.identity));
4282
+ return (repository.getReplicaRowIncludingPendingDelete?.(scope, key.sourceKey, key.identity) ??
4283
+ repository.getReplicaRow(scope, key.sourceKey, key.identity));
4072
4284
  }
4073
4285
  #aggregateKey(command) {
4074
4286
  const sourceKey = this.#entityType(command);
@@ -4094,14 +4306,14 @@ class OfflineSyncService {
4094
4306
  ...command,
4095
4307
  state: 'retry_wait',
4096
4308
  retryAt,
4097
- lastErrorCode: status > 0 ? String(status) : 'network',
4309
+ lastErrorCode: error instanceof OfflineLocalCompletionError ? 'local_completion' : status > 0 ? String(status) : 'network',
4098
4310
  serverCommitUnknown,
4099
4311
  };
4100
4312
  }
4101
4313
  async #persistFailedCommand(command, error, generation, row, serverCommitUnknown = true) {
4102
4314
  const failed = this.#failedCommand(command, error, serverCommitUnknown);
4103
4315
  await this.#serializeReplicaMutation(async (repository) => {
4104
- const current = row === undefined ? await this.#rowForCommand(command) : row;
4316
+ const current = row === undefined ? await this.#rowForCommand(command, repository) : row;
4105
4317
  if (!this.#isCurrent(generation))
4106
4318
  return;
4107
4319
  if (current) {
@@ -4260,18 +4472,18 @@ class OfflineSyncService {
4260
4472
  }
4261
4473
  }
4262
4474
  }
4263
- async #readKnownCommands() {
4475
+ async #readKnownCommands(repository = this.#repository) {
4264
4476
  const userId = this.#activeUserId;
4265
4477
  if (userId === null)
4266
4478
  return [];
4267
- const commands = (await this.#commandsForUser(userId))
4479
+ const commands = (await this.#commandsForUser(userId, repository))
4268
4480
  .filter((command) => this.#knownScopes.has(this.#scopeKey({ userId: command.userId, scopeId: command.scopeId })))
4269
4481
  .sort(compareOfflineCommands);
4270
4482
  this.#rememberCreatedAt(commands);
4271
4483
  return commands;
4272
4484
  }
4273
- async #nextCommandCreatedAt(userId) {
4274
- const commands = await this.#commandsForUser(userId);
4485
+ async #nextCommandCreatedAt(userId, repository = this.#repository) {
4486
+ const commands = await this.#commandsForUser(userId, repository);
4275
4487
  this.#rememberCreatedAt(commands);
4276
4488
  const createdAt = Math.max(Date.now(), this.#lastCommandCreatedAt + 1);
4277
4489
  this.#lastCommandCreatedAt = createdAt;
@@ -4281,9 +4493,9 @@ class OfflineSyncService {
4281
4493
  for (const command of commands)
4282
4494
  this.#lastCommandCreatedAt = Math.max(this.#lastCommandCreatedAt, command.createdAt);
4283
4495
  }
4284
- async #refreshState(generation = this.#generation) {
4285
- const commands = await this.#readKnownCommands();
4286
- const attentions = this.#activeUserId !== null && this.#repository.getPullAttentions ? await this.#repository.getPullAttentions(this.#activeUserId) : [];
4496
+ async #refreshState(generation = this.#generation, repository = this.#repository) {
4497
+ const commands = await this.#readKnownCommands(repository);
4498
+ const attentions = this.#activeUserId !== null && repository.getPullAttentions ? await repository.getPullAttentions(this.#activeUserId) : [];
4287
4499
  if (!this.#isCurrent(generation))
4288
4500
  return;
4289
4501
  this.#commands.set(commands);
@@ -4316,6 +4528,9 @@ class OfflineSyncService {
4316
4528
  #isCurrent(generation) {
4317
4529
  return generation === this.#generation;
4318
4530
  }
4531
+ #isCurrentUser(generation, userId) {
4532
+ return this.#isCurrent(generation) && this.#activeUserId === userId;
4533
+ }
4319
4534
  async #restoreInterruptedCommands() {
4320
4535
  const commands = await this.#readKnownCommands();
4321
4536
  await Promise.all(commands
@@ -4331,7 +4546,7 @@ class OfflineSyncService {
4331
4546
  if (!this.#isCurrent(generation))
4332
4547
  return null;
4333
4548
  const scope = { userId: command.userId, scopeId: command.scopeId };
4334
- const current = (await this.#repository.getCommands(scope)).find((candidate) => candidate.commandId === command.commandId);
4549
+ const current = (await repository.getCommands(scope)).find((candidate) => candidate.commandId === command.commandId);
4335
4550
  if (!current || !['pending', 'retry_wait'].includes(current.state))
4336
4551
  return null;
4337
4552
  const sending = {
@@ -4353,7 +4568,7 @@ class OfflineSyncService {
4353
4568
  if (!this.#isCurrent(generation))
4354
4569
  return null;
4355
4570
  const scope = { userId: command.userId, scopeId: command.scopeId };
4356
- const current = (await this.#repository.getCommands(scope)).find((candidate) => candidate.commandId === command.commandId);
4571
+ const current = (await repository.getCommands(scope)).find((candidate) => candidate.commandId === command.commandId);
4357
4572
  if (!current || current.state !== 'sending')
4358
4573
  return null;
4359
4574
  const transportCommand = { ...current, serverCommitUnknown: true };
@@ -4397,28 +4612,7 @@ class OfflineSyncService {
4397
4612
  this.#pendingPullScopes.delete(this.#scopeKey(scope));
4398
4613
  }
4399
4614
  async #waitForSendingTransitions() {
4400
- await Promise.allSettled([...this.#sendingTransitions]);
4401
- }
4402
- #canonicalJson(value) {
4403
- if (Array.isArray(value))
4404
- return `[${value.map((item) => this.#canonicalJson(item)).join(',')}]`;
4405
- if (value !== null && typeof value === 'object') {
4406
- if (Object.getPrototypeOf(value) !== Object.prototype) {
4407
- throw new OfflinePayloadValidationError();
4408
- }
4409
- return `{${Object.entries(value)
4410
- .sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0))
4411
- .map(([key, item]) => `${JSON.stringify(key)}:${this.#canonicalJson(item)}`)
4412
- .join(',')}}`;
4413
- }
4414
- if (typeof value === 'number' && !Number.isFinite(value)) {
4415
- throw new OfflinePayloadValidationError();
4416
- }
4417
- const serialized = JSON.stringify(value);
4418
- if (typeof serialized !== 'string') {
4419
- throw new OfflinePayloadValidationError();
4420
- }
4421
- return serialized;
4615
+ await Promise.allSettled([...this.#sendingTransitions, ...this.#commandSendTransitions.values()]);
4422
4616
  }
4423
4617
  #scopeKey(scope) {
4424
4618
  return `${canonicalOfflinePrincipalId(scope.userId)}:${scope.scopeId}`;
@@ -4430,9 +4624,40 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.3", ngImpor
4430
4624
  type: Injectable,
4431
4625
  args: [{ providedIn: 'root' }]
4432
4626
  }], ctorParameters: () => [] });
4627
+ function assertOfflinePayload(value, ancestors = new Set()) {
4628
+ if (value === null || typeof value === 'string' || typeof value === 'boolean')
4629
+ return;
4630
+ if (typeof value === 'number') {
4631
+ if (Number.isFinite(value))
4632
+ return;
4633
+ throw new OfflinePayloadValidationError();
4634
+ }
4635
+ if (typeof value !== 'object' || ancestors.has(value)) {
4636
+ throw new OfflinePayloadValidationError();
4637
+ }
4638
+ if (!Array.isArray(value) && Object.getPrototypeOf(value) !== Object.prototype) {
4639
+ throw new OfflinePayloadValidationError();
4640
+ }
4641
+ ancestors.add(value);
4642
+ const items = Array.isArray(value) ? value : Object.values(value);
4643
+ for (const item of items)
4644
+ assertOfflinePayload(item, ancestors);
4645
+ ancestors.delete(value);
4646
+ }
4433
4647
  function compareOfflineCommands(left, right) {
4434
4648
  return left.createdAt - right.createdAt || (left.commandId < right.commandId ? -1 : left.commandId > right.commandId ? 1 : 0);
4435
4649
  }
4650
+ class OfflineLocalCompletionError extends AggregateError {
4651
+ constructor(retryError, firstError) {
4652
+ super([firstError, retryError], 'Offline command reached the server but local acknowledgement could not be persisted.', {
4653
+ cause: retryError,
4654
+ });
4655
+ this.name = 'OfflineLocalCompletionError';
4656
+ }
4657
+ }
4658
+ function isRetryableLocalCompletionError(error) {
4659
+ return error instanceof OfflineReplicaTransientWriteError;
4660
+ }
4436
4661
 
4437
4662
  /** Raised when disabling requires pending commands to be synchronized while transport is offline. */
4438
4663
  class OfflineMutationPersistenceRequiresOnlineError extends Error {
@@ -4827,6 +5052,7 @@ class OfflineCoordinatorService {
4827
5052
  ...(ngDevMode ? [{ debugName: "isStorageReady" }] : /* istanbul ignore next */ []));
4828
5053
  this.networkState = this.#network.state;
4829
5054
  this.syncState = this.#sync.syncState;
5055
+ this.pendingCommands = this.#sync.pendingCommands;
4830
5056
  this.pendingCount = this.#sync.pendingCount;
4831
5057
  this.conflicts = this.#sync.conflicts;
4832
5058
  /** Device-local control for accepting new durable Outbox mutations. */
@@ -5392,10 +5618,16 @@ const offlineInterceptor = (request, next) => {
5392
5618
  const plan = registry.resolve(request);
5393
5619
  if (!plan)
5394
5620
  return transport();
5621
+ if (plan.readStrategy === 'local-only') {
5622
+ return readLocalOnly(plan, inject(ErrorHandler), inject(OfflineReplicaMutationCoordinator));
5623
+ }
5395
5624
  if (plan.readStrategy === 'local-first') {
5396
5625
  return readLocalFirst(request, plan, transport, fallback, inject(ErrorHandler), inject(OfflineReplicaMutationCoordinator));
5397
5626
  }
5398
- return readNetworkFirst(request, plan, transport, fallback);
5627
+ if (plan.readStrategy === 'fastest-first') {
5628
+ return readFastestFirst(request, plan, transport, fallback, inject(ErrorHandler), inject(OfflineReplicaMutationCoordinator));
5629
+ }
5630
+ return readNetworkFirst(request, plan, transport, fallback, inject(OfflineReplicaMutationCoordinator));
5399
5631
  }
5400
5632
  if (LOCAL_FIRST_MUTATION_METHODS.has(request.method)) {
5401
5633
  if (!inject(OFFLINE_MUTATION_PERSISTENCE_ENABLED)())
@@ -5407,8 +5639,12 @@ const offlineInterceptor = (request, next) => {
5407
5639
  }
5408
5640
  return transport();
5409
5641
  };
5410
- function readNetworkFirst(request, plan, transport, fallback) {
5411
- return defer(transport).pipe(catchError((error) => fallback.handle(request, error, plan) ?? throwError(() => error)), concatMap((event) => projectReadResponse(event, plan)));
5642
+ /** Resolves a provisional/local identity without starting remote transport. */
5643
+ function readLocalOnly(plan, errorHandler, replicaMutations) {
5644
+ return resolveLocalAttempt(plan, errorHandler, replicaMutations).pipe(concatMap((response) => (response ? of(response) : EMPTY)));
5645
+ }
5646
+ function readNetworkFirst(request, plan, transport, fallback, replicaMutations) {
5647
+ return defer(transport).pipe(catchError((error) => fallback.handle(request, error, plan) ?? throwError(() => error)), concatMap((event) => projectReadResponse(event, plan, replicaMutations)));
5412
5648
  }
5413
5649
  /**
5414
5650
  * Stale-while-revalidate local-first GET handling.
@@ -5425,14 +5661,29 @@ function readNetworkFirst(request, plan, transport, fallback) {
5425
5661
  */
5426
5662
  function readLocalFirst(request, plan, transport, fallback, errorHandler, replicaMutations) {
5427
5663
  return defer(transport).pipe(materialize(), connect((bufferedTransport$) => resolveLocalAttempt(plan, errorHandler, replicaMutations).pipe(concatMap((localResponse) => localResponse
5428
- ? concat(of(localResponse), drainRemoteAfterLocal(bufferedTransport$, plan))
5429
- : drainRemoteNetworkFirst(bufferedTransport$, request, plan, fallback))), { connector: () => new ReplaySubject() }));
5664
+ ? concat(of(localResponse), drainRemoteAfterLocal(bufferedTransport$, plan, replicaMutations))
5665
+ : drainRemoteNetworkFirst(bufferedTransport$, request, plan, fallback, replicaMutations))), { connector: () => new ReplaySubject() }));
5666
+ }
5667
+ /** Races a serialized local replica read against remote transport without allowing stale local data to follow remote. */
5668
+ function readFastestFirst(request, plan, transport, fallback, errorHandler, replicaMutations) {
5669
+ return defer(transport).pipe(materialize(), connect((bufferedTransport$) => {
5670
+ const localDecision$ = resolveLocalAttempt(plan, errorHandler, replicaMutations).pipe(concatMap((localResponse) => localResponse
5671
+ ? concat(of(localResponse), drainRemoteAfterLocal(bufferedTransport$, plan, replicaMutations))
5672
+ : drainRemoteNetworkFirst(bufferedTransport$, request, plan, fallback, replicaMutations)));
5673
+ // Angular transport emits Sent/progress events before the response.
5674
+ // They are not usable read results and therefore must not win the race.
5675
+ const remoteWinner$ = drainRemoteNetworkFirst(bufferedTransport$, request, plan, fallback, replicaMutations).pipe(filter((event) => event instanceof HttpResponse),
5676
+ // A remote error is not a usable response. Keep it buffered until the
5677
+ // local attempt decides whether it can satisfy the read.
5678
+ catchError(() => NEVER));
5679
+ return race(localDecision$, remoteWinner$);
5680
+ }, { connector: () => new ReplaySubject() }));
5430
5681
  }
5431
5682
  function resolveLocalAttempt(plan, errorHandler, replicaMutations) {
5432
5683
  return serializedLocalRead(plan, replicaMutations).pipe(catchError((localError) => {
5433
5684
  errorHandler.handleError(localError);
5434
5685
  return of(null);
5435
- }), concatMap((local) => (local ? tryProjectLocal(local, plan, errorHandler) : of(null))), take(1));
5686
+ }), concatMap((local) => (local ? tryProjectLocal(local, plan, errorHandler, replicaMutations) : of(null))), take(1));
5436
5687
  }
5437
5688
  /** Skips a queued local read when its HTTP subscriber leaves before the lane opens. */
5438
5689
  function serializedLocalRead(plan, replicaMutations) {
@@ -5454,26 +5705,29 @@ function serializedLocalRead(plan, replicaMutations) {
5454
5705
  };
5455
5706
  });
5456
5707
  }
5457
- function tryProjectLocal(cached, plan, errorHandler) {
5458
- return emitTaggedLocalResponse(cached, plan).pipe(catchError((error) => {
5708
+ function tryProjectLocal(cached, plan, errorHandler, replicaMutations) {
5709
+ return emitTaggedLocalResponse(cached, plan, replicaMutations).pipe(catchError((error) => {
5459
5710
  errorHandler.handleError(error);
5460
5711
  return of(null);
5461
5712
  }));
5462
5713
  }
5463
- function emitTaggedLocalResponse(cached, plan) {
5464
- return projectReadResponse(cached.clone({ headers: cached.headers.set(OFFLINE_RESPONSE_HEADER, 'local') }), plan);
5714
+ function emitTaggedLocalResponse(cached, plan, replicaMutations) {
5715
+ return projectReadResponse(cached.clone({ headers: cached.headers.set(OFFLINE_RESPONSE_HEADER, 'local') }), plan, replicaMutations);
5465
5716
  }
5466
- function drainRemoteAfterLocal(bufferedTransport$, plan) {
5467
- return bufferedTransport$.pipe(dematerialize(), catchError((error) => (isOfflineFallbackError(error) ? EMPTY : throwError(() => error))), concatMap((event) => projectReadResponse(event, plan)));
5717
+ function drainRemoteAfterLocal(bufferedTransport$, plan, replicaMutations) {
5718
+ return bufferedTransport$.pipe(dematerialize(), catchError((error) => (isOfflineFallbackError(error) ? EMPTY : throwError(() => error))), concatMap((event) => projectReadResponse(event, plan, replicaMutations)));
5468
5719
  }
5469
- function drainRemoteNetworkFirst(bufferedTransport$, request, plan, fallback) {
5470
- return bufferedTransport$.pipe(dematerialize(), catchError((error) => fallback.handle(request, error, plan) ?? throwError(() => error)), concatMap((event) => projectReadResponse(event, plan)));
5720
+ function drainRemoteNetworkFirst(bufferedTransport$, request, plan, fallback, replicaMutations) {
5721
+ return bufferedTransport$.pipe(dematerialize(), catchError((error) => fallback.handle(request, error, plan) ?? throwError(() => error)), concatMap((event) => projectReadResponse(event, plan, replicaMutations)));
5471
5722
  }
5472
- function projectReadResponse(event, plan) {
5723
+ function projectReadResponse(event, plan, replicaMutations) {
5473
5724
  if (!(event instanceof HttpResponse) || !plan.projectResponse)
5474
5725
  return of(event);
5475
5726
  const source = event.headers.get(OFFLINE_RESPONSE_HEADER) === 'local' ? 'local' : 'remote';
5476
- return from(plan.projectResponse(event, source)).pipe(map$1((response) => source === 'local' ? response.clone({ headers: response.headers.set(OFFLINE_RESPONSE_HEADER, 'local') }) : response));
5727
+ const projection = plan.serializeResponseProjection
5728
+ ? replicaMutations.runSerializedRead(() => plan.projectResponse(event, source))
5729
+ : plan.projectResponse(event, source);
5730
+ return from(projection).pipe(map$1((response) => source === 'local' ? response.clone({ headers: response.headers.set(OFFLINE_RESPONSE_HEADER, 'local') }) : response));
5477
5731
  }
5478
5732
  function observeTransport(source, network) {
5479
5733
  return source.pipe(tap({
@@ -5531,6 +5785,7 @@ async function createRandomOfflineEncryptionKey() {
5531
5785
  return Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('');
5532
5786
  }
5533
5787
  const settledSqliteOperation = async () => undefined;
5788
+ const COMMUNITY_SQLITE_OPEN_RETRY_DELAYS_MS = [50, 150, 300];
5534
5789
  const communitySqliteDrivers = new WeakMap();
5535
5790
  function sqliteErrorMessage(error) {
5536
5791
  if (error instanceof Error)
@@ -5540,6 +5795,17 @@ function sqliteErrorMessage(error) {
5540
5795
  }
5541
5796
  return String(error);
5542
5797
  }
5798
+ async function openCommunitySqliteDatabase(database) {
5799
+ for (const delayMs of COMMUNITY_SQLITE_OPEN_RETRY_DELAYS_MS) {
5800
+ const result = await database.open().then(() => ({ ok: true }), (error) => ({ ok: false, error }));
5801
+ if (result.ok)
5802
+ return;
5803
+ if (!isTransientSqliteLockError(result.error))
5804
+ throw result.error;
5805
+ await new Promise((resolve) => setTimeout(resolve, delayMs));
5806
+ }
5807
+ await database.open();
5808
+ }
5543
5809
  function normalizeCommunitySqliteDatabaseName(database) {
5544
5810
  return database.endsWith('.db') ? database.slice(0, -3) : database;
5545
5811
  }
@@ -5622,7 +5888,7 @@ function createCommunitySqliteDriver(connection, encrypted = COMMUNITY_SQLITE_EN
5622
5888
  const opening = (async () => {
5623
5889
  await ensureSecret(createEncryptionKey);
5624
5890
  const value = await createReloadSafeCommunitySqliteDatabase(connection, databaseName, encrypted);
5625
- await value.open();
5891
+ await openCommunitySqliteDatabase(value);
5626
5892
  databases.set(databaseKey, value);
5627
5893
  return value;
5628
5894
  })();
@@ -5848,26 +6114,21 @@ class SqliteOfflineRepository {
5848
6114
  async putCommand(command) {
5849
6115
  await this.#queueWrite((databaseId) => this.#putCommand(databaseId, command));
5850
6116
  }
6117
+ /** @deprecated Use {@link transactReplica} with `putCommands`. */
5851
6118
  replaceCommand(command) {
5852
6119
  return this.putCommand(command);
5853
6120
  }
5854
- async removeCommand(commandId) {
5855
- await this.#write('DELETE FROM offline_sync_commands WHERE command_id = ?', [commandId]);
6121
+ /** @deprecated Use {@link transactReplica} with `removeCommandIds`. */
6122
+ removeCommand(commandId) {
6123
+ return this.transactReplica({ removeCommandIds: [commandId] });
5856
6124
  }
5857
- async putPullAttention(attention) {
5858
- await this.#write(`INSERT INTO offline_pull_attentions (user_id, scope_id, reason, status) VALUES (?, ?, ?, ?)
5859
- ON CONFLICT(user_id, scope_id) DO UPDATE SET reason = excluded.reason, status = excluded.status`, [
5860
- canonicalOfflinePrincipalId(attention.userId),
5861
- attention.scopeId,
5862
- attention.reason,
5863
- attention.status === undefined ? null : attention.status,
5864
- ]);
6125
+ /** @deprecated Use {@link transactReplica} with `putPullAttentions`. */
6126
+ putPullAttention(attention) {
6127
+ return this.transactReplica({ putPullAttentions: [attention] });
5865
6128
  }
5866
- async removePullAttention(scope) {
5867
- await this.#write('DELETE FROM offline_pull_attentions WHERE user_id = ? AND scope_id = ?', [
5868
- canonicalOfflinePrincipalId(scope.userId),
5869
- scope.scopeId,
5870
- ]);
6129
+ /** @deprecated Use {@link transactReplica} with `removePullAttentions`. */
6130
+ removePullAttention(scope) {
6131
+ return this.transactReplica({ removePullAttentions: [scope] });
5871
6132
  }
5872
6133
  async clearUser(userId) {
5873
6134
  await this.#transaction((database) => this.#clearUser(database, userId));
@@ -6109,7 +6370,9 @@ class SqliteOfflineRepository {
6109
6370
  ON CONFLICT(id) DO UPDATE SET version = excluded.version, schema_hash = excluded.schema_hash`, [version, schemaHash]);
6110
6371
  }
6111
6372
  async #nativeTransaction(databaseId, run) {
6112
- await this.#sqlite.beginTransaction({ databaseId });
6373
+ await this.#sqlite.beginTransaction({ databaseId }).catch((error) => {
6374
+ throw normalizeOfflineReplicaTransientWriteError(error);
6375
+ });
6113
6376
  const execute = async () => run();
6114
6377
  return execute()
6115
6378
  .then(async (result) => {
@@ -6117,13 +6380,14 @@ class SqliteOfflineRepository {
6117
6380
  return result;
6118
6381
  })
6119
6382
  .catch(async (error) => {
6383
+ const normalizedError = normalizeOfflineReplicaTransientWriteError(error);
6120
6384
  const rollback = await this.#sqlite.rollbackTransaction({ databaseId }).then(() => ({ status: 'fulfilled' }), (rollbackError) => ({ status: 'rejected', rollbackError }));
6121
6385
  if (rollback.status === 'rejected') {
6122
- throw new AggregateError([error, rollback.rollbackError], 'Offline SQLite transaction and rollback both failed.', {
6123
- cause: error,
6386
+ throw new AggregateError([normalizedError, rollback.rollbackError], 'Offline SQLite transaction and rollback both failed.', {
6387
+ cause: normalizedError,
6124
6388
  });
6125
6389
  }
6126
- throw error;
6390
+ throw normalizedError;
6127
6391
  });
6128
6392
  }
6129
6393
  async #databaseConnection() {
@@ -6346,7 +6610,7 @@ class SqliteOfflineRepository {
6346
6610
  await this.#execute(databaseId, 'UPDATE offline_metadata SET schema_version = schema_version WHERE id = 1');
6347
6611
  const actual = await this.#dataVersion(databaseId);
6348
6612
  if (actual !== expected) {
6349
- throw new Error('Offline replica changed through another SQLite connection; retry the operation from fresh state.');
6613
+ throw new OfflineReplicaTransientWriteError('concurrent_revision', 'Offline replica changed through another SQLite connection; retry the operation from fresh state.');
6350
6614
  }
6351
6615
  return run(databaseId);
6352
6616
  });
@@ -6951,11 +7215,20 @@ function assertSupportedOfflineMode(platform, mode) {
6951
7215
  }
6952
7216
  }
6953
7217
 
6954
- /** Standard scoped local replica and outbox runtime for offline-capable Ionic applications. */
7218
+ /**
7219
+ * Experimental scoped local replica and outbox runtime for offline-capable Ionic applications.
7220
+ *
7221
+ * This entry point is not covered by the package's SemVer compatibility guarantee. Its public
7222
+ * APIs, persistence schema, and synchronization behavior may change incompatibly in a minor or
7223
+ * patch release before stabilization.
7224
+ *
7225
+ * @packageDocumentation
7226
+ * @experimental
7227
+ */
6955
7228
 
6956
7229
  /**
6957
7230
  * Generated bundle index. Do not edit.
6958
7231
  */
6959
7232
 
6960
- 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_COMPLETE_HEADER, OFFLINE_RESPONSE_HEADER, OFFLINE_RETRY_RANDOM, OFFLINE_SCHEMA_VERSION, OFFLINE_SYNC_CONTEXT, OfflineCommandInFlightError, OfflineCoordinatorService, OfflineMutationPersistenceDisabledError, OfflineMutationPersistencePendingError, OfflineMutationPersistenceRequiresOnlineError, OfflineMutationPersistenceService, OfflineMutationPolicyConflictError, OfflineMutationProtocolError, OfflineMutationRequestPolicyRegistry, OfflineNetworkService, OfflineOutboxCapacityError, OfflinePayloadValidationError, OfflineReplicaMutationCoordinator, OfflineReplicaPullService, OfflineReplicaSchemaMismatchError, OfflineRequestFallbackService, OfflineRequestPolicyRegistry, OfflineRouteInitializerService, 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, migrateOfflineDatabaseEncryption, naturalKey, normalizeOfflineNaturalKey, normalizeOfflineReplicaPullPage, nullable, offlineAggregateIntentMutations, offlineCommandLookupIdentity, offlineCommandTargetFromReplicaRow, offlineCommandWithBaseRevision, offlineGeneratedReplicaIdentity, offlineInterceptor, offlineNaturalKeyFromValues, offlineNaturalReplicaIdentity, offlineReadEmission, offlineReadSource, offlineReplicaRemoteIdentity, offlineRetryDelayMs, offlineSessionManifestAllows, parseOfflineCommandIdentity, parseOfflineMutationEnvelope, parseOfflinePrincipalId, projectOfflineReplicaValues, provideOffline, provideOfflineMutationRequestPolicy, provideOfflineRequestPolicy, provideRouteScopedOffline, real, recoverOfflineLocalReset, replicaAddressFromIdentity, requestOfflineLocalReset, requirePositiveOfflineInteger, selectOfflineRepository, serializeOfflineCommandIdentity, sha256OfflineReplicaSchema, shouldCommitOfflineCollection, supportsSynchronizedOfflineRepository, text };
7233
+ 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_COMPLETE_HEADER, OFFLINE_RESPONSE_HEADER, OFFLINE_RETRY_RANDOM, OFFLINE_SCHEMA_VERSION, OFFLINE_SYNC_CONTEXT, OfflineCommandInFlightError, OfflineCoordinatorService, OfflineImmediateCommandRejectedError, OfflineMutationPersistenceDisabledError, OfflineMutationPersistencePendingError, OfflineMutationPersistenceRequiresOnlineError, OfflineMutationPersistenceService, OfflineMutationPolicyConflictError, OfflineMutationProtocolError, OfflineMutationRequestPolicyRegistry, OfflineNetworkService, OfflineOutboxCapacityError, OfflinePayloadValidationError, OfflineReplicaMutationCoordinator, OfflineReplicaPullService, OfflineReplicaSchemaMismatchError, OfflineRequestFallbackService, OfflineRequestPolicyRegistry, OfflineRouteInitializerService, 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, migrateOfflineDatabaseEncryption, naturalKey, normalizeOfflineNaturalKey, normalizeOfflineReplicaPullPage, nullable, offlineAggregateIntentMutations, offlineCommandLookupIdentity, offlineCommandTargetFromReplicaRow, offlineCommandWithBaseRevision, offlineGeneratedReplicaIdentity, offlineInterceptor, offlineNaturalKeyFromValues, offlineNaturalReplicaIdentity, offlineReadEmission, offlineReadSource, offlineReplicaRemoteIdentity, offlineRetryDelayMs, offlineSessionManifestAllows, parseOfflineCommandIdentity, parseOfflineMutationEnvelope, parseOfflinePrincipalId, projectOfflineReplicaValues, provideOffline, provideOfflineMutationRequestPolicy, provideOfflineRequestPolicy, provideRouteScopedOffline, real, recoverOfflineLocalReset, replicaAddressFromIdentity, requestOfflineLocalReset, requirePositiveOfflineInteger, selectOfflineRepository, serializeOfflineCommandIdentity, sha256OfflineReplicaSchema, shouldCommitOfflineCollection, supportsSynchronizedOfflineRepository, text };
6961
7234
  //# sourceMappingURL=rdlabo-ionic-angular-kit-offline.mjs.map