@rdlabo/ionic-angular-kit 21.4.5 → 21.4.7

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.
@@ -1,16 +1,16 @@
1
1
  import * as i0 from '@angular/core';
2
- import { inject, Injectable, InjectionToken, makeEnvironmentProviders, ElementRef, Injector, input, computed, HostListener, Directive, afterNextRender } from '@angular/core';
2
+ import { inject, Injectable, InjectionToken, makeEnvironmentProviders, ElementRef, Injector, input, computed, HostListener, Directive, ErrorHandler, provideAppInitializer, Optional, afterNextRender } from '@angular/core';
3
3
  import { Storage } from '@ionic/storage-angular';
4
4
  import { ModalController, PopoverController, ToastController, AlertController, LoadingController, NavController } from '@ionic/angular/standalone';
5
5
  import { Capacitor } from '@capacitor/core';
6
6
  import { Keyboard } from '@capacitor/keyboard';
7
7
  import { ImpactStyle, Haptics } from '@capacitor/haptics';
8
8
  import { FORM_FIELD } from '@angular/forms/signals';
9
+ import { BehaviorSubject, throwError, of, from, retry, timer, Subject, Observable, startWith } from 'rxjs';
9
10
  import { Router } from '@angular/router';
10
- import { map, mergeMap, catchError, timeout, tap } from 'rxjs/operators';
11
- import { HttpErrorResponse, HttpResponse } from '@angular/common/http';
11
+ import { catchError, map, mergeMap, timeout, tap } from 'rxjs/operators';
12
+ import { HttpContextToken, HttpErrorResponse, HttpResponse } from '@angular/common/http';
12
13
  import { Network } from '@capacitor/network';
13
- import { from, throwError, retry, timer, Subject, Observable, startWith } from 'rxjs';
14
14
  import { App } from '@capacitor/app';
15
15
 
