@rdlabo/ionic-angular-kit 21.6.0 → 21.6.2
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.
- package/README.md +65 -0
- package/fesm2022/rdlabo-ionic-angular-kit-app-update.mjs +7 -11
- package/fesm2022/rdlabo-ionic-angular-kit-app-update.mjs.map +1 -1
- package/fesm2022/rdlabo-ionic-angular-kit-auth-firebase-social.mjs +31 -44
- package/fesm2022/rdlabo-ionic-angular-kit-auth-firebase-social.mjs.map +1 -1
- package/fesm2022/rdlabo-ionic-angular-kit-auth-firebase.mjs +28 -32
- package/fesm2022/rdlabo-ionic-angular-kit-auth-firebase.mjs.map +1 -1
- package/fesm2022/rdlabo-ionic-angular-kit-offline.mjs +664 -353
- package/fesm2022/rdlabo-ionic-angular-kit-offline.mjs.map +1 -1
- package/fesm2022/rdlabo-ionic-angular-kit-printer.mjs +40 -27
- package/fesm2022/rdlabo-ionic-angular-kit-printer.mjs.map +1 -1
- package/fesm2022/rdlabo-ionic-angular-kit.mjs +131 -150
- package/fesm2022/rdlabo-ionic-angular-kit.mjs.map +1 -1
- package/package.json +1 -1
- package/types/rdlabo-ionic-angular-kit-offline.d.ts +208 -84
|
@@ -5,8 +5,8 @@ import { toObservable } from '@angular/core/rxjs-interop';
|
|
|
5
5
|
import { map, distinctUntilChanged } from 'rxjs/operators';
|
|
6
6
|
import { App } from '@capacitor/app';
|
|
7
7
|
import { Network } from '@capacitor/network';
|
|
8
|
-
import { HttpErrorResponse, HttpContextToken, HttpResponse } from '@angular/common/http';
|
|
9
8
|
import { Capacitor } from '@capacitor/core';
|
|
9
|
+
import { HttpErrorResponse, HttpContextToken, HttpResponse } from '@angular/common/http';
|
|
10
10
|
import { defer, from, map as map$1, catchError, throwError, concatMap, materialize, connect, concat, of, ReplaySubject, take, dematerialize, EMPTY, tap } from 'rxjs';
|
|
11
11
|
|
|
12
12
|
const MAX_OFFLINE_NATURAL_KEY_TEXT_BYTES = 1024;
|
|
@@ -936,6 +936,7 @@ const OFFLINE_REPOSITORY_ATOMIC_MUTATION = Symbol('OFFLINE_REPOSITORY_ATOMIC_MUT
|
|
|
936
936
|
|
|
937
937
|
/** Current durable storage schema used by both web and native repositories. */
|
|
938
938
|
const OFFLINE_SCHEMA_VERSION = 2;
|
|
939
|
+
const settledRepositoryOperation = async () => undefined;
|
|
939
940
|
/** Canonical physical key shared by every repository and replica transaction coordinator. */
|
|
940
941
|
function canonicalOfflineReplicaRowKey(schema, row) {
|
|
941
942
|
const partition = schema.scope === 'user' ? 'user' : String(row.scopeId);
|
|
@@ -972,9 +973,9 @@ class IonicOfflineRepository {
|
|
|
972
973
|
#storage = inject(KitStorageService);
|
|
973
974
|
#options = inject(OFFLINE_KIT_OPTIONS);
|
|
974
975
|
#initialization = null;
|
|
975
|
-
#writes =
|
|
976
|
+
#writes = settledRepositoryOperation();
|
|
976
977
|
#activeReaders = 0;
|
|
977
|
-
#readersIdle =
|
|
978
|
+
#readersIdle = settledRepositoryOperation();
|
|
978
979
|
#resolveReadersIdle = null;
|
|
979
980
|
#rowIndexBuild = null;
|
|
980
981
|
initialize() {
|
|
@@ -1139,12 +1140,8 @@ class IonicOfflineRepository {
|
|
|
1139
1140
|
await this.#ensureRowPartitionsReady();
|
|
1140
1141
|
await this.#writes;
|
|
1141
1142
|
this.#beginReaders();
|
|
1142
|
-
|
|
1143
|
-
|
|
1144
|
-
}
|
|
1145
|
-
finally {
|
|
1146
|
-
this.#endReaders();
|
|
1147
|
-
}
|
|
1143
|
+
const read = async () => operation();
|
|
1144
|
+
return read().finally(() => this.#endReaders());
|
|
1148
1145
|
}
|
|
1149
1146
|
#beginReaders() {
|
|
1150
1147
|
if (this.#activeReaders === 0) {
|
|
@@ -1159,7 +1156,7 @@ class IonicOfflineRepository {
|
|
|
1159
1156
|
if (this.#activeReaders === 0) {
|
|
1160
1157
|
this.#resolveReadersIdle?.();
|
|
1161
1158
|
this.#resolveReadersIdle = null;
|
|
1162
|
-
this.#readersIdle =
|
|
1159
|
+
this.#readersIdle = settledRepositoryOperation();
|
|
1163
1160
|
}
|
|
1164
1161
|
}
|
|
1165
1162
|
async putCommand(command) {
|
|
@@ -1314,7 +1311,7 @@ class IonicOfflineRepository {
|
|
|
1314
1311
|
targetVersion,
|
|
1315
1312
|
targetHash,
|
|
1316
1313
|
});
|
|
1317
|
-
|
|
1314
|
+
const commitMigration = async () => {
|
|
1318
1315
|
const transformedRows = {};
|
|
1319
1316
|
for (const row of Object.values(rows)) {
|
|
1320
1317
|
let current = this.#toWebMigrationRow(row);
|
|
@@ -1358,8 +1355,8 @@ class IonicOfflineRepository {
|
|
|
1358
1355
|
replicaSchemaHash: targetHash,
|
|
1359
1356
|
});
|
|
1360
1357
|
await this.#storage.remove(REPLICA_SCHEMA_MIGRATION_KEY);
|
|
1361
|
-
}
|
|
1362
|
-
catch (error) {
|
|
1358
|
+
};
|
|
1359
|
+
await commitMigration().catch(async (error) => {
|
|
1363
1360
|
await this.#recoverReplicaSchemaMigration({
|
|
1364
1361
|
originalRows,
|
|
1365
1362
|
fromVersion,
|
|
@@ -1368,7 +1365,7 @@ class IonicOfflineRepository {
|
|
|
1368
1365
|
targetHash,
|
|
1369
1366
|
});
|
|
1370
1367
|
throw error;
|
|
1371
|
-
}
|
|
1368
|
+
});
|
|
1372
1369
|
});
|
|
1373
1370
|
}
|
|
1374
1371
|
#toWebMigrationRow(row) {
|
|
@@ -1752,6 +1749,7 @@ function compareUtf8Binary(left, right) {
|
|
|
1752
1749
|
return leftBytes.length < rightBytes.length ? -1 : leftBytes.length > rightBytes.length ? 1 : 0;
|
|
1753
1750
|
}
|
|
1754
1751
|
|
|
1752
|
+
const settledMutation = async () => undefined;
|
|
1755
1753
|
/**
|
|
1756
1754
|
* Serializes only local replica read/derive/write critical sections. Network
|
|
1757
1755
|
* transport must stay outside this coordinator so synchronization never holds
|
|
@@ -1765,7 +1763,7 @@ class OfflineReplicaMutationCoordinator {
|
|
|
1765
1763
|
#repository = inject(OFFLINE_REPOSITORY, { optional: true });
|
|
1766
1764
|
#projector = inject(OFFLINE_AGGREGATE_INTENT_PROJECTOR, { optional: true });
|
|
1767
1765
|
#options = inject(OFFLINE_KIT_OPTIONS, { optional: true });
|
|
1768
|
-
#tail =
|
|
1766
|
+
#tail = settledMutation();
|
|
1769
1767
|
/** Enqueues one local replica critical section behind any in-flight mutation. */
|
|
1770
1768
|
run(operation) {
|
|
1771
1769
|
const mutation = this.#tail.then(() => {
|
|
@@ -2616,182 +2614,59 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.17", ngImpo
|
|
|
2616
2614
|
args: [{ providedIn: 'root' }]
|
|
2617
2615
|
}] });
|
|
2618
2616
|
|
|
2619
|
-
/**
|
|
2620
|
-
|
|
2621
|
-
if (!manifest || manifest.authSubject !== authSubject)
|
|
2622
|
-
return false;
|
|
2623
|
-
return scopeId === undefined || manifest.scopeIds.includes(scopeId);
|
|
2624
|
-
}
|
|
2625
|
-
/** Owns activation and cleanup of the authenticated local-replica boundary. */
|
|
2626
|
-
class OfflineSessionService {
|
|
2617
|
+
/** Raised when a new durable mutation reaches Kit after mutation persistence was closed. */
|
|
2618
|
+
class OfflineMutationPersistenceDisabledError extends Error {
|
|
2627
2619
|
constructor() {
|
|
2628
|
-
|
|
2629
|
-
this
|
|
2630
|
-
this.#initialized = false;
|
|
2631
|
-
this.#localAccessThisRun = false;
|
|
2632
|
-
this.#remoteActivatedThisRun = false;
|
|
2633
|
-
this.activeManifest = this.#activeManifest.asReadonly();
|
|
2620
|
+
super('Offline mutation persistence was disabled before the mutation could be accepted.');
|
|
2621
|
+
this.name = 'OfflineMutationPersistenceDisabledError';
|
|
2634
2622
|
}
|
|
2635
|
-
|
|
2636
|
-
|
|
2637
|
-
|
|
2638
|
-
#
|
|
2639
|
-
#
|
|
2640
|
-
|
|
2641
|
-
|
|
2623
|
+
}
|
|
2624
|
+
/** Product-independent lease gate around every new durable Outbox command. */
|
|
2625
|
+
class OfflineMutationAdmissionService {
|
|
2626
|
+
#options = inject(OFFLINE_KIT_OPTIONS);
|
|
2627
|
+
#accepting = this.#options.mutationPersistence === undefined;
|
|
2628
|
+
#active = 0;
|
|
2629
|
+
#idle = null;
|
|
2630
|
+
#resolveIdle = null;
|
|
2631
|
+
get accepting() {
|
|
2632
|
+
return this.#accepting;
|
|
2633
|
+
}
|
|
2634
|
+
async run(operation) {
|
|
2635
|
+
if (!this.#accepting)
|
|
2636
|
+
throw new OfflineMutationPersistenceDisabledError();
|
|
2637
|
+
this.#active += 1;
|
|
2638
|
+
return new Promise((resolve) => resolve(operation())).finally(() => this.#release());
|
|
2639
|
+
}
|
|
2640
|
+
open() {
|
|
2641
|
+
this.#accepting = true;
|
|
2642
|
+
}
|
|
2643
|
+
async close() {
|
|
2644
|
+
this.#accepting = false;
|
|
2645
|
+
if (this.#active === 0)
|
|
2642
2646
|
return;
|
|
2643
|
-
|
|
2644
|
-
|
|
2645
|
-
|
|
2646
|
-
|
|
2647
|
-
this.#activeManifest.set(manifest ?? { userId, scopeIds: [], authSubject: null, updatedAt: 0 });
|
|
2648
|
-
}
|
|
2649
|
-
this.#initialized = true;
|
|
2650
|
-
}
|
|
2651
|
-
async activateSession(userId, scopeIds, authSubject, lease) {
|
|
2652
|
-
await this.initialize();
|
|
2653
|
-
if (lease && !lease.isCurrent())
|
|
2654
|
-
return false;
|
|
2655
|
-
const normalizedScopeIds = [...new Set(scopeIds)].sort((a, b) => a.localeCompare(b));
|
|
2656
|
-
const previousUserId = await this.#repository.getLastUserId();
|
|
2657
|
-
if (lease && !lease.isCurrent())
|
|
2658
|
-
return false;
|
|
2659
|
-
let previous = previousUserId === userId ? ((await this.#repository.getSessionManifest(userId)) ?? null) : null;
|
|
2660
|
-
if (lease && !lease.isCurrent())
|
|
2661
|
-
return false;
|
|
2662
|
-
// A changed provider subject is a different person even when the product reuses its numeric id.
|
|
2663
|
-
// This deliberately also clears legacy null -> known subject and known subject -> null transitions.
|
|
2664
|
-
if (previousUserId !== null && (previousUserId !== userId || previous?.authSubject !== authSubject)) {
|
|
2665
|
-
await this.#repository.clearUser(previousUserId);
|
|
2666
|
-
if (lease && !lease.isCurrent())
|
|
2667
|
-
return false;
|
|
2668
|
-
previous = null;
|
|
2669
|
-
}
|
|
2670
|
-
const active = new Set(normalizedScopeIds);
|
|
2671
|
-
await Promise.all((previous?.scopeIds ?? [])
|
|
2672
|
-
.filter((scopeId) => !active.has(scopeId))
|
|
2673
|
-
.map((scopeId) => this.#repository.clearScope({ userId, scopeId })));
|
|
2674
|
-
if (lease && !lease.isCurrent())
|
|
2675
|
-
return false;
|
|
2676
|
-
const manifest = {
|
|
2677
|
-
userId,
|
|
2678
|
-
scopeIds: normalizedScopeIds,
|
|
2679
|
-
authSubject,
|
|
2680
|
-
updatedAt: Date.now(),
|
|
2681
|
-
};
|
|
2682
|
-
await this.#repository.setLastUserId(userId);
|
|
2683
|
-
if (lease && !lease.isCurrent())
|
|
2684
|
-
return false;
|
|
2685
|
-
await this.#repository.putSessionManifest(userId, manifest);
|
|
2686
|
-
if (lease && !lease.isCurrent())
|
|
2687
|
-
return false;
|
|
2688
|
-
this.#activeManifest.set(manifest);
|
|
2689
|
-
this.#localAccessThisRun = true;
|
|
2690
|
-
this.#remoteActivatedThisRun = true;
|
|
2691
|
-
return lease ? true : undefined;
|
|
2692
|
-
}
|
|
2693
|
-
async clearActiveSession() {
|
|
2694
|
-
await this.initialize();
|
|
2695
|
-
const userId = await this.#repository.getLastUserId();
|
|
2696
|
-
if (userId !== null)
|
|
2697
|
-
await this.#repository.clearUser(userId);
|
|
2698
|
-
this.#activeManifest.set(null);
|
|
2699
|
-
this.#localAccessThisRun = false;
|
|
2700
|
-
this.#remoteActivatedThisRun = false;
|
|
2701
|
-
}
|
|
2702
|
-
/** Immediately revoke local and remote runtime access while durable cleanup is pending. */
|
|
2703
|
-
revokeAccess() {
|
|
2704
|
-
this.#localAccessThisRun = false;
|
|
2705
|
-
this.#remoteActivatedThisRun = false;
|
|
2706
|
-
}
|
|
2707
|
-
/** Disable remote pull/replay eligibility while retaining the verified local manifest. */
|
|
2708
|
-
async suspendRemoteSession() {
|
|
2709
|
-
await this.initialize();
|
|
2710
|
-
this.#remoteActivatedThisRun = false;
|
|
2711
|
-
}
|
|
2712
|
-
/**
|
|
2713
|
-
* Returns the persisted identity boundary for local-only route access.
|
|
2714
|
-
*
|
|
2715
|
-
* @remarks
|
|
2716
|
-
* This does not activate the sync context. Call it only after the authentication authority has
|
|
2717
|
-
* been classified as unavailable, never after explicit sign-out or HTTP 401/403. Legacy
|
|
2718
|
-
* manifests without an authentication-provider subject are rejected.
|
|
2719
|
-
*
|
|
2720
|
-
* @param authSubject - A currently known provider subject. When supplied, it must match the
|
|
2721
|
-
* persisted subject.
|
|
2722
|
-
*/
|
|
2723
|
-
async getOfflineAccessManifest(authSubject) {
|
|
2724
|
-
await this.initialize();
|
|
2725
|
-
const manifest = this.#activeManifest();
|
|
2726
|
-
if (!manifest?.authSubject || (authSubject !== undefined && manifest.authSubject !== authSubject)) {
|
|
2727
|
-
return null;
|
|
2647
|
+
if (!this.#idle) {
|
|
2648
|
+
this.#idle = new Promise((resolve) => {
|
|
2649
|
+
this.#resolveIdle = resolve;
|
|
2650
|
+
});
|
|
2728
2651
|
}
|
|
2729
|
-
return
|
|
2730
|
-
}
|
|
2731
|
-
/**
|
|
2732
|
-
* Activates a previously verified manifest for local replica and outbox access only.
|
|
2733
|
-
*
|
|
2734
|
-
* @remarks
|
|
2735
|
-
* This never enables pull or command replay. A later successful remote authentication must call
|
|
2736
|
-
* {@link activateSession} before synchronization can use transport.
|
|
2737
|
-
*
|
|
2738
|
-
* @param authSubject - A currently known provider subject. When supplied, it must match the
|
|
2739
|
-
* persisted subject.
|
|
2740
|
-
*/
|
|
2741
|
-
async activateOfflineSession(authSubject, lease) {
|
|
2742
|
-
const manifest = await this.getOfflineAccessManifest(authSubject);
|
|
2743
|
-
if (lease && !lease.isCurrent())
|
|
2744
|
-
return null;
|
|
2745
|
-
this.#localAccessThisRun = manifest !== null;
|
|
2746
|
-
this.#remoteActivatedThisRun = false;
|
|
2747
|
-
return manifest;
|
|
2748
|
-
}
|
|
2749
|
-
/** Returns the session allowed to use the local replica and append outbox commands. */
|
|
2750
|
-
async getLocalSession() {
|
|
2751
|
-
await this.initialize();
|
|
2752
|
-
return this.#localAccessThisRun ? this.#sessionFromManifest() : null;
|
|
2753
|
-
}
|
|
2754
|
-
/** Returns the remotely authenticated session eligible for pull and command replay. */
|
|
2755
|
-
async getSession() {
|
|
2756
|
-
await this.initialize();
|
|
2757
|
-
return this.#remoteActivatedThisRun ? this.#sessionFromManifest() : null;
|
|
2652
|
+
return this.#idle;
|
|
2758
2653
|
}
|
|
2759
|
-
#
|
|
2760
|
-
|
|
2761
|
-
|
|
2762
|
-
|
|
2763
|
-
|
|
2654
|
+
#release() {
|
|
2655
|
+
this.#active -= 1;
|
|
2656
|
+
if (this.#active !== 0)
|
|
2657
|
+
return;
|
|
2658
|
+
this.#resolveIdle?.();
|
|
2659
|
+
this.#idle = null;
|
|
2660
|
+
this.#resolveIdle = null;
|
|
2764
2661
|
}
|
|
2765
|
-
static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type:
|
|
2766
|
-
static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type:
|
|
2662
|
+
static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: OfflineMutationAdmissionService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
|
|
2663
|
+
static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: OfflineMutationAdmissionService, providedIn: 'root' }); }
|
|
2767
2664
|
}
|
|
2768
|
-
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type:
|
|
2665
|
+
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: OfflineMutationAdmissionService, decorators: [{
|
|
2769
2666
|
type: Injectable,
|
|
2770
2667
|
args: [{ providedIn: 'root' }]
|
|
2771
2668
|
}] });
|
|
2772
2669
|
|
|
2773
|
-
/**
|
|
2774
|
-
* Local offline storage could not be opened or migrated without risking data loss.
|
|
2775
|
-
*
|
|
2776
|
-
* Prefer `instanceof` / {@link OfflineStorageUnavailableError.reason} over message text.
|
|
2777
|
-
* The original failure is preserved on {@link Error.cause}. Kit never deletes Outbox or
|
|
2778
|
-
* replica rows in response to this error; recovery is product-owned and explicit.
|
|
2779
|
-
*/
|
|
2780
|
-
class OfflineStorageUnavailableError extends Error {
|
|
2781
|
-
/** Stable machine-readable discriminator for storage initialization failures. */
|
|
2782
|
-
static { this.code = 'OFFLINE_STORAGE_UNAVAILABLE'; }
|
|
2783
|
-
constructor(reason, message, options) {
|
|
2784
|
-
super(message, options);
|
|
2785
|
-
this.reason = reason;
|
|
2786
|
-
this.code = OfflineStorageUnavailableError.code;
|
|
2787
|
-
this.name = 'OfflineStorageUnavailableError';
|
|
2788
|
-
}
|
|
2789
|
-
}
|
|
2790
|
-
/** Narrows an unknown failure to {@link OfflineStorageUnavailableError}. */
|
|
2791
|
-
function isOfflineStorageUnavailableError(error) {
|
|
2792
|
-
return error instanceof OfflineStorageUnavailableError;
|
|
2793
|
-
}
|
|
2794
|
-
|
|
2795
2670
|
/** Raised before persistence when an outbox payload is not losslessly JSON serializable. */
|
|
2796
2671
|
class OfflinePayloadValidationError extends Error {
|
|
2797
2672
|
constructor(message = 'Offline command payload must contain only JSON values') {
|
|
@@ -2847,6 +2722,7 @@ function offlineRetryDelayMs(attempts, random = Math.random) {
|
|
|
2847
2722
|
/** Maintains the optimistic local replica and synchronizes its durable outbox. */
|
|
2848
2723
|
class OfflineSyncService {
|
|
2849
2724
|
#network;
|
|
2725
|
+
#mutationAdmission;
|
|
2850
2726
|
#repository;
|
|
2851
2727
|
#executor;
|
|
2852
2728
|
#context;
|
|
@@ -2875,6 +2751,7 @@ class OfflineSyncService {
|
|
|
2875
2751
|
#lastCommandCreatedAt;
|
|
2876
2752
|
constructor() {
|
|
2877
2753
|
this.#network = inject(OfflineNetworkService);
|
|
2754
|
+
this.#mutationAdmission = inject(OfflineMutationAdmissionService);
|
|
2878
2755
|
this.#repository = inject(OFFLINE_REPOSITORY);
|
|
2879
2756
|
this.#executor = inject(OFFLINE_COMMAND_EXECUTOR);
|
|
2880
2757
|
this.#context = inject(OFFLINE_SYNC_CONTEXT);
|
|
@@ -2988,21 +2865,25 @@ class OfflineSyncService {
|
|
|
2988
2865
|
this.#foregroundScopePolicy = null;
|
|
2989
2866
|
}
|
|
2990
2867
|
enqueue(request, options = {}) {
|
|
2991
|
-
|
|
2992
|
-
|
|
2868
|
+
return this.#mutationAdmission.run(() => {
|
|
2869
|
+
const generation = this.#generation;
|
|
2870
|
+
return this.#serializeReplicaMutation((repository) => this.#enqueue(request, options, generation, undefined, repository));
|
|
2871
|
+
});
|
|
2993
2872
|
}
|
|
2994
2873
|
/**
|
|
2995
2874
|
* Reads, derives, and commits one Outbox command, then rematerializes its
|
|
2996
2875
|
* aggregate from confirmed replica values plus remaining FIFO intents.
|
|
2997
2876
|
*/
|
|
2998
2877
|
enqueuePrepared(prepare, options = {}) {
|
|
2999
|
-
|
|
3000
|
-
|
|
3001
|
-
|
|
3002
|
-
|
|
3003
|
-
|
|
3004
|
-
|
|
3005
|
-
|
|
2878
|
+
return this.#mutationAdmission.run(() => {
|
|
2879
|
+
const generation = this.#generation;
|
|
2880
|
+
return this.#serializeReplicaMutation(async (repository) => {
|
|
2881
|
+
await this.initialize();
|
|
2882
|
+
if (!this.#isCurrent(generation))
|
|
2883
|
+
throw new Error('Offline session changed before prepared enqueue.');
|
|
2884
|
+
const prepared = await prepare(repository);
|
|
2885
|
+
return this.#enqueue(prepared.request, options, generation, undefined, repository);
|
|
2886
|
+
});
|
|
3006
2887
|
});
|
|
3007
2888
|
}
|
|
3008
2889
|
/**
|
|
@@ -3014,13 +2895,15 @@ class OfflineSyncService {
|
|
|
3014
2895
|
* rejected with no durable state change.
|
|
3015
2896
|
*/
|
|
3016
2897
|
enqueuePreparedBatch(prepare, options = {}) {
|
|
3017
|
-
|
|
3018
|
-
|
|
3019
|
-
|
|
3020
|
-
|
|
3021
|
-
|
|
3022
|
-
|
|
3023
|
-
|
|
2898
|
+
return this.#mutationAdmission.run(() => {
|
|
2899
|
+
const generation = this.#generation;
|
|
2900
|
+
return this.#serializeReplicaMutation(async (repository) => {
|
|
2901
|
+
await this.initialize();
|
|
2902
|
+
if (!this.#isCurrent(generation))
|
|
2903
|
+
throw new Error('Offline session changed before prepared batch enqueue.');
|
|
2904
|
+
const prepared = await prepare(repository);
|
|
2905
|
+
return this.#enqueuePreparedBatch(prepared, options, generation, repository);
|
|
2906
|
+
});
|
|
3024
2907
|
});
|
|
3025
2908
|
}
|
|
3026
2909
|
/**
|
|
@@ -3481,7 +3364,7 @@ class OfflineSyncService {
|
|
|
3481
3364
|
}
|
|
3482
3365
|
}
|
|
3483
3366
|
#flushInBackground() {
|
|
3484
|
-
void this.#beginFlush(false).catch((error) => this.#
|
|
3367
|
+
void this.#beginFlush(false).catch((error) => this.#reportError(error));
|
|
3485
3368
|
}
|
|
3486
3369
|
flush() {
|
|
3487
3370
|
return this.#beginFlush(true);
|
|
@@ -3542,17 +3425,18 @@ class OfflineSyncService {
|
|
|
3542
3425
|
for (const scope of pullScopes) {
|
|
3543
3426
|
if (!this.#isCurrent(generation) || !this.#network.connected())
|
|
3544
3427
|
return;
|
|
3545
|
-
|
|
3428
|
+
const pullScope = async () => {
|
|
3546
3429
|
await this.#pull.pull(scope);
|
|
3547
3430
|
await this.#markScopeReconciled(scope, generation);
|
|
3548
3431
|
pulledScopeKeys.add(this.#scopeKey(scope));
|
|
3549
|
-
}
|
|
3550
|
-
|
|
3551
|
-
|
|
3552
|
-
|
|
3432
|
+
};
|
|
3433
|
+
const pull = await pullScope().then(() => ({ status: 'fulfilled' }), (error) => ({ status: 'rejected', error }));
|
|
3434
|
+
if (pull.status === 'rejected') {
|
|
3435
|
+
prePullFailures.push(pull.error);
|
|
3436
|
+
if (this.#isFatalPullFailure(pull.error)) {
|
|
3553
3437
|
// Auth/upgrade-driven recovery only: stop remaining scopes immediately.
|
|
3554
|
-
fatalPullFailure = fatalPullFailure ?? error;
|
|
3555
|
-
await this.#persistFatalPullAttentions(error, scope, pullScopes, generation);
|
|
3438
|
+
fatalPullFailure = fatalPullFailure ?? pull.error;
|
|
3439
|
+
await this.#persistFatalPullAttentions(pull.error, scope, pullScopes, generation);
|
|
3556
3440
|
break;
|
|
3557
3441
|
}
|
|
3558
3442
|
if (this.#pendingPullScopes.has(this.#scopeKey(scope))) {
|
|
@@ -3602,20 +3486,20 @@ class OfflineSyncService {
|
|
|
3602
3486
|
for (const scope of postPullScopes) {
|
|
3603
3487
|
if (!this.#isCurrent(generation) || !this.#network.connected())
|
|
3604
3488
|
break;
|
|
3605
|
-
|
|
3606
|
-
|
|
3607
|
-
|
|
3608
|
-
// before the completed Outbox state is exposed to product UI.
|
|
3489
|
+
// A command response may contain only the aggregate's base row. Pull once per dirty scope so
|
|
3490
|
+
// sibling-table journal entries are visible before completed Outbox state reaches product UI.
|
|
3491
|
+
const pullScope = async () => {
|
|
3609
3492
|
await this.#pull.pull(scope);
|
|
3610
3493
|
await this.#markScopeReconciled(scope, generation);
|
|
3611
|
-
}
|
|
3612
|
-
|
|
3613
|
-
|
|
3614
|
-
|
|
3615
|
-
|
|
3494
|
+
};
|
|
3495
|
+
const pull = await pullScope().then(() => ({ status: 'fulfilled' }), (error) => ({ status: 'rejected', error }));
|
|
3496
|
+
if (pull.status === 'rejected') {
|
|
3497
|
+
if (this.#isFatalPullFailure(pull.error)) {
|
|
3498
|
+
fatalPullFailure = fatalPullFailure ?? pull.error;
|
|
3499
|
+
await this.#persistFatalPullAttentions(pull.error, scope, postPullScopes, generation);
|
|
3616
3500
|
break;
|
|
3617
3501
|
}
|
|
3618
|
-
postPullFailures.push(error);
|
|
3502
|
+
postPullFailures.push(pull.error);
|
|
3619
3503
|
}
|
|
3620
3504
|
}
|
|
3621
3505
|
}
|
|
@@ -3743,16 +3627,16 @@ class OfflineSyncService {
|
|
|
3743
3627
|
await this.#refreshState(generation);
|
|
3744
3628
|
if (!this.#isCurrent(generation))
|
|
3745
3629
|
return;
|
|
3746
|
-
|
|
3747
|
-
|
|
3748
|
-
|
|
3749
|
-
|
|
3750
|
-
catch (error) {
|
|
3630
|
+
const claimedCommand = sending;
|
|
3631
|
+
const readRow = async () => this.#rowForCommand(claimedCommand);
|
|
3632
|
+
const rowResult = await readRow().then((row) => ({ status: 'fulfilled', row }), (error) => ({ status: 'rejected', error }));
|
|
3633
|
+
if (rowResult.status === 'rejected') {
|
|
3751
3634
|
if (!this.#isCurrent(generation))
|
|
3752
3635
|
return;
|
|
3753
|
-
await this.#persistFailedCommand(sending, error, generation, null, sending.serverCommitUnknown === true);
|
|
3754
|
-
throw error;
|
|
3636
|
+
await this.#persistFailedCommand(sending, rowResult.error, generation, null, sending.serverCommitUnknown === true);
|
|
3637
|
+
throw rowResult.error;
|
|
3755
3638
|
}
|
|
3639
|
+
const row = rowResult.row;
|
|
3756
3640
|
if (!row) {
|
|
3757
3641
|
const error = new Error(`Offline replica row not found: ${sending.aggregateType}/${canonicalOfflineCommandIdentity(sending.identity)}`);
|
|
3758
3642
|
await this.#persistFailedCommand(sending, error, generation, null, sending.serverCommitUnknown === true);
|
|
@@ -3763,31 +3647,29 @@ class OfflineSyncService {
|
|
|
3763
3647
|
if (!transportCommand)
|
|
3764
3648
|
return;
|
|
3765
3649
|
sending = transportCommand;
|
|
3766
|
-
|
|
3767
|
-
|
|
3768
|
-
|
|
3769
|
-
}
|
|
3770
|
-
catch (error) {
|
|
3650
|
+
const executeCommand = async () => this.#executor.execute(sending, offlineCommandTargetFromReplicaRow(row));
|
|
3651
|
+
const execution = await executeCommand().then((result) => ({ status: 'fulfilled', result }), (error) => ({ status: 'rejected', error }));
|
|
3652
|
+
if (execution.status === 'rejected') {
|
|
3771
3653
|
if (!this.#isCurrent(generation))
|
|
3772
3654
|
return;
|
|
3773
|
-
const commitUnknown = this.#executor.provesCommandNotCommitted?.(error, sending)
|
|
3655
|
+
const commitUnknown = this.#executor.provesCommandNotCommitted?.(execution.error, sending)
|
|
3774
3656
|
? false
|
|
3775
|
-
: priorCommitUnknown || this.#serverCommitCouldBeUnknown(error);
|
|
3776
|
-
await this.#persistFailedCommand(sending, error, generation, row, commitUnknown);
|
|
3777
|
-
if (!this.#isClassifiableTransportError(error))
|
|
3778
|
-
throw error;
|
|
3657
|
+
: priorCommitUnknown || this.#serverCommitCouldBeUnknown(execution.error);
|
|
3658
|
+
await this.#persistFailedCommand(sending, execution.error, generation, row, commitUnknown);
|
|
3659
|
+
if (!this.#isClassifiableTransportError(execution.error))
|
|
3660
|
+
throw execution.error;
|
|
3779
3661
|
break;
|
|
3780
3662
|
}
|
|
3663
|
+
const result = execution.result;
|
|
3781
3664
|
if (!this.#isCurrent(generation))
|
|
3782
3665
|
return;
|
|
3783
|
-
|
|
3784
|
-
|
|
3785
|
-
|
|
3786
|
-
catch (error) {
|
|
3666
|
+
const completeCommand = async () => this.#completeCommand(commands, sending, result, generation);
|
|
3667
|
+
const completion = await completeCommand().then(() => ({ status: 'fulfilled' }), (error) => ({ status: 'rejected', error }));
|
|
3668
|
+
if (completion.status === 'rejected') {
|
|
3787
3669
|
if (!this.#isCurrent(generation))
|
|
3788
3670
|
return;
|
|
3789
|
-
await this.#persistFailedCommand(sending, error, generation, row, true);
|
|
3790
|
-
throw error;
|
|
3671
|
+
await this.#persistFailedCommand(sending, completion.error, generation, row, true);
|
|
3672
|
+
throw completion.error;
|
|
3791
3673
|
}
|
|
3792
3674
|
if (this.#isCurrent(generation)) {
|
|
3793
3675
|
const scope = { userId: sending.userId, scopeId: sending.scopeId };
|
|
@@ -4033,9 +3915,19 @@ class OfflineSyncService {
|
|
|
4033
3915
|
return status === 0 || status === 429 || status >= 500;
|
|
4034
3916
|
}
|
|
4035
3917
|
#reportError(error) {
|
|
4036
|
-
|
|
4037
|
-
|
|
4038
|
-
|
|
3918
|
+
queueMicrotask(() => this.#dispatchError(error));
|
|
3919
|
+
}
|
|
3920
|
+
#dispatchError(error) {
|
|
3921
|
+
let result;
|
|
3922
|
+
try {
|
|
3923
|
+
result = this.#errorHandler.handleError(error);
|
|
3924
|
+
}
|
|
3925
|
+
catch {
|
|
3926
|
+
return;
|
|
3927
|
+
}
|
|
3928
|
+
if (result instanceof Promise) {
|
|
3929
|
+
void result.catch(() => undefined);
|
|
3930
|
+
}
|
|
4039
3931
|
}
|
|
4040
3932
|
#assertServerRevision(revision) {
|
|
4041
3933
|
if (typeof revision === 'number' && !Number.isFinite(revision)) {
|
|
@@ -4316,41 +4208,400 @@ function compareOfflineCommands(left, right) {
|
|
|
4316
4208
|
return left.createdAt - right.createdAt || (left.commandId < right.commandId ? -1 : left.commandId > right.commandId ? 1 : 0);
|
|
4317
4209
|
}
|
|
4318
4210
|
|
|
4319
|
-
/**
|
|
4320
|
-
class
|
|
4211
|
+
/** Raised when disabling requires pending commands to be synchronized while transport is offline. */
|
|
4212
|
+
class OfflineMutationPersistenceRequiresOnlineError extends Error {
|
|
4321
4213
|
constructor() {
|
|
4322
|
-
|
|
4214
|
+
super('Pending offline mutations must be synchronized before persistence can be disabled.');
|
|
4215
|
+
this.name = 'OfflineMutationPersistenceRequiresOnlineError';
|
|
4216
|
+
}
|
|
4217
|
+
}
|
|
4218
|
+
/** Raised when pending commands remain after the disable transition attempted a flush. */
|
|
4219
|
+
class OfflineMutationPersistencePendingError extends Error {
|
|
4220
|
+
constructor(pendingCount) {
|
|
4221
|
+
super('Pending offline mutations remain after synchronization.');
|
|
4222
|
+
this.pendingCount = pendingCount;
|
|
4223
|
+
this.name = 'OfflineMutationPersistencePendingError';
|
|
4224
|
+
}
|
|
4225
|
+
}
|
|
4226
|
+
const settledMutationPersistence = async () => undefined;
|
|
4227
|
+
function invokeMutationPersistence(operation) {
|
|
4228
|
+
return new Promise((resolve) => resolve(operation()));
|
|
4229
|
+
}
|
|
4230
|
+
function reportMutationPersistenceError(errorHandler, error) {
|
|
4231
|
+
try {
|
|
4232
|
+
errorHandler.handleError(error);
|
|
4233
|
+
}
|
|
4234
|
+
catch {
|
|
4235
|
+
// Preference failure already degraded safely to disabled. Telemetry must not stop bootstrap.
|
|
4236
|
+
}
|
|
4237
|
+
}
|
|
4238
|
+
/** Read-only mutation admission signal consumed by the HTTP interceptor. */
|
|
4239
|
+
const OFFLINE_MUTATION_PERSISTENCE_ENABLED = new InjectionToken('OFFLINE_MUTATION_PERSISTENCE_ENABLED', {
|
|
4240
|
+
factory: () => () => true,
|
|
4241
|
+
});
|
|
4242
|
+
/** Product adapter used by Kit to persist the device-local mutation preference. */
|
|
4243
|
+
const OFFLINE_MUTATION_PERSISTENCE_ADAPTER = new InjectionToken('OFFLINE_MUTATION_PERSISTENCE_ADAPTER', { factory: () => null });
|
|
4244
|
+
/** Controls whether Kit accepts new durable mutations while leaving replica reads enabled. */
|
|
4245
|
+
class OfflineMutationPersistenceService {
|
|
4246
|
+
constructor() {
|
|
4247
|
+
this.#options = inject(OFFLINE_KIT_OPTIONS);
|
|
4248
|
+
this.#errorHandler = inject(ErrorHandler);
|
|
4249
|
+
this.#persistence = inject(OFFLINE_MUTATION_PERSISTENCE_ADAPTER);
|
|
4323
4250
|
this.#network = inject(OfflineNetworkService);
|
|
4324
4251
|
this.#sync = inject(OfflineSyncService);
|
|
4325
|
-
this.#
|
|
4326
|
-
this.#
|
|
4327
|
-
this.#
|
|
4252
|
+
this.#admission = inject(OfflineMutationAdmissionService);
|
|
4253
|
+
this.#configured = this.#options.mode !== 'readCacheOnly' && this.#options.mutationPersistence !== undefined;
|
|
4254
|
+
this.#state = signal(this.#configured ? 'initializing' : 'enabled', ...(ngDevMode ? [{ debugName: "#state" }] : /* istanbul ignore next */ []));
|
|
4255
|
+
this.#initializePromise = null;
|
|
4256
|
+
this.#transitionTail = settledMutationPersistence();
|
|
4328
4257
|
this.#transitionRevision = 0;
|
|
4329
|
-
this.#
|
|
4330
|
-
|
|
4331
|
-
|
|
4332
|
-
|
|
4333
|
-
|
|
4334
|
-
|
|
4335
|
-
|
|
4336
|
-
|
|
4337
|
-
* Product-policy guard: `true` only when encrypted local storage finished initialization successfully.
|
|
4338
|
-
*
|
|
4339
|
-
* Use this (or {@link storageState}) to disable offline mutations and replica reads when storage is unavailable.
|
|
4340
|
-
*/
|
|
4341
|
-
this.isStorageReady = computed(() => this.#storageState().status === 'ready', ...(ngDevMode ? [{ debugName: "isStorageReady" }] : /* istanbul ignore next */ []));
|
|
4342
|
-
this.networkState = this.#network.state;
|
|
4343
|
-
this.syncState = this.#sync.syncState;
|
|
4344
|
-
this.pendingCount = this.#sync.pendingCount;
|
|
4345
|
-
this.conflicts = this.#sync.conflicts;
|
|
4258
|
+
this.#persistedEnabled = !this.#configured;
|
|
4259
|
+
this.#latestTransition = null;
|
|
4260
|
+
/** Whether the product configured a device-local mutation persistence preference. */
|
|
4261
|
+
this.available = this.#configured;
|
|
4262
|
+
/** Whether new durable Outbox mutations are currently accepted. */
|
|
4263
|
+
this.enabled = computed(() => this.#state() === 'enabled', ...(ngDevMode ? [{ debugName: "enabled" }] : /* istanbul ignore next */ []));
|
|
4264
|
+
/** Whether Kit is draining accepted and pending mutations before disabling. */
|
|
4265
|
+
this.changing = computed(() => this.#state() === 'disabling', ...(ngDevMode ? [{ debugName: "changing" }] : /* istanbul ignore next */ []));
|
|
4346
4266
|
}
|
|
4347
|
-
#
|
|
4267
|
+
#options;
|
|
4268
|
+
#errorHandler;
|
|
4269
|
+
#persistence;
|
|
4348
4270
|
#network;
|
|
4349
4271
|
#sync;
|
|
4350
|
-
#
|
|
4351
|
-
#
|
|
4352
|
-
#
|
|
4353
|
-
#
|
|
4272
|
+
#admission;
|
|
4273
|
+
#configured;
|
|
4274
|
+
#state;
|
|
4275
|
+
#initializePromise;
|
|
4276
|
+
#transitionTail;
|
|
4277
|
+
#transitionRevision;
|
|
4278
|
+
#persistedEnabled;
|
|
4279
|
+
#latestTransition;
|
|
4280
|
+
/** Loads the durable preference before Kit initializes repository-backed services. */
|
|
4281
|
+
async initialize() {
|
|
4282
|
+
if (!this.#configured) {
|
|
4283
|
+
this.#admission.open();
|
|
4284
|
+
return;
|
|
4285
|
+
}
|
|
4286
|
+
await (this.#initializePromise ??= this.#loadInitialPreference());
|
|
4287
|
+
}
|
|
4288
|
+
/**
|
|
4289
|
+
* Enables or disables new durable mutations.
|
|
4290
|
+
*
|
|
4291
|
+
* Disabling closes admission synchronously, waits for already admitted commits,
|
|
4292
|
+
* flushes existing commands, verifies an empty Outbox, and only then persists OFF.
|
|
4293
|
+
*/
|
|
4294
|
+
setEnabled(enabled) {
|
|
4295
|
+
if (!this.#configured)
|
|
4296
|
+
return settledMutationPersistence();
|
|
4297
|
+
const initialization = this.initialize();
|
|
4298
|
+
const latest = this.#latestTransition;
|
|
4299
|
+
if (latest?.enabled === enabled)
|
|
4300
|
+
return latest.promise;
|
|
4301
|
+
if (!latest && ((enabled && this.#state() === 'enabled') || (!enabled && this.#state() === 'disabled'))) {
|
|
4302
|
+
return settledMutationPersistence();
|
|
4303
|
+
}
|
|
4304
|
+
const revision = ++this.#transitionRevision;
|
|
4305
|
+
if (!enabled) {
|
|
4306
|
+
this.#state.set('disabling');
|
|
4307
|
+
void this.#admission.close();
|
|
4308
|
+
}
|
|
4309
|
+
const transition = this.#transitionTail.then(() => initialization).then(() => this.#applyTransition(enabled, revision));
|
|
4310
|
+
this.#transitionTail = transition.catch(() => undefined);
|
|
4311
|
+
const promise = transition.finally(() => {
|
|
4312
|
+
if (this.#latestTransition?.revision === revision)
|
|
4313
|
+
this.#latestTransition = null;
|
|
4314
|
+
});
|
|
4315
|
+
this.#latestTransition = { enabled, promise, revision };
|
|
4316
|
+
return promise;
|
|
4317
|
+
}
|
|
4318
|
+
async #loadInitialPreference() {
|
|
4319
|
+
const persistence = this.#requiredPersistence();
|
|
4320
|
+
return invokeMutationPersistence(() => persistence.loadEnabled()).then((stored) => {
|
|
4321
|
+
this.#persistedEnabled = stored ?? this.#options.mutationPersistence?.defaultEnabled ?? true;
|
|
4322
|
+
if (this.#transitionRevision === 0) {
|
|
4323
|
+
this.#state.set(this.#persistedEnabled ? 'enabled' : 'disabled');
|
|
4324
|
+
if (this.#persistedEnabled)
|
|
4325
|
+
this.#admission.open();
|
|
4326
|
+
}
|
|
4327
|
+
}, async (error) => {
|
|
4328
|
+
this.#persistedEnabled = false;
|
|
4329
|
+
if (this.#transitionRevision === 0)
|
|
4330
|
+
this.#state.set('disabled');
|
|
4331
|
+
await this.#admission.close();
|
|
4332
|
+
reportMutationPersistenceError(this.#errorHandler, error);
|
|
4333
|
+
});
|
|
4334
|
+
}
|
|
4335
|
+
#applyTransition(enabled, revision) {
|
|
4336
|
+
if (revision !== this.#transitionRevision)
|
|
4337
|
+
return settledMutationPersistence();
|
|
4338
|
+
const transition = enabled ? this.#enable(revision) : this.#disable(revision);
|
|
4339
|
+
return transition.catch((error) => {
|
|
4340
|
+
if (revision === this.#transitionRevision) {
|
|
4341
|
+
this.#state.set(this.#persistedEnabled ? 'enabled' : 'disabled');
|
|
4342
|
+
if (this.#persistedEnabled)
|
|
4343
|
+
this.#admission.open();
|
|
4344
|
+
}
|
|
4345
|
+
return Promise.reject(error);
|
|
4346
|
+
});
|
|
4347
|
+
}
|
|
4348
|
+
async #enable(revision) {
|
|
4349
|
+
await this.#requiredPersistence().saveEnabled(true);
|
|
4350
|
+
this.#persistedEnabled = true;
|
|
4351
|
+
if (revision !== this.#transitionRevision)
|
|
4352
|
+
return;
|
|
4353
|
+
this.#state.set('enabled');
|
|
4354
|
+
this.#admission.open();
|
|
4355
|
+
}
|
|
4356
|
+
async #disable(revision) {
|
|
4357
|
+
await this.#admission.close();
|
|
4358
|
+
if (revision !== this.#transitionRevision)
|
|
4359
|
+
return;
|
|
4360
|
+
const pendingBeforeFlush = this.#sync.pendingCount();
|
|
4361
|
+
if (pendingBeforeFlush > 0) {
|
|
4362
|
+
if (this.#network.state() === 'offline')
|
|
4363
|
+
throw new OfflineMutationPersistenceRequiresOnlineError();
|
|
4364
|
+
await this.#sync.flush();
|
|
4365
|
+
}
|
|
4366
|
+
if (revision !== this.#transitionRevision)
|
|
4367
|
+
return;
|
|
4368
|
+
const pendingCount = this.#sync.pendingCount();
|
|
4369
|
+
if (pendingCount > 0)
|
|
4370
|
+
throw new OfflineMutationPersistencePendingError(pendingCount);
|
|
4371
|
+
await this.#requiredPersistence().saveEnabled(false);
|
|
4372
|
+
this.#persistedEnabled = false;
|
|
4373
|
+
if (revision === this.#transitionRevision)
|
|
4374
|
+
this.#state.set('disabled');
|
|
4375
|
+
}
|
|
4376
|
+
#requiredPersistence() {
|
|
4377
|
+
if (!this.#persistence)
|
|
4378
|
+
throw new Error('Offline mutation persistence adapter is not provided.');
|
|
4379
|
+
return this.#persistence;
|
|
4380
|
+
}
|
|
4381
|
+
static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: OfflineMutationPersistenceService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
|
|
4382
|
+
static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: OfflineMutationPersistenceService, providedIn: 'root' }); }
|
|
4383
|
+
}
|
|
4384
|
+
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: OfflineMutationPersistenceService, decorators: [{
|
|
4385
|
+
type: Injectable,
|
|
4386
|
+
args: [{ providedIn: 'root' }]
|
|
4387
|
+
}] });
|
|
4388
|
+
|
|
4389
|
+
/** Checks the authenticated subject and optional scope against one persisted session boundary. */
|
|
4390
|
+
function offlineSessionManifestAllows(manifest, authSubject, scopeId) {
|
|
4391
|
+
if (!manifest || manifest.authSubject !== authSubject)
|
|
4392
|
+
return false;
|
|
4393
|
+
return scopeId === undefined || manifest.scopeIds.includes(scopeId);
|
|
4394
|
+
}
|
|
4395
|
+
/** Owns activation and cleanup of the authenticated local-replica boundary. */
|
|
4396
|
+
class OfflineSessionService {
|
|
4397
|
+
constructor() {
|
|
4398
|
+
this.#repository = inject(OFFLINE_REPOSITORY);
|
|
4399
|
+
this.#activeManifest = signal(null, ...(ngDevMode ? [{ debugName: "#activeManifest" }] : /* istanbul ignore next */ []));
|
|
4400
|
+
this.#initialized = false;
|
|
4401
|
+
this.#localAccessThisRun = false;
|
|
4402
|
+
this.#remoteActivatedThisRun = false;
|
|
4403
|
+
this.activeManifest = this.#activeManifest.asReadonly();
|
|
4404
|
+
}
|
|
4405
|
+
#repository;
|
|
4406
|
+
#activeManifest;
|
|
4407
|
+
#initialized;
|
|
4408
|
+
#localAccessThisRun;
|
|
4409
|
+
#remoteActivatedThisRun;
|
|
4410
|
+
async initialize() {
|
|
4411
|
+
if (this.#initialized)
|
|
4412
|
+
return;
|
|
4413
|
+
await this.#repository.initialize();
|
|
4414
|
+
const userId = await this.#repository.getLastUserId();
|
|
4415
|
+
if (userId !== null) {
|
|
4416
|
+
const manifest = await this.#repository.getSessionManifest(userId);
|
|
4417
|
+
this.#activeManifest.set(manifest ?? { userId, scopeIds: [], authSubject: null, updatedAt: 0 });
|
|
4418
|
+
}
|
|
4419
|
+
this.#initialized = true;
|
|
4420
|
+
}
|
|
4421
|
+
async activateSession(userId, scopeIds, authSubject, lease) {
|
|
4422
|
+
await this.initialize();
|
|
4423
|
+
if (lease && !lease.isCurrent())
|
|
4424
|
+
return false;
|
|
4425
|
+
const normalizedScopeIds = [...new Set(scopeIds)].sort((a, b) => a.localeCompare(b));
|
|
4426
|
+
const previousUserId = await this.#repository.getLastUserId();
|
|
4427
|
+
if (lease && !lease.isCurrent())
|
|
4428
|
+
return false;
|
|
4429
|
+
let previous = previousUserId === userId ? ((await this.#repository.getSessionManifest(userId)) ?? null) : null;
|
|
4430
|
+
if (lease && !lease.isCurrent())
|
|
4431
|
+
return false;
|
|
4432
|
+
// A changed provider subject is a different person even when the product reuses its numeric id.
|
|
4433
|
+
// This deliberately also clears legacy null -> known subject and known subject -> null transitions.
|
|
4434
|
+
if (previousUserId !== null && (previousUserId !== userId || previous?.authSubject !== authSubject)) {
|
|
4435
|
+
await this.#repository.clearUser(previousUserId);
|
|
4436
|
+
if (lease && !lease.isCurrent())
|
|
4437
|
+
return false;
|
|
4438
|
+
previous = null;
|
|
4439
|
+
}
|
|
4440
|
+
const active = new Set(normalizedScopeIds);
|
|
4441
|
+
await Promise.all((previous?.scopeIds ?? [])
|
|
4442
|
+
.filter((scopeId) => !active.has(scopeId))
|
|
4443
|
+
.map((scopeId) => this.#repository.clearScope({ userId, scopeId })));
|
|
4444
|
+
if (lease && !lease.isCurrent())
|
|
4445
|
+
return false;
|
|
4446
|
+
const manifest = {
|
|
4447
|
+
userId,
|
|
4448
|
+
scopeIds: normalizedScopeIds,
|
|
4449
|
+
authSubject,
|
|
4450
|
+
updatedAt: Date.now(),
|
|
4451
|
+
};
|
|
4452
|
+
await this.#repository.setLastUserId(userId);
|
|
4453
|
+
if (lease && !lease.isCurrent())
|
|
4454
|
+
return false;
|
|
4455
|
+
await this.#repository.putSessionManifest(userId, manifest);
|
|
4456
|
+
if (lease && !lease.isCurrent())
|
|
4457
|
+
return false;
|
|
4458
|
+
this.#activeManifest.set(manifest);
|
|
4459
|
+
this.#localAccessThisRun = true;
|
|
4460
|
+
this.#remoteActivatedThisRun = true;
|
|
4461
|
+
return lease ? true : undefined;
|
|
4462
|
+
}
|
|
4463
|
+
async clearActiveSession() {
|
|
4464
|
+
await this.initialize();
|
|
4465
|
+
const userId = await this.#repository.getLastUserId();
|
|
4466
|
+
if (userId !== null)
|
|
4467
|
+
await this.#repository.clearUser(userId);
|
|
4468
|
+
this.#activeManifest.set(null);
|
|
4469
|
+
this.#localAccessThisRun = false;
|
|
4470
|
+
this.#remoteActivatedThisRun = false;
|
|
4471
|
+
}
|
|
4472
|
+
/** Immediately revoke local and remote runtime access while durable cleanup is pending. */
|
|
4473
|
+
revokeAccess() {
|
|
4474
|
+
this.#localAccessThisRun = false;
|
|
4475
|
+
this.#remoteActivatedThisRun = false;
|
|
4476
|
+
}
|
|
4477
|
+
/** Disable remote pull/replay eligibility while retaining the verified local manifest. */
|
|
4478
|
+
async suspendRemoteSession() {
|
|
4479
|
+
await this.initialize();
|
|
4480
|
+
this.#remoteActivatedThisRun = false;
|
|
4481
|
+
}
|
|
4482
|
+
/**
|
|
4483
|
+
* Returns the persisted identity boundary for local-only route access.
|
|
4484
|
+
*
|
|
4485
|
+
* @remarks
|
|
4486
|
+
* This does not activate the sync context. Call it only after the authentication authority has
|
|
4487
|
+
* been classified as unavailable, never after explicit sign-out or HTTP 401/403. Legacy
|
|
4488
|
+
* manifests without an authentication-provider subject are rejected.
|
|
4489
|
+
*
|
|
4490
|
+
* @param authSubject - A currently known provider subject. When supplied, it must match the
|
|
4491
|
+
* persisted subject.
|
|
4492
|
+
*/
|
|
4493
|
+
async getOfflineAccessManifest(authSubject) {
|
|
4494
|
+
await this.initialize();
|
|
4495
|
+
const manifest = this.#activeManifest();
|
|
4496
|
+
if (!manifest?.authSubject || (authSubject !== undefined && manifest.authSubject !== authSubject)) {
|
|
4497
|
+
return null;
|
|
4498
|
+
}
|
|
4499
|
+
return { ...manifest, scopeIds: [...manifest.scopeIds] };
|
|
4500
|
+
}
|
|
4501
|
+
/**
|
|
4502
|
+
* Activates a previously verified manifest for local replica and outbox access only.
|
|
4503
|
+
*
|
|
4504
|
+
* @remarks
|
|
4505
|
+
* This never enables pull or command replay. A later successful remote authentication must call
|
|
4506
|
+
* {@link activateSession} before synchronization can use transport.
|
|
4507
|
+
*
|
|
4508
|
+
* @param authSubject - A currently known provider subject. When supplied, it must match the
|
|
4509
|
+
* persisted subject.
|
|
4510
|
+
*/
|
|
4511
|
+
async activateOfflineSession(authSubject, lease) {
|
|
4512
|
+
const manifest = await this.getOfflineAccessManifest(authSubject);
|
|
4513
|
+
if (lease && !lease.isCurrent())
|
|
4514
|
+
return null;
|
|
4515
|
+
this.#localAccessThisRun = manifest !== null;
|
|
4516
|
+
this.#remoteActivatedThisRun = false;
|
|
4517
|
+
return manifest;
|
|
4518
|
+
}
|
|
4519
|
+
/** Returns the session allowed to use the local replica and append outbox commands. */
|
|
4520
|
+
async getLocalSession() {
|
|
4521
|
+
await this.initialize();
|
|
4522
|
+
return this.#localAccessThisRun ? this.#sessionFromManifest() : null;
|
|
4523
|
+
}
|
|
4524
|
+
/** Returns the remotely authenticated session eligible for pull and command replay. */
|
|
4525
|
+
async getSession() {
|
|
4526
|
+
await this.initialize();
|
|
4527
|
+
return this.#remoteActivatedThisRun ? this.#sessionFromManifest() : null;
|
|
4528
|
+
}
|
|
4529
|
+
#sessionFromManifest() {
|
|
4530
|
+
const manifest = this.#activeManifest();
|
|
4531
|
+
return manifest
|
|
4532
|
+
? { userId: manifest.userId, scopes: manifest.scopeIds.map((scopeId) => ({ userId: manifest.userId, scopeId })) }
|
|
4533
|
+
: null;
|
|
4534
|
+
}
|
|
4535
|
+
static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: OfflineSessionService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
|
|
4536
|
+
static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: OfflineSessionService, providedIn: 'root' }); }
|
|
4537
|
+
}
|
|
4538
|
+
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: OfflineSessionService, decorators: [{
|
|
4539
|
+
type: Injectable,
|
|
4540
|
+
args: [{ providedIn: 'root' }]
|
|
4541
|
+
}] });
|
|
4542
|
+
|
|
4543
|
+
/**
|
|
4544
|
+
* Local offline storage could not be opened or migrated without risking data loss.
|
|
4545
|
+
*
|
|
4546
|
+
* Prefer `instanceof` / {@link OfflineStorageUnavailableError.reason} over message text.
|
|
4547
|
+
* The original failure is preserved on {@link Error.cause}. Kit never deletes Outbox or
|
|
4548
|
+
* replica rows in response to this error; recovery is product-owned and explicit.
|
|
4549
|
+
*/
|
|
4550
|
+
class OfflineStorageUnavailableError extends Error {
|
|
4551
|
+
/** Stable machine-readable discriminator for storage initialization failures. */
|
|
4552
|
+
static { this.code = 'OFFLINE_STORAGE_UNAVAILABLE'; }
|
|
4553
|
+
constructor(reason, message, options) {
|
|
4554
|
+
super(message, options);
|
|
4555
|
+
this.reason = reason;
|
|
4556
|
+
this.code = OfflineStorageUnavailableError.code;
|
|
4557
|
+
this.name = 'OfflineStorageUnavailableError';
|
|
4558
|
+
}
|
|
4559
|
+
}
|
|
4560
|
+
/** Narrows an unknown failure to {@link OfflineStorageUnavailableError}. */
|
|
4561
|
+
function isOfflineStorageUnavailableError(error) {
|
|
4562
|
+
return error instanceof OfflineStorageUnavailableError;
|
|
4563
|
+
}
|
|
4564
|
+
|
|
4565
|
+
const settledTransition = async () => undefined;
|
|
4566
|
+
/** Coordinates local persistence, session boundaries, network state, and outbox synchronization. */
|
|
4567
|
+
class OfflineCoordinatorService {
|
|
4568
|
+
constructor() {
|
|
4569
|
+
this.#repository = inject(OFFLINE_REPOSITORY);
|
|
4570
|
+
this.#network = inject(OfflineNetworkService);
|
|
4571
|
+
this.#mutationPersistence = inject(OfflineMutationPersistenceService);
|
|
4572
|
+
this.#sync = inject(OfflineSyncService);
|
|
4573
|
+
this.#session = inject(OfflineSessionService);
|
|
4574
|
+
this.#options = inject(OFFLINE_KIT_OPTIONS);
|
|
4575
|
+
this.#storageState = signal({ status: 'initializing' }, ...(ngDevMode ? [{ debugName: "#storageState" }] : /* istanbul ignore next */ []));
|
|
4576
|
+
this.#transitionRevision = 0;
|
|
4577
|
+
this.#transitionTail = settledTransition();
|
|
4578
|
+
/**
|
|
4579
|
+
* Local storage readiness after {@link initialize}.
|
|
4580
|
+
*
|
|
4581
|
+
* When `unavailable`, the product opted into online-only startup; replica/outbox APIs must not be used.
|
|
4582
|
+
*/
|
|
4583
|
+
this.storageState = this.#storageState.asReadonly();
|
|
4584
|
+
/**
|
|
4585
|
+
* Product-policy guard: `true` only when encrypted local storage finished initialization successfully.
|
|
4586
|
+
*
|
|
4587
|
+
* Use this (or {@link storageState}) to disable offline mutations and replica reads when storage is unavailable.
|
|
4588
|
+
*/
|
|
4589
|
+
this.isStorageReady = computed(() => this.#storageState().status === 'ready', ...(ngDevMode ? [{ debugName: "isStorageReady" }] : /* istanbul ignore next */ []));
|
|
4590
|
+
this.networkState = this.#network.state;
|
|
4591
|
+
this.syncState = this.#sync.syncState;
|
|
4592
|
+
this.pendingCount = this.#sync.pendingCount;
|
|
4593
|
+
this.conflicts = this.#sync.conflicts;
|
|
4594
|
+
/** Device-local control for accepting new durable Outbox mutations. */
|
|
4595
|
+
this.mutationPersistence = this.#mutationPersistence;
|
|
4596
|
+
}
|
|
4597
|
+
#repository;
|
|
4598
|
+
#network;
|
|
4599
|
+
#mutationPersistence;
|
|
4600
|
+
#sync;
|
|
4601
|
+
#session;
|
|
4602
|
+
#options;
|
|
4603
|
+
#storageState;
|
|
4604
|
+
#transitionRevision;
|
|
4354
4605
|
#transitionTail;
|
|
4355
4606
|
/**
|
|
4356
4607
|
* Opens local storage, then session and sync.
|
|
@@ -4360,11 +4611,10 @@ class OfflineCoordinatorService {
|
|
|
4360
4611
|
* resolves with {@link storageState} `unavailable` and skips session/sync initialization.
|
|
4361
4612
|
*/
|
|
4362
4613
|
async initialize() {
|
|
4614
|
+
await this.#mutationPersistence.initialize();
|
|
4363
4615
|
const networkReady = this.#network.initialize();
|
|
4364
|
-
|
|
4365
|
-
|
|
4366
|
-
}
|
|
4367
|
-
catch (error) {
|
|
4616
|
+
const initializeRepository = async () => this.#repository.initialize();
|
|
4617
|
+
const repositoryReady = await initializeRepository().then(() => true, async (error) => {
|
|
4368
4618
|
await networkReady;
|
|
4369
4619
|
const typed = this.#asStorageUnavailable(error);
|
|
4370
4620
|
this.#storageState.set({ status: 'unavailable', error: typed });
|
|
@@ -4372,8 +4622,10 @@ class OfflineCoordinatorService {
|
|
|
4372
4622
|
if (!onUnavailable)
|
|
4373
4623
|
throw typed;
|
|
4374
4624
|
await onUnavailable(typed);
|
|
4625
|
+
return false;
|
|
4626
|
+
});
|
|
4627
|
+
if (!repositoryReady)
|
|
4375
4628
|
return;
|
|
4376
|
-
}
|
|
4377
4629
|
await networkReady;
|
|
4378
4630
|
this.#storageState.set({ status: 'ready' });
|
|
4379
4631
|
await this.#session.initialize();
|
|
@@ -4385,9 +4637,9 @@ class OfflineCoordinatorService {
|
|
|
4385
4637
|
await this.resumeRemoteSession();
|
|
4386
4638
|
}
|
|
4387
4639
|
/** Installs a remotely verified identity without starting pull or outbox replay. */
|
|
4388
|
-
prepareRemoteSession(userId, scopeIds, authSubject, authLease) {
|
|
4640
|
+
async prepareRemoteSession(userId, scopeIds, authSubject, authLease) {
|
|
4389
4641
|
if (this.#storageUnavailable())
|
|
4390
|
-
return
|
|
4642
|
+
return true;
|
|
4391
4643
|
const revision = ++this.#transitionRevision;
|
|
4392
4644
|
const lease = this.#lease(revision, authLease);
|
|
4393
4645
|
return this.#enqueueTransition(async () => {
|
|
@@ -4407,9 +4659,9 @@ class OfflineCoordinatorService {
|
|
|
4407
4659
|
/**
|
|
4408
4660
|
* Activates a restored identity for local replica/outbox use without enabling transport sync.
|
|
4409
4661
|
*/
|
|
4410
|
-
activateOfflineSession(authSubject, authLease) {
|
|
4662
|
+
async activateOfflineSession(authSubject, authLease) {
|
|
4411
4663
|
if (this.#storageUnavailable())
|
|
4412
|
-
return
|
|
4664
|
+
return null;
|
|
4413
4665
|
const revision = ++this.#transitionRevision;
|
|
4414
4666
|
const lease = this.#lease(revision, authLease);
|
|
4415
4667
|
return this.#enqueueTransition(async () => {
|
|
@@ -4422,9 +4674,9 @@ class OfflineCoordinatorService {
|
|
|
4422
4674
|
return lease.isCurrent() ? manifest : null;
|
|
4423
4675
|
});
|
|
4424
4676
|
}
|
|
4425
|
-
clearActiveSession() {
|
|
4677
|
+
async clearActiveSession() {
|
|
4426
4678
|
if (this.#storageUnavailable())
|
|
4427
|
-
return
|
|
4679
|
+
return;
|
|
4428
4680
|
this.#sync.revokeSession();
|
|
4429
4681
|
this.#session.revokeAccess();
|
|
4430
4682
|
++this.#transitionRevision;
|
|
@@ -4445,9 +4697,9 @@ class OfflineCoordinatorService {
|
|
|
4445
4697
|
await this.#sync.flush();
|
|
4446
4698
|
return this.#sync.pendingCount() === 0;
|
|
4447
4699
|
}
|
|
4448
|
-
flush() {
|
|
4700
|
+
async flush() {
|
|
4449
4701
|
if (this.#storageUnavailable())
|
|
4450
|
-
return
|
|
4702
|
+
return;
|
|
4451
4703
|
return this.#sync.flush();
|
|
4452
4704
|
}
|
|
4453
4705
|
#asStorageUnavailable(error) {
|
|
@@ -4591,6 +4843,57 @@ function assertOfflineRemoteIdentity(identity) {
|
|
|
4591
4843
|
}
|
|
4592
4844
|
}
|
|
4593
4845
|
|
|
4846
|
+
const COMMUNITY_SQLITE_ENCRYPTED = true;
|
|
4847
|
+
const COMMUNITY_SQLITE_MODE = 'secret';
|
|
4848
|
+
const COMMUNITY_SQLITE_VERSION = 1;
|
|
4849
|
+
const COMMUNITY_SQLITE_READONLY = false;
|
|
4850
|
+
|
|
4851
|
+
const OFFLINE_LOCAL_RESET_REQUESTED = 'requested';
|
|
4852
|
+
/** Persists an explicit destructive reset request, then reloads into a cold bootstrap. */
|
|
4853
|
+
async function requestOfflineLocalReset(options) {
|
|
4854
|
+
await options.markerStore.set({ key: options.markerKey, value: OFFLINE_LOCAL_RESET_REQUESTED });
|
|
4855
|
+
const reloadTarget = options.reloadTarget ?? globalThis.location;
|
|
4856
|
+
reloadTarget.reload();
|
|
4857
|
+
}
|
|
4858
|
+
/**
|
|
4859
|
+
* Recovers an explicit reset request before Angular and Kit open native SQLite.
|
|
4860
|
+
*
|
|
4861
|
+
* The marker is removed only after the Kit database and every product cleanup succeed.
|
|
4862
|
+
* Kit never invokes this helper automatically in response to a storage failure.
|
|
4863
|
+
*/
|
|
4864
|
+
async function recoverOfflineLocalReset(options) {
|
|
4865
|
+
if (!(options.nativePlatform ?? Capacitor.isNativePlatform()))
|
|
4866
|
+
return false;
|
|
4867
|
+
const marker = await options.markerStore.get({ key: options.markerKey });
|
|
4868
|
+
if (marker.value !== OFFLINE_LOCAL_RESET_REQUESTED)
|
|
4869
|
+
return false;
|
|
4870
|
+
await options.sqliteConnection.checkConnectionsConsistency();
|
|
4871
|
+
for (const databaseName of new Set(options.kitCompatibleDatabaseNames)) {
|
|
4872
|
+
const exists = await options.sqliteConnection.isDatabase(databaseName);
|
|
4873
|
+
if (exists.result) {
|
|
4874
|
+
const connection = await options.sqliteConnection.createConnection(databaseName, COMMUNITY_SQLITE_ENCRYPTED, COMMUNITY_SQLITE_MODE, COMMUNITY_SQLITE_VERSION, COMMUNITY_SQLITE_READONLY);
|
|
4875
|
+
await deleteAndCloseOfflineDatabase(options.sqliteConnection, databaseName, connection);
|
|
4876
|
+
}
|
|
4877
|
+
}
|
|
4878
|
+
await options.additionalCleanup?.();
|
|
4879
|
+
await options.markerStore.remove({ key: options.markerKey });
|
|
4880
|
+
return true;
|
|
4881
|
+
}
|
|
4882
|
+
async function settleOfflineResetOperation(operation) {
|
|
4883
|
+
return new Promise((resolve) => resolve(operation())).then(() => ({ ok: true }), (error) => ({ ok: false, error }));
|
|
4884
|
+
}
|
|
4885
|
+
async function deleteAndCloseOfflineDatabase(sqliteConnection, databaseName, connection) {
|
|
4886
|
+
const deletion = await settleOfflineResetOperation(() => connection.delete());
|
|
4887
|
+
const closing = await settleOfflineResetOperation(() => sqliteConnection.closeConnection(databaseName, COMMUNITY_SQLITE_READONLY));
|
|
4888
|
+
if (!deletion.ok && !closing.ok) {
|
|
4889
|
+
throw new AggregateError([deletion.error, closing.error], `Offline database ${databaseName} delete and close both failed.`);
|
|
4890
|
+
}
|
|
4891
|
+
if (!deletion.ok)
|
|
4892
|
+
throw deletion.error;
|
|
4893
|
+
if (!closing.ok)
|
|
4894
|
+
throw closing.error;
|
|
4895
|
+
}
|
|
4896
|
+
|
|
4594
4897
|
/**
|
|
4595
4898
|
* A successful HTTP response that violates the offline mutation protocol.
|
|
4596
4899
|
*
|
|
@@ -4742,10 +5045,11 @@ const COMMUNITY_SQLITE = new InjectionToken('COMMUNITY_SQLITE', {
|
|
|
4742
5045
|
* The returned lower-case hexadecimal value is suitable for
|
|
4743
5046
|
* `OfflineKitOptions.createEncryptionKey` and contains no device or user identifiers.
|
|
4744
5047
|
*/
|
|
4745
|
-
function createRandomOfflineEncryptionKey() {
|
|
5048
|
+
async function createRandomOfflineEncryptionKey() {
|
|
4746
5049
|
const bytes = crypto.getRandomValues(new Uint8Array(32));
|
|
4747
|
-
return
|
|
5050
|
+
return Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('');
|
|
4748
5051
|
}
|
|
5052
|
+
const settledSqliteOperation = async () => undefined;
|
|
4749
5053
|
/** Create the standard encrypted `@capacitor-community/sqlite` driver. */
|
|
4750
5054
|
function createCommunitySqliteDriver(connection) {
|
|
4751
5055
|
const databases = new Map();
|
|
@@ -4764,7 +5068,7 @@ function createCommunitySqliteDriver(connection) {
|
|
|
4764
5068
|
throw new Error('Native offline storage requires a non-empty encryption key on first open');
|
|
4765
5069
|
await connection.setEncryptionSecret(encryptionKey);
|
|
4766
5070
|
}
|
|
4767
|
-
const value = await connection.createConnection(databaseName,
|
|
5071
|
+
const value = await connection.createConnection(databaseName, COMMUNITY_SQLITE_ENCRYPTED, COMMUNITY_SQLITE_MODE, COMMUNITY_SQLITE_VERSION, COMMUNITY_SQLITE_READONLY);
|
|
4768
5072
|
await value.open();
|
|
4769
5073
|
databases.set(databaseName, value);
|
|
4770
5074
|
return { databaseId: databaseName };
|
|
@@ -4850,15 +5154,15 @@ class SqliteOfflineRepository {
|
|
|
4850
5154
|
#options = inject(OFFLINE_KIT_OPTIONS);
|
|
4851
5155
|
#databaseId = null;
|
|
4852
5156
|
#initialization = null;
|
|
4853
|
-
#writes =
|
|
5157
|
+
#writes = settledSqliteOperation();
|
|
4854
5158
|
#activeReaders = 0;
|
|
4855
|
-
#readersIdle =
|
|
5159
|
+
#readersIdle = settledSqliteOperation();
|
|
4856
5160
|
#resolveReadersIdle = null;
|
|
4857
5161
|
#atomicMutationRevision = null;
|
|
4858
5162
|
#atomicMutationCommitted = false;
|
|
4859
|
-
#atomicOperations =
|
|
5163
|
+
#atomicOperations = settledSqliteOperation();
|
|
4860
5164
|
#readSnapshotActive = false;
|
|
4861
|
-
#atomicIdle =
|
|
5165
|
+
#atomicIdle = settledSqliteOperation();
|
|
4862
5166
|
#resolveAtomicIdle = null;
|
|
4863
5167
|
initialize() {
|
|
4864
5168
|
this.#initialization ??= this.#open();
|
|
@@ -4919,12 +5223,8 @@ class SqliteOfflineRepository {
|
|
|
4919
5223
|
}
|
|
4920
5224
|
return this.#transaction(async () => {
|
|
4921
5225
|
this.#readSnapshotActive = true;
|
|
4922
|
-
|
|
4923
|
-
|
|
4924
|
-
}
|
|
4925
|
-
finally {
|
|
4926
|
-
this.#readSnapshotActive = false;
|
|
4927
|
-
}
|
|
5226
|
+
const executeRead = async () => read(this.#reader());
|
|
5227
|
+
return executeRead().finally(() => (this.#readSnapshotActive = false));
|
|
4928
5228
|
});
|
|
4929
5229
|
}
|
|
4930
5230
|
async [OFFLINE_REPOSITORY_ATOMIC_MUTATION](operation) {
|
|
@@ -4934,9 +5234,9 @@ class SqliteOfflineRepository {
|
|
|
4934
5234
|
throw new Error('Nested offline replica atomic mutations are not supported.');
|
|
4935
5235
|
}
|
|
4936
5236
|
this.#beginReaders();
|
|
4937
|
-
|
|
5237
|
+
const executeAtomicMutation = async () => {
|
|
4938
5238
|
const databaseId = await this.#databaseConnection();
|
|
4939
|
-
this.#atomicOperations =
|
|
5239
|
+
this.#atomicOperations = settledSqliteOperation();
|
|
4940
5240
|
this.#atomicMutationCommitted = false;
|
|
4941
5241
|
this.#atomicIdle = new Promise((resolve) => {
|
|
4942
5242
|
this.#resolveAtomicIdle = resolve;
|
|
@@ -4948,14 +5248,14 @@ class SqliteOfflineRepository {
|
|
|
4948
5248
|
await this.#queueAtomicOperation(() => this.#atomicTransaction(databaseId, async () => undefined, false));
|
|
4949
5249
|
}
|
|
4950
5250
|
return result;
|
|
4951
|
-
}
|
|
4952
|
-
finally {
|
|
5251
|
+
};
|
|
5252
|
+
return executeAtomicMutation().finally(() => {
|
|
4953
5253
|
this.#atomicMutationRevision = null;
|
|
4954
5254
|
this.#endReaders();
|
|
4955
5255
|
this.#resolveAtomicIdle?.();
|
|
4956
5256
|
this.#resolveAtomicIdle = null;
|
|
4957
|
-
this.#atomicIdle =
|
|
4958
|
-
}
|
|
5257
|
+
this.#atomicIdle = settledSqliteOperation();
|
|
5258
|
+
});
|
|
4959
5259
|
}
|
|
4960
5260
|
async putCommand(command) {
|
|
4961
5261
|
await this.#queueWrite((databaseId) => this.#putCommand(databaseId, command));
|
|
@@ -5070,35 +5370,35 @@ class SqliteOfflineRepository {
|
|
|
5070
5370
|
}
|
|
5071
5371
|
}
|
|
5072
5372
|
async #open() {
|
|
5073
|
-
|
|
5074
|
-
if (!this.#sqlite) {
|
|
5075
|
-
throw new OfflineStorageUnavailableError('storage_unavailable', 'Native offline storage requires a community SQLite connection');
|
|
5076
|
-
}
|
|
5077
|
-
const { databaseId } = await this.#sqlite.open({
|
|
5078
|
-
databaseName: this.#options.databaseName,
|
|
5079
|
-
createEncryptionKey: this.#wrapCreateEncryptionKey(this.#options.createEncryptionKey),
|
|
5080
|
-
});
|
|
5081
|
-
this.#databaseId = databaseId;
|
|
5082
|
-
for (const statement of SCHEMA)
|
|
5083
|
-
await this.#execute(databaseId, statement);
|
|
5084
|
-
const metadata = await this.#queryDatabase(databaseId, 'SELECT schema_version FROM offline_metadata WHERE id = 1');
|
|
5085
|
-
if (metadata.length === 0) {
|
|
5086
|
-
await this.#execute(databaseId, 'INSERT INTO offline_metadata (id, schema_version, last_user_id) VALUES (1, ?, NULL)', [
|
|
5087
|
-
OFFLINE_SCHEMA_VERSION,
|
|
5088
|
-
]);
|
|
5089
|
-
}
|
|
5090
|
-
else {
|
|
5091
|
-
const storedVersion = this.#number(metadata[0]['schema_version']);
|
|
5092
|
-
if (storedVersion !== OFFLINE_SCHEMA_VERSION) {
|
|
5093
|
-
throw new OfflineStorageUnavailableError('core_schema_incompatible', `Unsupported offline storage schema version ${storedVersion}; expected ${OFFLINE_SCHEMA_VERSION}. ` +
|
|
5094
|
-
'A lossless core schema migration is required before this database can be opened.');
|
|
5095
|
-
}
|
|
5096
|
-
}
|
|
5097
|
-
await this.#initializeReplicaSchema(databaseId);
|
|
5098
|
-
}
|
|
5099
|
-
catch (error) {
|
|
5373
|
+
await this.#openDatabase().catch((error) => {
|
|
5100
5374
|
throw this.#mapInitializationError(error);
|
|
5375
|
+
});
|
|
5376
|
+
}
|
|
5377
|
+
async #openDatabase() {
|
|
5378
|
+
if (!this.#sqlite) {
|
|
5379
|
+
throw new OfflineStorageUnavailableError('storage_unavailable', 'Native offline storage requires a community SQLite connection');
|
|
5380
|
+
}
|
|
5381
|
+
const { databaseId } = await this.#sqlite.open({
|
|
5382
|
+
databaseName: this.#options.databaseName,
|
|
5383
|
+
createEncryptionKey: this.#wrapCreateEncryptionKey(this.#options.createEncryptionKey),
|
|
5384
|
+
});
|
|
5385
|
+
this.#databaseId = databaseId;
|
|
5386
|
+
for (const statement of SCHEMA)
|
|
5387
|
+
await this.#execute(databaseId, statement);
|
|
5388
|
+
const metadata = await this.#queryDatabase(databaseId, 'SELECT schema_version FROM offline_metadata WHERE id = 1');
|
|
5389
|
+
if (metadata.length === 0) {
|
|
5390
|
+
await this.#execute(databaseId, 'INSERT INTO offline_metadata (id, schema_version, last_user_id) VALUES (1, ?, NULL)', [
|
|
5391
|
+
OFFLINE_SCHEMA_VERSION,
|
|
5392
|
+
]);
|
|
5393
|
+
}
|
|
5394
|
+
else {
|
|
5395
|
+
const storedVersion = this.#number(metadata[0]['schema_version']);
|
|
5396
|
+
if (storedVersion !== OFFLINE_SCHEMA_VERSION) {
|
|
5397
|
+
throw new OfflineStorageUnavailableError('core_schema_incompatible', `Unsupported offline storage schema version ${storedVersion}; expected ${OFFLINE_SCHEMA_VERSION}. ` +
|
|
5398
|
+
'A lossless core schema migration is required before this database can be opened.');
|
|
5399
|
+
}
|
|
5101
5400
|
}
|
|
5401
|
+
await this.#initializeReplicaSchema(databaseId);
|
|
5102
5402
|
}
|
|
5103
5403
|
async #initializeReplicaSchema(databaseId) {
|
|
5104
5404
|
const bundle = this.#options.replicaSchema;
|
|
@@ -5140,19 +5440,19 @@ class SqliteOfflineRepository {
|
|
|
5140
5440
|
#wrapCreateEncryptionKey(createEncryptionKey) {
|
|
5141
5441
|
if (!createEncryptionKey)
|
|
5142
5442
|
return undefined;
|
|
5143
|
-
return
|
|
5144
|
-
|
|
5443
|
+
return () => {
|
|
5444
|
+
const create = async () => {
|
|
5145
5445
|
const encryptionKey = await createEncryptionKey();
|
|
5146
5446
|
if (!encryptionKey) {
|
|
5147
5447
|
throw new OfflineStorageUnavailableError('encryption_key_unavailable', 'Native offline storage requires a non-empty encryption key on first open');
|
|
5148
5448
|
}
|
|
5149
5449
|
return encryptionKey;
|
|
5150
|
-
}
|
|
5151
|
-
|
|
5450
|
+
};
|
|
5451
|
+
return create().catch((error) => {
|
|
5152
5452
|
if (error instanceof OfflineStorageUnavailableError)
|
|
5153
5453
|
throw error;
|
|
5154
5454
|
throw new OfflineStorageUnavailableError('encryption_key_unavailable', error instanceof Error ? error.message : 'Offline encryption key is unavailable.', { cause: error });
|
|
5155
|
-
}
|
|
5455
|
+
});
|
|
5156
5456
|
};
|
|
5157
5457
|
}
|
|
5158
5458
|
#mapInitializationError(error) {
|
|
@@ -5179,15 +5479,21 @@ class SqliteOfflineRepository {
|
|
|
5179
5479
|
}
|
|
5180
5480
|
async #nativeTransaction(databaseId, run) {
|
|
5181
5481
|
await this.#sqlite.beginTransaction({ databaseId });
|
|
5182
|
-
|
|
5183
|
-
|
|
5482
|
+
const execute = async () => run();
|
|
5483
|
+
return execute()
|
|
5484
|
+
.then(async (result) => {
|
|
5184
5485
|
await this.#sqlite.commitTransaction({ databaseId });
|
|
5185
5486
|
return result;
|
|
5186
|
-
}
|
|
5187
|
-
|
|
5188
|
-
await this.#sqlite.rollbackTransaction({ databaseId });
|
|
5487
|
+
})
|
|
5488
|
+
.catch(async (error) => {
|
|
5489
|
+
const rollback = await this.#sqlite.rollbackTransaction({ databaseId }).then(() => ({ status: 'fulfilled' }), (rollbackError) => ({ status: 'rejected', rollbackError }));
|
|
5490
|
+
if (rollback.status === 'rejected') {
|
|
5491
|
+
throw new AggregateError([error, rollback.rollbackError], 'Offline SQLite transaction and rollback both failed.', {
|
|
5492
|
+
cause: error,
|
|
5493
|
+
});
|
|
5494
|
+
}
|
|
5189
5495
|
throw error;
|
|
5190
|
-
}
|
|
5496
|
+
});
|
|
5191
5497
|
}
|
|
5192
5498
|
async #databaseConnection() {
|
|
5193
5499
|
await this.initialize();
|
|
@@ -5312,16 +5618,12 @@ class SqliteOfflineRepository {
|
|
|
5312
5618
|
const reader = this.#reader();
|
|
5313
5619
|
const atomicTransaction = (run, marksCommit = true) => this.#queueAtomicOperation(() => this.#atomicTransaction(this.#databaseId, run, marksCommit));
|
|
5314
5620
|
return {
|
|
5315
|
-
initialize:
|
|
5621
|
+
initialize: settledSqliteOperation,
|
|
5316
5622
|
...reader,
|
|
5317
5623
|
runReadSnapshot: (read) => this.#queueAtomicOperation(() => this.#nativeTransaction(this.#databaseId, async () => {
|
|
5318
5624
|
this.#readSnapshotActive = true;
|
|
5319
|
-
|
|
5320
|
-
|
|
5321
|
-
}
|
|
5322
|
-
finally {
|
|
5323
|
-
this.#readSnapshotActive = false;
|
|
5324
|
-
}
|
|
5625
|
+
const executeRead = async () => read(reader);
|
|
5626
|
+
return executeRead().finally(() => (this.#readSnapshotActive = false));
|
|
5325
5627
|
})),
|
|
5326
5628
|
putCommand: (command) => atomicTransaction((databaseId) => this.#putCommand(databaseId, command)),
|
|
5327
5629
|
replaceCommand: (command) => atomicTransaction((databaseId) => this.#putCommand(databaseId, command)),
|
|
@@ -5351,12 +5653,8 @@ class SqliteOfflineRepository {
|
|
|
5351
5653
|
}
|
|
5352
5654
|
await this.#writes;
|
|
5353
5655
|
this.#beginReaders();
|
|
5354
|
-
|
|
5355
|
-
|
|
5356
|
-
}
|
|
5357
|
-
finally {
|
|
5358
|
-
this.#endReaders();
|
|
5359
|
-
}
|
|
5656
|
+
const read = async () => operation();
|
|
5657
|
+
return read().finally(() => this.#endReaders());
|
|
5360
5658
|
}
|
|
5361
5659
|
#beginReaders() {
|
|
5362
5660
|
if (this.#activeReaders === 0) {
|
|
@@ -5371,7 +5669,7 @@ class SqliteOfflineRepository {
|
|
|
5371
5669
|
if (this.#activeReaders === 0) {
|
|
5372
5670
|
this.#resolveReadersIdle?.();
|
|
5373
5671
|
this.#resolveReadersIdle = null;
|
|
5374
|
-
this.#readersIdle =
|
|
5672
|
+
this.#readersIdle = settledSqliteOperation();
|
|
5375
5673
|
}
|
|
5376
5674
|
}
|
|
5377
5675
|
async #query(statement, values = []) {
|
|
@@ -5845,6 +6143,7 @@ function provideOffline(options) {
|
|
|
5845
6143
|
replicaSchema: options.replicaSchema,
|
|
5846
6144
|
wireProtocol: options.wireProtocol,
|
|
5847
6145
|
outboxLimits: options.outboxLimits,
|
|
6146
|
+
mutationPersistence: options.mutationPersistence,
|
|
5848
6147
|
onStorageUnavailable: options.onStorageUnavailable,
|
|
5849
6148
|
},
|
|
5850
6149
|
},
|
|
@@ -5856,6 +6155,16 @@ function provideOffline(options) {
|
|
|
5856
6155
|
provide: OFFLINE_REPOSITORY,
|
|
5857
6156
|
useFactory: () => selectOfflineRepository(Capacitor.getPlatform(), inject(IonicOfflineRepository), inject(SqliteOfflineRepository)),
|
|
5858
6157
|
},
|
|
6158
|
+
{
|
|
6159
|
+
provide: OFFLINE_MUTATION_PERSISTENCE_ENABLED,
|
|
6160
|
+
useFactory: () => inject(OfflineMutationPersistenceService).enabled,
|
|
6161
|
+
},
|
|
6162
|
+
...(options.mutationPersistence
|
|
6163
|
+
? [
|
|
6164
|
+
options.mutationPersistence.adapter,
|
|
6165
|
+
{ provide: OFFLINE_MUTATION_PERSISTENCE_ADAPTER, useExisting: options.mutationPersistence.adapter },
|
|
6166
|
+
]
|
|
6167
|
+
: []),
|
|
5859
6168
|
{ provide: OFFLINE_SYNC_CONTEXT, useExisting: OfflineSessionService },
|
|
5860
6169
|
synchronized
|
|
5861
6170
|
? { provide: OFFLINE_COMMAND_EXECUTOR, useExisting: options.commandExecutor }
|
|
@@ -5905,6 +6214,8 @@ const offlineInterceptor = (request, next) => {
|
|
|
5905
6214
|
return readNetworkFirst(request, plan, transport, fallback);
|
|
5906
6215
|
}
|
|
5907
6216
|
if (LOCAL_FIRST_MUTATION_METHODS.has(request.method)) {
|
|
6217
|
+
if (!inject(OFFLINE_MUTATION_PERSISTENCE_ENABLED)())
|
|
6218
|
+
return transport();
|
|
5908
6219
|
const plan = inject(OfflineMutationRequestPolicyRegistry).resolve(request);
|
|
5909
6220
|
if (plan) {
|
|
5910
6221
|
return defer(() => from(plan.prepare())).pipe(map$1((response) => response.clone({ headers: response.headers.set(OFFLINE_RESPONSE_HEADER, 'optimistic') })));
|
|
@@ -6006,5 +6317,5 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.17", ngImpo
|
|
|
6006
6317
|
* Generated bundle index. Do not edit.
|
|
6007
6318
|
*/
|
|
6008
6319
|
|
|
6009
|
-
export { COMMUNITY_SQLITE, DEFAULT_OFFLINE_COMMAND_HOOKS, IonicOfflineRepository, OFFLINE_AGGREGATE_INTENT_PROJECTOR, OFFLINE_BYPASS, OFFLINE_COMMAND_EXECUTOR, OFFLINE_COMMAND_HOOKS, OFFLINE_KIT_OPTIONS, OFFLINE_MUTATION_REQUEST_POLICIES, OFFLINE_REPLICA_PROJECTOR, OFFLINE_REPLICA_PULLER, OFFLINE_REPOSITORY, OFFLINE_REQUEST_POLICIES, OFFLINE_RESPONSE_HEADER, OFFLINE_RETRY_RANDOM, OFFLINE_SCHEMA_VERSION, OFFLINE_SYNC_CONTEXT, OfflineCommandInFlightError, OfflineCoordinatorService, OfflineMutationPolicyConflictError, OfflineMutationProtocolError, OfflineMutationRequestPolicyRegistry, OfflineNetworkService, OfflineOutboxCapacityError, OfflinePayloadValidationError, OfflineReplicaMutationCoordinator, OfflineReplicaPullService, OfflineReplicaSchemaMismatchError, OfflineRequestFallbackService, OfflineRequestPolicyRegistry, OfflineSessionService, OfflineStorageUnavailableError, OfflineSyncService, SqliteOfflineRepository, assertOfflineLocalId, assertOfflineReplicaGeneratedRemoteId, assertOfflineReplicaNaturalKeyBaseline, assertSupportedOfflineMode, booleanColumn, canonicalOfflineCommandIdentity, canonicalOfflinePrincipalId, canonicalOfflineRemoteIdentity, canonicalOfflineReplicaIdentity, canonicalOfflineReplicaRowKey, commandFootprintKeys, commandIdentityFromReplicaIdentity, commandIdentityMatchesReplicaRow, createCommunitySqliteDriver, createOfflineAuthBridge, createRandomOfflineEncryptionKey, datetime, decodeOfflineReplicaValues, defineOfflineReplicaSchema, defineReplicaEntity, encodeOfflineReplicaValues, generatedId, ignored, integer, isOfflineAggregateIntentConflict, isOfflineFallbackError, isOfflineStorageUnavailableError, json, localOnly, naturalKey, normalizeOfflineNaturalKey, normalizeOfflineReplicaPullPage, nullable, offlineAggregateIntentMutations, offlineCommandLookupIdentity, offlineCommandTargetFromReplicaRow, offlineCommandWithBaseRevision, offlineGeneratedReplicaIdentity, offlineInterceptor, offlineNaturalKeyFromValues, offlineNaturalReplicaIdentity, offlineReplicaRemoteIdentity, offlineRetryDelayMs, offlineSessionManifestAllows, parseOfflineCommandIdentity, parseOfflineMutationEnvelope, parseOfflinePrincipalId, projectOfflineReplicaValues, provideOffline, provideOfflineMutationRequestPolicy, provideOfflineRequestPolicy, real, replicaAddressFromIdentity, requirePositiveOfflineInteger, selectOfflineRepository, serializeOfflineCommandIdentity, sha256OfflineReplicaSchema, supportsSynchronizedOfflineRepository, text };
|
|
6320
|
+
export { COMMUNITY_SQLITE, DEFAULT_OFFLINE_COMMAND_HOOKS, IonicOfflineRepository, OFFLINE_AGGREGATE_INTENT_PROJECTOR, OFFLINE_BYPASS, OFFLINE_COMMAND_EXECUTOR, OFFLINE_COMMAND_HOOKS, OFFLINE_KIT_OPTIONS, OFFLINE_MUTATION_REQUEST_POLICIES, OFFLINE_REPLICA_PROJECTOR, OFFLINE_REPLICA_PULLER, OFFLINE_REPOSITORY, OFFLINE_REQUEST_POLICIES, OFFLINE_RESPONSE_HEADER, OFFLINE_RETRY_RANDOM, OFFLINE_SCHEMA_VERSION, OFFLINE_SYNC_CONTEXT, OfflineCommandInFlightError, OfflineCoordinatorService, OfflineMutationPersistenceDisabledError, OfflineMutationPersistencePendingError, OfflineMutationPersistenceRequiresOnlineError, OfflineMutationPersistenceService, OfflineMutationPolicyConflictError, OfflineMutationProtocolError, OfflineMutationRequestPolicyRegistry, OfflineNetworkService, OfflineOutboxCapacityError, OfflinePayloadValidationError, OfflineReplicaMutationCoordinator, OfflineReplicaPullService, OfflineReplicaSchemaMismatchError, OfflineRequestFallbackService, OfflineRequestPolicyRegistry, OfflineSessionService, OfflineStorageUnavailableError, OfflineSyncService, SqliteOfflineRepository, assertOfflineLocalId, assertOfflineReplicaGeneratedRemoteId, assertOfflineReplicaNaturalKeyBaseline, assertSupportedOfflineMode, booleanColumn, canonicalOfflineCommandIdentity, canonicalOfflinePrincipalId, canonicalOfflineRemoteIdentity, canonicalOfflineReplicaIdentity, canonicalOfflineReplicaRowKey, commandFootprintKeys, commandIdentityFromReplicaIdentity, commandIdentityMatchesReplicaRow, createCommunitySqliteDriver, createOfflineAuthBridge, createRandomOfflineEncryptionKey, datetime, decodeOfflineReplicaValues, defineOfflineReplicaSchema, defineReplicaEntity, encodeOfflineReplicaValues, generatedId, ignored, integer, isOfflineAggregateIntentConflict, isOfflineFallbackError, isOfflineStorageUnavailableError, json, localOnly, naturalKey, normalizeOfflineNaturalKey, normalizeOfflineReplicaPullPage, nullable, offlineAggregateIntentMutations, offlineCommandLookupIdentity, offlineCommandTargetFromReplicaRow, offlineCommandWithBaseRevision, offlineGeneratedReplicaIdentity, offlineInterceptor, offlineNaturalKeyFromValues, offlineNaturalReplicaIdentity, offlineReplicaRemoteIdentity, offlineRetryDelayMs, offlineSessionManifestAllows, parseOfflineCommandIdentity, parseOfflineMutationEnvelope, parseOfflinePrincipalId, projectOfflineReplicaValues, provideOffline, provideOfflineMutationRequestPolicy, provideOfflineRequestPolicy, real, recoverOfflineLocalReset, replicaAddressFromIdentity, requestOfflineLocalReset, requirePositiveOfflineInteger, selectOfflineRepository, serializeOfflineCommandIdentity, sha256OfflineReplicaSchema, supportsSynchronizedOfflineRepository, text };
|
|
6010
6321
|
//# sourceMappingURL=rdlabo-ionic-angular-kit-offline.mjs.map
|