@aglyn/tenant-feature-instance 1.5.0 → 1.7.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.
Files changed (30) hide show
  1. package/README.md +2 -2
  2. package/package.json +7 -7
  3. package/src/lib/hooks/firebase/firebase-services.d.ts +7 -0
  4. package/src/lib/hooks/firebase/firebase-services.js.map +1 -1
  5. package/src/lib/hooks/firebase/firestore-multitab-wedge.d.ts +67 -1
  6. package/src/lib/hooks/firebase/firestore-multitab-wedge.js +81 -2
  7. package/src/lib/hooks/firebase/firestore-multitab-wedge.js.map +1 -1
  8. package/src/lib/hooks/firebase/firestore-stall-recovery.d.ts +52 -4
  9. package/src/lib/hooks/firebase/firestore-stall-recovery.js +87 -16
  10. package/src/lib/hooks/firebase/firestore-stall-recovery.js.map +1 -1
  11. package/src/lib/hooks/helpers/guarded-seed-write.d.ts +71 -1
  12. package/src/lib/hooks/helpers/guarded-seed-write.js +4 -3
  13. package/src/lib/hooks/helpers/guarded-seed-write.js.map +1 -1
  14. package/src/lib/hooks/helpers/listen-confirmation.d.ts +54 -7
  15. package/src/lib/hooks/helpers/listen-confirmation.js +89 -12
  16. package/src/lib/hooks/helpers/listen-confirmation.js.map +1 -1
  17. package/src/lib/hooks/helpers/use-doc.js +6 -4
  18. package/src/lib/hooks/helpers/use-doc.js.map +1 -1
  19. package/src/lib/hooks/use-firestore-collection.d.ts +7 -0
  20. package/src/lib/hooks/use-firestore-collection.js +6 -4
  21. package/src/lib/hooks/use-firestore-collection.js.map +1 -1
  22. package/src/lib/hooks/use-firestore-doc.d.ts +7 -0
  23. package/src/lib/hooks/use-firestore-doc.js +6 -4
  24. package/src/lib/hooks/use-firestore-doc.js.map +1 -1
  25. package/src/lib/hooks/use-paged-collection.d.ts +7 -1
  26. package/src/lib/hooks/use-paged-collection.js.map +1 -1
  27. package/src/lib/hooks/use-sorted-paged-collection.js +3 -1
  28. package/src/lib/hooks/use-sorted-paged-collection.js.map +1 -1
  29. package/src/lib/testing/list-query-double.js +1 -0
  30. package/src/lib/testing/list-query-double.js.map +1 -1
package/README.md CHANGED
@@ -8,11 +8,11 @@ the console halves of the `@aglyn/plugins-*` packages read and write site data
8
8
  through it. Install it directly only if you are building a client against an
9
9
  Aglyn deployment's Firestore.
10
10
 
11
- > Beta. Published from the Aglyn monorepo under the `beta` dist-tag; APIs can change between beta releases.
11
+ > Published to npm from the Aglyn monorepo. Versions follow [semantic versioning](https://semver.org).
12
12
 
13
13
  ## Install
14
14
 
15
- npm install @aglyn/tenant-feature-instance@beta
15
+ npm install @aglyn/tenant-feature-instance
16
16
 
17
17
  Peer dependencies:
18
18
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aglyn/tenant-feature-instance",
3
- "version": "1.5.0",
3
+ "version": "1.7.0",
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.5.0",
29
- "@aglyn/shared-data-enums": "1.5.0",
30
- "@aglyn/shared-ui-jsx": "1.5.0",
31
- "@aglyn/shared-util-email": "1.5.0",
32
- "@aglyn/shared-util-http": "1.5.0",
33
- "@aglyn/shared-util-timestamp": "1.5.0",
28
+ "@aglyn/aglyn": "1.7.0",
29
+ "@aglyn/shared-data-enums": "1.7.0",
30
+ "@aglyn/shared-ui-jsx": "1.7.0",
31
+ "@aglyn/shared-util-email": "1.7.0",
32
+ "@aglyn/shared-util-http": "1.7.0",
33
+ "@aglyn/shared-util-timestamp": "1.7.0",
34
34
  "@swc/helpers": "0.5.23",
35
35
  "lodash-es": "^4.18.1",
36
36
  "mobx": "^7.0.5"
@@ -5,6 +5,7 @@ import { type Firestore } from 'firebase/firestore';
5
5
  import { type RemoteConfig } from 'firebase/remote-config';
6
6
  import { type ReactNode } from 'react';
7
7
  import { type AuthPersistenceClass } from './auth-persistence';
8
+ import type { ListenHandle } from '../helpers/listen-confirmation';
8
9
  /**
9
10
  * Drop-in replacement for reactfire's `ObservableStatus<T>` — reactfire is
10
11
  * unmaintained against firebase majors past v9, but its shape is preserved
@@ -65,6 +66,12 @@ export interface ObservableStatus<T> {
65
66
  * the note on `attempt = 0` in `use-firestore-collection`.
66
67
  */
67
68
  serverDenied: boolean;
69
+ /**
70
+ * This hook's listener, for a guarded save seeded from `data` to wait on
71
+ * alone (`writeGuardedBySeed`'s `listen`, AGL-4135). Stable for the life of
72
+ * the hook.
73
+ */
74
+ listen: ListenHandle;
68
75
  }
69
76
  /** Replaces reactfire's `ReactFireOptions<T>` — drops the `suspense` field, which was never read. */
