@rdlabo/ionic-angular-kit 21.6.8 → 21.6.9

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.
@@ -2582,6 +2582,9 @@ class OfflineNetworkService {
2582
2582
  constructor() {
2583
2583
  this.#osConnected = signal(null, ...(ngDevMode ? [{ debugName: "#osConnected" }] : /* istanbul ignore next */ []));
2584
2584
  this.#apiReachable = signal(null, ...(ngDevMode ? [{ debugName: "#apiReachable" }] : /* istanbul ignore next */ []));
2585
+ this.#appActive = signal(true, ...(ngDevMode ? [{ debugName: "#appActive" }] : /* istanbul ignore next */ []));
2586
+ this.#lifecycleRevision = signal(0, ...(ngDevMode ? [{ debugName: "#lifecycleRevision" }] : /* istanbul ignore next */ []));
2587
+ this.#networkRevision = 0;
2585
2588
  this.#listeners = [];
2586
2589
  this.#initialized = false;
2587
2590
  this.state = computed(() => {
@@ -2592,23 +2595,43 @@ class OfflineNetworkService {
2592
2595
  return 'unverified';
2593
2596
  }, ...(ngDevMode ? [{ debugName: "state" }] : /* istanbul ignore next */ []));
2594
2597
  this.connected = computed(() => this.state() !== 'offline', ...(ngDevMode ? [{ debugName: "connected" }] : /* istanbul ignore next */ []));
2598
+ /** Whether Capacitor currently permits foreground transport work. */
2599
+ this.appActive = this.#appActive.asReadonly();
2600
+ /** Changes on every foreground/background transition, even when connectivity is unchanged. */
2601
+ this.lifecycleRevision = this.#lifecycleRevision.asReadonly();
2595
2602
  }
2596
2603
  #osConnected;
2597
2604
  #apiReachable;
2605
+ #appActive;
2606
+ #lifecycleRevision;
2607
+ #networkRevision;
2598
2608
  #listeners;
2599
2609
  #initialized;
2600
2610
  async initialize() {
2601
2611
  if (this.#initialized)
2602
2612
  return;
2603
2613
  this.#initialized = true;
2604
- this.#osConnected.set((await Network.getStatus()).connected);
2605
- this.#listeners.push(await Network.addListener('networkStatusChange', ({ connected }) => {
2606
- this.#osConnected.set(connected);
2607
- this.#apiReachable.set(connected ? null : false);
2608
- }), await App.addListener('appStateChange', ({ isActive }) => {
2609
- if (isActive)
2610
- void this.#refreshOsStatus();
2611
- }));
2614
+ const [networkListener, appListener] = await Promise.all([
2615
+ Network.addListener('networkStatusChange', ({ connected }) => {
2616
+ this.#networkRevision += 1;
2617
+ this.#osConnected.set(connected);
2618
+ this.#apiReachable.set(connected ? null : false);
2619
+ }),
2620
+ App.addListener('appStateChange', ({ isActive }) => {
2621
+ this.#lifecycleRevision.update((revision) => revision + 1);
2622
+ this.#appActive.set(isActive);
2623
+ if (isActive)
2624
+ void this.#refreshOsStatus();
2625
+ }),
2626
+ ]);
2627
+ this.#listeners.push(networkListener, appListener);
2628
+ const networkRevision = this.#networkRevision;
2629
+ const lifecycleRevision = this.#lifecycleRevision();
2630
+ const [network, app] = await Promise.all([Network.getStatus(), App.getState()]);
2631
+ if (this.#networkRevision === networkRevision)
2632
+ this.#osConnected.set(network.connected);
2633
+ if (this.#lifecycleRevision() === lifecycleRevision)
2634
+ this.#appActive.set(app.isActive);
2612
2635
  }
2613
2636
  markApiSuccess() {
2614
2637
  this.#apiReachable.set(true);
@@ -2617,7 +2640,10 @@ class OfflineNetworkService {
2617
2640
  this.#apiReachable.set(false);
2618
2641
  }
2619
2642
  async #refreshOsStatus() {
2620
- this.#osConnected.set((await Network.getStatus()).connected);
2643
+ const revision = this.#networkRevision;
2644
+ const status = await Network.getStatus();
2645
+ if (this.#networkRevision === revision)
2646
+ this.#osConnected.set(status.connected);
2621
2647
  }
2622
2648
  static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: OfflineNetworkService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
2623
2649
  static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: OfflineNetworkService, providedIn: 'root' }); }