16
16
  /**
@@ -1212,6 +1212,153 @@ const kitKeyboardInit = async (elementRef, type) => {
1212
1212
  ];
1213
1213
  };
1214
1214
 
1215
+ /** Internal alias of the application auth config used without a module cycle. */
1216
+ const KIT_AUTH_RECOVERY_CONFIG = new InjectionToken('@rdlabo/ionic-angular-kit:auth-recovery');
1217
+ /** Shared runtime access state consumed by guards, UI, HTTP, and realtime connections. */
1218
+ class KitAuthAccessService {
1219
+ constructor() {
1220
+ this.#mode = new BehaviorSubject('none');
1221
+ this.#revision = 0;
1222
+ /** Emits the current access mode and every later transition. */
1223
+ this.mode$ = this.#mode.asObservable();
1224
+ }
1225
+ #mode;
1226
+ #revision;
1227
+ /** Current synchronous access mode. */
1228
+ get mode() {
1229
+ return this.#mode.value;
1230
+ }
1231
+ /**
1232
+ * Monotonic runtime revision used to invalidate an in-flight access transition.
1233
+ *
1234
+ * @internal
1235
+ */
1236
+ get revision() {
1237
+ return this.#revision;
1238
+ }
1239
+ /**
1240
+ * Start a transition and invalidate every older asynchronous access decision.
1241
+ *
1242
+ * @param options - Set `suspendRemote` when the new decision must revoke published remote
1243
+ * capabilities immediately while keeping this new lease valid.
1244
+ */
1245
+ beginTransition(options = {}) {
1246
+ this.#revision += 1;
1247
+ const revision = this.#revision;
1248
+ if (options.suspendRemote && this.#mode.value === 'remote') {
1249
+ this.#mode.next('none');
1250
+ }
1251
+ return { isCurrent: () => this.#revision === revision };
1252
+ }
1253
+ /** Revoke published capabilities without invalidating the transition that owns `lease`. */
1254
+ suspend(lease) {
1255
+ if (!lease.isCurrent())
1256
+ return false;
1257
+ if (this.#mode.value !== 'none')
1258
+ this.#mode.next('none');
1259
+ return true;
1260
+ }
1261
+ /** Publish a verified local-replica-only session. */
1262
+ grantLocal() {
1263
+ this.#publish('local');
1264
+ }
1265
+ /** Publish a remotely authenticated session. */
1266
+ grantRemote() {
1267
+ this.#publish('remote');
1268
+ }
1269
+ /** Revoke both local and remote access. */
1270
+ clear() {
1271
+ this.#publish('none');
1272
+ }
1273
+ #publish(mode) {
1274
+ this.#revision += 1;
1275
+ this.#mode.next(mode);
1276
+ }
1277
+ static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: KitAuthAccessService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
1278
+ static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: KitAuthAccessService, providedIn: 'root' }); }
1279
+ }
1280
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: KitAuthAccessService, decorators: [{
1281
+ type: Injectable,
1282
+ args: [{ providedIn: 'root' }]
1283
+ }] });
1284
+ /** Coordinates single-flight recovery from local-only mode to remote access. */
1285
+ class KitAuthRecoveryService {
1286
+ #access = inject(KitAuthAccessService);
1287
+ #config = inject(KIT_AUTH_RECOVERY_CONFIG);
1288
+ #errorHandler = inject(ErrorHandler);
1289
+ #subscription = null;
1290
+ #recovery = null;
1291
+ /** Subscribe to the configured remote-availability stream once. */
1292
+ initialize() {
1293
+ const recovery = this.#config.remoteRecovery;
1294
+ if (!recovery || this.#subscription)
1295
+ return;
1296
+ this.#subscription = recovery.availability().subscribe({
1297
+ next: (available) => {
1298
+ if (available && this.#access.mode === 'local')
1299
+ void this.recover();
1300
+ },
1301
+ error: (error) => this.#errorHandler.handleError(error),
1302
+ });
1303
+ }
1304
+ /** Run one ordered remote recovery attempt, coalescing concurrent triggers. */
1305
+ recover() {
1306
+ if (this.#recovery)
1307
+ return this.#recovery;
1308
+ const promise = this.#runRecovery().finally(() => {
1309
+ if (this.#recovery === promise)
1310
+ this.#recovery = null;
1311
+ });
1312
+ this.#recovery = promise;
1313
+ return promise;
1314
+ }
1315
+ async #runRecovery() {
1316
+ const recovery = this.#config.remoteRecovery;
1317
+ if (!recovery || this.#access.mode !== 'local')
1318
+ return;
1319
+ const lease = this.#access.beginTransition();
1320
+ let expectedRevision = this.#access.revision;
1321
+ const isCurrent = () => this.#access.revision === expectedRevision;
1322
+ try {
1323
+ const result = await recovery.reauthenticate(lease);
1324
+ if (!isCurrent() || this.#access.mode !== 'local')
1325
+ return;
1326
+ if (result === false) {
1327
+ this.#access.clear();
1328
+ return;
1329
+ }
1330
+ if (!(await result.activate(lease)) || !isCurrent() || this.#access.mode !== 'local')
1331
+ return;
1332
+ this.#access.grantRemote();
1333
+ expectedRevision = this.#access.revision;
1334
+ await result.resume();
1335
+ }
1336
+ catch (error) {
1337
+ if (!isCurrent())
1338
+ return;
1339
+ if (isExplicitAuthDenial(error)) {
1340
+ this.#access.clear();
1341
+ }
1342
+ else if (!this.#config.isUnavailableError?.(error)) {
1343
+ this.#errorHandler.handleError(error);
1344
+ }
1345
+ }
1346
+ }
1347
+ static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: KitAuthRecoveryService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
1348
+ static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: KitAuthRecoveryService, providedIn: 'root' }); }
1349
+ }
1350
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: KitAuthRecoveryService, decorators: [{
1351
+ type: Injectable,
1352
+ args: [{ providedIn: 'root' }]
1353
+ }] });
1354
+ /** Returns true for authoritative authentication denials that must never use local fallback. */
1355
+ function isExplicitAuthDenial(error) {
1356
+ if (typeof error !== 'object' || error === null)
1357
+ return false;
1358
+ const status = error.status;
1359
+ return status === 401 || status === 403;
1360
+ }
1361
+
1215
1362
  /**
1216
1363
  * Injection token that carries the {@link KitAuthConfig} to the authentication guards.
1217
1364
  */
