@rdlabo/ionic-angular-kit 22.0.0-beta.pr94.sha870257bc2bf6 → 22.0.0-beta.pr96.sha53b4ae63682a

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, catchError, throwError, concatMap, materialize, connect, concat, of, ReplaySubject, filter, NEVER, race, take, Observable, dematerialize, EMPTY, 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_]*$/;
@@ -3098,7 +3098,7 @@ class OfflineSyncService {
3098
3098
  await this.#ensureInitialized();
3099
3099
  if (!this.#isCurrent(generation))
3100
3100
  throw new Error('Offline session changed before prepared replacement.');
3101
- const knownCommands = await this.#readKnownCommands();
3101
+ const knownCommands = await this.#readKnownCommands(repository);
3102
3102
  const replaced = knownCommands.find((command) => command.commandId === commandId);
3103
3103
  if (!replaced)
3104
3104
  throw new Error(`Offline command ${commandId} no longer exists.`);
@@ -3123,7 +3123,7 @@ class OfflineSyncService {
3123
3123
  await this.#ensureInitialized();
3124
3124
  if (!this.#isCurrent(generation))
3125
3125
  throw new Error('Offline session changed before prepared aggregate replacement.');
3126
- const knownCommands = await this.#readKnownCommands();
3126
+ const knownCommands = await this.#readKnownCommands(repository);
3127
3127
  const selected = knownCommands.find((command) => command.commandId === commandId);
3128
3128
  if (!selected)
3129
3129
  throw new Error(`Offline command ${commandId} no longer exists.`);
@@ -3171,7 +3171,7 @@ class OfflineSyncService {
3171
3171
  throw new Error('Offline session changed before serialized replica mutation.');
3172
3172
  const result = await operation(repository);
3173
3173
  if (this.#isCurrent(generation))
3174
- await this.#refreshState(generation);
3174
+ await this.#refreshState(generation, repository);
3175
3175
  return result;
3176
3176
  });
3177
3177
  }
@@ -3385,7 +3385,7 @@ class OfflineSyncService {
3385
3385
  if (generation !== this.#generation) {
3386
3386
  throw new Error('Offline session changed before the command could be persisted');
3387
3387
  }
3388
- const known = await this.#readKnownCommands();
3388
+ const known = await this.#readKnownCommands(repository);
3389
3389
  const remaining = [
3390
3390
  ...known.filter((command) => !(removeCommandIds ?? []).includes(command.commandId)),
3391
3391
  ...entries.map((entry) => entry.command),
@@ -3397,7 +3397,7 @@ class OfflineSyncService {
3397
3397
  if (entry.seedBaseRow !== undefined)
3398
3398
  seeds.set(this.#aggregateKey(entry.command), entry.seedBaseRow);
3399
3399
  }
3400
- const rematerialized = await this.#rematerializeAffectedAggregates(affected, remaining, seeds);
3400
+ const rematerialized = await this.#rematerializeAffectedAggregates(affected, remaining, seeds, repository);
3401
3401
  await repository.transactReplica({
3402
3402
  putRows: rematerialized.putRows,
3403
3403
  removeRows: rematerialized.removeRows,
@@ -3466,10 +3466,10 @@ class OfflineSyncService {
3466
3466
  throw new OfflineOutboxCapacityError('serialized_bytes', commands.length, currentBytes);
3467
3467
  }
3468
3468
  }
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();
3469
+ async #commandsForUser(userId, repository = this.#repository) {
3470
+ return repository.getCommandsForUser
3471
+ ? repository.getCommandsForUser(userId)
3472
+ : (await Promise.all([...this.#knownScopes.values()].filter((scope) => scope.userId === userId).map((scope) => repository.getCommands(scope)))).flat();
3473
3473
  }
3474
3474
  #serializedOutboxBytes(commands) {
3475
3475
  return new TextEncoder().encode(JSON.stringify(commands)).byteLength;
@@ -3483,7 +3483,7 @@ class OfflineSyncService {
3483
3483
  // enqueue, ACK, and pull application so an old before-image cannot replace
3484
3484
  // a newer authoritative row after its cursor has advanced.
3485
3485
  const command = await this.#replicaMutations.run(async (repository) => {
3486
- const current = (await this.#readKnownCommands()).find((item) => item.commandId === commandId);
3486
+ const current = (await this.#readKnownCommands(repository)).find((item) => item.commandId === commandId);
3487
3487
  if (!current)
3488
3488
  return null;
3489
3489
  this.#assertDiscardable([current]);
@@ -3511,7 +3511,7 @@ class OfflineSyncService {
3511
3511
  // Re-read only after every interrupted transport transition has settled.
3512
3512
  // An ACK may have removed the command while retryNow was waiting; never
3513
3513
  // resurrect such a command from an object captured before invalidation.
3514
- const current = (await this.#readKnownCommands()).find((item) => item.commandId === commandId);
3514
+ const current = (await this.#readKnownCommands(repository)).find((item) => item.commandId === commandId);
3515
3515
  if (!current)
3516
3516
  return false;
3517
3517
  if (current.state !== 'retry_wait' && current.state !== 'blocked_auth' && current.serverCommitUnknown !== true) {
@@ -3533,7 +3533,7 @@ class OfflineSyncService {
3533
3533
  if (!(await this.#restoreCurrentGeneration(generation)))
3534
3534
  return;
3535
3535
  const commands = await this.#replicaMutations.run(async (repository) => {
3536
- const current = await this.#readKnownCommands();
3536
+ const current = await this.#readKnownCommands(repository);
3537
3537
  this.#assertDiscardable(current);
3538
3538
  this.#invalidateFlush();
3539
3539
  await this.#discardCommands(current, repository);
@@ -3970,7 +3970,7 @@ class OfflineSyncService {
3970
3970
  serverRevision: result.clearRemoteId === true ? null : (revision ?? current.serverRevision),
3971
3971
  fetchedAt: Date.now(),
3972
3972
  };
3973
- const rematerialized = await this.#rematerializeAggregate(awaitingPull, latestCommands, identityUpdatedBase);
3973
+ const rematerialized = await this.#rematerializeAggregate(awaitingPull, latestCommands, identityUpdatedBase, latestCommands, repository);
3974
3974
  if (!this.#isCurrent(generation))
3975
3975
  return;
3976
3976
  await repository.transactReplica({
@@ -3993,14 +3993,13 @@ class OfflineSyncService {
3993
3993
  this.#pendingPullScopes.set(this.#scopeKey(scope), scope);
3994
3994
  commands.splice(0, commands.length, ...latestCommands);
3995
3995
  }
3996
- async #rowForCommand(command) {
3996
+ async #rowForCommand(command, repository = this.#repository) {
3997
3997
  const scope = { userId: command.userId, scopeId: command.scopeId };
3998
3998
  const entityType = this.#entityType(command);
3999
- return this.#getReplicaRowForSync(scope, entityType, command.identity);
3999
+ return this.#getReplicaRowForSync(scope, entityType, command.identity, repository);
4000
4000
  }
4001
- #getReplicaRowForSync(scope, sourceKey, identity) {
4002
- return (this.#repository.getReplicaRowIncludingPendingDelete?.(scope, sourceKey, identity) ??
4003
- this.#repository.getReplicaRow(scope, sourceKey, identity));
4001
+ #getReplicaRowForSync(scope, sourceKey, identity, repository = this.#repository) {
4002
+ return (repository.getReplicaRowIncludingPendingDelete?.(scope, sourceKey, identity) ?? repository.getReplicaRow(scope, sourceKey, identity));
4004
4003
  }
4005
4004
  #replicaState(state) {
4006
4005
  if (state === 'blocked_auth' || state === 'rejected' || state === 'conflict')
@@ -4017,36 +4016,36 @@ class OfflineSyncService {
4017
4016
  return schema;
4018
4017
  }
4019
4018
  async #discardCommands(discarded, repository) {
4020
- const all = await this.#readKnownCommands();
4019
+ const all = await this.#readKnownCommands(repository);
4021
4020
  const discardedIds = new Set(discarded.map((command) => command.commandId));
4022
4021
  const affected = new Map();
4023
4022
  for (const command of discarded)
4024
4023
  affected.set(this.#aggregateKey(command), command);
4025
4024
  const remaining = all.filter((item) => !discardedIds.has(item.commandId));
4026
- const rematerialized = await this.#rematerializeAffectedAggregates(affected, remaining);
4025
+ const rematerialized = await this.#rematerializeAffectedAggregates(affected, remaining, new Map(), repository);
4027
4026
  await repository.transactReplica({
4028
4027
  putRows: rematerialized.putRows,
4029
4028
  removeRows: rematerialized.removeRows,
4030
4029
  removeCommandIds: [...discardedIds],
4031
4030
  });
4032
4031
  }
4033
- async #rematerializeAffectedAggregates(affected, remaining, seeds = new Map()) {
4032
+ async #rematerializeAffectedAggregates(affected, remaining, seeds = new Map(), repository = this.#repository) {
4034
4033
  const putRows = [];
4035
4034
  const removeRows = [];
4036
4035
  for (const [key, command] of affected) {
4037
4036
  const remainingForAggregate = remaining.filter((item) => this.#aggregateKey(item) === key);
4038
4037
  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);
4038
+ const rematerialized = await this.#rematerializeAggregate(command, remainingForAggregate, seeds.has(key) ? seeds.get(key) : undefined, footprintCommands, repository);
4040
4039
  putRows.push(...(rematerialized.putRows ?? []));
4041
4040
  removeRows.push(...(rematerialized.removeRows ?? []));
4042
4041
  }
4043
4042
  return { putRows, removeRows };
4044
4043
  }
4045
- async #rematerializeAggregate(command, remaining, baseRow = undefined, footprintCommands = remaining) {
4046
- const current = baseRow === undefined ? await this.#rowForCommand(command) : baseRow;
4044
+ async #rematerializeAggregate(command, remaining, baseRow = undefined, footprintCommands = remaining, repository = this.#repository) {
4045
+ const current = baseRow === undefined ? await this.#rowForCommand(command, repository) : baseRow;
4047
4046
  const projection = this.#replicaMutations.projectAggregateIntent({
4048
4047
  baseRow: current,
4049
- localOnlyRows: await this.#localOnlyRowsForCommands(footprintCommands),
4048
+ localOnlyRows: await this.#localOnlyRowsForCommands(footprintCommands, repository),
4050
4049
  commands: remaining,
4051
4050
  trigger: 'local',
4052
4051
  });
@@ -4055,20 +4054,20 @@ class OfflineSyncService {
4055
4054
  }
4056
4055
  return offlineAggregateIntentMutations(projection, current);
4057
4056
  }
4058
- async #localOnlyRowsForCommands(commands) {
4057
+ async #localOnlyRowsForCommands(commands, repository = this.#repository) {
4059
4058
  const keys = new Map();
4060
4059
  for (const command of commands) {
4061
4060
  for (const key of commandFootprintKeys(command)) {
4062
4061
  keys.set(this.#replicaRowKey(key), key);
4063
4062
  }
4064
4063
  }
4065
- const rows = await Promise.all([...keys.values()].map((key) => this.#getLocalOnlyRow(key)));
4064
+ const rows = await Promise.all([...keys.values()].map((key) => this.#getLocalOnlyRow(key, repository)));
4066
4065
  return rows.filter((row) => row !== null);
4067
4066
  }
4068
- #getLocalOnlyRow(key) {
4067
+ #getLocalOnlyRow(key, repository = this.#repository) {
4069
4068
  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));
4069
+ return (repository.getReplicaRowIncludingPendingDelete?.(scope, key.sourceKey, key.identity) ??
4070
+ repository.getReplicaRow(scope, key.sourceKey, key.identity));
4072
4071
  }
4073
4072
  #aggregateKey(command) {
4074
4073
  const sourceKey = this.#entityType(command);
@@ -4101,7 +4100,7 @@ class OfflineSyncService {
4101
4100
  async #persistFailedCommand(command, error, generation, row, serverCommitUnknown = true) {
4102
4101
  const failed = this.#failedCommand(command, error, serverCommitUnknown);
4103
4102
  await this.#serializeReplicaMutation(async (repository) => {
4104
- const current = row === undefined ? await this.#rowForCommand(command) : row;
4103
+ const current = row === undefined ? await this.#rowForCommand(command, repository) : row;
4105
4104
  if (!this.#isCurrent(generation))
4106
4105
  return;
4107
4106
  if (current) {
@@ -4260,11 +4259,11 @@ class OfflineSyncService {
4260
4259
  }
4261
4260
  }
4262
4261
  }
4263
- async #readKnownCommands() {
4262
+ async #readKnownCommands(repository = this.#repository) {
4264
4263
  const userId = this.#activeUserId;
4265
4264
  if (userId === null)
4266
4265
  return [];
4267
- const commands = (await this.#commandsForUser(userId))
4266
+ const commands = (await this.#commandsForUser(userId, repository))
4268
4267
  .filter((command) => this.#knownScopes.has(this.#scopeKey({ userId: command.userId, scopeId: command.scopeId })))
4269
4268
  .sort(compareOfflineCommands);
4270
4269
  this.#rememberCreatedAt(commands);
@@ -4281,9 +4280,9 @@ class OfflineSyncService {
4281
4280
  for (const command of commands)
4282
4281
  this.#lastCommandCreatedAt = Math.max(this.#lastCommandCreatedAt, command.createdAt);
4283
4282
  }
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) : [];
4283
+ async #refreshState(generation = this.#generation, repository = this.#repository) {
4284
+ const commands = await this.#readKnownCommands(repository);
4285
+ const attentions = this.#activeUserId !== null && repository.getPullAttentions ? await repository.getPullAttentions(this.#activeUserId) : [];
4287
4286
  if (!this.#isCurrent(generation))
4288
4287
  return;
4289
4288
  this.#commands.set(commands);
@@ -4331,7 +4330,7 @@ class OfflineSyncService {
4331
4330
  if (!this.#isCurrent(generation))
4332
4331
  return null;
4333
4332
  const scope = { userId: command.userId, scopeId: command.scopeId };
4334
- const current = (await this.#repository.getCommands(scope)).find((candidate) => candidate.commandId === command.commandId);
4333
+ const current = (await repository.getCommands(scope)).find((candidate) => candidate.commandId === command.commandId);
4335
4334
  if (!current || !['pending', 'retry_wait'].includes(current.state))
4336
4335
  return null;
4337
4336
  const sending = {
@@ -4353,7 +4352,7 @@ class OfflineSyncService {
4353
4352
  if (!this.#isCurrent(generation))
4354
4353
  return null;
4355
4354
  const scope = { userId: command.userId, scopeId: command.scopeId };
4356
- const current = (await this.#repository.getCommands(scope)).find((candidate) => candidate.commandId === command.commandId);
4355
+ const current = (await repository.getCommands(scope)).find((candidate) => candidate.commandId === command.commandId);
4357
4356
  if (!current || current.state !== 'sending')
4358
4357
  return null;
4359
4358
  const transportCommand = { ...current, serverCommitUnknown: true };
@@ -5395,6 +5394,9 @@ const offlineInterceptor = (request, next) => {
5395
5394
  if (plan.readStrategy === 'local-first') {
5396
5395
  return readLocalFirst(request, plan, transport, fallback, inject(ErrorHandler), inject(OfflineReplicaMutationCoordinator));
5397
5396
  }
5397
+ if (plan.readStrategy === 'fastest-first') {
5398
+ return readFastestFirst(request, plan, transport, fallback, inject(ErrorHandler), inject(OfflineReplicaMutationCoordinator));
5399
+ }
5398
5400
  return readNetworkFirst(request, plan, transport, fallback);
5399
5401
  }
5400
5402
  if (LOCAL_FIRST_MUTATION_METHODS.has(request.method)) {
@@ -5428,6 +5430,21 @@ function readLocalFirst(request, plan, transport, fallback, errorHandler, replic
5428
5430
  ? concat(of(localResponse), drainRemoteAfterLocal(bufferedTransport$, plan))
5429
5431
  : drainRemoteNetworkFirst(bufferedTransport$, request, plan, fallback))), { connector: () => new ReplaySubject() }));
5430
5432
  }
5433
+ /** Races a serialized local replica read against remote transport without allowing stale local data to follow remote. */
5434
+ function readFastestFirst(request, plan, transport, fallback, errorHandler, replicaMutations) {
5435
+ return defer(transport).pipe(materialize(), connect((bufferedTransport$) => {
5436
+ const localDecision$ = resolveLocalAttempt(plan, errorHandler, replicaMutations).pipe(concatMap((localResponse) => localResponse
5437
+ ? concat(of(localResponse), drainRemoteAfterLocal(bufferedTransport$, plan))
5438
+ : drainRemoteNetworkFirst(bufferedTransport$, request, plan, fallback)));
5439
+ // Angular transport emits Sent/progress events before the response.
5440
+ // They are not usable read results and therefore must not win the race.
5441
+ const remoteWinner$ = drainRemoteNetworkFirst(bufferedTransport$, request, plan, fallback).pipe(filter((event) => event instanceof HttpResponse),
5442
+ // A remote error is not a usable response. Keep it buffered until the
5443
+ // local attempt decides whether it can satisfy the read.
5444
+ catchError(() => NEVER));
5445
+ return race(localDecision$, remoteWinner$);
5446
+ }, { connector: () => new ReplaySubject() }));
5447
+ }
5431
5448
  function resolveLocalAttempt(plan, errorHandler, replicaMutations) {
5432
5449
  return serializedLocalRead(plan, replicaMutations).pipe(catchError((localError) => {
5433
5450
  errorHandler.handleError(localError);