@rdlabo/ionic-angular-kit 22.0.0-beta.pr97.shac93e32c6e176 → 22.0.0-beta.pr98.sha390e3b036629

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, filter, NEVER, race, 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,33 @@ 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 normalizeOfflineReplicaTransientWriteError(error) {
945
+ if (error instanceof OfflineReplicaTransientWriteError)
946
+ return error;
947
+ const code = typeof error === 'object' && error !== null && typeof error.code === 'string'
948
+ ? error.code.toUpperCase()
949
+ : '';
950
+ const message = error instanceof Error ? error.message : typeof error === 'string' ? error : '';
951
+ const normalizedMessage = message.toUpperCase();
952
+ if (code.includes('SQLITE_BUSY') || normalizedMessage.includes('SQLITE_BUSY')) {
953
+ return new OfflineReplicaTransientWriteError('sqlite_busy', message || 'SQLite is busy.', { cause: error });
954
+ }
955
+ if (code.includes('SQLITE_LOCKED') ||
956
+ normalizedMessage.includes('SQLITE_LOCKED') ||
957
+ message.includes('database is locked') ||
958
+ message.includes('database table is locked')) {
959
+ return new OfflineReplicaTransientWriteError('sqlite_locked', message || 'SQLite database is locked.', { cause: error });
960
+ }
961
+ return error;
962
+ }
936
963
 
937
964
  /** Current durable storage schema used by both web and native repositories. */
938
965
  const OFFLINE_SCHEMA_VERSION = 2;
@@ -2824,6 +2851,15 @@ class OfflinePayloadValidationError extends Error {
2824
2851
  this.name = 'OfflinePayloadValidationError';
2825
2852
  }
2826
2853
  }
2854
+ /** A foreground durable-command send reached a terminal server-side state. */
2855
+ class OfflineImmediateCommandRejectedError extends Error {
2856
+ constructor(state, code) {
2857
+ super(`Immediate offline command delivery ended in ${state}${code ? ` (${code})` : ''}.`);
2858
+ this.state = state;
2859
+ this.code = code;
2860
+ this.name = 'OfflineImmediateCommandRejectedError';
2861
+ }
2862
+ }
2827
2863
  /** Raised before persistence when retaining another command would exceed the configured durable Outbox capacity. */