@@ -1243,14 +1390,18 @@ const KIT_AUTH_CONFIG = new InjectionToken('@rdlabo/ionic-angular-kit:auth');
1243
1390
  * });
1244
1391
  * ```
1245
1392
  */
1246
- const provideKitAuth = (configFactory) => makeEnvironmentProviders([{ provide: KIT_AUTH_CONFIG, useFactory: configFactory }]);
1393
+ const provideKitAuth = (configFactory) => makeEnvironmentProviders([
1394
+ { provide: KIT_AUTH_CONFIG, useFactory: configFactory },
1395
+ { provide: KIT_AUTH_RECOVERY_CONFIG, useExisting: KIT_AUTH_CONFIG },
1396
+ provideAppInitializer(() => inject(KitAuthRecoveryService).initialize()),
1397
+ ]);
1247
1398
  /**
1248
1399
  * Guard that requires the user to be unauthenticated (for example sign-in or sign-up pages).
1249
1400
  *
1250
1401
  * @remarks
1251
- * Allows the `required` and `anonymous` states (an anonymous user is permitted to proceed to a
1252
- * registration page). An authenticated user (`user`) is sent to `whenAuthorized`, and a user
1253
- * awaiting confirmation (`confirm`) is sent to `whenConfirming`.
1402
+ * Allows the `required`, `anonymous`, and `unavailable` states (an anonymous user is permitted to
1403
+ * proceed to a registration page). An authenticated user (`user`) is sent to `whenAuthorized`, and
1404
+ * a user awaiting confirmation (`confirm`) is sent to `whenConfirming`.
1254
1405
  *
1255
1406
  * @returns A stream emitting `true` to allow activation, or `false` after triggering a redirect.
1256
1407
  *
@@ -1263,7 +1414,17 @@ const kitRequiredUnauthorizedGuard = () => {
1263
1414
  const { authState, redirects } = inject(KIT_AUTH_CONFIG);
1264
1415
  const router = inject(Router);
1265
1416
  const navCtrl = inject(NavController);
1266
- return authState().pipe(map((data) => {
1417
+ const access = inject(KitAuthAccessService);
1418
+ const lease = access.beginTransition({ suspendRemote: true });
1419
+ return authState().pipe(catchError((error) => {
1420
+ if (lease.isCurrent() && isExplicitAuthDenial(error))
1421
+ access.clear();
1422
+ return throwError(() => error);
1423
+ }), map((data) => {
1424
+ if (!lease.isCurrent())
1425
+ return false;
1426
+ if (data !== 'unavailable')
1427
+ access.clear();
1267
1428
  if (data === 'user') {
1268
1429
  navCtrl.setDirection('root');
1269
1430
  router.navigate([redirects.whenAuthorized]);
@@ -1273,7 +1434,7 @@ const kitRequiredUnauthorizedGuard = () => {
1273
1434
  router.navigate([redirects.whenConfirming]);
1274
1435
  return false;
1275
1436
  }
1276
- // 'required' | 'anonymous'
1437
+ // 'required' | 'anonymous' | 'unavailable'
1277
1438
  return true;
1278
1439
  }));
1279
1440
  };
@@ -1295,7 +1456,17 @@ const kitRequireConfirmingGuard = () => {
1295
1456
  const { authState, redirects } = inject(KIT_AUTH_CONFIG);
1296
1457
  const router = inject(Router);
1297
1458
  const navCtrl = inject(NavController);
1298
- return authState().pipe(map((data) => {
1459
+ const access = inject(KitAuthAccessService);
1460
+ const lease = access.beginTransition({ suspendRemote: true });
1461
+ return authState().pipe(catchError((error) => {
1462
+ if (lease.isCurrent() && isExplicitAuthDenial(error))
1463
+ access.clear();
1464
+ return throwError(() => error);
1465
+ }), map((data) => {
1466
+ if (!lease.isCurrent())
1467
+ return false;
1468
+ if (data !== 'unavailable')
1469
+ access.clear();
1299
1470
  if (data === 'confirm') {
1300
1471
  return true;
1301
1472
  }
@@ -1310,6 +1481,8 @@ const kitRequireConfirmingGuard = () => {
1310
1481
  * @remarks
1311
1482
  * - `user` — runs {@link KitAuthConfig.onAuthorized} (token login, permission checks, and so on).
1312
1483
  * - `anonymous` — allowed as-is, for applications that permit anonymous browsing.
1484
+ * - `unavailable` — runs {@link KitAuthConfig.onUnavailable}; this is the only state intended for
1485
+ * restored local-replica access.
1313
1486
  * - `required` / `confirm` — runs {@link KitAuthConfig.onUnauthenticated}; if it resolves to `false`,
1314
1487
  * the user is redirected to `whenUnauthorized`.
1315
1488
  *
@@ -1323,28 +1496,149 @@ const kitRequireConfirmingGuard = () => {
1323
1496
  * ```
