@spacelr/sdk 0.10.10 → 0.11.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/dist/index.d.mts CHANGED
@@ -372,6 +372,12 @@ interface UploadProgress {
372
372
  }
373
373
 
374
374
  type RefreshCallback = (refreshToken: string) => Promise<StoredTokens>;
375
+ /**
376
+ * Reasons the SDK reports a **server-confirmed** auth loss via `onAuthLost`.
377
+ * A transient refresh failure (network/transport OR a 5xx) is NOT reported
378
+ * (#759/#762).
379
+ * See the `onAuthLost` JSDoc in `client.ts` for the full contract.
380
+ */
375
381
  type AuthLostReason = 'refresh-failed' | 'unauthorized';
376
382
  type TokenRefreshedListener = (tokens: StoredTokens) => void;
377
383
  type AuthLostListener = (reason: AuthLostReason) => void;
@@ -384,6 +390,7 @@ declare class TokenManager {
384
390
  private tokenRefreshedListeners;
385
391
  private authLostListeners;
386
392
  private authLostEmitted;
393
+ private pendingClear;
387
394
  constructor(storage?: TokenStorage, refreshBufferSeconds?: number, refreshLockName?: string);
388
395
  setRefreshCallback(callback: RefreshCallback): void;
389
396
  getAccessToken(): Promise<string | null>;
@@ -398,9 +405,52 @@ declare class TokenManager {
398
405
  * rather than an exception that would get wrapped as a network error.
399
406
  */
400
407
  forceRefresh(): Promise<string | null>;
408
+ /**
409
+ * Whether the stored session currently carries a refresh token. Used by the
410
+ * 401-recovery path to decide whether a refresh was even possible, so it can
411
+ * let `doRefresh` own the auth-loss classification instead of second-guessing
412
+ * it. A rejecting storage backend reads as "no refresh token".
413
+ */
414
+ hasRefreshToken(): Promise<boolean>;
401
415
  onTokenRefreshed(listener: TokenRefreshedListener): () => void;
402
416
  onAuthLost(listener: AuthLostListener): () => void;
403
417
  emitAuthLost(reason: AuthLostReason): void;
418
+ private dispatchAuthLost;
419
+ /**
420
+ * Handle a server-confirmed auth loss: drop the dead session, THEN notify.
421
+ *
422
+ * The stored tokens are cleared **before** listeners run (#759) so that a
423
+ * reload lands on the login screen and `hasStoredSession()` reads false — and,
424
+ * critically, so a listener that re-logs-in via `setTokens()` (synchronously
425
+ * OR after an await) writes its new session strictly AFTER the clear and can
426
+ * never be erased by it. The clear is a storage-only wipe: we do NOT reset
427
+ * `authLostEmitted` (as `clearTokens()` would), so the emit stays deduped for
428
+ * this lost session. A rejecting storage backend is swallowed — best-effort,
429
+ * the consumer is routed to logout regardless. `refreshPromise` is left to
430
+ * `doRefresh`'s own `finally`; nulling it here could clobber a newer in-flight
431
+ * refresh.
432
+ *
433
+ * The token-clearing auth-loss path. Called from `doRefresh` (single-flighted
434
+ * via `refreshPromise`) on a server-confirmed refresh rejection, and from
435
+ * `HttpClient` only when a 401 could not be refreshed AND no refresh was even
436
+ * attempted (no refresh token) — these are mutually exclusive, so there is
437
+ * exactly one clear per loss and it runs BEFORE any listener. A re-login a
438
+ * listener performs is therefore never erased.
439
+ */
440
+ notifyAuthLost(reason: AuthLostReason): Promise<void>;
441
+ /**
442
+ * A refresh failure that is transient (retryable), not a server-confirmed auth
443
+ * loss — so it must NOT eject a local-first app; the next request retries.
444
+ * Covers:
445
+ * - a transport failure (offline, tunnel, captive portal, unreachable
446
+ * gateway) surfaced as `SpacelrNetworkError`/`SpacelrTimeoutError` (#759);
447
+ * - a 5xx server response — e.g. a 503 the gateway returns when oauth-service
448
+ * is momentarily down (#760/#762) — which is retryable infrastructure, not
449
+ * a token rejection.
450
+ * A real auth rejection (401/invalid_grant) or any other non-5xx server error
451
+ * is NOT transient and is treated as a server-confirmed loss.
452
+ */
453
+ private isTransientTransportError;
404
454
  private isTokenExpired;
405
455
  private shouldRefresh;
406
456
  private tryRefresh;
@@ -454,8 +504,16 @@ declare class HttpClient {
454
504
  * caller should retry with a refreshed token. 403 is never routed here —
455
505
  * it means "forbidden for this action" and must not trigger logout.
456
506
  *
457
- * `emitAuthLost('unauthorized')` is deduped inside TokenManager, so it's a
458
- * no-op if `executeRefresh` already emitted 'refresh-failed'.
507
+ * Auth-loss ownership (#759 review):
508
+ * - When a refresh WAS possible (a refresh token existed), `doRefresh` owns
509
+ * the outcome: it clears + emits on a server-confirmed rejection, and stays
510
+ * silent on a transient transport failure. We must not second-guess it, so
511
+ * we do NOT emit here — that avoids a double clear/emit and stops a transient
512
+ * blip during a 401 retry from ejecting the user.
513
+ * - When no refresh was possible (no refresh token), this 401 IS the confirmed
514
+ * loss and we own it: `notifyAuthLost` clears the dead session then emits.
515
+ * The single clear always runs before any listener, so a listener that
516
+ * re-logs-in via `setTokens()` can never have its fresh session erased.
459
517
  */
460
518
  private recoverFromAuthFailure;
461
519
  private uploadFormOnce;
@@ -566,6 +624,17 @@ interface DatabaseChangeEvent {
566
624
  * for pubsub-mode events. Used by function triggers as an idempotency key.
567
625
  */
568
626
  eventId?: string;
627
+ /**
628
+ * Actual-BSON-type sidecar (#725). Envelope-only. Consumed by the typed
629
+ * `where` matcher in a later release; carried here so older matchers ignore
630
+ * it harmlessly. Kept in sync with @spacelr-workspace/shared-types.
631
+ */
632
+ __t?: {
633
+ fields?: Record<string, 'date' | 'objectId' | {
634
+ array: Array<'date' | 'objectId' | 'other'>;
635
+ }>;
636
+ incomplete?: true;
637
+ };
569
638
  }
570
639
  interface RealtimeConfig {
571
640
  baseUrl: string;
@@ -1922,16 +1991,35 @@ interface SpacelrClient {
1922
1991
  /** Disconnect realtime WebSocket (if connected) */
1923
1992
  disconnect(): void;
1924
1993
  /**
1925
- * Subscribe to auth loss. Fires in three situations:
1994
+ * Subscribe to a **server-confirmed** auth loss — a genuine, durable session
1995
+ * invalidation (refresh token revoked/expired, or a 401 that no refresh could
1996
+ * recover). Fires in two situations:
1926
1997
  * - `'refresh-failed'` — a refresh call was rejected by the server
1927
1998
  * (refresh token revoked or expired). Note: this can also fire from a
1928
1999
  * *background* refresh triggered inside the expiry buffer window, at
1929
2000
  * which point the current access token may still be valid for up to
1930
2001
  * `refreshBufferSeconds` (default 60). Treat the session as over anyway;
1931
2002
  * the refresh token is dead.
1932
- * - `'unauthorized'` — an authenticated request came back 401 and no
1933
- * fresh token could be produced (no refresh token, or the retry after
1934
- * a successful refresh was itself 401).
2003
+ * - `'unauthorized'` — an authenticated request came back 401 and the
2004
+ * session genuinely cannot be recovered: there was no refresh token to
2005
+ * try, or the retry after a successful refresh was itself 401. A 401 whose
2006
+ * refresh merely failed *transiently* (network) does NOT fire this — see
2007
+ * below.
2008
+ *
2009
+ * A **transient refresh failure does NOT fire this** — the SDK keeps the
2010
+ * session and the next request retries. That covers a network/transport
2011
+ * failure (offline, tunnel, captive portal, unreachable gateway; #759) AND a
2012
+ * **5xx** server response, e.g. a `503` the gateway returns while
2013
+ * oauth-service is momentarily down (#760/#762). This lets a local-first app
2014
+ * stay signed in through an outage instead of ejecting the user. Only a
2015
+ * server-confirmed rejection (a 401/invalid_grant, or another non-5xx server
2016
+ * error) fires.
2017
+ *
2018
+ * On a confirmed loss the SDK **clears the stored tokens itself**, so
2019
+ * `hasStoredSession()` reads `false` afterwards and a reload lands on the
2020
+ * login screen — you no longer need to call `clearTokens()` from the handler.
2021
+ * A `setTokens()` issued while that wipe is in flight (e.g. an external
2022
+ * re-login racing the loss) is applied **after** the wipe and is never lost.
1935
2023
  *
1936
2024
  * Typical consumer reaction: clear UI state and show the login screen.
1937
2025
  * The event is deduped until `setTokens`/`clearTokens` is called again.
package/dist/index.d.ts CHANGED
@@ -372,6 +372,12 @@ interface UploadProgress {
372
372
  }
373
373
 
374
374
  type RefreshCallback = (refreshToken: string) => Promise<StoredTokens>;
375
+ /**
376
+ * Reasons the SDK reports a **server-confirmed** auth loss via `onAuthLost`.
377
+ * A transient refresh failure (network/transport OR a 5xx) is NOT reported
378
+ * (#759/#762).
379
+ * See the `onAuthLost` JSDoc in `client.ts` for the full contract.
380
+ */
375
381
  type AuthLostReason = 'refresh-failed' | 'unauthorized';
376
382
  type TokenRefreshedListener = (tokens: StoredTokens) => void;
377
383
  type AuthLostListener = (reason: AuthLostReason) => void;
@@ -384,6 +390,7 @@ declare class TokenManager {
384
390
  private tokenRefreshedListeners;
385
391
  private authLostListeners;
386
392
  private authLostEmitted;
393
+ private pendingClear;
387
394
  constructor(storage?: TokenStorage, refreshBufferSeconds?: number, refreshLockName?: string);
388
395
  setRefreshCallback(callback: RefreshCallback): void;
389
396
  getAccessToken(): Promise<string | null>;
@@ -398,9 +405,52 @@ declare class TokenManager {
398
405
  * rather than an exception that would get wrapped as a network error.
399
406
  */
400
407
  forceRefresh(): Promise<string | null>;
408
+ /**
409
+ * Whether the stored session currently carries a refresh token. Used by the
410
+ * 401-recovery path to decide whether a refresh was even possible, so it can
411
+ * let `doRefresh` own the auth-loss classification instead of second-guessing
412
+ * it. A rejecting storage backend reads as "no refresh token".
413
+ */
414
+ hasRefreshToken(): Promise<boolean>;
401
415
  onTokenRefreshed(listener: TokenRefreshedListener): () => void;
402
416
  onAuthLost(listener: AuthLostListener): () => void;
403
417
  emitAuthLost(reason: AuthLostReason): void;
418
+ private dispatchAuthLost;
419
+ /**
420
+ * Handle a server-confirmed auth loss: drop the dead session, THEN notify.
421
+ *
422
+ * The stored tokens are cleared **before** listeners run (#759) so that a
423
+ * reload lands on the login screen and `hasStoredSession()` reads false — and,
424
+ * critically, so a listener that re-logs-in via `setTokens()` (synchronously
425
+ * OR after an await) writes its new session strictly AFTER the clear and can
426
+ * never be erased by it. The clear is a storage-only wipe: we do NOT reset
427
+ * `authLostEmitted` (as `clearTokens()` would), so the emit stays deduped for
428
+ * this lost session. A rejecting storage backend is swallowed — best-effort,
429
+ * the consumer is routed to logout regardless. `refreshPromise` is left to
430
+ * `doRefresh`'s own `finally`; nulling it here could clobber a newer in-flight
431
+ * refresh.
432
+ *
433
+ * The token-clearing auth-loss path. Called from `doRefresh` (single-flighted
434
+ * via `refreshPromise`) on a server-confirmed refresh rejection, and from
435
+ * `HttpClient` only when a 401 could not be refreshed AND no refresh was even
436
+ * attempted (no refresh token) — these are mutually exclusive, so there is
437
+ * exactly one clear per loss and it runs BEFORE any listener. A re-login a
438
+ * listener performs is therefore never erased.
439
+ */
440
+ notifyAuthLost(reason: AuthLostReason): Promise<void>;
441
+ /**
442
+ * A refresh failure that is transient (retryable), not a server-confirmed auth
443
+ * loss — so it must NOT eject a local-first app; the next request retries.
444
+ * Covers:
445
+ * - a transport failure (offline, tunnel, captive portal, unreachable
446
+ * gateway) surfaced as `SpacelrNetworkError`/`SpacelrTimeoutError` (#759);
447
+ * - a 5xx server response — e.g. a 503 the gateway returns when oauth-service
448
+ * is momentarily down (#760/#762) — which is retryable infrastructure, not
449
+ * a token rejection.
450
+ * A real auth rejection (401/invalid_grant) or any other non-5xx server error
451
+ * is NOT transient and is treated as a server-confirmed loss.
452
+ */
453
+ private isTransientTransportError;
404
454
  private isTokenExpired;
405
455
  private shouldRefresh;
406
456
  private tryRefresh;
@@ -454,8 +504,16 @@ declare class HttpClient {
454
504
  * caller should retry with a refreshed token. 403 is never routed here —
455
505
  * it means "forbidden for this action" and must not trigger logout.
456
506
  *
457
- * `emitAuthLost('unauthorized')` is deduped inside TokenManager, so it's a
458
- * no-op if `executeRefresh` already emitted 'refresh-failed'.
507
+ * Auth-loss ownership (#759 review):
508
+ * - When a refresh WAS possible (a refresh token existed), `doRefresh` owns
509
+ * the outcome: it clears + emits on a server-confirmed rejection, and stays
510
+ * silent on a transient transport failure. We must not second-guess it, so
511
+ * we do NOT emit here — that avoids a double clear/emit and stops a transient
512
+ * blip during a 401 retry from ejecting the user.
513
+ * - When no refresh was possible (no refresh token), this 401 IS the confirmed
514
+ * loss and we own it: `notifyAuthLost` clears the dead session then emits.
515
+ * The single clear always runs before any listener, so a listener that
516
+ * re-logs-in via `setTokens()` can never have its fresh session erased.
459
517
  */
460
518
  private recoverFromAuthFailure;
461
519
  private uploadFormOnce;
@@ -566,6 +624,17 @@ interface DatabaseChangeEvent {
566
624
  * for pubsub-mode events. Used by function triggers as an idempotency key.
567
625
  */
568
626
  eventId?: string;
627
+ /**
628
+ * Actual-BSON-type sidecar (#725). Envelope-only. Consumed by the typed
629
+ * `where` matcher in a later release; carried here so older matchers ignore
630
+ * it harmlessly. Kept in sync with @spacelr-workspace/shared-types.
631
+ */
632
+ __t?: {
633
+ fields?: Record<string, 'date' | 'objectId' | {
634
+ array: Array<'date' | 'objectId' | 'other'>;
635
+ }>;
636
+ incomplete?: true;
637
+ };
569
638
  }
570
639
  interface RealtimeConfig {
571
640
  baseUrl: string;
@@ -1922,16 +1991,35 @@ interface SpacelrClient {
1922
1991
  /** Disconnect realtime WebSocket (if connected) */
1923
1992
  disconnect(): void;
1924
1993
  /**
1925
- * Subscribe to auth loss. Fires in three situations:
1994
+ * Subscribe to a **server-confirmed** auth loss — a genuine, durable session
1995
+ * invalidation (refresh token revoked/expired, or a 401 that no refresh could
1996
+ * recover). Fires in two situations:
1926
1997
  * - `'refresh-failed'` — a refresh call was rejected by the server
1927
1998
  * (refresh token revoked or expired). Note: this can also fire from a
1928
1999
  * *background* refresh triggered inside the expiry buffer window, at
1929
2000
  * which point the current access token may still be valid for up to
1930
2001
  * `refreshBufferSeconds` (default 60). Treat the session as over anyway;
1931
2002
  * the refresh token is dead.
1932
- * - `'unauthorized'` — an authenticated request came back 401 and no
1933
- * fresh token could be produced (no refresh token, or the retry after
1934
- * a successful refresh was itself 401).
2003
+ * - `'unauthorized'` — an authenticated request came back 401 and the
2004
+ * session genuinely cannot be recovered: there was no refresh token to
2005
+ * try, or the retry after a successful refresh was itself 401. A 401 whose
2006
+ * refresh merely failed *transiently* (network) does NOT fire this — see
2007
+ * below.
2008
+ *
2009
+ * A **transient refresh failure does NOT fire this** — the SDK keeps the
2010
+ * session and the next request retries. That covers a network/transport
2011
+ * failure (offline, tunnel, captive portal, unreachable gateway; #759) AND a
2012
+ * **5xx** server response, e.g. a `503` the gateway returns while
2013
+ * oauth-service is momentarily down (#760/#762). This lets a local-first app
2014
+ * stay signed in through an outage instead of ejecting the user. Only a
2015
+ * server-confirmed rejection (a 401/invalid_grant, or another non-5xx server
2016
+ * error) fires.
2017
+ *
2018
+ * On a confirmed loss the SDK **clears the stored tokens itself**, so
2019
+ * `hasStoredSession()` reads `false` afterwards and a reload lands on the
2020
+ * login screen — you no longer need to call `clearTokens()` from the handler.
2021
+ * A `setTokens()` issued while that wipe is in flight (e.g. an external
2022
+ * re-login racing the loss) is applied **after** the wipe and is never lost.
1935
2023
  *
1936
2024
  * Typical consumer reaction: clear UI state and show the login screen.
1937
2025
  * The event is deduped until `setTokens`/`clearTokens` is called again.