@@ -2752,6 +2778,8 @@ class OfflineSyncService {
2752
2778
  #pendingPullScopes;
2753
2779
  #activeUserId;
2754
2780
  #flushPromise;
2781
+ #flushLifecycleRevision;
2782
+ #resumeAfterFlush;
2755
2783
  #partialFlushInFlight;
2756
2784
  #chainedFullFlush;
2757
2785
  #flushTransitions;
@@ -2782,6 +2810,8 @@ class OfflineSyncService {
2782
2810
  this.#pendingPullScopes = new Map();
2783
2811
  this.#activeUserId = null;
2784
2812
  this.#flushPromise = null;
2813
+ this.#flushLifecycleRevision = 0;
2814
+ this.#resumeAfterFlush = false;
2785
2815
  this.#partialFlushInFlight = false;
2786
2816
  this.#chainedFullFlush = null;
2787
2817
  this.#flushTransitions = new Set();
@@ -2813,11 +2843,12 @@ class OfflineSyncService {
2813
2843
  }, ...(ngDevMode ? [{ debugName: "syncState" }] : /* istanbul ignore next */ []));
2814
2844
  effect(() => {
2815
2845
  const connected = this.#network.connected();
2846
+ const appActive = this.#appActive();
2816
2847
  // The network transition may be observed after an explicit flush has already
2817
2848
  // persisted a fatal pull attention. Do not let that stale transition restart
2818
2849
  // the intentionally stopped loop; auth/session refresh remains able to retry.
2819
2850
  const hasFatalPullAttention = untracked(() => this.#pullAttentions().length > 0);
2820
- if (this.#initialized && connected && !hasFatalPullAttention)
2851
+ if (this.#initialized && connected && appActive && !hasFatalPullAttention)
2821
2852
  this.#flushInBackground();
2822
2853
  });
2823
2854
  }
@@ -2825,7 +2856,7 @@ class OfflineSyncService {
2825
2856
  const generation = this.#generation;
2826
2857
  if (!(await this.#restoreCurrentGeneration(generation)))
2827
2858
  return;
2828
- if (options.flush !== false && this.#network.connected())
2859
+ if (options.flush !== false && this.#canSynchronize())
2829
2860
  this.#flushInBackground();
2830
2861
  }
2831
2862
  #ensureInitialized() {
@@ -2867,7 +2898,7 @@ class OfflineSyncService {
2867
2898
  await this.#discoverScopes();
2868
2899
  await this.#restoreInterruptedCommands();
2869
2900
  await this.#refreshState();
2870
- if (this.#network.connected())
2901
+ if (this.#canSynchronize())
2871
2902
  this.#flushInBackground();
2872
2903
  }
2873
2904
  /** Restores local outbox visibility without enabling pull or replay transport. */
@@ -3258,7 +3289,7 @@ class OfflineSyncService {
3258
3289
  removeCommandIds,
3259
3290
  });
3260
3291
  await this.#refreshState().catch((error) => this.#reportError(error));
3261
- if (options.flush !== false && this.#network.connected())
3292
+ if (options.flush !== false && this.#canSynchronize())
3262
3293
  this.#flushInBackground();
3263
3294
  }
3264
3295
  #normalizedLocalOnlyFootprint(scope, footprint) {
@@ -3349,7 +3380,7 @@ class OfflineSyncService {
3349
3380
  await this.#restoreInterruptedCommands();
3350
3381
  await this.#refreshState();
3351
3382
  await this.#hooks.onCommandRemoved?.(command).catch((error) => this.#reportError(error));
3352
- if (options.flush !== false && this.#network.connected())
3383
+ if (options.flush !== false && this.#canSynchronize())
3353
3384
  this.#flushInBackground();
3354
3385
  }
3355
3386
  /** Clears a retry backoff/auth block selected explicitly by the user and sends the durable command now. */
@@ -3378,7 +3409,7 @@ class OfflineSyncService {
3378
3409
  });
3379
3410
  return true;
3380
3411
  });
3381
- if (retried && this.#network.connected())
3412
+ if (retried && this.#canSynchronize())
3382
3413
  await this.flush();
3383
3414
  }
3384
3415
  async discardAllPending() {
@@ -3414,8 +3445,12 @@ class OfflineSyncService {
3414
3445
  return this.#beginFlush(true);
3415
3446
  }
3416
3447
  #beginFlush(explicitFull) {
3448
+ const lifecycleRevision = this.#lifecycleRevision();
3417
3449
  const isPartial = !explicitFull && this.#foregroundScopePolicy !== null;
3418
3450
  if (this.#flushPromise) {
3451
+ if (lifecycleRevision !== this.#flushLifecycleRevision && this.#canSynchronize()) {
3452
+ this.#resumeAfterFlush = true;
3453
+ }
3419
3454
  if (explicitFull && this.#partialFlushInFlight) {
3420
3455
  if (!this.#chainedFullFlush) {
3421
3456
  const generation = this.#generation;
@@ -3444,7 +3479,13 @@ class OfflineSyncService {
3444
3479
  this.#flushPromise = null;
3445
3480
  this.#partialFlushInFlight = false;
3446
3481
  }
3482
+ const resumeAfterFlush = this.#resumeAfterFlush;
3483
+ this.#resumeAfterFlush = false;
3484
+ if (resumeAfterFlush && this.#canSynchronize()) {
3485
+ queueMicrotask(() => this.#flushInBackground());
3486
+ }
3447
3487
  });
3488
+ this.#flushLifecycleRevision = lifecycleRevision;
3448
3489
  this.#flushPromise = promise;
3449
3490
  this.#partialFlushInFlight = isPartial;
3450
3491
  this.#flushTransitions.add(promise);
@@ -3453,7 +3494,7 @@ class OfflineSyncService {
3453
3494
  async #runFlush(generation, explicitFull) {
3454
3495
  if (!this.#isCurrent(generation))
3455
3496
  return;
3456
- if (!this.#network.connected()) {
3497
+ if (!this.#canSynchronize()) {
3457
3498
  await this.#refreshState(generation);
3458
3499
  return;
3459
3500
  }
@@ -3467,8 +3508,9 @@ class OfflineSyncService {
3467
3508
  let fatalPullFailure = null;
3468
3509
  const pulledScopeKeys = new Set();
3469
3510
  for (const scope of pullScopes) {
3470
- if (!this.#isCurrent(generation) || !this.#network.connected())
3511
+ if (!this.#isCurrent(generation) || !this.#canSynchronize())
3471
3512
  return;
3513
+ const pullLifecycleRevision = this.#lifecycleRevision();
3472
3514
  const pullScope = async () => {
3473
3515
  await this.#pull.pull(scope);
3474
3516
  await this.#markScopeReconciled(scope, generation);
@@ -3476,6 +3518,8 @@ class OfflineSyncService {
3476
3518
  };
3477
3519
  const pull = await pullScope().then(() => ({ status: 'fulfilled' }), (error) => ({ status: 'rejected', error }));
3478
3520
  if (pull.status === 'rejected') {
3521
+ if (this.#isInterruptedTransportFailure(pull.error, pullLifecycleRevision))
3522
+ return;
3479
3523
  prePullFailures.push(pull.error);
3480
3524
  if (this.#isFatalPullFailure(pull.error)) {
3481
3525
  // Auth/upgrade-driven recovery only: stop remaining scopes immediately.
@@ -3490,7 +3534,7 @@ class OfflineSyncService {
3490
3534
  }
3491
3535
  const dirtyScopes = new Map();
3492
3536
  const sendWorkerFailures = [];
3493
- while (this.#network.connected() && this.#isCurrent(generation) && fatalPullFailure === null) {
3537
+ while (this.#canSynchronize() && this.#isCurrent(generation) && fatalPullFailure === null) {
3494
3538
  const known = await this.#readKnownCommands();
3495
3539
  const groups = this.#eligibleAggregateGroups(known).filter((group) => group.some((command) => (command.state === 'pending' || command.state === 'retry_wait') &&
3496
3540
  pulledScopeKeys.has(this.#scopeKey({ userId: command.userId, scopeId: command.scopeId }))));
@@ -3501,7 +3545,7 @@ class OfflineSyncService {
3501
3545
  const pendingBefore = known.filter((command) => command.state === 'pending' || command.state === 'retry_wait').length;
3502
3546
  let cursor = 0;
3503
3547
  const workers = Array.from({ length: Math.min(MAX_PARALLEL_AGGREGATES, groups.length) }, async () => {
3504
- while (cursor < groups.length) {
3548
+ while (cursor < groups.length && this.#canSynchronize()) {
3505
3549
  const group = groups[cursor++];
3506
3550
  if (group && this.#isCurrent(generation))
3507
3551
  await this.#sendAggregate(group, generation, dirtyScopes, pulledScopeKeys);
@@ -3528,8 +3572,9 @@ class OfflineSyncService {
3528
3572
  if (fatalPullFailure === null) {
3529
3573
  const postPullScopes = [...this.#pendingPullScopes.values()];
3530
3574
  for (const scope of postPullScopes) {
3531
- if (!this.#isCurrent(generation) || !this.#network.connected())
3575
+ if (!this.#isCurrent(generation) || !this.#canSynchronize())
3532
3576
  break;
3577
+ const pullLifecycleRevision = this.#lifecycleRevision();
3533
3578
  // A command response may contain only the aggregate's base row. Pull once per dirty scope so
3534
3579
  // sibling-table journal entries are visible before completed Outbox state reaches product UI.
3535
3580
  const pullScope = async () => {
@@ -3538,6 +3583,8 @@ class OfflineSyncService {
3538
3583
  };
3539
3584
  const pull = await pullScope().then(() => ({ status: 'fulfilled' }), (error) => ({ status: 'rejected', error }));
3540
3585
  if (pull.status === 'rejected') {
3586
+ if (this.#isInterruptedTransportFailure(pull.error, pullLifecycleRevision))
3587
+ return;
3541
3588
  if (this.#isFatalPullFailure(pull.error)) {
3542
3589
  fatalPullFailure = fatalPullFailure ?? pull.error;
3543
3590
  await this.#persistFatalPullAttentions(pull.error, scope, postPullScopes, generation);
@@ -3583,6 +3630,21 @@ class OfflineSyncService {
3583
3630
  return true;
3584
3631
  return error instanceof OfflineReplicaSchemaMismatchError;
3585
3632
  }
3633
+ #isInterruptedTransportFailure(error, lifecycleRevision) {
3634
+ if (this.#lifecycleRevision() === lifecycleRevision)
3635
+ return false;
3636
+ const status = this.#errorStatus(error);
3637
+ return status === 0 || status === 408;
3638
+ }
3639
+ #canSynchronize() {
3640
+ return this.#appActive() && this.#network.connected();
3641
+ }
3642
+ #appActive() {
3643
+ return this.#network.appActive?.() ?? true;
3644
+ }
3645
+ #lifecycleRevision() {
3646
+ return this.#network.lifecycleRevision?.() ?? 0;
3647
+ }
3586
3648
  #pullAttentionReason(error) {
3587
3649
  if (error instanceof OfflineReplicaSchemaMismatchError)
3588
3650
  return 'schema_upgrade_required';
@@ -4123,7 +4185,7 @@ class OfflineSyncService {
4123
4185
  return;
4124
4186
  this.#retryTimer = setTimeout(() => {
4125
4187
  this.#retryTimer = null;
4126
- if (this.#network.connected())
4188
+ if (this.#canSynchronize())
4127
4189
  this.#flushInBackground();
4128
4190
  }, Math.max(0, retryAt - Date.now()));
4129
4191
  }
@@ -4132,6 +4194,7 @@ class OfflineSyncService {
4132
4194
  this.#flushPromise = null;
4133
4195
  this.#partialFlushInFlight = false;
4134
4196
  this.#chainedFullFlush = null;
4197
+ this.#resumeAfterFlush = false;
4135
4198
  this.#scheduleRetry(null);
4136
4199
  }
4137
4200
  #isCurrent(generation) {
@@ -5150,27 +5213,106 @@ async function createRandomOfflineEncryptionKey() {
5150
5213
  return Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('');
5151
5214
  }
5152
5215
  const settledSqliteOperation = async () => undefined;
5153
- /** Create the standard encrypted `@capacitor-community/sqlite` driver. */
5216
+ const communitySqliteDrivers = new WeakMap();
5217
+ function sqliteErrorMessage(error) {
5218
+ if (error instanceof Error)
5219
+ return error.message;
5220
+ if (typeof error === 'object' && error !== null && 'message' in error && typeof error.message === 'string') {
5221
+ return error.message;
5222
+ }
5223
+ return String(error);
5224
+ }
5225
+ function normalizeCommunitySqliteDatabaseName(database) {
5226
+ return database.endsWith('.db') ? database.slice(0, -3) : database;
5227
+ }
5228
+ function isExistingCommunitySqliteConnectionError(error, database) {
5229
+ const databaseName = normalizeCommunitySqliteDatabaseName(database);
5230
+ return sqliteErrorMessage(error).includes(`Connection ${databaseName} already exists`);
5231
+ }
5232
+ function settleCommunitySqliteCreation(creation) {
5233
+ return creation.then((database) => ({ ok: true, database }), (error) => ({ ok: false, error }));
5234
+ }
5235
+ async function createReloadSafeCommunitySqliteDatabase(connection, databaseName) {
5236
+ const create = () => connection.createConnection(databaseName, COMMUNITY_SQLITE_ENCRYPTED, COMMUNITY_SQLITE_MODE, COMMUNITY_SQLITE_VERSION, COMMUNITY_SQLITE_READONLY);
5237
+ const creation = await settleCommunitySqliteCreation(create());
5238
+ if (creation.ok)
5239
+ return creation.database;
5240
+ if (!isExistingCommunitySqliteConnectionError(creation.error, databaseName) || !connection.closeConnection) {
5241
+ throw creation.error;
5242
+ }
5243
+ await connection.closeConnection(databaseName, COMMUNITY_SQLITE_READONLY);
5244
+ return create();
5245
+ }
5246
+ /**
5247
+ * Create the canonical encrypted `@capacitor-community/sqlite` driver for a connection owner.
5248
+ *
5249
+ * The supplied connection is the identity and exclusive owner of its native plugin connections. Repeated
5250
+ * calls with the same object return the same driver so normal concurrent access cannot be mistaken for a
5251
+ * WebView-reload orphan. Consumers must route database access through this driver and must not close or
5252
+ * replace the connection while the driver is active. A real WebView reload creates a new JavaScript owner,
5253
+ * allowing the driver to close the native connection orphaned by the previous owner and recreate it.
5254
+ */
5154
5255
  function createCommunitySqliteDriver(connection) {
5256
+ const currentDriver = communitySqliteDrivers.get(connection);
5257
+ if (currentDriver)
5258
+ return currentDriver;
5155
5259
  const databases = new Map();
5260
+ const openings = new Map();
5261
+ let secretInitialization = null;
5156
5262
  const database = (databaseId) => {
5157
- const value = databases.get(databaseId);
5263
+ const value = databases.get(normalizeCommunitySqliteDatabaseName(databaseId));
5158
5264
  if (!value)
5159
5265
  throw new Error(`Offline SQLite database "${databaseId}" is not open`);
5160
5266
  return value;
5161
5267
  };
5162
- return {
5163
- async open({ databaseName, createEncryptionKey }) {
5268
+ const ensureSecret = (createEncryptionKey) => {
5269
+ if (secretInitialization)
5270
+ return secretInitialization;
5271
+ const initialization = (async () => {
5164
5272
  const stored = await connection.isSecretStored();
5165
- if (!stored.result) {
5166
- const encryptionKey = await createEncryptionKey?.();
5167
- if (!encryptionKey)
5168
- throw new Error('Native offline storage requires a non-empty encryption key on first open');
5169
- await connection.setEncryptionSecret(encryptionKey);
5170
- }
5171
- const value = await connection.createConnection(databaseName, COMMUNITY_SQLITE_ENCRYPTED, COMMUNITY_SQLITE_MODE, COMMUNITY_SQLITE_VERSION, COMMUNITY_SQLITE_READONLY);
5273
+ if (stored.result)
5274
+ return;
5275
+ const encryptionKey = await createEncryptionKey?.();
5276
+ if (!encryptionKey)
5277
+ throw new Error('Native offline storage requires a non-empty encryption key on first open');
5278
+ await connection.setEncryptionSecret(encryptionKey);
5279
+ })();
5280
+ secretInitialization = initialization;
5281
+ return initialization.then(undefined, (error) => {
5282
+ if (secretInitialization === initialization)
5283
+ secretInitialization = null;
5284
+ throw error;
5285
+ });
5286
+ };
5287
+ const openDatabase = async (databaseName, createEncryptionKey) => {
5288
+ const databaseKey = normalizeCommunitySqliteDatabaseName(databaseName);
5289
+ const opened = databases.get(databaseKey);
5290
+ if (opened)
5291
+ return opened;
5292
+ const currentOpening = openings.get(databaseKey);
5293
+ if (currentOpening)
5294
+ return currentOpening;
5295
+ const opening = (async () => {
5296
+ await ensureSecret(createEncryptionKey);
5297
+ const value = await createReloadSafeCommunitySqliteDatabase(connection, databaseName);
5172
5298
  await value.open();
5173
- databases.set(databaseName, value);
5299
+ databases.set(databaseKey, value);
5300
+ return value;
5301
+ })();
5302
+ openings.set(databaseKey, opening);
5303
+ return opening.then((value) => {
5304
+ if (openings.get(databaseKey) === opening)
5305
+ openings.delete(databaseKey);
5306
+ return value;
5307
+ }, (error) => {
5308
+ if (openings.get(databaseKey) === opening)
5309
+ openings.delete(databaseKey);
5310
+ throw error;
5311
+ });
5312
+ };
5313
+ const driver = {
5314
+ async open({ databaseName, createEncryptionKey }) {
5315
+ await openDatabase(databaseName, createEncryptionKey);
5174
5316
  return { databaseId: databaseName };
5175
5317
  },
5176
5318
  async execute({ databaseId, statement, values = [] }) {
@@ -5190,6 +5332,8 @@ function createCommunitySqliteDriver(connection) {
5190
5332
  await database(databaseId).rollbackTransaction();
5191
5333
  },
5192
5334
  };
5335
+ communitySqliteDrivers.set(connection, driver);
5336
+ return driver;
5193
5337
  }
5194
5338
  const SCHEMA = [
5195
5339
  `CREATE TABLE IF NOT EXISTS offline_metadata (