1324
1497
  */
1325
1498
  const kitRequireAuthorizedGuard = (_route, state) => {
1326
- const { authState, onAuthorized, onUnauthenticated, redirects } = inject(KIT_AUTH_CONFIG);
1499
+ const { authState, onAuthorized, onUnauthenticated, onUnavailable, isUnavailableError, redirects } = inject(KIT_AUTH_CONFIG);
1327
1500
  const router = inject(Router);
1328
1501
  const navCtrl = inject(NavController);
1329
- return authState().pipe(mergeMap(async (data) => {
1502
+ const access = inject(KitAuthAccessService);
1503
+ const lease = access.beginTransition({ suspendRemote: true });
1504
+ const redirectUnauthorized = () => {
1505
+ if (!lease.isCurrent())
1506
+ return false;
1507
+ access.clear();
1508
+ navCtrl.setDirection('root');
1509
+ router.navigate([redirects.whenUnauthorized]);
1510
+ return false;
1511
+ };
1512
+ const resolveUnavailable = async (error) => {
1513
+ try {
1514
+ const fallback = onUnavailable ? await onUnavailable(state, error, lease) : false;
1515
+ if (!lease.isCurrent())
1516
+ return false;
1517
+ if (fallback === true) {
1518
+ access.grantLocal();
1519
+ return true;
1520
+ }
1521
+ if (fallback === false)
1522
+ return redirectUnauthorized();
1523
+ access.clear();
1524
+ return fallback;
1525
+ }
1526
+ catch (fallbackError) {
1527
+ if (!lease.isCurrent())
1528
+ return false;
1529
+ access.clear();
1530
+ throw fallbackError;
1531
+ }
1532
+ };
1533
+ const resolveRemote = async (result) => {
1534
+ if (!lease.isCurrent())
1535
+ return false;
1536
+ if (isRemoteAccessActivation(result)) {
1537
+ if (!(await result.activate(lease)) || !lease.isCurrent())
1538
+ return false;
1539
+ access.grantRemote();
1540
+ const remoteRevision = access.revision;
1541
+ try {
1542
+ await result.resume();
1543
+ }
1544
+ catch (error) {
1545
+ if (access.revision !== remoteRevision)
1546
+ return false;
1547
+ if (isExplicitAuthDenial(error)) {
1548
+ access.clear();
1549
+ throw error;
1550
+ }
1551
+ if (!isUnavailableError?.(error))
1552
+ throw error;
1553
+ }
1554
+ return access.revision === remoteRevision;
1555
+ }
1556
+ if (result === true)
1557
+ access.grantRemote();
1558
+ else
1559
+ access.clear();
1560
+ return result;
1561
+ };
1562
+ return authState().pipe(map((authState) => ({ authState })), catchError((error) => {
1563
+ if (!lease.isCurrent())
1564
+ return of({ authState: 'required' });
1565
+ if (isExplicitAuthDenial(error)) {
1566
+ access.clear();
1567
+ return throwError(() => error);
1568
+ }
1569
+ return isUnavailableError?.(error) ? of({ authState: 'unavailable', error }) : throwError(() => error);
1570
+ }), mergeMap(async ({ authState: data, error: authStateError }) => {
1571
+ if (!lease.isCurrent())
1572
+ return false;
1330
1573
  if (data === 'user') {
1331
1574
  // 既定は「許可」。tokenLogin / 権限確認等が必要なアプリだけ onAuthorized を渡す。
1332
- return onAuthorized ? onAuthorized(state) : true;
1575
+ if (!onAuthorized) {
1576
+ if (!lease.isCurrent())
1577
+ return false;
1578
+ access.grantRemote();
1579
+ return true;
1580
+ }
1581
+ try {
1582
+ const result = await onAuthorized(state, lease);
1583
+ if (!lease.isCurrent())
1584
+ return false;
1585
+ return await resolveRemote(result);
1586
+ }
1587
+ catch (error) {
1588
+ if (!lease.isCurrent())
1589
+ return false;
1590
+ if (isExplicitAuthDenial(error)) {
1591
+ access.clear();
1592
+ throw error;
1593
+ }
1594
+ if (!isUnavailableError?.(error))
1595
+ throw error;
1596
+ return resolveUnavailable(error);
1597
+ }
1333
1598
  }
1334
1599
  if (data === 'anonymous') {
1600
+ if (!lease.isCurrent())
1601
+ return false;
1602
+ access.grantRemote();
1335
1603
  return true;
1336
1604
  }
1605
+ if (data === 'unavailable') {
1606
+ return resolveUnavailable(authStateError);
1607
+ }
1608
+ // `required` / `confirm` are authoritative denials. Revoke a previously verified local
1609
+ // capability before an anonymous-sign-in fallback (if any) is allowed to await.
1610
+ if (!access.suspend(lease))
1611
+ return false;
1337
1612
  // 既定は false(whenUnauthorized へ)。匿名ログイン等のフォールバックが要るアプリだけ渡す。
1338
- const fallback = onUnauthenticated ? await onUnauthenticated(state) : false;
1613
+ const fallback = onUnauthenticated ? await onUnauthenticated(state, lease) : false;
1614
+ if (!lease.isCurrent())
1615
+ return false;
1339
1616
  if (fallback !== false) {
1340
- return fallback;
1617
+ return resolveRemote(fallback);
1341
1618
  }
1342
- navCtrl.setDirection('root');
1343
- router.navigate([redirects.whenUnauthorized]);
1344
- return false;
1619
+ return redirectUnauthorized();
1345
1620
  }));
1346
1621
  };
1622
+ function isRemoteAccessActivation(value) {
1623
+ return (typeof value === 'object' &&
1624
+ value !== null &&
1625
+ 'activate' in value &&
1626
+ typeof value.activate === 'function' &&
1627
+ 'resume' in value &&
1628
+ typeof value.resume === 'function');
1629
+ }
1347
1630
 
1631
+ /**
1632
+ * Marks the narrowly scoped credential-exchange request that establishes remote access.
1633
+ *
1634
+ * @remarks
1635
+ * When shared auth access enforcement is enabled, the application starts in `none` (or may be
1636
+ * recovering from `local`) and therefore cannot make ordinary authenticated requests. The one
1637
+ * server request that verifies the current provider credential must set this context token. It
1638
+ * still runs the complete header, retry, denial, and error pipeline; only the pre-existing
1639
+ * `remote` access requirement is deferred until that exchange succeeds.
1640
+ */
1641
+ const KIT_AUTH_BOOTSTRAP_REQUEST = new HttpContextToken(() => false);
1348
1642
  /**
1349
1643
  * HTTP methods that are safe to retry automatically.
1350
1644
  *
@@ -1498,7 +1792,8 @@ const dispatchError = (config, req, error) => {
1498
1792
  * `Idempotency-Key`), and the status is a {@link RETRYABLE_STATUSES | transient status}. The
1499
1793
  * backoff is `retryCount * 500ms` plus up to 250ms of jitter, or the server's `Retry-After`.
1500
1794
  * When the device is offline it stops retrying immediately.
1501
- * 5. On the final error, `offlineFallback` is consulted first; otherwise the error is classified by
1795
+ * 5. On the final error, enforced 401/403 revokes shared access and is rejected before fallback.
1796
+ * For every other error, `offlineFallback` is consulted first; otherwise the error is classified by
1502
1797
  * status (see {@link dispatchError}): `401`→`onUnauthorized`, `403`→`onForbidden`, `0`→
1503
1798
  * `onNetworkError` (when connected), `429`→`onRateLimited`, maintenance `503`→`onMaintenance`,
1504
1799
  * other `502`/`503`/`504`→`onServerBusy`, and `400`/`422`/`500` with a body message→`onServerError`.
@@ -1514,11 +1809,31 @@ const dispatchError = (config, req, error) => {
1514
1809
  */
1515
1810
  const kitAuthInterceptor = (request, next) => {
1516
1811
  const config = inject(KIT_HTTP_CONFIG);
1812
+ const access = inject(KitAuthAccessService);
1813
+ const isAuthBootstrap = request.context.get(KIT_AUTH_BOOTSTRAP_REQUEST);
1517
1814
  if (config.bypass?.(request)) {
1518
1815
  return next(request);
1519
1816
  }
1817
+ if (config.enforceAuthAccessMode && access.mode !== 'remote' && !isAuthBootstrap) {
1818
+ const error = new HttpErrorResponse({
1819
+ // `local` deliberately looks like a transport failure so an outer offline read interceptor
1820
+ // may resolve it. `none` must not use status 0, otherwise that interceptor could expose a
1821
+ // persisted replica before authentication.
1822
+ status: access.mode === 'local' ? 0 : 401,
1823
+ statusText: access.mode === 'local' ? 'Local access only' : 'Authentication required',
1824
+ url: request.url,
1825
+ });
1826
+ if (access.mode === 'local') {
1827
+ const fallback = config.offlineFallback?.(request, error);
1828
+ if (fallback)
1829
+ return fallback;
1830
+ }
1831
+ return throwError(() => error);
1832
+ }
1520
1833
  return from(Promise.resolve(config.getAuthHeaders(request))).pipe(catchError((headerError) => {
1521
1834
  // getAuthHeaders failed → the request is never sent; classify it instead of failing silently.
1835
+ if (config.enforceAuthAccessMode && isExplicitAuthDenial(headerError))
1836
+ access.clear();
1522
1837
  config.onAuthError?.(request, headerError);
1523
1838
  return throwError(() => headerError);
1524
1839
  }), mergeMap((authHeaders) => {
@@ -1556,9 +1871,16 @@ const kitAuthInterceptor = (request, next) => {
1556
1871
  config.onResponse?.(event);
1557
1872
  }
1558
1873
  }), catchError((error) => {
1559
- const fallback = config.offlineFallback?.(req, error);
1560
- if (fallback) {
1561
- return fallback;
1874
+ if (config.enforceAuthAccessMode && isExplicitAuthDenial(error)) {
1875
+ access.clear();
1876
+ dispatchError(config, req, error);
1877
+ return throwError(() => error);
1878
+ }
1879
+ if (!isAuthBootstrap) {
1880
+ const fallback = config.offlineFallback?.(req, error);
1881
+ if (fallback) {
1882
+ return fallback;
1883
+ }
1562
1884
  }
1563
1885
  dispatchError(config, req, error);
1564
1886
  return throwError(() => error);
@@ -1620,7 +1942,26 @@ class KitRealtimeLivenessWatchdog {
1620
1942
  * target-scoped reconnect, and a resync signal after connectivity is restored.
1621
1943
  */
1622
1944
  class KitRealtimeConnection {
1623
- constructor() {
1945
+ #events$;
1946
+ #reconnected$;
1947
+ #sockets;
1948
+ #health;
1949
+ #targets;
1950
+ #opening;
1951
+ #generation;
1952
+ #reconnectTimer;
1953
+ #reconnectPendingGeneration;
1954
+ #pingTimer;
1955
+ #reconnectAttempt;
1956
+ #isAppActive;
1957
+ #isNetworkConnected;
1958
+ #lifecycleRegistration;
1959
+ #lifecycleGeneration;
1960
+ #accessSubscription;
1961
+ // Constructor injection keeps direct `new` compatibility for existing subclasses and tests.
1962
+ // eslint-disable-next-line @angular-eslint/prefer-inject
1963
+ constructor(authAccess = null) {
1964
+ this.authAccess = authAccess;
1624
1965
  this.#events$ = new Subject();
1625
1966
  this.#reconnected$ = new Subject();
1626
1967
  /** Client ID used to classify self echoes. */
@@ -1638,26 +1979,12 @@ class KitRealtimeConnection {
1638
1979
  this.#isNetworkConnected = true;
1639
1980
  this.#lifecycleRegistration = null;
1640
1981
  this.#lifecycleGeneration = 0;
1982
+ this.#accessSubscription = null;
1641
1983
  /** All parsed events received by this connection. */
1642
1984
  this.events$ = this.#events$.asObservable();
1643
1985
  /** Emits after every fully established connection cycle, including the first, prompting a REST resync. */
1644
1986
  this.reconnected$ = this.#reconnected$.asObservable();
1645
1987
  }
1646
- #events$;
1647
- #reconnected$;
1648
- #sockets;
1649
- #health;
1650
- #targets;
1651
- #opening;
1652
- #generation;
1653
- #reconnectTimer;
1654
- #reconnectPendingGeneration;
1655
- #pingTimer;
1656
- #reconnectAttempt;
1657
- #isAppActive;
1658
- #isNetworkConnected;
1659
- #lifecycleRegistration;
1660
- #lifecycleGeneration;
1661
1988
  /** Override timing/protocol defaults in specialized clients or tests. */
1662
1989
  get realtimeOptions() {
1663
1990
  return {};
@@ -1672,6 +1999,7 @@ class KitRealtimeConnection {
1672
1999
  openTimeoutMs: options.openTimeoutMs ?? 15_000,
1673
2000
  pingIntervalMs: options.pingIntervalMs ?? 30_000,
1674
2001
  livenessTimeoutMs: options.livenessTimeoutMs ?? 70_000,
2002
+ requireRemoteAccess: options.requireRemoteAccess ?? false,
1675
2003
  };
1676
2004
  }
1677
2005
  /** Client ID used to classify self echoes. */
@@ -1690,7 +2018,8 @@ class KitRealtimeConnection {
1690
2018
  [...this.#health.values()].every(({ lastActivityAt }) => Date.now() - lastActivityAt < this.#options.livenessTimeoutMs));
1691
2019
  }
1692
2020
  get #canOpen() {
1693
- return this.shouldConnect && this.#isAppActive && this.#isNetworkConnected;
2021
+ const hasRemoteAccess = !this.#options.requireRemoteAccess || (this.authAccess !== null && this.authAccess.mode === 'remote');
2022
+ return this.shouldConnect && this.#isAppActive && this.#isNetworkConnected && hasRemoteAccess;
1694
2023
  }
1695
2024
  /** Hook used by authenticated clients to invalidate a token after handshake failure. */
1696
2025
  handleConnectionFailure() {
@@ -1776,6 +2105,7 @@ class KitRealtimeConnection {
1776
2105
  }
1777
2106
  /** Register lifecycle listeners and establish the currently requested targets. */
1778
2107
  async startConnection() {
2108
+ this.#registerAccessListener();
1779
2109
  await this.registerLifecycleListeners();
1780
2110
  if (!this.shouldConnect) {
1781
2111
  this.removeLifecycleListeners();
@@ -1788,6 +2118,8 @@ class KitRealtimeConnection {
1788
2118
  this.resetConnectionState();
1789
2119
  this.suspend();
1790
2120
  this.removeLifecycleListeners();
2121
+ this.#accessSubscription?.unsubscribe();
2122
+ this.#accessSubscription = null;
1791
2123
  }
1792
2124
  /** Rebuild targets while preserving the owning session's connection intent and listeners. */
1793
2125
  async refreshConnectionTargets() {
@@ -1884,6 +2216,18 @@ class KitRealtimeConnection {
1884
2216
  }
1885
2217
  }
1886
2218
  }
2219
+ #registerAccessListener() {
2220
+ if (!this.#options.requireRemoteAccess || !this.authAccess || this.#accessSubscription)
2221
+ return;
2222
+ this.#accessSubscription = this.authAccess.mode$.subscribe((mode) => {
2223
+ if (mode === 'remote' && this.#canOpen) {
2224
+ void this.open();
2225
+ }
2226
+ else {
2227
+ this.suspend();
2228
+ }
2229
+ });
2230
+ }
1887
2231
  #connectionFailed(generation, socket) {
1888
2232
  const health = this.#health.get(socket);
1889
2233
  if (generation !== this.#generation || !health || this.#sockets.get(health.key) !== socket) {
@@ -1992,12 +2336,14 @@ class KitRealtimeConnection {
1992
2336
  clearTimeout(this.#reconnectTimer);
1993
2337
  this.#reconnectTimer = null;
1994
2338
  }
1995
- static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: KitRealtimeConnection, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
2339
+ static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: KitRealtimeConnection, deps: [{ token: KitAuthAccessService, optional: true }], target: i0.ɵɵFactoryTarget.Injectable }); }
1996
2340
  static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: KitRealtimeConnection }); }
1997
2341
  }
1998
2342
  i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: KitRealtimeConnection, decorators: [{
1999
2343
  type: Injectable
2000
- }] });
2344
+ }], ctorParameters: () => [{ type: KitAuthAccessService, decorators: [{
2345
+ type: Optional
2346
+ }] }] });
2001
2347
 
2002
2348
  /**
2003
2349
  * Merge a newly fetched page of items into an existing list by id, keeping the result sorted.
@@ -2263,5 +2609,5 @@ function mountViewModel(host, onMount) {
2263
2609
  * Generated bundle index. Do not edit.
2264
2610
  */
2265
2611
 
2266
- export { KIT_AUTH_CONFIG, KIT_HTTP_CONFIG, KIT_LAST_AUTH_EMAIL_KEY, KIT_OVERLAY_CONFIG, KIT_REALTIME_CLIENT_ID, KIT_THEME_STORAGE_KEY, KitAuthInputDirective, KitLoadingController, KitMaintenanceController, KitOverlayController, KitRealtimeConnection, KitRealtimeLivenessWatchdog, KitReloadAlertController, KitStorageService, arrayConcatById, disableHandler, isMaintenanceError, kitAuthInterceptor, kitChangeEventDisabled, kitClearStoragePreservingKeys, kitCreateDidEnter, kitForgetEmail, kitImpact, kitIsValidEmail, kitKeyboardInit, kitPresentAuthFailedAlert, kitPresentLanguageActionSheet, kitRealtimeProtocols, kitRecallEmail, kitRememberEmail, kitRequireAuthorizedGuard, kitRequireConfirmingGuard, kitRequiredUnauthorizedGuard, mountViewModel, objectEqual, provideKitAuth, provideKitHttp, provideKitOverlay, toKitWebSocketUrl };
2612
+ export { KIT_AUTH_BOOTSTRAP_REQUEST, KIT_AUTH_CONFIG, KIT_AUTH_RECOVERY_CONFIG, KIT_HTTP_CONFIG, KIT_LAST_AUTH_EMAIL_KEY, KIT_OVERLAY_CONFIG, KIT_REALTIME_CLIENT_ID, KIT_THEME_STORAGE_KEY, KitAuthAccessService, KitAuthInputDirective, KitAuthRecoveryService, KitLoadingController, KitMaintenanceController, KitOverlayController, KitRealtimeConnection, KitRealtimeLivenessWatchdog, KitReloadAlertController, KitStorageService, arrayConcatById, disableHandler, isExplicitAuthDenial, isMaintenanceError, kitAuthInterceptor, kitChangeEventDisabled, kitClearStoragePreservingKeys, kitCreateDidEnter, kitForgetEmail, kitImpact, kitIsValidEmail, kitKeyboardInit, kitPresentAuthFailedAlert, kitPresentLanguageActionSheet, kitRealtimeProtocols, kitRecallEmail, kitRememberEmail, kitRequireAuthorizedGuard, kitRequireConfirmingGuard, kitRequiredUnauthorizedGuard, mountViewModel, objectEqual, provideKitAuth, provideKitHttp, provideKitOverlay, toKitWebSocketUrl };
2267
2613
  //# sourceMappingURL=rdlabo-ionic-angular-kit.mjs.map