@rdlabo/ionic-angular-kit 21.4.11 → 21.5.0

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 CHANGED
@@ -408,36 +408,37 @@ step immediately invalidates every in-flight auth lease; the second serializes c
408
408
  already in progress and removes the manifest and user replica.
409
409
 
410
410
  ```ts
411
- provideKitAuth(() => {
412
- const offline = inject(OfflineCoordinatorService);
413
- return {
414
- authState: () => auth.state$,
415
- onAuthorized: async () => {
416
- const session = await auth.exchangeCredential();
417
- return {
418
- activate: (lease) => offline.prepareRemoteSession(session.userId, session.groupIds, session.subject, lease),
419
- resume: () => offline.resumeRemoteSession(),
420
- };
411
+ import { createOfflineAuthBridge, isOfflineFallbackError } from '@rdlabo/ionic-angular-kit/offline';
412
+
413
+ provideKitAuth(() => ({
414
+ authState: () => auth.state$,
415
+ ...createOfflineAuthBridge({
416
+ exchange: async (ctx) => {
417
+ const remote = await auth.exchangeCredential(ctx);
418
+ const authSubject = auth.currentSubject();
419
+ return remote && authSubject
420
+ ? { ...remote, authSubject }
421
+ : false;
421
422
  },
422
- onUnavailable: async (_state, _error, lease) => (await offline.activateOfflineSession(auth.currentSubject(), lease)) !== null,
423
+ currentAuthSubject: () => auth.currentSubject(),
423
424
  isUnavailableError: isOfflineFallbackError,
424
- remoteRecovery: {
425
- availability: () => auth.authorityAvailable$,
426
- reauthenticate: async () => {
427
- const session = await auth.tryExchangeCredential();
428
- return session
429
- ? {
430
- activate: (lease) => offline.prepareRemoteSession(session.userId, session.groupIds, session.subject, lease),
431
- resume: () => offline.resumeRemoteSession(),
432
- }
433
- : false;
434
- },
435
- },
436
- redirects,
437
- };
438
- });
425
+ availability: () => auth.authorityAvailable$,
426
+ }),
427
+ redirects,
428
+ }));
439
429
  ```
440
430
 
431
+ `createOfflineAuthBridge` owns `exchange` → `prepareRemoteSession` → kit `grantRemote` → `resumeRemoteSession`
432
+ ordering via `KitRemoteAccessRecovery`. Product code keeps consent, error UI, and credential mapping inside
433
+ `exchange(context)` (`phase: 'authorize' | 'recover'`, optional route state, lease). Return `null`/`false` to decline
434
+ without throwing; thrown errors are never swallowed and remain available to the guard's unavailable/denial
435
+ classification. The returned identity requires a positive `userId`, non-negative numeric scope ids (including the
436
+ current user-scope compatibility value `0`), and a non-empty `authSubject`. The bridge compares that subject before
437
+ session activation, immediately before the coordinator commits through a composite lease, and around remote resume.
438
+ Optional `isIdentityCurrent` can add provider object-identity checks. `onRemoteResumed` receives the identity, phase,
439
+ route state, and post-grant lease for safe redirects or other product side effects. Default recovery availability
440
+ follows `offline.networkState !== 'offline'`.
441
+
441
442
  Register `offlineInterceptor` before `kitAuthInterceptor`. In local mode the auth interceptor synthesizes a
442
443
  transport-unavailable error before generating credentials or touching the network; the outer offline interceptor
443
444
  may then serve a matched `GET` from the replica. In `none` mode the same request is rejected and no local data is
@@ -1,6 +1,8 @@
1
1
  import * as i0 from '@angular/core';
2
2
  import { InjectionToken, inject, Injectable, signal, computed, ErrorHandler, effect, makeEnvironmentProviders, provideAppInitializer } from '@angular/core';
3
3
  import { KitStorageService } from '@rdlabo/ionic-angular-kit';
4
+ import { toObservable } from '@angular/core/rxjs-interop';
5
+ import { map, distinctUntilChanged } from 'rxjs/operators';
4
6
  import { App } from '@capacitor/app';
5
7
  import { Network } from '@capacitor/network';
6
8
  import { Capacitor } from '@capacitor/core';
@@ -2164,6 +2166,110 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.17", ngImpo
2164
2166
  args: [{ providedIn: 'root' }]