2828
2864
  class OfflineOutboxCapacityError extends Error {
2829
2865
  constructor(reason, currentCommands, currentBytes) {
@@ -2896,6 +2932,7 @@ class OfflineSyncService {
2896
2932
  #flushTransitions;
2897
2933
  #generation;
2898
2934
  #sendingTransitions;
2935
+ #commandSendTransitions;
2899
2936
  #retryTimer;
2900
2937
  /** When non-null, automatic flushes pull only foreground scopes plus Outbox scopes. */
2901
2938
  #foregroundScopePolicy;
@@ -2930,6 +2967,7 @@ class OfflineSyncService {
2930
2967
  this.#flushTransitions = new Set();
2931
2968
  this.#generation = 0;
2932
2969
  this.#sendingTransitions = new Set();
2970
+ this.#commandSendTransitions = new Map();
2933
2971
  this.#retryTimer = null;
2934
2972
  /** When non-null, automatic flushes pull only foreground scopes plus Outbox scopes. */
2935
2973
  this.#foregroundScopePolicy = null;
@@ -3235,7 +3273,10 @@ class OfflineSyncService {
3235
3273
  this.noteScope(scope);
3236
3274
  const commandIdentity = offlineCommandLookupIdentity(request.identity);
3237
3275
  const normalized = await this.#normalizeEnqueueRequest(scope, request, commandIdentity, repository);
3238
- const commandId = crypto.randomUUID();
3276
+ const commandId = request.commandId ?? crypto.randomUUID();
3277
+ if (typeof commandId !== 'string' || commandId.length === 0 || commandId.length > 255) {
3278
+ throw new Error('Offline command id must contain between 1 and 255 characters.');
3279
+ }
3239
3280
  const sourceKey = this.#hooks.entityType(request);
3240
3281
  const localOnlyFootprint = this.#normalizedLocalOnlyFootprint(scope, request.localOnlyFootprint);
3241
3282
  if (replaced)
@@ -3351,6 +3392,7 @@ class OfflineSyncService {
3351
3392
  #assertDistinctBatchFootprints(entries, existingCommands, allowOneAggregate = false) {
3352
3393
  const aggregates = new Set();
3353
3394
  const replicaKeys = new Set();
3395
+ const commandIds = new Set(existingCommands.map((command) => command.commandId));
3354
3396
  const existingFootprints = new Map();
3355
3397
  for (const command of existingCommands) {
3356
3398
  const aggregate = this.#aggregateKey(command);
@@ -3358,6 +3400,10 @@ class OfflineSyncService {
3358
3400
  existingFootprints.set(key, aggregate);
3359
3401
  }
3360
3402
  for (const entry of entries) {
3403
+ if (commandIds.has(entry.command.commandId)) {
3404
+ throw new Error(`Offline command id ${entry.command.commandId} is already in use.`);
3405
+ }
3406
+ commandIds.add(entry.command.commandId);
3361
3407
  const aggregate = this.#aggregateKey(entry.command);
3362
3408
  if (aggregates.has(aggregate) && !allowOneAggregate) {
3363
3409
  throw new Error('Prepared offline batch contains overlapping aggregate intents.');
@@ -3555,11 +3601,148 @@ class OfflineSyncService {
3555
3601
  const generation = this.#generation;
3556
3602
  return this.#flushAfterInitialization(generation);
3557
3603
  }
3604
+ /**
3605
+ * Sends one newly-created generated aggregate immediately after its durable
3606
+ * enqueue, without waiting for a pre-send pull.
3607
+ *
3608
+ * This fast path is deliberately narrow: the command must still be pending,
3609
+ * have no remote id or confirmed baseline, and be the first intent for its
3610
+ * aggregate. Existing aggregates continue through {@link flush}, where the
3611
+ * pre-pull conflict barrier remains mandatory. Authoritative pull
3612
+ * reconciliation is scheduled in the background after the local transport
3613
+ * acknowledgement has been committed.
3614
+ *
3615
+ * @returns The generated remote id when transport completed locally, or
3616
+ * `null` when transport is unavailable or did not produce a confirmed id.
3617
+ */
3618
+ async sendGeneratedCommandNow(commandId, locator) {
3619
+ const generation = this.#generation;
3620
+ if (!(await this.#restoreCurrentGeneration(generation)))
3621
+ return null;
3622
+ const userId = this.#activeUserId;
3623
+ if (userId === null)
3624
+ return null;
3625
+ return this.#beginGeneratedCommandSend(commandId, locator, generation, userId);
3626
+ }
3558
3627
  async #flushAfterInitialization(generation) {
3559
3628
  if (!(await this.#restoreCurrentGeneration(generation)))
3560
3629
  return;
3561
3630
  return this.#beginFlush(true);
3562
3631
  }
3632
+ #beginGeneratedCommandSend(commandId, locator, generation, userId) {
3633
+ const result = this.#runGeneratedCommandSend(commandId, locator, generation, userId);
3634
+ let requiresReconciliation = false;
3635
+ const transition = result
3636
+ .then((remoteId) => {
3637
+ requiresReconciliation = remoteId !== null;
3638
+ }, () => undefined)
3639
+ .finally(() => {
3640
+ this.#flushTransitions.delete(transition);
3641
+ if (requiresReconciliation && this.#canSynchronize() && this.#isCurrentUser(generation, userId)) {
3642
+ // A normal flush may already be in its post-pull phase. Ensure the
3643
+ // newly acknowledged command receives a later reconciliation pass.
3644
+ if (this.#flushPromise)
3645
+ this.#resumeAfterFlush = true;
3646
+ queueMicrotask(() => this.#flushInBackground());
3647
+ }
3648
+ });
3649
+ this.#flushTransitions.add(transition);
3650
+ return result;
3651
+ }
3652
+ async #runGeneratedCommandSend(commandId, locator, generation, userId) {
3653
+ if (!this.#isCurrentUser(generation, userId))
3654
+ return null;
3655
+ if (!this.#canSynchronize()) {
3656
+ await this.#refreshState(generation);
3657
+ return null;
3658
+ }
3659
+ if (this.#pullAttentions().length > 0)
3660
+ return null;
3661
+ if (!(await this.#discoverScopes(generation)))
3662
+ return null;
3663
+ if (!this.#isCurrentUser(generation, userId))
3664
+ return null;
3665
+ const known = await this.#readKnownCommands();
3666
+ if (!this.#isCurrentUser(generation, userId))
3667
+ return null;
3668
+ const command = known.find((candidate) => candidate.commandId === commandId);
3669
+ if (!command)
3670
+ return this.#generatedRemoteId(locator, userId, generation);
3671
+ if (command.userId !== userId)
3672
+ return null;
3673
+ if (command.scopeId !== locator.scopeId ||
3674
+ command.sourceKey !== locator.sourceKey ||
3675
+ command.identity.kind !== 'generated' ||
3676
+ command.identity.localId !== locator.localId) {
3677
+ throw new Error('Immediate generated command locator does not match the durable command.');
3678
+ }
3679
+ if (command.state === 'awaiting_pull') {
3680
+ return this.#commandReconciliationRemoteId(command) ?? this.#generatedRemoteId(locator, userId, generation);
3681
+ }
3682
+ if (command.state === 'sending') {
3683
+ const activeSend = this.#commandSendTransitions.get(this.#commandSendKey(command, generation));
3684
+ if (activeSend)
3685
+ await activeSend;
3686
+ return this.#generatedCommandOutcome(commandId, locator, generation, userId);
3687
+ }
3688
+ if (command.state !== 'pending')
3689
+ return null;
3690
+ const aggregate = known.filter((candidate) => this.#aggregateKey(candidate) === this.#aggregateKey(command));
3691
+ if (aggregate[0]?.commandId !== command.commandId) {
3692
+ throw new Error('Immediate generated command delivery requires the first aggregate intent.');
3693
+ }
3694
+ const row = await this.#rowForCommand(command);
3695
+ if (!row ||
3696
+ row.identity.kind !== 'generated' ||
3697
+ row.identity.remoteId !== null ||
3698
+ row.confirmedValues !== null ||
3699
+ command.identity.kind !== 'generated' ||
3700
+ command.baseRevision !== null ||
3701
+ command.replicaMutation === 'delete') {
3702
+ throw new Error('Immediate generated command delivery requires a new unconfirmed aggregate.');
3703
+ }
3704
+ const scope = { userId: command.userId, scopeId: command.scopeId };
3705
+ const scopeKey = this.#scopeKey(scope);
3706
+ if (!this.#knownScopes.has(scopeKey))
3707
+ return null;
3708
+ const dirtyScopes = new Map();
3709
+ await this.#sendAggregate([command], generation, dirtyScopes, new Set([scopeKey]));
3710
+ if (!this.#isCurrentUser(generation, userId))
3711
+ return null;
3712
+ for (const dirtyScope of dirtyScopes.values()) {
3713
+ this.#pendingPullScopes.set(this.#scopeKey(dirtyScope), dirtyScope);
3714
+ }
3715
+ return this.#generatedCommandOutcome(commandId, locator, generation, userId);
3716
+ }
3717
+ async #generatedCommandOutcome(commandId, locator, generation, userId) {
3718
+ if (!this.#isCurrentUser(generation, userId))
3719
+ return null;
3720
+ await this.#refreshState(generation);
3721
+ if (!this.#isCurrentUser(generation, userId))
3722
+ return null;
3723
+ const completed = (await this.#readKnownCommands()).find((candidate) => candidate.commandId === commandId);
3724
+ if (!this.#isCurrentUser(generation, userId))
3725
+ return null;
3726
+ if (completed && ['blocked_auth', 'rejected', 'conflict'].includes(completed.state)) {
3727
+ throw new OfflineImmediateCommandRejectedError(completed.state, completed.lastErrorCode);
3728
+ }
3729
+ return completed
3730
+ ? (this.#commandReconciliationRemoteId(completed) ?? this.#generatedRemoteId(locator, userId, generation))
3731
+ : this.#generatedRemoteId(locator, userId, generation);
3732
+ }
3733
+ async #generatedRemoteId(locator, userId, generation) {
3734
+ if (!this.#isCurrentUser(generation, userId))
3735
+ return null;
3736
+ const row = await this.#repository.getReplicaRow({ userId, scopeId: locator.scopeId }, locator.sourceKey, {
3737
+ kind: 'generated',
3738
+ localId: locator.localId,
3739
+ });
3740
+ return this.#isCurrentUser(generation, userId) && row?.identity.kind === 'generated' ? row.identity.remoteId : null;
3741
+ }
3742
+ #commandReconciliationRemoteId(command) {
3743
+ const identity = command.reconciliationIdentity;
3744
+ return identity && 'remoteId' in identity ? (identity.remoteId ?? null) : null;
3745
+ }
3563
3746
  #beginFlush(explicitFull) {
3564
3747
  const lifecycleRevision = this.#lifecycleRevision();
3565
3748
  const isPartial = !explicitFull && this.#foregroundScopePolicy !== null;
@@ -3829,75 +4012,94 @@ class OfflineSyncService {
3829
4012
  }
3830
4013
  async #sendAggregate(commands, generation, dirtyScopes, pulledScopeKeys) {
3831
4014
  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))
3839
- 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 })))
4015
+ if (!(await this.#sendCommandOnce(commands, command, generation, dirtyScopes, pulledScopeKeys)))
3843
4016
  break;
3844
- let sending = await this.#claimSendingCommand(command, generation);
3845
- if (!sending)
3846
- return;
4017
+ }
4018
+ }
4019
+ #sendCommandOnce(aggregateCommands, command, generation, dirtyScopes, pulledScopeKeys) {
4020
+ const transitionKey = this.#commandSendKey(command, generation);
4021
+ const active = this.#commandSendTransitions.get(transitionKey);
4022
+ if (active)
4023
+ return active;
4024
+ const transition = this.#sendCommand(aggregateCommands, command, generation, dirtyScopes, pulledScopeKeys).finally(() => {
4025
+ if (this.#commandSendTransitions.get(transitionKey) === transition) {
4026
+ this.#commandSendTransitions.delete(transitionKey);
4027
+ }
4028
+ });
4029
+ this.#commandSendTransitions.set(transitionKey, transition);
4030
+ return transition;
4031
+ }
4032
+ #commandSendKey(command, generation) {
4033
+ return JSON.stringify([generation, canonicalOfflinePrincipalId(command.userId), command.commandId]);
4034
+ }
4035
+ async #sendCommand(aggregateCommands, command, generation, dirtyScopes, pulledScopeKeys) {
4036
+ if (!this.#isCurrent(generation))
4037
+ return false;
4038
+ if (command.state === 'awaiting_pull')
4039
+ return true;
4040
+ if (command.state === 'retry_wait' && (command.retryAt ?? 0) > Date.now())
4041
+ return false;
4042
+ if (!['pending', 'retry_wait'].includes(command.state))
4043
+ return false;
4044
+ // User-scoped aggregates ignore scopeId in the FIFO key, so later commands may
4045
+ // belong to scopes that failed pre-pull even when the head was admitted.
4046
+ if (!pulledScopeKeys.has(this.#scopeKey({ userId: command.userId, scopeId: command.scopeId })))
4047
+ return false;
4048
+ let sending = await this.#claimSendingCommand(command, generation);
4049
+ if (!sending || !this.#isCurrent(generation))
4050
+ return false;
4051
+ await this.#refreshState(generation);
4052
+ if (!this.#isCurrent(generation))
4053
+ return false;
4054
+ const claimedCommand = sending;
4055
+ const readRow = async () => this.#rowForCommand(claimedCommand);
4056
+ const rowResult = await readRow().then((row) => ({ status: 'fulfilled', row }), (error) => ({ status: 'rejected', error }));
4057
+ if (rowResult.status === 'rejected') {
3847
4058
  if (!this.#isCurrent(generation))
3848
- return;
3849
- await this.#refreshState(generation);
4059
+ return false;
4060
+ await this.#persistFailedCommand(sending, rowResult.error, generation, null, sending.serverCommitUnknown === true);
4061
+ throw rowResult.error;
4062
+ }
4063
+ const row = rowResult.row;
4064
+ if (!row) {
4065
+ const error = new Error(`Offline replica row not found: ${sending.aggregateType}/${canonicalOfflineCommandIdentity(sending.identity)}`);
4066
+ await this.#persistFailedCommand(sending, error, generation, null, sending.serverCommitUnknown === true);
4067
+ throw error;
4068
+ }
4069
+ const priorCommitUnknown = sending.serverCommitUnknown === true;
4070
+ const transportCommand = await this.#markTransportStarted(sending, generation);
4071
+ if (!transportCommand)
4072
+ return false;
4073
+ sending = transportCommand;
4074
+ const executeCommand = async () => this.#executor.execute(sending, offlineCommandTargetFromReplicaRow(row));
4075
+ const execution = await executeCommand().then((result) => ({ status: 'fulfilled', result }), (error) => ({ status: 'rejected', error }));
4076
+ if (execution.status === 'rejected') {
3850
4077
  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;
4078
+ return false;
4079
+ const commitUnknown = this.#executor.provesCommandNotCommitted?.(execution.error, sending)
4080
+ ? false
4081
+ : priorCommitUnknown || this.#serverCommitCouldBeUnknown(execution.error);
4082
+ await this.#persistFailedCommand(sending, execution.error, generation, row, commitUnknown);
4083
+ if (!this.#isClassifiableTransportError(execution.error))
4084
+ throw execution.error;
4085
+ return false;
4086
+ }
4087
+ const result = execution.result;
4088
+ if (!this.#isCurrent(generation))
4089
+ return false;
4090
+ const completeCommand = async () => this.#completeCommandWithRetry(aggregateCommands, sending, result, generation);
4091
+ const completion = await completeCommand().then(() => ({ status: 'fulfilled' }), (error) => ({ status: 'rejected', error }));
4092
+ if (completion.status === 'rejected') {
3886
4093
  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
- }
4094
+ return false;
4095
+ await this.#persistFailedCommand(sending, completion.error, generation, row, true);
4096
+ throw completion.error;
3900
4097
  }
4098
+ if (this.#isCurrent(generation)) {
4099
+ const scope = { userId: sending.userId, scopeId: sending.scopeId };
4100
+ dirtyScopes.set(this.#scopeKey(scope), scope);
4101
+ }
4102
+ return true;
3901
4103
  }
3902
4104
  async #normalizeEnqueueRequest(scope, request, commandIdentity, repository) {
3903
4105
  let baseRevision = request.baseRevision ?? null;
@@ -3911,6 +4113,18 @@ class OfflineSyncService {
3911
4113
  async #completeCommand(commands, command, result, generation) {
3912
4114
  return this.#serializeReplicaMutation((repository) => this.#completeCommandLocked(commands, command, result, generation, repository));
3913
4115
  }
4116
+ async #completeCommandWithRetry(commands, command, result, generation) {
4117
+ return this.#completeCommand(commands, command, result, generation).catch(async (firstError) => {
4118
+ if (!isRetryableLocalCompletionError(firstError))
4119
+ throw firstError;
4120
+ const retry = await this.#completeCommand(commands, command, result, generation).then(() => ({ status: 'fulfilled' }), (error) => ({ status: 'rejected', error }));
4121
+ if (retry.status === 'fulfilled')
4122
+ return;
4123
+ if (!isRetryableLocalCompletionError(retry.error))
4124
+ throw retry.error;
4125
+ throw new OfflineLocalCompletionError(retry.error, firstError);
4126
+ });
4127
+ }
3914
4128
  async #completeCommandLocked(commands, command, result, generation, repository) {
3915
4129
  if (result.clearRemoteId === true && result.remoteId !== undefined) {
3916
4130
  throw new Error('Offline command cannot return remoteId and clearRemoteId together.');
@@ -4093,7 +4307,7 @@ class OfflineSyncService {
4093
4307
  ...command,
4094
4308
  state: 'retry_wait',
4095
4309
  retryAt,
4096
- lastErrorCode: status > 0 ? String(status) : 'network',
4310
+ lastErrorCode: error instanceof OfflineLocalCompletionError ? 'local_completion' : status > 0 ? String(status) : 'network',
4097
4311
  serverCommitUnknown,
4098
4312
  };
4099
4313
  }
@@ -4315,6 +4529,9 @@ class OfflineSyncService {
4315
4529
  #isCurrent(generation) {
4316
4530
  return generation === this.#generation;
4317
4531
  }
4532
+ #isCurrentUser(generation, userId) {
4533
+ return this.#isCurrent(generation) && this.#activeUserId === userId;
4534
+ }
4318
4535
  async #restoreInterruptedCommands() {
4319
4536
  const commands = await this.#readKnownCommands();
4320
4537
  await Promise.all(commands
@@ -4396,7 +4613,7 @@ class OfflineSyncService {
4396
4613
  this.#pendingPullScopes.delete(this.#scopeKey(scope));
4397
4614
  }
4398
4615
  async #waitForSendingTransitions() {
4399
- await Promise.allSettled([...this.#sendingTransitions]);
4616
+ await Promise.allSettled([...this.#sendingTransitions, ...this.#commandSendTransitions.values()]);
4400
4617
  }
4401
4618
  #canonicalJson(value) {
4402
4619
  if (Array.isArray(value))
@@ -4432,6 +4649,17 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.3", ngImpor
4432
4649
  function compareOfflineCommands(left, right) {
4433
4650
  return left.createdAt - right.createdAt || (left.commandId < right.commandId ? -1 : left.commandId > right.commandId ? 1 : 0);
4434
4651
  }
4652
+ class OfflineLocalCompletionError extends AggregateError {
4653
+ constructor(retryError, firstError) {
4654
+ super([firstError, retryError], 'Offline command reached the server but local acknowledgement could not be persisted.', {
4655
+ cause: retryError,
4656
+ });
4657
+ this.name = 'OfflineLocalCompletionError';
4658
+ }
4659
+ }
4660
+ function isRetryableLocalCompletionError(error) {
4661
+ return error instanceof OfflineReplicaTransientWriteError;
4662
+ }
4435
4663
 
4436
4664
  /** Raised when disabling requires pending commands to be synchronized while transport is offline. */
4437
4665
  class OfflineMutationPersistenceRequiresOnlineError extends Error {
@@ -4826,6 +5054,7 @@ class OfflineCoordinatorService {
4826
5054
  ...(ngDevMode ? [{ debugName: "isStorageReady" }] : /* istanbul ignore next */ []));
4827
5055
  this.networkState = this.#network.state;
4828
5056
  this.syncState = this.#sync.syncState;
5057
+ this.pendingCommands = this.#sync.pendingCommands;
4829
5058
  this.pendingCount = this.#sync.pendingCount;
4830
5059
  this.conflicts = this.#sync.conflicts;
4831
5060
  /** Device-local control for accepting new durable Outbox mutations. */
@@ -5391,6 +5620,9 @@ const offlineInterceptor = (request, next) => {
5391
5620
  const plan = registry.resolve(request);
5392
5621
  if (!plan)
5393
5622
  return transport();
5623
+ if (plan.readStrategy === 'local-only') {
5624
+ return readLocalOnly(plan, inject(ErrorHandler), inject(OfflineReplicaMutationCoordinator));
5625
+ }
5394
5626
  if (plan.readStrategy === 'local-first') {
5395
5627
  return readLocalFirst(request, plan, transport, fallback, inject(ErrorHandler), inject(OfflineReplicaMutationCoordinator));
5396
5628
  }
@@ -5409,6 +5641,10 @@ const offlineInterceptor = (request, next) => {
5409
5641
  }
5410
5642
  return transport();
5411
5643
  };
5644
+ /** Resolves a provisional/local identity without starting remote transport. */
5645
+ function readLocalOnly(plan, errorHandler, replicaMutations) {
5646
+ return resolveLocalAttempt(plan, errorHandler, replicaMutations).pipe(concatMap((response) => (response ? of(response) : EMPTY)));
5647
+ }
5412
5648
  function readNetworkFirst(request, plan, transport, fallback, replicaMutations) {
5413
5649
  return defer(transport).pipe(catchError((error) => fallback.handle(request, error, plan) ?? throwError(() => error)), concatMap((event) => projectReadResponse(event, plan, replicaMutations)));
5414
5650
  }
@@ -5490,7 +5726,10 @@ function projectReadResponse(event, plan, replicaMutations) {
5490
5726
  if (!(event instanceof HttpResponse) || !plan.projectResponse)
5491
5727
  return of(event);
5492
5728
  const source = event.headers.get(OFFLINE_RESPONSE_HEADER) === 'local' ? 'local' : 'remote';
5493
- return from(replicaMutations.runSerializedRead(() => plan.projectResponse(event, source))).pipe(map$1((response) => source === 'local' ? response.clone({ headers: response.headers.set(OFFLINE_RESPONSE_HEADER, 'local') }) : response));
5729
+ const projection = plan.serializeResponseProjection
5730
+ ? replicaMutations.runSerializedRead(() => plan.projectResponse(event, source))
5731
+ : plan.projectResponse(event, source);
5732
+ return from(projection).pipe(map$1((response) => source === 'local' ? response.clone({ headers: response.headers.set(OFFLINE_RESPONSE_HEADER, 'local') }) : response));
5494
5733
  }
5495
5734
  function observeTransport(source, network) {
5496
5735
  return source.pipe(tap({
@@ -6126,7 +6365,9 @@ class SqliteOfflineRepository {
6126
6365
  ON CONFLICT(id) DO UPDATE SET version = excluded.version, schema_hash = excluded.schema_hash`, [version, schemaHash]);
6127
6366
  }
6128
6367
  async #nativeTransaction(databaseId, run) {
6129
- await this.#sqlite.beginTransaction({ databaseId });
6368
+ await this.#sqlite.beginTransaction({ databaseId }).catch((error) => {
6369
+ throw normalizeOfflineReplicaTransientWriteError(error);
6370
+ });
6130
6371
  const execute = async () => run();
6131
6372
  return execute()
6132
6373
  .then(async (result) => {
@@ -6134,13 +6375,14 @@ class SqliteOfflineRepository {
6134
6375
  return result;
6135
6376
  })
6136
6377
  .catch(async (error) => {
6378
+ const normalizedError = normalizeOfflineReplicaTransientWriteError(error);
6137
6379
  const rollback = await this.#sqlite.rollbackTransaction({ databaseId }).then(() => ({ status: 'fulfilled' }), (rollbackError) => ({ status: 'rejected', rollbackError }));
6138
6380
  if (rollback.status === 'rejected') {
6139
- throw new AggregateError([error, rollback.rollbackError], 'Offline SQLite transaction and rollback both failed.', {
6140
- cause: error,
6381
+ throw new AggregateError([normalizedError, rollback.rollbackError], 'Offline SQLite transaction and rollback both failed.', {
6382
+ cause: normalizedError,
6141
6383
  });
6142
6384
  }
6143
- throw error;
6385
+ throw normalizedError;
6144
6386
  });
6145
6387
  }
6146
6388
  async #databaseConnection() {
@@ -6363,7 +6605,7 @@ class SqliteOfflineRepository {
6363
6605
  await this.#execute(databaseId, 'UPDATE offline_metadata SET schema_version = schema_version WHERE id = 1');
6364
6606
  const actual = await this.#dataVersion(databaseId);
6365
6607
  if (actual !== expected) {
6366
- throw new Error('Offline replica changed through another SQLite connection; retry the operation from fresh state.');
6608
+ throw new OfflineReplicaTransientWriteError('concurrent_revision', 'Offline replica changed through another SQLite connection; retry the operation from fresh state.');
6367
6609
  }
6368
6610
  return run(databaseId);
6369
6611
  });
@@ -6974,5 +7216,5 @@ function assertSupportedOfflineMode(platform, mode) {
6974
7216
  * Generated bundle index. Do not edit.
6975
7217
  */
6976
7218
 
6977
- 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 };
7219
+ 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 };
6978
7220
  //# sourceMappingURL=rdlabo-ionic-angular-kit-offline.mjs.map