70
77
  export interface FirestoreDocOptions<T> {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../../../libs/tenant/feature/instance/src/lib/hooks/firebase/firebase-services.tsx"],"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'use client'\n\nimport {\n type FirebaseApp,\n type FirebaseOptions,\n getApps,\n initializeApp,\n} from 'firebase/app'\nimport {\n type Analytics,\n getAnalytics as getAnalyticsInstance,\n initializeAnalytics as initializeAnalyticsInstance,\n} from 'firebase/analytics'\nimport { initializeAppCheck, ReCaptchaV3Provider } from 'firebase/app-check'\nimport { analyticsMayEmit } from '@aglyn/aglyn/app-utils/analytics-environment'\nimport { pushPlatformConsentDefault } from '@aglyn/aglyn/app-utils/platform-consent-default'\nimport { VISITOR_CONSENT_CHANGED_EVENT } from '@aglyn/aglyn/app-utils/visitor-consent'\nimport {\n type Auth,\n connectAuthEmulator,\n onIdTokenChanged,\n type User,\n} from 'firebase/auth'\nimport {\n type Firestore,\n connectFirestoreEmulator,\n getFirestore,\n initializeFirestore,\n} from 'firebase/firestore'\nimport {\n type RemoteConfig,\n getRemoteConfig as getRemoteConfigInstance,\n} from 'firebase/remote-config'\nimport {\n createContext,\n useContext,\n useEffect,\n useMemo,\n useRef,\n useState,\n type ReactNode,\n} from 'react'\nimport {\n FIREBASE_AUTH_EMULATOR_ENABLED,\n FIREBASE_FIRESTORE_EMULATOR_ENABLED,\n} from '@aglyn/shared-data-enums'\nimport {\n APP_CHECK_KEY_MISSING_MESSAGE,\n appCheckSiteKey,\n} from '../../constants/firebase-config'\nimport {\n authEmulatorUrl,\n firestoreEmulatorHost,\n} from '../../constants/firebase-emulator-hosts'\nimport {\n type AuthPersistenceClass,\n createAuthInstance,\n} from './auth-persistence'\nimport {\n firestoreCacheClassFor,\n localCacheFor,\n pruneSharedClientStateFor,\n} from './firestore-cache'\nimport { keepAppCheckRecaptchaContainer } from './app-check-recaptcha-container'\nimport {\n confirmSharedCacheLock,\n markMultiTabFirestore,\n} from './firestore-multitab-wedge'\nimport { firestorePersistencePrefix } from './firestore-shared-client-state'\nimport { startFirestoreTabHandoff } from './firestore-tab-handoff'\n\n/**\n * Drop-in replacement for reactfire's `ObservableStatus<T>` — reactfire is\n * unmaintained against firebase majors past v9, but its shape is preserved\n * here so `helpers/use-doc.ts`'s already-battle-tested onSnapshot+retry\n * implementation (AGL-216/223) didn't need to change.\n */\nexport interface ObservableStatus<T> {\n status: 'loading' | 'error' | 'success'\n hasEmitted: boolean\n isComplete: boolean\n data: T\n error: Error | undefined\n firstValuePromise: Promise<void>\n /**\n * The emitted `data` includes local writes the server has NOT\n * acknowledged (`snapshot.metadata.hasPendingWrites`).\n *\n * Carried rather than dropped because a caller cannot otherwise tell \"the\n * store holds this\" from \"my browser holds this\". `persistentLocalCache`\n * replays a queued write into the very first snapshot after a reload, so a\n * caller that treats every snapshot as authoritative will adopt its own\n * unacknowledged edit as the saved state — which is how the besigner ended\n * up unable to save real changes (AGL-1262).\n */\n hasPendingWrites: boolean\n /**\n * The emitted `data` came from the local cache and the server has NOT\n * confirmed it (`snapshot.metadata.fromCache`).\n *\n * Carried because it is the only per-listener ground truth about\n * freshness the SDK offers, and the console needs it (AGL-1066). Under\n * `persistentLocalCache` a listener whose server listen is being REFUSED\n * still emits cached snapshots and still reports `status: 'success'` —\n * the retry budget is reset by each cached emission and never spends, so\n * `status` can never reveal the fault (see\n * `use-firestore-collection-cached-retry.spec.ts`).\n *\n * Prefer this over `session-health`'s `staleSession` for anything that\n * asks \"is what I am looking at live?\". `staleSession` is a heuristic\n * needing two denied collections inside a window, and it is unreachable\n * on listener-only pages; this is a fact about THIS listener, costs\n * nothing, and clears itself the instant a server snapshot lands.\n */\n fromCache: boolean\n /**\n * The server has REFUSED this listen for longer than the retry budget, and\n * no server snapshot has arrived since (AGL-1066).\n *\n * `fromCache` says \"unconfirmed\", which is also true offline and true for\n * the first snapshot of a perfectly healthy load. This says \"refused\" —\n * only `permission-denied` counts it, and it takes a whole budget's worth\n * in a row, so it cannot fire offline and cannot fire on the AGL-216/217\n * post-sign-in token race.\n *\n * It is what `status` would say if the retry budget were spendable. It is\n * carried separately because correcting `status` in place would blank\n * every surface that renders cached data through an `error` branch — see\n * the note on `attempt = 0` in `use-firestore-collection`.\n */\n serverDenied: boolean\n}\n\n/** Replaces reactfire's `ReactFireOptions<T>` — drops the `suspense` field, which was never read. */\nexport interface FirestoreDocOptions<T> {\n idField?: string\n initialData?: T\n}\n\n/**\n * The Firebase products this provider builds, and therefore the ones every\n * page that renders it downloads.\n *\n * ⛔ NO Realtime Database and NO Cloud Storage (AGL-2706). Both were built\n * here and published as `useDatabase()` / `useStorage()`, and neither hook had\n * a single caller anywhere in the repo — so `@firebase/database` (125.9 KB\n * raw) and `@firebase/storage` (13.9 KB) were in the first load of every\n * console route to satisfy a context field nothing read.\n *\n * Realtime Database IS used, by `apps/console/hooks/use-presence.ts` and\n * `use-coediting.ts` — on their own Firebase app, with their own\n * `getDatabase`, behind the editor routes that need presence. That is the\n * shape to copy if a surface needs one of these: reach for the product where\n * the feature is, not in the provider every page mounts. A field here is paid\n * for by every route, used or not.\n */\ninterface FirebaseServices {\n app: FirebaseApp\n firestore: Firestore\n auth: Auth\n analytics: Analytics\n remoteConfig: RemoteConfig\n /**\n * The persistence class `auth` was actually created with (AGL-1379).\n *\n * Published so a **second** auth instance derives its class from the\n * primary rather than re-deciding it. `apps/console/hooks/use-presence.ts`\n * builds its own Firebase app and its own `Auth`; before this it took the\n * SDK default unconditionally, so configuring only the provider would have\n * left presence persisting a refresh token on an origin the provider had\n * just been careful not to persist one on.\n */\n authPersistence: AuthPersistenceClass\n}\n\nconst FirebaseServicesContext = createContext<FirebaseServices | undefined>(undefined)\n\n// Module-scope guards so HMR / remounts don't re-run emulator connection\n// (which throws if called twice) or double-initialize Firestore's\n// persistent cache.\n//\n// Firestore's is keyed by app NAME, not a bare boolean (AGL-1456): Firestore\n// initialization is once-per-app, so a module-global flag made the FIRST app\n// to mount decide for every later one — a second app would silently skip\n// `initializeFirestore` and take SDK defaults. That mattered the moment the\n// cache stopped being the same on every host.\nconst firestoreInitialized = new Set<string>()\nlet connectedAuth = false\n\n/**\n * True when THIS Chrome instance is under WebDriver automation control\n * (Puppeteer, Playwright, Selenium, or a raw CDP client) — never true for a\n * person's own browser.\n *\n * The `initializeFirestore` call below already documents the fault this\n * exists for: \"the emulator's WebChannel streaming misbehaves in automated\n * Chrome — listeners serve the initial empty from-cache snapshot and the\n * server sync never arrives\" (AGL-217). That mitigation only reaches\n * `FIREBASE_FIRESTORE_EMULATOR_ENABLED`, so an automated session against a\n * REAL, deployed backend — a browser-automation agent driving a live\n * console, which is exactly what `navigator.webdriver` detects — stayed\n * exposed. `getDocs`/`getDoc` and `onSnapshot` all resolve over the same\n * Watch stream internally, so a one-shot read wedges exactly like a listener\n * does: no error, nothing to catch, `loading` simply never gets its\n * settling event. That is the Media Library grid spinning on \"Loading\n * media…\" indefinitely with a perfectly healthy account and a perfectly\n * healthy network.\n *\n * `undefined` during SSR reads as `false` — `navigator` does not exist in\n * Node, and a server render can only ever produce the auto-detected\n * transport, never the forced one.\n */\nconst isAutomatedChromeSession = (): boolean =>\n typeof navigator !== 'undefined' && navigator.webdriver === true\n\n/**\n * The console tag's gtag config — ONE object, at module scope, deliberately\n * (AGL-1979).\n *\n * `initializeAnalytics(app, options)` throws `already-initialized` unless the\n * options `deepEqual` the ones the instance was first created with, and the\n * provider re-enters this block on every mount, every StrictMode double\n * invoke and every Fast Refresh. A fresh object literal per call survives\n * that only by *value*; a shared constant survives it by *identity*, which is\n * the first branch of the SDK's own comparison and cannot drift when someone\n * edits one call site and not another.\n *\n * ⚠️ The SDK MUTATES this object: `_initializeAnalytics` reads `options.config`\n * and writes `origin`, `update` and the installation id onto it in place.\n * That is precisely why sharing it is safe rather than dangerous — the object\n * the provider holds and the object the SDK stored are the same one, so they\n * cannot disagree.\n */\nconst CONSOLE_ANALYTICS_OPTIONS = {\n config: { send_page_view: false, content_group: 'console' },\n}\n\n/**\n * A surface's answer to \"may an analytics tag exist for this visitor at all?\".\n *\n * Registered from the app, at module scope, in the same shape as\n * `setFirestoreSessionReporters` and `setStaleSessionCheck` — and for a\n * sharper version of the same reason. This is consulted during the provider's\n * FIRST render, before any effect anywhere has run, so a gate installed from\n * an effect would arrive after the decision it exists to make.\n *\n * Answering `false` means the SDK is never asked to initialize: `gtag.js` is\n * never fetched, `window.gtag` never comes into existence, and the shared\n * `deliver()` in `analytics-events.ts` — whose fallback IS `window.gtag` —\n * therefore has nowhere to put a hit. That is the difference between a gate\n * and a suppression, and it is the difference AGL-1608 paid for: a resident\n * tag reports on its own, through enhanced measurement, whatever any flag\n * says afterwards.\n */\nexport type AnalyticsConsentGate = () => boolean\n\nlet analyticsConsentGate: AnalyticsConsentGate | null = null\n\n/**\n * Install the consent gate for this document, or clear it with `null`.\n *\n * UNREGISTERED MEANS ALLOWED, which is deliberate and is the only default that\n * is safe here. The tenant runtime does not use this provider's analytics\n * branch at all (it builds its own tag in `site-analytics.tsx`, behind the\n * AGL-1498 gate), and a self-hosted console points at the operator's own GA\n * property — silencing an operator's analytics because Aglyn's own surface\n * grew a gate is a failure they cannot diagnose. The surface that needs the\n * gate is the one that registers it.\n */\nexport function setAnalyticsConsentGate(\n gate: AnalyticsConsentGate | null,\n): void {\n analyticsConsentGate = gate\n}\n\n/** The gate's verdict, with an unregistered gate reading as \"allowed\". */\nfunction analyticsConsentAllows(): boolean {\n if (analyticsConsentGate === null) return true\n try {\n return analyticsConsentGate() === true\n } catch {\n // A gate that throws cannot be read as consent. Storage can throw in\n // private mode, and \"we could not tell\" is the one state this whole\n // mechanism resolves to \"no\".\n return false\n }\n}\n\n/**\n * The Analytics instance per Firebase app, so a re-boot after a consent change\n * hands back the tag that is already resident rather than asking the SDK for a\n * second one.\n *\n * `initializeAnalytics` is idempotent while the options match, so this is not\n * what makes re-entry safe — `CONSOLE_ANALYTICS_OPTIONS` being a shared\n * constant is. What this avoids is the noisy path: once anything has\n * initialized the provider with different options, every later call throws and\n * is logged, and a withdrawal followed by a re-grant would log it again.\n */\nconst analyticsByApp = new WeakMap<FirebaseApp, Analytics>()\n\n/**\n * Boot the console's Analytics tag, or return the one already booted.\n *\n * Extracted from the provider body so that \"when is the tag created\" and \"may\n * it be created\" are separable: the consent gate can defer this call to a\n * later render without the ordering below moving.\n */\nfunction bootAnalytics(app: FirebaseApp): Analytics | undefined {\n const existing = analyticsByApp.get(app)\n if (existing) return existing\n let analytics: Analytics\n // The region-conditional consent default (AGL-1597), declared BEFORE the\n // SDK boots the tag. Ordering is the whole of it: a `default` read after\n // `config` is not a default, and the SDK issues `config` inside\n // `initializeAnalytics` on the next line. Pushing onto `dataLayer` here\n // works even though gtag.js is not loaded yet — the queue is what makes the\n // ordering expressible.\n //\n // Still declared even though the gate above has already said yes, and the\n // two are not redundant. The gate answers \"may a tag exist\"; the default\n // answers \"what may the tag that does exist do\", per region, from its very\n // first hit. Ad storage stays denied everywhere on this surface.\n pushPlatformConsentDefault(\n typeof window === 'undefined' ? null : (window as never),\n )\n try {\n analytics = initializeAnalyticsInstance(app, CONSOLE_ANALYTICS_OPTIONS)\n } catch (error) {\n console.error(error)\n try {\n // Already initialized by someone else, with someone else's options:\n // take THAT instance rather than leaving consumers with nothing. The\n // tag it is attached to was configured without `send_page_view: false`\n // and without `content_group`, so this session reports a duplicate\n // startup page_view and an unstamped surface — degraded, and loudly so,\n // instead of silently dead.\n analytics = getAnalyticsInstance(app)\n } catch (fallbackError) {\n console.error(fallbackError)\n }\n }\n if (analytics) analyticsByApp.set(app, analytics)\n return analytics\n}\n\n/**\n * The tag this document may have right now: none outside a real production\n * deployment, none while consent is absent, otherwise the booted instance.\n */\nfunction analyticsForConsentState(app: FirebaseApp): Analytics | undefined {\n if (!analyticsMayEmit()) return undefined\n if (!analyticsConsentAllows()) return undefined\n return bootAnalytics(app)\n}\n\nexport interface FirebaseServicesProviderProps {\n firebaseConfig: FirebaseOptions\n appName: string\n /**\n * How much of *anything* this origin may keep on disk. Defaults to\n * `durable`, which is what every host serving this provider today is:\n * `*.aglyn.com` and `*.aglyn.app`, whose DNS we own and whose 14-day\n * session is the product.\n *\n * A **custom console domain** (AGL-1099c) must pass `ephemeral`. That is\n * the whole reason this is a prop rather than a constant: the class differs\n * per origin, not per build, and the decision belongs to whoever knows\n * which origin is being served.\n *\n * **It governs two things, and the name only names one.** It selects the\n * `Auth` persistence class (AGL-1379) *and* the Firestore `localCache`\n * (AGL-1456) — because both answer the same question about the same origin,\n * and splitting them into two props is precisely how the cache came to be\n * unconditional while the credential was hardened. See `firestore-cache.ts`.\n */\n authPersistence?: AuthPersistenceClass\n children?: ReactNode\n}\n\n/** The services every surface boots, before the per-document analytics verdict. */\ninterface FirebaseCoreServices {\n app: FirebaseApp\n firestore: Firestore\n auth: Auth\n remoteConfig: RemoteConfig\n}\n\n/**\n * Create (or adopt) the app, Auth, Firestore, App Check and Remote Config for\n * one Firebase app: everything the provider used to build in its first render\n * except Analytics, whose consent verdict belongs to the render that reads it.\n */\nfunction bootFirebaseCore(\n firebaseConfig: FirebaseOptions,\n appName: string,\n authPersistence: AuthPersistenceClass,\n): FirebaseCoreServices {\n const app =\n getApps().find((existing) => existing.name === appName) ??\n initializeApp(firebaseConfig, appName)\n // `durable` resolves to the same `getAuth(app)` this always called.\n const auth = createAuthInstance(app, authPersistence)\n\n // The durable cache's IndexedDB database, `<persistence prefix>main`.\n const persistencePrefix = app.options?.projectId\n ? firestorePersistencePrefix(app.name, app.options.projectId)\n : undefined\n const databaseName = persistencePrefix && `${persistencePrefix}main`\n // The origin's class, unless this tab fell back to the memory cache\n // because another tab locked the shared one (AGL-3428), or a tab has just\n // seen that lock (AGL-4090). Firestore only: `auth` above keeps the\n // origin's class.\n const firestoreCacheClass = firestoreCacheClassFor(authPersistence, databaseName)\n if (!firestoreInitialized.has(appName)) {\n try {\n // Under the emulator (dev/e2e only): force long-polling and skip\n // the persistent multi-tab cache. The emulator's WebChannel\n // streaming misbehaves in automated Chrome — listeners serve the\n // initial empty from-cache snapshot and the server sync never\n // arrives, which looks like \"empty pages with zero errors\"\n // (the AGL-217 mystery). Real traffic keeps the default transport\n // and persistent cache — except a WebDriver-controlled Chrome\n // against a real backend, which forces long-polling for the same\n // reason without giving up the cache (see `isAutomatedChromeSession`\n // below).\n //\n // ⚠️ CONSEQUENCE, and it will cost you hours if you do not know it\n // (AGL-1066): every stale-session/stale-cache fault is UNREPRODUCIBLE\n // locally through the app, because the cache that causes them is off\n // in exactly the configuration you would reach for to reproduce one.\n // A listener that keeps serving arbitrarily-old data while the server\n // refuses it, a `noDocument` tombstone that 404s a live host, the\n // retry budget that never spends because a cached emission resets it\n // — none of them can happen here. Test that behaviour with the unit\n // seams instead (`use-firestore-collection-cached-retry.spec.ts`\n // drives cached emissions and denials directly), or against a\n // deployed environment. Do NOT \"fix\" it by turning the cache on for\n // the emulator: the AGL-217 empty-pages-with-zero-errors mystery is\n // what that produces.\n initializeFirestore(\n app,\n FIREBASE_FIRESTORE_EMULATOR_ENABLED\n ? { experimentalForceLongPolling: true }\n : {\n // NOT unconditional (AGL-1456). `persistentLocalCache` writes\n // document bodies to this origin's IndexedDB, so on a custom\n // console domain it is the same exposure D6 removed from the\n // refresh token — see `firestore-cache.ts` for why one\n // declaration governs both.\n localCache: localCacheFor(firestoreCacheClass),\n // The real-backend half of the AGL-217 mitigation above: force\n // long-polling for a WebDriver-controlled Chrome even when it\n // is NOT talking to the emulator, because the WebChannel wedge\n // is a property of automated Chrome, not of which backend it\n // is automating against. Never true for a real visitor, so\n // production traffic keeps the SDK's own auto-detected\n // transport untouched.\n ...(isAutomatedChromeSession()\n ? { experimentalForceLongPolling: true }\n : {}),\n },\n )\n if (FIREBASE_FIRESTORE_EMULATOR_ENABLED) {\n // Where the server was told the emulator is, rather than a default\n // port another session's stack may hold (AGL-2834).\n const emulator = firestoreEmulatorHost()\n connectFirestoreEmulator(\n getFirestore(app),\n emulator.host,\n emulator.port,\n )\n } else {\n // The SDK never sweeps the multi-tab records the durable cache\n // strands in localStorage, and a full localStorage fails the whole\n // Firestore client — see `firestore-shared-client-state.ts`.\n void pruneSharedClientStateFor(firestoreCacheClass, app)\n // Only the durable multi-tab cache can be locked by another tab,\n // so only it gets the lease check after a stalled recovery.\n if (firestoreCacheClass === 'durable' && persistencePrefix && databaseName) {\n markMultiTabFirestore(getFirestore(app), databaseName)\n // A visible tab opened while a background tab holds the shared\n // cache's lease takes the lease at boot instead of routing every\n // query through the background tab until its lease lapses\n // (AGL-3660). In initializeFirestore's task: its first step\n // snapshots the other tabs before this tab's client can start.\n void startFirestoreTabHandoff(getFirestore(app), persistencePrefix)\n } else if (authPersistence === 'durable' && databaseName) {\n // A durable origin's tab on the memory cache. If that is because a\n // tab saw the shared cache locked, read the lease once, read-only,\n // so the record lasts only as long as the lock (AGL-4090).\n void confirmSharedCacheLock(databaseName)\n }\n }\n } catch {\n // already initialized (e.g. HMR reset the module flag) — getFirestore() returns the existing instance\n } finally {\n firestoreInitialized.add(appName)\n }\n }\n const firestore = getFirestore(app)\n\n if (!connectedAuth) {\n try {\n if (FIREBASE_AUTH_EMULATOR_ENABLED) {\n // The emulator the server was started with (AGL-2834).\n connectAuthEmulator(auth, authEmulatorUrl())\n }\n connectedAuth = true\n } catch (error) {\n console.error(error)\n }\n }\n // App Check must be skipped under the emulators: there is no App\n // Check emulator, so ReCaptcha would hit the real backend and its\n // 403s break emulator auth (the AGL-216 emulator sessions hit this).\n if (\n !FIREBASE_AUTH_EMULATOR_ENABLED &&\n !FIREBASE_FIRESTORE_EMULATOR_ENABLED\n ) {\n // No site key means no provider (AGL-2049). Registering one built on\n // `undefined` does not throw — it fails asynchronously inside the SDK,\n // where the catch below cannot see it — so this has to be a pre-check.\n const siteKey = appCheckSiteKey()\n if (!siteKey) {\n console.warn(APP_CHECK_KEY_MISSING_MESSAGE)\n } else {\n try {\n initializeAppCheck(app, {\n provider: new ReCaptchaV3Provider(siteKey),\n isTokenAutoRefreshEnabled: true,\n })\n // The widget renders into the SDK's <body> div only once Google's\n // script loads; a body cleared before then (hydration fallback,\n // global-error) made that render throw unhandled.\n keepAppCheckRecaptchaContainer(app.name)\n } catch (error) {\n console.error(error)\n }\n }\n }\n // Remote Config (AGL-228): release-flag delivery. Browser-only like\n // analytics; consumers set defaultConfig before their first getValue so\n // gating never blocks on the network.\n let remoteConfig: RemoteConfig\n try {\n remoteConfig = getRemoteConfigInstance(app)\n remoteConfig.settings.minimumFetchIntervalMillis =\n process.env.NODE_ENV === 'production' ? 3_600_000 : 60_000\n } catch (error) {\n console.error(error)\n }\n\n return { app, firestore, auth, remoteConfig }\n}\n\n/**\n * Services booted before React rendered anything, waiting for the provider to\n * adopt them (AGL-3660).\n *\n * The provider builds its services in its first render, and on the console\n * that render comes late: after every chunk of the route has executed, after\n * hydration, and after the `NoSsr` boundary above it has committed its\n * fallback and rendered again. Auth's persistence read and `accounts:lookup`,\n * and App Check's reCAPTCHA chain (script, script, iframe, token exchange),\n * which Auth AND Firestore requests both wait on whenever the cached App Check\n * token has expired, only started then. None of it depends on React, so a\n * surface that knows its config at module scope can start it there.\n *\n * Taken once, by the first provider that renders with the same app name and\n * persistence class; any later mount boots exactly as it always did. A\n * mismatched key is never adopted, so a preboot cannot hand a provider a\n * different persistence class than the one it was given.\n */\nconst prebooted = new Map<string, FirebaseCoreServices>()\nconst prebootKey = (appName: string, authPersistence: AuthPersistenceClass) =>\n `${appName}|${authPersistence}`\n\n/**\n * Start Firebase for this document now rather than at the provider's first\n * render. Browser only, once per app name and persistence class, and it never\n * throws: a failure here leaves the provider to boot as it always did.\n *\n * The Analytics consent gate is NOT read here (the provider reads it), so the\n * gate's module-scope registration does not have to precede this call.\n */\nexport function prebootFirebaseServices(options: {\n firebaseConfig: FirebaseOptions\n appName: string\n authPersistence?: AuthPersistenceClass\n}): void {\n if (typeof window === 'undefined') return\n const { firebaseConfig, appName, authPersistence = 'durable' } = options\n const key = prebootKey(appName, authPersistence)\n if (prebooted.has(key)) return\n try {\n prebooted.set(key, bootFirebaseCore(firebaseConfig, appName, authPersistence))\n } catch (error) {\n console.error(error)\n }\n}\n\nfunction takePrebootedFirebaseCore(\n appName: string,\n authPersistence: AuthPersistenceClass,\n): FirebaseCoreServices | undefined {\n const key = prebootKey(appName, authPersistence)\n const core = prebooted.get(key)\n if (core) prebooted.delete(key)\n return core\n}\n\nexport function FirebaseServicesProvider(props: FirebaseServicesProviderProps) {\n const { firebaseConfig, appName, authPersistence = 'durable', children } = props\n const servicesRef = useRef<FirebaseServices | undefined>(undefined)\n\n if (!servicesRef.current) {\n const core =\n takePrebootedFirebaseCore(appName, authPersistence) ??\n bootFirebaseCore(firebaseConfig, appName, authPersistence)\n // `initializeAnalytics`, not `getAnalytics`, for exactly one reason: it is\n // the only form that can pass `config`, and `send_page_view: false` is the\n // only way to stop the SDK's own startup `page_view` (AGL-1643).\n //\n // Booting Analytics issues `gtag('config', <id>, configProperties)`, and\n // the vendored SDK's own comment on that line reads \"This will trigger a\n // page_view event unless 'send_page_view' is set to false in\n // configProperties\". `getAnalytics(app)` passes no config at all, so the\n // key was never there and the hit always fired — on top of the manual\n // `page_view` the console's layout sends on mount. Two hits, one page.\n //\n // The SDK's is the one suppressed rather than the layout's, and the\n // direction is the whole decision: the SDK fires ONCE per document load,\n // while the layout fires on mount AND on every `usePathname` change. In a\n // client-routed app the layout's is a superset — killing it instead would\n // have left every in-app navigation unreported, halving console pageviews\n // rather than correcting them, and the reports would have looked fine.\n //\n // Nothing else about attribution moves: the surviving hit is sent from the\n // same document at mount, so `document.referrer` — which gtag resolves for\n // `page_referrer` itself, and which is what carries marketing traffic\n // source into the session — is still the external referrer at that moment.\n //\n // Re-entry is safe *only* while the options match. `initializeAnalytics`\n // returns the existing instance when they deep-equal the first call's and\n // throws `already-initialized` otherwise — and the options can be made to\n // differ by things no call site here controls (AGL-1979):\n //\n // * anything that touches the analytics provider WITHOUT options first\n // initializes it with `{}`. `getAnalytics()` is the obvious one, but\n // `@firebase/remote-config` reaches the same code path on its own —\n // `addExperimentToAnalytics` calls `analyticsProvider.getImmediate({\n // optional: true })`, and `optional` only suppresses the throw, it\n // does not stop the initialization.\n // * in dev, a module instance carrying a PREVIOUS version of these\n // options (this config changed under AGL-1857) surviving a Fast\n // Refresh alongside the new one.\n //\n // Once that happens the conflict is permanent for the document: every\n // later call throws, so without the fallback below `analytics` stayed\n // undefined forever and the next consumer — `logEvent(analytics, …)` —\n // read `.app` off it and threw a TypeError two frames away, which is how\n // this surfaced (top Cloud Error Reporting group, and reproduced live on\n // app.aglyn.com).\n //\n // `getAnalytics(app)` is the remedy the SDK's own error message names. It\n // cannot cost us the config on a healthy document: it only runs after\n // `initializeAnalytics` threw, and on a first init that throw can only be\n // `no-app-id` / `no-api-key` / `already-exists`, none of which\n // `getAnalytics` can rescue either — it re-throws and we fall through to\n // an undefined instance, which every consumer must now tolerate.\n // `content_group: 'console'` (AGL-1857) rides the same config: it is the\n // first-class GA4 axis that separates console traffic from `marketing`\n // (stamped by the tenant runtime on aglyn.com's own tag) and `docs`\n // (stamped by the Docusaurus head snippet) in standard reports, without\n // reaching for the Hostname dimension. The console is this provider's\n // only consumer, verified by grep — the tenant runtime builds its tag in\n // `site-analytics.tsx` and never passes through here.\n //\n // AND NOT AT ALL outside a real production deployment (AGL-2067). This\n // provider used to boot Analytics unconditionally, while\n // `apps/console/.env.development.local` points at the PRODUCTION\n // measurement id — so every `next dev` session and every Vercel preview\n // build produced genuine `session_start` / `first_visit` / `page_view`\n // hits in the live property. Not a theory: the archived Marketing\n // property's entire year-to-date history is 30 views / 6 users, ~24 of\n // them `/signin` on preview urls (docs/ANALYTICS.md).\n //\n // Not initialized rather than initialized-and-suppressed, because a\n // resident tag reports on its own — AGL-1608 is the same lesson from the\n // consent side. `useAnalytics()` returning undefined is already a\n // supported state everywhere (AGL-1979), which is what makes this a\n // two-line gate instead of an audit.\n //\n // `analyticsMayEmit` leans LOUD on an unknown deployment: a self-hosted\n // build points at the operator's own Firebase project and their own GA\n // property, and silencing a customer's analytics to protect ours is the\n // worse failure. See the module for the escape hatch.\n //\n // AND NOT while a registered consent gate says no (AGL-1498 posture,\n // applied to Aglyn's own console). `analyticsForConsentState` is where\n // both conditions and the boot itself now live, because the boot has to\n // be repeatable: a visitor whose region has not resolved yet is undecided\n // at this instant and may be granted a moment later, and a visitor who\n // withdraws mid-session has to lose the instance without the page\n // reloading. See the effect below.\n //\n // SCOPE. This is the console's tag and only the console's:\n // `CONSOLE_ANALYTICS_OPTIONS`, `content_group: 'console'`, and this\n // provider's analytics branch has no other consumer (the tenant runtime\n // builds its tag in `site-analytics.tsx` and never passes through here).\n // Customer sites keep the AGL-1498 gate and the host's own\n // `consent.mode`; nothing here reaches them.\n const initialAnalytics = analyticsForConsentState(core.app)\n\n servicesRef.current = {\n ...core,\n analytics: initialAnalytics,\n authPersistence,\n }\n }\n\n const services = servicesRef.current\n\n // The consent gate's other half: the verdict can CHANGE within one document,\n // in both directions, and everything else in this provider is built exactly\n // once by design.\n //\n // Deferred grant. A visitor with no stored record is undecided at the\n // instant this provider first renders, because resolving them needs the\n // region endpoint and that is a network call. Outside the prior-consent\n // regions the answer is implied consent, and it lands a few hundred\n // milliseconds later — same document, so `document.referrer` is still the\n // external referrer and the pageview's attribution is unaffected. Without\n // this, \"the gate is synchronous\" would have quietly meant \"the rest of the\n // world is never measured on a first visit\".\n //\n // Withdrawal. Dropping the instance unmounts every binding hung off it,\n // which is what unregisters the analytics transport — after that\n // `deliver()` falls through to `window.gtag`, and the shared consent writer\n // has already set `ga-disable-<id>` and sent a denied `consent update` on\n // that exact tag (AGL-1608). The resident tag cannot be unloaded; it can be\n // made to send nothing, and both halves are needed because either alone\n // leaks — enhanced measurement fires with no call site at all.\n const [analytics, setAnalytics] = useState<Analytics | undefined>(\n () => services.analytics,\n )\n useEffect(() => {\n const sync = () => setAnalytics(analyticsForConsentState(services.app))\n // Once on mount as well as on the event: the priming pass can resolve a\n // visitor between this provider's render and this effect, and the event it\n // dispatched then had no listener yet.\n sync()\n window.addEventListener(VISITOR_CONSENT_CHANGED_EVENT, sync)\n return () =>\n window.removeEventListener(VISITOR_CONSENT_CHANGED_EVENT, sync)\n }, [services])\n\n // Identity changes only when the tag comes or goes, so a consent-stable\n // document re-renders nothing.\n const value = useMemo(\n () =>\n services.analytics === analytics ? services : { ...services, analytics },\n [services, analytics],\n )\n\n return (\n <FirebaseServicesContext.Provider value={value}>\n {children}\n </FirebaseServicesContext.Provider>\n )\n}\nFirebaseServicesProvider.displayName = 'FirebaseServicesProvider'\n\nfunction useFirebaseServices(): FirebaseServices {\n const services = useContext(FirebaseServicesContext)\n if (!services) {\n throw new Error(\n 'Firebase hooks must be used within a <FirebaseServicesProvider>',\n )\n }\n return services\n}\n\nexport function useFirebaseApp(): FirebaseApp {\n return useFirebaseServices().app\n}\nexport function useFirestore(): Firestore {\n return useFirebaseServices().firestore\n}\nexport function useAuth(): Auth {\n return useFirebaseServices().auth\n}\n/**\n * The persistence class the provider's `Auth` was created with (AGL-1379).\n *\n * Read it — never re-derive it — when building a **second** Firebase app on\n * the same origin, so the second instance cannot end up more persistent than\n * the first. `apps/console/hooks/use-presence.ts` is the existing case.\n */\nexport function useAuthPersistence(): AuthPersistenceClass {\n return useFirebaseServices().authPersistence\n}\nexport function useAnalytics(): Analytics {\n return useFirebaseServices().analytics\n}\nexport function useRemoteConfig(): RemoteConfig {\n return useFirebaseServices().remoteConfig\n}\n\n/**\n * Replaces reactfire's `useUser()`. Reactfire subscribes via\n * `onIdTokenChanged` rather than `onAuthStateChanged` so fields like\n * `emailVerified` stay live across token refresh (e.g. after\n * `user.reload()` post-email-verification), not just sign-in/out — matched\n * here for behavioral parity.\n *\n * THREE states, not two (AGL-1261): `undefined` = auth has not resolved yet,\n * `null` = resolved, signed OUT, a `User` = resolved, signed in. This used to\n * collapse the emitted `null` into `undefined`, which made \"signed out\" and\n * \"still loading\" the same value — a state that, for a signed-out visitor,\n * never left \"loading\". `useSessionCookie` gates its whole body on\n * `user === undefined`, so its silent restore from the shared `__session`\n * cookie could never run: the cookie exchange returned a valid custom token\n * and nothing ever asked for it.\n */\nexport function useUser(): { data: User | null | undefined } {\n const auth = useAuth()\n const [user, setUser] = useState<User | null | undefined>(\n auth.currentUser ?? undefined,\n )\n\n useEffect(() => {\n return onIdTokenChanged(auth, (nextUser) => {\n // `?? null`, never `?? undefined` — see the note above.\n setUser(nextUser ?? null)\n })\n }, [auth])\n\n return { data: user }\n}\n\nexport interface SigninCheckResult {\n signedIn: boolean\n user: User | null\n}\n\n/** Replaces reactfire's `useSigninCheck()` — same `onIdTokenChanged` basis as `useUser()`. */\nexport function useSigninCheck(): {\n status: 'loading' | 'success' | 'error'\n data: SigninCheckResult | undefined\n error: Error | undefined\n} {\n const auth = useAuth()\n const [status, setStatus] = useState<'loading' | 'success' | 'error'>('loading')\n const [data, setData] = useState<SigninCheckResult | undefined>(undefined)\n const [error, setError] = useState<Error | undefined>(undefined)\n\n useEffect(() => {\n return onIdTokenChanged(\n auth,\n (user) => {\n setStatus('success')\n setError(undefined)\n setData({ signedIn: !!user, user: user ?? null })\n },\n (err) => {\n setStatus('error')\n setError(err)\n },\n )\n }, [auth])\n\n return { status, data, error }\n}\n"],"names":["getApps","initializeApp","getAnalytics","getAnalyticsInstance","initializeAnalytics","initializeAnalyticsInstance","initializeAppCheck","ReCaptchaV3Provider","analyticsMayEmit","pushPlatformConsentDefault","VISITOR_CONSENT_CHANGED_EVENT","connectAuthEmulator","onIdTokenChanged","connectFirestoreEmulator","getFirestore","initializeFirestore","getRemoteConfig","getRemoteConfigInstance","createContext","useContext","useEffect","useMemo","useRef","useState","FIREBASE_AUTH_EMULATOR_ENABLED","FIREBASE_FIRESTORE_EMULATOR_ENABLED","APP_CHECK_KEY_MISSING_MESSAGE","appCheckSiteKey","authEmulatorUrl","firestoreEmulatorHost","createAuthInstance","firestoreCacheClassFor","localCacheFor","pruneSharedClientStateFor","keepAppCheckRecaptchaContainer","confirmSharedCacheLock","markMultiTabFirestore","firestorePersistencePrefix","startFirestoreTabHandoff","FirebaseServicesContext","undefined","firestoreInitialized","Set","connectedAuth","isAutomatedChromeSession","navigator","webdriver","CONSOLE_ANALYTICS_OPTIONS","config","send_page_view","content_group","analyticsConsentGate","setAnalyticsConsentGate","gate","analyticsConsentAllows","analyticsByApp","WeakMap","bootAnalytics","app","existing","get","analytics","window","error","console","fallbackError","set","analyticsForConsentState","bootFirebaseCore","firebaseConfig","appName","authPersistence","find","name","auth","persistencePrefix","options","projectId","databaseName","firestoreCacheClass","has","experimentalForceLongPolling","localCache","emulator","host","port","add","firestore","siteKey","warn","provider","isTokenAutoRefreshEnabled","remoteConfig","settings","minimumFetchIntervalMillis","process","env","NODE_ENV","prebooted","Map","prebootKey","prebootFirebaseServices","key","takePrebootedFirebaseCore","core","delete","FirebaseServicesProvider","props","children","servicesRef","current","initialAnalytics","services","setAnalytics","sync","addEventListener","removeEventListener","value","Provider","displayName","useFirebaseServices","Error","useFirebaseApp","useFirestore","useAuth","useAuthPersistence","useAnalytics","useRemoteConfig","useUser","user","setUser","currentUser","nextUser","data","useSigninCheck","status","setStatus","setData","setError","signedIn","err"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAEA,SAGEA,OAAO,EACPC,aAAa,QACR,eAAc;AACrB,SAEEC,gBAAgBC,oBAAoB,EACpCC,uBAAuBC,2BAA2B,QAC7C,qBAAoB;AAC3B,SAASC,kBAAkB,EAAEC,mBAAmB,QAAQ,qBAAoB;AAC5E,SAASC,gBAAgB,QAAQ,+CAA8C;AAC/E,SAASC,0BAA0B,QAAQ,kDAAiD;AAC5F,SAASC,6BAA6B,QAAQ,yCAAwC;AACtF,SAEEC,mBAAmB,EACnBC,gBAAgB,QAEX,gBAAe;AACtB,SAEEC,wBAAwB,EACxBC,YAAY,EACZC,mBAAmB,QACd,qBAAoB;AAC3B,SAEEC,mBAAmBC,uBAAuB,QACrC,yBAAwB;AAC/B,SACEC,aAAa,EACbC,UAAU,EACVC,SAAS,EACTC,OAAO,EACPC,MAAM,EACNC,QAAQ,QAEH,QAAO;AACd,SACEC,8BAA8B,EAC9BC,mCAAmC,QAC9B,2BAA0B;AACjC,SACEC,6BAA6B,EAC7BC,eAAe,QACV,qCAAiC;AACxC,SACEC,eAAe,EACfC,qBAAqB,QAChB,6CAAyC;AAChD,SAEEC,kBAAkB,QACb,wBAAoB;AAC3B,SACEC,sBAAsB,EACtBC,aAAa,EACbC,yBAAyB,QACpB,uBAAmB;AAC1B,SAASC,8BAA8B,QAAQ,qCAAiC;AAChF,SACEC,sBAAsB,EACtBC,qBAAqB,QAChB,gCAA4B;AACnC,SAASC,0BAA0B,QAAQ,qCAAiC;AAC5E,SAASC,wBAAwB,QAAQ,6BAAyB;AA0GlE,MAAMC,wCAA0BrB,cAA4CsB;AAE5E,yEAAyE;AACzE,kEAAkE;AAClE,oBAAoB;AACpB,EAAE;AACF,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;IAChE,MAAM,CAACuB,OAAO2E,SAAS,GAAGnH,SAA4BiB;IAEtDpB,UAAU;QACR,OAAOR,iBACL8D,MACA,CAACuD;YACCO,UAAU;YACVE,SAASlG;YACTiG,QAAQ;gBAAEE,UAAU,CAAC,CAACV;gBAAMA,IAAI,EAAEA,eAAAA,OAAQ;YAAK;QACjD,GACA,CAACW;YACCJ,UAAU;YACVE,SAASE;QACX;IAEJ,GAAG;QAAClE;KAAK;IAET,OAAO;QAAE6D;QAAQF;QAAMtE;IAAM;AAC/B"}
1
+ {"version":3,"sources":["../../../../../../../../../libs/tenant/feature/instance/src/lib/hooks/firebase/firebase-services.tsx"],"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'use client'\n\nimport {\n type FirebaseApp,\n type FirebaseOptions,\n getApps,\n initializeApp,\n} from 'firebase/app'\nimport {\n type Analytics,\n getAnalytics as getAnalyticsInstance,\n initializeAnalytics as initializeAnalyticsInstance,\n} from 'firebase/analytics'\nimport { initializeAppCheck, ReCaptchaV3Provider } from 'firebase/app-check'\nimport { analyticsMayEmit } from '@aglyn/aglyn/app-utils/analytics-environment'\nimport { pushPlatformConsentDefault } from '@aglyn/aglyn/app-utils/platform-consent-default'\nimport { VISITOR_CONSENT_CHANGED_EVENT } from '@aglyn/aglyn/app-utils/visitor-consent'\nimport {\n type Auth,\n connectAuthEmulator,\n onIdTokenChanged,\n type User,\n} from 'firebase/auth'\nimport {\n type Firestore,\n connectFirestoreEmulator,\n getFirestore,\n initializeFirestore,\n} from 'firebase/firestore'\nimport {\n type RemoteConfig,\n getRemoteConfig as getRemoteConfigInstance,\n} from 'firebase/remote-config'\nimport {\n createContext,\n useContext,\n useEffect,\n useMemo,\n useRef,\n useState,\n type ReactNode,\n} from 'react'\nimport {\n FIREBASE_AUTH_EMULATOR_ENABLED,\n FIREBASE_FIRESTORE_EMULATOR_ENABLED,\n} from '@aglyn/shared-data-enums'\nimport {\n APP_CHECK_KEY_MISSING_MESSAGE,\n appCheckSiteKey,\n} from '../../constants/firebase-config'\nimport {\n authEmulatorUrl,\n firestoreEmulatorHost,\n} from '../../constants/firebase-emulator-hosts'\nimport {\n type AuthPersistenceClass,\n createAuthInstance,\n} from './auth-persistence'\nimport {\n firestoreCacheClassFor,\n localCacheFor,\n pruneSharedClientStateFor,\n} from './firestore-cache'\nimport { keepAppCheckRecaptchaContainer } from './app-check-recaptcha-container'\nimport type { ListenHandle } from '../helpers/listen-confirmation'\nimport {\n confirmSharedCacheLock,\n markMultiTabFirestore,\n} from './firestore-multitab-wedge'\nimport { firestorePersistencePrefix } from './firestore-shared-client-state'\nimport { startFirestoreTabHandoff } from './firestore-tab-handoff'\n\n/**\n * Drop-in replacement for reactfire's `ObservableStatus<T>` — reactfire is\n * unmaintained against firebase majors past v9, but its shape is preserved\n * here so `helpers/use-doc.ts`'s already-battle-tested onSnapshot+retry\n * implementation (AGL-216/223) didn't need to change.\n */\nexport interface ObservableStatus<T> {\n status: 'loading' | 'error' | 'success'\n hasEmitted: boolean\n isComplete: boolean\n data: T\n error: Error | undefined\n firstValuePromise: Promise<void>\n /**\n * The emitted `data` includes local writes the server has NOT\n * acknowledged (`snapshot.metadata.hasPendingWrites`).\n *\n * Carried rather than dropped because a caller cannot otherwise tell \"the\n * store holds this\" from \"my browser holds this\". `persistentLocalCache`\n * replays a queued write into the very first snapshot after a reload, so a\n * caller that treats every snapshot as authoritative will adopt its own\n * unacknowledged edit as the saved state — which is how the besigner ended\n * up unable to save real changes (AGL-1262).\n */\n hasPendingWrites: boolean\n /**\n * The emitted `data` came from the local cache and the server has NOT\n * confirmed it (`snapshot.metadata.fromCache`).\n *\n * Carried because it is the only per-listener ground truth about\n * freshness the SDK offers, and the console needs it (AGL-1066). Under\n * `persistentLocalCache` a listener whose server listen is being REFUSED\n * still emits cached snapshots and still reports `status: 'success'` —\n * the retry budget is reset by each cached emission and never spends, so\n * `status` can never reveal the fault (see\n * `use-firestore-collection-cached-retry.spec.ts`).\n *\n * Prefer this over `session-health`'s `staleSession` for anything that\n * asks \"is what I am looking at live?\". `staleSession` is a heuristic\n * needing two denied collections inside a window, and it is unreachable\n * on listener-only pages; this is a fact about THIS listener, costs\n * nothing, and clears itself the instant a server snapshot lands.\n */\n fromCache: boolean\n /**\n * The server has REFUSED this listen for longer than the retry budget, and\n * no server snapshot has arrived since (AGL-1066).\n *\n * `fromCache` says \"unconfirmed\", which is also true offline and true for\n * the first snapshot of a perfectly healthy load. This says \"refused\" —\n * only `permission-denied` counts it, and it takes a whole budget's worth\n * in a row, so it cannot fire offline and cannot fire on the AGL-216/217\n * post-sign-in token race.\n *\n * It is what `status` would say if the retry budget were spendable. It is\n * carried separately because correcting `status` in place would blank\n * every surface that renders cached data through an `error` branch — see\n * the note on `attempt = 0` in `use-firestore-collection`.\n */\n serverDenied: boolean\n /**\n * This hook's listener, for a guarded save seeded from `data` to wait on\n * alone (`writeGuardedBySeed`'s `listen`, AGL-4135). Stable for the life of\n * the hook.\n */\n listen: ListenHandle\n}\n\n/** Replaces reactfire's `ReactFireOptions<T>` — drops the `suspense` field, which was never read. */\nexport interface FirestoreDocOptions<T> {\n idField?: string\n initialData?: T\n}\n\n/**\n * The Firebase products this provider builds, and therefore the ones every\n * page that renders it downloads.\n *\n * ⛔ NO Realtime Database and NO Cloud Storage (AGL-2706). Both were built\n * here and published as `useDatabase()` / `useStorage()`, and neither hook had\n * a single caller anywhere in the repo — so `@firebase/database` (125.9 KB\n * raw) and `@firebase/storage` (13.9 KB) were in the first load of every\n * console route to satisfy a context field nothing read.\n *\n * Realtime Database IS used, by `apps/console/hooks/use-presence.ts` and\n * `use-coediting.ts` — on their own Firebase app, with their own\n * `getDatabase`, behind the editor routes that need presence. That is the\n * shape to copy if a surface needs one of these: reach for the product where\n * the feature is, not in the provider every page mounts. A field here is paid\n * for by every route, used or not.\n */\ninterface FirebaseServices {\n app: FirebaseApp\n firestore: Firestore\n auth: Auth\n analytics: Analytics\n remoteConfig: RemoteConfig\n /**\n * The persistence class `auth` was actually created with (AGL-1379).\n *\n * Published so a **second** auth instance derives its class from the\n * primary rather than re-deciding it. `apps/console/hooks/use-presence.ts`\n * builds its own Firebase app and its own `Auth`; before this it took the\n * SDK default unconditionally, so configuring only the provider would have\n * left presence persisting a refresh token on an origin the provider had\n * just been careful not to persist one on.\n */\n authPersistence: AuthPersistenceClass\n}\n\nconst FirebaseServicesContext = createContext<FirebaseServices | undefined>(undefined)\n\n// Module-scope guards so HMR / remounts don't re-run emulator connection\n// (which throws if called twice) or double-initialize Firestore's\n// persistent cache.\n//\n// Firestore's is keyed by app NAME, not a bare boolean (AGL-1456): Firestore\n// initialization is once-per-app, so a module-global flag made the FIRST app\n// to mount decide for every later one — a second app would silently skip\n// `initializeFirestore` and take SDK defaults. That mattered the moment the\n// cache stopped being the same on every host.\nconst firestoreInitialized = new Set<string>()\nlet connectedAuth = false\n\n/**\n * True when THIS Chrome instance is under WebDriver automation control\n * (Puppeteer, Playwright, Selenium, or a raw CDP client) — never true for a\n * person's own browser.\n *\n * The `initializeFirestore` call below already documents the fault this\n * exists for: \"the emulator's WebChannel streaming misbehaves in automated\n * Chrome — listeners serve the initial empty from-cache snapshot and the\n * server sync never arrives\" (AGL-217). That mitigation only reaches\n * `FIREBASE_FIRESTORE_EMULATOR_ENABLED`, so an automated session against a\n * REAL, deployed backend — a browser-automation agent driving a live\n * console, which is exactly what `navigator.webdriver` detects — stayed\n * exposed. `getDocs`/`getDoc` and `onSnapshot` all resolve over the same\n * Watch stream internally, so a one-shot read wedges exactly like a listener\n * does: no error, nothing to catch, `loading` simply never gets its\n * settling event. That is the Media Library grid spinning on \"Loading\n * media…\" indefinitely with a perfectly healthy account and a perfectly\n * healthy network.\n *\n * `undefined` during SSR reads as `false` — `navigator` does not exist in\n * Node, and a server render can only ever produce the auto-detected\n * transport, never the forced one.\n */\nconst isAutomatedChromeSession = (): boolean =>\n typeof navigator !== 'undefined' && navigator.webdriver === true\n\n/**\n * The console tag's gtag config — ONE object, at module scope, deliberately\n * (AGL-1979).\n *\n * `initializeAnalytics(app, options)` throws `already-initialized` unless the\n * options `deepEqual` the ones the instance was first created with, and the\n * provider re-enters this block on every mount, every StrictMode double\n * invoke and every Fast Refresh. A fresh object literal per call survives\n * that only by *value*; a shared constant survives it by *identity*, which is\n * the first branch of the SDK's own comparison and cannot drift when someone\n * edits one call site and not another.\n *\n * ⚠️ The SDK MUTATES this object: `_initializeAnalytics` reads `options.config`\n * and writes `origin`, `update` and the installation id onto it in place.\n * That is precisely why sharing it is safe rather than dangerous — the object\n * the provider holds and the object the SDK stored are the same one, so they\n * cannot disagree.\n */\nconst CONSOLE_ANALYTICS_OPTIONS = {\n config: { send_page_view: false, content_group: 'console' },\n}\n\n/**\n * A surface's answer to \"may an analytics tag exist for this visitor at all?\".\n *\n * Registered from the app, at module scope, in the same shape as\n * `setFirestoreSessionReporters` and `setStaleSessionCheck` — and for a\n * sharper version of the same reason. This is consulted during the provider's\n * FIRST render, before any effect anywhere has run, so a gate installed from\n * an effect would arrive after the decision it exists to make.\n *\n * Answering `false` means the SDK is never asked to initialize: `gtag.js` is\n * never fetched, `window.gtag` never comes into existence, and the shared\n * `deliver()` in `analytics-events.ts` — whose fallback IS `window.gtag` —\n * therefore has nowhere to put a hit. That is the difference between a gate\n * and a suppression, and it is the difference AGL-1608 paid for: a resident\n * tag reports on its own, through enhanced measurement, whatever any flag\n * says afterwards.\n */\nexport type AnalyticsConsentGate = () => boolean\n\nlet analyticsConsentGate: AnalyticsConsentGate | null = null\n\n/**\n * Install the consent gate for this document, or clear it with `null`.\n *\n * UNREGISTERED MEANS ALLOWED, which is deliberate and is the only default that\n * is safe here. The tenant runtime does not use this provider's analytics\n * branch at all (it builds its own tag in `site-analytics.tsx`, behind the\n * AGL-1498 gate), and a self-hosted console points at the operator's own GA\n * property — silencing an operator's analytics because Aglyn's own surface\n * grew a gate is a failure they cannot diagnose. The surface that needs the\n * gate is the one that registers it.\n */\nexport function setAnalyticsConsentGate(\n gate: AnalyticsConsentGate | null,\n): void {\n analyticsConsentGate = gate\n}\n\n/** The gate's verdict, with an unregistered gate reading as \"allowed\". */\nfunction analyticsConsentAllows(): boolean {\n if (analyticsConsentGate === null) return true\n try {\n return analyticsConsentGate() === true\n } catch {\n // A gate that throws cannot be read as consent. Storage can throw in\n // private mode, and \"we could not tell\" is the one state this whole\n // mechanism resolves to \"no\".\n return false\n }\n}\n\n/**\n * The Analytics instance per Firebase app, so a re-boot after a consent change\n * hands back the tag that is already resident rather than asking the SDK for a\n * second one.\n *\n * `initializeAnalytics` is idempotent while the options match, so this is not\n * what makes re-entry safe — `CONSOLE_ANALYTICS_OPTIONS` being a shared\n * constant is. What this avoids is the noisy path: once anything has\n * initialized the provider with different options, every later call throws and\n * is logged, and a withdrawal followed by a re-grant would log it again.\n */\nconst analyticsByApp = new WeakMap<FirebaseApp, Analytics>()\n\n/**\n * Boot the console's Analytics tag, or return the one already booted.\n *\n * Extracted from the provider body so that \"when is the tag created\" and \"may\n * it be created\" are separable: the consent gate can defer this call to a\n * later render without the ordering below moving.\n */\nfunction bootAnalytics(app: FirebaseApp): Analytics | undefined {\n const existing = analyticsByApp.get(app)\n if (existing) return existing\n let analytics: Analytics\n // The region-conditional consent default (AGL-1597), declared BEFORE the\n // SDK boots the tag. Ordering is the whole of it: a `default` read after\n // `config` is not a default, and the SDK issues `config` inside\n // `initializeAnalytics` on the next line. Pushing onto `dataLayer` here\n // works even though gtag.js is not loaded yet — the queue is what makes the\n // ordering expressible.\n //\n // Still declared even though the gate above has already said yes, and the\n // two are not redundant. The gate answers \"may a tag exist\"; the default\n // answers \"what may the tag that does exist do\", per region, from its very\n // first hit. Ad storage stays denied everywhere on this surface.\n pushPlatformConsentDefault(\n typeof window === 'undefined' ? null : (window as never),\n )\n try {\n analytics = initializeAnalyticsInstance(app, CONSOLE_ANALYTICS_OPTIONS)\n } catch (error) {\n console.error(error)\n try {\n // Already initialized by someone else, with someone else's options:\n // take THAT instance rather than leaving consumers with nothing. The\n // tag it is attached to was configured without `send_page_view: false`\n // and without `content_group`, so this session reports a duplicate\n // startup page_view and an unstamped surface — degraded, and loudly so,\n // instead of silently dead.\n analytics = getAnalyticsInstance(app)\n } catch (fallbackError) {\n console.error(fallbackError)\n }\n }\n if (analytics) analyticsByApp.set(app, analytics)\n return analytics\n}\n\n/**\n * The tag this document may have right now: none outside a real production\n * deployment, none while consent is absent, otherwise the booted instance.\n */\nfunction analyticsForConsentState(app: FirebaseApp): Analytics | undefined {\n if (!analyticsMayEmit()) return undefined\n if (!analyticsConsentAllows()) return undefined\n return bootAnalytics(app)\n}\n\nexport interface FirebaseServicesProviderProps {\n firebaseConfig: FirebaseOptions\n appName: string\n /**\n * How much of *anything* this origin may keep on disk. Defaults to\n * `durable`, which is what every host serving this provider today is:\n * `*.aglyn.com` and `*.aglyn.app`, whose DNS we own and whose 14-day\n * session is the product.\n *\n * A **custom console domain** (AGL-1099c) must pass `ephemeral`. That is\n * the whole reason this is a prop rather than a constant: the class differs\n * per origin, not per build, and the decision belongs to whoever knows\n * which origin is being served.\n *\n * **It governs two things, and the name only names one.** It selects the\n * `Auth` persistence class (AGL-1379) *and* the Firestore `localCache`\n * (AGL-1456) — because both answer the same question about the same origin,\n * and splitting them into two props is precisely how the cache came to be\n * unconditional while the credential was hardened. See `firestore-cache.ts`.\n */\n authPersistence?: AuthPersistenceClass\n children?: ReactNode\n}\n\n/** The services every surface boots, before the per-document analytics verdict. */\ninterface FirebaseCoreServices {\n app: FirebaseApp\n firestore: Firestore\n auth: Auth\n remoteConfig: RemoteConfig\n}\n\n/**\n * Create (or adopt) the app, Auth, Firestore, App Check and Remote Config for\n * one Firebase app: everything the provider used to build in its first render\n * except Analytics, whose consent verdict belongs to the render that reads it.\n */\nfunction bootFirebaseCore(\n firebaseConfig: FirebaseOptions,\n appName: string,\n authPersistence: AuthPersistenceClass,\n): FirebaseCoreServices {\n const app =\n getApps().find((existing) => existing.name === appName) ??\n initializeApp(firebaseConfig, appName)\n // `durable` resolves to the same `getAuth(app)` this always called.\n const auth = createAuthInstance(app, authPersistence)\n\n // The durable cache's IndexedDB database, `<persistence prefix>main`.\n const persistencePrefix = app.options?.projectId\n ? firestorePersistencePrefix(app.name, app.options.projectId)\n : undefined\n const databaseName = persistencePrefix && `${persistencePrefix}main`\n // The origin's class, unless this tab fell back to the memory cache\n // because another tab locked the shared one (AGL-3428), or a tab has just\n // seen that lock (AGL-4090). Firestore only: `auth` above keeps the\n // origin's class.\n const firestoreCacheClass = firestoreCacheClassFor(authPersistence, databaseName)\n if (!firestoreInitialized.has(appName)) {\n try {\n // Under the emulator (dev/e2e only): force long-polling and skip\n // the persistent multi-tab cache. The emulator's WebChannel\n // streaming misbehaves in automated Chrome — listeners serve the\n // initial empty from-cache snapshot and the server sync never\n // arrives, which looks like \"empty pages with zero errors\"\n // (the AGL-217 mystery). Real traffic keeps the default transport\n // and persistent cache — except a WebDriver-controlled Chrome\n // against a real backend, which forces long-polling for the same\n // reason without giving up the cache (see `isAutomatedChromeSession`\n // below).\n //\n // ⚠️ CONSEQUENCE, and it will cost you hours if you do not know it\n // (AGL-1066): every stale-session/stale-cache fault is UNREPRODUCIBLE\n // locally through the app, because the cache that causes them is off\n // in exactly the configuration you would reach for to reproduce one.\n // A listener that keeps serving arbitrarily-old data while the server\n // refuses it, a `noDocument` tombstone that 404s a live host, the\n // retry budget that never spends because a cached emission resets it\n // — none of them can happen here. Test that behaviour with the unit\n // seams instead (`use-firestore-collection-cached-retry.spec.ts`\n // drives cached emissions and denials directly), or against a\n // deployed environment. Do NOT \"fix\" it by turning the cache on for\n // the emulator: the AGL-217 empty-pages-with-zero-errors mystery is\n // what that produces.\n initializeFirestore(\n app,\n FIREBASE_FIRESTORE_EMULATOR_ENABLED\n ? { experimentalForceLongPolling: true }\n : {\n // NOT unconditional (AGL-1456). `persistentLocalCache` writes\n // document bodies to this origin's IndexedDB, so on a custom\n // console domain it is the same exposure D6 removed from the\n // refresh token — see `firestore-cache.ts` for why one\n // declaration governs both.\n localCache: localCacheFor(firestoreCacheClass),\n // The real-backend half of the AGL-217 mitigation above: force\n // long-polling for a WebDriver-controlled Chrome even when it\n // is NOT talking to the emulator, because the WebChannel wedge\n // is a property of automated Chrome, not of which backend it\n // is automating against. Never true for a real visitor, so\n // production traffic keeps the SDK's own auto-detected\n // transport untouched.\n ...(isAutomatedChromeSession()\n ? { experimentalForceLongPolling: true }\n : {}),\n },\n )\n if (FIREBASE_FIRESTORE_EMULATOR_ENABLED) {\n // Where the server was told the emulator is, rather than a default\n // port another session's stack may hold (AGL-2834).\n const emulator = firestoreEmulatorHost()\n connectFirestoreEmulator(\n getFirestore(app),\n emulator.host,\n emulator.port,\n )\n } else {\n // The SDK never sweeps the multi-tab records the durable cache\n // strands in localStorage, and a full localStorage fails the whole\n // Firestore client — see `firestore-shared-client-state.ts`.\n void pruneSharedClientStateFor(firestoreCacheClass, app)\n // Only the durable multi-tab cache can be locked by another tab,\n // so only it gets the lease check after a stalled recovery.\n if (firestoreCacheClass === 'durable' && persistencePrefix && databaseName) {\n markMultiTabFirestore(getFirestore(app), databaseName)\n // A visible tab opened while a background tab holds the shared\n // cache's lease takes the lease at boot instead of routing every\n // query through the background tab until its lease lapses\n // (AGL-3660). In initializeFirestore's task: its first step\n // snapshots the other tabs before this tab's client can start.\n void startFirestoreTabHandoff(getFirestore(app), persistencePrefix)\n } else if (authPersistence === 'durable' && databaseName) {\n // A durable origin's tab on the memory cache. If that is because a\n // tab saw the shared cache locked, read the lease once, read-only,\n // so the record lasts only as long as the lock (AGL-4090).\n void confirmSharedCacheLock(databaseName)\n }\n }\n } catch {\n // already initialized (e.g. HMR reset the module flag) — getFirestore() returns the existing instance\n } finally {\n firestoreInitialized.add(appName)\n }\n }\n const firestore = getFirestore(app)\n\n if (!connectedAuth) {\n try {\n if (FIREBASE_AUTH_EMULATOR_ENABLED) {\n // The emulator the server was started with (AGL-2834).\n connectAuthEmulator(auth, authEmulatorUrl())\n }\n connectedAuth = true\n } catch (error) {\n console.error(error)\n }\n }\n // App Check must be skipped under the emulators: there is no App\n // Check emulator, so ReCaptcha would hit the real backend and its\n // 403s break emulator auth (the AGL-216 emulator sessions hit this).\n if (\n !FIREBASE_AUTH_EMULATOR_ENABLED &&\n !FIREBASE_FIRESTORE_EMULATOR_ENABLED\n ) {\n // No site key means no provider (AGL-2049). Registering one built on\n // `undefined` does not throw — it fails asynchronously inside the SDK,\n // where the catch below cannot see it — so this has to be a pre-check.\n const siteKey = appCheckSiteKey()\n if (!siteKey) {\n console.warn(APP_CHECK_KEY_MISSING_MESSAGE)\n } else {\n try {\n initializeAppCheck(app, {\n provider: new ReCaptchaV3Provider(siteKey),\n isTokenAutoRefreshEnabled: true,\n })\n // The widget renders into the SDK's <body> div only once Google's\n // script loads; a body cleared before then (hydration fallback,\n // global-error) made that render throw unhandled.\n keepAppCheckRecaptchaContainer(app.name)\n } catch (error) {\n console.error(error)\n }\n }\n }\n // Remote Config (AGL-228): release-flag delivery. Browser-only like\n // analytics; consumers set defaultConfig before their first getValue so\n // gating never blocks on the network.\n let remoteConfig: RemoteConfig\n try {\n remoteConfig = getRemoteConfigInstance(app)\n remoteConfig.settings.minimumFetchIntervalMillis =\n process.env.NODE_ENV === 'production' ? 3_600_000 : 60_000\n } catch (error) {\n console.error(error)\n }\n\n return { app, firestore, auth, remoteConfig }\n}\n\n/**\n * Services booted before React rendered anything, waiting for the provider to\n * adopt them (AGL-3660).\n *\n * The provider builds its services in its first render, and on the console\n * that render comes late: after every chunk of the route has executed, after\n * hydration, and after the `NoSsr` boundary above it has committed its\n * fallback and rendered again. Auth's persistence read and `accounts:lookup`,\n * and App Check's reCAPTCHA chain (script, script, iframe, token exchange),\n * which Auth AND Firestore requests both wait on whenever the cached App Check\n * token has expired, only started then. None of it depends on React, so a\n * surface that knows its config at module scope can start it there.\n *\n * Taken once, by the first provider that renders with the same app name and\n * persistence class; any later mount boots exactly as it always did. A\n * mismatched key is never adopted, so a preboot cannot hand a provider a\n * different persistence class than the one it was given.\n */\nconst prebooted = new Map<string, FirebaseCoreServices>()\nconst prebootKey = (appName: string, authPersistence: AuthPersistenceClass) =>\n `${appName}|${authPersistence}`\n\n/**\n * Start Firebase for this document now rather than at the provider's first\n * render. Browser only, once per app name and persistence class, and it never\n * throws: a failure here leaves the provider to boot as it always did.\n *\n * The Analytics consent gate is NOT read here (the provider reads it), so the\n * gate's module-scope registration does not have to precede this call.\n */\nexport function prebootFirebaseServices(options: {\n firebaseConfig: FirebaseOptions\n appName: string\n authPersistence?: AuthPersistenceClass\n}): void {\n if (typeof window === 'undefined') return\n const { firebaseConfig, appName, authPersistence = 'durable' } = options\n const key = prebootKey(appName, authPersistence)\n if (prebooted.has(key)) return\n try {\n prebooted.set(key, bootFirebaseCore(firebaseConfig, appName, authPersistence))\n } catch (error) {\n console.error(error)\n }\n}\n\nfunction takePrebootedFirebaseCore(\n appName: string,\n authPersistence: AuthPersistenceClass,\n): FirebaseCoreServices | undefined {\n const key = prebootKey(appName, authPersistence)\n const core = prebooted.get(key)\n if (core) prebooted.delete(key)\n return core\n}\n\nexport function FirebaseServicesProvider(props: FirebaseServicesProviderProps) {\n const { firebaseConfig, appName, authPersistence = 'durable', children } = props\n const servicesRef = useRef<FirebaseServices | undefined>(undefined)\n\n if (!servicesRef.current) {\n const core =\n takePrebootedFirebaseCore(appName, authPersistence) ??\n bootFirebaseCore(firebaseConfig, appName, authPersistence)\n // `initializeAnalytics`, not `getAnalytics`, for exactly one reason: it is\n // the only form that can pass `config`, and `send_page_view: false` is the\n // only way to stop the SDK's own startup `page_view` (AGL-1643).\n //\n // Booting Analytics issues `gtag('config', <id>, configProperties)`, and\n // the vendored SDK's own comment on that line reads \"This will trigger a\n // page_view event unless 'send_page_view' is set to false in\n // configProperties\". `getAnalytics(app)` passes no config at all, so the\n // key was never there and the hit always fired — on top of the manual\n // `page_view` the console's layout sends on mount. Two hits, one page.\n //\n // The SDK's is the one suppressed rather than the layout's, and the\n // direction is the whole decision: the SDK fires ONCE per document load,\n // while the layout fires on mount AND on every `usePathname` change. In a\n // client-routed app the layout's is a superset — killing it instead would\n // have left every in-app navigation unreported, halving console pageviews\n // rather than correcting them, and the reports would have looked fine.\n //\n // Nothing else about attribution moves: the surviving hit is sent from the\n // same document at mount, so `document.referrer` — which gtag resolves for\n // `page_referrer` itself, and which is what carries marketing traffic\n // source into the session — is still the external referrer at that moment.\n //\n // Re-entry is safe *only* while the options match. `initializeAnalytics`\n // returns the existing instance when they deep-equal the first call's and\n // throws `already-initialized` otherwise — and the options can be made to\n // differ by things no call site here controls (AGL-1979):\n //\n // * anything that touches the analytics provider WITHOUT options first\n // initializes it with `{}`. `getAnalytics()` is the obvious one, but\n // `@firebase/remote-config` reaches the same code path on its own —\n // `addExperimentToAnalytics` calls `analyticsProvider.getImmediate({\n // optional: true })`, and `optional` only suppresses the throw, it\n // does not stop the initialization.\n // * in dev, a module instance carrying a PREVIOUS version of these\n // options (this config changed under AGL-1857) surviving a Fast\n // Refresh alongside the new one.\n //\n // Once that happens the conflict is permanent for the document: every\n // later call throws, so without the fallback below `analytics` stayed\n // undefined forever and the next consumer — `logEvent(analytics, …)` —\n // read `.app` off it and threw a TypeError two frames away, which is how\n // this surfaced (top Cloud Error Reporting group, and reproduced live on\n // app.aglyn.com).\n //\n // `getAnalytics(app)` is the remedy the SDK's own error message names. It\n // cannot cost us the config on a healthy document: it only runs after\n // `initializeAnalytics` threw, and on a first init that throw can only be\n // `no-app-id` / `no-api-key` / `already-exists`, none of which\n // `getAnalytics` can rescue either — it re-throws and we fall through to\n // an undefined instance, which every consumer must now tolerate.\n // `content_group: 'console'` (AGL-1857) rides the same config: it is the\n // first-class GA4 axis that separates console traffic from `marketing`\n // (stamped by the tenant runtime on aglyn.com's own tag) and `docs`\n // (stamped by the Docusaurus head snippet) in standard reports, without\n // reaching for the Hostname dimension. The console is this provider's\n // only consumer, verified by grep — the tenant runtime builds its tag in\n // `site-analytics.tsx` and never passes through here.\n //\n // AND NOT AT ALL outside a real production deployment (AGL-2067). This\n // provider used to boot Analytics unconditionally, while\n // `apps/console/.env.development.local` points at the PRODUCTION\n // measurement id — so every `next dev` session and every Vercel preview\n // build produced genuine `session_start` / `first_visit` / `page_view`\n // hits in the live property. Not a theory: the archived Marketing\n // property's entire year-to-date history is 30 views / 6 users, ~24 of\n // them `/signin` on preview urls (docs/ANALYTICS.md).\n //\n // Not initialized rather than initialized-and-suppressed, because a\n // resident tag reports on its own — AGL-1608 is the same lesson from the\n // consent side. `useAnalytics()` returning undefined is already a\n // supported state everywhere (AGL-1979), which is what makes this a\n // two-line gate instead of an audit.\n //\n // `analyticsMayEmit` leans LOUD on an unknown deployment: a self-hosted\n // build points at the operator's own Firebase project and their own GA\n // property, and silencing a customer's analytics to protect ours is the\n // worse failure. See the module for the escape hatch.\n //\n // AND NOT while a registered consent gate says no (AGL-1498 posture,\n // applied to Aglyn's own console). `analyticsForConsentState` is where\n // both conditions and the boot itself now live, because the boot has to\n // be repeatable: a visitor whose region has not resolved yet is undecided\n // at this instant and may be granted a moment later, and a visitor who\n // withdraws mid-session has to lose the instance without the page\n // reloading. See the effect below.\n //\n // SCOPE. This is the console's tag and only the console's:\n // `CONSOLE_ANALYTICS_OPTIONS`, `content_group: 'console'`, and this\n // provider's analytics branch has no other consumer (the tenant runtime\n // builds its tag in `site-analytics.tsx` and never passes through here).\n // Customer sites keep the AGL-1498 gate and the host's own\n // `consent.mode`; nothing here reaches them.\n const initialAnalytics = analyticsForConsentState(core.app)\n\n servicesRef.current = {\n ...core,\n analytics: initialAnalytics,\n authPersistence,\n }\n }\n\n const services = servicesRef.current\n\n // The consent gate's other half: the verdict can CHANGE within one document,\n // in both directions, and everything else in this provider is built exactly\n // once by design.\n //\n // Deferred grant. A visitor with no stored record is undecided at the\n // instant this provider first renders, because resolving them needs the\n // region endpoint and that is a network call. Outside the prior-consent\n // regions the answer is implied consent, and it lands a few hundred\n // milliseconds later — same document, so `document.referrer` is still the\n // external referrer and the pageview's attribution is unaffected. Without\n // this, \"the gate is synchronous\" would have quietly meant \"the rest of the\n // world is never measured on a first visit\".\n //\n // Withdrawal. Dropping the instance unmounts every binding hung off it,\n // which is what unregisters the analytics transport — after that\n // `deliver()` falls through to `window.gtag`, and the shared consent writer\n // has already set `ga-disable-<id>` and sent a denied `consent update` on\n // that exact tag (AGL-1608). The resident tag cannot be unloaded; it can be\n // made to send nothing, and both halves are needed because either alone\n // leaks — enhanced measurement fires with no call site at all.\n const [analytics, setAnalytics] = useState<Analytics | undefined>(\n () => services.analytics,\n )\n useEffect(() => {\n const sync = () => setAnalytics(analyticsForConsentState(services.app))\n // Once on mount as well as on the event: the priming pass can resolve a\n // visitor between this provider's render and this effect, and the event it\n // dispatched then had no listener yet.\n sync()\n window.addEventListener(VISITOR_CONSENT_CHANGED_EVENT, sync)\n return () =>\n window.removeEventListener(VISITOR_CONSENT_CHANGED_EVENT, sync)\n }, [services])\n\n // Identity changes only when the tag comes or goes, so a consent-stable\n // document re-renders nothing.\n const value = useMemo(\n () =>\n services.analytics === analytics ? services : { ...services, analytics },\n [services, analytics],\n )\n\n return (\n <FirebaseServicesContext.Provider value={value}>\n {children}\n </FirebaseServicesContext.Provider>\n )\n}\nFirebaseServicesProvider.displayName = 'FirebaseServicesProvider'\n\nfunction useFirebaseServices(): FirebaseServices {\n const services = useContext(FirebaseServicesContext)\n if (!services) {\n throw new Error(\n 'Firebase hooks must be used within a <FirebaseServicesProvider>',\n )\n }\n return services\n}\n\nexport function useFirebaseApp(): FirebaseApp {\n return useFirebaseServices().app\n}\nexport function useFirestore(): Firestore {\n return useFirebaseServices().firestore\n}\nexport function useAuth(): Auth {\n return useFirebaseServices().auth\n}\n/**\n * The persistence class the provider's `Auth` was created with (AGL-1379).\n *\n * Read it — never re-derive it — when building a **second** Firebase app on\n * the same origin, so the second instance cannot end up more persistent than\n * the first. `apps/console/hooks/use-presence.ts` is the existing case.\n */\nexport function useAuthPersistence(): AuthPersistenceClass {\n return useFirebaseServices().authPersistence\n}\nexport function useAnalytics(): Analytics {\n return useFirebaseServices().analytics\n}\nexport function useRemoteConfig(): RemoteConfig {\n return useFirebaseServices().remoteConfig\n}\n\n/**\n * Replaces reactfire's `useUser()`. Reactfire subscribes via\n * `onIdTokenChanged` rather than `onAuthStateChanged` so fields like\n * `emailVerified` stay live across token refresh (e.g. after\n * `user.reload()` post-email-verification), not just sign-in/out — matched\n * here for behavioral parity.\n *\n * THREE states, not two (AGL-1261): `undefined` = auth has not resolved yet,\n * `null` = resolved, signed OUT, a `User` = resolved, signed in. This used to\n * collapse the emitted `null` into `undefined`, which made \"signed out\" and\n * \"still loading\" the same value — a state that, for a signed-out visitor,\n * never left \"loading\". `useSessionCookie` gates its whole body on\n * `user === undefined`, so its silent restore from the shared `__session`\n * cookie could never run: the cookie exchange returned a valid custom token\n * and nothing ever asked for it.\n */\nexport function useUser(): { data: User | null | undefined } {\n const auth = useAuth()\n const [user, setUser] = useState<User | null | undefined>(\n auth.currentUser ?? undefined,\n )\n\n useEffect(() => {\n return onIdTokenChanged(auth, (nextUser) => {\n // `?? null`, never `?? undefined` — see the note above.\n setUser(nextUser ?? null)\n })\n }, [auth])\n\n return { data: user }\n}\n\nexport interface SigninCheckResult {\n signedIn: boolean\n user: User | null\n}\n\n/** Replaces reactfire's `useSigninCheck()` — same `onIdTokenChanged` basis as `useUser()`. */\nexport function useSigninCheck(): {\n status: 'loading' | 'success' | 'error'\n data: SigninCheckResult | undefined\n error: Error | undefined\n} {\n const auth = useAuth()\n const [status, setStatus] = useState<'loading' | 'success' | 'error'>('loading')\n const [data, setData] = useState<SigninCheckResult | undefined>(undefined)\n const [error, setError] = useState<Error | undefined>(undefined)\n\n useEffect(() => {\n return onIdTokenChanged(\n auth,\n (user) => {\n setStatus('success')\n setError(undefined)\n setData({ signedIn: !!user, user: user ?? null })\n },\n (err) => {\n setStatus('error')\n setError(err)\n },\n )\n }, [auth])\n\n return { status, data, error }\n}\n"],"names":["getApps","initializeApp","getAnalytics","getAnalyticsInstance","initializeAnalytics","initializeAnalyticsInstance","initializeAppCheck","ReCaptchaV3Provider","analyticsMayEmit","pushPlatformConsentDefault","VISITOR_CONSENT_CHANGED_EVENT","connectAuthEmulator","onIdTokenChanged","connectFirestoreEmulator","getFirestore","initializeFirestore","getRemoteConfig","getRemoteConfigInstance","createContext","useContext","useEffect","useMemo","useRef","useState","FIREBASE_AUTH_EMULATOR_ENABLED","FIREBASE_FIRESTORE_EMULATOR_ENABLED","APP_CHECK_KEY_MISSING_MESSAGE","appCheckSiteKey","authEmulatorUrl","firestoreEmulatorHost","createAuthInstance","firestoreCacheClassFor","localCacheFor","pruneSharedClientStateFor","keepAppCheckRecaptchaContainer","confirmSharedCacheLock","markMultiTabFirestore","firestorePersistencePrefix","startFirestoreTabHandoff","FirebaseServicesContext","undefined","firestoreInitialized","Set","connectedAuth","isAutomatedChromeSession","navigator","webdriver","CONSOLE_ANALYTICS_OPTIONS","config","send_page_view","content_group","analyticsConsentGate","setAnalyticsConsentGate","gate","analyticsConsentAllows","analyticsByApp","WeakMap","bootAnalytics","app","existing","get","analytics","window","error","console","fallbackError","set","analyticsForConsentState","bootFirebaseCore","firebaseConfig","appName","authPersistence","find","name","auth","persistencePrefix","options","projectId","databaseName","firestoreCacheClass","has","experimentalForceLongPolling","localCache","emulator","host","port","add","firestore","siteKey","warn","provider","isTokenAutoRefreshEnabled","remoteConfig","settings","minimumFetchIntervalMillis","process","env","NODE_ENV","prebooted","Map","prebootKey","prebootFirebaseServices","key","takePrebootedFirebaseCore","core","delete","FirebaseServicesProvider","props","children","servicesRef","current","initialAnalytics","services","setAnalytics","sync","addEventListener","removeEventListener","value","Provider","displayName","useFirebaseServices","Error","useFirebaseApp","useFirestore","useAuth","useAuthPersistence","useAnalytics","useRemoteConfig","useUser","user","setUser","currentUser","nextUser","data","useSigninCheck","status","setStatus","setData","setError","signedIn","err"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAEA,SAGEA,OAAO,EACPC,aAAa,QACR,eAAc;AACrB,SAEEC,gBAAgBC,oBAAoB,EACpCC,uBAAuBC,2BAA2B,QAC7C,qBAAoB;AAC3B,SAASC,kBAAkB,EAAEC,mBAAmB,QAAQ,qBAAoB;AAC5E,SAASC,gBAAgB,QAAQ,+CAA8C;AAC/E,SAASC,0BAA0B,QAAQ,kDAAiD;AAC5F,SAASC,6BAA6B,QAAQ,yCAAwC;AACtF,SAEEC,mBAAmB,EACnBC,gBAAgB,QAEX,gBAAe;AACtB,SAEEC,wBAAwB,EACxBC,YAAY,EACZC,mBAAmB,QACd,qBAAoB;AAC3B,SAEEC,mBAAmBC,uBAAuB,QACrC,yBAAwB;AAC/B,SACEC,aAAa,EACbC,UAAU,EACVC,SAAS,EACTC,OAAO,EACPC,MAAM,EACNC,QAAQ,QAEH,QAAO;AACd,SACEC,8BAA8B,EAC9BC,mCAAmC,QAC9B,2BAA0B;AACjC,SACEC,6BAA6B,EAC7BC,eAAe,QACV,qCAAiC;AACxC,SACEC,eAAe,EACfC,qBAAqB,QAChB,6CAAyC;AAChD,SAEEC,kBAAkB,QACb,wBAAoB;AAC3B,SACEC,sBAAsB,EACtBC,aAAa,EACbC,yBAAyB,QACpB,uBAAmB;AAC1B,SAASC,8BAA8B,QAAQ,qCAAiC;AAEhF,SACEC,sBAAsB,EACtBC,qBAAqB,QAChB,gCAA4B;AACnC,SAASC,0BAA0B,QAAQ,qCAAiC;AAC5E,SAASC,wBAAwB,QAAQ,6BAAyB;AAgHlE,MAAMC,wCAA0BrB,cAA4CsB;AAE5E,yEAAyE;AACzE,kEAAkE;AAClE,oBAAoB;AACpB,EAAE;AAC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iB;IAChE,MAAM,CAACuB,OAAO2E,SAAS,GAAGnH,SAA4BiB;IAEtDpB,UAAU;QACR,OAAOR,iBACL8D,MACA,CAACuD;YACCO,UAAU;YACVE,SAASlG;YACTiG,QAAQ;gBAAEE,UAAU,CAAC,CAACV;gBAAMA,IAAI,EAAEA,eAAAA,OAAQ;YAAK;QACjD,GACA,CAACW;YACCJ,UAAU;YACVE,SAASE;QACX;IAEJ,GAAG;QAAClE;KAAK;IAET,OAAO;QAAE6D;QAAQF;QAAMtE;IAAM;AAC/B"}
@@ -48,7 +48,8 @@ import { type Firestore } from 'firebase/firestore';
48
48
  * the tab reads the `owner` row itself:
49
49
  *
50
50
  * - **the read cannot complete in time** — the store is locked by another
51
- * tab's open transaction; or
51
+ * tab's open transaction. "In time" is {@link WEDGE_LOCK_MS}, longer than a
52
+ * starved but living tab holds it (AGL-4135); or
52
53
  * - **the lease is older than {@link STALE_PRIMARY_LEASE_MS}** — no tab,
53
54
  * including this one, is completing an election.
54
55
  *
@@ -148,6 +149,20 @@ export declare const STALE_PRIMARY_LEASE_MS = 15000;
148
149
  * every tab opened for the next five minutes started on the memory cache.
149
150
  */
150
151
  export declare const LEASE_PROBE_TIMEOUT_MS = 4000;
152
+ /**
153
+ * How long the wedge check's lease read may wait before the store counts as
154
+ * locked (AGL-4135). Five times {@link LEASE_PROBE_TIMEOUT_MS}, because a store
155
+ * held by a tab that is slow is not a store held by a tab that is frozen.
156
+ *
157
+ * A starved tab (busy, slow, throttled) keeps each IndexedDB transaction open
158
+ * until its event loop comes back between requests, and the SDK's lease
159
+ * renewal makes several requests. Measured in production (v1.5.0, a tab busy
160
+ * in 3 s slices): the store held every read for about 15 s, then answered with
161
+ * a fresh lease. At 4 s that read as the wedge, and the healthy tab was reloaded
162
+ * onto the memory cache, losing what had been typed into it. A frozen tab never
163
+ * lets go, so the wedge still reads as locked, only later.
164
+ */
165
+ export declare const WEDGE_LOCK_MS = 20000;
151
166
  /**
152
167
  * The probe's clock. A browser coalesces the ticks a frozen thread missed, so
153
168
  * counting ticks counts only the time the tab could have heard the answer.
@@ -222,6 +237,51 @@ export declare function probePrimaryLease(factory: IDBFactory | undefined, datab
222
237
  timeoutMs?: number;
223
238
  now?: () => number;
224
239
  }): Promise<PrimaryLeaseProbe>;
240
+ /**
241
+ * How long the lease read may take before a quiet client counts as WAITING on
242
+ * the store (AGL-4135). Shorter than {@link LEASE_PROBE_TIMEOUT_MS}, which
243
+ * decides a wedge: this asks only whether something holds the store now. The
244
+ * SDK's own transactions take milliseconds, so a read that waits a second has
245
+ * waited on one, from another tab or from this client's own backlog.
246
+ */
247
+ export declare const LEASE_PROMPT_READ_MS = 1000;
248
+ /** What the shared cache says about a client that has gone quiet (AGL-4135). */
249
+ export type LeaseCheck =
250
+ /**
251
+ * The store did not answer promptly. A transaction holds it, and every call
252
+ * this client makes is queued behind that transaction.
253
+ */
254
+ {
255
+ state: 'waiting';
256
+ }
257
+ /** Another tab holds a live lease and serves this client through it. */
258
+ | {
259
+ state: 'served';
260
+ ownerId: string;
261
+ }
262
+ /**
263
+ * Nothing here explains the quiet. This tab holds the lease, or the lease has
264
+ * lapsed or is vacant, or the lease could not be read or attributed.
265
+ */
266
+ | {
267
+ state: 'silent';
268
+ };
269
+ /**
270
+ * Reads a prompt lease probe for a quiet client whose own id is `selfId`.
271
+ * Pure. A lease is live while younger than the SDK's 5 s
272
+ * (`MAX_PRIMARY_ELIGIBLE_AGE_MS`). Without `selfId` a live lease cannot be told
273
+ * apart from this tab's own, so it reads as `silent`, which is what every stall
274
+ * was read as before.
275
+ */
276
+ export declare function leaseCheckFrom(probe: PrimaryLeaseProbe, selfId: string | undefined): LeaseCheck;
277
+ /**
278
+ * This tab's id in the multi-tab protocol: the id its `clientMetadata` row is
279
+ * written under, and any lease it holds. Read from the SDK's client
280
+ * (`Firestore._firestoreClient.clientId`, which is internal and set once the
281
+ * client has started). `undefined` when it is not there. Read in production
282
+ * (4.17.2) against the `clientMetadata` row the same tab wrote.
283
+ */
284
+ export declare function firestoreClientId(firestore: Firestore): string | undefined;
225
285
  /**
226
286
  * Whether a lease read taken right after a forced election, from a visible
227
287
  * online tab, shows the wedge. Anything that could be a healthy cache —
@@ -312,3 +372,9 @@ export declare function markMultiTabFirestore(firestore: Firestore, databaseName
312
372
  * origin, a tab already on the fallback).
313
373
  */
314
374
  export declare function browserWedgeEscalationFor(firestore: Firestore): (() => Promise<boolean>) | undefined;
375
+ /**
376
+ * The lease check `createStallRecovery` runs before a network cycle, or
377
+ * `undefined` when `firestore` does not run the durable multi-tab cache: a
378
+ * client with a cache of its own has no other tab to wait on. Never rejects.
379
+ */
380
+ export declare function browserLeaseCheckFor(firestore: Firestore): (() => Promise<LeaseCheck>) | undefined;
@@ -14,6 +14,7 @@
14
14
  * See the License for the specific language governing permissions and
15
15
  * limitations under the License.
16
16
  */ import { _ as _extends } from "@swc/helpers/_/_extends";
17
+ import { PRIMARY_LEASE_MAX_AGE_MS } from "./firestore-tab-handoff.js";
17
18
  /**
18
19
  * A MULTI-TAB CACHE THAT ANOTHER TAB HAS LOCKED, AND THE WAY OUT (AGL-3428).
19
20
  *
@@ -47,7 +48,8 @@
47
48
  * the tab reads the `owner` row itself:
48
49
  *
49
50
  * - **the read cannot complete in time** — the store is locked by another
50
- * tab's open transaction; or
51
+ * tab's open transaction. "In time" is {@link WEDGE_LOCK_MS}, longer than a
52
+ * starved but living tab holds it (AGL-4135); or
51
53
  * - **the lease is older than {@link STALE_PRIMARY_LEASE_MS}** — no tab,
52
54
  * including this one, is completing an election.
53
55
  *
@@ -140,6 +142,19 @@
140
142
  * verdict a healthy tab was reloaded, losing whatever was typed into it, and
141
143
  * every tab opened for the next five minutes started on the memory cache.
142
144
  */ export const LEASE_PROBE_TIMEOUT_MS = 4000;
145
+ /**
146
+ * How long the wedge check's lease read may wait before the store counts as
147
+ * locked (AGL-4135). Five times {@link LEASE_PROBE_TIMEOUT_MS}, because a store
148
+ * held by a tab that is slow is not a store held by a tab that is frozen.
149
+ *
150
+ * A starved tab (busy, slow, throttled) keeps each IndexedDB transaction open
151
+ * until its event loop comes back between requests, and the SDK's lease
152
+ * renewal makes several requests. Measured in production (v1.5.0, a tab busy
153
+ * in 3 s slices): the store held every read for about 15 s, then answered with
154
+ * a fresh lease. At 4 s that read as the wedge, and the healthy tab was reloaded
155
+ * onto the memory cache, losing what had been typed into it. A frozen tab never
156
+ * lets go, so the wedge still reads as locked, only later.
157
+ */ export const WEDGE_LOCK_MS = 20000;
143
158
  /**
144
159
  * The probe's clock. A browser coalesces the ticks a frozen thread missed, so
145
160
  * counting ticks counts only the time the tab could have heard the answer.
@@ -261,6 +276,48 @@ const OWNER_KEY = 'owner';
261
276
  };
262
277
  });
263
278
  }
279
+ /**
280
+ * How long the lease read may take before a quiet client counts as WAITING on
281
+ * the store (AGL-4135). Shorter than {@link LEASE_PROBE_TIMEOUT_MS}, which
282
+ * decides a wedge: this asks only whether something holds the store now. The
283
+ * SDK's own transactions take milliseconds, so a read that waits a second has
284
+ * waited on one, from another tab or from this client's own backlog.
285
+ */ export const LEASE_PROMPT_READ_MS = 1000;
286
+ /**
287
+ * Reads a prompt lease probe for a quiet client whose own id is `selfId`.
288
+ * Pure. A lease is live while younger than the SDK's 5 s
289
+ * (`MAX_PRIMARY_ELIGIBLE_AGE_MS`). Without `selfId` a live lease cannot be told
290
+ * apart from this tab's own, so it reads as `silent`, which is what every stall
291
+ * was read as before.
292
+ */ export function leaseCheckFrom(probe, selfId) {
293
+ if (probe.state === 'locked') return {
294
+ state: 'waiting'
295
+ };
296
+ if (probe.state === 'leased' && selfId !== undefined && probe.ownerId !== selfId && probe.ageMs < PRIMARY_LEASE_MAX_AGE_MS) {
297
+ return {
298
+ state: 'served',
299
+ ownerId: probe.ownerId
300
+ };
301
+ }
302
+ return {
303
+ state: 'silent'
304
+ };
305
+ }
306
+ /**
307
+ * This tab's id in the multi-tab protocol: the id its `clientMetadata` row is
308
+ * written under, and any lease it holds. Read from the SDK's client
309
+ * (`Firestore._firestoreClient.clientId`, which is internal and set once the
310
+ * client has started). `undefined` when it is not there. Read in production
311
+ * (4.17.2) against the `clientMetadata` row the same tab wrote.
312
+ */ export function firestoreClientId(firestore) {
313
+ try {
314
+ const client = firestore._firestoreClient;
315
+ const id = client == null ? void 0 : client.clientId;
316
+ return typeof id === 'string' && id.length > 0 ? id : undefined;
317
+ } catch (unused) {
318
+ return undefined;
319
+ }
320
+ }
264
321
  /**
265
322
  * Whether a lease read taken right after a forced election, from a visible
266
323
  * online tab, shows the wedge. Anything that could be a healthy cache —
@@ -460,11 +517,33 @@ const documentVisible = ()=>typeof document === 'undefined' || document.visibili
460
517
  const databaseName = multiTabDatabases.get(firestore);
461
518
  if (databaseName === undefined) return undefined;
462
519
  return createWedgeEscalation({
463
- probe: ()=>probePrimaryLease(browserIndexedDb(), databaseName),
520
+ probe: ()=>probePrimaryLease(browserIndexedDb(), databaseName, {
521
+ timeoutMs: WEDGE_LOCK_MS
522
+ }),
464
523
  fallBack: (evidence)=>fallBackToMemoryCache(evidence, {
465
524
  databaseName
466
525
  })
467
526
  });
468
527
  }
528
+ /**
529
+ * The lease check `createStallRecovery` runs before a network cycle, or
530
+ * `undefined` when `firestore` does not run the durable multi-tab cache: a
531
+ * client with a cache of its own has no other tab to wait on. Never rejects.
532
+ */ export function browserLeaseCheckFor(firestore) {
533
+ const databaseName = multiTabDatabases.get(firestore);
534
+ if (databaseName === undefined) return undefined;
535
+ return async ()=>{
536
+ try {
537
+ const probe = await probePrimaryLease(browserIndexedDb(), databaseName, {
538
+ timeoutMs: LEASE_PROMPT_READ_MS
539
+ });
540
+ return leaseCheckFrom(probe, firestoreClientId(firestore));
541
+ } catch (unused) {
542
+ return {
543
+ state: 'silent'
544
+ };
545
+ }
546
+ };
547
+ }
469
548
 
470
549
  //# sourceMappingURL=firestore-multitab-wedge.js.map