2165
2167
  }] });
2166
2168
 
2169
+ /**
2170
+ * Builds the offline-aware {@link KitAuthConfig} fragment for guarded route activation and recovery.
2171
+ *
2172
+ * @remarks
2173
+ * The bridge owns `exchange` → {@link OfflineCoordinatorService.prepareRemoteSession} → kit
2174
+ * `grantRemote` → {@link OfflineCoordinatorService.resumeRemoteSession} ordering by returning
2175
+ * {@link KitRemoteAccessRecovery}. Product consent, error UI, and DTO mapping stay outside.
2176
+ *
2177
+ * @example
2178
+ * ```ts
2179
+ * provideKitAuth(() => ({
2180
+ * authState: () => auth.state$,
2181
+ * ...createOfflineAuthBridge({
2182
+ * exchange: async (ctx) => {
2183
+ * const identity = await auth.exchangeCredential(ctx);
2184
+ * const authSubject = auth.currentSubject();
2185
+ * return identity && authSubject ? { ...identity, authSubject } : false;
2186
+ * },
2187
+ * currentAuthSubject: () => auth.currentSubject(),
2188
+ * isUnavailableError: isOfflineFallbackError,
2189
+ * }),
2190
+ * redirects,
2191
+ * }));
2192
+ * ```
2193
+ */
2194
+ function createOfflineAuthBridge(options) {
2195
+ const offline = options.offline ?? inject(OfflineCoordinatorService);
2196
+ const { exchange, currentAuthSubject, isUnavailableError, isIdentityCurrent, onRemoteResumed, retryDelayMs } = options;
2197
+ const defaultAvailability$ = options.availability
2198
+ ? undefined
2199
+ : toObservable(offline.networkState).pipe(map((state) => state !== 'offline'), distinctUntilChanged());
2200
+ const availability = options.availability ?? (() => defaultAvailability$);
2201
+ const identityStillCurrent = (lease, identity) => lease.isCurrent() && currentAuthSubject() === identity.authSubject && (isIdentityCurrent?.(identity) ?? true);
2202
+ const resolveRemoteAccess = async (phase, state, lease) => {
2203
+ if (!lease.isCurrent())
2204
+ return false;
2205
+ const identity = await exchange({ phase, state, lease });
2206
+ if (!lease.isCurrent())
2207
+ return false;
2208
+ if (identity === null || identity === false)
2209
+ return false;
2210
+ assertOfflineRemoteIdentity(identity);
2211
+ if (!identityStillCurrent(lease, identity))
2212
+ return false;
2213
+ return {
2214
+ activate: async (activateLease) => {
2215
+ if (!identityStillCurrent(activateLease, identity))
2216
+ return false;
2217
+ const identityLease = {
2218
+ isCurrent: () => identityStillCurrent(activateLease, identity),
2219
+ };
2220
+ const prepared = await offline.prepareRemoteSession(identity.userId, identity.scopeIds, identity.authSubject, identityLease);
2221
+ return prepared && identityLease.isCurrent();
2222
+ },
2223
+ resume: async (resumeLease) => {
2224
+ const resumeStillCurrent = () => (resumeLease?.isCurrent() ?? true) && currentAuthSubject() === identity.authSubject && (isIdentityCurrent?.(identity) ?? true);
2225
+ if (!resumeStillCurrent())
2226
+ return;
2227
+ await offline.resumeRemoteSession();
2228
+ if (!resumeStillCurrent())
2229
+ return;
2230
+ if (onRemoteResumed) {
2231
+ await onRemoteResumed({
2232
+ phase,
2233
+ state,
2234
+ lease: resumeLease ?? lease,
2235
+ identity,
2236
+ });
2237
+ if (!resumeStillCurrent())
2238
+ return;
2239
+ }
2240
+ },
2241
+ };
2242
+ };
2243
+ return {
2244
+ isUnavailableError,
2245
+ onAuthorized: (state, lease) => resolveRemoteAccess('authorize', state, lease),
2246
+ onUnavailable: async (_state, _error, lease) => {
2247
+ if (!lease.isCurrent())
2248
+ return false;
2249
+ const manifest = await offline.activateOfflineSession(currentAuthSubject(), lease);
2250
+ if (!lease.isCurrent())
2251
+ return false;
2252
+ return manifest !== null;
2253
+ },
2254
+ remoteRecovery: {
2255
+ retryDelayMs,
2256
+ availability,
2257
+ reauthenticate: (lease) => resolveRemoteAccess('recover', undefined, lease),
2258
+ },
2259
+ };
2260
+ }
2261
+ function assertOfflineRemoteIdentity(identity) {
2262
+ if (!Number.isSafeInteger(identity.userId) || identity.userId <= 0) {
2263
+ throw new Error('Offline remote identity userId must be a positive safe integer.');
2264
+ }
2265
+ if (!Array.isArray(identity.scopeIds) || identity.scopeIds.some((scopeId) => !Number.isSafeInteger(scopeId) || scopeId < 0)) {
2266
+ throw new Error('Offline remote identity scopeIds must contain only non-negative safe integers.');
2267
+ }
2268
+ if (typeof identity.authSubject !== 'string' || identity.authSubject.length === 0) {
2269
+ throw new Error('Offline remote identity authSubject must be a non-empty string.');
2270
+ }
2271
+ }
2272
+
2167
2273
  /** outbox再送時にoffline interceptorだけを迂回する。認証・retryは維持する。 */
