@aglyn/tenant-feature-instance 1.8.0 → 1.9.1

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aglyn/tenant-feature-instance",
3
- "version": "1.8.0",
3
+ "version": "1.9.1",
4
4
  "license": "Apache-2.0",
5
5
  "homepage": "https://aglyn.com",
6
6
  "repository": {
@@ -25,12 +25,12 @@
25
25
  "./package.json": "./package.json"
26
26
  },
27
27
  "dependencies": {
28
- "@aglyn/aglyn": "1.8.0",
29
- "@aglyn/shared-data-enums": "1.8.0",
30
- "@aglyn/shared-ui-jsx": "1.8.0",
31
- "@aglyn/shared-util-email": "1.8.0",
32
- "@aglyn/shared-util-http": "1.8.0",
33
- "@aglyn/shared-util-timestamp": "1.8.0",
28
+ "@aglyn/aglyn": "1.9.1",
29
+ "@aglyn/shared-data-enums": "1.9.1",
30
+ "@aglyn/shared-ui-jsx": "1.9.1",
31
+ "@aglyn/shared-util-email": "1.9.1",
32
+ "@aglyn/shared-util-http": "1.9.1",
33
+ "@aglyn/shared-util-timestamp": "1.9.1",
34
34
  "@swc/helpers": "0.5.23",
35
35
  "lodash-es": "^4.18.1",
36
36
  "mobx": "^7.0.5"
@@ -200,6 +200,10 @@ export type WedgeEvidence = {
200
200
  reason: 'lease-stale';
201
201
  ownerId: string;
202
202
  ageMs: number;
203
+ }
204
+ /** The SDK's AsyncQueue has failed for good (AGL-4156). */
205
+ | {
206
+ reason: 'queue-failed';
203
207
  };
204
208
  /** The fallback this tab recorded, and why. */
205
209
  export type MemoryCacheFallback = WedgeEvidence & {
@@ -360,10 +364,22 @@ export declare function fallBackToMemoryCache(evidence: WedgeEvidence, { storage
360
364
  reload?: () => void;
361
365
  now?: () => number;
362
366
  }): void;
367
+ /** Whether `thrown` (an error, an event's message, a rejection reason) is the SDK's failed-queue assertion. */
368
+ export declare function isFirestoreQueueFailure(thrown: unknown): boolean;
369
+ /**
370
+ * Watches `target` for the failed-queue assertion, as an uncaught error or an
371
+ * unhandled rejection, and calls `fallBack` once, the first time it appears.
372
+ * Returns the function that stops watching.
373
+ */
374
+ export declare function watchFirestoreQueueFailure(fallBack: (evidence: WedgeEvidence) => void, { target, isFallbackActive, }?: {
375
+ target?: Pick<Window, 'addEventListener' | 'removeEventListener'>;
376
+ isFallbackActive?: () => boolean;
377
+ }): () => void;
363
378
  /**
364
379
  * Registers `firestore` as running the durable multi-tab cache under
365
380
  * `databaseName` (`<persistence prefix>main`). Only a registered client ever
366
- * escalates past the network cycle.
381
+ * escalates past the network cycle, and only its page is watched for a failed
382
+ * queue ({@link watchFirestoreQueueFailure}).
367
383
  */
368
384
  export declare function markMultiTabFirestore(firestore: Firestore, databaseName: string): void;
369
385
  /**
@@ -496,16 +496,92 @@ const documentVisible = ()=>typeof document === 'undefined' || document.visibili
496
496
  } catch (unused) {
497
497
  return;
498
498
  }
499
- console.warn('[firestore] The multi-tab cache is locked by another tab; reloading this tab on the memory cache (AGL-3428).', record);
499
+ console.warn(evidence.reason === 'queue-failed' ? '[firestore] The multi-tab cache failed this tab\'s Firestore client; reloading this tab on the memory cache (AGL-4156).' : '[firestore] The multi-tab cache is locked by another tab; reloading this tab on the memory cache (AGL-3428).', record);
500
500
  reload();
501
501
  }
502
+ /**
503
+ * A FIRESTORE CLIENT WHOSE QUEUE HAS FAILED, AND THE WAY OUT (AGL-4156).
504
+ *
505
+ * The SDK runs every operation on one AsyncQueue. When an operation rejects
506
+ * with an error the queue does not retry, it keeps that error and refuses
507
+ * every later operation with the assertion `Unexpected state (ID: b815)`,
508
+ * whose `CONTEXT` names the first error. Nothing restarts it: the
509
+ * client is dead until the page reloads, so every read and listener in the tab
510
+ * fails, and pages stop loading.
511
+ *
512
+ * The durable cache is what kills it in production. On 2026-11-04 (v1.9.0,
513
+ * `@firebase/firestore` 4.18.0) a new Firefox sign-up's console lost its client
514
+ * on three page loads in 25 minutes. Each time, an IndexedDB request in the
515
+ * SDK's transaction threw "Attempt to get a record from database without an
516
+ * in-progress transaction". The SDK retries a failed transaction three times,
517
+ * then hands the raw `DOMException` to the queue, which counts it as fatal
518
+ * rather than as an `IndexedDbTransactionError` to back off from. The earlier
519
+ * cases ended the same way: a full `localStorage` (AGL-2845) and a null target
520
+ * from the IndexedDB target cache (`isCorePipeline`, 2026-10-14, Chrome).
521
+ *
522
+ * So the first b815 of a durable multi-tab client moves the tab onto the
523
+ * memory cache, which does not use IndexedDB, through the same per-tab
524
+ * {@link fallBackToMemoryCache} as the wedge. Nothing that could be saved is
525
+ * lost: the dead queue had already stopped every write in the tab. A tab already
526
+ * on the fallback runs the memory cache, which is never watched, so a b815 there
527
+ * cannot loop. No lock is shared, because another tab's client is not dead.
528
+ */ const QUEUE_FAILURE = /INTERNAL ASSERTION FAILED: Unexpected state \(ID: b815\)/;
529
+ /** Whether `thrown` (an error, an event's message, a rejection reason) is the SDK's failed-queue assertion. */ export function isFirestoreQueueFailure(thrown) {
530
+ try {
531
+ const message = typeof thrown === 'string' ? thrown : thrown && typeof thrown === 'object' && 'message' in thrown ? String(thrown.message) : '';
532
+ return QUEUE_FAILURE.test(message);
533
+ } catch (unused) {
534
+ return false;
535
+ }
536
+ }
537
+ /**
538
+ * Watches `target` for the failed-queue assertion, as an uncaught error or an
539
+ * unhandled rejection, and calls `fallBack` once, the first time it appears.
540
+ * Returns the function that stops watching.
541
+ */ export function watchFirestoreQueueFailure(fallBack, { target = typeof window === 'undefined' ? undefined : window, isFallbackActive = ()=>memoryCacheFallbackActive() } = {}) {
542
+ if (!target) return ()=>undefined;
543
+ let fired = false;
544
+ const onError = (event)=>{
545
+ const { error, message } = event;
546
+ check(isFirestoreQueueFailure(error) || isFirestoreQueueFailure(message));
547
+ };
548
+ const onRejection = (event)=>{
549
+ check(isFirestoreQueueFailure(event.reason));
550
+ };
551
+ const stop = ()=>{
552
+ target.removeEventListener('error', onError);
553
+ target.removeEventListener('unhandledrejection', onRejection);
554
+ };
555
+ const check = (failed)=>{
556
+ if (!failed || fired) return;
557
+ fired = true;
558
+ stop();
559
+ try {
560
+ if (isFallbackActive()) return;
561
+ fallBack({
562
+ reason: 'queue-failed'
563
+ });
564
+ } catch (unused) {
565
+ // Watching never breaks the page.
566
+ }
567
+ };
568
+ target.addEventListener('error', onError);
569
+ target.addEventListener('unhandledrejection', onRejection);
570
+ return stop;
571
+ }
502
572
  /** The IndexedDB database of each client running the durable multi-tab cache. */ const multiTabDatabases = new WeakMap();
503
573
  /**
504
574
  * Registers `firestore` as running the durable multi-tab cache under
505
575
  * `databaseName` (`<persistence prefix>main`). Only a registered client ever
506
- * escalates past the network cycle.
576
+ * escalates past the network cycle, and only its page is watched for a failed
577
+ * queue ({@link watchFirestoreQueueFailure}).
507
578
  */ export function markMultiTabFirestore(firestore, databaseName) {
508
579
  if (firestore && typeof firestore === 'object') {
580
+ if (!multiTabDatabases.has(firestore)) {
581
+ watchFirestoreQueueFailure((evidence)=>fallBackToMemoryCache(evidence, {
582
+ databaseName
583
+ }));
584
+ }
509
585
  multiTabDatabases.set(firestore, databaseName);
510
586
  }
511
587
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../../../libs/tenant/feature/instance/src/lib/hooks/firebase/firestore-multitab-wedge.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { type Firestore } from 'firebase/firestore'\n\nimport { PRIMARY_LEASE_MAX_AGE_MS } from './firestore-tab-handoff'\n\n/**\n * A MULTI-TAB CACHE THAT ANOTHER TAB HAS LOCKED, AND THE WAY OUT (AGL-3428).\n *\n * ## The wedge the network cycle cannot clear\n *\n * `firestore-stall-recovery.ts` recovers a lapsed primary lease by cycling the\n * network, which runs the lease election at once (AGL-3373). That needs the\n * election's IndexedDB transaction to run. Measured against\n * `@firebase/firestore` 4.17.2: `IndexedDbPersistence.runTransaction` opens\n * EVERY transaction over EVERY object store (`getObjectStores(schemaVersion)`),\n * so one tab that stops partway through a readwrite transaction — frozen or\n * discarded by the browser while it runs — holds every store for every tab on\n * the origin. Behind it, in every other tab:\n *\n * - the lease election waits, so the lease row is never renewed by anyone;\n * - cache reads wait, so pages sit on their spinners;\n * - the mutation-queue write waits, so a save never reaches the network;\n * - a freshly opened tab's persistence `start()` waits, so a new tab hangs too;\n * - `disableNetwork`, `enableNetwork` and `terminate` are queued on the same\n * AsyncQueue behind the stuck operation, so none of them ever runs.\n *\n * On 2026-09-30 production (beta.218) did exactly this three times in two\n * hours: every console tab stopped, and the `owner` row named a background\n * tab that had stopped renewing it.\n *\n * ## How it is told apart from a slow read\n *\n * Only after the network cycle, and only from a visible tab on a browser that\n * reports a network. Such a tab wins a lapsed lease within one 4-second\n * election tick, and the cycle has just forced one. So, after a short settle,\n * the tab reads the `owner` row itself:\n *\n * - **the read cannot complete in time** — the store is locked by another\n * tab's open transaction. \"In time\" is {@link WEDGE_LOCK_MS}, longer than a\n * starved but living tab holds it (AGL-4135); or\n * - **the lease is older than {@link STALE_PRIMARY_LEASE_MS}** — no tab,\n * including this one, is completing an election.\n *\n * Either is the wedge. A fresh lease — this tab's or another's — is a healthy\n * cache and a merely slow server, and nothing more happens.\n *\n * ## The way out\n *\n * The tab records a {@link MemoryCacheFallback} in `sessionStorage` and\n * reloads. `firestoreCacheClassFor` reads it at startup and gives this tab the\n * memory cache, which shares nothing with other tabs, so the locked database\n * cannot reach it. `sessionStorage` is per tab: tabs already running keep the\n * durable cache, and the fallback leaves when this tab closes or after\n * {@link MEMORY_CACHE_FALLBACK_TTL_MS}.\n *\n * A reload, not an in-place swap, because nothing in place can work: the\n * wedged instance's `terminate()` is queued behind the stuck operation, a\n * second instance for the same app throws until the first is gone, and\n * hundreds of readers hold the instance from context and from closures.\n * Nothing that could be saved is lost — the wedge had already stopped every\n * write in the tab from leaving it.\n *\n * ## The tabs that open next (AGL-4090)\n *\n * Every tab used to find the lock on its own, so each NEW tab spent the whole\n * path above — the 8 s stall, the cycle's two 5 s steps, the settle, the 4 s\n * read, the reload — on an empty page: about half a minute, per tab. So a tab\n * whose read found the store LOCKED also leaves a {@link SharedCacheLock} in\n * `localStorage`, and `firestoreCacheClassFor` starts every tab that opens\n * while it is fresh on the memory cache at once: no stall, no reload.\n *\n * - **Only a lock is shared.** A locked store hangs every tab that opens the\n * database, a new one included. A stale lease does not: no transaction\n * holds the store, and a freshly started tab wins a lapsed lease at its\n * first election (AGL-3373). That fallback stays per tab.\n * - **Each tab that starts from it reads the lease again**, read-only, once\n * ({@link confirmSharedCacheLock}). Still locked, it re-stamps the record;\n * anything else clears it, so the first tab after the lock lifts is the\n * last one moved. The record lasts as long as the lock while tabs keep\n * opening, and {@link SHARED_CACHE_LOCK_TTL_MS} past the last tab that saw it.\n * - **Nothing here writes to IndexedDB or touches the lease.** A tab on the\n * memory cache takes no part in the multi-tab protocol, so it can never be\n * a second primary over the shared cache (AGL-3788).\n *\n * The cost is the memory cache's, and it is why the fallback was per tab: a\n * write made offline in such a tab is lost if the tab closes first, and the\n * tab shares no cache with the others. But while the store is locked, the\n * durable cache in a new tab can do none of that either: its persistence\n * never starts, so it reads nothing and no write leaves it. The cost is real\n * only for a record that has outlived its lock, and the re-read clears that\n * at the first tab that starts from it.\n *\n * Not chosen: a lease read at boot in every tab, in place of the record. The\n * cache is fixed when `initializeFirestore` runs, synchronously in the\n * provider's first render, and IndexedDB answers asynchronously, so a boot\n * read can shorten the wait to the read plus a reload but never skip it. It\n * would also add a read to every healthy tab's boot, and at boot the store can\n * be held for seconds for healthy reasons (the primary's LRU collection, a\n * schema upgrade) that the stall and the cycle rule out today, so it would\n * reload healthy tabs.\n */\n\n/** `sessionStorage` key of this tab's memory-cache fallback. */\nexport const MEMORY_CACHE_FALLBACK_KEY = 'aglyn:firestore-memory-cache-fallback'\n\n/**\n * How long a tab keeps the memory cache after falling back. The SDK's own\n * inactivity horizon (`MAX_CLIENT_AGE_MS`), after which a tab that is still\n * stuck no longer counts as a client; past it, a reload tries the durable\n * cache again, and falls back again if it has to.\n */\nexport const MEMORY_CACHE_FALLBACK_TTL_MS = 30 * 60 * 1000\n\n/** `localStorage` key of the lock a tab saw, for the tabs that open next (AGL-4090). */\nexport const SHARED_CACHE_LOCK_KEY = 'aglyn:firestore-shared-cache-locked'\n\n/**\n * How long a lock one tab saw starts new tabs on the memory cache, unless a\n * tab that starts from it sees the lock again. Long enough for the tabs a\n * person opens together (a page, then its preview); short, because a record\n * that outlives its lock moves every new tab, not one.\n */\nexport const SHARED_CACHE_LOCK_TTL_MS = 5 * 60 * 1000\n\n/**\n * A lease older than this, read from a visible online tab right after a\n * forced election, means no election is completing. The SDK treats a lease as\n * lapsed at 5 s (`MAX_PRIMARY_ELIGIBLE_AGE_MS`) and runs the election every\n * 4 s; this is three times the first, so an election that is merely late is\n * never mistaken for one that cannot run.\n */\nexport const STALE_PRIMARY_LEASE_MS = 15_000\n\n/**\n * How long the lease read may take before the store is judged locked. The\n * SDK's own transactions take milliseconds.\n *\n * Measured in time this tab was RUNNING, not on the wall clock (AGL-4120). While\n * the main thread is frozen, the read's answer sits unhandled in the same task\n * queue as the timeout, so a four-second freeze used to read as a locked store:\n * an `owner` read measured 3,945 ms in a freeze and 0 ms after it. On that false\n * verdict a healthy tab was reloaded, losing whatever was typed into it, and\n * every tab opened for the next five minutes started on the memory cache.\n */\nexport const LEASE_PROBE_TIMEOUT_MS = 4_000\n\n/**\n * How long the wedge check's lease read may wait before the store counts as\n * locked (AGL-4135). Five times {@link LEASE_PROBE_TIMEOUT_MS}, because a store\n * held by a tab that is slow is not a store held by a tab that is frozen.\n *\n * A starved tab (busy, slow, throttled) keeps each IndexedDB transaction open\n * until its event loop comes back between requests, and the SDK's lease\n * renewal makes several requests. Measured in production (v1.5.0, a tab busy\n * in 3 s slices): the store held every read for about 15 s, then answered with\n * a fresh lease. At 4 s that read as the wedge, and the healthy tab was reloaded\n * onto the memory cache, losing what had been typed into it. A frozen tab never\n * lets go, so the wedge still reads as locked, only later.\n */\nexport const WEDGE_LOCK_MS = 20_000\n\n/**\n * The probe's clock. A browser coalesces the ticks a frozen thread missed, so\n * counting ticks counts only the time the tab could have heard the answer.\n */\nexport const LEASE_PROBE_TICK_MS = 250\n\n/**\n * How long after the network cycle the lease is read, so the election the\n * cycle queued has run.\n */\nexport const LEASE_SETTLE_MS = 3_000\n\n/** The SDK's lease store and its single row's key (`DbPrimaryClientStore`, `DbPrimaryClientKey`). */\nconst OWNER_STORE = 'owner'\nconst OWNER_KEY = 'owner'\n\n/** What reading the lease found. */\nexport type PrimaryLeaseProbe =\n /** The read did not complete in time: another tab's transaction holds the store. */\n | { state: 'locked' }\n /** The lease row: who holds it and how long ago it was renewed. */\n | { state: 'leased'; ownerId: string; ageMs: number }\n /** There is no lease row. */\n | { state: 'vacant' }\n /** The lease could not be read: no IndexedDB, no database, no store, an error. */\n | { state: 'unknown' }\n\n/** Why a tab concluded the multi-tab cache is wedged. */\nexport type WedgeEvidence =\n | { reason: 'lease-locked' }\n | { reason: 'lease-stale'; ownerId: string; ageMs: number }\n\n/** The fallback this tab recorded, and why. */\nexport type MemoryCacheFallback = WedgeEvidence & { at: number }\n\n/** A lock one tab saw, recorded for the tabs that open next (AGL-4090). */\nexport interface SharedCacheLock {\n reason: 'lease-locked'\n /** The database whose store was locked: `<persistence prefix>main`. */\n databaseName: string\n /** When a tab last saw it locked. */\n at: number\n}\n\n/** What a tab that started from a {@link SharedCacheLock} found when it read the lease again. */\nexport type SharedCacheLockCheck =\n /** There was no fresh record for this database: nothing was read. */\n | 'absent'\n /** The store is still locked; the record was re-stamped. */\n | 'still-locked'\n /** The store answered; the record is gone, so the next tab gets the durable cache. */\n | 'cleared'\n /** Storage could not be read or written; the record is left to expire. */\n | 'failed'\n\n/**\n * Reads the SDK's `owner` row from `databaseName`.\n *\n * Opens only a database that already exists, at whatever version it has (the\n * same rule as `readHeartbeatClientIds`): `open(name)` on a missing database\n * would create it at version 1 under the SDK. The connection serves one\n * read-only request and is closed — also on `versionchange`, so it never\n * holds up the SDK's own upgrade, and also when the read lands after the\n * timeout.\n */\nexport async function probePrimaryLease(\n factory: IDBFactory | undefined,\n databaseName: string,\n {\n timeoutMs = LEASE_PROBE_TIMEOUT_MS,\n now = Date.now,\n }: { timeoutMs?: number; now?: () => number } = {},\n): Promise<PrimaryLeaseProbe> {\n if (!factory || typeof factory.databases !== 'function') return { state: 'unknown' }\n try {\n const databases = await factory.databases()\n if (!databases.some((database) => database.name === databaseName)) {\n return { state: 'unknown' }\n }\n } catch {\n return { state: 'unknown' }\n }\n\n return new Promise((resolve) => {\n let settled = false\n let database: IDBDatabase | undefined\n const settle = (probe: PrimaryLeaseProbe) => {\n if (settled) return\n settled = true\n clearInterval(clock)\n resolve(probe)\n }\n const close = () => {\n try {\n database?.close()\n } catch {\n // Already closed.\n }\n }\n // Only a lock can hold a read-only request this long; the connection is\n // closed when the request finally lands.\n const tickMs = Math.min(LEASE_PROBE_TICK_MS, timeoutMs)\n let ticks = Math.ceil(timeoutMs / tickMs)\n const clock = setInterval(() => {\n ticks -= 1\n if (ticks <= 0) settle({ state: 'locked' })\n }, tickMs)\n\n let request: IDBOpenDBRequest\n try {\n request = factory.open(databaseName)\n } catch {\n settle({ state: 'unknown' })\n return\n }\n // The database was deleted between `databases()` and `open()`: abort the\n // creation rather than leave the SDK an empty version-1 database.\n request.onupgradeneeded = () => request.transaction?.abort()\n request.onerror = () => settle({ state: 'unknown' })\n request.onsuccess = () => {\n database = request.result\n database.onversionchange = close\n if (settled || !database.objectStoreNames.contains(OWNER_STORE)) {\n close()\n settle({ state: 'unknown' })\n return\n }\n try {\n const read = database\n .transaction(OWNER_STORE, 'readonly')\n .objectStore(OWNER_STORE)\n .get(OWNER_KEY)\n read.onsuccess = () => {\n close()\n const row = read.result as\n | { ownerId?: unknown; leaseTimestampMs?: unknown }\n | undefined\n if (\n !row ||\n typeof row.ownerId !== 'string' ||\n typeof row.leaseTimestampMs !== 'number'\n ) {\n settle({ state: 'vacant' })\n return\n }\n settle({\n state: 'leased',\n ownerId: row.ownerId,\n ageMs: now() - row.leaseTimestampMs,\n })\n }\n read.onerror = () => {\n close()\n settle({ state: 'unknown' })\n }\n } catch {\n close()\n settle({ state: 'unknown' })\n }\n }\n })\n}\n\n/**\n * How long the lease read may take before a quiet client counts as WAITING on\n * the store (AGL-4135). Shorter than {@link LEASE_PROBE_TIMEOUT_MS}, which\n * decides a wedge: this asks only whether something holds the store now. The\n * SDK's own transactions take milliseconds, so a read that waits a second has\n * waited on one, from another tab or from this client's own backlog.\n */\nexport const LEASE_PROMPT_READ_MS = 1_000\n\n/** What the shared cache says about a client that has gone quiet (AGL-4135). */\nexport type LeaseCheck =\n /**\n * The store did not answer promptly. A transaction holds it, and every call\n * this client makes is queued behind that transaction.\n */\n | { state: 'waiting' }\n /** Another tab holds a live lease and serves this client through it. */\n | { state: 'served'; ownerId: string }\n /**\n * Nothing here explains the quiet. This tab holds the lease, or the lease has\n * lapsed or is vacant, or the lease could not be read or attributed.\n */\n | { state: 'silent' }\n\n/**\n * Reads a prompt lease probe for a quiet client whose own id is `selfId`.\n * Pure. A lease is live while younger than the SDK's 5 s\n * (`MAX_PRIMARY_ELIGIBLE_AGE_MS`). Without `selfId` a live lease cannot be told\n * apart from this tab's own, so it reads as `silent`, which is what every stall\n * was read as before.\n */\nexport function leaseCheckFrom(\n probe: PrimaryLeaseProbe,\n selfId: string | undefined,\n): LeaseCheck {\n if (probe.state === 'locked') return { state: 'waiting' }\n if (\n probe.state === 'leased' &&\n selfId !== undefined &&\n probe.ownerId !== selfId &&\n probe.ageMs < PRIMARY_LEASE_MAX_AGE_MS\n ) {\n return { state: 'served', ownerId: probe.ownerId }\n }\n return { state: 'silent' }\n}\n\n/**\n * This tab's id in the multi-tab protocol: the id its `clientMetadata` row is\n * written under, and any lease it holds. Read from the SDK's client\n * (`Firestore._firestoreClient.clientId`, which is internal and set once the\n * client has started). `undefined` when it is not there. Read in production\n * (4.17.2) against the `clientMetadata` row the same tab wrote.\n */\nexport function firestoreClientId(firestore: Firestore): string | undefined {\n try {\n const client = (firestore as unknown as {\n _firestoreClient?: { clientId?: unknown }\n })._firestoreClient\n const id = client?.clientId\n return typeof id === 'string' && id.length > 0 ? id : undefined\n } catch {\n return undefined\n }\n}\n\n/**\n * Whether a lease read taken right after a forced election, from a visible\n * online tab, shows the wedge. Anything that could be a healthy cache —\n * a fresh lease, no lease row, an unreadable one — is not evidence.\n */\nexport function wedgeEvidenceFrom(\n probe: PrimaryLeaseProbe,\n staleMs = STALE_PRIMARY_LEASE_MS,\n): WedgeEvidence | undefined {\n if (probe.state === 'locked') return { reason: 'lease-locked' }\n if (probe.state === 'leased' && probe.ageMs >= staleMs) {\n return { reason: 'lease-stale', ownerId: probe.ownerId, ageMs: probe.ageMs }\n }\n return undefined\n}\n\n/**\n * The object stored under `key`, when it parses and its `at` is within\n * `ttlMs` of `now` and not ahead of it.\n */\nfunction readStampedRecord(\n storage: Pick<Storage, 'getItem'> | undefined,\n key: string,\n now: number,\n ttlMs: number,\n): ({ at: number } & Record<string, unknown>) | undefined {\n let raw: string | null\n try {\n raw = storage?.getItem(key) ?? null\n } catch {\n return undefined\n }\n if (raw === null) return undefined\n let parsed: unknown\n try {\n parsed = JSON.parse(raw)\n } catch {\n return undefined\n }\n if (typeof parsed !== 'object' || parsed === null) return undefined\n const record = parsed as { at?: unknown } & Record<string, unknown>\n if (typeof record.at !== 'number' || !Number.isFinite(record.at)) return undefined\n if (now - record.at >= ttlMs || record.at > now) return undefined\n return record as { at: number } & Record<string, unknown>\n}\n\n/**\n * This tab's fallback, or `undefined` when there is none, it has expired, or\n * it does not parse.\n */\nexport function readMemoryCacheFallback(\n storage: Pick<Storage, 'getItem'> | undefined,\n now: number,\n ttlMs = MEMORY_CACHE_FALLBACK_TTL_MS,\n): MemoryCacheFallback | undefined {\n return readStampedRecord(storage, MEMORY_CACHE_FALLBACK_KEY, now, ttlMs) as\n | MemoryCacheFallback\n | undefined\n}\n\n/**\n * The lock a tab saw on `databaseName`, or `undefined` when there is none, it\n * names another database, it has expired, or it does not parse.\n */\nexport function readSharedCacheLock(\n storage: Pick<Storage, 'getItem'> | undefined,\n databaseName: string | undefined,\n now: number,\n ttlMs = SHARED_CACHE_LOCK_TTL_MS,\n): SharedCacheLock | undefined {\n if (databaseName === undefined) return undefined\n const record = readStampedRecord(storage, SHARED_CACHE_LOCK_KEY, now, ttlMs)\n if (record?.reason !== 'lease-locked' || record.databaseName !== databaseName) {\n return undefined\n }\n return record as unknown as SharedCacheLock\n}\n\nconst browserSessionStorage = (): Storage | undefined => {\n try {\n return typeof window === 'undefined' ? undefined : window.sessionStorage\n } catch {\n // Site data blocked: reading `window.sessionStorage` throws.\n return undefined\n }\n}\n\nconst browserLocalStorage = (): Storage | undefined => {\n try {\n return typeof window === 'undefined' ? undefined : window.localStorage\n } catch {\n // Site data blocked: reading `window.localStorage` throws.\n return undefined\n }\n}\n\nconst browserIndexedDb = (): IDBFactory | undefined => {\n try {\n return typeof window === 'undefined' ? undefined : window.indexedDB\n } catch {\n return undefined\n }\n}\n\n/** Whether this browser tab is running on its memory-cache fallback. */\nexport function memoryCacheFallbackActive(now = Date.now()): boolean {\n return readMemoryCacheFallback(browserSessionStorage(), now) !== undefined\n}\n\n/**\n * Whether another tab has just seen the store of `databaseName` locked, so\n * this tab should start on the memory cache rather than wait to find out.\n */\nexport function sharedCacheLockActive(\n databaseName: string | undefined,\n now = Date.now(),\n): boolean {\n return readSharedCacheLock(browserLocalStorage(), databaseName, now) !== undefined\n}\n\n/**\n * Records, for the tabs that open next, that the store of `databaseName` is\n * locked now. Never throws: without the record, the next tab finds the lock\n * itself, as it always has.\n */\nexport function recordSharedCacheLock(\n databaseName: string,\n {\n storage = browserLocalStorage(),\n now = Date.now,\n }: { storage?: Pick<Storage, 'setItem'>; now?: () => number } = {},\n): void {\n const record: SharedCacheLock = { reason: 'lease-locked', databaseName, at: now() }\n try {\n storage?.setItem(SHARED_CACHE_LOCK_KEY, JSON.stringify(record))\n } catch {\n // Full or blocked.\n }\n}\n\n/**\n * Run once by a tab that started on the memory cache: reads the lease of\n * `databaseName` again and keeps another tab's lock record only while the\n * store is still locked. Never creates a record and never rejects.\n */\nexport async function confirmSharedCacheLock(\n databaseName: string,\n {\n probe = () => probePrimaryLease(browserIndexedDb(), databaseName),\n storage = browserLocalStorage(),\n now = Date.now,\n }: {\n probe?: () => Promise<PrimaryLeaseProbe>\n storage?: Pick<Storage, 'getItem' | 'setItem' | 'removeItem'>\n now?: () => number\n } = {},\n): Promise<SharedCacheLockCheck> {\n if (!storage) return 'absent'\n const seen = readSharedCacheLock(storage, databaseName, now())\n if (!seen) return 'absent'\n try {\n if ((await probe()).state === 'locked') {\n recordSharedCacheLock(databaseName, { storage, now })\n return 'still-locked'\n }\n const current = readSharedCacheLock(storage, databaseName, now())\n // Another tab saw the lock again while this read ran; its record is\n // newer than this read, so it stands.\n if (current && current.at !== seen.at) return 'still-locked'\n if (current) storage.removeItem(SHARED_CACHE_LOCK_KEY)\n return 'cleared'\n } catch {\n return 'failed'\n }\n}\n\nexport interface WedgeEscalationDeps {\n /** Reads the lease. */\n probe: () => Promise<PrimaryLeaseProbe>\n /** Moves this tab off the shared cache. */\n fallBack: (evidence: WedgeEvidence) => void\n /** Whether this tab is already on the fallback — it then never escalates. */\n isFallbackActive?: () => boolean\n isOnline?: () => boolean\n isVisible?: () => boolean\n /** Waits `ms`; the settle before the lease read. */\n wait?: (ms: number) => Promise<void>\n settleMs?: number\n}\n\nconst browserOnline = () =>\n typeof navigator === 'undefined' || navigator.onLine !== false\n\nconst documentVisible = () =>\n typeof document === 'undefined' || document.visibilityState !== 'hidden'\n\n/**\n * The step `createStallRecovery` runs after its network cycle for a\n * multi-tab client. Resolves `true` when it has moved the tab to the fallback.\n * Never rejects.\n */\nexport function createWedgeEscalation(\n deps: WedgeEscalationDeps,\n): () => Promise<boolean> {\n const {\n probe,\n fallBack,\n isFallbackActive = () => memoryCacheFallbackActive(),\n isOnline = browserOnline,\n isVisible = documentVisible,\n wait = (ms) => new Promise<void>((resolve) => setTimeout(resolve, ms)),\n settleMs = LEASE_SETTLE_MS,\n } = deps\n return async () => {\n try {\n if (isFallbackActive()) return false\n await wait(settleMs)\n // Both guards again: the reader may have gone, or the network with it.\n if (!isOnline() || !isVisible()) return false\n const evidence = wedgeEvidenceFrom(await probe())\n if (!evidence) return false\n fallBack(evidence)\n return true\n } catch {\n return false\n }\n }\n}\n\n/**\n * Records the fallback for this tab and reloads it onto the memory cache.\n * When the record cannot be written it does not reload: without it, the\n * reloaded tab would open the same locked database and hang again.\n *\n * A lock is also recorded for the tabs that open next (AGL-4090), first and\n * whatever happens to this tab's own record: they would hang on it too.\n */\nexport function fallBackToMemoryCache(\n evidence: WedgeEvidence,\n {\n storage = browserSessionStorage(),\n sharedStorage = browserLocalStorage(),\n databaseName,\n reload = () => window.location.reload(),\n now = Date.now,\n }: {\n storage?: Pick<Storage, 'setItem'>\n /** Where the tabs that open next look for a lock this tab saw. */\n sharedStorage?: Pick<Storage, 'setItem'>\n /** The locked database. Without it, nothing is shared. */\n databaseName?: string\n reload?: () => void\n now?: () => number\n } = {},\n): void {\n if (evidence.reason === 'lease-locked' && databaseName !== undefined) {\n recordSharedCacheLock(databaseName, { storage: sharedStorage, now })\n }\n if (!storage) return\n const record: MemoryCacheFallback = { ...evidence, at: now() }\n try {\n storage.setItem(MEMORY_CACHE_FALLBACK_KEY, JSON.stringify(record))\n } catch {\n return\n }\n console.warn(\n '[firestore] The multi-tab cache is locked by another tab; reloading this tab on the memory cache (AGL-3428).',\n record,\n )\n reload()\n}\n\n/** The IndexedDB database of each client running the durable multi-tab cache. */\nconst multiTabDatabases = new WeakMap<Firestore, string>()\n\n/**\n * Registers `firestore` as running the durable multi-tab cache under\n * `databaseName` (`<persistence prefix>main`). Only a registered client ever\n * escalates past the network cycle.\n */\nexport function markMultiTabFirestore(firestore: Firestore, databaseName: string): void {\n if (firestore && typeof firestore === 'object') {\n multiTabDatabases.set(firestore, databaseName)\n }\n}\n\n/**\n * The browser escalation for `firestore`, or `undefined` when it does not run\n * the durable multi-tab cache (the emulator configuration, an ephemeral\n * origin, a tab already on the fallback).\n */\nexport function browserWedgeEscalationFor(\n firestore: Firestore,\n): (() => Promise<boolean>) | undefined {\n const databaseName = multiTabDatabases.get(firestore)\n if (databaseName === undefined) return undefined\n return createWedgeEscalation({\n probe: () =>\n probePrimaryLease(browserIndexedDb(), databaseName, {\n timeoutMs: WEDGE_LOCK_MS,\n }),\n fallBack: (evidence) => fallBackToMemoryCache(evidence, { databaseName }),\n })\n}\n\n/**\n * The lease check `createStallRecovery` runs before a network cycle, or\n * `undefined` when `firestore` does not run the durable multi-tab cache: a\n * client with a cache of its own has no other tab to wait on. Never rejects.\n */\nexport function browserLeaseCheckFor(\n firestore: Firestore,\n): (() => Promise<LeaseCheck>) | undefined {\n const databaseName = multiTabDatabases.get(firestore)\n if (databaseName === undefined) return undefined\n return async () => {\n try {\n const probe = await probePrimaryLease(browserIndexedDb(), databaseName, {\n timeoutMs: LEASE_PROMPT_READ_MS,\n })\n return leaseCheckFrom(probe, firestoreClientId(firestore))\n } catch {\n return { state: 'silent' }\n }\n }\n}\n"],"names":["PRIMARY_LEASE_MAX_AGE_MS","MEMORY_CACHE_FALLBACK_KEY","MEMORY_CACHE_FALLBACK_TTL_MS","SHARED_CACHE_LOCK_KEY","SHARED_CACHE_LOCK_TTL_MS","STALE_PRIMARY_LEASE_MS","LEASE_PROBE_TIMEOUT_MS","WEDGE_LOCK_MS","LEASE_PROBE_TICK_MS","LEASE_SETTLE_MS","OWNER_STORE","OWNER_KEY","probePrimaryLease","factory","databaseName","timeoutMs","now","Date","databases","state","some","database","name","Promise","resolve","settled","settle","probe","clearInterval","clock","close","tickMs","Math","min","ticks","ceil","setInterval","request","open","onupgradeneeded","transaction","abort","onerror","onsuccess","result","onversionchange","objectStoreNames","contains","read","objectStore","get","row","ownerId","leaseTimestampMs","ageMs","LEASE_PROMPT_READ_MS","leaseCheckFrom","selfId","undefined","firestoreClientId","firestore","client","_firestoreClient","id","clientId","length","wedgeEvidenceFrom","staleMs","reason","readStampedRecord","storage","key","ttlMs","raw","getItem","parsed","JSON","parse","record","at","Number","isFinite","readMemoryCacheFallback","readSharedCacheLock","browserSessionStorage","window","sessionStorage","browserLocalStorage","localStorage","browserIndexedDb","indexedDB","memoryCacheFallbackActive","sharedCacheLockActive","recordSharedCacheLock","setItem","stringify","confirmSharedCacheLock","seen","current","removeItem","browserOnline","navigator","onLine","documentVisible","document","visibilityState","createWedgeEscalation","deps","fallBack","isFallbackActive","isOnline","isVisible","wait","ms","setTimeout","settleMs","evidence","fallBackToMemoryCache","sharedStorage","reload","location","console","warn","multiTabDatabases","WeakMap","markMultiTabFirestore","set","browserWedgeEscalationFor","browserLeaseCheckFor"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;AAID,SAASA,wBAAwB,QAAQ,6BAAyB;AAElE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA+FC,GAED,8DAA8D,GAC9D,OAAO,MAAMC,4BAA4B,wCAAuC;AAEhF;;;;;CAKC,GACD,OAAO,MAAMC,+BAA+B,KAAK,KAAK,KAAI;AAE1D,sFAAsF,GACtF,OAAO,MAAMC,wBAAwB,sCAAqC;AAE1E;;;;;CAKC,GACD,OAAO,MAAMC,2BAA2B,IAAI,KAAK,KAAI;AAErD;;;;;;CAMC,GACD,OAAO,MAAMC,yBAAyB,MAAM;AAE5C;;;;;;;;;;CAUC,GACD,OAAO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AAOA,cAAc,UAAU;QAC9C+D,kBAAkBG,GAAG,CAAClE,WAAW9C;IACnC;AACF;AAEA;;;;CAIC,GACD,OAAO,SAASiH,0BACdnE,SAAoB;IAEpB,MAAM9C,eAAe6G,kBAAkBzE,GAAG,CAACU;IAC3C,IAAI9C,iBAAiB4C,WAAW,OAAOA;IACvC,OAAOgD,sBAAsB;QAC3B/E,OAAO,IACLf,kBAAkB6E,oBAAoB3E,cAAc;gBAClDC,WAAWR;YACb;QACFqG,UAAU,CAACQ,WAAaC,sBAAsBD,UAAU;gBAAEtG;YAAa;IACzE;AACF;AAEA;;;;CAIC,GACD,OAAO,SAASkH,qBACdpE,SAAoB;IAEpB,MAAM9C,eAAe6G,kBAAkBzE,GAAG,CAACU;IAC3C,IAAI9C,iBAAiB4C,WAAW,OAAOA;IACvC,OAAO;QACL,IAAI;YACF,MAAM/B,QAAQ,MAAMf,kBAAkB6E,oBAAoB3E,cAAc;gBACtEC,WAAWwC;YACb;YACA,OAAOC,eAAe7B,OAAOgC,kBAAkBC;QACjD,EAAE,eAAM;YACN,OAAO;gBAAEzC,OAAO;YAAS;QAC3B;IACF;AACF"}
1
+ {"version":3,"sources":["../../../../../../../../../libs/tenant/feature/instance/src/lib/hooks/firebase/firestore-multitab-wedge.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { type Firestore } from 'firebase/firestore'\n\nimport { PRIMARY_LEASE_MAX_AGE_MS } from './firestore-tab-handoff'\n\n/**\n * A MULTI-TAB CACHE THAT ANOTHER TAB HAS LOCKED, AND THE WAY OUT (AGL-3428).\n *\n * ## The wedge the network cycle cannot clear\n *\n * `firestore-stall-recovery.ts` recovers a lapsed primary lease by cycling the\n * network, which runs the lease election at once (AGL-3373). That needs the\n * election's IndexedDB transaction to run. Measured against\n * `@firebase/firestore` 4.17.2: `IndexedDbPersistence.runTransaction` opens\n * EVERY transaction over EVERY object store (`getObjectStores(schemaVersion)`),\n * so one tab that stops partway through a readwrite transaction — frozen or\n * discarded by the browser while it runs — holds every store for every tab on\n * the origin. Behind it, in every other tab:\n *\n * - the lease election waits, so the lease row is never renewed by anyone;\n * - cache reads wait, so pages sit on their spinners;\n * - the mutation-queue write waits, so a save never reaches the network;\n * - a freshly opened tab's persistence `start()` waits, so a new tab hangs too;\n * - `disableNetwork`, `enableNetwork` and `terminate` are queued on the same\n * AsyncQueue behind the stuck operation, so none of them ever runs.\n *\n * On 2026-09-30 production (beta.218) did exactly this three times in two\n * hours: every console tab stopped, and the `owner` row named a background\n * tab that had stopped renewing it.\n *\n * ## How it is told apart from a slow read\n *\n * Only after the network cycle, and only from a visible tab on a browser that\n * reports a network. Such a tab wins a lapsed lease within one 4-second\n * election tick, and the cycle has just forced one. So, after a short settle,\n * the tab reads the `owner` row itself:\n *\n * - **the read cannot complete in time** — the store is locked by another\n * tab's open transaction. \"In time\" is {@link WEDGE_LOCK_MS}, longer than a\n * starved but living tab holds it (AGL-4135); or\n * - **the lease is older than {@link STALE_PRIMARY_LEASE_MS}** — no tab,\n * including this one, is completing an election.\n *\n * Either is the wedge. A fresh lease — this tab's or another's — is a healthy\n * cache and a merely slow server, and nothing more happens.\n *\n * ## The way out\n *\n * The tab records a {@link MemoryCacheFallback} in `sessionStorage` and\n * reloads. `firestoreCacheClassFor` reads it at startup and gives this tab the\n * memory cache, which shares nothing with other tabs, so the locked database\n * cannot reach it. `sessionStorage` is per tab: tabs already running keep the\n * durable cache, and the fallback leaves when this tab closes or after\n * {@link MEMORY_CACHE_FALLBACK_TTL_MS}.\n *\n * A reload, not an in-place swap, because nothing in place can work: the\n * wedged instance's `terminate()` is queued behind the stuck operation, a\n * second instance for the same app throws until the first is gone, and\n * hundreds of readers hold the instance from context and from closures.\n * Nothing that could be saved is lost — the wedge had already stopped every\n * write in the tab from leaving it.\n *\n * ## The tabs that open next (AGL-4090)\n *\n * Every tab used to find the lock on its own, so each NEW tab spent the whole\n * path above — the 8 s stall, the cycle's two 5 s steps, the settle, the 4 s\n * read, the reload — on an empty page: about half a minute, per tab. So a tab\n * whose read found the store LOCKED also leaves a {@link SharedCacheLock} in\n * `localStorage`, and `firestoreCacheClassFor` starts every tab that opens\n * while it is fresh on the memory cache at once: no stall, no reload.\n *\n * - **Only a lock is shared.** A locked store hangs every tab that opens the\n * database, a new one included. A stale lease does not: no transaction\n * holds the store, and a freshly started tab wins a lapsed lease at its\n * first election (AGL-3373). That fallback stays per tab.\n * - **Each tab that starts from it reads the lease again**, read-only, once\n * ({@link confirmSharedCacheLock}). Still locked, it re-stamps the record;\n * anything else clears it, so the first tab after the lock lifts is the\n * last one moved. The record lasts as long as the lock while tabs keep\n * opening, and {@link SHARED_CACHE_LOCK_TTL_MS} past the last tab that saw it.\n * - **Nothing here writes to IndexedDB or touches the lease.** A tab on the\n * memory cache takes no part in the multi-tab protocol, so it can never be\n * a second primary over the shared cache (AGL-3788).\n *\n * The cost is the memory cache's, and it is why the fallback was per tab: a\n * write made offline in such a tab is lost if the tab closes first, and the\n * tab shares no cache with the others. But while the store is locked, the\n * durable cache in a new tab can do none of that either: its persistence\n * never starts, so it reads nothing and no write leaves it. The cost is real\n * only for a record that has outlived its lock, and the re-read clears that\n * at the first tab that starts from it.\n *\n * Not chosen: a lease read at boot in every tab, in place of the record. The\n * cache is fixed when `initializeFirestore` runs, synchronously in the\n * provider's first render, and IndexedDB answers asynchronously, so a boot\n * read can shorten the wait to the read plus a reload but never skip it. It\n * would also add a read to every healthy tab's boot, and at boot the store can\n * be held for seconds for healthy reasons (the primary's LRU collection, a\n * schema upgrade) that the stall and the cycle rule out today, so it would\n * reload healthy tabs.\n */\n\n/** `sessionStorage` key of this tab's memory-cache fallback. */\nexport const MEMORY_CACHE_FALLBACK_KEY = 'aglyn:firestore-memory-cache-fallback'\n\n/**\n * How long a tab keeps the memory cache after falling back. The SDK's own\n * inactivity horizon (`MAX_CLIENT_AGE_MS`), after which a tab that is still\n * stuck no longer counts as a client; past it, a reload tries the durable\n * cache again, and falls back again if it has to.\n */\nexport const MEMORY_CACHE_FALLBACK_TTL_MS = 30 * 60 * 1000\n\n/** `localStorage` key of the lock a tab saw, for the tabs that open next (AGL-4090). */\nexport const SHARED_CACHE_LOCK_KEY = 'aglyn:firestore-shared-cache-locked'\n\n/**\n * How long a lock one tab saw starts new tabs on the memory cache, unless a\n * tab that starts from it sees the lock again. Long enough for the tabs a\n * person opens together (a page, then its preview); short, because a record\n * that outlives its lock moves every new tab, not one.\n */\nexport const SHARED_CACHE_LOCK_TTL_MS = 5 * 60 * 1000\n\n/**\n * A lease older than this, read from a visible online tab right after a\n * forced election, means no election is completing. The SDK treats a lease as\n * lapsed at 5 s (`MAX_PRIMARY_ELIGIBLE_AGE_MS`) and runs the election every\n * 4 s; this is three times the first, so an election that is merely late is\n * never mistaken for one that cannot run.\n */\nexport const STALE_PRIMARY_LEASE_MS = 15_000\n\n/**\n * How long the lease read may take before the store is judged locked. The\n * SDK's own transactions take milliseconds.\n *\n * Measured in time this tab was RUNNING, not on the wall clock (AGL-4120). While\n * the main thread is frozen, the read's answer sits unhandled in the same task\n * queue as the timeout, so a four-second freeze used to read as a locked store:\n * an `owner` read measured 3,945 ms in a freeze and 0 ms after it. On that false\n * verdict a healthy tab was reloaded, losing whatever was typed into it, and\n * every tab opened for the next five minutes started on the memory cache.\n */\nexport const LEASE_PROBE_TIMEOUT_MS = 4_000\n\n/**\n * How long the wedge check's lease read may wait before the store counts as\n * locked (AGL-4135). Five times {@link LEASE_PROBE_TIMEOUT_MS}, because a store\n * held by a tab that is slow is not a store held by a tab that is frozen.\n *\n * A starved tab (busy, slow, throttled) keeps each IndexedDB transaction open\n * until its event loop comes back between requests, and the SDK's lease\n * renewal makes several requests. Measured in production (v1.5.0, a tab busy\n * in 3 s slices): the store held every read for about 15 s, then answered with\n * a fresh lease. At 4 s that read as the wedge, and the healthy tab was reloaded\n * onto the memory cache, losing what had been typed into it. A frozen tab never\n * lets go, so the wedge still reads as locked, only later.\n */\nexport const WEDGE_LOCK_MS = 20_000\n\n/**\n * The probe's clock. A browser coalesces the ticks a frozen thread missed, so\n * counting ticks counts only the time the tab could have heard the answer.\n */\nexport const LEASE_PROBE_TICK_MS = 250\n\n/**\n * How long after the network cycle the lease is read, so the election the\n * cycle queued has run.\n */\nexport const LEASE_SETTLE_MS = 3_000\n\n/** The SDK's lease store and its single row's key (`DbPrimaryClientStore`, `DbPrimaryClientKey`). */\nconst OWNER_STORE = 'owner'\nconst OWNER_KEY = 'owner'\n\n/** What reading the lease found. */\nexport type PrimaryLeaseProbe =\n /** The read did not complete in time: another tab's transaction holds the store. */\n | { state: 'locked' }\n /** The lease row: who holds it and how long ago it was renewed. */\n | { state: 'leased'; ownerId: string; ageMs: number }\n /** There is no lease row. */\n | { state: 'vacant' }\n /** The lease could not be read: no IndexedDB, no database, no store, an error. */\n | { state: 'unknown' }\n\n/** Why a tab concluded the multi-tab cache is wedged. */\nexport type WedgeEvidence =\n | { reason: 'lease-locked' }\n | { reason: 'lease-stale'; ownerId: string; ageMs: number }\n /** The SDK's AsyncQueue has failed for good (AGL-4156). */\n | { reason: 'queue-failed' }\n\n/** The fallback this tab recorded, and why. */\nexport type MemoryCacheFallback = WedgeEvidence & { at: number }\n\n/** A lock one tab saw, recorded for the tabs that open next (AGL-4090). */\nexport interface SharedCacheLock {\n reason: 'lease-locked'\n /** The database whose store was locked: `<persistence prefix>main`. */\n databaseName: string\n /** When a tab last saw it locked. */\n at: number\n}\n\n/** What a tab that started from a {@link SharedCacheLock} found when it read the lease again. */\nexport type SharedCacheLockCheck =\n /** There was no fresh record for this database: nothing was read. */\n | 'absent'\n /** The store is still locked; the record was re-stamped. */\n | 'still-locked'\n /** The store answered; the record is gone, so the next tab gets the durable cache. */\n | 'cleared'\n /** Storage could not be read or written; the record is left to expire. */\n | 'failed'\n\n/**\n * Reads the SDK's `owner` row from `databaseName`.\n *\n * Opens only a database that already exists, at whatever version it has (the\n * same rule as `readHeartbeatClientIds`): `open(name)` on a missing database\n * would create it at version 1 under the SDK. The connection serves one\n * read-only request and is closed — also on `versionchange`, so it never\n * holds up the SDK's own upgrade, and also when the read lands after the\n * timeout.\n */\nexport async function probePrimaryLease(\n factory: IDBFactory | undefined,\n databaseName: string,\n {\n timeoutMs = LEASE_PROBE_TIMEOUT_MS,\n now = Date.now,\n }: { timeoutMs?: number; now?: () => number } = {},\n): Promise<PrimaryLeaseProbe> {\n if (!factory || typeof factory.databases !== 'function') return { state: 'unknown' }\n try {\n const databases = await factory.databases()\n if (!databases.some((database) => database.name === databaseName)) {\n return { state: 'unknown' }\n }\n } catch {\n return { state: 'unknown' }\n }\n\n return new Promise((resolve) => {\n let settled = false\n let database: IDBDatabase | undefined\n const settle = (probe: PrimaryLeaseProbe) => {\n if (settled) return\n settled = true\n clearInterval(clock)\n resolve(probe)\n }\n const close = () => {\n try {\n database?.close()\n } catch {\n // Already closed.\n }\n }\n // Only a lock can hold a read-only request this long; the connection is\n // closed when the request finally lands.\n const tickMs = Math.min(LEASE_PROBE_TICK_MS, timeoutMs)\n let ticks = Math.ceil(timeoutMs / tickMs)\n const clock = setInterval(() => {\n ticks -= 1\n if (ticks <= 0) settle({ state: 'locked' })\n }, tickMs)\n\n let request: IDBOpenDBRequest\n try {\n request = factory.open(databaseName)\n } catch {\n settle({ state: 'unknown' })\n return\n }\n // The database was deleted between `databases()` and `open()`: abort the\n // creation rather than leave the SDK an empty version-1 database.\n request.onupgradeneeded = () => request.transaction?.abort()\n request.onerror = () => settle({ state: 'unknown' })\n request.onsuccess = () => {\n database = request.result\n database.onversionchange = close\n if (settled || !database.objectStoreNames.contains(OWNER_STORE)) {\n close()\n settle({ state: 'unknown' })\n return\n }\n try {\n const read = database\n .transaction(OWNER_STORE, 'readonly')\n .objectStore(OWNER_STORE)\n .get(OWNER_KEY)\n read.onsuccess = () => {\n close()\n const row = read.result as\n | { ownerId?: unknown; leaseTimestampMs?: unknown }\n | undefined\n if (\n !row ||\n typeof row.ownerId !== 'string' ||\n typeof row.leaseTimestampMs !== 'number'\n ) {\n settle({ state: 'vacant' })\n return\n }\n settle({\n state: 'leased',\n ownerId: row.ownerId,\n ageMs: now() - row.leaseTimestampMs,\n })\n }\n read.onerror = () => {\n close()\n settle({ state: 'unknown' })\n }\n } catch {\n close()\n settle({ state: 'unknown' })\n }\n }\n })\n}\n\n/**\n * How long the lease read may take before a quiet client counts as WAITING on\n * the store (AGL-4135). Shorter than {@link LEASE_PROBE_TIMEOUT_MS}, which\n * decides a wedge: this asks only whether something holds the store now. The\n * SDK's own transactions take milliseconds, so a read that waits a second has\n * waited on one, from another tab or from this client's own backlog.\n */\nexport const LEASE_PROMPT_READ_MS = 1_000\n\n/** What the shared cache says about a client that has gone quiet (AGL-4135). */\nexport type LeaseCheck =\n /**\n * The store did not answer promptly. A transaction holds it, and every call\n * this client makes is queued behind that transaction.\n */\n | { state: 'waiting' }\n /** Another tab holds a live lease and serves this client through it. */\n | { state: 'served'; ownerId: string }\n /**\n * Nothing here explains the quiet. This tab holds the lease, or the lease has\n * lapsed or is vacant, or the lease could not be read or attributed.\n */\n | { state: 'silent' }\n\n/**\n * Reads a prompt lease probe for a quiet client whose own id is `selfId`.\n * Pure. A lease is live while younger than the SDK's 5 s\n * (`MAX_PRIMARY_ELIGIBLE_AGE_MS`). Without `selfId` a live lease cannot be told\n * apart from this tab's own, so it reads as `silent`, which is what every stall\n * was read as before.\n */\nexport function leaseCheckFrom(\n probe: PrimaryLeaseProbe,\n selfId: string | undefined,\n): LeaseCheck {\n if (probe.state === 'locked') return { state: 'waiting' }\n if (\n probe.state === 'leased' &&\n selfId !== undefined &&\n probe.ownerId !== selfId &&\n probe.ageMs < PRIMARY_LEASE_MAX_AGE_MS\n ) {\n return { state: 'served', ownerId: probe.ownerId }\n }\n return { state: 'silent' }\n}\n\n/**\n * This tab's id in the multi-tab protocol: the id its `clientMetadata` row is\n * written under, and any lease it holds. Read from the SDK's client\n * (`Firestore._firestoreClient.clientId`, which is internal and set once the\n * client has started). `undefined` when it is not there. Read in production\n * (4.17.2) against the `clientMetadata` row the same tab wrote.\n */\nexport function firestoreClientId(firestore: Firestore): string | undefined {\n try {\n const client = (firestore as unknown as {\n _firestoreClient?: { clientId?: unknown }\n })._firestoreClient\n const id = client?.clientId\n return typeof id === 'string' && id.length > 0 ? id : undefined\n } catch {\n return undefined\n }\n}\n\n/**\n * Whether a lease read taken right after a forced election, from a visible\n * online tab, shows the wedge. Anything that could be a healthy cache —\n * a fresh lease, no lease row, an unreadable one — is not evidence.\n */\nexport function wedgeEvidenceFrom(\n probe: PrimaryLeaseProbe,\n staleMs = STALE_PRIMARY_LEASE_MS,\n): WedgeEvidence | undefined {\n if (probe.state === 'locked') return { reason: 'lease-locked' }\n if (probe.state === 'leased' && probe.ageMs >= staleMs) {\n return { reason: 'lease-stale', ownerId: probe.ownerId, ageMs: probe.ageMs }\n }\n return undefined\n}\n\n/**\n * The object stored under `key`, when it parses and its `at` is within\n * `ttlMs` of `now` and not ahead of it.\n */\nfunction readStampedRecord(\n storage: Pick<Storage, 'getItem'> | undefined,\n key: string,\n now: number,\n ttlMs: number,\n): ({ at: number } & Record<string, unknown>) | undefined {\n let raw: string | null\n try {\n raw = storage?.getItem(key) ?? null\n } catch {\n return undefined\n }\n if (raw === null) return undefined\n let parsed: unknown\n try {\n parsed = JSON.parse(raw)\n } catch {\n return undefined\n }\n if (typeof parsed !== 'object' || parsed === null) return undefined\n const record = parsed as { at?: unknown } & Record<string, unknown>\n if (typeof record.at !== 'number' || !Number.isFinite(record.at)) return undefined\n if (now - record.at >= ttlMs || record.at > now) return undefined\n return record as { at: number } & Record<string, unknown>\n}\n\n/**\n * This tab's fallback, or `undefined` when there is none, it has expired, or\n * it does not parse.\n */\nexport function readMemoryCacheFallback(\n storage: Pick<Storage, 'getItem'> | undefined,\n now: number,\n ttlMs = MEMORY_CACHE_FALLBACK_TTL_MS,\n): MemoryCacheFallback | undefined {\n return readStampedRecord(storage, MEMORY_CACHE_FALLBACK_KEY, now, ttlMs) as\n | MemoryCacheFallback\n | undefined\n}\n\n/**\n * The lock a tab saw on `databaseName`, or `undefined` when there is none, it\n * names another database, it has expired, or it does not parse.\n */\nexport function readSharedCacheLock(\n storage: Pick<Storage, 'getItem'> | undefined,\n databaseName: string | undefined,\n now: number,\n ttlMs = SHARED_CACHE_LOCK_TTL_MS,\n): SharedCacheLock | undefined {\n if (databaseName === undefined) return undefined\n const record = readStampedRecord(storage, SHARED_CACHE_LOCK_KEY, now, ttlMs)\n if (record?.reason !== 'lease-locked' || record.databaseName !== databaseName) {\n return undefined\n }\n return record as unknown as SharedCacheLock\n}\n\nconst browserSessionStorage = (): Storage | undefined => {\n try {\n return typeof window === 'undefined' ? undefined : window.sessionStorage\n } catch {\n // Site data blocked: reading `window.sessionStorage` throws.\n return undefined\n }\n}\n\nconst browserLocalStorage = (): Storage | undefined => {\n try {\n return typeof window === 'undefined' ? undefined : window.localStorage\n } catch {\n // Site data blocked: reading `window.localStorage` throws.\n return undefined\n }\n}\n\nconst browserIndexedDb = (): IDBFactory | undefined => {\n try {\n return typeof window === 'undefined' ? undefined : window.indexedDB\n } catch {\n return undefined\n }\n}\n\n/** Whether this browser tab is running on its memory-cache fallback. */\nexport function memoryCacheFallbackActive(now = Date.now()): boolean {\n return readMemoryCacheFallback(browserSessionStorage(), now) !== undefined\n}\n\n/**\n * Whether another tab has just seen the store of `databaseName` locked, so\n * this tab should start on the memory cache rather than wait to find out.\n */\nexport function sharedCacheLockActive(\n databaseName: string | undefined,\n now = Date.now(),\n): boolean {\n return readSharedCacheLock(browserLocalStorage(), databaseName, now) !== undefined\n}\n\n/**\n * Records, for the tabs that open next, that the store of `databaseName` is\n * locked now. Never throws: without the record, the next tab finds the lock\n * itself, as it always has.\n */\nexport function recordSharedCacheLock(\n databaseName: string,\n {\n storage = browserLocalStorage(),\n now = Date.now,\n }: { storage?: Pick<Storage, 'setItem'>; now?: () => number } = {},\n): void {\n const record: SharedCacheLock = { reason: 'lease-locked', databaseName, at: now() }\n try {\n storage?.setItem(SHARED_CACHE_LOCK_KEY, JSON.stringify(record))\n } catch {\n // Full or blocked.\n }\n}\n\n/**\n * Run once by a tab that started on the memory cache: reads the lease of\n * `databaseName` again and keeps another tab's lock record only while the\n * store is still locked. Never creates a record and never rejects.\n */\nexport async function confirmSharedCacheLock(\n databaseName: string,\n {\n probe = () => probePrimaryLease(browserIndexedDb(), databaseName),\n storage = browserLocalStorage(),\n now = Date.now,\n }: {\n probe?: () => Promise<PrimaryLeaseProbe>\n storage?: Pick<Storage, 'getItem' | 'setItem' | 'removeItem'>\n now?: () => number\n } = {},\n): Promise<SharedCacheLockCheck> {\n if (!storage) return 'absent'\n const seen = readSharedCacheLock(storage, databaseName, now())\n if (!seen) return 'absent'\n try {\n if ((await probe()).state === 'locked') {\n recordSharedCacheLock(databaseName, { storage, now })\n return 'still-locked'\n }\n const current = readSharedCacheLock(storage, databaseName, now())\n // Another tab saw the lock again while this read ran; its record is\n // newer than this read, so it stands.\n if (current && current.at !== seen.at) return 'still-locked'\n if (current) storage.removeItem(SHARED_CACHE_LOCK_KEY)\n return 'cleared'\n } catch {\n return 'failed'\n }\n}\n\nexport interface WedgeEscalationDeps {\n /** Reads the lease. */\n probe: () => Promise<PrimaryLeaseProbe>\n /** Moves this tab off the shared cache. */\n fallBack: (evidence: WedgeEvidence) => void\n /** Whether this tab is already on the fallback — it then never escalates. */\n isFallbackActive?: () => boolean\n isOnline?: () => boolean\n isVisible?: () => boolean\n /** Waits `ms`; the settle before the lease read. */\n wait?: (ms: number) => Promise<void>\n settleMs?: number\n}\n\nconst browserOnline = () =>\n typeof navigator === 'undefined' || navigator.onLine !== false\n\nconst documentVisible = () =>\n typeof document === 'undefined' || document.visibilityState !== 'hidden'\n\n/**\n * The step `createStallRecovery` runs after its network cycle for a\n * multi-tab client. Resolves `true` when it has moved the tab to the fallback.\n * Never rejects.\n */\nexport function createWedgeEscalation(\n deps: WedgeEscalationDeps,\n): () => Promise<boolean> {\n const {\n probe,\n fallBack,\n isFallbackActive = () => memoryCacheFallbackActive(),\n isOnline = browserOnline,\n isVisible = documentVisible,\n wait = (ms) => new Promise<void>((resolve) => setTimeout(resolve, ms)),\n settleMs = LEASE_SETTLE_MS,\n } = deps\n return async () => {\n try {\n if (isFallbackActive()) return false\n await wait(settleMs)\n // Both guards again: the reader may have gone, or the network with it.\n if (!isOnline() || !isVisible()) return false\n const evidence = wedgeEvidenceFrom(await probe())\n if (!evidence) return false\n fallBack(evidence)\n return true\n } catch {\n return false\n }\n }\n}\n\n/**\n * Records the fallback for this tab and reloads it onto the memory cache.\n * When the record cannot be written it does not reload: without it, the\n * reloaded tab would open the same locked database and hang again.\n *\n * A lock is also recorded for the tabs that open next (AGL-4090), first and\n * whatever happens to this tab's own record: they would hang on it too.\n */\nexport function fallBackToMemoryCache(\n evidence: WedgeEvidence,\n {\n storage = browserSessionStorage(),\n sharedStorage = browserLocalStorage(),\n databaseName,\n reload = () => window.location.reload(),\n now = Date.now,\n }: {\n storage?: Pick<Storage, 'setItem'>\n /** Where the tabs that open next look for a lock this tab saw. */\n sharedStorage?: Pick<Storage, 'setItem'>\n /** The locked database. Without it, nothing is shared. */\n databaseName?: string\n reload?: () => void\n now?: () => number\n } = {},\n): void {\n if (evidence.reason === 'lease-locked' && databaseName !== undefined) {\n recordSharedCacheLock(databaseName, { storage: sharedStorage, now })\n }\n if (!storage) return\n const record: MemoryCacheFallback = { ...evidence, at: now() }\n try {\n storage.setItem(MEMORY_CACHE_FALLBACK_KEY, JSON.stringify(record))\n } catch {\n return\n }\n console.warn(\n evidence.reason === 'queue-failed'\n ? '[firestore] The multi-tab cache failed this tab\\'s Firestore client; reloading this tab on the memory cache (AGL-4156).'\n : '[firestore] The multi-tab cache is locked by another tab; reloading this tab on the memory cache (AGL-3428).',\n record,\n )\n reload()\n}\n\n/**\n * A FIRESTORE CLIENT WHOSE QUEUE HAS FAILED, AND THE WAY OUT (AGL-4156).\n *\n * The SDK runs every operation on one AsyncQueue. When an operation rejects\n * with an error the queue does not retry, it keeps that error and refuses\n * every later operation with the assertion `Unexpected state (ID: b815)`,\n * whose `CONTEXT` names the first error. Nothing restarts it: the\n * client is dead until the page reloads, so every read and listener in the tab\n * fails, and pages stop loading.\n *\n * The durable cache is what kills it in production. On 2026-11-04 (v1.9.0,\n * `@firebase/firestore` 4.18.0) a new Firefox sign-up's console lost its client\n * on three page loads in 25 minutes. Each time, an IndexedDB request in the\n * SDK's transaction threw \"Attempt to get a record from database without an\n * in-progress transaction\". The SDK retries a failed transaction three times,\n * then hands the raw `DOMException` to the queue, which counts it as fatal\n * rather than as an `IndexedDbTransactionError` to back off from. The earlier\n * cases ended the same way: a full `localStorage` (AGL-2845) and a null target\n * from the IndexedDB target cache (`isCorePipeline`, 2026-10-14, Chrome).\n *\n * So the first b815 of a durable multi-tab client moves the tab onto the\n * memory cache, which does not use IndexedDB, through the same per-tab\n * {@link fallBackToMemoryCache} as the wedge. Nothing that could be saved is\n * lost: the dead queue had already stopped every write in the tab. A tab already\n * on the fallback runs the memory cache, which is never watched, so a b815 there\n * cannot loop. No lock is shared, because another tab's client is not dead.\n */\nconst QUEUE_FAILURE = /INTERNAL ASSERTION FAILED: Unexpected state \\(ID: b815\\)/\n\n/** Whether `thrown` (an error, an event's message, a rejection reason) is the SDK's failed-queue assertion. */\nexport function isFirestoreQueueFailure(thrown: unknown): boolean {\n try {\n const message =\n typeof thrown === 'string'\n ? thrown\n : thrown && typeof thrown === 'object' && 'message' in thrown\n ? String((thrown as { message: unknown }).message)\n : ''\n return QUEUE_FAILURE.test(message)\n } catch {\n return false\n }\n}\n\n/**\n * Watches `target` for the failed-queue assertion, as an uncaught error or an\n * unhandled rejection, and calls `fallBack` once, the first time it appears.\n * Returns the function that stops watching.\n */\nexport function watchFirestoreQueueFailure(\n fallBack: (evidence: WedgeEvidence) => void,\n {\n target = typeof window === 'undefined' ? undefined : window,\n isFallbackActive = () => memoryCacheFallbackActive(),\n }: {\n target?: Pick<Window, 'addEventListener' | 'removeEventListener'>\n isFallbackActive?: () => boolean\n } = {},\n): () => void {\n if (!target) return () => undefined\n let fired = false\n const onError = (event: Event) => {\n const { error, message } = event as ErrorEvent\n check(isFirestoreQueueFailure(error) || isFirestoreQueueFailure(message))\n }\n const onRejection = (event: Event) => {\n check(isFirestoreQueueFailure((event as PromiseRejectionEvent).reason))\n }\n const stop = () => {\n target.removeEventListener('error', onError)\n target.removeEventListener('unhandledrejection', onRejection)\n }\n const check = (failed: boolean) => {\n if (!failed || fired) return\n fired = true\n stop()\n try {\n if (isFallbackActive()) return\n fallBack({ reason: 'queue-failed' })\n } catch {\n // Watching never breaks the page.\n }\n }\n target.addEventListener('error', onError)\n target.addEventListener('unhandledrejection', onRejection)\n return stop\n}\n\n/** The IndexedDB database of each client running the durable multi-tab cache. */\nconst multiTabDatabases = new WeakMap<Firestore, string>()\n\n/**\n * Registers `firestore` as running the durable multi-tab cache under\n * `databaseName` (`<persistence prefix>main`). Only a registered client ever\n * escalates past the network cycle, and only its page is watched for a failed\n * queue ({@link watchFirestoreQueueFailure}).\n */\nexport function markMultiTabFirestore(firestore: Firestore, databaseName: string): void {\n if (firestore && typeof firestore === 'object') {\n if (!multiTabDatabases.has(firestore)) {\n watchFirestoreQueueFailure((evidence) =>\n fallBackToMemoryCache(evidence, { databaseName }),\n )\n }\n multiTabDatabases.set(firestore, databaseName)\n }\n}\n\n/**\n * The browser escalation for `firestore`, or `undefined` when it does not run\n * the durable multi-tab cache (the emulator configuration, an ephemeral\n * origin, a tab already on the fallback).\n */\nexport function browserWedgeEscalationFor(\n firestore: Firestore,\n): (() => Promise<boolean>) | undefined {\n const databaseName = multiTabDatabases.get(firestore)\n if (databaseName === undefined) return undefined\n return createWedgeEscalation({\n probe: () =>\n probePrimaryLease(browserIndexedDb(), databaseName, {\n timeoutMs: WEDGE_LOCK_MS,\n }),\n fallBack: (evidence) => fallBackToMemoryCache(evidence, { databaseName }),\n })\n}\n\n/**\n * The lease check `createStallRecovery` runs before a network cycle, or\n * `undefined` when `firestore` does not run the durable multi-tab cache: a\n * client with a cache of its own has no other tab to wait on. Never rejects.\n */\nexport function browserLeaseCheckFor(\n firestore: Firestore,\n): (() => Promise<LeaseCheck>) | undefined {\n const databaseName = multiTabDatabases.get(firestore)\n if (databaseName === undefined) return undefined\n return async () => {\n try {\n const probe = await probePrimaryLease(browserIndexedDb(), databaseName, {\n timeoutMs: LEASE_PROMPT_READ_MS,\n })\n return leaseCheckFrom(probe, firestoreClientId(firestore))\n } catch {\n return { state: 'silent' }\n }\n }\n}\n"],"names":["PRIMARY_LEASE_MAX_AGE_MS","MEMORY_CACHE_FALLBACK_KEY","MEMORY_CACHE_FALLBACK_TTL_MS","SHARED_CACHE_LOCK_KEY","SHARED_CACHE_LOCK_TTL_MS","STALE_PRIMARY_LEASE_MS","LEASE_PROBE_TIMEOUT_MS","WEDGE_LOCK_MS","LEASE_PROBE_TICK_MS","LEASE_SETTLE_MS","OWNER_STORE","OWNER_KEY","probePrimaryLease","factory","databaseName","timeoutMs","now","Date","databases","state","some","database","name","Promise","resolve","settled","settle","probe","clearInterval","clock","close","tickMs","Math","min","ticks","ceil","setInterval","request","open","onupgradeneeded","transaction","abort","onerror","onsuccess","result","onversionchange","objectStoreNames","contains","read","objectStore","get","row","ownerId","leaseTimestampMs","ageMs","LEASE_PROMPT_READ_MS","leaseCheckFrom","selfId","undefined","firestoreClientId","firestore","client","_firestoreClient","id","clientId","length","wedgeEvidenceFrom","staleMs","reason","readStampedRecord","storage","key","ttlMs","raw","getItem","parsed","JSON","parse","record","at","Number","isFinite","readMemoryCacheFallback","readSharedCacheLock","browserSessionStorage","window","sessionStorage","browserLocalStorage","localStorage","browserIndexedDb","indexedDB","memoryCacheFallbackActive","sharedCacheLockActive","recordSharedCacheLock","setItem","stringify","confirmSharedCacheLock","seen","current","removeItem","browserOnline","navigator","onLine","documentVisible","document","visibilityState","createWedgeEscalation","deps","fallBack","isFallbackActive","isOnline","isVisible","wait","ms","setTimeout","settleMs","evidence","fallBackToMemoryCache","sharedStorage","reload","location","console","warn","QUEUE_FAILURE","isFirestoreQueueFailure","thrown","message","String","test","watchFirestoreQueueFailure","target","fired","onError","event","error","check","onRejection","stop","removeEventListener","failed","addEventListener","multiTabDatabases","WeakMap","markMultiTabFirestore","has","set","browserWedgeEscalationFor","browserLeaseCheckFor"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;AAID,SAASA,wBAAwB,QAAQ,6BAAyB;AAElE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA+FC,GAED,8DAA8D,GAC9D,OAAO,MAAMC,4BAA4B,wCAAuC;AAEhF;;;;;CAKC,GACD,OAAO,MAAMC,+BAA+B,KAAK,KAAK,KAAI;AAE1D,sFAAsF,GACtF,OAAO,MAAMC,wBAAwB,sCAAqC;AAE1E;;;;;CAKC,GACD,OAAO,MAAMC,2BAA2B,IAAI,KAAK,KAAI;AAErD;;;;;;CAMC,GACD,OAAO,MAAMC,yBAAyB,MAAM;AAE5C;;;;;;;;;;CAUC,GACD,OAAO,MAAMC,yBAAyB,KAAK;AAE3C;;;;;;;;;;;;CAYC,GACD,OAAO,MAAMC,gBAAgB,MAAM;AAEnC;;;CAGC,GACD,OAAO,MAAMC,sBAAsB,IAAG;AAEtC;;;CAGC,GACD,OAAO,MAAMC,kBAAkB,KAAK;AAEpC,mGAAmG,GACnG,MAAMC,cAAc;AACpB,MAAMC,YAAY;AA2ClB;;;;;;;;;CASC,GACD,OAAO,eAAeC,kBACpBC,OAA+B,EA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