@aglyn/tenant-feature-instance 1.0.0-beta.143
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/README.md +3 -0
- package/jest.config.d.ts +36 -0
- package/package.json +45 -0
- package/src/index.d.ts +17 -0
- package/src/index.js +18 -0
- package/src/index.js.map +1 -0
- package/src/lib/components/duplicate-resource-dialog.d.ts +77 -0
- package/src/lib/components/duplicate-resource-dialog.js +217 -0
- package/src/lib/components/duplicate-resource-dialog.js.map +1 -0
- package/src/lib/constants/firebase-config.d.ts +68 -0
- package/src/lib/constants/firebase-config.js +155 -0
- package/src/lib/constants/firebase-config.js.map +1 -0
- package/src/lib/constants/firebase-emulator-hosts.d.ts +60 -0
- package/src/lib/constants/firebase-emulator-hosts.js +81 -0
- package/src/lib/constants/firebase-emulator-hosts.js.map +1 -0
- package/src/lib/constants/mock-data.d.ts +24 -0
- package/src/lib/constants/mock-data.js +49 -0
- package/src/lib/constants/mock-data.js.map +1 -0
- package/src/lib/constants/site-paths.d.ts +47 -0
- package/src/lib/constants/site-paths.js +66 -0
- package/src/lib/constants/site-paths.js.map +1 -0
- package/src/lib/hooks/firebase/auth-persistence.d.ts +74 -0
- package/src/lib/hooks/firebase/auth-persistence.js +117 -0
- package/src/lib/hooks/firebase/auth-persistence.js.map +1 -0
- package/src/lib/hooks/firebase/firebase-services.d.ts +172 -0
- package/src/lib/hooks/firebase/firebase-services.js +522 -0
- package/src/lib/hooks/firebase/firebase-services.js.map +1 -0
- package/src/lib/hooks/firebase/firestore-cache.d.ts +125 -0
- package/src/lib/hooks/firebase/firestore-cache.js +152 -0
- package/src/lib/hooks/firebase/firestore-cache.js.map +1 -0
- package/src/lib/hooks/firebase/firestore-shared-client-state.d.ts +169 -0
- package/src/lib/hooks/firebase/firestore-shared-client-state.js +316 -0
- package/src/lib/hooks/firebase/firestore-shared-client-state.js.map +1 -0
- package/src/lib/hooks/firestore-denial-reporter.d.ts +192 -0
- package/src/lib/hooks/firestore-denial-reporter.js +293 -0
- package/src/lib/hooks/firestore-denial-reporter.js.map +1 -0
- package/src/lib/hooks/helpers/besigner-nodes-converter.d.ts +62 -0
- package/src/lib/hooks/helpers/besigner-nodes-converter.js +91 -0
- package/src/lib/hooks/helpers/besigner-nodes-converter.js.map +1 -0
- package/src/lib/hooks/helpers/guarded-nodes-save.d.ts +80 -0
- package/src/lib/hooks/helpers/guarded-nodes-save.js +89 -0
- package/src/lib/hooks/helpers/guarded-nodes-save.js.map +1 -0
- package/src/lib/hooks/helpers/guarded-seed-write.d.ts +125 -0
- package/src/lib/hooks/helpers/guarded-seed-write.js +193 -0
- package/src/lib/hooks/helpers/guarded-seed-write.js.map +1 -0
- package/src/lib/hooks/helpers/listen-options.d.ts +91 -0
- package/src/lib/hooks/helpers/listen-options.js +92 -0
- package/src/lib/hooks/helpers/listen-options.js.map +1 -0
- package/src/lib/hooks/helpers/use-doc.d.ts +38 -0
- package/src/lib/hooks/helpers/use-doc.js +213 -0
- package/src/lib/hooks/helpers/use-doc.js.map +1 -0
- package/src/lib/hooks/helpers/use-modify-doc-callback.d.ts +28 -0
- package/src/lib/hooks/helpers/use-modify-doc-callback.js +110 -0
- package/src/lib/hooks/helpers/use-modify-doc-callback.js.map +1 -0
- package/src/lib/hooks/host-collection-queries.d.ts +125 -0
- package/src/lib/hooks/host-collection-queries.js +126 -0
- package/src/lib/hooks/host-collection-queries.js.map +1 -0
- package/src/lib/hooks/list-filter-constraints.d.ts +64 -0
- package/src/lib/hooks/list-filter-constraints.js +288 -0
- package/src/lib/hooks/list-filter-constraints.js.map +1 -0
- package/src/lib/hooks/sorted-collection-window.d.ts +207 -0
- package/src/lib/hooks/sorted-collection-window.js +150 -0
- package/src/lib/hooks/sorted-collection-window.js.map +1 -0
- package/src/lib/hooks/use-component-version.d.ts +43 -0
- package/src/lib/hooks/use-component-version.js +73 -0
- package/src/lib/hooks/use-component-version.js.map +1 -0
- package/src/lib/hooks/use-component.d.ts +39 -0
- package/src/lib/hooks/use-component.js +55 -0
- package/src/lib/hooks/use-component.js.map +1 -0
- package/src/lib/hooks/use-console-host-route.d.ts +24 -0
- package/src/lib/hooks/use-console-host-route.js +77 -0
- package/src/lib/hooks/use-console-host-route.js.map +1 -0
- package/src/lib/hooks/use-duplicate-resource-api.d.ts +43 -0
- package/src/lib/hooks/use-duplicate-resource-api.js +61 -0
- package/src/lib/hooks/use-duplicate-resource-api.js.map +1 -0
- package/src/lib/hooks/use-firestore-collection.d.ts +62 -0
- package/src/lib/hooks/use-firestore-collection.js +307 -0
- package/src/lib/hooks/use-firestore-collection.js.map +1 -0
- package/src/lib/hooks/use-firestore-doc.d.ts +42 -0
- package/src/lib/hooks/use-firestore-doc.js +192 -0
- package/src/lib/hooks/use-firestore-doc.js.map +1 -0
- package/src/lib/hooks/use-form-version.d.ts +44 -0
- package/src/lib/hooks/use-form-version.js +73 -0
- package/src/lib/hooks/use-form-version.js.map +1 -0
- package/src/lib/hooks/use-host-activity-logger.d.ts +35 -0
- package/src/lib/hooks/use-host-activity-logger.js +96 -0
- package/src/lib/hooks/use-host-activity-logger.js.map +1 -0
- package/src/lib/hooks/use-host-campaigns.d.ts +53 -0
- package/src/lib/hooks/use-host-campaigns.js +93 -0
- package/src/lib/hooks/use-host-campaigns.js.map +1 -0
- package/src/lib/hooks/use-host-org-id.d.ts +96 -0
- package/src/lib/hooks/use-host-org-id.js +154 -0
- package/src/lib/hooks/use-host-org-id.js.map +1 -0
- package/src/lib/hooks/use-host-resource-api.d.ts +43 -0
- package/src/lib/hooks/use-host-resource-api.js +60 -0
- package/src/lib/hooks/use-host-resource-api.js.map +1 -0
- package/src/lib/hooks/use-host-template.d.ts +44 -0
- package/src/lib/hooks/use-host-template.js +82 -0
- package/src/lib/hooks/use-host-template.js.map +1 -0
- package/src/lib/hooks/use-host-version-api.d.ts +59 -0
- package/src/lib/hooks/use-host-version-api.js +69 -0
- package/src/lib/hooks/use-host-version-api.js.map +1 -0
- package/src/lib/hooks/use-host.d.ts +101 -0
- package/src/lib/hooks/use-host.js +45 -0
- package/src/lib/hooks/use-host.js.map +1 -0
- package/src/lib/hooks/use-layout-version.d.ts +33 -0
- package/src/lib/hooks/use-layout-version.js +64 -0
- package/src/lib/hooks/use-layout-version.js.map +1 -0
- package/src/lib/hooks/use-layout.d.ts +41 -0
- package/src/lib/hooks/use-layout.js +49 -0
- package/src/lib/hooks/use-layout.js.map +1 -0
- package/src/lib/hooks/use-live-artifact-count.d.ts +50 -0
- package/src/lib/hooks/use-live-artifact-count.js +102 -0
- package/src/lib/hooks/use-live-artifact-count.js.map +1 -0
- package/src/lib/hooks/use-org-member-options.d.ts +57 -0
- package/src/lib/hooks/use-org-member-options.js +112 -0
- package/src/lib/hooks/use-org-member-options.js.map +1 -0
- package/src/lib/hooks/use-org-plan.d.ts +46 -0
- package/src/lib/hooks/use-org-plan.js +86 -0
- package/src/lib/hooks/use-org-plan.js.map +1 -0
- package/src/lib/hooks/use-paged-collection.d.ts +95 -0
- package/src/lib/hooks/use-paged-collection.js +130 -0
- package/src/lib/hooks/use-paged-collection.js.map +1 -0
- package/src/lib/hooks/use-plugin-config.d.ts +38 -0
- package/src/lib/hooks/use-plugin-config.js +120 -0
- package/src/lib/hooks/use-plugin-config.js.map +1 -0
- package/src/lib/hooks/use-scope-tokens.d.ts +28 -0
- package/src/lib/hooks/use-scope-tokens.js +100 -0
- package/src/lib/hooks/use-scope-tokens.js.map +1 -0
- package/src/lib/hooks/use-screen-version.d.ts +33 -0
- package/src/lib/hooks/use-screen-version.js +65 -0
- package/src/lib/hooks/use-screen-version.js.map +1 -0
- package/src/lib/hooks/use-screen.d.ts +68 -0
- package/src/lib/hooks/use-screen.js +50 -0
- package/src/lib/hooks/use-screen.js.map +1 -0
- package/src/lib/hooks/use-sending-identity-api.d.ts +197 -0
- package/src/lib/hooks/use-sending-identity-api.js +95 -0
- package/src/lib/hooks/use-sending-identity-api.js.map +1 -0
- package/src/lib/hooks/use-sorted-paged-collection.d.ts +48 -0
- package/src/lib/hooks/use-sorted-paged-collection.js +213 -0
- package/src/lib/hooks/use-sorted-paged-collection.js.map +1 -0
- package/src/lib/hooks/use-switcher-collection.d.ts +105 -0
- package/src/lib/hooks/use-switcher-collection.js +275 -0
- package/src/lib/hooks/use-switcher-collection.js.map +1 -0
- package/src/lib/hooks/use-user-name.d.ts +51 -0
- package/src/lib/hooks/use-user-name.js +90 -0
- package/src/lib/hooks/use-user-name.js.map +1 -0
- package/src/lib/hooks/use-user-photo.d.ts +50 -0
- package/src/lib/hooks/use-user-photo.js +87 -0
- package/src/lib/hooks/use-user-photo.js.map +1 -0
- package/src/lib/tenant.d.ts +61 -0
- package/src/lib/tenant.js +62 -0
- package/src/lib/tenant.js.map +1 -0
|
@@ -0,0 +1,522 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* Copyright 2026 Aglyn LLC
|
|
4
|
+
*
|
|
5
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
6
|
+
* you may not use this file except in compliance with the License.
|
|
7
|
+
* You may obtain a copy of the License at
|
|
8
|
+
*
|
|
9
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
+
*
|
|
11
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
12
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
13
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
|
+
* See the License for the specific language governing permissions and
|
|
15
|
+
* limitations under the License.
|
|
16
|
+
*/ 'use client';
|
|
17
|
+
import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
18
|
+
import { jsx as _jsx } from "react/jsx-runtime";
|
|
19
|
+
import { getApps, initializeApp } from "firebase/app";
|
|
20
|
+
import { getAnalytics as getAnalyticsInstance, initializeAnalytics as initializeAnalyticsInstance } from "firebase/analytics";
|
|
21
|
+
import { initializeAppCheck, ReCaptchaV3Provider } from "firebase/app-check";
|
|
22
|
+
import { analyticsMayEmit } from "@aglyn/aglyn/app-utils/analytics-environment";
|
|
23
|
+
import { pushPlatformConsentDefault } from "@aglyn/aglyn/app-utils/platform-consent-default";
|
|
24
|
+
import { VISITOR_CONSENT_CHANGED_EVENT } from "@aglyn/aglyn/app-utils/visitor-consent";
|
|
25
|
+
import { connectAuthEmulator, onIdTokenChanged } from "firebase/auth";
|
|
26
|
+
import { connectFirestoreEmulator, getFirestore, initializeFirestore } from "firebase/firestore";
|
|
27
|
+
import { getRemoteConfig as getRemoteConfigInstance } from "firebase/remote-config";
|
|
28
|
+
import { createContext, useContext, useEffect, useMemo, useRef, useState } from "react";
|
|
29
|
+
import { FIREBASE_AUTH_EMULATOR_ENABLED, FIREBASE_FIRESTORE_EMULATOR_ENABLED } from "@aglyn/shared-data-enums";
|
|
30
|
+
import { APP_CHECK_KEY_MISSING_MESSAGE, appCheckSiteKey } from "../../constants/firebase-config.js";
|
|
31
|
+
import { authEmulatorUrl, firestoreEmulatorHost } from "../../constants/firebase-emulator-hosts.js";
|
|
32
|
+
import { createAuthInstance } from "./auth-persistence.js";
|
|
33
|
+
import { localCacheFor, pruneSharedClientStateFor } from "./firestore-cache.js";
|
|
34
|
+
const FirebaseServicesContext = /*#__PURE__*/ createContext(undefined);
|
|
35
|
+
// Module-scope guards so HMR / remounts don't re-run emulator connection
|
|
36
|
+
// (which throws if called twice) or double-initialize Firestore's
|
|
37
|
+
// persistent cache.
|
|
38
|
+
//
|
|
39
|
+
// Firestore's is keyed by app NAME, not a bare boolean (AGL-1456): Firestore
|
|
40
|
+
// initialization is once-per-app, so a module-global flag made the FIRST app
|
|
41
|
+
// to mount decide for every later one — a second app would silently skip
|
|
42
|
+
// `initializeFirestore` and take SDK defaults. That mattered the moment the
|
|
43
|
+
// cache stopped being the same on every host.
|
|
44
|
+
const firestoreInitialized = new Set();
|
|
45
|
+
let connectedAuth = false;
|
|
46
|
+
/**
|
|
47
|
+
* True when THIS Chrome instance is under WebDriver automation control
|
|
48
|
+
* (Puppeteer, Playwright, Selenium, or a raw CDP client) — never true for a
|
|
49
|
+
* person's own browser.
|
|
50
|
+
*
|
|
51
|
+
* The `initializeFirestore` call below already documents the fault this
|
|
52
|
+
* exists for: "the emulator's WebChannel streaming misbehaves in automated
|
|
53
|
+
* Chrome — listeners serve the initial empty from-cache snapshot and the
|
|
54
|
+
* server sync never arrives" (AGL-217). That mitigation only reaches
|
|
55
|
+
* `FIREBASE_FIRESTORE_EMULATOR_ENABLED`, so an automated session against a
|
|
56
|
+
* REAL, deployed backend — a browser-automation agent driving a live
|
|
57
|
+
* console, which is exactly what `navigator.webdriver` detects — stayed
|
|
58
|
+
* exposed. `getDocs`/`getDoc` and `onSnapshot` all resolve over the same
|
|
59
|
+
* Watch stream internally, so a one-shot read wedges exactly like a listener
|
|
60
|
+
* does: no error, nothing to catch, `loading` simply never gets its
|
|
61
|
+
* settling event. That is the Media Library grid spinning on "Loading
|
|
62
|
+
* media…" indefinitely with a perfectly healthy account and a perfectly
|
|
63
|
+
* healthy network.
|
|
64
|
+
*
|
|
65
|
+
* `undefined` during SSR reads as `false` — `navigator` does not exist in
|
|
66
|
+
* Node, and a server render can only ever produce the auto-detected
|
|
67
|
+
* transport, never the forced one.
|
|
68
|
+
*/ const isAutomatedChromeSession = ()=>typeof navigator !== 'undefined' && navigator.webdriver === true;
|
|
69
|
+
/**
|
|
70
|
+
* The console tag's gtag config — ONE object, at module scope, deliberately
|
|
71
|
+
* (AGL-1979).
|
|
72
|
+
*
|
|
73
|
+
* `initializeAnalytics(app, options)` throws `already-initialized` unless the
|
|
74
|
+
* options `deepEqual` the ones the instance was first created with, and the
|
|
75
|
+
* provider re-enters this block on every mount, every StrictMode double
|
|
76
|
+
* invoke and every Fast Refresh. A fresh object literal per call survives
|
|
77
|
+
* that only by *value*; a shared constant survives it by *identity*, which is
|
|
78
|
+
* the first branch of the SDK's own comparison and cannot drift when someone
|
|
79
|
+
* edits one call site and not another.
|
|
80
|
+
*
|
|
81
|
+
* ⚠️ The SDK MUTATES this object: `_initializeAnalytics` reads `options.config`
|
|
82
|
+
* and writes `origin`, `update` and the installation id onto it in place.
|
|
83
|
+
* That is precisely why sharing it is safe rather than dangerous — the object
|
|
84
|
+
* the provider holds and the object the SDK stored are the same one, so they
|
|
85
|
+
* cannot disagree.
|
|
86
|
+
*/ const CONSOLE_ANALYTICS_OPTIONS = {
|
|
87
|
+
config: {
|
|
88
|
+
send_page_view: false,
|
|
89
|
+
content_group: 'console'
|
|
90
|
+
}
|
|
91
|
+
};
|
|
92
|
+
let analyticsConsentGate = null;
|
|
93
|
+
/**
|
|
94
|
+
* Install the consent gate for this document, or clear it with `null`.
|
|
95
|
+
*
|
|
96
|
+
* UNREGISTERED MEANS ALLOWED, which is deliberate and is the only default that
|
|
97
|
+
* is safe here. The tenant runtime does not use this provider's analytics
|
|
98
|
+
* branch at all (it builds its own tag in `site-analytics.tsx`, behind the
|
|
99
|
+
* AGL-1498 gate), and a self-hosted console points at the operator's own GA
|
|
100
|
+
* property — silencing an operator's analytics because Aglyn's own surface
|
|
101
|
+
* grew a gate is a failure they cannot diagnose. The surface that needs the
|
|
102
|
+
* gate is the one that registers it.
|
|
103
|
+
*/ export function setAnalyticsConsentGate(gate) {
|
|
104
|
+
analyticsConsentGate = gate;
|
|
105
|
+
}
|
|
106
|
+
/** The gate's verdict, with an unregistered gate reading as "allowed". */ function analyticsConsentAllows() {
|
|
107
|
+
if (analyticsConsentGate === null) return true;
|
|
108
|
+
try {
|
|
109
|
+
return analyticsConsentGate() === true;
|
|
110
|
+
} catch (unused) {
|
|
111
|
+
// A gate that throws cannot be read as consent. Storage can throw in
|
|
112
|
+
// private mode, and "we could not tell" is the one state this whole
|
|
113
|
+
// mechanism resolves to "no".
|
|
114
|
+
return false;
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* The Analytics instance per Firebase app, so a re-boot after a consent change
|
|
119
|
+
* hands back the tag that is already resident rather than asking the SDK for a
|
|
120
|
+
* second one.
|
|
121
|
+
*
|
|
122
|
+
* `initializeAnalytics` is idempotent while the options match, so this is not
|
|
123
|
+
* what makes re-entry safe — `CONSOLE_ANALYTICS_OPTIONS` being a shared
|
|
124
|
+
* constant is. What this avoids is the noisy path: once anything has
|
|
125
|
+
* initialized the provider with different options, every later call throws and
|
|
126
|
+
* is logged, and a withdrawal followed by a re-grant would log it again.
|
|
127
|
+
*/ const analyticsByApp = new WeakMap();
|
|
128
|
+
/**
|
|
129
|
+
* Boot the console's Analytics tag, or return the one already booted.
|
|
130
|
+
*
|
|
131
|
+
* Extracted from the provider body so that "when is the tag created" and "may
|
|
132
|
+
* it be created" are separable: the consent gate can defer this call to a
|
|
133
|
+
* later render without the ordering below moving.
|
|
134
|
+
*/ function bootAnalytics(app) {
|
|
135
|
+
const existing = analyticsByApp.get(app);
|
|
136
|
+
if (existing) return existing;
|
|
137
|
+
let analytics;
|
|
138
|
+
// The region-conditional consent default (AGL-1597), declared BEFORE the
|
|
139
|
+
// SDK boots the tag. Ordering is the whole of it: a `default` read after
|
|
140
|
+
// `config` is not a default, and the SDK issues `config` inside
|
|
141
|
+
// `initializeAnalytics` on the next line. Pushing onto `dataLayer` here
|
|
142
|
+
// works even though gtag.js is not loaded yet — the queue is what makes the
|
|
143
|
+
// ordering expressible.
|
|
144
|
+
//
|
|
145
|
+
// Still declared even though the gate above has already said yes, and the
|
|
146
|
+
// two are not redundant. The gate answers "may a tag exist"; the default
|
|
147
|
+
// answers "what may the tag that does exist do", per region, from its very
|
|
148
|
+
// first hit. Ad storage stays denied everywhere on this surface.
|
|
149
|
+
pushPlatformConsentDefault(typeof window === 'undefined' ? null : window);
|
|
150
|
+
try {
|
|
151
|
+
analytics = initializeAnalyticsInstance(app, CONSOLE_ANALYTICS_OPTIONS);
|
|
152
|
+
} catch (error) {
|
|
153
|
+
console.error(error);
|
|
154
|
+
try {
|
|
155
|
+
// Already initialized by someone else, with someone else's options:
|
|
156
|
+
// take THAT instance rather than leaving consumers with nothing. The
|
|
157
|
+
// tag it is attached to was configured without `send_page_view: false`
|
|
158
|
+
// and without `content_group`, so this session reports a duplicate
|
|
159
|
+
// startup page_view and an unstamped surface — degraded, and loudly so,
|
|
160
|
+
// instead of silently dead.
|
|
161
|
+
analytics = getAnalyticsInstance(app);
|
|
162
|
+
} catch (fallbackError) {
|
|
163
|
+
console.error(fallbackError);
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
if (analytics) analyticsByApp.set(app, analytics);
|
|
167
|
+
return analytics;
|
|
168
|
+
}
|
|
169
|
+
/**
|
|
170
|
+
* The tag this document may have right now: none outside a real production
|
|
171
|
+
* deployment, none while consent is absent, otherwise the booted instance.
|
|
172
|
+
*/ function analyticsForConsentState(app) {
|
|
173
|
+
if (!analyticsMayEmit()) return undefined;
|
|
174
|
+
if (!analyticsConsentAllows()) return undefined;
|
|
175
|
+
return bootAnalytics(app);
|
|
176
|
+
}
|
|
177
|
+
export function FirebaseServicesProvider(props) {
|
|
178
|
+
const { firebaseConfig, appName, authPersistence = 'durable', children } = props;
|
|
179
|
+
const servicesRef = useRef(undefined);
|
|
180
|
+
if (!servicesRef.current) {
|
|
181
|
+
var _getApps_find;
|
|
182
|
+
const app = (_getApps_find = getApps().find((existing)=>existing.name === appName)) != null ? _getApps_find : initializeApp(firebaseConfig, appName);
|
|
183
|
+
// `durable` resolves to the same `getAuth(app)` this always called.
|
|
184
|
+
const auth = createAuthInstance(app, authPersistence);
|
|
185
|
+
if (!firestoreInitialized.has(appName)) {
|
|
186
|
+
try {
|
|
187
|
+
// Under the emulator (dev/e2e only): force long-polling and skip
|
|
188
|
+
// the persistent multi-tab cache. The emulator's WebChannel
|
|
189
|
+
// streaming misbehaves in automated Chrome — listeners serve the
|
|
190
|
+
// initial empty from-cache snapshot and the server sync never
|
|
191
|
+
// arrives, which looks like "empty pages with zero errors"
|
|
192
|
+
// (the AGL-217 mystery). Real traffic keeps the default transport
|
|
193
|
+
// and persistent cache — except a WebDriver-controlled Chrome
|
|
194
|
+
// against a real backend, which forces long-polling for the same
|
|
195
|
+
// reason without giving up the cache (see `isAutomatedChromeSession`
|
|
196
|
+
// below).
|
|
197
|
+
//
|
|
198
|
+
// ⚠️ CONSEQUENCE, and it will cost you hours if you do not know it
|
|
199
|
+
// (AGL-1066): every stale-session/stale-cache fault is UNREPRODUCIBLE
|
|
200
|
+
// locally through the app, because the cache that causes them is off
|
|
201
|
+
// in exactly the configuration you would reach for to reproduce one.
|
|
202
|
+
// A listener that keeps serving arbitrarily-old data while the server
|
|
203
|
+
// refuses it, a `noDocument` tombstone that 404s a live host, the
|
|
204
|
+
// retry budget that never spends because a cached emission resets it
|
|
205
|
+
// — none of them can happen here. Test that behaviour with the unit
|
|
206
|
+
// seams instead (`use-firestore-collection-cached-retry.spec.ts`
|
|
207
|
+
// drives cached emissions and denials directly), or against a
|
|
208
|
+
// deployed environment. Do NOT "fix" it by turning the cache on for
|
|
209
|
+
// the emulator: the AGL-217 empty-pages-with-zero-errors mystery is
|
|
210
|
+
// what that produces.
|
|
211
|
+
initializeFirestore(app, FIREBASE_FIRESTORE_EMULATOR_ENABLED ? {
|
|
212
|
+
experimentalForceLongPolling: true
|
|
213
|
+
} : _extends({
|
|
214
|
+
// NOT unconditional (AGL-1456). `persistentLocalCache` writes
|
|
215
|
+
// document bodies to this origin's IndexedDB, so on a custom
|
|
216
|
+
// console domain it is the same exposure D6 removed from the
|
|
217
|
+
// refresh token — see `firestore-cache.ts` for why one
|
|
218
|
+
// declaration governs both.
|
|
219
|
+
localCache: localCacheFor(authPersistence)
|
|
220
|
+
}, isAutomatedChromeSession() ? {
|
|
221
|
+
experimentalForceLongPolling: true
|
|
222
|
+
} : {}));
|
|
223
|
+
if (FIREBASE_FIRESTORE_EMULATOR_ENABLED) {
|
|
224
|
+
// Where the server was told the emulator is, rather than a default
|
|
225
|
+
// port another session's stack may hold (AGL-2834).
|
|
226
|
+
const emulator = firestoreEmulatorHost();
|
|
227
|
+
connectFirestoreEmulator(getFirestore(app), emulator.host, emulator.port);
|
|
228
|
+
} else {
|
|
229
|
+
// The SDK never sweeps the multi-tab records the durable cache
|
|
230
|
+
// strands in localStorage, and a full localStorage fails the whole
|
|
231
|
+
// Firestore client — see `firestore-shared-client-state.ts`.
|
|
232
|
+
void pruneSharedClientStateFor(authPersistence, app);
|
|
233
|
+
}
|
|
234
|
+
} catch (unused) {
|
|
235
|
+
// already initialized (e.g. HMR reset the module flag) — getFirestore() returns the existing instance
|
|
236
|
+
} finally{
|
|
237
|
+
firestoreInitialized.add(appName);
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
const firestore = getFirestore(app);
|
|
241
|
+
if (!connectedAuth) {
|
|
242
|
+
try {
|
|
243
|
+
if (FIREBASE_AUTH_EMULATOR_ENABLED) {
|
|
244
|
+
// The emulator the server was started with (AGL-2834).
|
|
245
|
+
connectAuthEmulator(auth, authEmulatorUrl());
|
|
246
|
+
}
|
|
247
|
+
connectedAuth = true;
|
|
248
|
+
} catch (error) {
|
|
249
|
+
console.error(error);
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
// App Check must be skipped under the emulators: there is no App
|
|
253
|
+
// Check emulator, so ReCaptcha would hit the real backend and its
|
|
254
|
+
// 403s break emulator auth (the AGL-216 emulator sessions hit this).
|
|
255
|
+
if (!FIREBASE_AUTH_EMULATOR_ENABLED && !FIREBASE_FIRESTORE_EMULATOR_ENABLED) {
|
|
256
|
+
// No site key means no provider (AGL-2049). Registering one built on
|
|
257
|
+
// `undefined` does not throw — it fails asynchronously inside the SDK,
|
|
258
|
+
// where the catch below cannot see it — so this has to be a pre-check.
|
|
259
|
+
const siteKey = appCheckSiteKey();
|
|
260
|
+
if (!siteKey) {
|
|
261
|
+
console.warn(APP_CHECK_KEY_MISSING_MESSAGE);
|
|
262
|
+
} else {
|
|
263
|
+
try {
|
|
264
|
+
initializeAppCheck(app, {
|
|
265
|
+
provider: new ReCaptchaV3Provider(siteKey),
|
|
266
|
+
isTokenAutoRefreshEnabled: true
|
|
267
|
+
});
|
|
268
|
+
} catch (error) {
|
|
269
|
+
console.error(error);
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
// `initializeAnalytics`, not `getAnalytics`, for exactly one reason: it is
|
|
274
|
+
// the only form that can pass `config`, and `send_page_view: false` is the
|
|
275
|
+
// only way to stop the SDK's own startup `page_view` (AGL-1643).
|
|
276
|
+
//
|
|
277
|
+
// Booting Analytics issues `gtag('config', <id>, configProperties)`, and
|
|
278
|
+
// the vendored SDK's own comment on that line reads "This will trigger a
|
|
279
|
+
// page_view event unless 'send_page_view' is set to false in
|
|
280
|
+
// configProperties". `getAnalytics(app)` passes no config at all, so the
|
|
281
|
+
// key was never there and the hit always fired — on top of the manual
|
|
282
|
+
// `page_view` the console's layout sends on mount. Two hits, one page.
|
|
283
|
+
//
|
|
284
|
+
// The SDK's is the one suppressed rather than the layout's, and the
|
|
285
|
+
// direction is the whole decision: the SDK fires ONCE per document load,
|
|
286
|
+
// while the layout fires on mount AND on every `usePathname` change. In a
|
|
287
|
+
// client-routed app the layout's is a superset — killing it instead would
|
|
288
|
+
// have left every in-app navigation unreported, halving console pageviews
|
|
289
|
+
// rather than correcting them, and the reports would have looked fine.
|
|
290
|
+
//
|
|
291
|
+
// Nothing else about attribution moves: the surviving hit is sent from the
|
|
292
|
+
// same document at mount, so `document.referrer` — which gtag resolves for
|
|
293
|
+
// `page_referrer` itself, and which is what carries marketing traffic
|
|
294
|
+
// source into the session — is still the external referrer at that moment.
|
|
295
|
+
//
|
|
296
|
+
// Re-entry is safe *only* while the options match. `initializeAnalytics`
|
|
297
|
+
// returns the existing instance when they deep-equal the first call's and
|
|
298
|
+
// throws `already-initialized` otherwise — and the options can be made to
|
|
299
|
+
// differ by things no call site here controls (AGL-1979):
|
|
300
|
+
//
|
|
301
|
+
// * anything that touches the analytics provider WITHOUT options first
|
|
302
|
+
// initializes it with `{}`. `getAnalytics()` is the obvious one, but
|
|
303
|
+
// `@firebase/remote-config` reaches the same code path on its own —
|
|
304
|
+
// `addExperimentToAnalytics` calls `analyticsProvider.getImmediate({
|
|
305
|
+
// optional: true })`, and `optional` only suppresses the throw, it
|
|
306
|
+
// does not stop the initialization.
|
|
307
|
+
// * in dev, a module instance carrying a PREVIOUS version of these
|
|
308
|
+
// options (this config changed under AGL-1857) surviving a Fast
|
|
309
|
+
// Refresh alongside the new one.
|
|
310
|
+
//
|
|
311
|
+
// Once that happens the conflict is permanent for the document: every
|
|
312
|
+
// later call throws, so without the fallback below `analytics` stayed
|
|
313
|
+
// undefined forever and the next consumer — `logEvent(analytics, …)` —
|
|
314
|
+
// read `.app` off it and threw a TypeError two frames away, which is how
|
|
315
|
+
// this surfaced (top Cloud Error Reporting group, and reproduced live on
|
|
316
|
+
// app.aglyn.com).
|
|
317
|
+
//
|
|
318
|
+
// `getAnalytics(app)` is the remedy the SDK's own error message names. It
|
|
319
|
+
// cannot cost us the config on a healthy document: it only runs after
|
|
320
|
+
// `initializeAnalytics` threw, and on a first init that throw can only be
|
|
321
|
+
// `no-app-id` / `no-api-key` / `already-exists`, none of which
|
|
322
|
+
// `getAnalytics` can rescue either — it re-throws and we fall through to
|
|
323
|
+
// an undefined instance, which every consumer must now tolerate.
|
|
324
|
+
// `content_group: 'console'` (AGL-1857) rides the same config: it is the
|
|
325
|
+
// first-class GA4 axis that separates console traffic from `marketing`
|
|
326
|
+
// (stamped by the tenant runtime on aglyn.com's own tag) and `docs`
|
|
327
|
+
// (stamped by the Docusaurus head snippet) in standard reports, without
|
|
328
|
+
// reaching for the Hostname dimension. The console is this provider's
|
|
329
|
+
// only consumer, verified by grep — the tenant runtime builds its tag in
|
|
330
|
+
// `site-analytics.tsx` and never passes through here.
|
|
331
|
+
//
|
|
332
|
+
// AND NOT AT ALL outside a real production deployment (AGL-2067). This
|
|
333
|
+
// provider used to boot Analytics unconditionally, while
|
|
334
|
+
// `apps/console/.env.development.local` points at the PRODUCTION
|
|
335
|
+
// measurement id — so every `next dev` session and every Vercel preview
|
|
336
|
+
// build produced genuine `session_start` / `first_visit` / `page_view`
|
|
337
|
+
// hits in the live property. Not a theory: the archived Marketing
|
|
338
|
+
// property's entire year-to-date history is 30 views / 6 users, ~24 of
|
|
339
|
+
// them `/signin` on preview urls (docs/ANALYTICS.md).
|
|
340
|
+
//
|
|
341
|
+
// Not initialized rather than initialized-and-suppressed, because a
|
|
342
|
+
// resident tag reports on its own — AGL-1608 is the same lesson from the
|
|
343
|
+
// consent side. `useAnalytics()` returning undefined is already a
|
|
344
|
+
// supported state everywhere (AGL-1979), which is what makes this a
|
|
345
|
+
// two-line gate instead of an audit.
|
|
346
|
+
//
|
|
347
|
+
// `analyticsMayEmit` leans LOUD on an unknown deployment: a self-hosted
|
|
348
|
+
// build points at the operator's own Firebase project and their own GA
|
|
349
|
+
// property, and silencing a customer's analytics to protect ours is the
|
|
350
|
+
// worse failure. See the module for the escape hatch.
|
|
351
|
+
//
|
|
352
|
+
// AND NOT while a registered consent gate says no (AGL-1498 posture,
|
|
353
|
+
// applied to Aglyn's own console). `analyticsForConsentState` is where
|
|
354
|
+
// both conditions and the boot itself now live, because the boot has to
|
|
355
|
+
// be repeatable: a visitor whose region has not resolved yet is undecided
|
|
356
|
+
// at this instant and may be granted a moment later, and a visitor who
|
|
357
|
+
// withdraws mid-session has to lose the instance without the page
|
|
358
|
+
// reloading. See the effect below.
|
|
359
|
+
//
|
|
360
|
+
// SCOPE. This is the console's tag and only the console's:
|
|
361
|
+
// `CONSOLE_ANALYTICS_OPTIONS`, `content_group: 'console'`, and this
|
|
362
|
+
// provider's analytics branch has no other consumer (the tenant runtime
|
|
363
|
+
// builds its tag in `site-analytics.tsx` and never passes through here).
|
|
364
|
+
// Customer sites keep the AGL-1498 gate and the host's own
|
|
365
|
+
// `consent.mode`; nothing here reaches them.
|
|
366
|
+
const initialAnalytics = analyticsForConsentState(app);
|
|
367
|
+
// Remote Config (AGL-228): release-flag delivery. Browser-only like
|
|
368
|
+
// analytics; consumers set defaultConfig before their first getValue so
|
|
369
|
+
// gating never blocks on the network.
|
|
370
|
+
let remoteConfig;
|
|
371
|
+
try {
|
|
372
|
+
remoteConfig = getRemoteConfigInstance(app);
|
|
373
|
+
remoteConfig.settings.minimumFetchIntervalMillis = process.env.NODE_ENV === 'production' ? 3600000 : 60000;
|
|
374
|
+
} catch (error) {
|
|
375
|
+
console.error(error);
|
|
376
|
+
}
|
|
377
|
+
servicesRef.current = {
|
|
378
|
+
app,
|
|
379
|
+
firestore,
|
|
380
|
+
auth,
|
|
381
|
+
analytics: initialAnalytics,
|
|
382
|
+
remoteConfig,
|
|
383
|
+
authPersistence
|
|
384
|
+
};
|
|
385
|
+
}
|
|
386
|
+
const services = servicesRef.current;
|
|
387
|
+
// The consent gate's other half: the verdict can CHANGE within one document,
|
|
388
|
+
// in both directions, and everything else in this provider is built exactly
|
|
389
|
+
// once by design.
|
|
390
|
+
//
|
|
391
|
+
// Deferred grant. A visitor with no stored record is undecided at the
|
|
392
|
+
// instant this provider first renders, because resolving them needs the
|
|
393
|
+
// region endpoint and that is a network call. Outside the prior-consent
|
|
394
|
+
// regions the answer is implied consent, and it lands a few hundred
|
|
395
|
+
// milliseconds later — same document, so `document.referrer` is still the
|
|
396
|
+
// external referrer and the pageview's attribution is unaffected. Without
|
|
397
|
+
// this, "the gate is synchronous" would have quietly meant "the rest of the
|
|
398
|
+
// world is never measured on a first visit".
|
|
399
|
+
//
|
|
400
|
+
// Withdrawal. Dropping the instance unmounts every binding hung off it,
|
|
401
|
+
// which is what unregisters the analytics transport — after that
|
|
402
|
+
// `deliver()` falls through to `window.gtag`, and the shared consent writer
|
|
403
|
+
// has already set `ga-disable-<id>` and sent a denied `consent update` on
|
|
404
|
+
// that exact tag (AGL-1608). The resident tag cannot be unloaded; it can be
|
|
405
|
+
// made to send nothing, and both halves are needed because either alone
|
|
406
|
+
// leaks — enhanced measurement fires with no call site at all.
|
|
407
|
+
const [analytics, setAnalytics] = useState(()=>services.analytics);
|
|
408
|
+
useEffect(()=>{
|
|
409
|
+
const sync = ()=>setAnalytics(analyticsForConsentState(services.app));
|
|
410
|
+
// Once on mount as well as on the event: the priming pass can resolve a
|
|
411
|
+
// visitor between this provider's render and this effect, and the event it
|
|
412
|
+
// dispatched then had no listener yet.
|
|
413
|
+
sync();
|
|
414
|
+
window.addEventListener(VISITOR_CONSENT_CHANGED_EVENT, sync);
|
|
415
|
+
return ()=>window.removeEventListener(VISITOR_CONSENT_CHANGED_EVENT, sync);
|
|
416
|
+
}, [
|
|
417
|
+
services
|
|
418
|
+
]);
|
|
419
|
+
// Identity changes only when the tag comes or goes, so a consent-stable
|
|
420
|
+
// document re-renders nothing.
|
|
421
|
+
const value = useMemo(()=>services.analytics === analytics ? services : _extends({}, services, {
|
|
422
|
+
analytics
|
|
423
|
+
}), [
|
|
424
|
+
services,
|
|
425
|
+
analytics
|
|
426
|
+
]);
|
|
427
|
+
return /*#__PURE__*/ _jsx(FirebaseServicesContext.Provider, {
|
|
428
|
+
value: value,
|
|
429
|
+
children: children
|
|
430
|
+
});
|
|
431
|
+
}
|
|
432
|
+
FirebaseServicesProvider.displayName = 'FirebaseServicesProvider';
|
|
433
|
+
function useFirebaseServices() {
|
|
434
|
+
const services = useContext(FirebaseServicesContext);
|
|
435
|
+
if (!services) {
|
|
436
|
+
throw new Error('Firebase hooks must be used within a <FirebaseServicesProvider>');
|
|
437
|
+
}
|
|
438
|
+
return services;
|
|
439
|
+
}
|
|
440
|
+
export function useFirebaseApp() {
|
|
441
|
+
return useFirebaseServices().app;
|
|
442
|
+
}
|
|
443
|
+
export function useFirestore() {
|
|
444
|
+
return useFirebaseServices().firestore;
|
|
445
|
+
}
|
|
446
|
+
export function useAuth() {
|
|
447
|
+
return useFirebaseServices().auth;
|
|
448
|
+
}
|
|
449
|
+
/**
|
|
450
|
+
* The persistence class the provider's `Auth` was created with (AGL-1379).
|
|
451
|
+
*
|
|
452
|
+
* Read it — never re-derive it — when building a **second** Firebase app on
|
|
453
|
+
* the same origin, so the second instance cannot end up more persistent than
|
|
454
|
+
* the first. `apps/console/hooks/use-presence.ts` is the existing case.
|
|
455
|
+
*/ export function useAuthPersistence() {
|
|
456
|
+
return useFirebaseServices().authPersistence;
|
|
457
|
+
}
|
|
458
|
+
export function useAnalytics() {
|
|
459
|
+
return useFirebaseServices().analytics;
|
|
460
|
+
}
|
|
461
|
+
export function useRemoteConfig() {
|
|
462
|
+
return useFirebaseServices().remoteConfig;
|
|
463
|
+
}
|
|
464
|
+
/**
|
|
465
|
+
* Replaces reactfire's `useUser()`. Reactfire subscribes via
|
|
466
|
+
* `onIdTokenChanged` rather than `onAuthStateChanged` so fields like
|
|
467
|
+
* `emailVerified` stay live across token refresh (e.g. after
|
|
468
|
+
* `user.reload()` post-email-verification), not just sign-in/out — matched
|
|
469
|
+
* here for behavioral parity.
|
|
470
|
+
*
|
|
471
|
+
* THREE states, not two (AGL-1261): `undefined` = auth has not resolved yet,
|
|
472
|
+
* `null` = resolved, signed OUT, a `User` = resolved, signed in. This used to
|
|
473
|
+
* collapse the emitted `null` into `undefined`, which made "signed out" and
|
|
474
|
+
* "still loading" the same value — a state that, for a signed-out visitor,
|
|
475
|
+
* never left "loading". `useSessionCookie` gates its whole body on
|
|
476
|
+
* `user === undefined`, so its silent restore from the shared `__session`
|
|
477
|
+
* cookie could never run: the cookie exchange returned a valid custom token
|
|
478
|
+
* and nothing ever asked for it.
|
|
479
|
+
*/ export function useUser() {
|
|
480
|
+
var _auth_currentUser;
|
|
481
|
+
const auth = useAuth();
|
|
482
|
+
const [user, setUser] = useState((_auth_currentUser = auth.currentUser) != null ? _auth_currentUser : undefined);
|
|
483
|
+
useEffect(()=>{
|
|
484
|
+
return onIdTokenChanged(auth, (nextUser)=>{
|
|
485
|
+
// `?? null`, never `?? undefined` — see the note above.
|
|
486
|
+
setUser(nextUser != null ? nextUser : null);
|
|
487
|
+
});
|
|
488
|
+
}, [
|
|
489
|
+
auth
|
|
490
|
+
]);
|
|
491
|
+
return {
|
|
492
|
+
data: user
|
|
493
|
+
};
|
|
494
|
+
}
|
|
495
|
+
/** Replaces reactfire's `useSigninCheck()` — same `onIdTokenChanged` basis as `useUser()`. */ export function useSigninCheck() {
|
|
496
|
+
const auth = useAuth();
|
|
497
|
+
const [status, setStatus] = useState('loading');
|
|
498
|
+
const [data, setData] = useState(undefined);
|
|
499
|
+
const [error, setError] = useState(undefined);
|
|
500
|
+
useEffect(()=>{
|
|
501
|
+
return onIdTokenChanged(auth, (user)=>{
|
|
502
|
+
setStatus('success');
|
|
503
|
+
setError(undefined);
|
|
504
|
+
setData({
|
|
505
|
+
signedIn: !!user,
|
|
506
|
+
user: user != null ? user : null
|
|
507
|
+
});
|
|
508
|
+
}, (err)=>{
|
|
509
|
+
setStatus('error');
|
|
510
|
+
setError(err);
|
|
511
|
+
});
|
|
512
|
+
}, [
|
|
513
|
+
auth
|
|
514
|
+
]);
|
|
515
|
+
return {
|
|
516
|
+
status,
|
|
517
|
+
data,
|
|
518
|
+
error
|
|
519
|
+
};
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
//# sourceMappingURL=firebase-services.js.map
|
|
@@ -0,0 +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 { localCacheFor, pruneSharedClientStateFor } from './firestore-cache'\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\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 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 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(authPersistence),\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(authPersistence, app)\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 } catch (error) {\n console.error(error)\n }\n }\n }\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(app)\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 servicesRef.current = {\n app,\n firestore,\n auth,\n analytics: initialAnalytics,\n remoteConfig,\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","localCacheFor","pruneSharedClientStateFor","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","FirebaseServicesProvider","props","firebaseConfig","appName","authPersistence","children","servicesRef","current","find","name","auth","has","experimentalForceLongPolling","localCache","emulator","host","port","add","firestore","siteKey","warn","provider","isTokenAutoRefreshEnabled","initialAnalytics","remoteConfig","settings","minimumFetchIntervalMillis","process","env","NODE_ENV","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,SAASC,aAAa,EAAEC,yBAAyB,QAAQ,uBAAmB;AA0G5E,MAAMC,wCAA0Bf,cAA4CgB;AAE5E,yEAAyE;AACzE,kEAAkE;AAClE,oBAAoB;AACpB,EAAE;AACF,6EAA6E;AAC7E,6EAA6E;AAC7E,yEAAyE;AACzE,4EAA4E;AAC5E,8CAA8C;AAC9C,MAAMC,uBAAuB,IAAIC;AACjC,IAAIC,gBAAgB;AAEpB;;;;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