2168
2274
  const OFFLINE_BYPASS = new HttpContextToken(() => false);
2169
2275
  /** Header attached to responses served from the local replica fallback. */
@@ -2808,5 +2914,5 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.17", ngImpo
2808
2914
  * Generated bundle index. Do not edit.
2809
2915
  */
2810
2916
 
2811
- export { COMMUNITY_SQLITE, DEFAULT_OFFLINE_COMMAND_HOOKS, IonicOfflineRepository, OFFLINE_BYPASS, OFFLINE_COMMAND_EXECUTOR, OFFLINE_COMMAND_HOOKS, OFFLINE_KIT_OPTIONS, OFFLINE_REPLICA_PULLER, OFFLINE_REPOSITORY, OFFLINE_REQUEST_POLICIES, OFFLINE_RESPONSE_HEADER, OFFLINE_SCHEMA_VERSION, OFFLINE_SYNC_CONTEXT, OfflineCoordinatorService, OfflineNetworkService, OfflinePayloadValidationError, OfflineReplicaPullService, OfflineRequestFallbackService, OfflineRequestPolicyRegistry, OfflineSessionService, OfflineSyncService, SqliteOfflineRepository, assertOfflineReplicaServerId, booleanColumn, createCommunitySqliteDriver, datetime, decodeOfflineReplicaValues, defineOfflineReplicaSchema, defineReplicaEntity, encodeOfflineReplicaValues, ignored, integer, isOfflineFallbackError, json, nullable, offlineInterceptor, projectOfflineReplicaValues, provideOffline, provideOfflineRequestPolicy, real, selectOfflineRepository, serverId, sha256OfflineReplicaSchema, text };
2917
+ export { COMMUNITY_SQLITE, DEFAULT_OFFLINE_COMMAND_HOOKS, IonicOfflineRepository, OFFLINE_BYPASS, OFFLINE_COMMAND_EXECUTOR, OFFLINE_COMMAND_HOOKS, OFFLINE_KIT_OPTIONS, OFFLINE_REPLICA_PULLER, OFFLINE_REPOSITORY, OFFLINE_REQUEST_POLICIES, OFFLINE_RESPONSE_HEADER, OFFLINE_SCHEMA_VERSION, OFFLINE_SYNC_CONTEXT, OfflineCoordinatorService, OfflineNetworkService, OfflinePayloadValidationError, OfflineReplicaPullService, OfflineRequestFallbackService, OfflineRequestPolicyRegistry, OfflineSessionService, OfflineSyncService, SqliteOfflineRepository, assertOfflineReplicaServerId, booleanColumn, createCommunitySqliteDriver, createOfflineAuthBridge, datetime, decodeOfflineReplicaValues, defineOfflineReplicaSchema, defineReplicaEntity, encodeOfflineReplicaValues, ignored, integer, isOfflineFallbackError, json, nullable, offlineInterceptor, projectOfflineReplicaValues, provideOffline, provideOfflineRequestPolicy, real, selectOfflineRepository, serverId, sha256OfflineReplicaSchema, text };
2812
2918
  //# sourceMappingURL=rdlabo-ionic-angular-kit-offline.mjs.map